@stackone/cli 1.46.1 → 1.47.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/dist/cli.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{t as e}from"./cliCore-BharJXXM.mjs";import"./agentConfig-BWQWMYKQ.mjs";import"./setupMigration-C1ShGzOu.mjs";import"./agentApiKey-CWXxJgCO.mjs";import{config as t}from"dotenv";process.env.DOTENV_CONFIG_QUIET=`true`,t(),new e().run();export{};
2
+ import{t as e}from"./cliCore-B0uelpFO.mjs";import"./agentConfig-BWQWMYKQ.mjs";import"./setupMigration-C1ShGzOu.mjs";import"./agentApiKey-CWXxJgCO.mjs";import{config as t}from"dotenv";process.env.DOTENV_CONFIG_QUIET=`true`,t(),new e().run();export{};
@@ -139,21 +139,21 @@ Error: `+(e instanceof Error?e.message:String(e)))),process.exit(1)}c?.stop(),y.
139
139
  Error: `+(e instanceof Error?e.message:String(e)))),process.exit(1)}a?.stop(),y.log(T.green(`
140
140
  ✓ Build complete
141
141
  `))}};const jn=(e,t,n)=>{let r=e.message;switch(r.type){case`text`:n&&process.stdout.write(r.content??``);break;case`tool_call`:{let n=r.toolName??`unknown tool`;t&&(t.text=T.cyan(`[${e.phase}] Tool: ${n}`));break}case`tool_error`:y.error(T.red(`\n[${e.phase}] Tool error (${r.toolName}): ${r.error??`Unknown error`}`));break;case`error`:y.error(T.red(`\n[${e.phase}] ${r.error??`Unknown error`}`));break;default:break}};function Mn(e,t){switch(e.type){case`text`:t(null),process.stdout.write(e.content??``);break;case`tool_call`:{let n=e.toolName??`unknown tool`;t(q(T.cyan(`Tool: ${n}`)).start());break}case`tool_result`:t(null);break;case`tool_progress`:{let n=e.progress?.operation||e.toolName||`Working...`;t(q(T.cyan(`Tool: ${n}`)).start());break}case`tool_error`:t(null),y.error(T.red(`\nTool error (${e.toolName}): ${e.error??`Unknown error`}`));break;case`error`:t(null),y.error(T.red(`\n${e.error??`Unknown error`}`));break;case`done`:t(null);break;default:process.env.VERBOSE&&console.warn(`[AgentRun] Unknown message type:`,e.type);break}}const Nn=e=>{let t=e.trim();return t===`~`?I():t.startsWith(`~/`)?R(I(),t.slice(2)):t},Pn=(e,t,n)=>e?`global`:t?`local`:n?null:`global`,Fn=(e,t)=>e?.trim()||(t?null:process.cwd()),In=e=>e.existingConfig?`overwrite`:Ln(e),Ln=e=>e.mode===`local`&&e.alreadyAuthed?`work`:`auth`,Rn=(e,t)=>{switch(e){case`mode`:return t.mode===`local`?t.hasGit?`repo-confirm`:`path-input`:In(t);case`repo-confirm`:return t.repoAccepted?In(t):`path-input`;case`path-input`:return In(t);case`overwrite`:return Ln(t);case`auth`:return`work`;default:return`done`}},zn=(e,t)=>Ee(`git`,[`-C`,e,...t],{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim(),Bn=e=>{try{let t=zn(e,[`rev-parse`,`--show-toplevel`]);if(!t)return null;let n;try{n=zn(e,[`remote`,`get-url`,`origin`])||void 0}catch{}return{root:t,remoteUrl:n}}catch{return null}},Vn=`connector-guide.md`,Hn=`<!-- BEGIN stackone-connector-guide -->`,Un=`<!-- END stackone-connector-guide -->`,Wn=/^[a-z0-9][a-z0-9_-]*$/,Gn=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),Kn=e=>`<!-- Generated by \`stackone agent sync\` from @stackone/agent-harness@${e}. Edit upstream, not here. -->`,qn=e=>{if(e.includes(`..`)||!Wn.test(e))throw Error(`Refusing unsafe path segment: ${JSON.stringify(e)}`)},Q=(e,...t)=>{let n=_e(e),r=_e(n,...t);if(r!==n&&!r.startsWith(n+ve))throw Error(`Refusing path outside ${n}: ${r}`);return r},Jn=(e,...t)=>de(Q(e,...t),`utf-8`),Yn=(e,...t)=>de(Q(e,...t)),Xn=()=>{let e=w(import.meta.url).resolve(`@stackone/agent-harness`),t=ge(e);for(let e=0;e<6;e++){if(N(R(t,`package.json`))&&N(R(t,`plugin`)))return t;let e=ge(t);if(e===t)break;t=e}return ge(ge(e))},Zn=()=>R(Xn(),`plugin`),Qn=e=>{try{let t=e?_e(e,`..`):Xn();return JSON.parse(Jn(t,`package.json`)).version??`unknown`}catch{return`unknown`}},$n=e=>{let t=e.charCodeAt(0)===65279?e.slice(1):e,n=t.match(/^---\n[\s\S]*?\n---\n?/);return n&&(t=t.slice(n[0].length)),t=t.replace(/^\s*<!--[\s\S]*?-->\s*/,``),t.trim()},er=(e,t,n)=>{let r=[Hn,Kn(n),``,t,``,Un].join(`
142
- `);if(e.includes(Hn)&&e.includes(Un)){let t=RegExp(`${Gn(Hn)}[\\s\\S]*?${Gn(Un)}`);return e.replace(t,r)}let i=e.replace(/\s*$/,``);return i.length>0?`${i}\n\n${r}\n`:`${r}\n`},tr=e=>{let t=[];for(let n of P(e,{withFileTypes:!0}))if(n.isDirectory()){let r=tr(Q(e,n.name));t.push(...r.map(e=>R(n.name,e)))}else t.push(n.name);return t},nr=(e,t)=>{if(!N(t))return!1;let n=tr(e).sort(),r=tr(t).sort();return n.length!==r.length||n.some((e,t)=>e!==r[t])?!1:n.every(n=>Yn(e,n).equals(Yn(t,n)))},rr=(e,t)=>{fe(t,{recursive:!0,force:!0}),ue(ge(t),{recursive:!0}),le(e,t,{recursive:!0})},ir=e=>P(e,{withFileTypes:!0}).some(t=>{if(!t.isDirectory())return!1;let n=Q(e,t.name);return N(Q(n,`SKILL.md`))||ir(n)}),ar=e=>{if(!N(e))return[];let t=[],n=[];for(let r of P(e,{withFileTypes:!0})){if(!r.isDirectory()||!Wn.test(r.name))continue;let i=Q(e,r.name);N(Q(i,`SKILL.md`))?t.push(r.name):ir(i)&&n.push(r.name)}return n.length>0&&console.warn(`Skipped ${n.length} grouped skill director${n.length===1?`y`:`ies`} (${n.join(`, `)}): skills must be one level down (skills/<name>/SKILL.md). Claude Code reads plugin skills one level deep too, so grouped skills are not reachable by any route — flatten them to make them usable.`),t.sort()},or=()=>({changed:[],unchanged:[],missing:[]}),sr=(e,t,n,r)=>{let i=or();for(let a of e){qn(a);let e=Q(t,a);if(!N(e)||!pe(e).isDirectory()){i.missing.push(a);continue}let o=Q(n,a);if(nr(e,o)){i.unchanged.push(a);continue}i.changed.push(a),r||rr(e,o)}return i},cr=(e,t,n)=>{if(!N(e)||!pe(e).isDirectory())return{status:`missing-source`,fileCount:0};let r=tr(e).length;return r===0?{status:`missing-source`,fileCount:0}:nr(e,t)?{status:`unchanged`,fileCount:r}:(n||rr(e,t),{status:`changed`,fileCount:r})},lr=(e,t,n,r)=>{if(!N(Q(e,Vn)))return`missing-source`;let i=$n(Jn(e,Vn)),a=Q(t,`CLAUDE.md`),o=N(a)?Jn(t,`CLAUDE.md`):``,s=er(o,i,n);return s===o?`unchanged`:(r||me(a,s),`changed`)},ur=e=>{let t=_e(e.pluginDir??Zn()),n=_e(e.cwd),r=e.version??Qn(t),i=e.check??!1,a=Q(n,`.claude`),o=Q(t,`skills`),s=sr(ar(o),o,Q(a,`skills`),i),c=cr(Q(t,`commands`),Q(a,`commands`),i),l=cr(Q(t,`agents`),Q(a,`agents`),i),u=lr(t,n,r,i),d=s.changed.length>0||c.status===`changed`||l.status===`changed`||u===`changed`,f=u!==`missing-source`||c.status!==`missing-source`||l.status!==`missing-source`||s.changed.length+s.unchanged.length>0;if(!i&&f){ue(a,{recursive:!0});let e={harnessVersion:r,skills:s.changed.concat(s.unchanged).sort(),commands:c.fileCount,agents:l.fileCount,guide:u!==`missing-source`};me(Q(a,`.stackone-connector-env.json`),`${JSON.stringify(e,null,2)}\n`)}return{skills:s,commands:c,agents:l,guide:u,hasChanges:d}},dr=e=>{try{let t=e??Zn();return pe(t).isDirectory()?e?JSON.parse(Jn(_e(t,`..`),`package.json`)).name===`@stackone/agent-harness`:!0:!1}catch{return!1}},fr=({message:e,choices:t,initialIndex:n=0,onSelect:r,onCancel:i})=>{let[a,o]=W(()=>t.length?Math.min(Math.max(n,0),t.length-1):0);return xe((e,n)=>{if(t.length===0){n.escape&&i?.();return}n.upArrow?o(e=>(e-1+t.length)%t.length):n.downArrow?o(e=>(e+1)%t.length):n.return?r(t[a].value):n.escape&&i?.()}),t.length===0?null:V.createElement(z,{flexDirection:`column`,paddingY:1},V.createElement(z,{borderStyle:`round`,borderColor:`cyan`,flexDirection:`column`,paddingX:2,paddingY:1},V.createElement(B,{bold:!0},e),V.createElement(z,{flexDirection:`column`,marginTop:1},t.map((e,t)=>V.createElement(B,{key:e.value,color:t===a?`#00af66`:`white`},t===a?`❯ `:` `,e.label)))),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`↑↓ to navigate • Enter to select`)))},pr=({message:e,initialValue:t=``,validate:n,onSubmit:r,onCancel:i})=>{let[a,o]=W(t),[s,c]=W(null);return xe((e,t)=>{if(t.return){let e=n?n(a):!0;e===!0?r(a):c(e);return}if(t.escape){i?.();return}if(t.backspace||t.delete){o(e=>e.slice(0,-1)),c(null);return}e&&!t.ctrl&&!t.meta&&!t.tab&&!t.upArrow&&!t.downArrow&&(o(t=>t+e),c(null))}),V.createElement(z,{flexDirection:`column`,paddingY:1},V.createElement(B,{bold:!0},e),V.createElement(z,{marginTop:1},V.createElement(B,null,`> `),V.createElement(B,null,a),V.createElement(B,{inverse:!0},` `)),s&&V.createElement(z,{marginTop:1},V.createElement(B,{color:`red`},s)),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`Enter to submit • Esc to cancel`)))},mr=e=>N(`${e}/CLAUDE.md`)||N(`${e}/.mcp.json`),hr=e=>{try{return pe(e).isDirectory()}catch{return!1}},gr=({initialMode:e,pathFlag:t,startDir:n,onExit:r})=>{let[i,o]=W(`mode`),[c,u]=W(null),[f,p]=W(!1),[h,g]=W([]),[v,y]=W(``),[b,x]=W(e),[C,te]=W(``),[w,T]=W(``),[E,ne]=W(!1),[D,re]=W(null),ie=U(0),O=Se(e=>{ie.current+=1;let t=ie.current;g(n=>[...n,{...e,id:t}])},[]),k=Se(e=>{u(e)},[]),ae=Se(async e=>{let t=_e(Nn(e));if(!hr(t)){k({status:`error`,message:N(t)?`Target path is not a directory: ${t}`:`Target path does not exist: ${t}`});return}te(t);let n=mr(t),r=d(await ee());ne(r),o(Rn(`path-input`,{mode:`local`,hasGit:!1,repoAccepted:!1,existingConfig:n,alreadyAuthed:r}))},[k]),oe=Se(e=>{if(x(e),e===`local`){let e=t?.trim();if(e){ae(e);return}let r=Bn(n);r&&(T(`Install the connector setup into this repo? ${r.remoteUrl?`${r.remoteUrl} (${r.root})`:r.root}`),te(r.root)),o(Rn(`mode`,{mode:`local`,hasGit:!!r,repoAccepted:!1,existingConfig:!1,alreadyAuthed:!1}));return}o(Rn(`mode`,{mode:`global`,hasGit:!1,repoAccepted:!1,existingConfig:mr(n),alreadyAuthed:!1}))},[t,n,ae]);H(()=>{e&&oe(e)},[]);let se=Se(e=>{e?ae(C):o(`path-input`)},[ae,C]),A=Se(e=>{if(!e){k({status:`cancelled`});return}o(Rn(`overwrite`,{mode:b??`global`,hasGit:!1,repoAccepted:!1,existingConfig:!0,alreadyAuthed:E}))},[b,E,k]);return H(()=>{if(i!==`auth`)return;let e=!1;return y(`Starting browser authentication…`),Tn(t=>{e||y(t)}).then(t=>{e||(re(t),O({icon:`✓`,text:t.email?`Authenticated as ${t.email}`:`Authenticated`,color:Z.success}),o(`work`))}).catch(t=>{e||k({status:`error`,message:t instanceof Error?t.message:`Authentication failed`})}),()=>{e=!0}},[i,O,k]),H(()=>{if(i!==`work`)return;let e=!1;return(async()=>{try{let t=D??await ee();if(!t)throw Error(`Not authenticated — no API key found`);let r=await S(b===`local`?C:n,t.apiKey);if(r.migrated&&O({icon:`✓`,text:`Migrated ${r.actions.length} item(s) from a previous setup`,color:Z.success}),b===`local`){y(`Creating .mcp.json…`),l(m(C),s(),t.apiKey),O({icon:`✓`,text:`Created .mcp.json`,color:Z.success}),y(`Syncing connector-building skills + guide…`);let e=ur({cwd:C});O({icon:`✓`,text:`Connector environment ready (${e.skills.changed.length+e.skills.unchanged.length} skills in .claude/, ${e.guide===`missing-source`?`guide unavailable in this version`:`guide in CLAUDE.md`})`,color:Z.success})}else y(`Installing global MCP configuration…`),l(a(),_(),t.apiKey),O({icon:`✓`,text:`Installed to Claude (global)`,color:Z.success});if(e)return;y(``),k({status:`done`})}catch(t){if(e)return;k({status:`error`,message:t instanceof Error?t.message:`Setup failed`})}})(),()=>{e=!0}},[i,D,b,C,n,O,k]),H(()=>{if(!c)return;let e=setTimeout(()=>r(c),60);return()=>clearTimeout(e)},[c,r]),V.createElement(z,{flexDirection:`column`,padding:1},f?V.createElement(At,{wordmark:!0}):V.createElement(Mt,{ready:!0,onComplete:()=>p(!0)}),h.length>0&&V.createElement(z,{flexDirection:`column`,marginTop:1},h.map(e=>V.createElement(B,{key:e.id,color:e.color},e.icon?`${e.icon} `:``,e.text))),V.createElement(z,{marginTop:1},(()=>{if(c)return c.status===`error`?V.createElement(B,{color:Z.error},`✗ `,c.message??`Setup failed`):c.status===`cancelled`?V.createElement(B,{color:Z.dim},`Setup cancelled.`):V.createElement(z,{flexDirection:`column`},V.createElement(B,{color:Z.success},`✓ Setup complete!`),V.createElement(z,{marginTop:1,flexDirection:`column`},V.createElement(B,{color:Z.dim},`Verify with `,V.createElement(B,{color:Z.primary},`claude mcp list`)),V.createElement(B,{color:Z.dim},`Tip: run`,` `,V.createElement(B,{color:Z.primary},`claude --dangerously-skip-permissions`),` `,`to skip permission prompts`),b===`local`&&V.createElement(B,{color:Z.dim},`Refresh skills anytime with`,` `,V.createElement(B,{color:Z.primary},`stackone agent sync`))));switch(i){case`mode`:return e?null:V.createElement(fr,{message:`How do you want to set up the StackOne agent?`,initialIndex:0,choices:[{label:`Local — this project: auth + .mcp.json + connector skills (.claude/) + guide (CLAUDE.md)`,value:`local`},{label:`Global — any repo: auth + global MCP only (no connector skills/guide)`,value:`global`}],onSelect:e=>oe(e),onCancel:()=>k({status:`cancelled`})});case`repo-confirm`:return V.createElement(fr,{message:w,initialIndex:0,choices:[{label:`Yes`,value:`yes`},{label:`No, let me choose a path`,value:`no`}],onSelect:e=>se(e===`yes`),onCancel:()=>k({status:`cancelled`})});case`path-input`:return V.createElement(pr,{message:`Path to install the connector setup into:`,initialValue:n,validate:e=>{let t=Nn(e)||n;return N(t)?hr(t)?!0:`Path is not a directory: ${t}`:`Path does not exist: ${t}`},onSubmit:e=>void ae(e.trim()||n),onCancel:()=>k({status:`cancelled`})});case`overwrite`:{let e=b===`local`;return V.createElement(fr,{message:e?`Existing setup found in ${C}. Overwrite it?`:`Local setup detected in ${n} (it won't be modified). Set up the agent globally anyway?`,initialIndex:e?1:0,choices:[{label:e?`Yes, overwrite`:`Yes, set up globally`,value:`yes`},{label:`No, cancel`,value:`no`}],onSelect:e=>A(e===`yes`),onCancel:()=>k({status:`cancelled`})})}case`auth`:case`work`:return V.createElement(B,null,V.createElement(B,{color:Z.primary},V.createElement(Oe,{type:`dots`})),` `,v);default:return null}})()))},_r=e=>new Promise(t=>{let{unmount:n}=ye(e(e=>{n(),t(e)}))}),vr=()=>_r(e=>V.createElement(fr,{message:`How do you want to set up the StackOne agent?`,initialIndex:0,choices:[{label:`Local — this project: auth + .mcp.json + connector skills (.claude/) + guide (CLAUDE.md)`,value:`local`},{label:`Global — any repo: auth + global MCP only (no connector skills/guide)`,value:`global`}],onSelect:t=>e(t)})),yr=(e,t=!0)=>_r(n=>V.createElement(fr,{message:e,initialIndex:t?0:1,choices:[{label:`Yes`,value:`yes`},{label:`No`,value:`no`}],onSelect:e=>n(e===`yes`),onCancel:()=>n(!1)})),br=async e=>{let t=Bn(e);return t&&await yr(`Install the connector setup into this repo? ${t.remoteUrl?`${t.remoteUrl} (${t.root})`:t.root}`,!0)?t.root:_r(n=>V.createElement(pr,{message:t?`Path to install into:`:`Current directory is not a git repo. Path to install into:`,initialValue:e,validate:t=>{let n=Nn(t)||e;return N(n)?!0:`Path does not exist: ${n}`},onSubmit:t=>n(Nn(t)||e)}))},xr=e=>new Promise(t=>{let{unmount:n}=ye(V.createElement(gr,{initialMode:e.initialMode,pathFlag:e.pathFlag,startDir:e.startDir??process.cwd(),onExit:e=>{n(),t(e)}}))});var Sr=class{async execute(e){y.log(T.blue.bold(`🤖 StackOne Agent Setup - Local Project
142
+ `);if(e.includes(Hn)&&e.includes(Un)){let t=RegExp(`${Gn(Hn)}[\\s\\S]*?${Gn(Un)}`);return e.replace(t,r)}let i=e.replace(/\s*$/,``);return i.length>0?`${i}\n\n${r}\n`:`${r}\n`},tr=e=>{let t=[];for(let n of P(e,{withFileTypes:!0}))if(n.isDirectory()){let r=tr(Q(e,n.name));t.push(...r.map(e=>R(n.name,e)))}else t.push(n.name);return t},nr=(e,t)=>{if(!N(t))return!1;let n=tr(e).sort(),r=tr(t).sort();return n.length!==r.length||n.some((e,t)=>e!==r[t])?!1:n.every(n=>Yn(e,n).equals(Yn(t,n)))},rr=(e,t)=>{if(!N(t))return!1;let n=tr(t).sort(),r=[...e.keys()].sort();return n.length!==r.length||r.some((e,t)=>e!==n[t])?!1:r.every(n=>Yn(e.get(n),n).equals(Yn(t,n)))},ir=(e,t)=>{fe(t,{recursive:!0,force:!0}),ue(ge(t),{recursive:!0}),le(e,t,{recursive:!0})},ar=e=>P(e,{withFileTypes:!0}).some(t=>{if(!t.isDirectory())return!1;let n=Q(e,t.name);return N(Q(n,`SKILL.md`))||ar(n)}),or=e=>{if(!N(e))return[];let t=[],n=[];for(let r of P(e,{withFileTypes:!0})){if(!r.isDirectory()||!Wn.test(r.name))continue;let i=Q(e,r.name);N(Q(i,`SKILL.md`))?t.push(r.name):ar(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()},sr=()=>({changed:[],unchanged:[],missing:[]}),cr=(e,t,n,r)=>{let i=sr();for(let a of e){qn(a);let e=Q(t,a);if(!N(e)||!pe(e).isDirectory()){i.missing.push(a);continue}let o=Q(n,a);if(nr(e,o)){i.unchanged.push(a);continue}i.changed.push(a),r||ir(e,o)}return i},lr=(e,t,n)=>{let r=e.filter(e=>N(e)&&pe(e).isDirectory()&&tr(e).length>0);if(r.length===0)return{status:`missing-source`,fileCount:0};let i=new Map;for(let e of r)for(let t of tr(e))i.set(t,e);let a=i.size;if(rr(i,t))return{status:`unchanged`,fileCount:a};if(!n){fe(t,{recursive:!0,force:!0}),ue(t,{recursive:!0});for(let e of r)le(e,t,{recursive:!0})}return{status:`changed`,fileCount:a}},ur=(e,t,n,r)=>{if(!N(Q(e,Vn)))return`missing-source`;let i=$n(Jn(e,Vn)),a=Q(t,`CLAUDE.md`),o=N(a)?Jn(t,`CLAUDE.md`):``,s=er(o,i,n);return s===o?`unchanged`:(r||me(a,s),`changed`)},dr=e=>{let t=_e(e.pluginDir??Zn()),n=_e(e.cwd),r=e.version??Qn(t),i=e.check??!1,a=Q(n,`.claude`),o=e.buildtimeOnly??!1,s=Q(t,`interactive`),c=Q(a,`skills`),l=Q(t,`skills`),u=cr(or(l),l,c,i);if(!o){let e=Q(s,`skills`),t=cr(or(e),e,c,i);u.changed.push(...t.changed),u.unchanged.push(...t.unchanged),u.missing.push(...t.missing)}let d=lr(o?[Q(t,`commands`)]:[Q(t,`commands`),Q(s,`commands`)],Q(a,`commands`),i),f=lr(o?[Q(t,`agents`)]:[Q(t,`agents`),Q(s,`agents`)],Q(a,`agents`),i),p=ur(t,n,r,i),m=u.changed.length>0||d.status===`changed`||f.status===`changed`||p===`changed`,h=p!==`missing-source`||d.status!==`missing-source`||f.status!==`missing-source`||u.changed.length+u.unchanged.length>0;if(!i&&h){ue(a,{recursive:!0});let e={harnessVersion:r,skills:u.changed.concat(u.unchanged).sort(),commands:d.fileCount,agents:f.fileCount,guide:p!==`missing-source`};me(Q(a,`.stackone-connector-env.json`),`${JSON.stringify(e,null,2)}\n`)}return{skills:u,commands:d,agents:f,guide:p,hasChanges:m}},fr=e=>{try{let t=e??Zn();return pe(t).isDirectory()?e?JSON.parse(Jn(_e(t,`..`),`package.json`)).name===`@stackone/agent-harness`:!0:!1}catch{return!1}},pr=({message:e,choices:t,initialIndex:n=0,onSelect:r,onCancel:i})=>{let[a,o]=W(()=>t.length?Math.min(Math.max(n,0),t.length-1):0);return xe((e,n)=>{if(t.length===0){n.escape&&i?.();return}n.upArrow?o(e=>(e-1+t.length)%t.length):n.downArrow?o(e=>(e+1)%t.length):n.return?r(t[a].value):n.escape&&i?.()}),t.length===0?null:V.createElement(z,{flexDirection:`column`,paddingY:1},V.createElement(z,{borderStyle:`round`,borderColor:`cyan`,flexDirection:`column`,paddingX:2,paddingY:1},V.createElement(B,{bold:!0},e),V.createElement(z,{flexDirection:`column`,marginTop:1},t.map((e,t)=>V.createElement(B,{key:e.value,color:t===a?`#00af66`:`white`},t===a?`❯ `:` `,e.label)))),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`↑↓ to navigate • Enter to select`)))},mr=({message:e,initialValue:t=``,validate:n,onSubmit:r,onCancel:i})=>{let[a,o]=W(t),[s,c]=W(null);return xe((e,t)=>{if(t.return){let e=n?n(a):!0;e===!0?r(a):c(e);return}if(t.escape){i?.();return}if(t.backspace||t.delete){o(e=>e.slice(0,-1)),c(null);return}e&&!t.ctrl&&!t.meta&&!t.tab&&!t.upArrow&&!t.downArrow&&(o(t=>t+e),c(null))}),V.createElement(z,{flexDirection:`column`,paddingY:1},V.createElement(B,{bold:!0},e),V.createElement(z,{marginTop:1},V.createElement(B,null,`> `),V.createElement(B,null,a),V.createElement(B,{inverse:!0},` `)),s&&V.createElement(z,{marginTop:1},V.createElement(B,{color:`red`},s)),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`Enter to submit • Esc to cancel`)))},hr=e=>N(`${e}/CLAUDE.md`)||N(`${e}/.mcp.json`),gr=e=>{try{return pe(e).isDirectory()}catch{return!1}},_r=({initialMode:e,pathFlag:t,startDir:n,onExit:r})=>{let[i,o]=W(`mode`),[c,u]=W(null),[f,p]=W(!1),[h,g]=W([]),[v,y]=W(``),[b,x]=W(e),[C,te]=W(``),[w,T]=W(``),[E,ne]=W(!1),[D,re]=W(null),ie=U(0),O=Se(e=>{ie.current+=1;let t=ie.current;g(n=>[...n,{...e,id:t}])},[]),k=Se(e=>{u(e)},[]),ae=Se(async e=>{let t=_e(Nn(e));if(!gr(t)){k({status:`error`,message:N(t)?`Target path is not a directory: ${t}`:`Target path does not exist: ${t}`});return}te(t);let n=hr(t),r=d(await ee());ne(r),o(Rn(`path-input`,{mode:`local`,hasGit:!1,repoAccepted:!1,existingConfig:n,alreadyAuthed:r}))},[k]),oe=Se(e=>{if(x(e),e===`local`){let e=t?.trim();if(e){ae(e);return}let r=Bn(n);r&&(T(`Install the connector setup into this repo? ${r.remoteUrl?`${r.remoteUrl} (${r.root})`:r.root}`),te(r.root)),o(Rn(`mode`,{mode:`local`,hasGit:!!r,repoAccepted:!1,existingConfig:!1,alreadyAuthed:!1}));return}o(Rn(`mode`,{mode:`global`,hasGit:!1,repoAccepted:!1,existingConfig:hr(n),alreadyAuthed:!1}))},[t,n,ae]);H(()=>{e&&oe(e)},[]);let se=Se(e=>{e?ae(C):o(`path-input`)},[ae,C]),A=Se(e=>{if(!e){k({status:`cancelled`});return}o(Rn(`overwrite`,{mode:b??`global`,hasGit:!1,repoAccepted:!1,existingConfig:!0,alreadyAuthed:E}))},[b,E,k]);return H(()=>{if(i!==`auth`)return;let e=!1;return y(`Starting browser authentication…`),Tn(t=>{e||y(t)}).then(t=>{e||(re(t),O({icon:`✓`,text:t.email?`Authenticated as ${t.email}`:`Authenticated`,color:Z.success}),o(`work`))}).catch(t=>{e||k({status:`error`,message:t instanceof Error?t.message:`Authentication failed`})}),()=>{e=!0}},[i,O,k]),H(()=>{if(i!==`work`)return;let e=!1;return(async()=>{try{let t=D??await ee();if(!t)throw Error(`Not authenticated — no API key found`);let r=await S(b===`local`?C:n,t.apiKey);if(r.migrated&&O({icon:`✓`,text:`Migrated ${r.actions.length} item(s) from a previous setup`,color:Z.success}),b===`local`){y(`Creating .mcp.json…`),l(m(C),s(),t.apiKey),O({icon:`✓`,text:`Created .mcp.json`,color:Z.success}),y(`Syncing connector-building skills + guide…`);let e=dr({cwd:C});O({icon:`✓`,text:`Connector environment ready (${e.skills.changed.length+e.skills.unchanged.length} skills in .claude/, ${e.guide===`missing-source`?`guide unavailable in this version`:`guide in CLAUDE.md`})`,color:Z.success})}else y(`Installing global MCP configuration…`),l(a(),_(),t.apiKey),O({icon:`✓`,text:`Installed to Claude (global)`,color:Z.success});if(e)return;y(``),k({status:`done`})}catch(t){if(e)return;k({status:`error`,message:t instanceof Error?t.message:`Setup failed`})}})(),()=>{e=!0}},[i,D,b,C,n,O,k]),H(()=>{if(!c)return;let e=setTimeout(()=>r(c),60);return()=>clearTimeout(e)},[c,r]),V.createElement(z,{flexDirection:`column`,padding:1},f?V.createElement(At,{wordmark:!0}):V.createElement(Mt,{ready:!0,onComplete:()=>p(!0)}),h.length>0&&V.createElement(z,{flexDirection:`column`,marginTop:1},h.map(e=>V.createElement(B,{key:e.id,color:e.color},e.icon?`${e.icon} `:``,e.text))),V.createElement(z,{marginTop:1},(()=>{if(c)return c.status===`error`?V.createElement(B,{color:Z.error},`✗ `,c.message??`Setup failed`):c.status===`cancelled`?V.createElement(B,{color:Z.dim},`Setup cancelled.`):V.createElement(z,{flexDirection:`column`},V.createElement(B,{color:Z.success},`✓ Setup complete!`),V.createElement(z,{marginTop:1,flexDirection:`column`},V.createElement(B,{color:Z.dim},`Verify with `,V.createElement(B,{color:Z.primary},`claude mcp list`)),V.createElement(B,{color:Z.dim},`Tip: run`,` `,V.createElement(B,{color:Z.primary},`claude --dangerously-skip-permissions`),` `,`to skip permission prompts`),b===`local`&&V.createElement(B,{color:Z.dim},`Refresh skills anytime with`,` `,V.createElement(B,{color:Z.primary},`stackone agent sync`))));switch(i){case`mode`:return e?null:V.createElement(pr,{message:`How do you want to set up the StackOne agent?`,initialIndex:0,choices:[{label:`Local — this project: auth + .mcp.json + connector skills (.claude/) + guide (CLAUDE.md)`,value:`local`},{label:`Global — any repo: auth + global MCP only (no connector skills/guide)`,value:`global`}],onSelect:e=>oe(e),onCancel:()=>k({status:`cancelled`})});case`repo-confirm`:return V.createElement(pr,{message:w,initialIndex:0,choices:[{label:`Yes`,value:`yes`},{label:`No, let me choose a path`,value:`no`}],onSelect:e=>se(e===`yes`),onCancel:()=>k({status:`cancelled`})});case`path-input`:return V.createElement(mr,{message:`Path to install the connector setup into:`,initialValue:n,validate:e=>{let t=Nn(e)||n;return N(t)?gr(t)?!0:`Path is not a directory: ${t}`:`Path does not exist: ${t}`},onSubmit:e=>void ae(e.trim()||n),onCancel:()=>k({status:`cancelled`})});case`overwrite`:{let e=b===`local`;return V.createElement(pr,{message:e?`Existing setup found in ${C}. Overwrite it?`:`Local setup detected in ${n} (it won't be modified). Set up the agent globally anyway?`,initialIndex:e?1:0,choices:[{label:e?`Yes, overwrite`:`Yes, set up globally`,value:`yes`},{label:`No, cancel`,value:`no`}],onSelect:e=>A(e===`yes`),onCancel:()=>k({status:`cancelled`})})}case`auth`:case`work`:return V.createElement(B,null,V.createElement(B,{color:Z.primary},V.createElement(Oe,{type:`dots`})),` `,v);default:return null}})()))},vr=e=>new Promise(t=>{let{unmount:n}=ye(e(e=>{n(),t(e)}))}),yr=()=>vr(e=>V.createElement(pr,{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)})),br=(e,t=!0)=>vr(n=>V.createElement(pr,{message:e,initialIndex:t?0:1,choices:[{label:`Yes`,value:`yes`},{label:`No`,value:`no`}],onSelect:e=>n(e===`yes`),onCancel:()=>n(!1)})),xr=async e=>{let t=Bn(e);return t&&await br(`Install the connector setup into this repo? ${t.remoteUrl?`${t.remoteUrl} (${t.root})`:t.root}`,!0)?t.root:vr(n=>V.createElement(mr,{message:t?`Path to install into:`:`Current directory is not a git repo. Path to install into:`,initialValue:e,validate:t=>{let n=Nn(t)||e;return N(n)?!0:`Path does not exist: ${n}`},onSubmit:t=>n(Nn(t)||e)}))},Sr=e=>new Promise(t=>{let{unmount:n}=ye(V.createElement(_r,{initialMode:e.initialMode,pathFlag:e.pathFlag,startDir:e.startDir??process.cwd(),onExit:e=>{n(),t(e)}}))});var Cr=class{async execute(e){y.log(T.blue.bold(`🤖 StackOne Agent Setup - Local Project
143
143
  `));try{let t=_e(Nn(e?.targetPath??process.cwd()));await Re(t).then(()=>!0).catch(()=>!1)||(y.error(`Target path does not exist: ${t}`),process.exit(1)),e?.targetPath&&y.log(T.dim(`Installing into ${t}\n`));let n=await Re(`${t}/CLAUDE.md`).then(()=>!0).catch(()=>!1),r=await Re(`${t}/.mcp.json`).then(()=>!0).catch(()=>!1);if(n||r){y.warn(`Existing local setup detected:`),n&&y.log(T.dim(` • CLAUDE.md found`)),r&&y.log(T.dim(` • .mcp.json found`)),y.log(``);let t=pn(!!e?.legacy,e?.credentials),i=!!process.stdin.isTTY;t||!i?y.log(T.dim(t?`Non-interactive credentials detected; proceeding without confirmation.
144
144
  `:`No interactive terminal detected; proceeding without overwrite confirmation.
145
- `)):(await yr(`Overwrite existing local configuration?`,!1)||(y.log(T.dim(`
145
+ `)):(await br(`Overwrite existing local configuration?`,!1)||(y.log(T.dim(`
146
146
  Setup cancelled.`)),process.exit(0)),y.log(``))}let i=await ee();(!i||!d(i))&&(y.warn(`Not authenticated globally.`),y.log(T.white(`Let's authenticate now...
147
147
  `)),i=await En(!!e?.legacy,e?.credentials),y.log(``)),C(await S(t,i.apiKey));let a=q(`Creating .mcp.json...`).start();try{l(m(t),s(),i.apiKey),a.succeed(`Created .mcp.json`),y.success(`Local setup complete!`),y.log(T.white(`Files created:`)),y.log(T.cyan(` • .mcp.json`)),y.log(T.dim(`Token stored securely in Claude MCP server config.`)),y.log(T.dim(`
148
148
  💡 The stackone-agent-local MCP server is now available in this project`)),y.log(T.dim(`
149
149
  💡 Tip: Run Claude without permission prompts:`),T.cyan(`claude --dangerously-skip-permissions`)),y.log(T.blue(`
150
- Verify:`),T.cyan(`claude mcp list`)),y.log(``)}catch(e){a.fail(`Failed to create .mcp.json`),e instanceof Error&&y.error(e.message)}let o=q(`Syncing connector-building skills + guide...`).start();try{let e=ur({cwd:t}),n=e.skills.changed.length+e.skills.unchanged.length,r=e.guide===`missing-source`?`unavailable in this version`:`in CLAUDE.md`;o.succeed(`Connector-building environment ready (${n} skills in .claude/, guide ${r})`),y.log(T.dim(` Refresh anytime with`),T.cyan(`stackone agent sync`))}catch(e){o.fail(`Failed to sync connector-building environment`),e instanceof Error&&y.error(e.message)}process.exit(0)}catch(e){e instanceof Error?y.error(e.message):y.error(`Unknown error occurred`),process.exit(1)}}},Cr=class{async execute(e){let t=se(),n=e?.mode;if(y.log(T.bold(`
150
+ Verify:`),T.cyan(`claude mcp list`)),y.log(``)}catch(e){a.fail(`Failed to create .mcp.json`),e instanceof Error&&y.error(e.message)}let o=q(`Syncing connector-building skills + guide...`).start();try{let e=dr({cwd:t}),n=e.skills.changed.length+e.skills.unchanged.length,r=e.guide===`missing-source`?`unavailable in this version`:`in CLAUDE.md`;o.succeed(`Connector-building environment ready (${n} skills in .claude/, guide ${r})`),y.log(T.dim(` Refresh anytime with`),T.cyan(`stackone agent sync`))}catch(e){o.fail(`Failed to sync connector-building environment`),e instanceof Error&&y.error(e.message)}process.exit(0)}catch(e){e instanceof Error?y.error(e.message):y.error(`Unknown error occurred`),process.exit(1)}}},wr=class{async execute(e){let t=se(),n=e?.mode;if(y.log(T.bold(`
151
151
  Available skills
152
152
  `)),t.length===0){y.log(T.dim(` No bundled skills found.
153
- `));return}for(let e of t)y.log(` • ${e}`);if(n){let e=j(n);if(e.length>0){y.log(T.bold(`\nRecommended for mode "${n}":\n`));for(let n of e){let e=t.includes(n);y.log(` • ${n}${e?``:T.dim(` (not found)`)}`)}}}y.log(``)}};const wr=(e,t,n)=>{let r=n?`stale`:`synced`;t.changed.length>0&&y.log(T.cyan(` • ${e} ${r}: ${t.changed.join(`, `)}`)),t.missing.length>0&&y.log(T.dim(` • ${e} not in this harness version: ${t.missing.join(`, `)}`))},Tr=(e,t,n)=>{if(t.status===`missing-source`)return;let r=t.status===`changed`?n?`stale`:`synced`:`up to date`;y.log(T.cyan(` • ${e} ${r}: ${t.fileCount} file(s)`))},Er=(e,t)=>{e===`missing-source`?y.log(T.dim(` • connector-guide.md not in this harness version — skipped CLAUDE.md`)):e===`changed`&&y.log(T.cyan(` • CLAUDE.md guide block ${t?`stale`:`updated`}`))};var Dr=class{async execute(e){let t=!!e?.check,n=e?.pluginDir;dr(n)||(y.error(n?`--plugin-dir is not a valid @stackone/agent-harness plugin dir: ${n}`:`Could not locate the bundled @stackone/agent-harness plugin. Reinstall the CLI and try again.`),process.exit(1));let r=Qn(n);y.log(T.blue.bold(`🧩 ${t?`Checking`:`Syncing`} connector-building environment`)+T.dim(` (agent-harness@${r}${n?` [--plugin-dir]`:``})\n`));try{let e=ur({cwd:process.cwd(),check:t,pluginDir:n});wr(`skills`,e.skills,t),Tr(`commands`,e.commands,t),Tr(`agents`,e.agents,t),Er(e.guide,t),t&&(e.hasChanges&&(y.log(``),y.error("Connector-building environment is out of date. Run `stackone agent sync` to update."),process.exit(1)),y.success(`Connector-building environment is up to date.`),process.exit(0)),e.hasChanges?(y.success(`Connector-building environment synced into .claude/ and CLAUDE.md.`),y.log(T.dim(`
154
- 💡 Skills and the connector guide are managed by the CLI — `),T.dim("re-run `stackone agent sync` after a CLI update."))):y.success(`Already up to date — nothing to sync.`),process.exit(0)}catch(e){y.error(e instanceof Error?e.message:`Unknown error during sync`),process.exit(1)}}};const Or={profiles:{}},kr=()=>{let t=i.readConfigFile(e);if(!t)return Or;try{return JSON.parse(t)}catch{return Or}},Ar=e=>kr().profiles[e],jr=e=>!!kr().profiles[e],Mr=(t,n)=>{let r=kr();r.profiles[t]=n,i.writeConfigFile(e,JSON.stringify(r,null,2))},Nr=()=>{let e=kr();return Object.keys(e.profiles)},Pr=`https://api.stackone.com`;var Fr=class{async execute({profile:e,connector:r,apiUrl:i,apiKey:a}={}){if(!e&&!a&&(y.error(`Profile or API key is required`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),e&&a&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&i&&y.warn(`Specifying ${t(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!jr(e)){y.error(`Configuration profile ${t(e)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let n=Nr();n.length>0&&(y.info(`Available configuration profiles:`),n.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let o=e?Ar(e):{apiUrl:i??Pr,apiKey:a};o?.apiKey||(y.error(`API key is missing`),y.log(`Please provide a valid API key in the profile or via the ${t(`--api-key`)} option.`),process.exit(1)),r||(y.error(`Connector identifier is required in the format provider_key@version.`),process.exit(1));let s=r.split(`@`);(s.length!==2||!s[0]||!s[1])&&(y.error(`Invalid connector format ${n(r)}. Expected format: ${t(`provider_key@version`)}`),process.exit(1));let c=o.apiUrl??Pr,l=await this.dropConnector(r,c,o.apiKey);process.exit(l?0:1)}async dropConnector(e,n,i){let a=q(`🗑️ Dropping connector ${t(e)}...`).start();try{let r=Buffer.from(i).toString(`base64`),o=await fetch(`${n}/registry/connectors/${e}`,{method:`DELETE`,headers:{Authorization:`Basic ${r}`}});return a.stop(),o.status===204?(y.success(`Successfully dropped connector ${t(e)} from the registry`),!0):o.status===404?(y.error(`Connector ${t(e)} not found in the registry`),!1):o.status===401||o.status===403?(y.error(`You do not have permission to drop this connector`),!1):o.status===409?(y.error(`Connector ${t(e)} has associated configs and cannot be dropped`),y.log(`Please delete all associated integration configurations before dropping the connector.`),!1):(o.ok||await b(o,`Failed to drop connector ${t(e)} from the registry`),!1)}catch(i){return a.stop(),y.error(`Failed to drop connector ${t(e)} from registry: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),!1}}};const Ir=`stackone`;async function Lr(e,n){n.length===0&&(y.error(`Multiple versions of connector ${t(e)} were found but no owner information was returned`),process.exit(1));let r=n.map(e=>({value:e,label:e===Ir?`StackOne`:`Custom`,hint:e===Ir?`Official StackOne connector`:`Custom connector version created by your organization`}));y.warn(`Multiple versions of connector ${t(e)} were found. Please select which version to use.`);let i=await Ze({message:`Which version would you like to use?`,options:r});return Je(i)&&(y.error(`Operation cancelled.`),process.exit(1)),i}const Rr=`https://api.stackone.com`;var zr=class{async execute({profile:e,connector:r,accountId:i,format:a,outputFile:s,apiUrl:c,apiKey:l,owner:u}={}){if(!e&&!l&&(y.error(`Profile or API key is required`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),e&&l&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&c&&y.warn(`Specifying ${t(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!jr(e)){y.error(`Configuration profile ${t(e)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let n=Nr();n.length>0&&(y.info(`Available configuration profiles:`),n.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let d=e?Ar(e):{apiUrl:c??Rr,apiKey:l};d?.apiKey||(y.error(`API key is missing`),y.log(`Please provide a valid API key in the profile or via the ${t(`--api-key`)} option.`),process.exit(1)),J(r)&&J(i)&&(y.error(`Either ${t(`--connector`)} or ${t(`--account-id`)} must be provided`),process.exit(1)),Y(r)&&Y(i)&&(y.error(`Please provide either ${t(`--connector`)} or ${t(`--account-id`)}, not both.`),process.exit(1)),Y(a)&&a!==`yaml`&&a!==`json`&&(y.error(`Format must be either ${t(`yaml`)} or ${t(`json`)}.`),process.exit(1));let f=d.apiUrl??Rr,p;if(Y(r)){this.#t(r)||(y.error(`Invalid connector format ${n(r)}. Expected format: ${t(`provider_key@version`)} or ${t(`provider_key`)}`),process.exit(1));let e=this.#n(r);p=await this.#r(e,f,d.apiKey,a,u)}else Y(i)?p=await this.#i(i,f,d.apiKey,a):(y.error(`Either ${t(`--connector`)} or ${t(`--account-id`)} must be provided`),process.exit(1));if(Y(s))try{G.writeFileSync(s,p,`utf-8`),y.success(`Connector written to file: ${t(s)}`)}catch(e){y.error(`Failed to write connector to file ${t(s)}: ${e.message}`),process.exit(1)}else if(y.log(`\n${T.blue.inverse(` CONNECTOR CONTENT `)}\n`),!a||a===`yaml`)y.log(this.#e(p));else if(a===`json`)try{o(JSON.parse(p))}catch{y.log(p)}else y.log(p);process.exit(0)}#e(e){return e.split(`
153
+ `));return}for(let e of t)y.log(` • ${e}`);if(n){let e=j(n);if(e.length>0){y.log(T.bold(`\nRecommended for mode "${n}":\n`));for(let n of e){let e=t.includes(n);y.log(` • ${n}${e?``:T.dim(` (not found)`)}`)}}}y.log(``)}};const Tr=(e,t,n)=>{let r=n?`stale`:`synced`;t.changed.length>0&&y.log(T.cyan(` • ${e} ${r}: ${t.changed.join(`, `)}`)),t.missing.length>0&&y.log(T.dim(` • ${e} not in this harness version: ${t.missing.join(`, `)}`))},Er=(e,t,n)=>{if(t.status===`missing-source`)return;let r=t.status===`changed`?n?`stale`:`synced`:`up to date`;y.log(T.cyan(` • ${e} ${r}: ${t.fileCount} file(s)`))},Dr=(e,t)=>{e===`missing-source`?y.log(T.dim(` • connector-guide.md not in this harness version — skipped CLAUDE.md`)):e===`changed`&&y.log(T.cyan(` • CLAUDE.md guide block ${t?`stale`:`updated`}`))};var Or=class{async execute(e){let t=!!e?.check,n=e?.pluginDir;fr(n)||(y.error(n?`--plugin-dir is not a valid @stackone/agent-harness plugin dir: ${n}`:`Could not locate the bundled @stackone/agent-harness plugin. Reinstall the CLI and try again.`),process.exit(1));let r=Qn(n);y.log(T.blue.bold(`🧩 ${t?`Checking`:`Syncing`} connector-building environment`)+T.dim(` (agent-harness@${r}${n?` [--plugin-dir]`:``})\n`));try{let r=dr({cwd:process.cwd(),check:t,pluginDir:n,buildtimeOnly:!!e?.buildtimeOnly});Tr(`skills`,r.skills,t),Er(`commands`,r.commands,t),Er(`agents`,r.agents,t),Dr(r.guide,t),t&&(r.hasChanges&&(y.log(``),y.error("Connector-building environment is out of date. Run `stackone agent sync` to update."),process.exit(1)),y.success(`Connector-building environment is up to date.`),process.exit(0)),r.hasChanges?(y.success(`Connector-building environment synced into .claude/ and CLAUDE.md.`),y.log(T.dim(`
154
+ 💡 Skills and the connector guide are managed by the CLI — `),T.dim("re-run `stackone agent sync` after a CLI update."))):y.success(`Already up to date — nothing to sync.`),process.exit(0)}catch(e){y.error(e instanceof Error?e.message:`Unknown error during sync`),process.exit(1)}}};const kr={profiles:{}},Ar=()=>{let t=i.readConfigFile(e);if(!t)return kr;try{return JSON.parse(t)}catch{return kr}},jr=e=>Ar().profiles[e],Mr=e=>!!Ar().profiles[e],Nr=(t,n)=>{let r=Ar();r.profiles[t]=n,i.writeConfigFile(e,JSON.stringify(r,null,2))},Pr=()=>{let e=Ar();return Object.keys(e.profiles)},Fr=`https://api.stackone.com`;var Ir=class{async execute({profile:e,connector:r,apiUrl:i,apiKey:a}={}){if(!e&&!a&&(y.error(`Profile or API key is required`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),e&&a&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&i&&y.warn(`Specifying ${t(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!Mr(e)){y.error(`Configuration profile ${t(e)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let n=Pr();n.length>0&&(y.info(`Available configuration profiles:`),n.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let o=e?jr(e):{apiUrl:i??Fr,apiKey:a};o?.apiKey||(y.error(`API key is missing`),y.log(`Please provide a valid API key in the profile or via the ${t(`--api-key`)} option.`),process.exit(1)),r||(y.error(`Connector identifier is required in the format provider_key@version.`),process.exit(1));let s=r.split(`@`);(s.length!==2||!s[0]||!s[1])&&(y.error(`Invalid connector format ${n(r)}. Expected format: ${t(`provider_key@version`)}`),process.exit(1));let c=o.apiUrl??Fr,l=await this.dropConnector(r,c,o.apiKey);process.exit(l?0:1)}async dropConnector(e,n,i){let a=q(`🗑️ Dropping connector ${t(e)}...`).start();try{let r=Buffer.from(i).toString(`base64`),o=await fetch(`${n}/registry/connectors/${e}`,{method:`DELETE`,headers:{Authorization:`Basic ${r}`}});return a.stop(),o.status===204?(y.success(`Successfully dropped connector ${t(e)} from the registry`),!0):o.status===404?(y.error(`Connector ${t(e)} not found in the registry`),!1):o.status===401||o.status===403?(y.error(`You do not have permission to drop this connector`),!1):o.status===409?(y.error(`Connector ${t(e)} has associated configs and cannot be dropped`),y.log(`Please delete all associated integration configurations before dropping the connector.`),!1):(o.ok||await b(o,`Failed to drop connector ${t(e)} from the registry`),!1)}catch(i){return a.stop(),y.error(`Failed to drop connector ${t(e)} from registry: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),!1}}};const Lr=`stackone`;async function Rr(e,n){n.length===0&&(y.error(`Multiple versions of connector ${t(e)} were found but no owner information was returned`),process.exit(1));let r=n.map(e=>({value:e,label:e===Lr?`StackOne`:`Custom`,hint:e===Lr?`Official StackOne connector`:`Custom connector version created by your organization`}));y.warn(`Multiple versions of connector ${t(e)} were found. Please select which version to use.`);let i=await Ze({message:`Which version would you like to use?`,options:r});return Je(i)&&(y.error(`Operation cancelled.`),process.exit(1)),i}const zr=`https://api.stackone.com`;var Br=class{async execute({profile:e,connector:r,accountId:i,format:a,outputFile:s,apiUrl:c,apiKey:l,owner:u}={}){if(!e&&!l&&(y.error(`Profile or API key is required`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),e&&l&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&c&&y.warn(`Specifying ${t(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!Mr(e)){y.error(`Configuration profile ${t(e)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let n=Pr();n.length>0&&(y.info(`Available configuration profiles:`),n.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let d=e?jr(e):{apiUrl:c??zr,apiKey:l};d?.apiKey||(y.error(`API key is missing`),y.log(`Please provide a valid API key in the profile or via the ${t(`--api-key`)} option.`),process.exit(1)),J(r)&&J(i)&&(y.error(`Either ${t(`--connector`)} or ${t(`--account-id`)} must be provided`),process.exit(1)),Y(r)&&Y(i)&&(y.error(`Please provide either ${t(`--connector`)} or ${t(`--account-id`)}, not both.`),process.exit(1)),Y(a)&&a!==`yaml`&&a!==`json`&&(y.error(`Format must be either ${t(`yaml`)} or ${t(`json`)}.`),process.exit(1));let f=d.apiUrl??zr,p;if(Y(r)){this.#t(r)||(y.error(`Invalid connector format ${n(r)}. Expected format: ${t(`provider_key@version`)} or ${t(`provider_key`)}`),process.exit(1));let e=this.#n(r);p=await this.#r(e,f,d.apiKey,a,u)}else Y(i)?p=await this.#i(i,f,d.apiKey,a):(y.error(`Either ${t(`--connector`)} or ${t(`--account-id`)} must be provided`),process.exit(1));if(Y(s))try{G.writeFileSync(s,p,`utf-8`),y.success(`Connector written to file: ${t(s)}`)}catch(e){y.error(`Failed to write connector to file ${t(s)}: ${e.message}`),process.exit(1)}else if(y.log(`\n${T.blue.inverse(` CONNECTOR CONTENT `)}\n`),!a||a===`yaml`)y.log(this.#e(p));else if(a===`json`)try{o(JSON.parse(p))}catch{y.log(p)}else y.log(p);process.exit(0)}#e(e){return e.split(`
155
155
  `).map(e=>{if(e.trim().startsWith(`#`))return T.gray(e);if(e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t+1),r=e.substring(t+1),i=r,a=r.trim();return a===`true`||a===`false`?i=r.replace(a,T.cyan(a)):a===`null`||a===`~`?i=r.replace(a,T.gray(a)):/^-?\d+(\.\d+)?$/.test(a)?i=r.replace(a,T.green(a)):(a.startsWith(`"`)&&a.endsWith(`"`)||a.startsWith(`'`)&&a.endsWith(`'`)||a&&!a.startsWith(`-`))&&(i=r.replace(a,T.yellow(a))),T.red(n)+i}return e.trim().startsWith(`-`)?e.replace(`-`,T.gray(`-`)):e}).join(`
156
- `)}#t=e=>!e.includes(`/`)&&!e.includes(`\\`)&&!e.endsWith(`.yaml`)&&!e.endsWith(`.yml`)?e.includes(`@`)?e.split(`@`).length===2:!0:!1;#n=e=>e.includes(`@`)?e:`${e}@latest`;async#r(e,n,i,a,o){let s=q(`Getting connector ${t(e)} from registry...`).start();try{let r=Buffer.from(i).toString(`base64`),c=a?`?format=${a}`:``,l=o?`${c?`&`:`?`}owner=${encodeURIComponent(o)}`:``,u=await fetch(`${n}/registry/connectors/${e}${c}${l}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});if(s.stop(),u.status===409){o&&(await b(u,`Failed to get connector ${t(e)} from the registry`),process.exit(1));let i=await Lr(e,(await u.json()).availableOwners??[]),a=`${n}/registry/connectors/${e}${c}${c?`&`:`?`}owner=${encodeURIComponent(i)}`;s.text=`Getting connector ${t(e)} from registry...`,s.start();let l=await fetch(a,{method:`GET`,headers:{Authorization:`Basic ${r}`}});return s.stop(),l.ok||(await b(l,`Failed to get connector ${t(e)} from the registry`),process.exit(1)),await l.text()}return u.ok||(await b(u,`Failed to get connector ${t(e)} from the registry`),process.exit(1)),await u.text()}catch(i){s.stop(),y.error(`Failed to get connector ${t(e)} from the registry: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}}async#i(e,n,i,a){let o=q(`Getting connector from account ${t(e)}...`).start();try{let r=Buffer.from(i).toString(`base64`),s=a?`?format=${a}`:``,c=await fetch(`${n}/accounts/${e}/connector${s}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});return o.stop(),c.ok||(await b(c,`Failed to get connector from account ${t(e)}`),process.exit(1)),await c.text()}catch(i){o.stop(),y.error(`Failed to get connector from account ${t(e)}: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}}};const Br=`http://localhost:4000`;var Vr=class{async execute({environment:e}={}){let n=e?.toLowerCase()??`production`;try{qe(`${T.inverse(` Initialize profile `)}`);let e=await Qe({message:`Profile label`,validate:e=>{if(!e||e.trim().length===0)return`The profile label is required`;if(e.includes(` `))return`The profile label cannot contain spaces`}});if(Je(e))return Ge(`Configuration profile initialization cancelled`),process.exit(0);if(jr(e)){let n=await Ke({message:`Configuration profile with name ${t(e)} already exists. Do you want to overwrite it?`});if(Je(n)||!n)return Ge(`Configuration profile initialization cancelled`),process.exit(0)}let r;if(n===`production`)r=`https://api.stackone.com`;else if(n===`staging`)r=`https://api.stackone-dev.com`;else{let e=await Qe({message:`API URL`,placeholder:Br,initialValue:Br,validate:e=>{if(!e||e.trim().length===0)return`API URL is required`;try{new URL(e)}catch{return`Please enter a valid URL`}}});if(Je(e))return Ge(`Configuration profile initialization cancelled`),process.exit(0);r=e}let i=await Xe({message:`API Key`,validate:e=>{if(!e||e.trim().length===0)return`API Key is required`}});if(Je(i))return Ge(`Configuration profile initialization cancelled`),process.exit(0);Mr(e,{label:e,environment:n,apiUrl:r,apiKey:i}),Ye(`${T.green(`✔`)} Configuration profile ${t(e)} initialized successfully!`),process.exit(0)}catch(e){e?.isTtyError?y.error(`Prompt couldn't be rendered in the current environment`):y.error(`Failed to initialize configuration profile: ${e}`),process.exit(1)}}};const $={pending:`○`,acceptRemote:`●`,acceptLocal:`◐`,acceptBoth:`◑`,current:`◉`,arrow:`→`,check:`✓`,cross:`✗`,warning:`⚠`};var Hr=class{constructor(e,t,n,r){this.conflicts=[],this.currentIndex=0,this.totalConflicts=0,this.currentCleanup=null,this.connectorId=t,this.localVersion=n,this.remoteVersion=r,this.conflicts=e.map(e=>({conflict:e,choice:e.type===`unchanged`?`remote`:`pending`})),this.totalConflicts=e.filter(e=>e.type===`conflict`).length}resetForReResolution(){this.currentIndex=0}async resolve(){return this.totalConflicts===0?{cancelled:!1,states:this.conflicts}:(this.moveToNextConflict(),new Promise(e=>{let t=st({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),this.render();let n=n=>{let r=n.toString();if(r===``){this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});return}if(r===`\x1B`&&n.length===1){this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});return}if(r.startsWith(`\x1B[`)){switch(r.slice(2)){case`D`:this.moveToPrevConflict(),this.render();break;case`C`:this.moveToNextConflict(),this.render();break}return}switch(r){case`r`:case`R`:this.setCurrentChoice(`remote`),this.advanceAfterChoice(t);break;case`l`:case`L`:this.setCurrentChoice(`local`),this.advanceAfterChoice(t);break;case`b`:case`B`:this.setCurrentChoice(`both`),this.advanceAfterChoice(t);break;case`\r`:case`
156
+ `)}#t=e=>!e.includes(`/`)&&!e.includes(`\\`)&&!e.endsWith(`.yaml`)&&!e.endsWith(`.yml`)?e.includes(`@`)?e.split(`@`).length===2:!0:!1;#n=e=>e.includes(`@`)?e:`${e}@latest`;async#r(e,n,i,a,o){let s=q(`Getting connector ${t(e)} from registry...`).start();try{let r=Buffer.from(i).toString(`base64`),c=a?`?format=${a}`:``,l=o?`${c?`&`:`?`}owner=${encodeURIComponent(o)}`:``,u=await fetch(`${n}/registry/connectors/${e}${c}${l}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});if(s.stop(),u.status===409){o&&(await b(u,`Failed to get connector ${t(e)} from the registry`),process.exit(1));let i=await Rr(e,(await u.json()).availableOwners??[]),a=`${n}/registry/connectors/${e}${c}${c?`&`:`?`}owner=${encodeURIComponent(i)}`;s.text=`Getting connector ${t(e)} from registry...`,s.start();let l=await fetch(a,{method:`GET`,headers:{Authorization:`Basic ${r}`}});return s.stop(),l.ok||(await b(l,`Failed to get connector ${t(e)} from the registry`),process.exit(1)),await l.text()}return u.ok||(await b(u,`Failed to get connector ${t(e)} from the registry`),process.exit(1)),await u.text()}catch(i){s.stop(),y.error(`Failed to get connector ${t(e)} from the registry: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}}async#i(e,n,i,a){let o=q(`Getting connector from account ${t(e)}...`).start();try{let r=Buffer.from(i).toString(`base64`),s=a?`?format=${a}`:``,c=await fetch(`${n}/accounts/${e}/connector${s}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});return o.stop(),c.ok||(await b(c,`Failed to get connector from account ${t(e)}`),process.exit(1)),await c.text()}catch(i){o.stop(),y.error(`Failed to get connector from account ${t(e)}: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}}};const Vr=`http://localhost:4000`;var Hr=class{async execute({environment:e}={}){let n=e?.toLowerCase()??`production`;try{qe(`${T.inverse(` Initialize profile `)}`);let e=await Qe({message:`Profile label`,validate:e=>{if(!e||e.trim().length===0)return`The profile label is required`;if(e.includes(` `))return`The profile label cannot contain spaces`}});if(Je(e))return Ge(`Configuration profile initialization cancelled`),process.exit(0);if(Mr(e)){let n=await Ke({message:`Configuration profile with name ${t(e)} already exists. Do you want to overwrite it?`});if(Je(n)||!n)return Ge(`Configuration profile initialization cancelled`),process.exit(0)}let r;if(n===`production`)r=`https://api.stackone.com`;else if(n===`staging`)r=`https://api.stackone-dev.com`;else{let e=await Qe({message:`API URL`,placeholder:Vr,initialValue:Vr,validate:e=>{if(!e||e.trim().length===0)return`API URL is required`;try{new URL(e)}catch{return`Please enter a valid URL`}}});if(Je(e))return Ge(`Configuration profile initialization cancelled`),process.exit(0);r=e}let i=await Xe({message:`API Key`,validate:e=>{if(!e||e.trim().length===0)return`API Key is required`}});if(Je(i))return Ge(`Configuration profile initialization cancelled`),process.exit(0);Nr(e,{label:e,environment:n,apiUrl:r,apiKey:i}),Ye(`${T.green(`✔`)} Configuration profile ${t(e)} initialized successfully!`),process.exit(0)}catch(e){e?.isTtyError?y.error(`Prompt couldn't be rendered in the current environment`):y.error(`Failed to initialize configuration profile: ${e}`),process.exit(1)}}};const $={pending:`○`,acceptRemote:`●`,acceptLocal:`◐`,acceptBoth:`◑`,current:`◉`,arrow:`→`,check:`✓`,cross:`✗`,warning:`⚠`};var Ur=class{constructor(e,t,n,r){this.conflicts=[],this.currentIndex=0,this.totalConflicts=0,this.currentCleanup=null,this.connectorId=t,this.localVersion=n,this.remoteVersion=r,this.conflicts=e.map(e=>({conflict:e,choice:e.type===`unchanged`?`remote`:`pending`})),this.totalConflicts=e.filter(e=>e.type===`conflict`).length}resetForReResolution(){this.currentIndex=0}async resolve(){return this.totalConflicts===0?{cancelled:!1,states:this.conflicts}:(this.moveToNextConflict(),new Promise(e=>{let t=st({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),this.render();let n=n=>{let r=n.toString();if(r===``){this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});return}if(r===`\x1B`&&n.length===1){this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});return}if(r.startsWith(`\x1B[`)){switch(r.slice(2)){case`D`:this.moveToPrevConflict(),this.render();break;case`C`:this.moveToNextConflict(),this.render();break}return}switch(r){case`r`:case`R`:this.setCurrentChoice(`remote`),this.advanceAfterChoice(t);break;case`l`:case`L`:this.setCurrentChoice(`local`),this.advanceAfterChoice(t);break;case`b`:case`B`:this.setCurrentChoice(`both`),this.advanceAfterChoice(t);break;case`\r`:case`
157
157
  `:this.allResolved()?(this.cleanup(t),e({cancelled:!1,states:this.conflicts})):(this.moveToNextUnresolved(),this.render());break;case`q`:case`Q`:this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});break;case`a`:case`A`:this.acceptAllRemaining(`remote`),this.render();break;case`u`:case`U`:this.setCurrentChoice(`pending`),this.render();break}};process.stdin.on(`data`,n),this.currentCleanup=()=>{process.stdin.removeListener(`data`,n),process.stdin.isTTY&&process.stdin.setRawMode(!1),t.close()}}))}cleanup(e){this.currentCleanup?(this.currentCleanup(),this.currentCleanup=null):(process.stdin.isTTY&&process.stdin.setRawMode(!1),e.close())}advanceAfterChoice(e){this.allResolved()||this.moveToNextUnresolved(),this.render()}render(){v();let e=process.stdout.columns||80;this.renderHeader(e),this.renderProgressBar(e),this.renderCurrentConflict(e),this.renderControls(e)}renderHeader(e){let t=this.connectorId,n=`${this.localVersion} ${$.arrow} ${this.remoteVersion}`,r=Math.max(0,e-17),i=Math.floor(r/2),a=r-i,o=` `.repeat(i)+`CONFLICT RESOLVER`+` `.repeat(a);y.log(``),y.log(T.bgBlue.white.bold(o)),y.log(T.gray(this.centerText(t,e))),y.log(T.gray(this.centerText(n,e))),y.log(``)}renderProgressBar(e){let t=this.conflicts.filter(e=>e.conflict.type===`conflict`),n=this.getCurrentConflictIndex(),r=t.map((e,t)=>{let r=t===n,i,a;switch(e.choice){case`remote`:i=r?$.current:$.acceptRemote,a=T.green;break;case`local`:i=r?$.current:$.acceptLocal,a=T.yellow;break;case`both`:i=r?$.current:$.acceptBoth,a=T.cyan;break;default:i=r?$.current:$.pending,a=r?T.white:T.gray}return a(i)}),i=t.filter(e=>e.choice!==`pending`).length,a=` Conflict ${n+1} of ${this.totalConflicts} • ${i}/${this.totalConflicts} resolved `;y.log(T.gray(this.centerText(a,e))),y.log(this.centerText(r.join(` `),e)),y.log(``)}renderCurrentConflict(e){let t=this.conflicts[this.currentIndex];if(!t||t.conflict.type!==`conflict`)return;let n=t.conflict;if(y.log(T.gray(`_`.repeat(e))),y.log(`
158
158
 
159
159
  `),n.local){let e=t.choice===`local`||t.choice===`both`?T.yellow.bold(`${$.check} LOCAL (keeping)`):T.red.bold(`${$.cross} LOCAL (removing)`),r=n.local.split(`
@@ -167,9 +167,9 @@ Available skills
167
167
  `),s=r.length>20?`\n${T.gray(`... and ${r.length-20} more lines`)}`:``;y.log(`${e}\n\n${o}${s}`)}y.log(`
168
168
 
169
169
  `),y.log(T.gray(`_`.repeat(e))),y.log(``)}renderControls(e){let t=[T.green(`[R] Accept Remote`),T.yellow(`[L] Keep Local`),T.cyan(`[B] Keep Both`),T.gray(`[U] Undo`)],n=[T.gray(`[←/→] Navigate`),T.gray(`[A] Accept all remaining`)],r=this.allResolved()?[T.green.bold(`[Enter] Apply Changes`),T.gray(`[Esc] Cancel`)]:[T.gray(`[Enter] Next Unresolved`),T.gray(`[Esc] Cancel`)];y.log(this.centerText(t.join(` `),e)),y.log(``),y.log(this.centerText(n.join(` `),e)),y.log(``),y.log(this.centerText(r.join(` `),e)),this.allResolved()&&(y.log(``),y.log(T.green.bold(this.centerText(`✓ All conflicts resolved!`,e))))}renderFinalSummary(){v();let e=this.conflicts.filter(e=>e.conflict.type===`conflict`),t=0,n=0,r=0;for(let i of e)switch(i.choice){case`remote`:t++;break;case`local`:n++;break;case`both`:r++;break}let i=[T.green.bold(`Conflict resolution complete`),``,`${T.bold(this.totalConflicts)} conflicts resolved:`,``,`${T.green($.acceptRemote)} Accepted remote: ${t}`,`${T.yellow($.acceptLocal)} Kept local: ${n}`,`${T.cyan($.acceptBoth)} Kept both: ${r}`];y.box(i.join(`
170
- `))}renderCancelled(){v(),y.log(T.yellow(`Conflict resolution cancelled`)),y.log(``),y.log(`No changes were made to your local connector file.`)}getCurrentConflictIndex(){let e=-1;for(let t=0;t<=this.currentIndex&&t<this.conflicts.length;t++)this.conflicts[t].conflict.type===`conflict`&&e++;return e}moveToNextConflict(){for(let e=this.currentIndex+1;e<this.conflicts.length;e++)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}for(let e=0;e<this.currentIndex;e++)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}}moveToPrevConflict(){for(let e=this.currentIndex-1;e>=0;e--)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}for(let e=this.conflicts.length-1;e>this.currentIndex;e--)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}}moveToNextUnresolved(){for(let e=this.currentIndex+1;e<this.conflicts.length;e++)if(this.conflicts[e].conflict.type===`conflict`&&this.conflicts[e].choice===`pending`){this.currentIndex=e;return}for(let e=0;e<this.currentIndex;e++)if(this.conflicts[e].conflict.type===`conflict`&&this.conflicts[e].choice===`pending`){this.currentIndex=e;return}}setCurrentChoice(e){this.conflicts[this.currentIndex]?.conflict.type===`conflict`&&(this.conflicts[this.currentIndex].choice=e)}allResolved(){return this.conflicts.filter(e=>e.conflict.type===`conflict`).every(e=>e.choice!==`pending`)}acceptAllRemaining(e){for(let t of this.conflicts)t.conflict.type===`conflict`&&t.choice===`pending`&&(t.choice=e)}centerText(e,t){let n=this.stripAnsi(e),r=Math.max(0,Math.floor((t-n.length)/2));return` `.repeat(r)+e}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*m/g,``)}getResolvedContent(){let e=[];for(let t of this.conflicts)if(t.conflict.type===`unchanged`)e.push(t.conflict.content||``);else if(t.conflict.type===`conflict`)switch(t.choice){case`remote`:t.conflict.remote&&e.push(t.conflict.remote);break;case`local`:t.conflict.local&&e.push(t.conflict.local);break;case`both`:t.conflict.local&&e.push(t.conflict.local),t.conflict.remote&&e.push(t.conflict.remote);break;case`pending`:t.conflict.remote&&e.push(t.conflict.remote);break}return e.join(``)}};const Ur=`https://api.stackone.com`;var Wr=class{async execute({profile:e,connector:n,outputPath:r,apiUrl:i,apiKey:a,owner:o}={}){if(J(n)&&(y.error(`Connector identifier is required`),y.log(`Please provide a connector identifier using the ${t(`--connector`)} option in the format: ${t(`provider_key@version`)} or ${t(`provider_key`)}`),y.log(`If no version is specified, the latest version will be pulled.`),process.exit(1)),!e&&!a&&(y.error(`Profile or API key is required`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),e&&a&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&i&&y.warn(`Specifying ${t(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!jr(e)){y.error(`Configuration profile ${t(e)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let n=Nr();n.length>0&&(y.info(`Available configuration profiles:`),n.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let s=e?Ar(e):{apiUrl:i??Ur,apiKey:a};s?.apiKey||(y.error(`API key is missing`),y.log(`Please provide a valid API key in the profile or via the ${t(`--api-key`)} option.`),process.exit(1));let c=s.apiUrl??Ur,[l,u]=n.split(`@`),d=await this.#f(l,c,s.apiKey,u??`latest`,o),f=this.#e(d),p=f.version??`unknown`,m=this.#t(r,f.key,p),h=this.#r(m),g=h===null,_=d;if(!g){let e=this.#i(h,m);e&&(y.warn(e.message),e.errors.length>0&&x(e.errors,!1),y.log(``));let t=e?void 0:this.#e(h);if(this.#o(h,d)){this.#a(h,d,m);let e=t?.version??`unknown`,r=await this.#s(h,d,n,e,p);r.action===`cancel`&&(Ge(`Pull cancelled`),process.exit(0)),r.action===`keep-local`&&(y.log(``),y.info(`Keeping local version. No changes made.`),process.exit(0)),r.action===`interactive-cancel`&&process.exit(0),r.action===`interactive`&&(_=r.resolvedContent)}else y.info(`No changes detected in connector configuration.`),process.exit(0)}let ee=at(_).connector,v=ee?.key??f.key,b=ee?.version??p,S=this.#t(r,v,b),C=S;if(S!==m){let e=await this.#n(S);y.log(``),e!==void 0&&(C=e)}await this.#d(C,_),g?y.success(`Connector ${t(v)}@${t(b)} pulled successfully (new connector)`):y.success(`Connector ${t(v)}@${t(b)} updated successfully`);let te=v===f.key?t(v):`${t(f.key)} ${T.whiteBright(`→`)} ${t(v)}`,w=b===p?t(b):`${t(p)} ${T.whiteBright(`→`)} ${t(b)}`,E=C===m?t(C):`${t(m)}\n ${T.whiteBright(`→`)} ${t(C)}`;y.log(`\n${T.blue.inverse(` CONNECTOR DETAILS `)}\n`),y.log(` Provider: ${te}`),y.log(` Version: ${w}`),y.log(` Output file: ${E}`),process.exit(0)}#e(e){let n=at(e),r=n?.errors??[];if(n.success)return n.connector;y.error(`Connector pulled from the registry is not valid`),y.log(`Please make sure you are using the latest version of the StackOne CLI by running ${t(`stackone update`)}`),r.length>0&&x(r,!0),process.exit(1)}#t(e,n,r){let i=`${n}_v${r.replaceAll(`.`,`-`)}.s1.yaml`;return e?(G.existsSync(e)&&(G.statSync(e).isDirectory()||(y.error(`Output path ${t(e)} is not a directory`),y.log(`Please provide a valid directory path to store connectors or use the default path.`),process.exit(1))),Me.resolve(e,n,i)):Me.resolve(process.cwd(),`connectors`,n,i)}async#n(e){if(!G.existsSync(e))return;let n=Me.basename(e),r=Me.dirname(e);y.warn(`File ${t(n)} already exists at ${t(r)}`);let i=await Ze({message:`How would you like to proceed?`,options:[{value:`override`,label:`Override existing file`,hint:`Replace the existing file with the new content`},{value:`rename`,label:`Save with a different name`,hint:`Provide a new filename for the connector`},{value:`cancel`,label:`Cancel`,hint:`Abort the pull operation`}]});if((Je(i)||i===`cancel`)&&(Ge(`Operation cancelled. No local changes were made.`),process.exit(0)),i===`override`)return;let a=await Qe({message:`Enter the new filename:`,placeholder:n,validate:e=>{if(!e||e.trim()===``)return`Filename cannot be empty`;if(!e.endsWith(`.s1.yaml`))return`Filename must end with .s1.yaml`;let t=Me.join(r,e.trim());if(G.existsSync(t))return`File ${e} already exists`}});return Je(a)&&(Ge(`Operation cancelled. No local changes were made.`),process.exit(0)),Me.join(r,a.trim())}#r(e){if(!G.existsSync(e))return null;try{return G.readFileSync(e,`utf-8`)}catch{return null}}#i(e,n){try{let r=at(e);if(!r.success){let e=r.errors??[];return{message:`Local connector ${t(Me.basename(n))} has validation errors:`,errors:e}}}catch(e){return{message:`Local connector ${t(Me.basename(n))} could not be validated: ${e.message}`,errors:[]}}return null}#a(e,t,n){let r=ot(e,t);if(!r.some(e=>e.added||e.removed)){y.info(`No changes detected in connector configuration.`);return}y.log(`${T.blue.inverse(` CHANGES `)}\n`),y.log(T.gray(`--- local: ${n}`)),y.log(T.gray(`+++ remote: StackOne Registry`)),y.log(``);let i=0,a=0;for(let e of r){let t=e.value.split(`
171
- `).filter(e=>e!==``);if(e.added){i+=t.length;for(let e of t)y.log(T.green(`+ ${e}`))}else if(e.removed){a+=t.length;for(let e of t)y.log(T.red(`- ${e}`))}else if(t.length<=6)for(let e of t)y.log(T.gray(` ${e}`));else{for(let e=0;e<3;e++)y.log(T.gray(` ${t[e]}`));y.log(T.gray(` ... (${t.length-6} unchanged lines)`));for(let e=t.length-3;e<t.length;e++)y.log(T.gray(` ${t[e]}`))}}y.log(``),y.log(T.gray(`Summary: ${T.green(`+${i}`)} additions, ${T.red(`-${a}`)} deletions`))}#o(e,t){return ot(e,t).some(e=>e.added||e.removed)}async#s(e,t,n,r,i){y.log(``);let a=await Ze({message:`How would you like to resolve the differences?`,options:[{value:`override`,label:`Override local with remote`,hint:`Replace your local file with the StackOne version`},{value:`keep-local`,label:`Keep local version`,hint:`Cancel the pull and keep your current file`},{value:`interactive`,label:`Resolve conflicts interactively`,hint:`Choose which changes to accept one by one`},{value:`cancel`,label:`Cancel`,hint:`Abort the pull operation`}]});if(Je(a))return{action:`cancel`};if(a===`override`)return{action:`override`};if(a===`keep-local`)return{action:`keep-local`};if(a===`interactive`){let a=await this.#c(e,t,n,r,i);return a===null?{action:`interactive-cancel`}:{action:`interactive`,resolvedContent:a}}return{action:`cancel`}}async#c(e,t,n,r,i){let a=ot(e,t),o=this.#u(a);if(o.length===0)return y.info(`No conflicts to resolve.`),t;let s=new Hr(o,n,r,i);for(;;){if((await s.resolve()).cancelled)return null;let e=s.getResolvedContent(),t=at(e);if(t.success)return s.renderFinalSummary(),e;let n=await this.#l(t.errors);if(n===`cancel`)return v(),y.info(`Operation cancelled. No changes were made to the local connector.`),null;if(n===`save`)return v(),y.warn(`The connector was saved but it is invalid`),e;s.resetForReResolution()}}async#l(e){let{createInterface:t}=await import(`readline`);return new Promise(n=>{v();let r=(e||[{message:`Unknown validation error`}]).map(e=>` • ${e.message}`).join(`
172
- `);y.box({title:`⚠️ Validation Failed`,message:`The resolved connector configuration is invalid:\n\n${r}`,style:{borderColor:`yellow`,padding:1}}),y.log(``),y.log(T.bold(` Choose an action:`)),y.log(``),y.log(T.cyan(` [B]`)+` ← Go back to conflict resolution`),y.log(T.dim(` Modify your choices to fix the validation errors`)),y.log(``),y.log(T.yellow(` [S]`)+` 💾 Save anyway`),y.log(T.dim(` Save the invalid configuration (not recommended)`)),y.log(``),y.log(T.red(` [C]`)+` ✖ Cancel`),y.log(T.dim(` Discard all changes`)),y.log(``);let i=t({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();let a=e=>{let t=e.toString().toLowerCase(),r=()=>{process.stdin.removeListener(`data`,a),process.stdin.isTTY&&process.stdin.setRawMode(!1),i.close()};if(t===``||t===`\x1B`){r(),n(`cancel`);return}switch(t){case`b`:r(),n(`back`);break;case`s`:r(),n(`save`);break;case`c`:case`q`:r(),n(`cancel`);break}};process.stdin.on(`data`,a)})}#u(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(!r.added&&!r.removed)t.push({type:`unchanged`,content:r.value}),n++;else if(r.removed){let i=e[n+1];i?.added?(t.push({type:`conflict`,local:r.value,remote:i.value}),n+=2):(t.push({type:`conflict`,local:r.value,remote:void 0}),n++)}else r.added&&t.push({type:`conflict`,local:void 0,remote:r.value}),n++}return t}async#d(e,n){let r=Me.dirname(e);G.existsSync(r)||G.mkdirSync(r,{recursive:!0});try{G.writeFileSync(e,n,`utf-8`)}catch(n){y.error(`Failed to write connector to file ${t(e)}: ${n.message}`),process.exit(1)}}async#f(e,n,i,a,o){let s=q(`Pulling connector ${t(e)}@${t(a)} from registry...`).start();try{let r=Buffer.from(i).toString(`base64`),c=`${n}/registry/connectors/${e}@${a}${o?`?owner=${encodeURIComponent(o)}`:``}`,l=await fetch(c,{method:`GET`,headers:{Authorization:`Basic ${r}`}});if(s.stop(),l.status===409){o&&(await this.#p(l,e,a),process.exit(1));let i=(await l.json()).availableOwners??[],c=await Lr(`${e}@${a}`,i);s.text=`Pulling connector ${t(e)}@${t(a)} from registry...`,s.start();let u=`${n}/registry/connectors/${e}@${a}`,d=await fetch(`${u}?owner=${encodeURIComponent(c)}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});return s.stop(),d.ok||(await this.#p(d,e,a),process.exit(1)),await d.text()}return l.ok||(await this.#p(l,e,a),process.exit(1)),await l.text()}catch(i){s.stop(),y.error(`Failed to pull connector ${t(e)}@${t(a)} from the registry: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid.`),process.exit(1)}}async#p(e,n,r){switch(e.status){case 401:case 403:y.error(`Access denied`),y.log(`Please ensure that your API key is valid and has the ${t(`connectors:read`)} scope required to pull connectors.`);break;case 404:y.error(`Connector ${t(n)}@${t(r)} was not found in the registry`),await this.#m(n);break;case 429:y.error(`Rate limit exceeded`),y.log(`Too many requests. Please wait a moment before trying again.`);break;default:await b(e,`Failed to pull connector ${t(n)}`)}}async#m(e){y.info(`To see available versions, check the connector documentation or contact support.`)}};const Gr=`https://api.stackone.com`;var Kr=class{async execute({profile:e,fileOrDir:n,apiUrl:r,apiKey:i,force:a}={}){if(!e&&!i&&(y.error(`Profile or API key is required`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),e&&i&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&r&&y.warn(`Specifying ${t(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!jr(e)){y.error(`Configuration profile ${t(e)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let n=Nr();n.length>0&&(y.info(`Available configuration profiles:`),n.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let o=e?Ar(e):{apiUrl:r??Gr,apiKey:i};o?.apiKey||(y.error(`API key is missing`),y.log(`Please provide a valid API key in the profile or via the ${t(`--api-key`)} option.`),process.exit(1)),n||(y.error(`File or directory is required.`),process.exit(1));try{K(n)}catch{y.error(`File or directory not found: ${T.red(n)}`),process.exit(1)}let s=K(n),c=o.apiUrl??Gr;if(s.isDirectory()){let e=$r(n),t=0;e.length===0?(y.error(`No .s1.yaml connector files found in the directory: ${n}.`),process.exit(1)):(y.start(`Found ${e.length} connector(s) file(s). Pushing to registry...`),y.log(``));for(let n of e)await this.uploadFile(n,c,o.apiKey,a)&&t++;t===0?y.error(`Error while pushing connectors: no files were uploaded`):(y.log(``),y.info(`Upload completed: ${T.green(t)} of ${T.blue(e.length)} file(s) uploaded successfully.`)),process.exit(t>0?0:1)}else n.endsWith(`.s1.yaml`)||(y.error(`Only ${t(`.s1.yaml`)} files are supported for upload`),process.exit(1));let l=await this.uploadFile(n,c,o.apiKey,a);process.exit(l?0:1)}async uploadFile(e,n,i,a){let o=q(`📤 Pushing connector in ${Ne(e)}...`).start();try{let r=Qr(e);if(!r)return!1;let s=Ne(e),c=new FormData,l=new Blob([r],{type:`application/x-yaml`});c.append(`file`,l,s),a&&c.append(`force`,`true`);let u=Buffer.from(i).toString(`base64`),d=await fetch(`${n}/registry/connectors`,{method:`POST`,headers:{Authorization:`Basic ${u}`},body:c});if(o.stop(),!d.ok)return d.status===409||d.status===422?await this.handleVersionConflict(d,e,n,i,a):(await b(d,`Failed to push connector in ${t(s)} to the registry`),!1);let f=await d.json();return y.success(`Successfully uploaded ${t(s)} with connector ${t(f.provider)}@${t(f.version)}`),!0}catch(i){return o.stop(),y.error(`Failed to upload file ${t(e)}: ${i}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),!1}}async handleVersionConflict(e,n,r,i,a){let o=qr(e.status,a);o&&y.warn(o);let s=await e.text(),c;try{c=JSON.parse(s)}catch{}let l=dt.valid(c?.latestVersion);if(!l)return await b(new Response(s,{status:e.status,statusText:e.statusText}),`Failed to push connector in ${t(Ne(n))} to the registry`),!1;let u=ke(n,`utf-8`),d=Jr(u),f=d?`${t(d)}`:``,p=e.status===409?`Version ${f} already exists in the registry. Latest version: ${t(l)}`:`Version ${f} is lower than the latest version in the registry. Latest version: ${t(l)}`;y.error(p);let m=dt.inc(l,`patch`)??l,h=dt.inc(l,`minor`)??l,g=dt.inc(l,`major`)??l,_=await Ze({message:`How would you like to proceed?`,options:[{value:m,label:`Bump patch version (${m})`},{value:h,label:`Bump minor version (${h})`},{value:g,label:`Bump major version (${g})`},{value:`cancel`,label:`Cancel push`}]});return Je(_)||_===`cancel`?(Ge(`Push cancelled`),!1):(je(n,Yr(u,_),`utf-8`),y.info(`Updated version to ${t(_)} in ${Ne(n)}`),this.uploadFile(n,r,i,a))}};const qr=(e,n)=>!n||e!==409?null:`${t(`--force`)} was ignored because Immutable Versioning is enabled for this project, so a published connector version cannot be overwritten. Push a new version, or turn Immutable Versioning off in the project settings.`,Jr=e=>e.match(/^\s*version: (\S+)/m)?.[1],Yr=(e,t)=>e.replace(/^(\s*version: )\S+/m,`$1${t}`),Xr=e=>{try{let t=rt(e);return t.changelog?.summary?.trim()?null:`has no changelog entry for version ${t.version}`}catch{return null}},Zr=()=>{y.log(`Every published version must record what changed. Add an ${t(`info.changelog`)} block:`),y.log(``),y.log(T.gray(` info:`)),y.log(T.gray(` changelog:`)),y.log(T.gray(` summary: What changed in this version.`)),y.log(T.gray(` labels: [new-actions] # optional, one of: ${ct.join(`, `)}`)),y.log(``)},Qr=e=>{let t=nt(e),r=at(t),i=r?.errors??[];if(r.success){let r=Xr(t);if(r){y.error(`Connector in ${n(e)} ${r}`),Zr();return}return t}else i.length>0?(y.error(`Connector in ${n(e)} is not valid`),x(i,!0)):y.error(`Connector in ${n(e)} is not valid. Please check the file for errors.`)},$r=e=>{let t=[],n=Ae(e,{withFileTypes:!0});for(let r of n){let n=Fe(e,r.name);r.isDirectory()?t.push(...$r(n)):r.name.endsWith(`.s1.yaml`)&&t.push(n)}return t},ei=(e,t)=>{if(!e)return{ok:!1,reason:`Action has no pagination config, so there is no page size to override.`};switch(e.type){case`page`:return e.iterator.pageSizeKey?{ok:!0,pagination:{...e,iterator:{...e.iterator,defaultPageSize:t}}}:{ok:!1,reason:`Pagination declares no pageSizeKey, so the provider's page size cannot be set. Add dataSync.pagination.iterator.pageSizeKey, or use --params if the provider takes its page size as a regular action input.`};case`offset`:return{ok:!0,pagination:{...e,iterator:{...e.iterator,defaultLimit:t}}};case`cursor`:return{ok:!1,reason:`Cursor pagination has no page size key to override — the strategy only ever sets the cursor. If the provider takes a page size (GraphQL "first", for example), it is an ordinary action input: pass it with --params, which the paginator preserves across pages.`}}},ti=e=>({path:e.path,query:e.queryParams,headers:e.header,body:e.body}),ni=e=>({pathParams:e.path??{},queryParams:e.query??{},headers:e.headers??{},body:e.body??{}}),ri=(e,t)=>{switch(e.type){case`time_filter`:return{kind:`timestamp`,value:t};case`delta_token`:return{kind:`cursor`,value:t}}},ii=(e,t,n)=>{let{in:r,key:i}=e.iterator;return ai(n[r])[i]===t.value},ai=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:{},oi=2e3;var si=class extends Error{constructor(e){super(`Action failed on page ${e.iteration}: ${e.statusCode??`unknown`} ${e.providerMessage??`no response`}`.trim()),this.name=`SyncPageError`,this.iteration=e.iteration,this.statusCode=e.statusCode,this.providerMessage=e.providerMessage,this.providerData=e.providerData,this.inputs=e.inputs,this.pagesCompleted=e.pagesCompleted,this.recordsCollected=e.recordsCollected}};const ci=async({dataSyncConfig:e,baseInputs:t,checkpointIn:n,callAction:r,maxPages:i,runStartTime:a,onPage:o})=>{let s=e.incremental?$e(e.incremental):null,c=s?s.applyToInputs({baseInputs:t,checkpoint:n}):t,l=e.incremental&&n?ii(e.incremental,n,c):null,u=e.pagination?et(e.pagination,{baseInputs:c}):null,d=Math.min(i,oi),f=[],p=[],m=[],h=null,g=0,_=null,ee=e=>({items:f,pages:p,pagesRetrieved:g,stoppedBy:e,extractedCheckpoints:m,checkpointOut:e===`exhausted`&&s?s.finalizeCheckpoint({runStartTime:a,extractedCheckpoints:m}):null,checkpointApplied:l});for(;;){if(g>=d)return ee(`maxIterations`);let t=h??u?.computeNextInputs({previousResponse:void 0,currentIteration:g})??c,n=await r(t);if(g++,n.response?.successful!==!0)throw new si({iteration:g,statusCode:n.response?.statusCode,providerMessage:n.response?.message,providerData:n.response?.data,inputs:t,pagesCompleted:g-1,recordsCollected:f.length});let i=tt(n,e),a=Ue(i),l=u?u.isExhausted(n,g):!0,v=s?.extractFromPage({block:n,items:i,isFinalPage:l})??null,y={iteration:g,inputs:t,itemCount:i.length,statusCode:n.response?.statusCode,exhausted:l,extractedCheckpoint:v};if(p.push(y),o?.(y),v){let e=m.findIndex(e=>e.kind===v.kind&&e.value===v.value);e!==-1&&m.splice(e,1),m.push(v)}if(_!==null&&a===_)return ee(`duplicatePage`);if(f.push(...i),_=a,l)return ee(`exhausted`);h=u?.computeNextInputs({previousResponse:n,currentIteration:g})}},li=(e,t)=>{let n=e.dataSync;return n?n.allowed===!0?t===`incremental`&&!n.incremental?{ok:!1,reason:`Action does not support incremental syncs: no dataSync.incremental block`}:{ok:!0,dataSyncConfig:n}:{ok:!1,reason:`Action data sync is not enabled: dataSync.allowed is false`}:{ok:!1,reason:`Action does not support data sync: no dataSync block`}},ui=(e,t)=>Math.min(t??e.maxPages??oi,oi),di=async({dataSyncConfig:e,mode:t,checkpointValue:n,baseInputs:r,callAction:i,maxPages:a,now:o,onPage:s})=>{let c=async(t,n)=>({mode:t,checkpointIn:n,...await ci({dataSyncConfig:e,baseInputs:r,checkpointIn:n,callAction:i,maxPages:a,runStartTime:o(),onPage:s&&(e=>s(e,t))})});if(t===`full`)return{phases:[await c(`full`,null)]};if(n!==void 0&&e.incremental)return{phases:[await c(`incremental`,ri(e.incremental,n))]};let l=await c(`full`,null);return l.checkpointOut?{phases:[l,await c(`incremental`,l.checkpointOut)]}:{phases:[l],skipped:`no checkpoint produced by the full phase`}},fi=({actionId:e,connector:t,dataSyncConfig:n,result:r,warnings:i,includePages:a})=>{let o=r.phases.find(e=>e.items.length>0)?.items[0];return{actionId:e,connector:t,dataSyncConfigFingerprint:lt(n),phases:r.phases.map(e=>({mode:e.mode,pagesRetrieved:e.pagesRetrieved,records:e.items.length,stoppedBy:e.stoppedBy,checkpointIn:e.checkpointIn,checkpointOut:e.checkpointOut,checkpointApplied:e.checkpointApplied,...a?{pages:e.pages.map(e=>({iteration:e.iteration,inputs:e.inputs,itemCount:e.itemCount,statusCode:e.statusCode,exhausted:e.exhausted}))}:{}})),...r.skipped?{incrementalPhaseSkipped:r.skipped}:{},...o?{sampleRecord:o}:{},warnings:i}},pi=(e,t)=>{let n=[],{incremental:r}=t;for(let r of e.phases)n.push(...mi(r,t));let i=e.phases.some(e=>e.stoppedBy===`exhausted`&&e.checkpointOut===null);r?.type===`delta_token`&&i&&n.push(`The run reached the end of the data but produced no delta token, so production would abandon every following incremental fire ("no checkpoint to resume from"). Check dataSync.incremental.response.path (${r.response.path})${r.response.onlyOnFinalPage?` — it is only read on the final page`:``}.`);let a=e.phases.find(e=>e.mode===`full`),o=e.phases.find(e=>e.mode===`incremental`);return a&&o&&o.checkpointApplied===!0&&o.items.length>=a.items.length&&n.push(`The incremental phase did not narrow the result set (${a.items.length} records full vs ${o.items.length} incremental). Verify the provider honours ${gi(t)}; every sync will refetch the whole dataset if it does not.`),n},mi=(e,t)=>{let n=[],{incremental:r}=t;return e.checkpointApplied===!1&&n.push(`The ${e.mode} phase checkpoint (kind "${e.checkpointIn?.kind}") was ignored by the ${r?.type} strategy, so this run fetched an unfiltered dataset. It reports success but proves nothing about incremental behaviour.`),e.stoppedBy===`maxIterations`&&n.push(`The ${e.mode} phase was truncated at the ${e.pagesRetrieved}-page cap before exhausting the provider, so no checkpoint was produced. Production withholds a truncated run's checkpoint for the same reason.`),e.stoppedBy===`duplicatePage`&&n.push(`The ${e.mode} phase stopped after two identical consecutive pages, which means the iterator is not reaching the provider. A declared input alone is not enough — the request step must forward it via args (value: $.inputs.${t.pagination?hi(t):`cursor`}). Connector validation cannot catch this.`),r?.type===`time_filter`&&r.response?.updatedAtPath&&e.items.length>0&&e.extractedCheckpoints.length===0&&n.push(`dataSync.incremental.response.updatedAtPath (${r.response.updatedAtPath}) resolved on no record in the ${e.mode} phase, so the watermark fell back to this machine's clock minus ${r.safetyBufferSeconds??60}s. Records changed during the run can be missed.`),n},hi=e=>{let t=e.pagination;if(!t)return`cursor`;switch(t.type){case`cursor`:return t.iterator.key;case`offset`:return t.iterator.offsetKey;case`page`:return t.iterator.pageKey}},gi=e=>{let{incremental:t}=e;return t?`${t.iterator.key} in ${t.iterator.in}`:`the incremental iterator`},_i=X.object({provider_key:X.string().optional(),provider_version:X.string().optional(),auth_config_key:X.string(),environment:X.string().default(`production`),organization_id:X.string().default(`cli-organization-id`),account_id:X.string().default(`cli-account-secure-id`),project_id:X.string().default(`cli-project-secure-id`),credentials:X.record(X.string(),X.any()).default({})}),vi=X.record(X.string(),X.any()),yi=X.object({path:X.record(X.string(),X.any()).default({}),queryParams:X.record(X.string(),X.any()).default({}),header:X.record(X.string(),X.any()).default({}),body:X.record(X.string(),X.any()).default({})}),bi=`https://api.stackone.com`;var xi=class{async execute({connector:e,action:n,actionId:r,account:i,accountId:a,params:s,credentials:c,profile:l,outputFile:u,debug:d,apiUrl:f,apiKey:p,owner:m,syncFull:h,syncIncremental:g,syncMaxPages:_,syncPageSize:ee}={}){if(!l&&!p&&a&&(y.error(`Profile or API key is required when providing an account ID`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),l&&p&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),l&&f&&y.warn(`Specifying --api-url with a profile won't have any effect. Using API url from profile.`),l&&!jr(l)){y.error(`Configuration profile ${t(l)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let e=Nr();e.length>0&&(y.info(`Available configuration profiles:`),e.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let v=l?Ar(l):{apiUrl:f??bi,apiKey:p};J(i)&&J(a)&&(y.error(`A valid account or account ID is required to run an action`),process.exit(1));let b;if(Y(e))if(this.#s(e)){!l&&!p&&(y.error(`Profile or API key is required when using a connector identifier`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.`),process.exit(1));let n=this.#c(e);b=await this.#l(n,v?.apiUrl??bi,v?.apiKey,m)}else b=this.#n(e);else Y(a)&&(b=await this.#u(a,v?.apiUrl??bi,v?.apiKey));let x=Y(n)?this.#a(n,e):b;J(x)&&(y.error(`A valid connector is required to run an action.`),process.exit(1));let S=Y(x?.actions)?Object.keys(x?.actions).length:0,C=Y(x?.actions)?Object.keys(x.actions)[S-1]:void 0,te=Y(C)?x?.actions?.[C]?.id:void 0,w=(Y(r)&&!r?.startsWith(`${x.key}_`)?`${x.key}_${r}`:r)??te;J(w)&&(y.error(`A valid action ID is required to run an action`),process.exit(1));let E=Y(a)?await this.#d(a,v?.apiUrl??bi,v?.apiKey):{},ne=Y(i)?this.#o(i,x.key??`unknown`,x.version??`unknown`):void 0,D=Y(c)?this.#f(c):{},re={...E,...ne,credentials:{...E.credentials??{},...D}};J(re)&&(y.error(`A valid account data is required to run an action.`),process.exit(1));let ie=x.actions?.[w];J(ie)&&(y.error(`Action ID ${t(w)} not found in the connector ${t(x.key)}@${t(x.version)}.`),process.exit(1));let O=Y(s)?this.#p(s,w):{path:{},queryParams:{},header:{},body:{}};if(h||g!==void 0)return this.#e({connector:x,actionId:w,action:ie,account:re,baseInputs:ti(O),mode:h?`full`:`incremental`,checkpointValue:typeof g==`string`&&g!==``?g:void 0,maxPagesOverride:_,pageSizeOverride:ee,outputFile:u,debug:d});let k=Date.now(),ae=await this.#m({connector:x,actionId:w,account:re,queryParams:{...O.queryParams,...d?{debug:`true`}:{}},pathParams:O.path,body:O.body,headers:O.header}),oe=Date.now()-k;if(Y(u))try{G.writeFileSync(u,JSON.stringify(ae.output,null,2),`utf-8`),y.info(`Output written to file: ${u}`)}catch(e){y.error(`Failed to write output to file ${u}: ${e.message}`),process.exit(1)}else y.log(`\n${T.blue.inverse(` ACTION OUTPUT `)}`),o(ae.output);y.log(``),y.info(`Action ${t(w)} from connector ${t(x?.key)}@${t(x?.version)} finished in ${T.yellowBright((oe/1e3).toFixed(2))} seconds.`),process.exit(0)}async#e({connector:e,actionId:n,action:r,account:i,baseInputs:a,mode:s,checkpointValue:c,maxPagesOverride:l,pageSizeOverride:u,outputFile:d,debug:f}){let p=li(r,s);p.ok||(y.error(p.reason),process.exit(1));let{dataSyncConfig:m}=p;if(Y(u)){let e=ei(m.pagination,u);e.ok||(y.error(`Cannot override the page size: ${e.reason}`),process.exit(1)),m={...m,pagination:e.pagination}}let h=ui(m,l);y.info(`Data sync ${t(s)} run of ${t(n)} — pagination ${t(m.pagination?.type??`none`)}${Y(u)?` (page size ${t(String(u))})`:``}, incremental ${t(m.incremental?.type??`none`)}, page cap ${t(String(h))}`);let g=Date.now(),_,ee=new ft;try{_=await di({dataSyncConfig:m,mode:s,checkpointValue:c,baseInputs:a,maxPages:h,now:()=>new Date,callAction:async t=>it({mode:`action_id`,actionId:n,account:i,connector:e,...ni(t),getHttpClient:async()=>ee}),onPage:(e,t)=>{y.log(` ${T.gray(t)} page ${T.yellowBright(e.iteration)} — ${T.green(e.itemCount)} records${e.exhausted?T.gray(` (last)`):``}`)}})}catch(e){e instanceof si&&this.#t(e,m),this.#g(e)}let v=(Date.now()-g)/1e3,b=pi(_,m),x={actionId:n,connector:`${e.key}@${e.version}`,dataSyncConfig:m,result:_,warnings:b};if(y.log(`\n${T.blue.inverse(` DATA SYNC SUMMARY `)}`),o(fi({...x,includePages:f===!0})),Y(d))try{G.writeFileSync(d,JSON.stringify({...fi({...x,includePages:!0}),records:_.phases.map(e=>e.items)},null,2),`utf-8`),y.info(`Records and summary written to file: ${d}`)}catch(e){y.error(`Failed to write output to file ${d}: ${e.message}`),process.exit(1)}b.length>0&&(y.log(`${T.yellow.inverse(` WARNINGS `)}`),b.forEach(e=>y.warn(e))),y.log(``),y.info(`Data sync ${t(s)} run finished in ${T.yellowBright(v.toFixed(2))} seconds. Nothing was indexed.`);let S=_.phases.some(e=>e.checkpointApplied===!1)||_.phases.some(e=>e.stoppedBy===`duplicatePage`);process.exit(S?1:0)}#t(e,n){if(y.error(`Data sync failed on page ${t(String(e.iteration))} — ${r(String(e.statusCode??`unknown`))} ${e.providerMessage??``}`.trim()),y.log(`${e.pagesCompleted} page(s) and ${e.recordsCollected} record(s) succeeded before this one.\n`),Y(e.providerData)&&(y.log(`${T.red.inverse(` PROVIDER ERROR `)}`),o(e.providerData),y.log(``)),y.log(`${T.yellow.inverse(` REQUEST THAT FAILED `)}`),o(e.inputs),e.iteration>1&&Y(n.pagination)){let{pagination:r}=n;y.log(``),y.info(`Page 1 succeeded and page ${e.iteration} did not, so the ${t(r.type)} iterator is the first thing to check: the value above under ${t(ut(r)??`query`)} is what the provider rejected. A provider that requires a page-size argument alongside the cursor needs it supplied via ${t(`--params`)}, since the iterator only sets the cursor itself.`)}process.exit(1)}#n=e=>{let t=e;try{t=nt(e)}catch{}return t?this.#i(t):void 0};#r=e=>{try{return nt(e)}catch(n){y.error(`Failed to load connector file from ${t(e)}: ${n.message}`),process.exit(1)}};#i=e=>{let t=at(e),n=t?.errors??[];if(t.success)return t.connector||(y.error(`Failed to load connector.`),process.exit(1)),t.connector;n.length>0?(y.error(`Connector is not valid`),x(n,!0),process.exit(1)):(y.error(`Connector is not valid. Please check the file for errors.`),process.exit(1))};#a=(e,t)=>{let n=e;try{n=G.readFileSync(e,`utf-8`)}catch{}J(t)&&(y.error(`A valid connector is required to load an action.`),process.exit(1));let r=`${this.#r(t)} - ${n.split(`
170
+ `))}renderCancelled(){v(),y.log(T.yellow(`Conflict resolution cancelled`)),y.log(``),y.log(`No changes were made to your local connector file.`)}getCurrentConflictIndex(){let e=-1;for(let t=0;t<=this.currentIndex&&t<this.conflicts.length;t++)this.conflicts[t].conflict.type===`conflict`&&e++;return e}moveToNextConflict(){for(let e=this.currentIndex+1;e<this.conflicts.length;e++)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}for(let e=0;e<this.currentIndex;e++)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}}moveToPrevConflict(){for(let e=this.currentIndex-1;e>=0;e--)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}for(let e=this.conflicts.length-1;e>this.currentIndex;e--)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}}moveToNextUnresolved(){for(let e=this.currentIndex+1;e<this.conflicts.length;e++)if(this.conflicts[e].conflict.type===`conflict`&&this.conflicts[e].choice===`pending`){this.currentIndex=e;return}for(let e=0;e<this.currentIndex;e++)if(this.conflicts[e].conflict.type===`conflict`&&this.conflicts[e].choice===`pending`){this.currentIndex=e;return}}setCurrentChoice(e){this.conflicts[this.currentIndex]?.conflict.type===`conflict`&&(this.conflicts[this.currentIndex].choice=e)}allResolved(){return this.conflicts.filter(e=>e.conflict.type===`conflict`).every(e=>e.choice!==`pending`)}acceptAllRemaining(e){for(let t of this.conflicts)t.conflict.type===`conflict`&&t.choice===`pending`&&(t.choice=e)}centerText(e,t){let n=this.stripAnsi(e),r=Math.max(0,Math.floor((t-n.length)/2));return` `.repeat(r)+e}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*m/g,``)}getResolvedContent(){let e=[];for(let t of this.conflicts)if(t.conflict.type===`unchanged`)e.push(t.conflict.content||``);else if(t.conflict.type===`conflict`)switch(t.choice){case`remote`:t.conflict.remote&&e.push(t.conflict.remote);break;case`local`:t.conflict.local&&e.push(t.conflict.local);break;case`both`:t.conflict.local&&e.push(t.conflict.local),t.conflict.remote&&e.push(t.conflict.remote);break;case`pending`:t.conflict.remote&&e.push(t.conflict.remote);break}return e.join(``)}};const Wr=`https://api.stackone.com`;var Gr=class{async execute({profile:e,connector:n,outputPath:r,apiUrl:i,apiKey:a,owner:o}={}){if(J(n)&&(y.error(`Connector identifier is required`),y.log(`Please provide a connector identifier using the ${t(`--connector`)} option in the format: ${t(`provider_key@version`)} or ${t(`provider_key`)}`),y.log(`If no version is specified, the latest version will be pulled.`),process.exit(1)),!e&&!a&&(y.error(`Profile or API key is required`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),e&&a&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&i&&y.warn(`Specifying ${t(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!Mr(e)){y.error(`Configuration profile ${t(e)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let n=Pr();n.length>0&&(y.info(`Available configuration profiles:`),n.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let s=e?jr(e):{apiUrl:i??Wr,apiKey:a};s?.apiKey||(y.error(`API key is missing`),y.log(`Please provide a valid API key in the profile or via the ${t(`--api-key`)} option.`),process.exit(1));let c=s.apiUrl??Wr,[l,u]=n.split(`@`),d=await this.#f(l,c,s.apiKey,u??`latest`,o),f=this.#e(d),p=f.version??`unknown`,m=this.#t(r,f.key,p),h=this.#r(m),g=h===null,_=d;if(!g){let e=this.#i(h,m);e&&(y.warn(e.message),e.errors.length>0&&x(e.errors,!1),y.log(``));let t=e?void 0:this.#e(h);if(this.#o(h,d)){this.#a(h,d,m);let e=t?.version??`unknown`,r=await this.#s(h,d,n,e,p);r.action===`cancel`&&(Ge(`Pull cancelled`),process.exit(0)),r.action===`keep-local`&&(y.log(``),y.info(`Keeping local version. No changes made.`),process.exit(0)),r.action===`interactive-cancel`&&process.exit(0),r.action===`interactive`&&(_=r.resolvedContent)}else y.info(`No changes detected in connector configuration.`),process.exit(0)}let ee=at(_).connector,v=ee?.key??f.key,b=ee?.version??p,S=this.#t(r,v,b),C=S;if(S!==m){let e=await this.#n(S);y.log(``),e!==void 0&&(C=e)}await this.#d(C,_),g?y.success(`Connector ${t(v)}@${t(b)} pulled successfully (new connector)`):y.success(`Connector ${t(v)}@${t(b)} updated successfully`);let te=v===f.key?t(v):`${t(f.key)} ${T.whiteBright(`→`)} ${t(v)}`,w=b===p?t(b):`${t(p)} ${T.whiteBright(`→`)} ${t(b)}`,E=C===m?t(C):`${t(m)}\n ${T.whiteBright(`→`)} ${t(C)}`;y.log(`\n${T.blue.inverse(` CONNECTOR DETAILS `)}\n`),y.log(` Provider: ${te}`),y.log(` Version: ${w}`),y.log(` Output file: ${E}`),process.exit(0)}#e(e){let n=at(e),r=n?.errors??[];if(n.success)return n.connector;y.error(`Connector pulled from the registry is not valid`),y.log(`Please make sure you are using the latest version of the StackOne CLI by running ${t(`stackone update`)}`),r.length>0&&x(r,!0),process.exit(1)}#t(e,n,r){let i=`${n}_v${r.replaceAll(`.`,`-`)}.s1.yaml`;return e?(G.existsSync(e)&&(G.statSync(e).isDirectory()||(y.error(`Output path ${t(e)} is not a directory`),y.log(`Please provide a valid directory path to store connectors or use the default path.`),process.exit(1))),Me.resolve(e,n,i)):Me.resolve(process.cwd(),`connectors`,n,i)}async#n(e){if(!G.existsSync(e))return;let n=Me.basename(e),r=Me.dirname(e);y.warn(`File ${t(n)} already exists at ${t(r)}`);let i=await Ze({message:`How would you like to proceed?`,options:[{value:`override`,label:`Override existing file`,hint:`Replace the existing file with the new content`},{value:`rename`,label:`Save with a different name`,hint:`Provide a new filename for the connector`},{value:`cancel`,label:`Cancel`,hint:`Abort the pull operation`}]});if((Je(i)||i===`cancel`)&&(Ge(`Operation cancelled. No local changes were made.`),process.exit(0)),i===`override`)return;let a=await Qe({message:`Enter the new filename:`,placeholder:n,validate:e=>{if(!e||e.trim()===``)return`Filename cannot be empty`;if(!e.endsWith(`.s1.yaml`))return`Filename must end with .s1.yaml`;let t=Me.join(r,e.trim());if(G.existsSync(t))return`File ${e} already exists`}});return Je(a)&&(Ge(`Operation cancelled. No local changes were made.`),process.exit(0)),Me.join(r,a.trim())}#r(e){if(!G.existsSync(e))return null;try{return G.readFileSync(e,`utf-8`)}catch{return null}}#i(e,n){try{let r=at(e);if(!r.success){let e=r.errors??[];return{message:`Local connector ${t(Me.basename(n))} has validation errors:`,errors:e}}}catch(e){return{message:`Local connector ${t(Me.basename(n))} could not be validated: ${e.message}`,errors:[]}}return null}#a(e,t,n){let r=ot(e,t);if(!r.some(e=>e.added||e.removed)){y.info(`No changes detected in connector configuration.`);return}y.log(`${T.blue.inverse(` CHANGES `)}\n`),y.log(T.gray(`--- local: ${n}`)),y.log(T.gray(`+++ remote: StackOne Registry`)),y.log(``);let i=0,a=0;for(let e of r){let t=e.value.split(`
171
+ `).filter(e=>e!==``);if(e.added){i+=t.length;for(let e of t)y.log(T.green(`+ ${e}`))}else if(e.removed){a+=t.length;for(let e of t)y.log(T.red(`- ${e}`))}else if(t.length<=6)for(let e of t)y.log(T.gray(` ${e}`));else{for(let e=0;e<3;e++)y.log(T.gray(` ${t[e]}`));y.log(T.gray(` ... (${t.length-6} unchanged lines)`));for(let e=t.length-3;e<t.length;e++)y.log(T.gray(` ${t[e]}`))}}y.log(``),y.log(T.gray(`Summary: ${T.green(`+${i}`)} additions, ${T.red(`-${a}`)} deletions`))}#o(e,t){return ot(e,t).some(e=>e.added||e.removed)}async#s(e,t,n,r,i){y.log(``);let a=await Ze({message:`How would you like to resolve the differences?`,options:[{value:`override`,label:`Override local with remote`,hint:`Replace your local file with the StackOne version`},{value:`keep-local`,label:`Keep local version`,hint:`Cancel the pull and keep your current file`},{value:`interactive`,label:`Resolve conflicts interactively`,hint:`Choose which changes to accept one by one`},{value:`cancel`,label:`Cancel`,hint:`Abort the pull operation`}]});if(Je(a))return{action:`cancel`};if(a===`override`)return{action:`override`};if(a===`keep-local`)return{action:`keep-local`};if(a===`interactive`){let a=await this.#c(e,t,n,r,i);return a===null?{action:`interactive-cancel`}:{action:`interactive`,resolvedContent:a}}return{action:`cancel`}}async#c(e,t,n,r,i){let a=ot(e,t),o=this.#u(a);if(o.length===0)return y.info(`No conflicts to resolve.`),t;let s=new Ur(o,n,r,i);for(;;){if((await s.resolve()).cancelled)return null;let e=s.getResolvedContent(),t=at(e);if(t.success)return s.renderFinalSummary(),e;let n=await this.#l(t.errors);if(n===`cancel`)return v(),y.info(`Operation cancelled. No changes were made to the local connector.`),null;if(n===`save`)return v(),y.warn(`The connector was saved but it is invalid`),e;s.resetForReResolution()}}async#l(e){let{createInterface:t}=await import(`readline`);return new Promise(n=>{v();let r=(e||[{message:`Unknown validation error`}]).map(e=>` • ${e.message}`).join(`
172
+ `);y.box({title:`⚠️ Validation Failed`,message:`The resolved connector configuration is invalid:\n\n${r}`,style:{borderColor:`yellow`,padding:1}}),y.log(``),y.log(T.bold(` Choose an action:`)),y.log(``),y.log(T.cyan(` [B]`)+` ← Go back to conflict resolution`),y.log(T.dim(` Modify your choices to fix the validation errors`)),y.log(``),y.log(T.yellow(` [S]`)+` 💾 Save anyway`),y.log(T.dim(` Save the invalid configuration (not recommended)`)),y.log(``),y.log(T.red(` [C]`)+` ✖ Cancel`),y.log(T.dim(` Discard all changes`)),y.log(``);let i=t({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();let a=e=>{let t=e.toString().toLowerCase(),r=()=>{process.stdin.removeListener(`data`,a),process.stdin.isTTY&&process.stdin.setRawMode(!1),i.close()};if(t===``||t===`\x1B`){r(),n(`cancel`);return}switch(t){case`b`:r(),n(`back`);break;case`s`:r(),n(`save`);break;case`c`:case`q`:r(),n(`cancel`);break}};process.stdin.on(`data`,a)})}#u(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(!r.added&&!r.removed)t.push({type:`unchanged`,content:r.value}),n++;else if(r.removed){let i=e[n+1];i?.added?(t.push({type:`conflict`,local:r.value,remote:i.value}),n+=2):(t.push({type:`conflict`,local:r.value,remote:void 0}),n++)}else r.added&&t.push({type:`conflict`,local:void 0,remote:r.value}),n++}return t}async#d(e,n){let r=Me.dirname(e);G.existsSync(r)||G.mkdirSync(r,{recursive:!0});try{G.writeFileSync(e,n,`utf-8`)}catch(n){y.error(`Failed to write connector to file ${t(e)}: ${n.message}`),process.exit(1)}}async#f(e,n,i,a,o){let s=q(`Pulling connector ${t(e)}@${t(a)} from registry...`).start();try{let r=Buffer.from(i).toString(`base64`),c=`${n}/registry/connectors/${e}@${a}${o?`?owner=${encodeURIComponent(o)}`:``}`,l=await fetch(c,{method:`GET`,headers:{Authorization:`Basic ${r}`}});if(s.stop(),l.status===409){o&&(await this.#p(l,e,a),process.exit(1));let i=(await l.json()).availableOwners??[],c=await Rr(`${e}@${a}`,i);s.text=`Pulling connector ${t(e)}@${t(a)} from registry...`,s.start();let u=`${n}/registry/connectors/${e}@${a}`,d=await fetch(`${u}?owner=${encodeURIComponent(c)}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});return s.stop(),d.ok||(await this.#p(d,e,a),process.exit(1)),await d.text()}return l.ok||(await this.#p(l,e,a),process.exit(1)),await l.text()}catch(i){s.stop(),y.error(`Failed to pull connector ${t(e)}@${t(a)} from the registry: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid.`),process.exit(1)}}async#p(e,n,r){switch(e.status){case 401:case 403:y.error(`Access denied`),y.log(`Please ensure that your API key is valid and has the ${t(`connectors:read`)} scope required to pull connectors.`);break;case 404:y.error(`Connector ${t(n)}@${t(r)} was not found in the registry`),await this.#m(n);break;case 429:y.error(`Rate limit exceeded`),y.log(`Too many requests. Please wait a moment before trying again.`);break;default:await b(e,`Failed to pull connector ${t(n)}`)}}async#m(e){y.info(`To see available versions, check the connector documentation or contact support.`)}};const Kr=`https://api.stackone.com`;var qr=class{async execute({profile:e,fileOrDir:n,apiUrl:r,apiKey:i,force:a}={}){if(!e&&!i&&(y.error(`Profile or API key is required`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),e&&i&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&r&&y.warn(`Specifying ${t(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!Mr(e)){y.error(`Configuration profile ${t(e)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let n=Pr();n.length>0&&(y.info(`Available configuration profiles:`),n.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let o=e?jr(e):{apiUrl:r??Kr,apiKey:i};o?.apiKey||(y.error(`API key is missing`),y.log(`Please provide a valid API key in the profile or via the ${t(`--api-key`)} option.`),process.exit(1)),n||(y.error(`File or directory is required.`),process.exit(1));try{K(n)}catch{y.error(`File or directory not found: ${T.red(n)}`),process.exit(1)}let s=K(n),c=o.apiUrl??Kr;if(s.isDirectory()){let e=ei(n),t=0;e.length===0?(y.error(`No .s1.yaml connector files found in the directory: ${n}.`),process.exit(1)):(y.start(`Found ${e.length} connector(s) file(s). Pushing to registry...`),y.log(``));for(let n of e)await this.uploadFile(n,c,o.apiKey,a)&&t++;t===0?y.error(`Error while pushing connectors: no files were uploaded`):(y.log(``),y.info(`Upload completed: ${T.green(t)} of ${T.blue(e.length)} file(s) uploaded successfully.`)),process.exit(t>0?0:1)}else n.endsWith(`.s1.yaml`)||(y.error(`Only ${t(`.s1.yaml`)} files are supported for upload`),process.exit(1));let l=await this.uploadFile(n,c,o.apiKey,a);process.exit(l?0:1)}async uploadFile(e,n,i,a){let o=q(`📤 Pushing connector in ${Ne(e)}...`).start();try{let r=$r(e);if(!r)return!1;let s=Ne(e),c=new FormData,l=new Blob([r],{type:`application/x-yaml`});c.append(`file`,l,s),a&&c.append(`force`,`true`);let u=Buffer.from(i).toString(`base64`),d=await fetch(`${n}/registry/connectors`,{method:`POST`,headers:{Authorization:`Basic ${u}`},body:c});if(o.stop(),!d.ok)return d.status===409||d.status===422?await this.handleVersionConflict(d,e,n,i,a):(await b(d,`Failed to push connector in ${t(s)} to the registry`),!1);let f=await d.json();return y.success(`Successfully uploaded ${t(s)} with connector ${t(f.provider)}@${t(f.version)}`),!0}catch(i){return o.stop(),y.error(`Failed to upload file ${t(e)}: ${i}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),!1}}async handleVersionConflict(e,n,r,i,a){let o=Jr(e.status,a);o&&y.warn(o);let s=await e.text(),c;try{c=JSON.parse(s)}catch{}let l=dt.valid(c?.latestVersion);if(!l)return await b(new Response(s,{status:e.status,statusText:e.statusText}),`Failed to push connector in ${t(Ne(n))} to the registry`),!1;let u=ke(n,`utf-8`),d=Yr(u),f=d?`${t(d)}`:``,p=e.status===409?`Version ${f} already exists in the registry. Latest version: ${t(l)}`:`Version ${f} is lower than the latest version in the registry. Latest version: ${t(l)}`;y.error(p);let m=dt.inc(l,`patch`)??l,h=dt.inc(l,`minor`)??l,g=dt.inc(l,`major`)??l,_=await Ze({message:`How would you like to proceed?`,options:[{value:m,label:`Bump patch version (${m})`},{value:h,label:`Bump minor version (${h})`},{value:g,label:`Bump major version (${g})`},{value:`cancel`,label:`Cancel push`}]});return Je(_)||_===`cancel`?(Ge(`Push cancelled`),!1):(je(n,Xr(u,_),`utf-8`),y.info(`Updated version to ${t(_)} in ${Ne(n)}`),this.uploadFile(n,r,i,a))}};const Jr=(e,n)=>!n||e!==409?null:`${t(`--force`)} was ignored because Immutable Versioning is enabled for this project, so a published connector version cannot be overwritten. Push a new version, or turn Immutable Versioning off in the project settings.`,Yr=e=>e.match(/^\s*version: (\S+)/m)?.[1],Xr=(e,t)=>e.replace(/^(\s*version: )\S+/m,`$1${t}`),Zr=e=>{try{let t=rt(e);return t.changelog?.summary?.trim()?null:`has no changelog entry for version ${t.version}`}catch{return null}},Qr=()=>{y.log(`Every published version must record what changed. Add an ${t(`info.changelog`)} block:`),y.log(``),y.log(T.gray(` info:`)),y.log(T.gray(` changelog:`)),y.log(T.gray(` summary: What changed in this version.`)),y.log(T.gray(` labels: [new-actions] # optional, one of: ${ct.join(`, `)}`)),y.log(``)},$r=e=>{let t=nt(e),r=at(t),i=r?.errors??[];if(r.success){let r=Zr(t);if(r){y.error(`Connector in ${n(e)} ${r}`),Qr();return}return t}else i.length>0?(y.error(`Connector in ${n(e)} is not valid`),x(i,!0)):y.error(`Connector in ${n(e)} is not valid. Please check the file for errors.`)},ei=e=>{let t=[],n=Ae(e,{withFileTypes:!0});for(let r of n){let n=Fe(e,r.name);r.isDirectory()?t.push(...ei(n)):r.name.endsWith(`.s1.yaml`)&&t.push(n)}return t},ti=(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.`}}},ni=e=>({path:e.path,query:e.queryParams,headers:e.header,body:e.body}),ri=e=>({pathParams:e.path??{},queryParams:e.query??{},headers:e.headers??{},body:e.body??{}}),ii=(e,t)=>{switch(e.type){case`time_filter`:return{kind:`timestamp`,value:t};case`delta_token`:return{kind:`cursor`,value:t}}},ai=(e,t,n)=>{let{in:r,key:i}=e.iterator;return oi(n[r])[i]===t.value},oi=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:{},si=2e3;var ci=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 li=async({dataSyncConfig:e,baseInputs:t,checkpointIn:n,callAction:r,maxPages:i,runStartTime:a,onPage:o})=>{let s=e.incremental?$e(e.incremental):null,c=s?s.applyToInputs({baseInputs:t,checkpoint:n}):t,l=e.incremental&&n?ai(e.incremental,n,c):null,u=e.pagination?et(e.pagination,{baseInputs:c}):null,d=Math.min(i,si),f=[],p=[],m=[],h=null,g=0,_=null,ee=e=>({items:f,pages:p,pagesRetrieved:g,stoppedBy:e,extractedCheckpoints:m,checkpointOut:e===`exhausted`&&s?s.finalizeCheckpoint({runStartTime:a,extractedCheckpoints:m}):null,checkpointApplied:l});for(;;){if(g>=d)return ee(`maxIterations`);let t=h??u?.computeNextInputs({previousResponse:void 0,currentIteration:g})??c,n=await r(t);if(g++,n.response?.successful!==!0)throw new ci({iteration:g,statusCode:n.response?.statusCode,providerMessage:n.response?.message,providerData:n.response?.data,inputs:t,pagesCompleted:g-1,recordsCollected:f.length});let i=tt(n,e),a=Ue(i),l=u?u.isExhausted(n,g):!0,v=s?.extractFromPage({block:n,items:i,isFinalPage:l})??null,y={iteration:g,inputs:t,itemCount:i.length,statusCode:n.response?.statusCode,exhausted:l,extractedCheckpoint:v};if(p.push(y),o?.(y),v){let e=m.findIndex(e=>e.kind===v.kind&&e.value===v.value);e!==-1&&m.splice(e,1),m.push(v)}if(_!==null&&a===_)return ee(`duplicatePage`);if(f.push(...i),_=a,l)return ee(`exhausted`);h=u?.computeNextInputs({previousResponse:n,currentIteration:g})}},ui=(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`}},di=(e,t)=>Math.min(t??e.maxPages??si,si),fi=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 li({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`,ii(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`}},pi=({actionId:e,connector:t,dataSyncConfig:n,result:r,warnings:i,includePages:a})=>{let o=r.phases.find(e=>e.items.length>0)?.items[0];return{actionId:e,connector:t,dataSyncConfigFingerprint:lt(n),phases:r.phases.map(e=>({mode:e.mode,pagesRetrieved:e.pagesRetrieved,records:e.items.length,stoppedBy:e.stoppedBy,checkpointIn:e.checkpointIn,checkpointOut:e.checkpointOut,checkpointApplied:e.checkpointApplied,...a?{pages:e.pages.map(e=>({iteration:e.iteration,inputs:e.inputs,itemCount:e.itemCount,statusCode:e.statusCode,exhausted:e.exhausted}))}:{}})),...r.skipped?{incrementalPhaseSkipped:r.skipped}:{},...o?{sampleRecord:o}:{},warnings:i}},mi=(e,t)=>{let n=[],{incremental:r}=t;for(let r of e.phases)n.push(...hi(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 ${_i(t)}; every sync will refetch the whole dataset if it does not.`),n},hi=(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?gi(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},gi=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}},_i=e=>{let{incremental:t}=e;return t?`${t.iterator.key} in ${t.iterator.in}`:`the incremental iterator`},vi=X.object({provider_key:X.string().optional(),provider_version:X.string().optional(),auth_config_key:X.string(),environment:X.string().default(`production`),organization_id:X.string().default(`cli-organization-id`),account_id:X.string().default(`cli-account-secure-id`),project_id:X.string().default(`cli-project-secure-id`),credentials:X.record(X.string(),X.any()).default({})}),yi=X.record(X.string(),X.any()),bi=X.object({path:X.record(X.string(),X.any()).default({}),queryParams:X.record(X.string(),X.any()).default({}),header:X.record(X.string(),X.any()).default({}),body:X.record(X.string(),X.any()).default({})}),xi=`https://api.stackone.com`;var Si=class{async execute({connector:e,action:n,actionId:r,account:i,accountId:a,params:s,credentials:c,profile:l,outputFile:u,debug:d,apiUrl:f,apiKey:p,owner:m,syncFull:h,syncIncremental:g,syncMaxPages:_,syncPageSize:ee}={}){if(!l&&!p&&a&&(y.error(`Profile or API key is required when providing an account ID`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),l&&p&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),l&&f&&y.warn(`Specifying --api-url with a profile won't have any effect. Using API url from profile.`),l&&!Mr(l)){y.error(`Configuration profile ${t(l)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let e=Pr();e.length>0&&(y.info(`Available configuration profiles:`),e.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let v=l?jr(l):{apiUrl:f??xi,apiKey:p};J(i)&&J(a)&&(y.error(`A valid account or account ID is required to run an action`),process.exit(1));let b;if(Y(e))if(this.#s(e)){!l&&!p&&(y.error(`Profile or API key is required when using a connector identifier`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.`),process.exit(1));let n=this.#c(e);b=await this.#l(n,v?.apiUrl??xi,v?.apiKey,m)}else b=this.#n(e);else Y(a)&&(b=await this.#u(a,v?.apiUrl??xi,v?.apiKey));let x=Y(n)?this.#a(n,e):b;J(x)&&(y.error(`A valid connector is required to run an action.`),process.exit(1));let S=Y(x?.actions)?Object.keys(x?.actions).length:0,C=Y(x?.actions)?Object.keys(x.actions)[S-1]:void 0,te=Y(C)?x?.actions?.[C]?.id:void 0,w=(Y(r)&&!r?.startsWith(`${x.key}_`)?`${x.key}_${r}`:r)??te;J(w)&&(y.error(`A valid action ID is required to run an action`),process.exit(1));let E=Y(a)?await this.#d(a,v?.apiUrl??xi,v?.apiKey):{},ne=Y(i)?this.#o(i,x.key??`unknown`,x.version??`unknown`):void 0,D=Y(c)?this.#f(c):{},re={...E,...ne,credentials:{...E.credentials??{},...D}};J(re)&&(y.error(`A valid account data is required to run an action.`),process.exit(1));let ie=x.actions?.[w];J(ie)&&(y.error(`Action ID ${t(w)} not found in the connector ${t(x.key)}@${t(x.version)}.`),process.exit(1));let O=Y(s)?this.#p(s,w):{path:{},queryParams:{},header:{},body:{}};if(h||g!==void 0)return this.#e({connector:x,actionId:w,action:ie,account:re,baseInputs:ni(O),mode:h?`full`:`incremental`,checkpointValue:typeof g==`string`&&g!==``?g:void 0,maxPagesOverride:_,pageSizeOverride:ee,outputFile:u,debug:d});let k=Date.now(),ae=await this.#m({connector:x,actionId:w,account:re,queryParams:{...O.queryParams,...d?{debug:`true`}:{}},pathParams:O.path,body:O.body,headers:O.header}),oe=Date.now()-k;if(Y(u))try{G.writeFileSync(u,JSON.stringify(ae.output,null,2),`utf-8`),y.info(`Output written to file: ${u}`)}catch(e){y.error(`Failed to write output to file ${u}: ${e.message}`),process.exit(1)}else y.log(`\n${T.blue.inverse(` ACTION OUTPUT `)}`),o(ae.output);y.log(``),y.info(`Action ${t(w)} from connector ${t(x?.key)}@${t(x?.version)} finished in ${T.yellowBright((oe/1e3).toFixed(2))} seconds.`),process.exit(0)}async#e({connector:e,actionId:n,action:r,account:i,baseInputs:a,mode:s,checkpointValue:c,maxPagesOverride:l,pageSizeOverride:u,outputFile:d,debug:f}){let p=ui(r,s);p.ok||(y.error(p.reason),process.exit(1));let{dataSyncConfig:m}=p;if(Y(u)){let e=ti(m.pagination,u);e.ok||(y.error(`Cannot override the page size: ${e.reason}`),process.exit(1)),m={...m,pagination:e.pagination}}let h=di(m,l);y.info(`Data sync ${t(s)} run of ${t(n)} — pagination ${t(m.pagination?.type??`none`)}${Y(u)?` (page size ${t(String(u))})`:``}, incremental ${t(m.incremental?.type??`none`)}, page cap ${t(String(h))}`);let g=Date.now(),_,ee=new ft;try{_=await fi({dataSyncConfig:m,mode:s,checkpointValue:c,baseInputs:a,maxPages:h,now:()=>new Date,callAction:async t=>it({mode:`action_id`,actionId:n,account:i,connector:e,...ri(t),getHttpClient:async()=>ee}),onPage:(e,t)=>{y.log(` ${T.gray(t)} page ${T.yellowBright(e.iteration)} — ${T.green(e.itemCount)} records${e.exhausted?T.gray(` (last)`):``}`)}})}catch(e){e instanceof ci&&this.#t(e,m),this.#g(e)}let v=(Date.now()-g)/1e3,b=mi(_,m),x={actionId:n,connector:`${e.key}@${e.version}`,dataSyncConfig:m,result:_,warnings:b};if(y.log(`\n${T.blue.inverse(` DATA SYNC SUMMARY `)}`),o(pi({...x,includePages:f===!0})),Y(d))try{G.writeFileSync(d,JSON.stringify({...pi({...x,includePages:!0}),records:_.phases.map(e=>e.items)},null,2),`utf-8`),y.info(`Records and summary written to file: ${d}`)}catch(e){y.error(`Failed to write output to file ${d}: ${e.message}`),process.exit(1)}b.length>0&&(y.log(`${T.yellow.inverse(` WARNINGS `)}`),b.forEach(e=>y.warn(e))),y.log(``),y.info(`Data sync ${t(s)} run finished in ${T.yellowBright(v.toFixed(2))} seconds. Nothing was indexed.`);let S=_.phases.some(e=>e.checkpointApplied===!1)||_.phases.some(e=>e.stoppedBy===`duplicatePage`);process.exit(S?1:0)}#t(e,n){if(y.error(`Data sync failed on page ${t(String(e.iteration))} — ${r(String(e.statusCode??`unknown`))} ${e.providerMessage??``}`.trim()),y.log(`${e.pagesCompleted} page(s) and ${e.recordsCollected} record(s) succeeded before this one.\n`),Y(e.providerData)&&(y.log(`${T.red.inverse(` PROVIDER ERROR `)}`),o(e.providerData),y.log(``)),y.log(`${T.yellow.inverse(` REQUEST THAT FAILED `)}`),o(e.inputs),e.iteration>1&&Y(n.pagination)){let{pagination:r}=n;y.log(``),y.info(`Page 1 succeeded and page ${e.iteration} did not, so the ${t(r.type)} iterator is the first thing to check: the value above under ${t(ut(r)??`query`)} is what the provider rejected. A provider that requires a page-size argument alongside the cursor needs it supplied via ${t(`--params`)}, since the iterator only sets the cursor itself.`)}process.exit(1)}#n=e=>{let t=e;try{t=nt(e)}catch{}return t?this.#i(t):void 0};#r=e=>{try{return nt(e)}catch(n){y.error(`Failed to load connector file from ${t(e)}: ${n.message}`),process.exit(1)}};#i=e=>{let t=at(e),n=t?.errors??[];if(t.success)return t.connector||(y.error(`Failed to load connector.`),process.exit(1)),t.connector;n.length>0?(y.error(`Connector is not valid`),x(n,!0),process.exit(1)):(y.error(`Connector is not valid. Please check the file for errors.`),process.exit(1))};#a=(e,t)=>{let n=e;try{n=G.readFileSync(e,`utf-8`)}catch{}J(t)&&(y.error(`A valid connector is required to load an action.`),process.exit(1));let r=`${this.#r(t)} - ${n.split(`
173
173
  `).map((e,t)=>t===0?e:` ${e}`).join(`
174
- `)}`;return this.#i(r)};#o=(e,t,n)=>{let r=e;try{r=G.readFileSync(e,`utf-8`)}catch{}try{let e=_i.parse(JSON.parse(r));return{providerKey:t,providerVersion:n,authConfigKey:e.auth_config_key,environment:e.environment,organizationId:e.organization_id,secureId:e.account_id,projectSecureId:e.project_id}}catch(e){let t=[];try{t=JSON.parse(e.message)}catch{}y.error(`Failed to parse account information`),x(t,!1),t.length===0&&y.log(e.message),process.exit(1)}};#s=e=>!e.includes(`/`)&&!e.includes(`\\`)&&!e.endsWith(`.yaml`)&&!e.endsWith(`.yml`)?e.includes(`@`)?e.split(`@`).length===2:!0:!1;#c=e=>e.includes(`@`)?e:`${e}@latest`;#l=async(e,n,i,a)=>{(J(e)||J(n)||J(i))&&(y.error(`Connector identifier, API URL, and API key are required to fetch connector from registry.`),process.exit(1));let o=q();try{o.text=`Fetching connector ${t(e)} from registry...`,o.start();let r=Buffer.from(i).toString(`base64`),s=a?`?owner=${encodeURIComponent(a)}`:``,c=await fetch(`${n}/registry/connectors/${e}${s}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});if(o.stop(),c.status===409){a&&(await b(c,`Failed to fetch connector ${t(e)} from registry`),process.exit(1));let i=await Lr(e,(await c.json()).availableOwners??[]);o.text=`Fetching connector ${t(e)} from registry...`,o.start();let s=await fetch(`${n}/registry/connectors/${e}?owner=${encodeURIComponent(i)}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});o.stop(),s.ok||(await b(s,`Failed to fetch connector ${t(e)} from registry`),process.exit(1));let l=await s.text(),u=this.#i(l);return y.success(`Fetched connector ${t(u.key)}@${t(u.version)} from registry`),u}c.ok||(await b(c,`Failed to fetch connector ${t(e)} from registry`),process.exit(1));let l=await c.text(),u=this.#i(l);return y.success(`Fetched connector ${t(u.key)}@${t(u.version)} from registry`),u}catch(i){o.stop(),y.error(`Failed to fetch connector ${t(e)} from registry: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}};#u=async(e,n,i)=>{(J(e)||J(n)||J(i))&&(y.error(`Account ID, API URL, and API key are required to fetch connector`),process.exit(1));let a=q();try{a.text=`Fetching connector for account ${t(e)} from API...`,a.start();let r=Buffer.from(i).toString(`base64`),o=await fetch(`${n}/accounts/${e}/connector`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});a.stop(),o.ok||(await b(o,`Failed to fetch connector`),process.exit(1));let s=await o.text(),c=this.#i(s);return y.success(`Fetched connector ${t(c.key)}@${t(c.version)} for account ${t(e)}`),c}catch(e){a.stop(),y.error(`Failed to fetch connector: ${e.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}};#d=async(e,n,i)=>{(J(e)||J(n)||J(i))&&(y.error(`Account ID, API URL, and API key are required to fetch account information.`),process.exit(1));let a=q();try{a.text=`Fetching account ${t(e)} information from API...`,a.start();let r=Buffer.from(i).toString(`base64`),o=await fetch(`${n}/accounts/${e}/credentials`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});a.stop(),o.ok||(await b(o,`Failed to fetch account ${t(e)} information`),process.exit(1));let s=await o.json();return y.success(`Fetched account ${t(e)} information from project ${t(s.project_id)}`),{providerKey:s.provider_key,providerVersion:s.provider_version,authConfigKey:s.auth_config_key,environment:s.environment,organizationId:s.organization_id,secureId:s.account_id,projectSecureId:s.project_id,credentials:s.credentials}}catch(i){a.stop(),y.error(`Failed to fetch account ${t(e)} information: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}};#f=e=>{let t=e;try{t=G.readFileSync(e,`utf-8`)}catch{}try{return vi.parse(JSON.parse(t))}catch(e){let t=[];try{t=JSON.parse(e.message)}catch{}y.error(`Failed to parse credentials`),x(t,!1),t.length===0&&y.log(e.message),process.exit(1)}};#p=(e,n)=>{let r=e;try{r=G.readFileSync(e,`utf-8`)}catch{}try{return yi.parse(JSON.parse(r))}catch(e){let r=[];try{r=JSON.parse(e.message)}catch{}y.error(`Invalid parameters for action ${t(n)}.`),x(r,!1),r.length===0&&y.log(e.message),process.exit(1)}};async#m({connector:e,actionId:n,account:r,pathParams:i={},queryParams:a={},body:s={},headers:c={}}){try{let l=await it({mode:`action_id`,actionId:n,account:r,connector:e,pathParams:i,queryParams:a,body:s,headers:c,getHttpClient:async()=>new ft});if(l.response?.successful){let e={...this.#h(a,l.steps),...We(l.outputs)?l.outputs:{data:l.outputs}};return{statusCode:l.response?.statusCode,output:e}}else{let r=l.response?.message??`An error occurred while processing the request`;y.error(`Action ID ${t(n)} from connector ${t(e.key)}@${t(e.version)} failed with status ${l.response?.statusCode}: ${r}`);let i={...this.#h(a,l.steps)};Object.keys(i).length>0&&(y.log(`${T.yellow.inverse(` EXECUTION DETAILS `)}`),o(i)),process.exit(1)}}catch(e){this.#g(e)}}#h(e,t){return e?.debug===`true`?{debug:{steps:t}}:{}}#g(e){let t=e;switch(J(t.errorType)&&(y.error(`An unknown error occurred`),y.log(`${e instanceof Error?e.message:String(e)}`),process.exit(1)),t.errorType){case`MISSING_ACTION_ERROR`:y.error(`The specified action was not found: ${t.message}`);break;case`INVALID_ACTION_INPUTS_ERROR`:let e=t;y.error(`Invalid action inputs`),x(e.validationErrors,!1);break;case`INVALID_CURSOR_ERROR`:y.error(`Invalid cursor: ${t.message}`);break;default:y.error(`An error occurred: ${t.message}`)}process.exit(1)}};const Si=pt(we);var Ci=class{constructor(){this.packageName=`@stackone/cli`,this.spinner=q(),this.currentVersion=$t()}async execute(e={}){this.spinner.text=`Checking for updates...`,this.spinner.start();try{let t=await this.getLatestVersion();this.spinner.stop(),t||(y.error(`Failed to check for updates`),process.exit(1)),this.isNewerVersion(t,this.currentVersion)?(y.box(`New version available: ${T.yellow(this.currentVersion)} → ${T.green(t)}`),await this.performUpdate(t)):e.force?(y.warn(`No updates available, but forcing reinstall...`),await this.performUpdate(t)):y.success(`You are already on the latest version (${this.currentVersion})`),process.exit(0)}catch(e){this.spinner.stop(),y.error(`Error while trying to update StackOne CLI: ${e?.message??`Unknown error`}`),process.exit(1)}}async getLatestVersion(){try{let{stdout:e}=await Si(`npm view ${this.packageName} version`,{encoding:`utf-8`});return e.trim()}catch{return null}}isNewerVersion(e,t){return dt.gt(e,t)}async performUpdate(e){this.spinner.text=`Updating to latest version (${t(e)})...`,this.spinner.start();let n=`npm install -g ${this.packageName}@latest`;try{await Si(n,{encoding:`utf-8`}),this.spinner.stop(),y.success(`StackOne CLI updated successfully to latest version (${t(e)})`)}catch{throw this.spinner.stop(),Error(`Failed to install update. Please try manually: ${n}`)}}};const wi=e=>e===null?!0:Object.values(e).some(e=>e!==null),Ti=()=>{y.log(`${T.gray.inverse(` CONNECTORS VALIDATION `)} ${T.yellow.inverse(` WATCH MODE `)}\n`)};var Ei=class{async execute(e){let{watchMode:t,fileOrDir:n}=e,r=q(`Watching for file changes... ${T.gray(`(press "q" to quit)`)}`);if(!n)return;let i=Ie(n);try{await ht(i)}catch{y.error(`The specified path does not exist: ${i}\n`),process.exit(1)}if(t){v();let e={},{watch:t}=await import(`chokidar`),n=(await import(`readline`)).createInterface({input:process.stdin,output:process.stdout});process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding(`utf8`);let a=()=>{s.close(),r.stop(),n.close(),y.log(T.grey(`
175
- Exiting watch mode...`)),process.exit(0)};Ti(),y.start(`Validating connectors...`);let o=await Ai(i);e=Di(e,o||{}),Oi(e,i),r.start();let s=t(i,{persistent:!0,ignoreInitial:!0}),c=async t=>{if(!t.endsWith(`.s1.yaml`)&&!t.endsWith(`s1.partial.yaml`))return;let n=t.endsWith(`s1.partial.yaml`)?await Mi(t):[t];if(!(!n||n.length===0)){v(),r.stop(),Ti(),y.log(T.gray(`File change detected: ${t}`)),y.start(`Validating connectors...`);for(let t of n){let n=await Ai(t);e=Di(e,n||{})}Oi(e,i),r.start()}};s.on(`change`,async e=>await c(e)),process.stdin.on(`data`,e=>{e.toString()===`q`&&a()}),process.on(`SIGINT`,()=>{a()})}else{let e=await Ai(i,y);process.exit(wi(e)?1:0)}}};const Di=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]=r;return e},Oi=(e,n)=>{v(),Ti();let r=0,i=0;for(let[n,a]of Object.entries(e))a===null?r++:(y?.error(`Connector ${t(n)} is not valid`),x(a,!0),i++);y.log(``),y.log(T.blue.inverse(` Validation Summary `)),y.log(`Connectors path: ${t(n)}`),y.log(`${r===0?T.red(`0`):T.green(r)} valid, ${i===0?T.green(`0`):T.red(i)} invalid connectors\n`)},ki=async e=>{let t=[],n=await mt(e);for(let r of n){let n=Fe(e,r),i=await ht(n);i.isDirectory()?t.push(...await ki(n)):i.isFile()&&r.endsWith(`.s1.yaml`)&&t.push(n)}return t},Ai=async(e,r)=>{let i=await ht(e),a={};if(i.isDirectory()){let i=await ki(e);if(i.length===0)return r?.error(`No StackOne connector found in ${n(e)}`),r?.log(`Connector files need to have the extension ${t(`*.s1.yaml`)}`),null;let o=0,s=0;for(let e of i){let t=await ji(e,r);t===null?o++:(r?.log(``),s++),a[e]=t}return r?.log(``),r?.log(T.blue.inverse(` Validation Summary `)),r?.log(`${o===0?T.red(`0`):T.green(o)} valid, ${s===0?T.green(`0`):T.red(s)} invalid connectors`),a}else if(i.isFile()&&e.endsWith(`s1.yaml`))return a[e]=await ji(e,r),a;else if(i.isFile()&&e.endsWith(`partial.yaml`)){r?.error(`Partial connector files cannot be validated directly`),r?.log(`The file ${n(e)} is a partial connector file.`);let i=await Mi(e);return i&&i?.length>0&&r?.log(`Did you mean ${t(i[0])}?`),null}else return r?.error(`No StackOne connector found in ${n(e)}`),r?.log(`Connector files need to have the extension ${t(`*.s1.yaml`)}`),null},ji=async(e,n)=>{let r=at(nt(e)),i=r?.errors??[];if(r.success){let r=e.split(`/`).pop()||e;return n?.success(`Connector ${t(r)} is valid!`),null}else if(i.length>0)return n?.error(`Connector ${t(e)} is not valid`),n&&x(i,!0),i;else return n?.error(`Connector ${t(e)} is not valid. Please check the file for errors`),[]},Mi=async e=>{let t=Pe(e);try{return(await mt(t)).filter(e=>e.endsWith(`.s1.yaml`))?.map(e=>Fe(t,e))}catch{}};function Ni(e){if(!e)return!1;try{let{hostname:t}=new URL(e);return t===`stackone-dev.com`||t.endsWith(`.stackone-dev.com`)}catch{return!1}}function Pi(){return process.env.AI_TELEMETRY_URL?process.env.AI_TELEMETRY_URL:[process.env.AUTH_SERVER_URL,process.env.STACKONE_API_URL].some(Ni)?`https://ai-telemetry.stackone-dev.com`:`https://ai-telemetry.stackone.com`}function Fi(){let e=process.env.STACKONE_AGENT_TOKEN,t=process.env.LANGSMITH_PROJECT||`stackone-agent-cli`;if(process.env.AI_TELEMETRY_URL=Pi(),e)try{ce({apiKey:e,projectName:t}),process.env.VERBOSE&&console.log(`[Telemetry] Initialized for project:`,t)}catch(e){process.env.VERBOSE&&console.error(`[Telemetry] Failed to initialize:`,e)}}const Ii=e=>{let t=e.trim();return/^\d+$/.test(t)?Number(t):NaN},Li=R(I(),`.stackone`),Ri=R(Li,`version-check.json`),zi=(e=!1)=>{let t=Ui(),n=Date.now();if(e||!t||n-t.lastCheckTime>1728e5){let e=Bi();e&&Vi(e)&&Hi(e),Wi({lastCheckTime:n})}},Bi=()=>{try{return De(`npm view @stackone/cli version`,{encoding:`utf-8`,stdio:[`pipe`,`pipe`,`pipe`],timeout:15e3}).trim()}catch{return null}},Vi=e=>{try{let t=$t();return dt.gt(e,t)}catch{return!1}},Hi=e=>{let t=$t(),n=`Update available: ${T.dim(t)} → ${T.green(e)}`,r=`\n\nRun ${T.cyan(`stackone update`)} to update`;y.box(n,r)},Ui=()=>{try{if(!N(Ri))return null;let e=de(Ri,`utf-8`);return JSON.parse(e)}catch{return null}},Wi=e=>{try{N(Li)||ue(Li,{recursive:!0}),me(Ri,JSON.stringify(e,null,2),`utf-8`)}catch{}};var Gi=class{constructor(e=new ne,t=$t()){this.program=e,this.version=t,Fi(),this.setupProgram(),this.registerCommands()}setupProgram(){this.program.name(`stackone`).description(`StackOne CLI`).version(this.version,`-v, --version`)}registerCommands(){let e=new Vr,t=new Kr,n=new Wr,r=new Fr,i=new zr,a=new Ei,o=new On,s=new Sr,c=new fn,l=new dn,u=new An,d=new Cr,f=new Dr,p=new xi,m=new Ci;this.program.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>process.stderr.write(e),outputError:(e,t)=>{t(T.red(e))}}),this.program.command(`init`).option(`-e, --env <environment>`,`Specify the environment for the configuration profile`).description(`Initialize & create a StackOne CLI configuration profile`).action(t=>{e.execute({environment:t.env})}),this.program.command(`push`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`--force`,`Force push the connector, bypassing version conflict checks`).addArgument(new E(`<path>`,`Connector file or directory to push`)).description(`Push a connector to the StackOne registry`).action((e,n)=>{t.execute({profile:n.profile,fileOrDir:e,apiUrl:n.apiUrl,apiKey:n.apiKey,force:n.force})}),this.program.command(`drop`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).addArgument(new E(`<connector>`,`Connector identifier in format provider_key@version`)).description(`Drop a connector from the StackOne registry`).action((e,t)=>{r.execute({profile:t.profile,connector:e,apiUrl:t.apiUrl,apiKey:t.apiKey})}),this.program.command(`get`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-c, --connector <connector>`,`Connector identifier in format provider_key@version or provider_key (defaults to latest)`).option(`--account-id <account-id>`,`Account ID to fetch connector from`).option(`-f, --format <format>`,`Output format: yaml or json (default: yaml)`,`yaml`).option(`-o, --output-file <output-file>`,`File to write the output to`).option(`--builtin`,`Use the builtin (StackOne) version of the connector`).option(`--custom`,`Use the custom (organization) version of the connector`).option(`--owner <owner>`,`Owner to use for disambiguating connector versions`).description(`Get a connector from the StackOne registry`).action(e=>{[e.builtin,e.custom,e.owner].filter(Boolean).length>1&&(y.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),i.execute({profile:e.profile,connector:e.connector,accountId:e.accountId,format:e.format,outputFile:e.outputFile,apiUrl:e.apiUrl,apiKey:e.apiKey,owner:e.builtin?`builtin`:e.custom?`custom`:e.owner})}),this.program.command(`pull`).option(`-c, --connector <connector>`,`Connector identifier in format provider_key@version or provider_key`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-o, --output <path>`,`Output directory for the connectors files (default: ./connectors)`).option(`--builtin`,`Use the builtin (StackOne) version of the connector`).option(`--custom`,`Use the custom (organization) version of the connector`).option(`--owner <owner>`,`Owner to use for disambiguating connector versions`).description(`Pull a connector configuration from StackOne registry to local filesystem`).action(e=>{[e.builtin,e.custom,e.owner].filter(Boolean).length>1&&(y.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),n.execute({profile:e.profile,connector:e.connector,outputPath:e.output,apiUrl:e.apiUrl,apiKey:e.apiKey,owner:e.builtin?`builtin`:e.custom?`custom`:e.owner})}),this.program.command(`validate`).option(`-w, --watch`,`Run in watch mode`).addArgument(new E(`<path>`,`Connector file or directory with connectors to validate`)).description(`Validate a StackOne connector`).action((e,t)=>{a.execute({watchMode:t.watch,fileOrDir:e})}),this.program.command(`run`).option(`--connector <connector>`,`Connector file, inline YAML, or identifier (provider_key@version or provider_key for latest)`).option(`--action <action>`,`Action to execute on the connector (path to file or inline string action code)`).option(`--action-id <action-id>`,`Action ID to execute on the connector`).option(`--account <account>`,`Account details to use for running the connector (path to file or inline string account data)`).option(`--account-id <account-id>`,`Account ID to use for running the connector against (fetches connector from API if --connector not provided)`).option(`--params <params>`,`Action parameters (path to file or inline string with JSON parameters)`).option(`--credentials <credentials>`,`Credentials to use (path to file or inline string with JSON credentials)`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-o, --output-file <output-file>`,`File to write the output to`).option(`-d, --debug`,`Enables debug mode to include more details in the action execution output`).option(`--builtin`,`Use the builtin (StackOne) version of the connector`).option(`--custom`,`Use the custom (organization) version of the connector`).option(`--owner <owner>`,`Owner to use for disambiguating connector versions`).option(`--sync-full`,`Walk the action's dataSync config to exhaustion, as a full sync would (reads only, indexes nothing)`).option(`--sync-incremental [checkpoint]`,`Test incremental sync. With a checkpoint value, resumes from it; without one, runs a full pass first and resumes from the checkpoint it produces`).option(`--sync-max-pages <pages>`,`Cap pages for a sync run (clamped to the production limit of 2000)`,Ii).option(`--sync-page-size <size>`,`Override the provider page size for a sync run, so a small sample account still produces multiple pages (page and offset strategies only)`,Ii).description(`Run a connector action`).action(e=>{[e.builtin,e.custom,e.owner].filter(Boolean).length>1&&(y.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),e.syncFull&&e.syncIncremental!==void 0&&(y.error(`--sync-full and --sync-incremental are mutually exclusive. Please provide only one.`),process.exit(1)),e.syncIncremental===``&&(y.error(`--sync-incremental was given an empty checkpoint value. Omit the value to derive one from a full pass, or pass a real checkpoint.`),process.exit(1)),e.syncMaxPages!==void 0&&(Number.isNaN(e.syncMaxPages)||e.syncMaxPages<1)&&(y.error(`--sync-max-pages must be a positive integer.`),process.exit(1)),e.syncPageSize!==void 0&&(Number.isNaN(e.syncPageSize)||e.syncPageSize<1)&&(y.error(`--sync-page-size must be a positive integer.`),process.exit(1)),e.syncPageSize!==void 0&&!e.syncFull&&!e.syncIncremental&&(y.error(`--sync-page-size only applies to --sync-full or --sync-incremental.`),process.exit(1)),p.execute({connector:e.connector,action:e.action,actionId:e.actionId,account:e.account,accountId:e.accountId,params:e.params,credentials:e.credentials,profile:e.profile,outputFile:e.outputFile,debug:e.debug,apiUrl:e.apiUrl,apiKey:e.apiKey,owner:e.builtin?`builtin`:e.custom?`custom`:e.owner,syncFull:e.syncFull,syncIncremental:e.syncIncremental,syncMaxPages:e.syncMaxPages,syncPageSize:e.syncPageSize})});let h=this.program.command(`agent`).description(`StackOne agent commands`);h.command(`setup`).option(`-g, --global`,`Global only: auth + MCP server (no connector skills/guide)`).option(`-l, --local`,`Local: auth + .mcp.json + connector skills (.claude/) and guide (CLAUDE.md)`).option(`--path <dir>`,`Target project path for local setup (defaults to the current directory)`).option(`--legacy`,`Use email/password login instead of browser-based auth`).option(`--email <email>`,`Email for legacy login (or set STACKONE_EMAIL); requires --legacy`).option(`--password <password>`,`Password for legacy login (or set STACKONE_PASSWORD); requires --legacy. Prefer --password-stdin`).option(`--password-stdin`,`Read password for legacy login from stdin; requires --legacy`).description(`Set up the StackOne agent — prompts for global vs local when neither flag is given`).action(async e=>{e.global&&e.local&&(y.error(`--global and --local are mutually exclusive. Please provide only one.`),process.exit(1));let t=e.email!==void 0,n=e.password!==void 0,r=e.passwordStdin===!0;n&&r&&(y.error(`--password and --password-stdin are mutually exclusive. Please provide only one.`),process.exit(1));let i=t||n||r;i&&!e.legacy&&(y.error(`--email, --password, and --password-stdin require --legacy.`),process.exit(1)),t&&e.email.trim()===``&&(y.error(`--email cannot be empty.`),process.exit(1)),n&&e.password===``&&(y.error(`--password cannot be empty.`),process.exit(1)),r&&(t||process.env.STACKONE_EMAIL?.trim()||(y.error(`--password-stdin requires --email or STACKONE_EMAIL (stdin is consumed for the password, so email cannot be prompted).`),process.exit(1)));let a={email:e.email,password:e.password,passwordFromStdin:r},c=!!process.stdin.isTTY;if(c&&!e.legacy&&!i){let t=await xr({initialMode:e.global?`global`:e.local?`local`:null,pathFlag:e.path});process.exit(t.status===`error`?1:0)}let l=c&&!i;!e.global&&!e.local&&!l&&y.log(T.dim(`No interactive terminal detected — defaulting to global setup. Run in a terminal for the prompt, or pass --local (with --path) / --global.`));let u=Pn(e.global,e.local,l);if(u===null&&(u=await vr()),u===`local`){let t=Fn(e.path,l);t===null&&(t=await br(process.cwd())),await s.execute({legacy:!!e.legacy,credentials:a,targetPath:t})}else await o.execute({legacy:!!e.legacy,credentials:a})}),h.command(`cleanup`).description(`Remove all API keys and credentials from configurations`).action(()=>{c.execute()}),h.command(`run`).description(`Run the agent once with a prompt (non-interactive)`).argument(`<prompt>`,`What to do`).option(`-m, --mode <mode>`,`Mode: build, test, or research`,`build`).option(`--max-turns <n>`,`Max agent turns`,`25`).option(`-v, --verbose`,`Verbose output`).action(async(e,t)=>{let n=[`build`,`test`,`research`],r=t.mode??`build`;n.includes(r)||(y.error(`${T.red(`Invalid mode:`)} ${T.white(r)}. Valid modes are: ${n.join(`, `)}.`),process.exit(1));let i=t.maxTurns?parseInt(String(t.maxTurns),10):void 0;await u.execute({prompt:String(e),mode:r,maxTurns:i!==void 0&&!isNaN(i)?i:void 0,verbose:t.verbose})}),h.command(`skills`).description(`List available agent skills and optional recommendations by mode`).option(`-m, --mode <mode>`,`Show skills recommended for this mode`).action(async e=>{await d.execute({mode:e.mode})}),h.command(`sync`).description(`Sync the connector-building skills + guide into this project (.claude/ + CLAUDE.md)`).option(`--check`,`Report drift and exit non-zero instead of writing (CI guard)`).option(`--plugin-dir <path>`,`Override the agent-harness plugin dir (e.g. point at a checkout in CI/benchmarks)`).action(async e=>{await f.execute({check:!!e.check,pluginDir:e.pluginDir})}),h.command(`chat`).option(`-m, --mode <mode>`,`Mode: build, test, or research`,`build`).option(`-c, --connector <name>`,`Connector name`).option(`-a, --action <name>`,`Action name`).option(`-g, --goal <goal>`,`Initial goal/message`).option(`-t, --temperature <number>`,`Temperature (0-1, default: 0.5)`,parseFloat).option(`-v, --verbose`,`Enable verbose logging`).description(`Start an interactive chat session with the agent (use /commands in chat)`).action(async e=>{let t=[`build`,`test`,`research`];e.mode&&!t.includes(e.mode)&&(y.error(`❌ Error: Invalid mode "${e.mode}". Must be one of: ${t.join(`, `)}`),process.exit(1)),e.temperature!==void 0&&(isNaN(e.temperature)&&(y.error(`❌ Error: Temperature must be a valid number`),process.exit(1)),(e.temperature<0||e.temperature>1)&&(y.error(`❌ Error: Temperature must be between 0 and 1`),process.exit(1))),l.execute({mode:e.mode,connector:e.connector,action:e.action,goal:e.goal,temperature:e.temperature,verbose:e.verbose})}),this.program.command(`update`).option(`-f, --force`,`Force reinstall even if already on latest version`).description(`Update the CLI to the latest version`).action(e=>{m.execute({force:e.force})}),this.program.command(`version`).description(`Show version information`).action(async()=>{y.log(`${T.inverse.greenBright(`StackOne`)} ${T.grey(`CLI`)} ${T.whiteBright(this.version)}`),zi(!0),process.exit(0)})}run(){process.argv.includes(`version`)||zi(),this.program.parse(process.argv)}};export{Gi as t};
174
+ `)}`;return this.#i(r)};#o=(e,t,n)=>{let r=e;try{r=G.readFileSync(e,`utf-8`)}catch{}try{let e=vi.parse(JSON.parse(r));return{providerKey:t,providerVersion:n,authConfigKey:e.auth_config_key,environment:e.environment,organizationId:e.organization_id,secureId:e.account_id,projectSecureId:e.project_id}}catch(e){let t=[];try{t=JSON.parse(e.message)}catch{}y.error(`Failed to parse account information`),x(t,!1),t.length===0&&y.log(e.message),process.exit(1)}};#s=e=>!e.includes(`/`)&&!e.includes(`\\`)&&!e.endsWith(`.yaml`)&&!e.endsWith(`.yml`)?e.includes(`@`)?e.split(`@`).length===2:!0:!1;#c=e=>e.includes(`@`)?e:`${e}@latest`;#l=async(e,n,i,a)=>{(J(e)||J(n)||J(i))&&(y.error(`Connector identifier, API URL, and API key are required to fetch connector from registry.`),process.exit(1));let o=q();try{o.text=`Fetching connector ${t(e)} from registry...`,o.start();let r=Buffer.from(i).toString(`base64`),s=a?`?owner=${encodeURIComponent(a)}`:``,c=await fetch(`${n}/registry/connectors/${e}${s}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});if(o.stop(),c.status===409){a&&(await b(c,`Failed to fetch connector ${t(e)} from registry`),process.exit(1));let i=await Rr(e,(await c.json()).availableOwners??[]);o.text=`Fetching connector ${t(e)} from registry...`,o.start();let s=await fetch(`${n}/registry/connectors/${e}?owner=${encodeURIComponent(i)}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});o.stop(),s.ok||(await b(s,`Failed to fetch connector ${t(e)} from registry`),process.exit(1));let l=await s.text(),u=this.#i(l);return y.success(`Fetched connector ${t(u.key)}@${t(u.version)} from registry`),u}c.ok||(await b(c,`Failed to fetch connector ${t(e)} from registry`),process.exit(1));let l=await c.text(),u=this.#i(l);return y.success(`Fetched connector ${t(u.key)}@${t(u.version)} from registry`),u}catch(i){o.stop(),y.error(`Failed to fetch connector ${t(e)} from registry: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}};#u=async(e,n,i)=>{(J(e)||J(n)||J(i))&&(y.error(`Account ID, API URL, and API key are required to fetch connector`),process.exit(1));let a=q();try{a.text=`Fetching connector for account ${t(e)} from API...`,a.start();let r=Buffer.from(i).toString(`base64`),o=await fetch(`${n}/accounts/${e}/connector`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});a.stop(),o.ok||(await b(o,`Failed to fetch connector`),process.exit(1));let s=await o.text(),c=this.#i(s);return y.success(`Fetched connector ${t(c.key)}@${t(c.version)} for account ${t(e)}`),c}catch(e){a.stop(),y.error(`Failed to fetch connector: ${e.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}};#d=async(e,n,i)=>{(J(e)||J(n)||J(i))&&(y.error(`Account ID, API URL, and API key are required to fetch account information.`),process.exit(1));let a=q();try{a.text=`Fetching account ${t(e)} information from API...`,a.start();let r=Buffer.from(i).toString(`base64`),o=await fetch(`${n}/accounts/${e}/credentials`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});a.stop(),o.ok||(await b(o,`Failed to fetch account ${t(e)} information`),process.exit(1));let s=await o.json();return y.success(`Fetched account ${t(e)} information from project ${t(s.project_id)}`),{providerKey:s.provider_key,providerVersion:s.provider_version,authConfigKey:s.auth_config_key,environment:s.environment,organizationId:s.organization_id,secureId:s.account_id,projectSecureId:s.project_id,credentials:s.credentials}}catch(i){a.stop(),y.error(`Failed to fetch account ${t(e)} information: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}};#f=e=>{let t=e;try{t=G.readFileSync(e,`utf-8`)}catch{}try{return yi.parse(JSON.parse(t))}catch(e){let t=[];try{t=JSON.parse(e.message)}catch{}y.error(`Failed to parse credentials`),x(t,!1),t.length===0&&y.log(e.message),process.exit(1)}};#p=(e,n)=>{let r=e;try{r=G.readFileSync(e,`utf-8`)}catch{}try{return bi.parse(JSON.parse(r))}catch(e){let r=[];try{r=JSON.parse(e.message)}catch{}y.error(`Invalid parameters for action ${t(n)}.`),x(r,!1),r.length===0&&y.log(e.message),process.exit(1)}};async#m({connector:e,actionId:n,account:r,pathParams:i={},queryParams:a={},body:s={},headers:c={}}){try{let l=await it({mode:`action_id`,actionId:n,account:r,connector:e,pathParams:i,queryParams:a,body:s,headers:c,getHttpClient:async()=>new ft});if(l.response?.successful){let e={...this.#h(a,l.steps),...We(l.outputs)?l.outputs:{data:l.outputs}};return{statusCode:l.response?.statusCode,output:e}}else{let r=l.response?.message??`An error occurred while processing the request`;y.error(`Action ID ${t(n)} from connector ${t(e.key)}@${t(e.version)} failed with status ${l.response?.statusCode}: ${r}`);let i={...this.#h(a,l.steps)};Object.keys(i).length>0&&(y.log(`${T.yellow.inverse(` EXECUTION DETAILS `)}`),o(i)),process.exit(1)}}catch(e){this.#g(e)}}#h(e,t){return e?.debug===`true`?{debug:{steps:t}}:{}}#g(e){let t=e;switch(J(t.errorType)&&(y.error(`An unknown error occurred`),y.log(`${e instanceof Error?e.message:String(e)}`),process.exit(1)),t.errorType){case`MISSING_ACTION_ERROR`:y.error(`The specified action was not found: ${t.message}`);break;case`INVALID_ACTION_INPUTS_ERROR`:let e=t;y.error(`Invalid action inputs`),x(e.validationErrors,!1);break;case`INVALID_CURSOR_ERROR`:y.error(`Invalid cursor: ${t.message}`);break;default:y.error(`An error occurred: ${t.message}`)}process.exit(1)}};const Ci=pt(we);var wi=class{constructor(){this.packageName=`@stackone/cli`,this.spinner=q(),this.currentVersion=$t()}async execute(e={}){this.spinner.text=`Checking for updates...`,this.spinner.start();try{let t=await this.getLatestVersion();this.spinner.stop(),t||(y.error(`Failed to check for updates`),process.exit(1)),this.isNewerVersion(t,this.currentVersion)?(y.box(`New version available: ${T.yellow(this.currentVersion)} → ${T.green(t)}`),await this.performUpdate(t)):e.force?(y.warn(`No updates available, but forcing reinstall...`),await this.performUpdate(t)):y.success(`You are already on the latest version (${this.currentVersion})`),process.exit(0)}catch(e){this.spinner.stop(),y.error(`Error while trying to update StackOne CLI: ${e?.message??`Unknown error`}`),process.exit(1)}}async getLatestVersion(){try{let{stdout:e}=await Ci(`npm view ${this.packageName} version`,{encoding:`utf-8`});return e.trim()}catch{return null}}isNewerVersion(e,t){return dt.gt(e,t)}async performUpdate(e){this.spinner.text=`Updating to latest version (${t(e)})...`,this.spinner.start();let n=`npm install -g ${this.packageName}@latest`;try{await Ci(n,{encoding:`utf-8`}),this.spinner.stop(),y.success(`StackOne CLI updated successfully to latest version (${t(e)})`)}catch{throw this.spinner.stop(),Error(`Failed to install update. Please try manually: ${n}`)}}};const Ti=e=>e===null?!0:Object.values(e).some(e=>e!==null),Ei=()=>{y.log(`${T.gray.inverse(` CONNECTORS VALIDATION `)} ${T.yellow.inverse(` WATCH MODE `)}\n`)};var Di=class{async execute(e){let{watchMode:t,fileOrDir:n}=e,r=q(`Watching for file changes... ${T.gray(`(press "q" to quit)`)}`);if(!n)return;let i=Ie(n);try{await ht(i)}catch{y.error(`The specified path does not exist: ${i}\n`),process.exit(1)}if(t){v();let e={},{watch:t}=await import(`chokidar`),n=(await import(`readline`)).createInterface({input:process.stdin,output:process.stdout});process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding(`utf8`);let a=()=>{s.close(),r.stop(),n.close(),y.log(T.grey(`
175
+ Exiting watch mode...`)),process.exit(0)};Ei(),y.start(`Validating connectors...`);let o=await ji(i);e=Oi(e,o||{}),ki(e,i),r.start();let s=t(i,{persistent:!0,ignoreInitial:!0}),c=async t=>{if(!t.endsWith(`.s1.yaml`)&&!t.endsWith(`s1.partial.yaml`))return;let n=t.endsWith(`s1.partial.yaml`)?await Ni(t):[t];if(!(!n||n.length===0)){v(),r.stop(),Ei(),y.log(T.gray(`File change detected: ${t}`)),y.start(`Validating connectors...`);for(let t of n){let n=await ji(t);e=Oi(e,n||{})}ki(e,i),r.start()}};s.on(`change`,async e=>await c(e)),process.stdin.on(`data`,e=>{e.toString()===`q`&&a()}),process.on(`SIGINT`,()=>{a()})}else{let e=await ji(i,y);process.exit(Ti(e)?1:0)}}};const Oi=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]=r;return e},ki=(e,n)=>{v(),Ei();let r=0,i=0;for(let[n,a]of Object.entries(e))a===null?r++:(y?.error(`Connector ${t(n)} is not valid`),x(a,!0),i++);y.log(``),y.log(T.blue.inverse(` Validation Summary `)),y.log(`Connectors path: ${t(n)}`),y.log(`${r===0?T.red(`0`):T.green(r)} valid, ${i===0?T.green(`0`):T.red(i)} invalid connectors\n`)},Ai=async e=>{let t=[],n=await mt(e);for(let r of n){let n=Fe(e,r),i=await ht(n);i.isDirectory()?t.push(...await Ai(n)):i.isFile()&&r.endsWith(`.s1.yaml`)&&t.push(n)}return t},ji=async(e,r)=>{let i=await ht(e),a={};if(i.isDirectory()){let i=await Ai(e);if(i.length===0)return r?.error(`No StackOne connector found in ${n(e)}`),r?.log(`Connector files need to have the extension ${t(`*.s1.yaml`)}`),null;let o=0,s=0;for(let e of i){let t=await Mi(e,r);t===null?o++:(r?.log(``),s++),a[e]=t}return r?.log(``),r?.log(T.blue.inverse(` Validation Summary `)),r?.log(`${o===0?T.red(`0`):T.green(o)} valid, ${s===0?T.green(`0`):T.red(s)} invalid connectors`),a}else if(i.isFile()&&e.endsWith(`s1.yaml`))return a[e]=await Mi(e,r),a;else if(i.isFile()&&e.endsWith(`partial.yaml`)){r?.error(`Partial connector files cannot be validated directly`),r?.log(`The file ${n(e)} is a partial connector file.`);let i=await Ni(e);return i&&i?.length>0&&r?.log(`Did you mean ${t(i[0])}?`),null}else return r?.error(`No StackOne connector found in ${n(e)}`),r?.log(`Connector files need to have the extension ${t(`*.s1.yaml`)}`),null},Mi=async(e,n)=>{let r=at(nt(e)),i=r?.errors??[];if(r.success){let r=e.split(`/`).pop()||e;return n?.success(`Connector ${t(r)} is valid!`),null}else if(i.length>0)return n?.error(`Connector ${t(e)} is not valid`),n&&x(i,!0),i;else return n?.error(`Connector ${t(e)} is not valid. Please check the file for errors`),[]},Ni=async e=>{let t=Pe(e);try{return(await mt(t)).filter(e=>e.endsWith(`.s1.yaml`))?.map(e=>Fe(t,e))}catch{}};function Pi(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 Fi(){return process.env.AI_TELEMETRY_URL?process.env.AI_TELEMETRY_URL:[process.env.AUTH_SERVER_URL,process.env.STACKONE_API_URL].some(Pi)?`https://ai-telemetry.stackone-dev.com`:`https://ai-telemetry.stackone.com`}function Ii(){let e=process.env.STACKONE_AGENT_TOKEN,t=process.env.LANGSMITH_PROJECT||`stackone-agent-cli`;if(process.env.AI_TELEMETRY_URL=Fi(),e)try{ce({apiKey:e,projectName:t}),process.env.VERBOSE&&console.log(`[Telemetry] Initialized for project:`,t)}catch(e){process.env.VERBOSE&&console.error(`[Telemetry] Failed to initialize:`,e)}}const Li=e=>{let t=e.trim();return/^\d+$/.test(t)?Number(t):NaN},Ri=R(I(),`.stackone`),zi=R(Ri,`version-check.json`),Bi=(e=!1)=>{let t=Wi(),n=Date.now();if(e||!t||n-t.lastCheckTime>1728e5){let e=Vi();e&&Hi(e)&&Ui(e),Gi({lastCheckTime:n})}},Vi=()=>{try{return De(`npm view @stackone/cli version`,{encoding:`utf-8`,stdio:[`pipe`,`pipe`,`pipe`],timeout:15e3}).trim()}catch{return null}},Hi=e=>{try{let t=$t();return dt.gt(e,t)}catch{return!1}},Ui=e=>{let t=$t(),n=`Update available: ${T.dim(t)} → ${T.green(e)}`,r=`\n\nRun ${T.cyan(`stackone update`)} to update`;y.box(n,r)},Wi=()=>{try{if(!N(zi))return null;let e=de(zi,`utf-8`);return JSON.parse(e)}catch{return null}},Gi=e=>{try{N(Ri)||ue(Ri,{recursive:!0}),me(zi,JSON.stringify(e,null,2),`utf-8`)}catch{}};var Ki=class{constructor(e=new ne,t=$t()){this.program=e,this.version=t,Ii(),this.setupProgram(),this.registerCommands()}setupProgram(){this.program.name(`stackone`).description(`StackOne CLI`).version(this.version,`-v, --version`)}registerCommands(){let e=new Hr,t=new qr,n=new Gr,r=new Ir,i=new Br,a=new Di,o=new On,s=new Cr,c=new fn,l=new dn,u=new An,d=new wr,f=new Or,p=new Si,m=new wi;this.program.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>process.stderr.write(e),outputError:(e,t)=>{t(T.red(e))}}),this.program.command(`init`).option(`-e, --env <environment>`,`Specify the environment for the configuration profile`).description(`Initialize & create a StackOne CLI configuration profile`).action(t=>{e.execute({environment:t.env})}),this.program.command(`push`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`--force`,`Force push the connector, bypassing version conflict checks`).addArgument(new E(`<path>`,`Connector file or directory to push`)).description(`Push a connector to the StackOne registry`).action((e,n)=>{t.execute({profile:n.profile,fileOrDir:e,apiUrl:n.apiUrl,apiKey:n.apiKey,force:n.force})}),this.program.command(`drop`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).addArgument(new E(`<connector>`,`Connector identifier in format provider_key@version`)).description(`Drop a connector from the StackOne registry`).action((e,t)=>{r.execute({profile:t.profile,connector:e,apiUrl:t.apiUrl,apiKey:t.apiKey})}),this.program.command(`get`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-c, --connector <connector>`,`Connector identifier in format provider_key@version or provider_key (defaults to latest)`).option(`--account-id <account-id>`,`Account ID to fetch connector from`).option(`-f, --format <format>`,`Output format: yaml or json (default: yaml)`,`yaml`).option(`-o, --output-file <output-file>`,`File to write the output to`).option(`--builtin`,`Use the builtin (StackOne) version of the connector`).option(`--custom`,`Use the custom (organization) version of the connector`).option(`--owner <owner>`,`Owner to use for disambiguating connector versions`).description(`Get a connector from the StackOne registry`).action(e=>{[e.builtin,e.custom,e.owner].filter(Boolean).length>1&&(y.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),i.execute({profile:e.profile,connector:e.connector,accountId:e.accountId,format:e.format,outputFile:e.outputFile,apiUrl:e.apiUrl,apiKey:e.apiKey,owner:e.builtin?`builtin`:e.custom?`custom`:e.owner})}),this.program.command(`pull`).option(`-c, --connector <connector>`,`Connector identifier in format provider_key@version or provider_key`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-o, --output <path>`,`Output directory for the connectors files (default: ./connectors)`).option(`--builtin`,`Use the builtin (StackOne) version of the connector`).option(`--custom`,`Use the custom (organization) version of the connector`).option(`--owner <owner>`,`Owner to use for disambiguating connector versions`).description(`Pull a connector configuration from StackOne registry to local filesystem`).action(e=>{[e.builtin,e.custom,e.owner].filter(Boolean).length>1&&(y.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),n.execute({profile:e.profile,connector:e.connector,outputPath:e.output,apiUrl:e.apiUrl,apiKey:e.apiKey,owner:e.builtin?`builtin`:e.custom?`custom`:e.owner})}),this.program.command(`validate`).option(`-w, --watch`,`Run in watch mode`).addArgument(new E(`<path>`,`Connector file or directory with connectors to validate`)).description(`Validate a StackOne connector`).action((e,t)=>{a.execute({watchMode:t.watch,fileOrDir:e})}),this.program.command(`run`).option(`--connector <connector>`,`Connector file, inline YAML, or identifier (provider_key@version or provider_key for latest)`).option(`--action <action>`,`Action to execute on the connector (path to file or inline string action code)`).option(`--action-id <action-id>`,`Action ID to execute on the connector`).option(`--account <account>`,`Account details to use for running the connector (path to file or inline string account data)`).option(`--account-id <account-id>`,`Account ID to use for running the connector against (fetches connector from API if --connector not provided)`).option(`--params <params>`,`Action parameters (path to file or inline string with JSON parameters)`).option(`--credentials <credentials>`,`Credentials to use (path to file or inline string with JSON credentials)`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-o, --output-file <output-file>`,`File to write the output to`).option(`-d, --debug`,`Enables debug mode to include more details in the action execution output`).option(`--builtin`,`Use the builtin (StackOne) version of the connector`).option(`--custom`,`Use the custom (organization) version of the connector`).option(`--owner <owner>`,`Owner to use for disambiguating connector versions`).option(`--sync-full`,`Walk the action's dataSync config to exhaustion, as a full sync would (reads only, indexes nothing)`).option(`--sync-incremental [checkpoint]`,`Test incremental sync. With a checkpoint value, resumes from it; without one, runs a full pass first and resumes from the checkpoint it produces`).option(`--sync-max-pages <pages>`,`Cap pages for a sync run (clamped to the production limit of 2000)`,Li).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)`,Li).description(`Run a connector action`).action(e=>{[e.builtin,e.custom,e.owner].filter(Boolean).length>1&&(y.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),e.syncFull&&e.syncIncremental!==void 0&&(y.error(`--sync-full and --sync-incremental are mutually exclusive. Please provide only one.`),process.exit(1)),e.syncIncremental===``&&(y.error(`--sync-incremental was given an empty checkpoint value. Omit the value to derive one from a full pass, or pass a real checkpoint.`),process.exit(1)),e.syncMaxPages!==void 0&&(Number.isNaN(e.syncMaxPages)||e.syncMaxPages<1)&&(y.error(`--sync-max-pages must be a positive integer.`),process.exit(1)),e.syncPageSize!==void 0&&(Number.isNaN(e.syncPageSize)||e.syncPageSize<1)&&(y.error(`--sync-page-size must be a positive integer.`),process.exit(1)),e.syncPageSize!==void 0&&!e.syncFull&&!e.syncIncremental&&(y.error(`--sync-page-size only applies to --sync-full or --sync-incremental.`),process.exit(1)),p.execute({connector:e.connector,action:e.action,actionId:e.actionId,account:e.account,accountId:e.accountId,params:e.params,credentials:e.credentials,profile:e.profile,outputFile:e.outputFile,debug:e.debug,apiUrl:e.apiUrl,apiKey:e.apiKey,owner:e.builtin?`builtin`:e.custom?`custom`:e.owner,syncFull:e.syncFull,syncIncremental:e.syncIncremental,syncMaxPages:e.syncMaxPages,syncPageSize:e.syncPageSize})});let h=this.program.command(`agent`).description(`StackOne agent commands`);h.command(`setup`).option(`-g, --global`,`Global only: auth + MCP server (no connector skills/guide)`).option(`-l, --local`,`Local: auth + .mcp.json + connector skills (.claude/) and guide (CLAUDE.md)`).option(`--path <dir>`,`Target project path for local setup (defaults to the current directory)`).option(`--legacy`,`Use email/password login instead of browser-based auth`).option(`--email <email>`,`Email for legacy login (or set STACKONE_EMAIL); requires --legacy`).option(`--password <password>`,`Password for legacy login (or set STACKONE_PASSWORD); requires --legacy. Prefer --password-stdin`).option(`--password-stdin`,`Read password for legacy login from stdin; requires --legacy`).description(`Set up the StackOne agent — prompts for global vs local when neither flag is given`).action(async e=>{e.global&&e.local&&(y.error(`--global and --local are mutually exclusive. Please provide only one.`),process.exit(1));let t=e.email!==void 0,n=e.password!==void 0,r=e.passwordStdin===!0;n&&r&&(y.error(`--password and --password-stdin are mutually exclusive. Please provide only one.`),process.exit(1));let i=t||n||r;i&&!e.legacy&&(y.error(`--email, --password, and --password-stdin require --legacy.`),process.exit(1)),t&&e.email.trim()===``&&(y.error(`--email cannot be empty.`),process.exit(1)),n&&e.password===``&&(y.error(`--password cannot be empty.`),process.exit(1)),r&&(t||process.env.STACKONE_EMAIL?.trim()||(y.error(`--password-stdin requires --email or STACKONE_EMAIL (stdin is consumed for the password, so email cannot be prompted).`),process.exit(1)));let a={email:e.email,password:e.password,passwordFromStdin:r},c=!!process.stdin.isTTY;if(c&&!e.legacy&&!i){let t=await Sr({initialMode:e.global?`global`:e.local?`local`:null,pathFlag:e.path});process.exit(t.status===`error`?1:0)}let l=c&&!i;!e.global&&!e.local&&!l&&y.log(T.dim(`No interactive terminal detected — defaulting to global setup. Run in a terminal for the prompt, or pass --local (with --path) / --global.`));let u=Pn(e.global,e.local,l);if(u===null&&(u=await yr()),u===`local`){let t=Fn(e.path,l);t===null&&(t=await xr(process.cwd())),await s.execute({legacy:!!e.legacy,credentials:a,targetPath:t})}else await o.execute({legacy:!!e.legacy,credentials:a})}),h.command(`cleanup`).description(`Remove all API keys and credentials from configurations`).action(()=>{c.execute()}),h.command(`run`).description(`Run the agent once with a prompt (non-interactive)`).argument(`<prompt>`,`What to do`).option(`-m, --mode <mode>`,`Mode: build, test, or research`,`build`).option(`--max-turns <n>`,`Max agent turns`,`25`).option(`-v, --verbose`,`Verbose output`).action(async(e,t)=>{let n=[`build`,`test`,`research`],r=t.mode??`build`;n.includes(r)||(y.error(`${T.red(`Invalid mode:`)} ${T.white(r)}. Valid modes are: ${n.join(`, `)}.`),process.exit(1));let i=t.maxTurns?parseInt(String(t.maxTurns),10):void 0;await u.execute({prompt:String(e),mode:r,maxTurns:i!==void 0&&!isNaN(i)?i:void 0,verbose:t.verbose})}),h.command(`skills`).description(`List available agent skills and optional recommendations by mode`).option(`-m, --mode <mode>`,`Show skills recommended for this mode`).action(async e=>{await d.execute({mode:e.mode})}),h.command(`sync`).description(`Sync the connector-building skills + guide into this project (.claude/ + CLAUDE.md)`).option(`--check`,`Report drift and exit non-zero instead of writing (CI guard)`).option(`--plugin-dir <path>`,`Override the agent-harness plugin dir (e.g. point at a checkout in CI/benchmarks)`).option(`--buildtime-only`,`Skip interactive commands and skills — for unattended runs, which cannot answer their prompts`).action(async e=>{await f.execute({check:!!e.check,pluginDir:e.pluginDir,buildtimeOnly:!!e.buildtimeOnly})}),h.command(`chat`).option(`-m, --mode <mode>`,`Mode: build, test, or research`,`build`).option(`-c, --connector <name>`,`Connector name`).option(`-a, --action <name>`,`Action name`).option(`-g, --goal <goal>`,`Initial goal/message`).option(`-t, --temperature <number>`,`Temperature (0-1, default: 0.5)`,parseFloat).option(`-v, --verbose`,`Enable verbose logging`).description(`Start an interactive chat session with the agent (use /commands in chat)`).action(async e=>{let t=[`build`,`test`,`research`];e.mode&&!t.includes(e.mode)&&(y.error(`❌ Error: Invalid mode "${e.mode}". Must be one of: ${t.join(`, `)}`),process.exit(1)),e.temperature!==void 0&&(isNaN(e.temperature)&&(y.error(`❌ Error: Temperature must be a valid number`),process.exit(1)),(e.temperature<0||e.temperature>1)&&(y.error(`❌ Error: Temperature must be between 0 and 1`),process.exit(1))),l.execute({mode:e.mode,connector:e.connector,action:e.action,goal:e.goal,temperature:e.temperature,verbose:e.verbose})}),this.program.command(`update`).option(`-f, --force`,`Force reinstall even if already on latest version`).description(`Update the CLI to the latest version`).action(e=>{m.execute({force:e.force})}),this.program.command(`version`).description(`Show version information`).action(async()=>{y.log(`${T.inverse.greenBright(`StackOne`)} ${T.grey(`CLI`)} ${T.whiteBright(this.version)}`),Bi(!0),process.exit(0)})}run(){process.argv.includes(`version`)||Bi(),this.program.parse(process.argv)}};export{Ki as t};
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{t as e}from"./cliCore-BharJXXM.mjs";import"./agentConfig-BWQWMYKQ.mjs";import"./setupMigration-C1ShGzOu.mjs";import"./agentApiKey-CWXxJgCO.mjs";export{e as CLI};
1
+ import{t as e}from"./cliCore-B0uelpFO.mjs";import"./agentConfig-BWQWMYKQ.mjs";import"./setupMigration-C1ShGzOu.mjs";import"./agentApiKey-CWXxJgCO.mjs";export{e as CLI};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/cli",
3
- "version": "1.46.1",
3
+ "version": "1.47.0",
4
4
  "description": "StackOne Connect CLI tool",
5
5
  "type": "module",
6
6
  "main": "dist/index.mjs",
@@ -35,12 +35,12 @@
35
35
  "@clack/prompts": "0.11.0",
36
36
  "@stackone/agent-config": "1.4.0",
37
37
  "@stackone/agent-harness": "0.18.0",
38
- "@stackone/connect-sdk": "2.115.0",
39
- "@stackone/core": "3.28.2",
40
- "@stackone/defender": "0.7.4",
38
+ "@stackone/connect-sdk": "2.117.0",
39
+ "@stackone/core": "3.31.0",
40
+ "@stackone/defender": "0.8.2",
41
41
  "@stackone/expressions": "0.39.0",
42
- "@stackone/transport": "2.34.1",
43
- "@stackone/utils": "1.2.0",
42
+ "@stackone/transport": "2.35.0",
43
+ "@stackone/utils": "1.2.2",
44
44
  "chalk": "5.6.2",
45
45
  "chokidar": "5.0.0",
46
46
  "commander": "14.0.2",