@stackone/cli 1.23.2 → 1.24.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -0
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/cliCore-BY4hchrt.cjs +160 -0
- package/dist/cliCore-CnBmVgQy.mjs +160 -0
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +8 -7
- package/dist/cliCore-DCFUXreH.cjs +0 -160
- package/dist/cliCore-fJL5mI3_.mjs +0 -160
package/README.md
CHANGED
|
@@ -124,6 +124,9 @@ stackone pull --connector my-provider --profile <profile-label>
|
|
|
124
124
|
- `-p, --profile <label>` - Configuration profile to use
|
|
125
125
|
- `--api-key <api-key>` - API key to use for authentication (alternative to using a profile)
|
|
126
126
|
- `--api-url <api-url>` - API URL to use (defaults to `https://api.stackone.com` if not specified)
|
|
127
|
+
- `--builtin` - Use the builtin (StackOne) version of the connector
|
|
128
|
+
- `--custom` - Use the custom (organization) version of the connector
|
|
129
|
+
- `--owner <owner>` - Explicitly specify the owner to disambiguate between multiple versions of the same connector
|
|
127
130
|
|
|
128
131
|
**Note:** You must provide either `--profile` or `--api-key`. If using `--api-key`, the `--api-url` option is optional and will default to the production API URL.
|
|
129
132
|
|
|
@@ -153,6 +156,24 @@ stackone pull --connector my-provider --profile <profile-label>
|
|
|
153
156
|
stackone pull --connector my-provider@1.0.0 --api-key your-api-key --api-url https://staging.api.stackone.com
|
|
154
157
|
```
|
|
155
158
|
|
|
159
|
+
5. **Pull builtin (StackOne) version:**
|
|
160
|
+
|
|
161
|
+
```bash
|
|
162
|
+
stackone pull --connector my-provider@1.0.0 --profile production --builtin
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
6. **Pull custom (organization) version:**
|
|
166
|
+
|
|
167
|
+
```bash
|
|
168
|
+
stackone pull --connector my-provider@1.0.0 --profile production --custom
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
7. **Pull with explicit owner:**
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
stackone pull --connector my-provider@1.0.0 --profile production --owner my-org
|
|
175
|
+
```
|
|
176
|
+
|
|
156
177
|
**Conflict Resolution:**
|
|
157
178
|
|
|
158
179
|
When pulling a connector that already exists locally, the command will:
|
|
@@ -247,6 +268,9 @@ stackone get --account-id acc_123 --profile <profile-label>
|
|
|
247
268
|
- `-p, --profile <label>` - Configuration profile to use
|
|
248
269
|
- `--api-key <api-key>` - API key to use for authentication (alternative to using a profile)
|
|
249
270
|
- `--api-url <api-url>` - API URL to use (defaults to `https://api.stackone.com` if not specified)
|
|
271
|
+
- `--builtin` - Use the builtin (StackOne) version of the connector
|
|
272
|
+
- `--custom` - Use the custom (organization) version of the connector
|
|
273
|
+
- `--owner <owner>` - Explicitly specify the owner to disambiguate between multiple versions of the same connector
|
|
250
274
|
|
|
251
275
|
**Note:**
|
|
252
276
|
|
|
@@ -291,6 +315,24 @@ stackone get --account-id acc_123 --profile <profile-label>
|
|
|
291
315
|
stackone get --connector my-provider@1.0.0 --api-key your-api-key --api-url https://staging.api.stackone.com
|
|
292
316
|
```
|
|
293
317
|
|
|
318
|
+
7. **Get builtin (StackOne) version:**
|
|
319
|
+
|
|
320
|
+
```bash
|
|
321
|
+
stackone get --connector my-provider@1.0.0 --profile production --builtin
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
8. **Get custom (organization) version:**
|
|
325
|
+
|
|
326
|
+
```bash
|
|
327
|
+
stackone get --connector my-provider@1.0.0 --profile production --custom
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
9. **Get with explicit owner:**
|
|
331
|
+
|
|
332
|
+
```bash
|
|
333
|
+
stackone get --connector my-provider@1.0.0 --profile production --owner my-org
|
|
334
|
+
```
|
|
335
|
+
|
|
294
336
|
**Features:**
|
|
295
337
|
|
|
296
338
|
- **Flexible authentication**: Use either a saved profile or provide credentials directly
|
|
@@ -349,6 +391,9 @@ stackone run --account-id <account-id> --api-key <your-api-key>
|
|
|
349
391
|
- `--api-url <api-url>` - API URL to use (defaults to `https://api.stackone.com` if not specified)
|
|
350
392
|
- `-o, --output-file <output-file>` - File path to write the execution output to (JSON format)
|
|
351
393
|
- `-d, --debug` - Enable debug mode to include execution steps and detailed information in the output
|
|
394
|
+
- `--builtin` - Use the builtin (StackOne) version of the connector when fetching from the registry
|
|
395
|
+
- `--custom` - Use the custom (organization) version of the connector when fetching from the registry
|
|
396
|
+
- `--owner <owner>` - Explicitly specify the owner to disambiguate between multiple versions of the same connector in the registry
|
|
352
397
|
|
|
353
398
|
**Note:** You must provide either `--profile` or `--api-key` when using `--account-id`. If using `--api-key`, the `--api-url` option is optional and will default to the production API URL.
|
|
354
399
|
|
|
@@ -420,6 +465,24 @@ stackone run --account-id <account-id> --api-key <your-api-key>
|
|
|
420
465
|
stackone run --account-id acc_123 --profile production --debug --output-file result.json
|
|
421
466
|
```
|
|
422
467
|
|
|
468
|
+
12. **Run with builtin (StackOne) connector version:**
|
|
469
|
+
|
|
470
|
+
```bash
|
|
471
|
+
stackone run --connector my-provider@1.0.0 --account-id acc_123 --profile production --builtin
|
|
472
|
+
```
|
|
473
|
+
|
|
474
|
+
13. **Run with custom (organization) connector version:**
|
|
475
|
+
|
|
476
|
+
```bash
|
|
477
|
+
stackone run --connector my-provider@1.0.0 --account-id acc_123 --profile production --custom
|
|
478
|
+
```
|
|
479
|
+
|
|
480
|
+
14. **Run with explicit owner for version disambiguation:**
|
|
481
|
+
|
|
482
|
+
```bash
|
|
483
|
+
stackone run --connector my-provider@1.0.0 --account-id acc_123 --profile production --owner my-org
|
|
484
|
+
```
|
|
485
|
+
|
|
423
486
|
**Account Format** (JSON):
|
|
424
487
|
|
|
425
488
|
When using `--account` with a file or inline JSON, use this structure:
|
package/dist/cli.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const e=require(`./agentConfig-BTZi_eTF.cjs`),t=require(`./cliCore-
|
|
2
|
+
const e=require(`./agentConfig-BTZi_eTF.cjs`),t=require(`./cliCore-BY4hchrt.cjs`);require(`./agentApiKey-D0XnbpYf.cjs`),require(`./setupMigration-CbFy6i_l.cjs`);let n=require(`dotenv`);process.env.DOTENV_CONFIG_QUIET=`true`,(0,n.config)(),new t.t().run();
|
package/dist/cli.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import"./agentConfig-D_NqqTkf.mjs";import{t as e}from"./cliCore-
|
|
2
|
+
import"./agentConfig-D_NqqTkf.mjs";import{t as e}from"./cliCore-CnBmVgQy.mjs";import"./agentApiKey-XBjE_ul4.mjs";import"./setupMigration-DsLJUF0a.mjs";import{config as t}from"dotenv";process.env.DOTENV_CONFIG_QUIET=`true`,t(),new e().run();export{};
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
const e=require(`./agentConfig-BTZi_eTF.cjs`),t=require(`./fileNames-Booqk8P6.cjs`),n=require(`./agentApiKey-D0XnbpYf.cjs`),r=require(`./setupMigration-CbFy6i_l.cjs`);let i=require(`chalk`);i=e._(i);let a=require(`commander`),o=require(`@stackone/agent-harness`),s=require(`node:fs`);s=e._(s);let c=require(`node:os`);c=e._(c);let l=require(`node:path`);l=e._(l);let u=require(`ink`),d=require(`react`);d=e._(d);let f=require(`ink-spinner`);f=e._(f);let p=require(`ora`);p=e._(p);let m=require(`fs`);m=e._(m);let h=require(`path`);h=e._(h);let g=require(`node:process`),_=require(`node:readline`),v=require(`inquirer`);v=e._(v);let y=require(`@stackone/utils`),b=require(`@clack/prompts`),x=require(`@stackone/connect-sdk`),S=require(`diff`),C=require(`readline`),w=require(`semver`);w=e._(w);let T=require(`@stackone/transport`),E=require(`node:child_process`),ee=require(`node:util`),te=require(`url`),D=require(`fs/promises`);function O(e){return e.replace(/\*\*\*(.+?)\*\*\*/g,`$1`).replace(/\*\*(.+?)\*\*/g,`$1`).replace(/\*(.+?)\*/g,`$1`).replace(/^#{1,6}\s+/gm,``).replace(/```([\s\S]*?)```/g,`$1`).replace(/`(.+?)`/g,`$1`).replace(/!\[([^\]]{0,500})\]\([^)]{1,2000}\)/g,`$1`).replace(/\[([^\]]{1,500})\]\([^)]{1,2000}\)/g,`$1`).replace(/^(?!_+$)[-*_]{3,}$/gm,``).replace(/^>\s+/gm,``).trim()}function k(e){return e===` `||e===` `||e===`
|
|
2
|
+
`||e===`\r`}function ne(e,t){let n=t-1;for(;n>=0&&k(e[n]);)n--;for(;n>=0&&!k(e[n]);)n--;return n+1}function re(e,t){let n=t;for(;n<e.length&&k(e[n]);)n++;for(;n<e.length&&!k(e[n]);)n++;return n}const ie={type:`header`};function A(e){return e.filter(e=>!(e.role===`system`&&e.content.startsWith(`TOOL_START:`)))}const ae=({title:e,mode:t,connector:n,action:r,onSubmit:i,onExit:a,onStop:o,messages:s,currentToolCalls:c=[],isThinking:l=!1,isComplete:p=!1,error:m,isInterrupted:h=!1,commandHistory:g=[],streamingText:_=``,usage:v,detailViewData:y=null,onCloseDetailView:b,onResumeConversation:x,onToggleTrust:S,onRewindTo:C,spawnedSubagentActive:w=!1,spawnedSubagentName:T=`Subagent`,spawnedSubagentComplete:E=!1,queuedMessages:ee=[],isProcessingQueue:te=!1,initInfo:D,pendingDeleteConfirmation:k=null,onConfirmDelete:ae,lastSubmittedUserContent:oe,lastSubmittedUserTimestamp:se,slashCommands:ce=[]})=>{let{exit:le}=(0,u.useApp)(),[j,M]=(0,d.useState)(``),[N,P]=(0,d.useState)(0),F=(0,d.useRef)(0),[ue,de]=(0,d.useState)(!0),I=(0,d.useRef)(s),[fe,L]=(0,d.useState)(-1),pe=(0,d.useRef)(g),me=(0,d.useRef)(``),[R,he]=(0,d.useState)([]),[ge,z]=(0,d.useState)(0),[B,V]=(0,d.useState)(0),[H,U]=(0,d.useState)(!1),[W,G]=(0,d.useState)(!1),[K,_e]=(0,d.useState)(!1),ve=(0,d.useRef)(``),[q,ye]=(0,d.useState)(1),[J,Y]=(0,d.useState)(null),[X,be]=(0,d.useState)(1),[Z,xe]=(0,d.useState)(s.length===0);(0,d.useEffect)(()=>{s.length>0&&Z&&xe(!1)},[s.length,Z]);let Se=(0,d.useMemo)(()=>ce.map(e=>`/${e.name}`),[ce]);(0,d.useEffect)(()=>{I.current=s},[s]),(0,d.useEffect)(()=>{pe.current=g},[g]),(0,d.useEffect)(()=>{me.current=j,j.startsWith(`/`)?(he(Se.filter(e=>e.startsWith(j.toLowerCase()))),z(0)):(he([]),z(0))},[j]),(0,d.useEffect)(()=>{F.current=N},[N]),(0,d.useEffect)(()=>{if(y?.items){let e=Math.max(0,y.items.length-1);V(t=>Math.min(t,e))}},[y?.items?.length]),(0,u.useInput)((0,d.useCallback)((e,t)=>{let n=me.current,r=fe;if(t.escape&&(l||_||c.length>0)&&!y){o?.(),M(``),me.current=``,F.current=0,P(0),L(-1);return}if(t.escape&&w&&W&&!y){G(!1);return}if(t.escape&&K&&!w&&!y){_e(!1);return}if(k&&ae){if(t.escape||e.toLowerCase()===`n`){ye(1),ae(!1);return}if(e.toLowerCase()===`y`){ye(0),ae(!0);return}if(t.upArrow||t.downArrow){ye(e=>e===0?1:0);return}if(t.return){ae(q===0);return}return}if(y){if(J){if(t.escape||t.ctrl&&e===`c`){Y(null);return}if(t.leftArrow||t.rightArrow){be(e=>e===0?1:0);return}if(e.toLowerCase()===`y`){S&&S(J.path),Y(null);return}if(e.toLowerCase()===`n`){Y(null);return}if(t.return){X===0&&S&&S(J.path),Y(null);return}return}if(t.escape||t.ctrl&&e===`c`)if(H){U(!1);return}else{b?.(),V(0);return}if(t.upArrow&&!H){V(e=>e>0?e-1:y.items.length-1);return}if(t.downArrow&&!H){V(e=>e<y.items.length-1?e+1:0);return}if(t.ctrl&&e===`o`&&y.type===`trust`&&!J&&!H){let e=y.items[B];e?.path&&(Y({path:e.path,name:e.name}),be(1));return}if(t.return){if(H)return;if(y.type===`resume`){let e=y.items[B];e.messages&&x&&(x(e.messages),b?.(),V(0));return}if(y.type===`rewind`){let e=y.items[B];e.index!==void 0&&C&&(C(e.index),b?.(),V(0));return}U(!0);return}return}if(t.ctrl&&e===`o`){w?G(e=>!e):_e(e=>!e);return}if(t.ctrl&&e===`u`){M(``),F.current=0,P(0),L(-1);return}if(t.ctrl&&e===`c`||e===``)if(n.trim()){M(``),me.current=``,F.current=0,P(0),L(-1);return}else{a(),le();return}if(t.shift&&t.return){let e=F.current;M(t=>t.slice(0,e)+`
|
|
3
|
+
`+t.slice(e));let t=e+1;F.current=t,P(t);return}if(t.ctrl&&e===`a`){F.current=0,P(0);return}if(t.ctrl&&e===`e`){F.current=n.length,P(n.length);return}let s=e===`\x1Bb`||e===`b`&&(t.alt||t.meta)||e===`\x1B\x1B[D`||e===`\x1B[1;3D`||e===`\x1B[1;9D`||(t.alt||t.meta)&&t.leftArrow&&!t.ctrl&&!t.shift,u=e===`\x1Bf`||e===`f`&&(t.alt||t.meta)||e===`\x1B\x1B[C`||e===`\x1B[1;3C`||e===`\x1B[1;9C`||(t.alt||t.meta)&&t.rightArrow&&!t.ctrl&&!t.shift;if(s){let e=ne(n,F.current);F.current=e,P(e);return}if(u){let e=re(n,F.current);F.current=e,P(e);return}if(t.home||e===`\x1B[H`||e===`\x1BOH`){F.current=0,P(0);return}if(t.end||e===`\x1B[F`||e===`\x1BOF`){F.current=n.length,P(n.length);return}if(process.platform===`darwin`&&t.meta&&t.leftArrow&&!t.alt){F.current=0,P(0);return}if(process.platform===`darwin`&&t.meta&&t.rightArrow&&!t.alt){F.current=n.length,P(n.length);return}if(process.platform===`darwin`&&t.meta&&t.upArrow){F.current=0,P(0);return}if(process.platform===`darwin`&&t.meta&&t.downArrow){F.current=n.length,P(n.length);return}if(t.ctrl&&t.leftArrow&&process.platform!==`darwin`){let e=ne(n,F.current);F.current=e,P(e);return}if(t.ctrl&&t.rightArrow&&process.platform!==`darwin`){let e=re(n,F.current);F.current=e,P(e);return}let d=()=>{let e=process.stdout?.columns||80,t=Math.max(20,e-6),r=[],i=0;n.split(`
|
|
4
|
+
`).forEach((e,n)=>{let a=i,o=n===0?t-2:t;if(e.length===0)r.push({start:a,end:a});else{let n=0;for(;n<e.length;){let i=n===0?o:t;r.push({start:a+n,end:a+Math.min(n+i,e.length)}),n+=i}}i=a+e.length+1});let a=F.current,o=r.findIndex(e=>a>=e.start&&a<e.end);return o===-1&&r.length>0&&(o=r.findIndex(e=>a===e.end)),{rows:r,currentRow:Math.max(0,o)}};if(t.upArrow){if(R.length>0){z(e=>e>0?e-1:R.length-1);return}let e=pe.current;if(r>=0&&e.length>0){L(t=>{let n=Math.max(0,t-1),r=e[n]||``;return M(r),F.current=r.length,P(r.length),n});return}let{rows:t,currentRow:n}=d();if(n>0){let e=F.current-t[n].start,r=t[n-1],i=r.start+Math.min(e,r.end-r.start);F.current=i,P(i);return}if(e.length>0){L(t=>{let n=t<0?e.length-1:Math.max(0,t-1),r=e[n]||``;return M(r),F.current=r.length,P(r.length),n});return}return}if(t.downArrow){if(R.length>0){z(e=>e<R.length-1?e+1:0);return}let e=pe.current;if(r>=0&&e.length>0){L(t=>{let n=t>=e.length-1?-1:t+1,r=n<0?``:e[n]||``;return M(r),F.current=r.length,P(r.length),n});return}let{rows:t,currentRow:n}=d();if(n<t.length-1){let e=F.current-t[n].start,r=t[n+1],i=r.start+Math.min(e,r.end-r.start);F.current=i,P(i);return}return}if(t.return){if(R.length>0){let e=R[ge];he([]),z(0),M(``),F.current=0,P(0),ve.current=e,i(e);return}if(n.trim()){let e=n.trim();ve.current=e,i(e),M(``),me.current=``,F.current=0,P(0),L(-1)}return}if((t.backspace||t.delete)&&F.current>0){let e=F.current;M(t=>t.slice(0,e-1)+t.slice(e));let t=Math.max(0,e-1);F.current=t,P(t),L(-1);return}if(t.leftArrow&&!t.meta&&!t.alt&&!t.ctrl){let e=Math.max(0,F.current-1);F.current=e,P(e);return}if(t.rightArrow&&!t.meta&&!t.alt&&!t.ctrl){let e=Math.min(n.length,F.current+1);F.current=e,P(e);return}if(t.tab&&n.startsWith(`/`)){let e=Se.filter(e=>e.startsWith(j.toLowerCase()));if(e.length===1){let t=e[0].length;M(e[0]),F.current=t,P(t)}return}if(e){if(t.meta||t.alt||t.ctrl||!e.split(``).every(e=>{let t=e.charCodeAt(0);return t>=32&&t!==127||t===10||t===9}))return;let n=F.current;M(t=>t.slice(0,n)+e+t.slice(n));let r=n+e.length;F.current=r,P(r),L(-1)}},[i,a,le,j,N,fe,Se,R,ge,y,H,b,w,E,W,x,B,l,_,c,o,C,k,ae,q,s,K])),(0,d.useEffect)(()=>{p&&de(!1)},[p]);let Ce=`\x1B[38;2;0;175;102m`,Q=`\x1B[0m`,we=`${Ce} ╔═════════╗${Q} ▄▖▗ ▌ ▄▖ ▄▖ ▗ ${Ce}╔═════════╗${Q}
|
|
5
|
+
${Ce} ║ ┌────╚════╗${Q} ▚ ▜▘▀▌▛▘▙▘▌▌▛▌█▌ ▌▌▛▌█▌▛▌▜▘ ${Ce}║ ┌────╚════╗${Q}
|
|
6
|
+
${Ce} ╚════╗────┘ ║${Q} ▄▌▐▖█▌▙▖▛▖▙▌▌▌▙▖ ▛▌▙▌▙▖▌▌▐▖ ${Ce}╚════╗────┘ ║${Q}
|
|
7
|
+
${Ce} ╚═════════╝${Q} ▄▌ ${Ce}╚═════════╝${Q}`,$=A(s),Te=$.reduce((e,t,n)=>t.role===`user`?n:e,-1),Ee=(e,t)=>{let n=e.role===`system`&&e.content.startsWith(`TOOL:`),r=e.role===`system`&&e.content.startsWith(`TOOL_START:`),i=e.role===`user`?`white`:e.role===`assistant`||n||r?`#00AF66`:`gray`,a=e.role===`user`?`❯ You`:e.role===`assistant`?e.isSubagent?`⚡ Subagent`:`◆ StackOne Agent`:`ℹ System`,o=e.content;r&&(a=`🔧 Tool • ${e.content.split(`|||`)[1]||``}`,o=``);let s=!1;if(n){let t=e.content.split(`|||`),n=t[0].replace(`TOOL:`,``),r=t.length>=3&&t[1]||``,i=t.length>=3?t.slice(2).join(`|||`):t[1]||``;a=r?`🔧 Tool • ${n} • ${r}`:`🔧 Tool • ${n}`,K?o=i:i.length>200?(s=!0,o=i.slice(0,200)):o=i}let c=e.role===`user`,l=Te>=0&&t===Te,f=e.content||(l?ve.current:``)||(l&&g?.length?g[g.length-1]:``)||`(no content)`,p=c?f:O(o??``);return c?d.default.createElement(u.Box,{key:`msg-${e.timestamp.getTime()}-${t}`,marginBottom:1,flexDirection:`column`},d.default.createElement(u.Text,{bold:!0,color:i},`❯ You`,d.default.createElement(u.Text,{color:`gray`},` • `,e.timestamp.toLocaleTimeString())),d.default.createElement(u.Box,{paddingLeft:2},d.default.createElement(u.Text,{color:`white`,wrap:`wrap`},p))):d.default.createElement(u.Box,{key:`msg-${e.timestamp.getTime()}-${t}`,marginBottom:1,flexDirection:`column`},d.default.createElement(u.Text,{bold:!0,color:i},a,d.default.createElement(u.Text,{color:`gray`},` • `,e.timestamp.toLocaleTimeString())),o!==void 0&&o!==``&&d.default.createElement(u.Box,{paddingLeft:2,flexDirection:`column`},d.default.createElement(u.Text,{color:n?`gray`:void 0,italic:n,wrap:`wrap`},p),s&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0,italic:!0},`... (truncated, press Ctrl+O to expand)`))))};return d.default.createElement(u.Box,{flexDirection:`column`,padding:2},d.default.createElement(u.Static,{items:[ie]},()=>d.default.createElement(u.Box,{key:`static-header`,flexDirection:`column`,marginBottom:1},d.default.createElement(u.Text,null,we,`
|
|
8
|
+
`),d.default.createElement(u.Text,{dimColor:!0},`⚠️ Preview Feature: experimental; sessions monitored. Review outputs carefully.`),d.default.createElement(u.Text,null,`
|
|
9
|
+
`))),d.default.createElement(u.Box,{flexDirection:`column`,marginBottom:1},Z&&d.default.createElement(u.Box,{flexDirection:`column`,marginBottom:1},d.default.createElement(u.Text,{bold:!0},`StackOne Builder - AI agent for connector development`),d.default.createElement(u.Text,{dimColor:!0},`
|
|
10
|
+
`,`I can help you build connectors, add actions, test integrations, and answer questions about provider capabilities.`),d.default.createElement(u.Text,null,`
|
|
11
|
+
`,`What would you like to work on?`),d.default.createElement(u.Text,{dimColor:!0},`
|
|
12
|
+
`,`Examples:`),d.default.createElement(u.Text,{dimColor:!0},`
|
|
13
|
+
`,` • "Create a new connector for Datadog"`),d.default.createElement(u.Text,{dimColor:!0},` `,`• "Add a get_user action to the Slack connector"`),d.default.createElement(u.Text,{dimColor:!0},` `,`• "Test the list_events action using account acc_xyz123"`)),$.map((e,t)=>Ee(e,t))),d.default.createElement(u.Box,{flexDirection:`column`,marginBottom:1},d.default.createElement(d.default.Fragment,null,(w||E)&&d.default.createElement(u.Box,{marginBottom:0,marginTop:0,borderStyle:`single`,borderColor:`#00AF66`,paddingX:2,paddingY:1,flexDirection:`column`,height:W?`100%`:void 0},d.default.createElement(u.Text,{bold:!0,color:`#00AF66`},E?`✓`:`⚡`,` Subprocess:`,` `,T,` `,E?`(Complete)`:``,` `,W?`(Expanded)`:``),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},E?W?`Press Ctrl+O or ESC to collapse`:`Press Ctrl+O to expand`:W?`Running... Press Ctrl+O or ESC to collapse`:`Running... Press Ctrl+O to expand`)),W?d.default.createElement(d.default.Fragment,null,s.filter(e=>e.isSubagent&&!e.content.startsWith(`TOOL_START:`)).map((e,t)=>{let n=e.role===`system`&&e.content.startsWith(`TOOL:`),r=e.role===`assistant`?`⚡ Subagent`:`ℹ System`,i=e.content;if(n){let t=e.content.split(`|||`),n=t[0].replace(`TOOL:`,``),a=t.length>=3?t.slice(2).join(`|||`):t[1]||``;r=`🔧 Tool • ${n}`,i=a.slice(0,500),a.length>500&&(i+=`
|
|
14
|
+
... (truncated)`)}return d.default.createElement(u.Box,{key:`${e.timestamp.getTime()}-${t}-${e.role}-subagent`,marginTop:1,flexDirection:`column`},d.default.createElement(u.Text,{bold:!0,color:`#00AF66`},r,d.default.createElement(u.Text,{color:`gray`},` `,`•`,` `,e.timestamp.toLocaleTimeString())),d.default.createElement(u.Box,{paddingLeft:2},d.default.createElement(u.Text,{color:n?`gray`:`#00AF66`,dimColor:n,wrap:`wrap`},O(i))))}),!E&&!h&&l&&c.length===0&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{color:`#00AF66`},d.default.createElement(f.default,{type:`dots`})),d.default.createElement(u.Text,{dimColor:!0},` Thinking...`)),!E&&!h&&c.length>0&&d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},c.map((e,t)=>d.default.createElement(u.Box,{key:t,marginBottom:1},e.status===`running`&&d.default.createElement(u.Text,{color:`#00AF66`},d.default.createElement(f.default,{type:`dots`})),d.default.createElement(u.Text,{color:`#00AF66`},` `,e.skillName?d.default.createElement(d.default.Fragment,null,`✨ Skill •`,` `,e.skillName):d.default.createElement(d.default.Fragment,null,`🔧 `,e.name),e.status===`running`&&`...`,e.status===`completed`&&` ✓`)))),!E&&_&&!h&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{color:`#00AF66`},O(_)))):d.default.createElement(d.default.Fragment,null,s.filter(e=>e.isSubagent&&!e.content.startsWith(`TOOL_START:`)&&e.role!==`system`||e.content.startsWith(`TOOL:`)).slice(-2).map((e,t)=>{let n=e.role===`system`&&e.content.startsWith(`TOOL:`),r=e.content;if(n){let t=e.content.split(`|||`),n=t[0].replace(`TOOL:`,``),i=t.length>=3?t.slice(2).join(`|||`):t[1]||``;r=`🔧 ${n}: ${i.slice(0,100)}${i.length>100?`...`:``}`}let i=r.split(`
|
|
15
|
+
`).slice(0,2).join(`
|
|
16
|
+
`);return d.default.createElement(u.Box,{key:t,marginTop:1},d.default.createElement(u.Text,{color:`#00AF66`,dimColor:n},O(i),r.split(`
|
|
17
|
+
`).length>2&&`...`))}),!E&&!h&&l&&c.length===0&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{color:`#00AF66`},d.default.createElement(f.default,{type:`dots`})),d.default.createElement(u.Text,{dimColor:!0},` Thinking...`)),!E&&!h&&c.length>0&&d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},c.slice(-2).map((e,t)=>d.default.createElement(u.Box,{key:t,marginBottom:1},e.status===`running`&&d.default.createElement(u.Text,{color:`#00AF66`},d.default.createElement(f.default,{type:`dots`})),d.default.createElement(u.Text,{color:`#00AF66`},` `,e.skillName?d.default.createElement(d.default.Fragment,null,`✨ Skill •`,` `,e.skillName):d.default.createElement(d.default.Fragment,null,`🔧 `,e.name),e.status===`running`&&`...`,e.status===`completed`&&` ✓`))),c.length>2&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`... and`,` `,c.length-2,` `,`more (Ctrl+O to expand)`))),!E&&_&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{color:`#00AF66`},O(_).split(`
|
|
18
|
+
`).slice(0,2).join(`
|
|
19
|
+
`),O(_).split(`
|
|
20
|
+
`).length>2&&`
|
|
21
|
+
...`))))),_&&!w&&!h&&d.default.createElement(u.Box,{marginBottom:1,flexDirection:`column`},d.default.createElement(u.Text,{bold:!0,color:`#00AF66`},`◆ StackOne Agent`,d.default.createElement(u.Text,{color:`gray`},` • `,new Date().toLocaleTimeString())),d.default.createElement(u.Box,{paddingLeft:2},d.default.createElement(u.Text,{wrap:`wrap`},O(_)))),!w&&!h&&c.length>0&&d.default.createElement(u.Box,{marginBottom:1,flexDirection:`column`},c.map((e,t)=>d.default.createElement(u.Box,{key:t,marginBottom:1},e.status===`running`&&d.default.createElement(u.Text,{color:`#00AF66`},d.default.createElement(f.default,{type:`dots`})),d.default.createElement(u.Text,{color:`#00AF66`},` `,e.skillName?d.default.createElement(d.default.Fragment,null,`✨ Skill • `,e.skillName):d.default.createElement(d.default.Fragment,null,`🔧 `,e.name),e.status===`running`&&`...`,e.status===`completed`&&` ✓`))))),!w&&!h&&l&&c.length===0&&d.default.createElement(u.Box,{marginBottom:1},d.default.createElement(u.Text,{color:`#00AF66`},d.default.createElement(f.default,{type:`dots`})),d.default.createElement(u.Text,{dimColor:!0},` Thinking...`)),h&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{color:`red`},`⏺ Interrupted · What should the StackOne Agent do instead?`)),m&&d.default.createElement(u.Box,{marginBottom:1,borderStyle:`single`,borderColor:`red`,paddingX:2,paddingY:1,flexDirection:`column`},d.default.createElement(u.Text,{color:`red`},`✗ `,m),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`Press Enter to try again or Ctrl+C to exit`))),p&&d.default.createElement(u.Box,{marginBottom:1,borderStyle:`single`,borderColor:`#00AF66`,paddingX:2},d.default.createElement(u.Text,{color:`#00AF66`},`✓ Complete`)),y&&d.default.createElement(u.Box,{marginBottom:1,borderStyle:`single`,borderColor:`#00AF66`,paddingX:2,paddingY:1,flexDirection:`column`},H?d.default.createElement(d.default.Fragment,null,d.default.createElement(u.Text,{bold:!0,color:`#00AF66`},y.items[B].name),y.type!==`trust`&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},y.items[B].description)),y.type===`skills`&&d.default.createElement(u.Box,{flexDirection:`column`},y.items[B].version?d.default.createElement(u.Text,{dimColor:!0},`Version:`,` `,String(y.items[B].version)):null,y.items[B].author?d.default.createElement(u.Text,{dimColor:!0},`Author:`,` `,String(y.items[B].author)):null,y.items[B].tags&&Array.isArray(y.items[B].tags)?d.default.createElement(u.Text,{dimColor:!0},`Tags:`,` `,y.items[B].tags.join(`, `)):null,y.items[B].content?d.default.createElement(u.Box,{marginTop:1,flexDirection:`column`},d.default.createElement(u.Text,{bold:!0},`Skill Content:`),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{wrap:`wrap`},String(y.items[B].content).slice(0,2e3),String(y.items[B].content).length>2e3?`
|
|
22
|
+
|
|
23
|
+
... (content truncated)`:``))):d.default.createElement(u.Text,{dimColor:!0},`No content available`)),y.type===`tools`&&d.default.createElement(u.Box,{flexDirection:`column`},d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`Category:`,` `,String(y.items[B].category))),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{bold:!0},`Input Parameters:`)),y.items[B].inputSchema?d.default.createElement(u.Box,{marginTop:1,paddingLeft:2,flexDirection:`column`},(()=>{let e=y.items[B].inputSchema,t=e.properties||{},n=e.required||[];return Object.entries(t).map(([e,t])=>d.default.createElement(u.Box,{key:e,flexDirection:`column`,marginBottom:1},d.default.createElement(u.Text,null,e,n.includes(e)?` *`:``,d.default.createElement(u.Text,{dimColor:!0},` `,`(`,t.type?String(t.type):`any`,`)`)),t.description?d.default.createElement(u.Box,{paddingLeft:2},d.default.createElement(u.Text,{dimColor:!0},String(t.description))):null))})(),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`* = required parameter`))):d.default.createElement(u.Box,{marginTop:1,paddingLeft:2},d.default.createElement(u.Text,{dimColor:!0},`No parameters`)),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{bold:!0},`Output:`)),d.default.createElement(u.Box,{marginTop:1,paddingLeft:2},d.default.createElement(u.Text,{dimColor:!0},`Returns JSON with tool execution results`))),y.type===`trust`&&d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},d.default.createElement(u.Text,null,d.default.createElement(u.Text,{dimColor:!0},`Path: `),d.default.createElement(u.Text,null,String(y.items[B].path))),d.default.createElement(u.Text,null,d.default.createElement(u.Text,{dimColor:!0},`Trusted at: `),d.default.createElement(u.Text,null,y.items[B].trustedAt?new Date(y.items[B].trustedAt).toLocaleString():`N/A`))),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`Press Esc to go back`))):J?d.default.createElement(d.default.Fragment,null,d.default.createElement(u.Text,{bold:!0,color:`yellow`},`⚠️ Remove Trust`),d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},d.default.createElement(u.Text,{color:`white`},`Are you sure you want to remove trust from:`),d.default.createElement(u.Text,{color:`cyan`,bold:!0},J.path)),d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},d.default.createElement(u.Text,{color:`yellow`},`⚠️ This action is permanent. To trust this folder again,`),d.default.createElement(u.Text,{color:`yellow`},`you must open a new chat session in that directory.`)),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{color:X===0?`green`:`gray`,bold:X===0},X===0?`❯ [Y]es`:` Yes`),d.default.createElement(u.Text,null,` `),d.default.createElement(u.Text,{color:X===1?`green`:`gray`,bold:X===1},X===1?`❯ [N]o`:` No`)),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`←→ to select • Enter to confirm • Esc to cancel`))):d.default.createElement(d.default.Fragment,null,d.default.createElement(u.Text,{bold:!0,color:`#00AF66`},y.type===`skills`?`📚 Skills (${y.items.length})`:y.type===`tools`?`🔧 Tools (${y.items.length})`:y.type===`mcp`?`📡 MCP Servers (${y.items.filter(e=>e.connected).length}/${y.items.length} connected)`:y.type===`trust`?`📁 Trusted Folders (${y.items.length})`:y.type===`rewind`?`⏮️ Command History (${y.items.length})`:`💬 Recent Conversations (${y.items.length})`),d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},y.items.map((e,t)=>{let n=t===B?`❯ `:` `,r=process.stdout.columns||80,i=Math.min(r-10,120),a=(e.name||``).replace(/\n/g,` ⏎ `),o=``;if(y.type===`mcp`?o=e.connected?`● `:`○ `:y.type===`trust`&&(o=e.trusted?`● `:`○ `),y.type===`skills`)return d.default.createElement(u.Text,{key:t,color:t===B?`#00AF66`:`gray`},n,a);let s=e.tokens?` (~${e.tokens.toLocaleString()} tokens)`:``,c=i-(n.length+o.length+a.length+s.length)-5,l=``;if(e.description&&c>10){let t=String(e.description).replace(/\n/g,` ⏎ `);l=t.length>c?` - ${t.slice(0,c)}...`:` - ${t}`}let f=`${n}${o}${a}${s}${l}`,p=f.slice(0,i);return d.default.createElement(u.Text,{key:t,color:t===B?`#00AF66`:`gray`},p,f.length>i?`...`:``)})),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},y.type===`skills`?`↑↓ Navigate • Enter for details • Esc to close`:y.type===`trust`?`↑↓ Navigate • Ctrl+O to remove trust • Enter for details • Esc to close`:y.type===`resume`?`↑↓ Navigate • Enter to resume • Esc to close`:y.type===`rewind`?`↑↓ Navigate • Enter to rewind to • Esc to close`:`↑↓ Navigate • Enter for details • Esc to close`)))),ee.length>0&&d.default.createElement(u.Box,{flexDirection:`column`,marginBottom:1},ee.map((e,t)=>d.default.createElement(u.Box,{key:t,marginBottom:t<ee.length-1?1:0},d.default.createElement(u.Text,{dimColor:!0},`📬 `),d.default.createElement(u.Text,null,e.content))),te&&d.default.createElement(u.Text,{dimColor:!0,italic:!0},`Processing...`)),k&&d.default.createElement(u.Box,{marginBottom:1},d.default.createElement(u.Text,{color:`yellow`},`Delete `),d.default.createElement(u.Text,{color:`red`},k.isDirectory&&k.directoryContents?`${k.files.map(e=>e.split(`/`).pop()).join(`, `)}/ (${k.directoryContents.length} files)`:k.files.map(e=>e.split(`/`).pop()).join(`, `)),d.default.createElement(u.Text,{color:`yellow`},`? `),d.default.createElement(u.Text,{color:q===0?`green`:`gray`},q===0?`[Y]es`:`y`),d.default.createElement(u.Text,null,`/`),d.default.createElement(u.Text,{color:q===1?`green`:`gray`},q===1?`[N]o`:`n`)),ue&&!p&&!y&&!k&&d.default.createElement(d.default.Fragment,null,d.default.createElement(u.Box,{borderStyle:`double`,borderColor:`white`,paddingX:2,flexDirection:`column`},(()=>{let e=process.stdout.columns||80,t=Math.max(20,e-6),n=j.split(`
|
|
24
|
+
`),r=0,i=[];return n.forEach((e,a)=>{let o=r,s=o+e.length;r=s+1;let c=a===0,l=c?t-2:t,f=[];if(e.length===0)f.push(``);else{let n=e,r=!0;for(;n.length>0;){let e=r?l:t;f.push(n.slice(0,e)),n=n.slice(e),r=!1}}let p=0;f.forEach((e,t)=>{let r=o+p,l=r+e.length,m=c&&t===0,h=N>=r&&N<l,g=N===s&&a<n.length-1&&t===f.length-1,_=N===l&&t===f.length-1&&a===n.length-1,v=`${a}-${t}`;if(h||g||_){let t=N-r,n=e.slice(0,t),a=g?` `:e.charAt(t)||` `,o=g?``:e.slice(t+1);i.push(d.default.createElement(u.Box,{key:v},m&&d.default.createElement(u.Text,{color:`#00AF66`},`❯ `),d.default.createElement(u.Text,{color:`white`},n),d.default.createElement(u.Text,{backgroundColor:`white`,color:`black`,bold:!0},a),d.default.createElement(u.Text,{color:`white`},o)))}else i.push(d.default.createElement(u.Box,{key:v},m&&d.default.createElement(u.Text,{color:`#00AF66`},`❯ `),d.default.createElement(u.Text,{color:`white`},e||` `)));p+=e.length})}),i})()),R.length>0&&d.default.createElement(u.Box,{marginTop:1,paddingLeft:2,flexDirection:`column`},R.map((e,t)=>d.default.createElement(u.Box,{key:e},d.default.createElement(u.Text,{color:t===ge?`#00AF66`:`gray`},t===ge?`❯ `:` `,e))))),v&&(()=>{let e=100-(v.input_tokens+v.output_tokens)/1e6*100,t=e>50?`green`:e>20?`yellow`:`red`,n=e<10;return d.default.createElement(u.Box,{marginTop:1,flexDirection:`column`},d.default.createElement(u.Text,{dimColor:!0},`📊 Model: Sonnet 4.5 • 🧠 Context left:`,` `,d.default.createElement(u.Text,{color:t},e.toFixed(1),`%`)),n&&d.default.createElement(u.Text,{color:`red`},`⚠️ Context low (`,e.toFixed(1),`% remaining)`))})(),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},ue?`Type message and press Enter • Shift+Enter for new line • `:``,(l||_||c.length>0)&&`ESC to stop • `,w?`Ctrl+O to expand subprocess • `:`Ctrl+O to show/hide full tool results • `,`Ctrl+C to clear/exit`)))},oe=({timeRemaining:e,onRunSetup:t,onIgnore:n})=>{let{exit:r}=(0,u.useApp)(),[i,a]=(0,d.useState)(0);(0,u.useInput)((e,o)=>{if(e===`1`){t(),r();return}if(e===`2`){n(),r();return}o.upArrow?a(0):o.downArrow?a(1):o.return?i===0?(t(),r()):(n(),r()):o.escape&&(n(),r())});let o=`\x1B[38;2;0;175;102m`,{hours:s,minutes:c}=e,l=s>0?`${s} hour${s===1?``:`s`} and ${c} minute${c===1?``:`s`}`:`${c} minute${c===1?``:`s`}`;return d.default.createElement(u.Box,{flexDirection:`column`,padding:2},d.default.createElement(u.Box,{borderStyle:`round`,borderColor:`yellow`,flexDirection:`column`,paddingX:2,paddingY:1},d.default.createElement(u.Text,{bold:!0,color:`yellow`},`⚠️ Credential Warning`),d.default.createElement(u.Text,null),d.default.createElement(u.Text,null,`Your StackOne credentials expire in `,l,` (last day of 7-day validity).`),d.default.createElement(u.Text,null),d.default.createElement(u.Text,null,"To avoid interruption, run `stackone agent setup` to reauthenticate."),d.default.createElement(u.Text,null),d.default.createElement(u.Text,{color:i===0?o:`white`},i===0?`❯ `:` `,`1. Run stackone agent setup`),d.default.createElement(u.Text,{color:i===1?o:`white`},i===1?`❯ `:` `,`2. Ignore and continue`)),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`↑↓ to navigate • Enter to confirm • Esc to continue`)))},se=({directory:e,onConfirm:t,onCancel:n})=>{let{exit:r}=(0,u.useApp)(),[i,a]=(0,d.useState)(0);(0,u.useInput)((e,o)=>{o.upArrow?a(0):o.downArrow?a(1):o.return?i===0?(t(),r()):(n(),r()):o.escape&&(n(),r())});let o=`\x1B[38;2;0;175;102m`;return d.default.createElement(u.Box,{flexDirection:`column`,padding:2},d.default.createElement(u.Box,{borderStyle:`round`,borderColor:`#00AF66`,flexDirection:`column`,paddingX:2,paddingY:1},d.default.createElement(u.Text,{bold:!0},`Do you trust the files in this folder?`),d.default.createElement(u.Text,null),d.default.createElement(u.Text,{dimColor:!0},e),d.default.createElement(u.Text,null),d.default.createElement(u.Text,null,`StackOne Agent may read, write, or execute files contained in this directory.`),d.default.createElement(u.Text,null,`This can pose security risks, so only use files and commands from trusted sources.`),d.default.createElement(u.Text,null),d.default.createElement(u.Text,{color:i===0?o:`white`},i===0?`❯ `:` `,`1. Yes, proceed`),d.default.createElement(u.Text,{color:i===1?o:`white`},i===1?`❯ `:` `,`2. No, exit`)),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`↑↓ to navigate • Enter to confirm • Esc to exit`)))};function ce(){return[]}const le=(e,t)=>{try{if(t.existed&&t.content!==null){let n=l.dirname(e);return s.existsSync(n)||s.mkdirSync(n,{recursive:!0}),s.writeFileSync(e,t.content,`utf-8`),{success:!0,action:`restored`}}else return s.existsSync(e)?(s.unlinkSync(e),{success:!0,action:`deleted`}):{success:!0,action:`restored`}}catch(e){return{success:!1,action:`error`,error:e instanceof Error?e.message:String(e)}}},j=[{name:`commands`,description:`Show all available commands`,argumentHint:``,source:`cli`},{name:`skills`,description:`View and toggle skills (max 8)`,argumentHint:``,source:`cli`},{name:`tools`,description:`View available tools`,argumentHint:``,source:`cli`},{name:`mcp`,description:`List configured MCP servers`,argumentHint:``,source:`cli`},{name:`trust`,description:`View and manage trusted folders`,argumentHint:``,source:`cli`},{name:`compact`,description:`Summarize conversation to free up context`,argumentHint:``,source:`cli`},{name:`exit`,description:`Exit the agent (or use Ctrl+C)`,argumentHint:``,source:`cli`}],M=new Set([`heapdump`]);function N(e,t){let n=new Map(t.map(e=>[e.name,e]));for(let t of e)!n.has(t.name)&&!M.has(t.name)&&n.set(t.name,{...t,source:`harness`});return Array.from(n.values())}const P=({mode:t,connector:n,action:r,goal:i,verbose:a,temperature:u,apiKey:f})=>{let[p,m]=(0,d.useState)([]),[h,g]=(0,d.useState)(new Map),[_,v]=(0,d.useState)(!1),[y,b]=(0,d.useState)(),[x,S]=(0,d.useState)(!1),[C,w]=(0,d.useState)(!0),[T,E]=(0,d.useState)([]),[ee,te]=(0,d.useState)([]),[D,O]=(0,d.useState)(``),[k]=(0,d.useState)(),[ne,re]=(0,d.useState)(!1),[ie,A]=(0,d.useState)(null),oe=(0,d.useRef)((0,o.createDefaultVisualizationRegistry)()),se=(0,d.useRef)((0,o.createSkillTracker)()),[M]=(0,d.useState)(new Date),[P,F]=(0,d.useState)(0),[ue,de]=(0,d.useState)(!1),I=(0,d.useRef)(!1),[fe,L]=(0,d.useState)(``),[pe,me]=(0,d.useState)(!1),[R,he]=(0,d.useState)([]),[ge,z]=(0,d.useState)(!1),[B,V]=(0,d.useState)(!1),H=(0,d.useRef)(!1),U=(0,d.useRef)({shouldStop:!1,requestId:0,controller:null}),[W,G]=(0,d.useState)([]),K=(0,d.useRef)(null),[_e,ve]=(0,d.useState)([]),q=(0,d.useRef)(null),ye=(0,d.useRef)([]),J=(0,d.useRef)(0),[Y,X]=(0,d.useState)({claudeSkills:{count:0,names:[],totalSize:0},mcpServers:[],toolCounts:{total:0,builtin:[],mcpByServer:{}},errors:[]}),[be,Z]=(0,d.useState)(j),xe=(0,d.useRef)(new Map),Se=(0,d.useRef)(-1),[Ce,Q]=(0,d.useState)(null),we=(0,d.useRef)(null),$=(0,d.useRef)({operation:``,phase:`idle`}),Te=(e,t=!1)=>{let n=$.current,r=e;n.operation&&(r=`${r}\n\nContext: ${n.operation}`);let i={idle:`Agent was idle`,thinking:`Agent was processing your request`,tool_execution:n.toolName?`Agent was executing tool: ${n.toolName}`:`Agent was executing a tool`,streaming:`Agent was generating a response`};if(n.phase!==`idle`&&(r=`${r}\nPhase: ${i[n.phase]}`),t&&n.toolName&&n.toolInput)try{let e=typeof n.toolInput==`string`?n.toolInput:JSON.stringify(n.toolInput,null,2),t=e.length>500?e.slice(0,500)+`...`:e;r=`${r}\nTool input: ${t}`}catch{}return r};(0,d.useEffect)(()=>{let t=l.join(c.homedir(),`.stackone`,`agent_history`);try{if(s.existsSync(t)){let e=s.readFileSync(t,`utf-8`),n;try{let t=JSON.parse(e);n=Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.trim()):e.split(`
|
|
25
|
+
`).filter(e=>e.trim())}catch{n=e.split(`
|
|
26
|
+
`).filter(e=>e.trim())}te(n)}}catch(t){a&&e.h.error(`[History] Failed to load command history:`,t)}},[a]);let Ee=(0,d.useRef)([]);(0,d.useEffect)(()=>{(async()=>{let n={claudeSkills:{count:0,names:[],totalSize:0},mcpServers:[],toolCounts:{total:0,builtin:[],mcpByServer:{}},errors:[]};try{try{let e=(0,o.getAvailableSkillNames)(),t=(0,o.getBundledSkillsPath)();E(e.map(e=>{let n=l.join(t,e,`SKILL.md`),r,i;try{if(s.existsSync(n)){let e=s.readFileSync(n,`utf-8`);i=e;let t=e.match(/^---\n([\s\S]*?)\n---/);if(t){let e=t[1].match(/description:\s*\|?\s*\n?([\s\S]*?)(?=\n\w+:|$)/);e&&(r=e[1].trim().split(`
|
|
27
|
+
`)[0].trim())}}}catch{}return{name:e,description:r,content:i}})),n.claudeSkills={count:e.length,names:e,totalSize:0}}catch(t){e.h.error(`[Skills] Failed to load skills:`,t),n.errors.push(`Failed to load skills`)}try{let e=ce();Ee.current=e;for(let t of e)n.mcpServers.push({name:t.name,count:0});let t=`fetch.extract_html_text.web_search.vector_search.get_external_integrations.analyze_external_integration.analyze_external_integrations.get_external_repos.scan_external_repo.search_external_repo.get_provider_coverage.get_providers.map_provider_key.get_stackone_actions.meta_feedback.get_stackone_categories.get_docs.get_stackone_expressions.extract_oas_actions.get_provider_actions.scramble_credentials.improve_descriptions.discover_actions.get_improve_descriptions_task_status.get_discover_actions_task_status.test_actions.get_test_actions_task_status.analyze_versioning.get_analyze_versioning_task_status.falcon_workflow.falcon_research.falcon_build.falcon_oauth.falcon_test.falcon_security`.split(`.`);n.mcpServers.push({name:`stackone`,count:t.length}),n.toolCounts.mcpByServer.stackone=t}catch(e){n.errors.push(`MCP: ${e instanceof Error?e.message:String(e)}`)}n.toolCounts.builtin=[`Read`,`Write`,`Edit`,`Glob`,`Grep`,`Bash`,`WebSearch`,`WebFetch`],n.toolCounts.total=n.toolCounts.builtin.length;try{Z(N(await(await(0,o.createAgentSession)({prompt:``,mode:t,apiKey:f})).supportedCommands(),j))}catch(t){a&&e.h.warn(`[Commands] Failed to fetch harness commands:`,t)}X(n)}catch(t){e.h.error(`[Init] Failed to initialize runtime:`,t)}finally{w(!1)}})()},[f,t,a]),(0,d.useEffect)(()=>{H.current=B},[B]),(0,d.useEffect)(()=>{if(k&&!ne){let e=k.input_tokens+k.output_tokens,t=(1e6-e)/1e6*100;if(t<10){let n={role:`system`,content:`⚠️ Context Warning\n\nYou have ${t.toFixed(1)}% context remaining (${(1e6-e).toLocaleString()} tokens).\n\nConsider using /compact to summarize the conversation and free up context.`,timestamp:new Date};m(e=>[...e,n]),re(!0)}}},[k,ne]);let De=(0,d.useCallback)(async i=>{try{let e=p.filter(e=>e.role===`user`||e.role===`assistant`);if(e.length<2)return;let a=i.trim().slice(0,50)||e.find(e=>e.role===`user`)?.content?.slice(0,50)||`conversation`;await s.promises.mkdir(l.join(c.homedir(),`.stackone`,`conversations`),{recursive:!0});let o=Date.now(),u=`${o}-${a.replace(/[^a-zA-Z0-9]/g,`-`).toLowerCase().slice(0,50)}.json`,d=l.join(c.homedir(),`.stackone`,`conversations`,u);await s.promises.writeFile(d,JSON.stringify({title:a,timestamp:o,goal:i,messages:p.filter(e=>e.role!==`system`),mode:t,connector:n,action:r},null,2))}catch(t){e.h.error(`Failed to save conversation:`,t)}},[p,t,n,r]),Oe=(0,d.useCallback)(async(i,u=!1)=>{if((C||H.current)&&!u){he(e=>[...e,{content:i,timestamp:new Date}]),K.current&&clearTimeout(K.current),K.current=setTimeout(()=>{Ae()},3e4);return}if(b(void 0),S(!1),i===`/skills`){if(T.length===0){let e={role:`system`,content:`📚 No skills loaded. Skills will be loaded on startup.`,timestamp:new Date};m(t=>[...t,e]);return}A({type:`skills`,items:T.map(e=>({name:e.name,description:e.description,content:e.content}))});return}if(i===`/tools`){let e=[];for(let t of Y.mcpServers){let n=Y.toolCounts.mcpByServer[t.name]||[];for(let r of n)e.push({name:r,description:`MCP tool (${t.name})`,category:`MCP:${t.name}`})}let t=[...Y.toolCounts.builtin.map(e=>({name:e,description:`Built-in (from agent harness)`,category:`Built-in`})),...e,...Y.mcpServers.filter(e=>!Y.toolCounts.mcpByServer[e.name]?.length).map(e=>({name:e.name,description:e.name===`stackone`?`MCP server (${e.count} tools) - from agent harness`:`MCP server (${e.count} tools)`,category:`MCP`}))];A({type:`tools`,items:t.length>0?t:[{name:`—`,description:`Tools provided by harness (built-in + skills + MCP)`,category:``}]});return}if(i===`/commands`){let e=`📋 Available Commands:
|
|
28
|
+
|
|
29
|
+
`;for(let t of be){let n=t.argumentHint?` ${t.argumentHint}`:``;e+=` /${t.name}${n} - ${t.description}\n`}let t={role:`system`,content:e,timestamp:new Date};m(e=>[...e,t]);return}if(i===`/exit`&&process.exit(0),i===`/instructions`){let e=[`📜 Active Instructions
|
|
30
|
+
`];if(T.length>0){e.push(`Skills Loaded (${T.length}):`);for(let t of T)e.push(` • ${t.name}${t.description?` - ${t.description}`:``}`);e.push(``)}e.push(`Session Context:`),e.push(` • Mode: ${t}`),n&&e.push(` • Connector: ${n}`),r&&e.push(` • Action: ${r}`),e.push(` • Turn Count: ${P}`),e.push(``);let i={instructions:`Mode: ${t}\nSkills: ${T.map(e=>e.name).join(`, `)||`none`}\nConnector: ${n||`none`}`,skills:T.map(e=>({name:e.name,description:e.description,enabled:!0})),session:{id:`current`,startedAt:M,mode:t,turnCount:P}},a=oe.current.render(`instructions`,i);a?.content&&e.push(a.content);let o={role:`system`,content:e.join(`
|
|
31
|
+
`),timestamp:new Date};m(e=>[...e,o]);return}if(i===`/safety`){let e=`🛡️ Safety Rules
|
|
32
|
+
|
|
33
|
+
`;e+=`Command execution is protected by safety checks implemented in the agent harness.
|
|
34
|
+
`,e+=`These checks may block or require confirmation for potentially dangerous operations,
|
|
35
|
+
`,e+=`such as destructive filesystem commands or writing directly to devices.
|
|
36
|
+
|
|
37
|
+
`,e+=`The exact safety rules and heuristics are maintained by the runtime and may change over time.
|
|
38
|
+
`;try{(0,o.checkCommandSafety)(`ls -la`),e+=`
|
|
39
|
+
✓ Safety hook is active and working`}catch{e+=`
|
|
40
|
+
⚠ Safety hook check failed`}let t={role:`system`,content:e,timestamp:new Date};m(e=>[...e,t]);return}if(i===`/mcp`){if(Y.mcpServers.length===0){let e={role:`system`,content:`📡 No MCP servers configured`,timestamp:new Date};m(t=>[...t,e]);return}A({type:`mcp`,items:Y.mcpServers.map(e=>{let t=Y.toolCounts.mcpByServer[e.name]||[];return{name:e.name,description:`${t.length} tools`,tools:t,connected:t.length>0}})});return}if(i===`/trust`){let{getTrustedFoldersForDisplay:e}=await Promise.resolve().then(()=>require(`./trustedFolders-Dax3_RJQ.cjs`)),t=e();if(t.length===0){let e={role:`system`,content:`📁 No trusted folders found.
|
|
41
|
+
|
|
42
|
+
Folders are automatically trusted when you open a chat session in them.`,timestamp:new Date};m(t=>[...t,e]);return}A({type:`trust`,items:t.map(e=>({name:e.name,description:e.path,path:e.path,trusted:e.trusted,trustedAt:e.trustedAt}))});return}if(i===`/rewind`){try{let e=l.join(c.homedir(),`.stackone`,`agent_history`);if(!s.existsSync(e)){let e={role:`system`,content:`⏮️ No command history found.`,timestamp:new Date};m(t=>[...t,e]);return}let t=s.readFileSync(e,`utf-8`).split(`
|
|
43
|
+
`).filter(e=>e.trim());if(t.length===0){let e={role:`system`,content:`⏮️ Command history is empty.`,timestamp:new Date};m(t=>[...t,e]);return}A({type:`rewind`,items:t.reverse().slice(0,10).map((e,n)=>({name:e,description:`${t.length-n} messages ago`,index:t.length-n-1}))})}catch(e){let t={role:`system`,content:`❌ Error loading history: ${e instanceof Error?e.message:String(e)}`,timestamp:new Date};m(e=>[...e,t])}return}if(i===`/resume`){try{let e=l.join(c.homedir(),`.stackone`,`conversations`);if(!s.existsSync(e)){let e={role:`system`,content:`▶️ No conversation history found. Start a new conversation first!`,timestamp:new Date};m(t=>[...t,e]);return}let t=s.readdirSync(e).filter(e=>e.endsWith(`.json`)).sort((e,t)=>{let n=parseInt(e.split(`-`)[0])||0;return(parseInt(t.split(`-`)[0])||0)-n}).slice(0,10);if(t.length===0){let e={role:`system`,content:`▶️ No conversations found.`,timestamp:new Date};m(t=>[...t,e]);return}let n=t.map(t=>{try{let n=s.readFileSync(l.join(e,t),`utf-8`),r=JSON.parse(n);return{file:t,title:r.title||`Untitled conversation`,timestamp:r.timestamp,messages:r.messages,goal:r.goal}}catch{return null}}).filter(Boolean);if(n.length===0){let e={role:`system`,content:`▶️ No valid conversations found.`,timestamp:new Date};m(t=>[...t,e]);return}A({type:`resume`,items:n.map(e=>({name:e?.title,description:new Date(e?.timestamp).toLocaleString(),goal:e?.goal,file:e?.file,messages:e?.messages}))})}catch(e){let t={role:`system`,content:`❌ Error loading conversations: ${e instanceof Error?e.message:String(e)}`,timestamp:new Date};m(e=>[...e,t])}return}let d=be.map(e=>`/${e.name}`),h=i.split(` `)[0];if(i.startsWith(`/`)&&h!==`/`&&!d.includes(h)){let e={role:`system`,content:`❌ Unknown command: ${i}\n\nType /commands to see available commands.`,timestamp:new Date};m(t=>[...t,e]);return}if(i===`/compact`){let e={role:`user`,content:i,timestamp:new Date};m(t=>[...t,e]),v(!0);try{let e=p.filter(e=>e.role===`user`||e.role===`assistant`).map(e=>`${e.role===`user`?`User`:`Assistant`}: ${e.content}`).join(`
|
|
44
|
+
|
|
45
|
+
`),t=e.length>2e3?e.slice(0,2e3)+`
|
|
46
|
+
|
|
47
|
+
[... truncated for context]`:e;v(!1);let n={role:`system`,content:`🗜️ Compact mode activated - recent context:\n\n${t}`,timestamp:new Date};m(e=>[e[e.length-1],n])}catch(e){v(!1),b(e instanceof Error?e.message:`Failed to summarize conversation`)}return}te(t=>{let n=i.trim();if(!n)return t;let r=[...t,n],o=r.length-1;Se.current=o,xe.current.has(o)||xe.current.set(o,{commandIndex:o,command:n,timestamp:Date.now(),files:new Map});let u=l.join(c.homedir(),`.stackone`,`agent_history`);try{let e=l.dirname(u);s.existsSync(e)||s.mkdirSync(e,{recursive:!0});let t=r.slice(-1e3);s.writeFileSync(u,JSON.stringify(t),`utf-8`)}catch(t){a&&e.h.error(`[History] Failed to save command history:`,t)}return r});let _={role:`user`,content:i,timestamp:new Date};m(e=>[...e,_]),v(!0),V(!0),F(e=>e+1),U.current.requestId+=1,U.current.shouldStop=!1,U.current.controller=new AbortController;let y=U.current.requestId,x=U.current.controller.signal;q.current&&=(clearTimeout(q.current),null),ve([]);let w=()=>!U.current.shouldStop&&U.current.requestId===y;try{let s=p.filter(e=>(e.role===`user`||e.role===`assistant`)&&!e.isSubagent).map(e=>({role:e.role,content:e.content})).slice(-20).map(e=>`${e.role}: ${e.content.slice(0,500)}`).join(`
|
|
48
|
+
`);ye.current=[],J.current=0;try{a&&(e.h.log(`
|
|
49
|
+
[AGENT:CONFIG] ═══════════════════════════════════════`),e.h.log(`[AGENT:CONFIG] Prompt: "${i.slice(0,100)}..."`),e.h.log(`[AGENT:CONFIG] Mode: ${t}`),e.h.log(`[AGENT:CONFIG] MCP Servers: ${Ee.current.map(e=>e.name).join(`, `)||`none`}`),e.h.log(`[AGENT:CONFIG] API Key: ${f?`${f.slice(0,15)}...`:`MISSING`}`),e.h.log(`[AGENT:CONFIG] Context keys: ${Object.keys({connector:n,action:r}).filter(e=>({connector:n,action:r})[e]).join(`, `)||`none`}`),e.h.log(`[AGENT:CONFIG] Max turns: 1000`),e.h.log(`[AGENT:CONFIG] ═══════════════════════════════════════
|
|
50
|
+
`));let c=0,l=Date.now();for await(let u of(0,o.executeAgent)({prompt:i,mode:t,mcpServers:Ee.current,apiKey:f,context:{connector:n,action:r,conversationSummary:s||void 0},maxTurns:1e3,verbose:a||!1,streaming:!1,origin:`cli`,abortSignal:x})){c++;let t=Date.now()-l;if(a){let n=u.type===`text`?` content="${(u.content||``).slice(0,30)}..."`:u.type===`error`?` error="${u.error}"`:u.type===`tool_call`?` tool="${u.toolName}"`:``;e.h.log(`[AGENT:MSG #${c}] type=${u.type}${n} (${t}ms)`)}if(!w())return;if(u.type===`text`){$.current.phase=`streaming`,O(e=>e+(u.content??``)),ke();continue}if(u.type===`skill_invocation`){let e=`skill-${++J.current}`;g(t=>{let n=new Map(t);return n.set(e,{name:`Skill`,status:`running`,skillName:u.skillName,inputSummary:u.skillArgs}),n}),setTimeout(()=>{g(t=>{let n=new Map(t);return n.delete(e),n})},2e3);continue}if(u.type===`tool_call`){$.current={operation:`Processing: "${i.slice(0,100)}${i.length>100?`...`:``}"`,phase:`tool_execution`,toolName:u.toolName,toolInput:u.toolInput};let e=`tc-${++J.current}`;if(ye.current.push(e),G(t=>[...t,{id:e,name:u.toolName??``,input:u.toolInput,output:void 0}]),u.toolName===`spawn_subagent`&&u.toolInput){let e=u.toolInput,t=e.description??e.goal??e.name??`Subagent`;if(typeof t==`string`&&t.length>50){let e=String(t).split(/[.!?]/)[0];t=e.length>50?e.slice(0,47)+`...`:e}L(String(t)),I.current=!0,setTimeout(()=>de(!0),10)}let t=u.toolInput,n=``;t&&typeof t==`object`&&(t.command?n=String(t.command).slice(0,100):t.file_path?n=String(t.file_path):t.pattern?n=String(t.pattern):t.url?n=String(t.url):t.query&&(n=String(t.query))),O(e=>(e&&m(t=>[...t,{role:`assistant`,content:e,timestamp:new Date,isSubagent:I.current}]),``)),g(t=>{let r=new Map(t);return r.set(e,{name:u.toolName??``,status:`running`,inputSummary:n}),r});continue}if(u.type===`tool_result`){$.current={...$.current,phase:`streaming`,toolName:void 0,toolInput:void 0};let e=ye.current.shift();if(e){G(t=>t.map(t=>t.id===e?{...t,output:u.toolResult}:t));let t=``;g(n=>{let r=n.get(e);r?.inputSummary&&(t=r.inputSummary);let i=new Map(n);return i.delete(e),i});let n=typeof u.toolResult==`string`?u.toolResult:JSON.stringify(u.toolResult,null,2),r={role:`system`,content:`TOOL:${u.toolName}|||${t}|||${n}`,timestamp:new Date,isSubagent:I.current};m(e=>[...e,r])}continue}if(u.type===`tool_progress`){let e=u.progress;u.toolName&&g(t=>{let n=new Map(t);for(let[t,r]of n)if(r.name===u.toolName){n.set(t,{...r,inputSummary:e?.operation||r.inputSummary});break}return n});continue}if(u.type===`tool_error`){$.current={...$.current,phase:`streaming`,toolName:void 0,toolInput:void 0};let e=ye.current.shift();e&&(G(t=>t.map(t=>t.id===e?{...t,output:`Error: ${u.error}`}:t)),g(t=>{let n=new Map(t);return n.delete(e),n}));continue}if(u.type===`error`){let t=u.error??`Unknown error`,n=t;if(a){e.h.log(`
|
|
51
|
+
[AGENT:ERROR] ═══════════════════════════════════════`),e.h.log(`[AGENT:ERROR] Message: ${t}`),e.h.log(`[AGENT:ERROR] Full message object:`);try{e.h.log(JSON.stringify(u,null,2))}catch{e.h.log(`[AGENT:ERROR] (could not stringify message)`)}e.h.log(`[AGENT:ERROR] Messages received before error: ${c}`),e.h.log(`[AGENT:ERROR] Time elapsed: ${Date.now()-l}ms`),e.h.log(`[AGENT:ERROR] ═══════════════════════════════════════
|
|
52
|
+
`)}t.includes(`exited with code 1`)?n=`Agent subprocess failed (exit code 1).
|
|
53
|
+
|
|
54
|
+
Possible causes:
|
|
55
|
+
• Authentication issue with StackOne API
|
|
56
|
+
• Network connectivity problem
|
|
57
|
+
• Invalid agent configuration
|
|
58
|
+
|
|
59
|
+
Run 'stackone agent setup' to refresh credentials.
|
|
60
|
+
|
|
61
|
+
Original error: ${t}`:t.includes(`401`)||t.includes(`unauthorized`)||t.includes(`Unauthorized`)?n=`Authentication failed.
|
|
62
|
+
|
|
63
|
+
Run 'stackone agent setup' to refresh your credentials.
|
|
64
|
+
|
|
65
|
+
Original error: ${t}`:t.includes(`403`)||t.includes(`forbidden`)||t.includes(`Forbidden`)?n=`Access denied. Your credentials may not have permission for this operation.
|
|
66
|
+
|
|
67
|
+
Run 'stackone agent setup' to refresh your credentials.
|
|
68
|
+
|
|
69
|
+
Original error: ${t}`:(t.includes(`ENOTFOUND`)||t.includes(`ECONNREFUSED`)||t.includes(`network`))&&(n=`Network error. Check your internet connection.
|
|
70
|
+
|
|
71
|
+
Original error: ${t}`),b(n),$.current={operation:``,phase:`idle`};continue}if(u.type===`done`){if(a){let t=Date.now()-l;e.h.log(`
|
|
72
|
+
[AGENT:DONE] ═══════════════════════════════════════`),e.h.log(`[AGENT:DONE] Total messages received: ${c}`),e.h.log(`[AGENT:DONE] Total time: ${t}ms`),e.h.log(`[AGENT:DONE] Status: ${u.status||`unknown`}`),c<=2&&e.h.log(`[AGENT:DONE] ⚠️ WARNING: Very few messages - agent may have failed early`),e.h.log(`[AGENT:DONE] ═══════════════════════════════════════
|
|
73
|
+
`)}$.current={operation:``,phase:`idle`},v(!1),g(new Map),G([]);let t=I.current;O(e=>(e&&m(n=>[...n,{role:`assistant`,content:e,timestamp:new Date,isSubagent:t}]),``)),t?(I.current=!1,setTimeout(()=>{m(t=>{let n=t.filter(e=>e.isSubagent&&e.role===`assistant`).map(e=>e.content).join(`
|
|
74
|
+
|
|
75
|
+
`);return n?.trim()?setTimeout(()=>{me(!1),de(!1),setTimeout(()=>{try{Oe(n,!0)}catch(t){e.h.error(`[SUBAGENT] Error:`,t),V(!1)}},100)},300):(me(!1),de(!1),V(!1)),t})},100)):V(!1),await De(i)}}}catch(e){if(!w())return;v(!1),g(new Map),b(Te(e instanceof Error?e.message:String(e),a||!1)),$.current={operation:``,phase:`idle`}}w()&&(v(!1),g(new Map),V(!1),G([]),$.current={operation:``,phase:`idle`})}catch(t){if(!w()){a&&e.h.log(`[STREAM] Ignoring error from interrupted request:`,t instanceof Error?t.message:String(t));return}v(!1),g(new Map),V(!1),G([]);let n=t instanceof Error?t.message:String(t);n.toLowerCase().includes(`cloudfront`)||n.includes(`403`)&&n.includes(`Request blocked`)?b(`⚠️ Request temporarily blocked by CloudFront
|
|
76
|
+
|
|
77
|
+
The API server's firewall blocked this request. This usually happens due to:
|
|
78
|
+
• Rate limiting (too many requests in a short time)
|
|
79
|
+
• Request size limits being exceeded
|
|
80
|
+
• Temporary server-side issues
|
|
81
|
+
|
|
82
|
+
What to try:
|
|
83
|
+
1. Wait a few seconds and try again
|
|
84
|
+
2. Start a fresh conversation with /compact
|
|
85
|
+
3. If this persists, contact the StackOne team
|
|
86
|
+
|
|
87
|
+
Press Enter to retry.`):n.includes(`403`)||n.includes(`Invalid authentication token`)||n.includes(`authentication`)?b(`Authentication failed. Your token may be invalid or expired.
|
|
88
|
+
|
|
89
|
+
To fix this:
|
|
90
|
+
1. Run: stackone agent setup
|
|
91
|
+
2. Follow the prompts to authenticate
|
|
92
|
+
3. Try again
|
|
93
|
+
|
|
94
|
+
Original error: ${n}`):n.includes(`API key`)||n.includes(`Invalid API Key`)?(e.h.error(`
|
|
95
|
+
❌ Critical error:`,n),e.h.error(`Please check your configuration and try again.
|
|
96
|
+
`),process.exit(1)):b(Te(n,a||!1)),$.current={operation:``,phase:`idle`},V(!1),v(!1),g(new Map)}},[C,p,i,t,n,r,k,ne,f,ue,De]);(0,d.useEffect)(()=>{C||i&&Oe(i)},[C,i,t,Y]);let ke=()=>{he(e=>(e.length===0||g(e=>(!(e.size>0)&&H.current&&(K.current&&=(clearTimeout(K.current),null),setTimeout(()=>Ae(),100)),e)),e))},Ae=()=>{he(e=>{if(e.length===0)return e;z(!0),O(e=>{if(e){let t={role:`assistant`,content:e,timestamp:new Date,isSubagent:I.current};m(e=>[...e,t])}return``});let t=e.map(e=>({role:`user`,content:e.content,timestamp:new Date}));m(e=>[...e,...t]);let n=e.map(e=>e.content).join(`
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
`);return z(!1),V(!1),G([]),K.current&&=(clearTimeout(K.current),null),setTimeout(()=>{Oe(n,!0)},100),[]})},je=(0,d.useCallback)(async e=>{let{removeTrustedFolder:t,getTrustedFoldersForDisplay:n}=await Promise.resolve().then(()=>require(`./trustedFolders-Dax3_RJQ.cjs`));t(e);let r=n();r.length===0?A(null):A({type:`trust`,items:r.map(e=>({name:e.name,description:e.path,path:e.path,trusted:e.trusted,trustedAt:e.trustedAt}))})},[A]);(0,d.useEffect)(()=>{let e=T.map(e=>e.name);se.current.setActiveSkills(e)},[T]),(0,d.useEffect)(()=>{if(!C&&R.length>0){let e=setTimeout(()=>{ke()},100);return()=>clearTimeout(e)}},[C,R.length]);let Me=()=>{},Ne=(0,d.useCallback)(()=>{U.current.shouldStop=!0,U.current.controller?.abort(),S(!0),O(e=>{if(e){let t=I.current,n={role:`assistant`,content:e,timestamp:new Date,isSubagent:t};m(e=>[...e,n])}return``}),v(!1),V(!1),H.current=!1,g(new Map),G([]),m(e=>e.map(e=>{if(e.content.startsWith(`TOOL_START:`)){let t=e.content.split(`|||`)[1]||`unknown`;return{...e,content:`TOOL:${t}|||[Interrupted]|||`}}return e})),he([]),ve([]),z(!1),q.current&&=(clearTimeout(q.current),null)},[]),Pe=(0,d.useCallback)(e=>{we.current&&=(we.current.resolve(e),null),Q(null)},[]);return C?d.default.createElement(ae,{title:`Agent ${t.charAt(0).toUpperCase()+t.slice(1)} Mode`,mode:t,connector:n,action:r,messages:[],currentToolCalls:[],isThinking:!1,isComplete:!1,error:void 0,isInterrupted:!1,onSubmit:()=>{},onExit:Me,onStop:Ne,slashCommands:be}):d.default.createElement(ae,{title:`Agent ${t.charAt(0).toUpperCase()+t.slice(1)} Mode`,mode:t,connector:n,action:r,messages:p,currentToolCalls:Array.from(h.values()),isThinking:_,isComplete:!1,error:y,isInterrupted:x,onSubmit:Oe,onExit:Me,onStop:Ne,commandHistory:ee,streamingText:D,usage:k,detailViewData:ie,onCloseDetailView:()=>A(null),onToggleTrust:je,slashCommands:be,onRewindTo:e=>{try{let t=l.join(c.homedir(),`.stackone`,`agent_history`),n=s.readFileSync(t,`utf-8`),r;try{let e=JSON.parse(n);r=Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim()):n.split(`
|
|
101
|
+
`).filter(e=>e.trim())}catch{r=n.split(`
|
|
102
|
+
`).filter(e=>e.trim())}let i=new Map,a=[],o=[],u=[],d=Array.from(xe.current.keys()).filter(t=>t>e).sort((e,t)=>e-t);for(let e of d){let t=xe.current.get(e);if(t)for(let[e,n]of t.files)i.has(e)||i.set(e,n)}for(let[e,t]of i){let n=le(e,t);n.success?n.action===`deleted`?o.push(e):a.push(e):u.push(`${e}: ${n.error}`)}for(let e of d)xe.current.delete(e);Se.current=e;let f=r.slice(0,e+1);s.writeFileSync(t,JSON.stringify(f),`utf-8`);let p=`⏮️ Rewound to command: "${r[e]}"`;if(a.length>0||o.length>0){if(p+=`
|
|
103
|
+
|
|
104
|
+
📁 File changes:`,a.length>0){p+=`\n Restored (${a.length}):`;for(let e of a.slice(0,10))p+=`\n • ${l.basename(e)}`;a.length>10&&(p+=`\n ... and ${a.length-10} more`)}if(o.length>0){p+=`\n Deleted (${o.length}):`;for(let e of o.slice(0,10))p+=`\n • ${l.basename(e)}`;o.length>10&&(p+=`\n ... and ${o.length-10} more`)}}else p+=`
|
|
105
|
+
|
|
106
|
+
📁 No file changes to restore.`;if(u.length>0){p+=`\n\n⚠️ Errors (${u.length}):`;for(let e of u.slice(0,5))p+=`\n • ${e}`}let h={role:`system`,content:p,timestamp:new Date};m(e=>[...e,h]),te(f)}catch(e){let t={role:`system`,content:`❌ Error rewinding: ${e instanceof Error?e.message:String(e)}`,timestamp:new Date};m(e=>[...e,t])}},onResumeConversation:e=>{m(e.map(e=>({...e,timestamp:new Date(e.timestamp)})))},spawnedSubagentActive:ue,spawnedSubagentName:fe,spawnedSubagentComplete:pe,queuedMessages:R,isProcessingQueue:ge,initInfo:Y,pendingDeleteConfirmation:Ce,onConfirmDelete:Pe})};var F=class{async execute(t){if(!process.execArgv.some(e=>e.startsWith(`--max-old-space-size`))){let{spawn:e}=await import(`child_process`);e(process.execPath,[`--max-old-space-size=8192`,...process.argv.slice(1)],{stdio:`inherit`,env:process.env}).on(`exit`,e=>{process.exit(e||0)});return}process.stdout.write(`\x1Bc`);let{getAgentApiKey:n,getAgentCredentialStatus:r,CredentialExpiredError:a,CredentialMissingError:o}=await Promise.resolve().then(()=>require(`./agentApiKey-KPaYoRgu.cjs`)),{hasOldSetupFiles:f,migrateFromLocalSetup:p,displayMigrationMessage:m}=await Promise.resolve().then(()=>require(`./setupMigration-C6iULDjK.cjs`));try{let i=process.cwd();f(i)&&m(await p(i));let a=n(),o=r(),h=o.status===`expiring_soon`?o.timeRemaining:void 0;process.env.STACKONE_AGENT_TOKEN||(process.env.STACKONE_AGENT_TOKEN=a);let g=l.join(c.homedir(),`.stackone`,`trusted_directories`),_=[];try{s.existsSync(g)&&(_=s.readFileSync(g,`utf-8`).split(`
|
|
107
|
+
`).filter(e=>e.trim()))}catch(t){e.h.error(`[Trust] Failed to load trusted directories:`,t)}if(!_.includes(i)){let t=!1,{addTrustedFolder:n}=await Promise.resolve().then(()=>require(`./trustedFolders-Dax3_RJQ.cjs`)),{waitUntilExit:r}=(0,u.render)(d.default.createElement(se,{directory:i,onConfirm:()=>{t=!0,n(i)},onCancel:()=>{t=!1}}));await r(),t||(e.h.log(`
|
|
108
|
+
Exiting...`),process.exit(0)),process.stdout.write(`\x1Bc`)}let v=a;if(h){let e={current:`ignore`},{waitUntilExit:t}=(0,u.render)(d.default.createElement(oe,{timeRemaining:h,onRunSetup:()=>{e.current=`setup`},onIgnore:()=>{e.current=`ignore`}}));if(await t(),e.current===`setup`){process.stdout.write(`\x1Bc`);let{spawnSync:e}=await import(`node:child_process`),t=e(process.execPath,[process.argv[1],`agent`,`setup`],{stdio:`inherit`});t.status!==0&&process.exit(t.status??1);let r=n();process.env.STACKONE_AGENT_TOKEN=r,v=r}process.stdout.write(`\x1Bc`)}let{waitUntilExit:y}=(0,u.render)(d.default.createElement(P,{...t,apiKey:v}),{exitOnCtrlC:!1});await y()}catch(t){t instanceof a&&(e.h.error(`
|
|
109
|
+
❌ Credentials Expired
|
|
110
|
+
`),e.h.log(i.default.white(`Your StackOne credentials have expired.
|
|
111
|
+
`)),e.h.log(i.default.white("To continue using the agent, run `stackone agent setup` to reauthenticate.\n")),e.h.log(i.default.dim(`Credentials are valid for 7 days after authentication.
|
|
112
|
+
`)),process.exit(1)),t instanceof o&&(e.h.error(`
|
|
113
|
+
❌ Authentication Required
|
|
114
|
+
`),e.h.log(i.default.white(`You need to authenticate before using the agent.
|
|
115
|
+
`)),e.h.log(i.default.white("To get started, run `stackone agent setup` to authenticate.\n")),e.h.log(i.default.dim(`This will:`)),e.h.log(i.default.dim(` • Authenticate with your StackOne credentials`)),e.h.log(i.default.dim(` • Save your token securely to ~/.stackone/agent-config.json`)),e.h.log(i.default.dim(` • Enable access to StackOne Agent and MCP tools
|
|
116
|
+
`)),e.h.log(i.default.white(`If you already ran setup, your local configuration may be missing or unreadable.`)),e.h.log(i.default.white(`Run setup again to create or repair your authentication configuration.
|
|
117
|
+
`)),process.exit(1));let n=t instanceof Error?t.message:String(t);e.h.error(`
|
|
118
|
+
❌ Error:`,n),e.h.log(i.default.dim(`
|
|
119
|
+
If you continue to see this error, try running:`)),e.h.log(i.default.cyan(` stackone agent setup
|
|
120
|
+
`)),process.exit(1)}}},ue=class{async execute(){e.h.log(i.default.blue.bold(`🧹 StackOne Agent Cleanup
|
|
121
|
+
`));try{let t=(0,p.default)(`Removing stored configuration...`).start();await e.t(),t.succeed(`Removed ~/.stackone/agent-config.json`),e.h.success(`Cleanup complete!`),e.h.log(i.default.white(`
|
|
122
|
+
What was removed:`)),e.h.log(i.default.cyan(` • ~/.stackone/agent-config.json`)),e.h.log(i.default.dim(`
|
|
123
|
+
To authenticate again:`)),e.h.log(i.default.cyan(` stackone agent setup`)),e.h.log(``),process.exit(0)}catch(t){t instanceof Error?e.h.error(t.message):e.h.error(`Unknown error occurred`),process.exit(1)}}},de=class{constructor(e){this.baseUrl=e||process.env.AUTH_SERVER_URL||`https://idp-api.stackone.com`}async login(e,t){try{let n=`${this.baseUrl}/auth/sign-in/mcp`,r=await fetch(n,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({email:e,password:t})});if(!r.ok){let e=await r.text(),t={};try{t=JSON.parse(e)}catch{}return{success:!1,error:t.error||`HTTP ${r.status}: ${r.statusText}`}}let i=await r.text(),a=JSON.parse(i);return a.apiKey?{success:!0,apiKey:a.apiKey}:{success:!1,error:`Invalid response format`}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Network error occurred`}}}async validateKey(e){try{let t=`${this.baseUrl}/api-key/verify`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({key:e})});if(!n.ok){let e=await n.text(),t={};try{t=JSON.parse(e)}catch{}return{valid:!1,error:t.error||`HTTP ${n.status}: ${n.statusText}`}}let r=await n.text();return JSON.parse(r)}catch(e){return{valid:!1,error:e instanceof Error?e.message:`Network error occurred`}}}};const I=new de;function fe(e){let t=new Date(e),n=new Date,r=t.getTime()-n.getTime(),i=Math.floor(r/(1440*60*1e3)),a=Math.floor(r%(1440*60*1e3)/(3600*1e3)),o=t.toLocaleTimeString(`en-US`,{hour:`numeric`,minute:`2-digit`,hour12:!0});return`${t.toLocaleDateString(`en-US`,{weekday:`short`,month:`short`,day:`numeric`})} at ${o} (${i>0?`${i} days, ${a} hours`:`${a} hours`} from now)`}var L=class{async execute(){e.h.log(i.default.blue.bold(`🤖 StackOne Agent Setup - Global Configuration
|
|
124
|
+
`));try{let t=await e.a(),n;if(t?.email){e.h.log(i.default.dim(`Last used email: ${t.email}\n`));let{useExisting:r}=await v.default.prompt([{type:`confirm`,name:`useExisting`,message:`Sign in with this email?`,default:!0}]);if(r)n=t.email;else{let t=(0,_.createInterface)({input:g.stdin,output:g.stdout});n=await new Promise(e=>{t.question(i.default.white(`Email: `),t=>{e(t.trim())})}),t.close(),n||(e.h.error(`Email is required`),process.exit(1))}}else{let t=(0,_.createInterface)({input:g.stdin,output:g.stdout});n=await new Promise(e=>{t.question(i.default.white(`Email: `),t=>{e(t.trim())})}),t.close(),n||(e.h.error(`Email is required`),process.exit(1))}let r=await v.default.prompt([{type:`password`,name:`password`,message:`Password:`,mask:`*`}]);r.password||(e.h.error(`Password is required`),process.exit(1)),e.h.log(``);let a=(0,p.default)(`Authenticating...`).start(),o=await I.login(n,r.password);(!o.success||!o.apiKey)&&(a.fail(`Authentication failed`),e.h.error(`${o.error||`Invalid credentials`}`),e.h.log(i.default.dim(`Please check your email and password and try again.
|
|
125
|
+
`)),process.exit(1)),a.succeed(`Login successful!`);let s=new Date(Date.now()+10080*60*1e3).toISOString();await e.s({apiKey:o.apiKey,userId:n,email:n,expiresAt:s,serverUrl:e.n()}),e.h.success(`API key saved to ~/.stackone/agent-config.json`),e.h.log(i.default.white(`✓ Key expires at`),i.default.cyan(fe(s))),e.h.success(`
|
|
126
|
+
Setup complete!`),e.h.log(i.default.dim(`
|
|
127
|
+
💡 Start the StackOne Agent Chat:`),i.default.cyan(`stackone agent chat`)),e.h.log(``),process.exit(0)}catch(t){t instanceof Error?e.h.error(t.message):e.h.error(`Unknown error occurred`),process.exit(1)}}},pe=class{async execute(t){let{prompt:r,mode:a=`build`,maxTurns:s=25,verbose:c=!1}=t;r.trim()||(e.h.error(`A prompt is required.`),process.exit(1));let l;try{l=n.r()}catch(t){t instanceof Error&&t.name===`CredentialMissingError`?(e.h.error(`
|
|
128
|
+
❌ Authentication Required
|
|
129
|
+
`),e.h.log(i.default.white("Run `stackone agent setup` to authenticate, then try again.\n"))):e.h.error(t instanceof Error?t.message:String(t)),process.exit(1)}let u=ce();c&&(e.h.log(i.default.dim(`Mode: ${a}\n`)),u.length>0&&e.h.log(i.default.dim(`MCP Servers: ${u.map(e=>e.name).join(`, `)}\n`)));let d=null;try{for await(let e of(0,o.executeAgent)({prompt:r.trim(),mode:a,apiKey:l,maxTurns:s,verbose:c,mcpServers:u,origin:`cli`}))me(e,e=>{d&&d.stop(),d=e})}catch(t){d?.fail(),e.h.error(i.default.red(`
|
|
130
|
+
Error: `+(t instanceof Error?t.message:String(t)))),process.exit(1)}d?.stop(),e.h.log(i.default.green(`
|
|
131
|
+
✓ Done
|
|
132
|
+
`))}};function me(t,n){switch(t.type){case`text`:n(null),process.stdout.write(t.content??``);break;case`tool_call`:{let e=t.toolName??`unknown tool`;n((0,p.default)(i.default.cyan(`Tool: ${e}`)).start());break}case`tool_result`:n(null);break;case`tool_progress`:{let e=t.progress?.operation||t.toolName||`Working...`;n((0,p.default)(i.default.cyan(`Tool: ${e}`)).start());break}case`tool_error`:n(null),e.h.error(i.default.red(`\nTool error (${t.toolName}): ${t.error??`Unknown error`}`));break;case`error`:n(null),e.h.error(i.default.red(`\n${t.error??`Unknown error`}`));break;case`done`:n(null);break;default:process.env.VERBOSE&&console.warn(`[AgentRun] Unknown message type:`,t.type);break}}var R=class{async execute(){e.h.log(i.default.blue.bold(`🤖 StackOne Agent Setup - Local Project
|
|
133
|
+
`));try{let t=process.cwd();r.n(t)&&r.t(await r.r(t));let n=await e.a();if(!n||!e.i(n)){e.h.warn(`Not authenticated globally.`),e.h.log(i.default.white(`Let's authenticate now...
|
|
134
|
+
`));let t=(0,_.createInterface)({input:g.stdin,output:g.stdout}),r=await new Promise(e=>{t.question(i.default.white(`Email: `),t=>{e(t.trim())})});t.close(),r||(e.h.error(`Email is required`),process.exit(1));let a=await v.default.prompt([{type:`password`,name:`password`,message:`Password:`,mask:`*`}]);a.password||(e.h.error(`Password is required`),process.exit(1)),e.h.log(``);let o=(0,p.default)(`Authenticating...`).start(),s=await I.login(r,a.password);(!s.success||!s.apiKey)&&(o.fail(`Authentication failed`),e.h.error(`${s.error||`Invalid credentials`}`),e.h.log(i.default.dim(`Please check your email and password and try again.
|
|
135
|
+
`)),process.exit(1)),o.succeed(`Login successful!`);let c=new Date(Date.now()+10080*60*1e3).toISOString();await e.s({apiKey:s.apiKey,userId:r,email:r,expiresAt:c,serverUrl:e.n()}),n={apiKey:s.apiKey,userId:r,email:r,expiresAt:c,serverUrl:e.n()},e.h.log(``)}e.h.success(`Setup complete!`),e.h.log(i.default.white(`
|
|
136
|
+
Token saved to:`)),e.h.log(i.default.cyan(` ~/.stackone/agent-config.json`)),e.h.log(``),process.exit(0)}catch(t){t instanceof Error?e.h.error(t.message):e.h.error(`Unknown error occurred`),process.exit(1)}}},he=class{async execute(t){let n=(0,o.getAvailableSkillNames)(),r=t?.mode;if(e.h.log(i.default.bold(`
|
|
137
|
+
Available skills
|
|
138
|
+
`)),n.length===0){e.h.log(i.default.dim(` No bundled skills found.
|
|
139
|
+
`));return}for(let t of n)e.h.log(` • ${t}`);if(r){let t=(0,o.getSkillsForMode)(r);if(t.length>0){e.h.log(i.default.bold(`\nRecommended for mode "${r}":\n`));for(let r of t){let t=n.includes(r);e.h.log(` • ${r}${t?``:i.default.dim(` (not found)`)}`)}}}e.h.log(``)}};const ge={profiles:{}},z=()=>{let n=e.c.readConfigFile(t.n);if(!n)return ge;try{return JSON.parse(n)}catch{return ge}},B=e=>z().profiles[e],V=e=>!!z().profiles[e],H=(n,r)=>{let i=z();i.profiles[n]=r,e.c.writeConfigFile(t.n,JSON.stringify(i,null,2))},U=()=>{let e=z();return Object.keys(e.profiles)},W=`https://api.stackone.com`;var G=class{async execute({profile:t,connector:n,apiUrl:r,apiKey:a}={}){if(!t&&!a&&(e.h.error(`Profile or API key is required`),e.h.log(`Please provide a profile using the ${e.m(`--profile`)} option or an API key using the ${e.m(`--api-key`)} option.`),e.h.log(`To create a profile, run ${e.m(`stackone init`)}.`),process.exit(1)),t&&a&&(e.h.error(`Please provide either a profile or an API key, not both`),process.exit(1)),t&&r&&e.h.warn(`Specifying ${e.m(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),t&&!V(t)){e.h.error(`Configuration profile ${e.m(t)} not found`),e.h.log(`Run ${e.m(`stackone init`)} to create a new configuration profile.\n`);let n=U();n.length>0&&(e.h.info(`Available configuration profiles:`),n.forEach(t=>{e.h.log(` - ${i.default.blue(t)}`)})),process.exit(1)}let o=t?B(t):{apiUrl:r??W,apiKey:a};o?.apiKey||(e.h.error(`API key is missing`),e.h.log(`Please provide a valid API key in the profile or via the ${e.m(`--api-key`)} option.`),process.exit(1)),n||(e.h.error(`Connector identifier is required in the format provider_key@version.`),process.exit(1));let s=n.split(`@`);(s.length!==2||!s[0]||!s[1])&&(e.h.error(`Invalid connector format ${e.p(n)}. Expected format: ${e.m(`provider_key@version`)}`),process.exit(1));let c=o.apiUrl??W,l=await this.dropConnector(n,c,o.apiKey);process.exit(l?0:1)}async dropConnector(t,n,r){let i=(0,p.default)(`🗑️ Dropping connector ${e.m(t)}...`).start();try{let a=Buffer.from(r).toString(`base64`),o=await fetch(`${n}/registry/connectors/${t}`,{method:`DELETE`,headers:{Authorization:`Basic ${a}`}});return i.stop(),o.status===204?(e.h.success(`Successfully dropped connector ${e.m(t)} from the registry`),!0):o.status===404?(e.h.error(`Connector ${e.m(t)} not found in the registry`),!1):o.status===401||o.status===403?(e.h.error(`You do not have permission to drop this connector`),!1):o.status===409?(e.h.error(`Connector ${e.m(t)} has associated configs and cannot be dropped`),e.h.log(`Please delete all associated integration configurations before dropping the connector.`),!1):(o.ok||await e.f(o,`Failed to drop connector ${e.m(t)} from the registry`),!1)}catch(r){return i.stop(),e.h.error(`Failed to drop connector ${e.m(t)} from registry: ${r.message}`),e.h.log(`Please ensure that the API at ${e.g(n)} is reachable and the API key is valid`),!1}}};const K=`stackone`;async function _e(t,n){n.length===0&&(e.h.error(`Multiple versions of connector ${e.m(t)} were found but no owner information was returned`),process.exit(1));let r=n.map(e=>({value:e,label:e===K?`StackOne`:`Custom`,hint:e===K?`Official StackOne connector`:`Custom connector version created by your organization`}));e.h.warn(`Multiple versions of connector ${e.m(t)} were found. Please select which version to use.`);let i=await(0,b.select)({message:`Which version would you like to use?`,options:r});return(0,b.isCancel)(i)&&(e.h.error(`Operation cancelled.`),process.exit(1)),i}const ve=`https://api.stackone.com`;var q=class{async execute({profile:t,connector:n,accountId:r,format:a,outputFile:o,apiUrl:s,apiKey:c,owner:l}={}){if(!t&&!c&&(e.h.error(`Profile or API key is required`),e.h.log(`Please provide a profile using the ${e.m(`--profile`)} option or an API key using the ${e.m(`--api-key`)} option.`),e.h.log(`To create a profile, run ${e.m(`stackone init`)}.`),process.exit(1)),t&&c&&(e.h.error(`Please provide either a profile or an API key, not both`),process.exit(1)),t&&s&&e.h.warn(`Specifying ${e.m(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),t&&!V(t)){e.h.error(`Configuration profile ${e.m(t)} not found`),e.h.log(`Run ${e.m(`stackone init`)} to create a new configuration profile.\n`);let n=U();n.length>0&&(e.h.info(`Available configuration profiles:`),n.forEach(t=>{e.h.log(` - ${i.default.blue(t)}`)})),process.exit(1)}let u=t?B(t):{apiUrl:s??ve,apiKey:c};u?.apiKey||(e.h.error(`API key is missing`),e.h.log(`Please provide a valid API key in the profile or via the ${e.m(`--api-key`)} option.`),process.exit(1)),(0,y.isMissing)(n)&&(0,y.isMissing)(r)&&(e.h.error(`Either ${e.m(`--connector`)} or ${e.m(`--account-id`)} must be provided`),process.exit(1)),(0,y.notMissing)(n)&&(0,y.notMissing)(r)&&(e.h.error(`Please provide either ${e.m(`--connector`)} or ${e.m(`--account-id`)}, not both.`),process.exit(1)),(0,y.notMissing)(a)&&a!==`yaml`&&a!==`json`&&(e.h.error(`Format must be either ${e.m(`yaml`)} or ${e.m(`json`)}.`),process.exit(1));let d=u.apiUrl??ve,f;if((0,y.notMissing)(n)){this.#t(n)||(e.h.error(`Invalid connector format ${e.p(n)}. Expected format: ${e.m(`provider_key@version`)} or ${e.m(`provider_key`)}`),process.exit(1));let t=this.#n(n);f=await this.#r(t,d,u.apiKey,a,l)}else (0,y.notMissing)(r)?f=await this.#i(r,d,u.apiKey,a):(e.h.error(`Either ${e.m(`--connector`)} or ${e.m(`--account-id`)} must be provided`),process.exit(1));if((0,y.notMissing)(o))try{m.default.writeFileSync(o,f,`utf-8`),e.h.success(`Connector written to file: ${e.m(o)}`)}catch(t){e.h.error(`Failed to write connector to file ${e.m(o)}: ${t.message}`),process.exit(1)}else if(e.h.log(`\n${i.default.blue.inverse(` CONNECTOR CONTENT `)}\n`),!a||a===`yaml`)e.h.log(this.#e(f));else if(a===`json`)try{e.d(JSON.parse(f))}catch{e.h.log(f)}else e.h.log(f);process.exit(0)}#e(e){return e.split(`
|
|
140
|
+
`).map(e=>{if(e.trim().startsWith(`#`))return i.default.gray(e);if(e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t+1),r=e.substring(t+1),a=r,o=r.trim();return o===`true`||o===`false`?a=r.replace(o,i.default.cyan(o)):o===`null`||o===`~`?a=r.replace(o,i.default.gray(o)):/^-?\d+(\.\d+)?$/.test(o)?a=r.replace(o,i.default.green(o)):(o.startsWith(`"`)&&o.endsWith(`"`)||o.startsWith(`'`)&&o.endsWith(`'`)||o&&!o.startsWith(`-`))&&(a=r.replace(o,i.default.yellow(o))),i.default.red(n)+a}return e.trim().startsWith(`-`)?e.replace(`-`,i.default.gray(`-`)):e}).join(`
|
|
141
|
+
`)}#t=e=>!e.includes(`/`)&&!e.includes(`\\`)&&!e.endsWith(`.yaml`)&&!e.endsWith(`.yml`)?e.includes(`@`)?e.split(`@`).length===2:!0:!1;#n=e=>e.includes(`@`)?e:`${e}@latest`;async#r(t,n,r,i,a){let o=(0,p.default)(`Getting connector ${e.m(t)} from registry...`).start();try{let s=Buffer.from(r).toString(`base64`),c=i?`?format=${i}`:``,l=a?`${c?`&`:`?`}owner=${encodeURIComponent(a)}`:``,u=await fetch(`${n}/registry/connectors/${t}${c}${l}`,{method:`GET`,headers:{Authorization:`Basic ${s}`}});if(o.stop(),u.status===409){a&&(await e.f(u,`Failed to get connector ${e.m(t)} from the registry`),process.exit(1));let r=await _e(t,(await u.json()).availableOwners??[]),i=`${n}/registry/connectors/${t}${c}${c?`&`:`?`}owner=${encodeURIComponent(r)}`;o.text=`Getting connector ${e.m(t)} from registry...`,o.start();let l=await fetch(i,{method:`GET`,headers:{Authorization:`Basic ${s}`}});return o.stop(),l.ok||(await e.f(l,`Failed to get connector ${e.m(t)} from the registry`),process.exit(1)),await l.text()}return u.ok||(await e.f(u,`Failed to get connector ${e.m(t)} from the registry`),process.exit(1)),await u.text()}catch(r){o.stop(),e.h.error(`Failed to get connector ${e.m(t)} from the registry: ${r.message}`),e.h.log(`Please ensure that the API at ${e.g(n)} is reachable and the API key is valid`),process.exit(1)}}async#i(t,n,r,i){let a=(0,p.default)(`Getting connector from account ${e.m(t)}...`).start();try{let o=Buffer.from(r).toString(`base64`),s=i?`?format=${i}`:``,c=await fetch(`${n}/accounts/${t}/connector${s}`,{method:`GET`,headers:{Authorization:`Basic ${o}`}});return a.stop(),c.ok||(await e.f(c,`Failed to get connector from account ${e.m(t)}`),process.exit(1)),await c.text()}catch(r){a.stop(),e.h.error(`Failed to get connector from account ${e.m(t)}: ${r.message}`),e.h.log(`Please ensure that the API at ${e.g(n)} is reachable and the API key is valid`),process.exit(1)}}};const ye=`https://api.stackone.com`,J=`https://api.stackone-dev.com`,Y=`http://localhost:4000`;var X=class{async execute({environment:t}={}){let n=t?.toLowerCase()??`production`;try{(0,b.intro)(`${i.default.inverse(` Initialize profile `)}`);let t=await(0,b.text)({message:`Profile label`,validate:e=>{if(!e||e.trim().length===0)return`The profile label is required`;if(e.includes(` `))return`The profile label cannot contain spaces`}});if((0,b.isCancel)(t))return(0,b.cancel)(`Configuration profile initialization cancelled`),process.exit(0);if(V(t)){let n=await(0,b.confirm)({message:`Configuration profile with name ${e.m(t)} already exists. Do you want to overwrite it?`});if((0,b.isCancel)(n)||!n)return(0,b.cancel)(`Configuration profile initialization cancelled`),process.exit(0)}let r;if(n===`production`)r=`https://api.stackone.com`;else if(n===`staging`)r=`https://api.stackone-dev.com`;else{let e=await(0,b.text)({message:`API URL`,placeholder:Y,initialValue:Y,validate:e=>{if(!e||e.trim().length===0)return`API URL is required`;try{new URL(e)}catch{return`Please enter a valid URL`}}});if((0,b.isCancel)(e))return(0,b.cancel)(`Configuration profile initialization cancelled`),process.exit(0);r=e}let a=await(0,b.password)({message:`API Key`,validate:e=>{if(!e||e.trim().length===0)return`API Key is required`}});if((0,b.isCancel)(a))return(0,b.cancel)(`Configuration profile initialization cancelled`),process.exit(0);H(t,{label:t,environment:n,apiUrl:r,apiKey:a}),(0,b.outro)(`${i.default.green(`✔`)} Configuration profile ${e.m(t)} initialized successfully!`),process.exit(0)}catch(t){t?.isTtyError?e.h.error(`Prompt couldn't be rendered in the current environment`):e.h.error(`Failed to initialize configuration profile: ${t}`),process.exit(1)}}};const be=20,Z={pending:`○`,acceptRemote:`●`,acceptLocal:`◐`,acceptBoth:`◑`,current:`◉`,arrow:`→`,check:`✓`,cross:`✗`,warning:`⚠`};var xe=class{constructor(e,t,n,r){this.conflicts=[],this.currentIndex=0,this.totalConflicts=0,this.currentCleanup=null,this.connectorId=t,this.localVersion=n,this.remoteVersion=r,this.conflicts=e.map(e=>({conflict:e,choice:e.type===`unchanged`?`remote`:`pending`})),this.totalConflicts=e.filter(e=>e.type===`conflict`).length}resetForReResolution(){this.currentIndex=0}async resolve(){return this.totalConflicts===0?{cancelled:!1,states:this.conflicts}:(this.moveToNextConflict(),new Promise(e=>{let t=(0,C.createInterface)({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),this.render();let n=n=>{let r=n.toString();if(r===``){this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});return}if(r===`\x1B`&&n.length===1){this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});return}if(r.startsWith(`\x1B[`)){switch(r.slice(2)){case`D`:this.moveToPrevConflict(),this.render();break;case`C`:this.moveToNextConflict(),this.render();break}return}switch(r){case`r`:case`R`:this.setCurrentChoice(`remote`),this.advanceAfterChoice(t);break;case`l`:case`L`:this.setCurrentChoice(`local`),this.advanceAfterChoice(t);break;case`b`:case`B`:this.setCurrentChoice(`both`),this.advanceAfterChoice(t);break;case`\r`:case`
|
|
142
|
+
`:this.allResolved()?(this.cleanup(t),e({cancelled:!1,states:this.conflicts})):(this.moveToNextUnresolved(),this.render());break;case`q`:case`Q`:this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});break;case`a`:case`A`:this.acceptAllRemaining(`remote`),this.render();break;case`u`:case`U`:this.setCurrentChoice(`pending`),this.render();break}};process.stdin.on(`data`,n),this.currentCleanup=()=>{process.stdin.removeListener(`data`,n),process.stdin.isTTY&&process.stdin.setRawMode(!1),t.close()}}))}cleanup(e){this.currentCleanup?(this.currentCleanup(),this.currentCleanup=null):(process.stdin.isTTY&&process.stdin.setRawMode(!1),e.close())}advanceAfterChoice(e){this.allResolved()||this.moveToNextUnresolved(),this.render()}render(){e.l();let t=process.stdout.columns||80;this.renderHeader(t),this.renderProgressBar(t),this.renderCurrentConflict(t),this.renderControls(t)}renderHeader(t){let n=this.connectorId,r=`${this.localVersion} ${Z.arrow} ${this.remoteVersion}`,a=Math.max(0,t-17),o=Math.floor(a/2),s=a-o,c=` `.repeat(o)+`CONFLICT RESOLVER`+` `.repeat(s);e.h.log(``),e.h.log(i.default.bgBlue.white.bold(c)),e.h.log(i.default.gray(this.centerText(n,t))),e.h.log(i.default.gray(this.centerText(r,t))),e.h.log(``)}renderProgressBar(t){let n=this.conflicts.filter(e=>e.conflict.type===`conflict`),r=this.getCurrentConflictIndex(),a=n.map((e,t)=>{let n=t===r,a,o;switch(e.choice){case`remote`:a=n?Z.current:Z.acceptRemote,o=i.default.green;break;case`local`:a=n?Z.current:Z.acceptLocal,o=i.default.yellow;break;case`both`:a=n?Z.current:Z.acceptBoth,o=i.default.cyan;break;default:a=n?Z.current:Z.pending,o=n?i.default.white:i.default.gray}return o(a)}),o=n.filter(e=>e.choice!==`pending`).length,s=` Conflict ${r+1} of ${this.totalConflicts} • ${o}/${this.totalConflicts} resolved `;e.h.log(i.default.gray(this.centerText(s,t))),e.h.log(this.centerText(a.join(` `),t)),e.h.log(``)}renderCurrentConflict(t){let n=this.conflicts[this.currentIndex];if(!n||n.conflict.type!==`conflict`)return;let r=n.conflict;if(e.h.log(i.default.gray(`_`.repeat(t))),e.h.log(`
|
|
143
|
+
|
|
144
|
+
`),r.local){let t=n.choice===`local`||n.choice===`both`?i.default.yellow.bold(`${Z.check} LOCAL (keeping)`):i.default.red.bold(`${Z.cross} LOCAL (removing)`),a=r.local.split(`
|
|
145
|
+
`).filter(e=>e!==``),o=a.slice(0,20),s=n.choice===`local`||n.choice===`both`?i.default.yellow:i.default.red,c=o.map(e=>s(`- ${e}`)).join(`
|
|
146
|
+
`),l=a.length>20?`\n${i.default.gray(`... and ${a.length-20} more lines`)}`:``;e.h.log(`${t}\n\n${c}${l}`)}if(e.h.log(`
|
|
147
|
+
|
|
148
|
+
`),e.h.log(i.default.gray(`_`.repeat(t))),e.h.log(`
|
|
149
|
+
|
|
150
|
+
`),r.remote){let t=n.choice===`remote`||n.choice===`both`?i.default.green.bold(`${Z.check} REMOTE (accepting)`):i.default.gray.bold(`${Z.pending} REMOTE (skipping)`),a=r.remote.split(`
|
|
151
|
+
`).filter(e=>e!==``),o=a.slice(0,20),s=n.choice===`remote`||n.choice===`both`?i.default.green:i.default.gray,c=o.map(e=>s(`+ ${e}`)).join(`
|
|
152
|
+
`),l=a.length>20?`\n${i.default.gray(`... and ${a.length-20} more lines`)}`:``;e.h.log(`${t}\n\n${c}${l}`)}e.h.log(`
|
|
153
|
+
|
|
154
|
+
`),e.h.log(i.default.gray(`_`.repeat(t))),e.h.log(``)}renderControls(t){let n=[i.default.green(`[R] Accept Remote`),i.default.yellow(`[L] Keep Local`),i.default.cyan(`[B] Keep Both`),i.default.gray(`[U] Undo`)],r=[i.default.gray(`[←/→] Navigate`),i.default.gray(`[A] Accept all remaining`)],a=this.allResolved()?[i.default.green.bold(`[Enter] Apply Changes`),i.default.gray(`[Esc] Cancel`)]:[i.default.gray(`[Enter] Next Unresolved`),i.default.gray(`[Esc] Cancel`)];e.h.log(this.centerText(n.join(` `),t)),e.h.log(``),e.h.log(this.centerText(r.join(` `),t)),e.h.log(``),e.h.log(this.centerText(a.join(` `),t)),this.allResolved()&&(e.h.log(``),e.h.log(i.default.green.bold(this.centerText(`✓ All conflicts resolved!`,t))))}renderFinalSummary(){e.l();let t=this.conflicts.filter(e=>e.conflict.type===`conflict`),n=0,r=0,a=0;for(let e of t)switch(e.choice){case`remote`:n++;break;case`local`:r++;break;case`both`:a++;break}let o=[i.default.green.bold(`Conflict resolution complete`),``,`${i.default.bold(this.totalConflicts)} conflicts resolved:`,``,`${i.default.green(Z.acceptRemote)} Accepted remote: ${n}`,`${i.default.yellow(Z.acceptLocal)} Kept local: ${r}`,`${i.default.cyan(Z.acceptBoth)} Kept both: ${a}`];e.h.box(o.join(`
|
|
155
|
+
`))}renderCancelled(){e.l(),e.h.log(i.default.yellow(`Conflict resolution cancelled`)),e.h.log(``),e.h.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 Se=`https://api.stackone.com`,Ce=3;var Q=class{async execute({profile:t,connector:n,outputPath:r,apiUrl:a,apiKey:o,owner:s}={}){if((0,y.isMissing)(n)&&(e.h.error(`Connector identifier is required`),e.h.log(`Please provide a connector identifier using the ${e.m(`--connector`)} option in the format: ${e.m(`provider_key@version`)} or ${e.m(`provider_key`)}`),e.h.log(`If no version is specified, the latest version will be pulled.`),process.exit(1)),!t&&!o&&(e.h.error(`Profile or API key is required`),e.h.log(`Please provide a profile using the ${e.m(`--profile`)} option or an API key using the ${e.m(`--api-key`)} option.`),e.h.log(`To create a profile, run ${e.m(`stackone init`)}.`),process.exit(1)),t&&o&&(e.h.error(`Please provide either a profile or an API key, not both`),process.exit(1)),t&&a&&e.h.warn(`Specifying ${e.m(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),t&&!V(t)){e.h.error(`Configuration profile ${e.m(t)} not found`),e.h.log(`Run ${e.m(`stackone init`)} to create a new configuration profile.\n`);let n=U();n.length>0&&(e.h.info(`Available configuration profiles:`),n.forEach(t=>{e.h.log(` - ${i.default.blue(t)}`)})),process.exit(1)}let c=t?B(t):{apiUrl:a??Se,apiKey:o};c?.apiKey||(e.h.error(`API key is missing`),e.h.log(`Please provide a valid API key in the profile or via the ${e.m(`--api-key`)} option.`),process.exit(1));let l=c.apiUrl??Se,[u,d]=n.split(`@`),f=await this.#f(u,l,c.apiKey,d??`latest`,s),p=this.#e(f),m=p.version??`unknown`,h=this.#t(r,p.key,m),g=this.#r(h),_=g===null,v=f;if(!_){let t=this.#i(g,h);t&&(e.h.warn(t.message),t.errors.length>0&&e.u(t.errors,!1),e.h.log(``));let r=t?void 0:this.#e(g);if(this.#o(g,f)){this.#a(g,f,h);let t=r?.version??`unknown`,i=await this.#s(g,f,n,t,m);i.action===`cancel`&&((0,b.cancel)(`Pull cancelled`),process.exit(0)),i.action===`keep-local`&&(e.h.log(``),e.h.info(`Keeping local version. No changes made.`),process.exit(0)),i.action===`interactive-cancel`&&process.exit(0),i.action===`interactive`&&(v=i.resolvedContent)}else e.h.info(`No changes detected in connector configuration.`),process.exit(0)}let S=(0,x.validateYamlConnector)(v).connector,C=S?.key??p.key,w=S?.version??m,T=this.#t(r,C,w),E=T;if(T!==h){let t=await this.#n(T);e.h.log(``),t!==void 0&&(E=t)}await this.#d(E,v),_?e.h.success(`Connector ${e.m(C)}@${e.m(w)} pulled successfully (new connector)`):e.h.success(`Connector ${e.m(C)}@${e.m(w)} updated successfully`);let ee=C===p.key?e.m(C):`${e.m(p.key)} ${i.default.whiteBright(`→`)} ${e.m(C)}`,te=w===m?e.m(w):`${e.m(m)} ${i.default.whiteBright(`→`)} ${e.m(w)}`,D=E===h?e.m(E):`${e.m(h)}\n ${i.default.whiteBright(`→`)} ${e.m(E)}`;e.h.log(`\n${i.default.blue.inverse(` CONNECTOR DETAILS `)}\n`),e.h.log(` Provider: ${ee}`),e.h.log(` Version: ${te}`),e.h.log(` Output file: ${D}`),process.exit(0)}#e(t){let n=(0,x.validateYamlConnector)(t),r=n?.errors??[];if(n.success)return n.connector;e.h.error(`Connector pulled from the registry is not valid`),e.h.log(`Please make sure you are using the latest version of the StackOne CLI by running ${e.m(`stackone update`)}`),r.length>0&&e.u(r,!0),process.exit(1)}#t(t,n,r){let i=`${n}_v${r.replaceAll(`.`,`-`)}.s1.yaml`;return t?(m.default.existsSync(t)&&(m.default.statSync(t).isDirectory()||(e.h.error(`Output path ${e.m(t)} is not a directory`),e.h.log(`Please provide a valid directory path to store connectors or use the default path.`),process.exit(1))),h.default.resolve(t,n,i)):h.default.resolve(process.cwd(),`connectors`,n,i)}async#n(t){if(!m.default.existsSync(t))return;let n=h.default.basename(t),r=h.default.dirname(t);e.h.warn(`File ${e.m(n)} already exists at ${e.m(r)}`);let i=await(0,b.select)({message:`How would you like to proceed?`,options:[{value:`override`,label:`Override existing file`,hint:`Replace the existing file with the new content`},{value:`rename`,label:`Save with a different name`,hint:`Provide a new filename for the connector`},{value:`cancel`,label:`Cancel`,hint:`Abort the pull operation`}]});if(((0,b.isCancel)(i)||i===`cancel`)&&((0,b.cancel)(`Operation cancelled. No local changes were made.`),process.exit(0)),i===`override`)return;let a=await(0,b.text)({message:`Enter the new filename:`,placeholder:n,validate:e=>{if(!e||e.trim()===``)return`Filename cannot be empty`;if(!e.endsWith(`.s1.yaml`))return`Filename must end with .s1.yaml`;let t=h.default.join(r,e.trim());if(m.default.existsSync(t))return`File ${e} already exists`}});return(0,b.isCancel)(a)&&((0,b.cancel)(`Operation cancelled. No local changes were made.`),process.exit(0)),h.default.join(r,a.trim())}#r(e){if(!m.default.existsSync(e))return null;try{return m.default.readFileSync(e,`utf-8`)}catch{return null}}#i(t,n){try{let r=(0,x.validateYamlConnector)(t);if(!r.success){let t=r.errors??[];return{message:`Local connector ${e.m(h.default.basename(n))} has validation errors:`,errors:t}}}catch(t){return{message:`Local connector ${e.m(h.default.basename(n))} could not be validated: ${t.message}`,errors:[]}}return null}#a(t,n,r){let a=(0,S.diffLines)(t,n);if(!a.some(e=>e.added||e.removed)){e.h.info(`No changes detected in connector configuration.`);return}e.h.log(`${i.default.blue.inverse(` CHANGES `)}\n`),e.h.log(i.default.gray(`--- local: ${r}`)),e.h.log(i.default.gray(`+++ remote: StackOne Registry`)),e.h.log(``);let o=0,s=0;for(let t of a){let n=t.value.split(`
|
|
156
|
+
`).filter(e=>e!==``);if(t.added){o+=n.length;for(let t of n)e.h.log(i.default.green(`+ ${t}`))}else if(t.removed){s+=n.length;for(let t of n)e.h.log(i.default.red(`- ${t}`))}else if(n.length<=6)for(let t of n)e.h.log(i.default.gray(` ${t}`));else{for(let t=0;t<3;t++)e.h.log(i.default.gray(` ${n[t]}`));e.h.log(i.default.gray(` ... (${n.length-6} unchanged lines)`));for(let t=n.length-3;t<n.length;t++)e.h.log(i.default.gray(` ${n[t]}`))}}e.h.log(``),e.h.log(i.default.gray(`Summary: ${i.default.green(`+${o}`)} additions, ${i.default.red(`-${s}`)} deletions`))}#o(e,t){return(0,S.diffLines)(e,t).some(e=>e.added||e.removed)}async#s(t,n,r,i,a){e.h.log(``);let o=await(0,b.select)({message:`How would you like to resolve the differences?`,options:[{value:`override`,label:`Override local with remote`,hint:`Replace your local file with the StackOne version`},{value:`keep-local`,label:`Keep local version`,hint:`Cancel the pull and keep your current file`},{value:`interactive`,label:`Resolve conflicts interactively`,hint:`Choose which changes to accept one by one`},{value:`cancel`,label:`Cancel`,hint:`Abort the pull operation`}]});if((0,b.isCancel)(o))return{action:`cancel`};if(o===`override`)return{action:`override`};if(o===`keep-local`)return{action:`keep-local`};if(o===`interactive`){let e=await this.#c(t,n,r,i,a);return e===null?{action:`interactive-cancel`}:{action:`interactive`,resolvedContent:e}}return{action:`cancel`}}async#c(t,n,r,i,a){let o=(0,S.diffLines)(t,n),s=this.#u(o);if(s.length===0)return e.h.info(`No conflicts to resolve.`),n;let c=new xe(s,r,i,a);for(;;){if((await c.resolve()).cancelled)return null;let t=c.getResolvedContent(),n=(0,x.validateYamlConnector)(t);if(n.success)return c.renderFinalSummary(),t;let r=await this.#l(n.errors);if(r===`cancel`)return e.l(),e.h.info(`Operation cancelled. No changes were made to the local connector.`),null;if(r===`save`)return e.l(),e.h.warn(`The connector was saved but it is invalid`),t;c.resetForReResolution()}}async#l(t){let{createInterface:n}=await import(`readline`);return new Promise(r=>{e.l();let a=(t||[{message:`Unknown validation error`}]).map(e=>` • ${e.message}`).join(`
|
|
157
|
+
`);e.h.box({title:`⚠️ Validation Failed`,message:`The resolved connector configuration is invalid:\n\n${a}`,style:{borderColor:`yellow`,padding:1}}),e.h.log(``),e.h.log(i.default.bold(` Choose an action:`)),e.h.log(``),e.h.log(i.default.cyan(` [B]`)+` ← Go back to conflict resolution`),e.h.log(i.default.dim(` Modify your choices to fix the validation errors`)),e.h.log(``),e.h.log(i.default.yellow(` [S]`)+` 💾 Save anyway`),e.h.log(i.default.dim(` Save the invalid configuration (not recommended)`)),e.h.log(``),e.h.log(i.default.red(` [C]`)+` ✖ Cancel`),e.h.log(i.default.dim(` Discard all changes`)),e.h.log(``);let o=n({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();let s=e=>{let t=e.toString().toLowerCase(),n=()=>{process.stdin.removeListener(`data`,s),process.stdin.isTTY&&process.stdin.setRawMode(!1),o.close()};if(t===``||t===`\x1B`){n(),r(`cancel`);return}switch(t){case`b`:n(),r(`back`);break;case`s`:n(),r(`save`);break;case`c`:case`q`:n(),r(`cancel`);break}};process.stdin.on(`data`,s)})}#u(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(!r.added&&!r.removed)t.push({type:`unchanged`,content:r.value}),n++;else if(r.removed){let i=e[n+1];i?.added?(t.push({type:`conflict`,local:r.value,remote:i.value}),n+=2):(t.push({type:`conflict`,local:r.value,remote:void 0}),n++)}else r.added&&t.push({type:`conflict`,local:void 0,remote:r.value}),n++}return t}async#d(t,n){let r=h.default.dirname(t);m.default.existsSync(r)||m.default.mkdirSync(r,{recursive:!0});try{m.default.writeFileSync(t,n,`utf-8`)}catch(n){e.h.error(`Failed to write connector to file ${e.m(t)}: ${n.message}`),process.exit(1)}}async#f(t,n,r,i,a){let o=(0,p.default)(`Pulling connector ${e.m(t)}@${e.m(i)} from registry...`).start();try{let s=Buffer.from(r).toString(`base64`),c=`${n}/registry/connectors/${t}@${i}${a?`?owner=${encodeURIComponent(a)}`:``}`,l=await fetch(c,{method:`GET`,headers:{Authorization:`Basic ${s}`}});if(o.stop(),l.status===409){a&&(await this.#p(l,t,i),process.exit(1));let r=(await l.json()).availableOwners??[],c=await _e(`${t}@${i}`,r);o.text=`Pulling connector ${e.m(t)}@${e.m(i)} from registry...`,o.start();let u=`${n}/registry/connectors/${t}@${i}`,d=await fetch(`${u}?owner=${encodeURIComponent(c)}`,{method:`GET`,headers:{Authorization:`Basic ${s}`}});return o.stop(),d.ok||(await this.#p(d,t,i),process.exit(1)),await d.text()}return l.ok||(await this.#p(l,t,i),process.exit(1)),await l.text()}catch(r){o.stop(),e.h.error(`Failed to pull connector ${e.m(t)}@${e.m(i)} from the registry: ${r.message}`),e.h.log(`Please ensure that the API at ${e.g(n)} is reachable and the API key is valid.`),process.exit(1)}}async#p(t,n,r){switch(t.status){case 401:case 403:e.h.error(`Access denied`),e.h.log(`Please ensure that your API key is valid and has the ${e.m(`connectors:read`)} scope required to pull connectors.`);break;case 404:e.h.error(`Connector ${e.m(n)}@${e.m(r)} was not found in the registry`),await this.#m(n);break;case 429:e.h.error(`Rate limit exceeded`),e.h.log(`Too many requests. Please wait a moment before trying again.`);break;default:await e.f(t,`Failed to pull connector ${e.m(n)}`)}}async#m(t){e.h.info(`To see available versions, check the connector documentation or contact support.`)}};const we=`https://api.stackone.com`;var $=class{async execute({profile:t,fileOrDir:n,apiUrl:r,apiKey:a}={}){if(!t&&!a&&(e.h.error(`Profile or API key is required`),e.h.log(`Please provide a profile using the ${e.m(`--profile`)} option or an API key using the ${e.m(`--api-key`)} option.`),e.h.log(`To create a profile, run ${e.m(`stackone init`)}.`),process.exit(1)),t&&a&&(e.h.error(`Please provide either a profile or an API key, not both`),process.exit(1)),t&&r&&e.h.warn(`Specifying ${e.m(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),t&&!V(t)){e.h.error(`Configuration profile ${e.m(t)} not found`),e.h.log(`Run ${e.m(`stackone init`)} to create a new configuration profile.\n`);let n=U();n.length>0&&(e.h.info(`Available configuration profiles:`),n.forEach(t=>{e.h.log(` - ${i.default.blue(t)}`)})),process.exit(1)}let o=t?B(t):{apiUrl:r??we,apiKey:a};o?.apiKey||(e.h.error(`API key is missing`),e.h.log(`Please provide a valid API key in the profile or via the ${e.m(`--api-key`)} option.`),process.exit(1)),n||(e.h.error(`File or directory is required.`),process.exit(1));try{(0,m.statSync)(n)}catch{e.h.error(`File or directory not found: ${i.default.red(n)}`),process.exit(1)}let s=(0,m.statSync)(n),c=o.apiUrl??we;if(s.isDirectory()){let t=Oe(n),r=0;t.length===0?(e.h.error(`No .s1.yaml connector files found in the directory: ${n}.`),process.exit(1)):(e.h.start(`Found ${t.length} connector(s) file(s). Pushing to registry...`),e.h.log(``));for(let e of t)await this.uploadFile(e,c,o.apiKey)&&r++;r===0?e.h.error(`Error while pushing connectors: no files were uploaded`):(e.h.log(``),e.h.info(`Upload completed: ${i.default.green(r)} of ${i.default.blue(t.length)} file(s) uploaded successfully.`)),process.exit(r>0?0:1)}else n.endsWith(`.s1.yaml`)||(e.h.error(`Only ${e.m(`.s1.yaml`)} files are supported for upload`),process.exit(1));let l=await this.uploadFile(n,c,o.apiKey);process.exit(l?0:1)}async uploadFile(t,n,r){let i=(0,p.default)(`📤 Pushing connector in ${(0,h.basename)(t)}...`).start();try{let a=De(t);if(!a)return!1;let o=(0,h.basename)(t),s=new FormData,c=new Blob([a],{type:`application/x-yaml`});s.append(`file`,c,o);let l=Buffer.from(r).toString(`base64`),u=await fetch(`${n}/registry/connectors`,{method:`POST`,headers:{Authorization:`Basic ${l}`},body:s});if(i.stop(),!u.ok)return u.status===409||u.status===422?await this.handleVersionConflict(u,t,n,r):(await e.f(u,`Failed to push connector in ${e.m(o)} to the registry`),!1);let d=await u.json();return e.h.success(`Successfully uploaded ${e.m(o)} with connector ${e.m(d.provider)}@${e.m(d.version)}`),!0}catch(r){return i.stop(),e.h.error(`Failed to upload file ${e.m(t)}: ${r}`),e.h.log(`Please ensure that the API at ${e.g(n)} is reachable and the API key is valid`),!1}}async handleVersionConflict(t,n,r,i){let a=await t.text(),o;try{o=JSON.parse(a)}catch{}let s=w.default.valid(o?.latestVersion);if(!s)return await e.f(new Response(a,{status:t.status,statusText:t.statusText}),`Failed to push connector in ${e.m((0,h.basename)(n))} to the registry`),!1;let c=(0,m.readFileSync)(n,`utf-8`),l=Te(c),u=l?`${e.m(l)}`:``,d=t.status===409?`Version ${u} already exists in the registry. Latest version: ${e.m(s)}`:`Version ${u} is lower than the latest version in the registry. Latest version: ${e.m(s)}`;e.h.error(d);let f=w.default.inc(s,`patch`)??s,p=w.default.inc(s,`minor`)??s,g=w.default.inc(s,`major`)??s,_=await(0,b.select)({message:`How would you like to proceed?`,options:[{value:f,label:`Bump patch version (${f})`},{value:p,label:`Bump minor version (${p})`},{value:g,label:`Bump major version (${g})`},{value:`cancel`,label:`Cancel push`}]});return(0,b.isCancel)(_)||_===`cancel`?((0,b.cancel)(`Push cancelled`),!1):((0,m.writeFileSync)(n,Ee(c,_),`utf-8`),e.h.info(`Updated version to ${e.m(_)} in ${(0,h.basename)(n)}`),this.uploadFile(n,r,i))}};const Te=e=>e.match(/^\s*version: (\S+)/m)?.[1],Ee=(e,t)=>e.replace(/^(\s*version: )\S+/m,`$1${t}`),De=t=>{let n=(0,x.loadConnector)(t),r=(0,x.validateYamlConnector)(n),i=r?.errors??[];if(r.success)return n;i.length>0?(e.h.error(`Connector in ${e.p(t)} is not valid`),e.u(i,!0)):e.h.error(`Connector in ${e.p(t)} is not valid. Please check the file for errors.`)},Oe=e=>{let t=[],n=(0,m.readdirSync)(e,{withFileTypes:!0});for(let r of n){let n=(0,h.join)(e,r.name);r.isDirectory()?t.push(...Oe(n)):r.name.endsWith(`.s1.yaml`)&&t.push(n)}return t},ke=y.z.object({provider_key:y.z.string().optional(),provider_version:y.z.string().optional(),auth_config_key:y.z.string(),environment:y.z.string().default(`production`),organization_id:y.z.string().default(`cli-organization-id`),account_id:y.z.string().default(`cli-account-secure-id`),project_id:y.z.string().default(`cli-project-secure-id`),credentials:y.z.record(y.z.string(),y.z.any()).default({})}),Ae=y.z.record(y.z.string(),y.z.any()),je=y.z.object({path:y.z.record(y.z.string(),y.z.any()).default({}),queryParams:y.z.record(y.z.string(),y.z.any()).default({}),header:y.z.record(y.z.string(),y.z.any()).default({}),body:y.z.record(y.z.string(),y.z.any()).default({})}),Me=`https://api.stackone.com`;var Ne=class{async execute({connector:t,action:n,actionId:r,account:a,accountId:o,params:s,credentials:c,profile:l,outputFile:u,debug:d,apiUrl:f,apiKey:p,owner:h}={}){if(!l&&!p&&o&&(e.h.error(`Profile or API key is required when providing an account ID`),e.h.log(`Please provide a profile using the ${e.m(`--profile`)} option or an API key using the ${e.m(`--api-key`)} option.`),e.h.log(`To create a profile, run ${e.m(`stackone init`)}.`),process.exit(1)),l&&p&&(e.h.error(`Please provide either a profile or an API key, not both`),process.exit(1)),l&&f&&e.h.warn(`Specifying --api-url with a profile won't have any effect. Using API url from profile.`),l&&!V(l)){e.h.error(`Configuration profile ${e.m(l)} not found`),e.h.log(`Run ${e.m(`stackone init`)} to create a new configuration profile.\n`);let t=U();t.length>0&&(e.h.info(`Available configuration profiles:`),t.forEach(t=>{e.h.log(` - ${i.default.blue(t)}`)})),process.exit(1)}let g=l?B(l):{apiUrl:f??Me,apiKey:p};(0,y.isMissing)(a)&&(0,y.isMissing)(o)&&(e.h.error(`A valid account or account ID is required to run an action`),process.exit(1));let _;if((0,y.notMissing)(t))if(this.#a(t)){!l&&!p&&(e.h.error(`Profile or API key is required when using a connector identifier`),e.h.log(`Please provide a profile using the ${e.m(`--profile`)} option or an API key using the ${e.m(`--api-key`)} option.`),e.h.log(`Run ${e.m(`stackone init`)} to create a new configuration profile.`),process.exit(1));let n=this.#o(t);_=await this.#s(n,g?.apiUrl??Me,g?.apiKey,h)}else _=this.#e(t);else (0,y.notMissing)(o)&&(_=await this.#c(o,g?.apiUrl??Me,g?.apiKey));let v=(0,y.notMissing)(n)?this.#r(n,t):_;(0,y.isMissing)(v)&&(e.h.error(`A valid connector is required to run an action.`),process.exit(1));let b=(0,y.notMissing)(v?.actions)?Object.keys(v?.actions).length:0,x=(0,y.notMissing)(v?.actions)?Object.keys(v.actions)[b-1]:void 0,S=(0,y.notMissing)(x)?v?.actions?.[x]?.id:void 0,C=((0,y.notMissing)(r)&&!r?.startsWith(`${v.key}_`)?`${v.key}_${r}`:r)??S;(0,y.isMissing)(C)&&(e.h.error(`A valid action ID is required to run an action`),process.exit(1));let w=(0,y.notMissing)(o)?await this.#l(o,g?.apiUrl??Me,g?.apiKey):{},T=(0,y.notMissing)(a)?this.#i(a,v.key??`unknown`,v.version??`unknown`):void 0,E=(0,y.notMissing)(c)?this.#u(c):{},ee={...w,...T,credentials:{...w.credentials??{},...E}};(0,y.isMissing)(ee)&&(e.h.error(`A valid account data is required to run an action.`),process.exit(1));let te=v.actions?.[C];(0,y.isMissing)(te)&&(e.h.error(`Action ID ${e.m(C)} not found in the connector ${e.m(v.key)}@${e.m(v.version)}.`),process.exit(1));let D=(0,y.notMissing)(s)?this.#d(s,C):{path:{},queryParams:{},header:{},body:{}},O=Date.now(),k=await this.#f({connector:v,actionId:C,account:ee,queryParams:{...D.queryParams,...d?{debug:`true`}:{}},pathParams:D.path,body:D.body,headers:D.header}),ne=Date.now()-O;if((0,y.notMissing)(u))try{m.default.writeFileSync(u,JSON.stringify(k.output,null,2),`utf-8`),e.h.info(`Output written to file: ${u}`)}catch(t){e.h.error(`Failed to write output to file ${u}: ${t.message}`),process.exit(1)}else e.h.log(`\n${i.default.blue.inverse(` ACTION OUTPUT `)}`),e.d(k.output);e.h.log(``),e.h.info(`Action ${e.m(C)} from connector ${e.m(v?.key)}@${e.m(v?.version)} finished in ${i.default.yellowBright((ne/1e3).toFixed(2))} seconds.`),process.exit(0)}#e=e=>{let t=e;try{t=(0,x.loadConnector)(e)}catch{}return t?this.#n(t):void 0};#t=t=>{try{return(0,x.loadConnector)(t)}catch(n){e.h.error(`Failed to load connector file from ${e.m(t)}: ${n.message}`),process.exit(1)}};#n=t=>{let n=(0,x.validateYamlConnector)(t),r=n?.errors??[];if(n.success)return n.connector||(e.h.error(`Failed to load connector.`),process.exit(1)),n.connector;r.length>0?(e.h.error(`Connector is not valid`),e.u(r,!0),process.exit(1)):(e.h.error(`Connector is not valid. Please check the file for errors.`),process.exit(1))};#r=(t,n)=>{let r=t;try{r=m.default.readFileSync(t,`utf-8`)}catch{}(0,y.isMissing)(n)&&(e.h.error(`A valid connector is required to load an action.`),process.exit(1));let i=`${this.#t(n)} - ${r.split(`
|
|
158
|
+
`).map((e,t)=>t===0?e:` ${e}`).join(`
|
|
159
|
+
`)}`;return this.#n(i)};#i=(t,n,r)=>{let i=t;try{i=m.default.readFileSync(t,`utf-8`)}catch{}try{let e=ke.parse(JSON.parse(i));return{providerKey:n,providerVersion:r,authConfigKey:e.auth_config_key,environment:e.environment,organizationId:e.organization_id,secureId:e.account_id,projectSecureId:e.project_id}}catch(t){let n=[];try{n=JSON.parse(t.message)}catch{}e.h.error(`Failed to parse account information`),e.u(n,!1),n.length===0&&e.h.log(t.message),process.exit(1)}};#a=e=>!e.includes(`/`)&&!e.includes(`\\`)&&!e.endsWith(`.yaml`)&&!e.endsWith(`.yml`)?e.includes(`@`)?e.split(`@`).length===2:!0:!1;#o=e=>e.includes(`@`)?e:`${e}@latest`;#s=async(t,n,r,i)=>{((0,y.isMissing)(t)||(0,y.isMissing)(n)||(0,y.isMissing)(r))&&(e.h.error(`Connector identifier, API URL, and API key are required to fetch connector from registry.`),process.exit(1));let a=(0,p.default)();try{a.text=`Fetching connector ${e.m(t)} from registry...`,a.start();let o=Buffer.from(r).toString(`base64`),s=i?`?owner=${encodeURIComponent(i)}`:``,c=await fetch(`${n}/registry/connectors/${t}${s}`,{method:`GET`,headers:{Authorization:`Basic ${o}`}});if(a.stop(),c.status===409){i&&(await e.f(c,`Failed to fetch connector ${e.m(t)} from registry`),process.exit(1));let r=await _e(t,(await c.json()).availableOwners??[]);a.text=`Fetching connector ${e.m(t)} from registry...`,a.start();let s=await fetch(`${n}/registry/connectors/${t}?owner=${encodeURIComponent(r)}`,{method:`GET`,headers:{Authorization:`Basic ${o}`}});a.stop(),s.ok||(await e.f(s,`Failed to fetch connector ${e.m(t)} from registry`),process.exit(1));let l=await s.text(),u=this.#n(l);return e.h.success(`Fetched connector ${e.m(u.key)}@${e.m(u.version)} from registry`),u}c.ok||(await e.f(c,`Failed to fetch connector ${e.m(t)} from registry`),process.exit(1));let l=await c.text(),u=this.#n(l);return e.h.success(`Fetched connector ${e.m(u.key)}@${e.m(u.version)} from registry`),u}catch(r){a.stop(),e.h.error(`Failed to fetch connector ${e.m(t)} from registry: ${r.message}`),e.h.log(`Please ensure that the API at ${e.g(n)} is reachable and the API key is valid`),process.exit(1)}};#c=async(t,n,r)=>{((0,y.isMissing)(t)||(0,y.isMissing)(n)||(0,y.isMissing)(r))&&(e.h.error(`Account ID, API URL, and API key are required to fetch connector`),process.exit(1));let i=(0,p.default)();try{i.text=`Fetching connector for account ${e.m(t)} from API...`,i.start();let a=Buffer.from(r).toString(`base64`),o=await fetch(`${n}/accounts/${t}/connector`,{method:`GET`,headers:{Authorization:`Basic ${a}`}});i.stop(),o.ok||(await e.f(o,`Failed to fetch connector`),process.exit(1));let s=await o.text(),c=this.#n(s);return e.h.success(`Fetched connector ${e.m(c.key)}@${e.m(c.version)} for account ${e.m(t)}`),c}catch(t){i.stop(),e.h.error(`Failed to fetch connector: ${t.message}`),e.h.log(`Please ensure that the API at ${e.g(n)} is reachable and the API key is valid`),process.exit(1)}};#l=async(t,n,r)=>{((0,y.isMissing)(t)||(0,y.isMissing)(n)||(0,y.isMissing)(r))&&(e.h.error(`Account ID, API URL, and API key are required to fetch account information.`),process.exit(1));let i=(0,p.default)();try{i.text=`Fetching account ${e.m(t)} information from API...`,i.start();let a=Buffer.from(r).toString(`base64`),o=await fetch(`${n}/accounts/${t}/credentials`,{method:`GET`,headers:{Authorization:`Basic ${a}`}});i.stop(),o.ok||(await e.f(o,`Failed to fetch account ${e.m(t)} information`),process.exit(1));let s=await o.json();return e.h.success(`Fetched account ${e.m(t)} information from project ${e.m(s.project_id)}`),{providerKey:s.provider_key,providerVersion:s.provider_version,authConfigKey:s.auth_config_key,environment:s.environment,organizationId:s.organization_id,secureId:s.account_id,projectSecureId:s.project_id,credentials:s.credentials}}catch(r){i.stop(),e.h.error(`Failed to fetch account ${e.m(t)} information: ${r.message}`),e.h.log(`Please ensure that the API at ${e.g(n)} is reachable and the API key is valid`),process.exit(1)}};#u=t=>{let n=t;try{n=m.default.readFileSync(t,`utf-8`)}catch{}try{return Ae.parse(JSON.parse(n))}catch(t){let n=[];try{n=JSON.parse(t.message)}catch{}e.h.error(`Failed to parse credentials`),e.u(n,!1),n.length===0&&e.h.log(t.message),process.exit(1)}};#d=(t,n)=>{let r=t;try{r=m.default.readFileSync(t,`utf-8`)}catch{}try{return je.parse(JSON.parse(r))}catch(t){let r=[];try{r=JSON.parse(t.message)}catch{}e.h.error(`Invalid parameters for action ${e.m(n)}.`),e.u(r,!1),r.length===0&&e.h.log(t.message),process.exit(1)}};async#f({connector:t,actionId:n,account:r,pathParams:a={},queryParams:o={},body:s={},headers:c={}}){try{let l=await(0,x.runAction)({mode:`action_id`,actionId:n,account:r,connector:t,pathParams:a,queryParams:o,body:s,headers:c,getHttpClient:async()=>new T.HttpClient});if(l.response?.successful){let e={...this.#p(o,l.steps),...(0,y.isObject)(l.outputs)?l.outputs:{data:l.outputs}};return{statusCode:l.response?.statusCode,output:e}}else{let r=l.response?.message??`An error occurred while processing the request`;e.h.error(`Action ID ${e.m(n)} from connector ${e.m(t.key)}@${e.m(t.version)} failed with status ${l.response?.statusCode}: ${r}`);let a={...this.#p(o,l.steps)};Object.keys(a).length>0&&(e.h.log(`${i.default.yellow.inverse(` EXECUTION DETAILS `)}`),e.d(a)),process.exit(1)}}catch(e){this.#m(e)}}#p(e,t){return e?.debug===`true`?{debug:{steps:t}}:{}}#m(t){let n=t;switch((0,y.isMissing)(n.errorType)&&(e.h.error(`An unknown error occurred`),e.h.log(`${t instanceof Error?t.message:String(t)}`),process.exit(1)),n.errorType){case`MISSING_ACTION_ERROR`:e.h.error(`The specified action was not found: ${n.message}`);break;case`INVALID_ACTION_INPUTS_ERROR`:let t=n;e.h.error(`Invalid action inputs`),e.u(t.validationErrors,!1);break;case`INVALID_CURSOR_ERROR`:e.h.error(`Invalid cursor: ${n.message}`);break;default:e.h.error(`An error occurred: ${n.message}`)}process.exit(1)}};const Pe=()=>{try{let e=(0,h.join)((0,h.dirname)((0,te.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),`..`,`package.json`);return JSON.parse((0,m.readFileSync)(e,`utf8`)).version}catch{return`unknown`}},Fe=(0,ee.promisify)(E.exec);var Ie=class{constructor(){this.packageName=`@stackone/cli`,this.spinner=(0,p.default)(),this.currentVersion=Pe()}async execute(t={}){this.spinner.text=`Checking for updates...`,this.spinner.start();try{let n=await this.getLatestVersion();this.spinner.stop(),n||(e.h.error(`Failed to check for updates`),process.exit(1)),this.isNewerVersion(n,this.currentVersion)?(e.h.box(`New version available: ${i.default.yellow(this.currentVersion)} → ${i.default.green(n)}`),await this.performUpdate(n)):t.force?(e.h.warn(`No updates available, but forcing reinstall...`),await this.performUpdate(n)):e.h.success(`You are already on the latest version (${this.currentVersion})`),process.exit(0)}catch(t){this.spinner.stop(),e.h.error(`Error while trying to update StackOne CLI: ${t?.message??`Unknown error`}`),process.exit(1)}}async getLatestVersion(){try{let{stdout:e}=await Fe(`npm view ${this.packageName} version`,{encoding:`utf-8`});return e.trim()}catch{return null}}isNewerVersion(e,t){return w.default.gt(e,t)}isUsingVolta(){if(typeof process.env.VOLTA_HOME!=`string`||process.env.VOLTA_HOME.length===0)return!1;let e=(0,l.join)(process.env.VOLTA_HOME,`bin`),t=(0,l.join)(e,`stackone`),n=(0,l.join)(e,`stackone.exe`);return(0,s.existsSync)(t)||(0,s.existsSync)(n)}async performUpdate(t){let n=this.isUsingVolta();this.spinner.text=`Updating to latest version (${e.m(t)})...`,this.spinner.start();try{await Fe(n?`volta install ${this.packageName}@latest`:`npm install -g ${this.packageName}@latest`,{encoding:`utf-8`}),this.spinner.stop(),e.h.success(`StackOne CLI updated successfully to latest version (${e.m(t)})`)}catch{this.spinner.stop();let e=n?`volta install ${this.packageName}@latest`:`npm install -g ${this.packageName}@latest`;throw Error(`Failed to install update. Please try manually: ${e}`)}}};const Le=()=>{e.h.log(`${i.default.gray.inverse(` CONNECTORS VALIDATION `)} ${i.default.yellow.inverse(` WATCH MODE `)}\n`)};var Re=class{async execute(t){let{watchMode:n,fileOrDir:r}=t,a=(0,p.default)(`Watching for file changes... ${i.default.gray(`(press "q" to quit)`)}`);if(!r)return;let o=(0,h.resolve)(r);try{await(0,D.stat)(o)}catch{e.h.error(`The specified path does not exist: ${o}\n`),process.exit(1)}if(n){e.l();let t={},{watch:n}=await import(`chokidar`),r=(await import(`readline`)).createInterface({input:process.stdin,output:process.stdout});process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding(`utf8`);let s=()=>{l.close(),a.stop(),r.close(),e.h.log(i.default.grey(`
|
|
160
|
+
Exiting watch mode...`)),process.exit(0)};Le(),e.h.start(`Validating connectors...`);let c=await He(o);t=ze(t,c||{}),Be(t,o),a.start();let l=n(o,{persistent:!0,ignoreInitial:!0}),u=async n=>{if(!n.endsWith(`.s1.yaml`)&&!n.endsWith(`s1.partial.yaml`))return;let r=n.endsWith(`s1.partial.yaml`)?await We(n):[n];if(!(!r||r.length===0)){e.l(),a.stop(),Le(),e.h.log(i.default.gray(`File change detected: ${n}`)),e.h.start(`Validating connectors...`);for(let e of r){let n=await He(e);t=ze(t,n||{})}Be(t,o),a.start()}};l.on(`change`,async e=>await u(e)),process.stdin.on(`data`,e=>{e.toString()===`q`&&s()}),process.on(`SIGINT`,()=>{s()})}else await He(o,e.h),process.exit(0)}};const ze=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]=r;return e},Be=(t,n)=>{e.l(),Le();let r=0,a=0;for(let[n,i]of Object.entries(t))i===null?r++:(e.h?.error(`Connector ${e.m(n)} is not valid`),e.u(i,!0),a++);e.h.log(``),e.h.log(i.default.blue.inverse(` Validation Summary `)),e.h.log(`Connectors path: ${e.m(n)}`),e.h.log(`${r===0?i.default.red(`0`):i.default.green(r)} valid, ${a===0?i.default.green(`0`):i.default.red(a)} invalid connectors\n`)},Ve=async e=>{let t=[],n=await(0,D.readdir)(e);for(let r of n){let n=(0,h.join)(e,r),i=await(0,D.stat)(n);i.isDirectory()?t.push(...await Ve(n)):i.isFile()&&r.endsWith(`.s1.yaml`)&&t.push(n)}return t},He=async(t,n)=>{let r=await(0,D.stat)(t),a={};if(r.isDirectory()){let r=await Ve(t);if(r.length===0)return n?.error(`No StackOne connector found in ${e.p(t)}`),n?.log(`Connector files need to have the extension ${e.m(`*.s1.yaml`)}`),null;let o=0,s=0;for(let e of r){let t=await Ue(e,n);t===null?o++:(n?.log(``),s++),a[e]=t}return n?.log(``),n?.log(i.default.blue.inverse(` Validation Summary `)),n?.log(`${o===0?i.default.red(`0`):i.default.green(o)} valid, ${s===0?i.default.green(`0`):i.default.red(s)} invalid connectors`),a}else if(r.isFile()&&t.endsWith(`s1.yaml`))return a[t]=await Ue(t,n),a;else if(r.isFile()&&t.endsWith(`partial.yaml`)){n?.error(`Partial connector files cannot be validated directly`),n?.log(`The file ${e.p(t)} is a partial connector file.`);let r=await We(t);return r&&r?.length>0&&n?.log(`Did you mean ${e.m(r[0])}?`),null}else return n?.error(`No StackOne connector found in ${e.p(t)}`),n?.log(`Connector files need to have the extension ${e.m(`*.s1.yaml`)}`),null},Ue=async(t,n)=>{let r=(0,x.validateYamlConnector)((0,x.loadConnector)(t)),i=r?.errors??[];if(r.success){let r=t.split(`/`).pop()||t;return n?.success(`Connector ${e.m(r)} is valid!`),null}else if(i.length>0)return n?.error(`Connector ${e.m(t)} is not valid`),n&&e.u(i,!0),i;else return n?.error(`Connector ${e.m(t)} is not valid. Please check the file for errors`),[]},We=async e=>{let t=(0,h.dirname)(e);try{return(await(0,D.readdir)(t)).filter(e=>e.endsWith(`.s1.yaml`))?.map(e=>(0,h.join)(t,e))}catch{}};function Ge(){let e=process.env.STACKONE_AGENT_TOKEN,t=process.env.LANGSMITH_PROJECT||`stackone-agent-cli`;if(e)try{(0,o.initUnifiedApiTelemetry)({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 Ke=`@stackone/cli`,qe=2880*60*1e3,Je=(0,l.join)((0,c.homedir)(),`.stackone`),Ye=(0,l.join)(Je,`version-check.json`),Xe=(e=!1)=>{let t=et(),n=Date.now();if(e||!t||n-t.lastCheckTime>1728e5){let e=Ze();e&&Qe(e)&&$e(e),tt({lastCheckTime:n})}},Ze=()=>{try{return(0,E.execSync)(`npm view @stackone/cli version`,{encoding:`utf-8`,stdio:[`pipe`,`pipe`,`pipe`],timeout:15e3}).trim()}catch{return null}},Qe=e=>{try{let t=Pe();return w.default.gt(e,t)}catch{return!1}},$e=t=>{let n=Pe(),r=`Update available: ${i.default.dim(n)} → ${i.default.green(t)}`,a=`\n\nRun ${i.default.cyan(`stackone update`)} to update`;e.h.box(r,a)},et=()=>{try{if(!(0,s.existsSync)(Ye))return null;let e=(0,s.readFileSync)(Ye,`utf-8`);return JSON.parse(e)}catch{return null}},tt=e=>{try{(0,s.existsSync)(Je)||(0,s.mkdirSync)(Je,{recursive:!0}),(0,s.writeFileSync)(Ye,JSON.stringify(e,null,2),`utf-8`)}catch{}};var nt=class{constructor(e=new a.Command,t=Pe()){this.program=e,this.version=t,Ge(),this.setupProgram(),this.registerCommands()}setupProgram(){this.program.name(`stackone`).description(`StackOne CLI`).version(this.version,`-v, --version`)}registerCommands(){let t=new X,n=new $,r=new Q,o=new G,s=new q,c=new Re,l=new L,u=new R,d=new ue,f=new F,p=new pe,m=new he,h=new Ne,g=new Ie;this.program.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>process.stderr.write(e),outputError:(e,t)=>{t(i.default.red(e))}}),this.program.command(`init`).option(`-e, --env <environment>`,`Specify the environment for the configuration profile`).description(`Initialize & create a StackOne CLI configuration profile`).action(e=>{t.execute({environment:e.env})}),this.program.command(`push`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).addArgument(new a.Argument(`<path>`,`Connector file or directory to push`)).description(`Push a connector to the StackOne registry`).action((e,t)=>{n.execute({profile:t.profile,fileOrDir:e,apiUrl:t.apiUrl,apiKey:t.apiKey})}),this.program.command(`drop`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).addArgument(new a.Argument(`<connector>`,`Connector identifier in format provider_key@version`)).description(`Drop a connector from the StackOne registry`).action((e,t)=>{o.execute({profile:t.profile,connector:e,apiUrl:t.apiUrl,apiKey:t.apiKey})}),this.program.command(`get`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-c, --connector <connector>`,`Connector identifier in format provider_key@version or provider_key (defaults to latest)`).option(`--account-id <account-id>`,`Account ID to fetch connector from`).option(`-f, --format <format>`,`Output format: yaml or json (default: yaml)`,`yaml`).option(`-o, --output-file <output-file>`,`File to write the output to`).option(`--builtin`,`Use the builtin (StackOne) version of the connector`).option(`--custom`,`Use the custom (organization) version of the connector`).option(`--owner <owner>`,`Owner to use for disambiguating connector versions`).description(`Get a connector from the StackOne registry`).action(t=>{[t.builtin,t.custom,t.owner].filter(Boolean).length>1&&(e.h.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),s.execute({profile:t.profile,connector:t.connector,accountId:t.accountId,format:t.format,outputFile:t.outputFile,apiUrl:t.apiUrl,apiKey:t.apiKey,owner:t.builtin?`builtin`:t.custom?`custom`:t.owner})}),this.program.command(`pull`).option(`-c, --connector <connector>`,`Connector identifier in format provider_key@version or provider_key`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-o, --output <path>`,`Output directory for the connectors files (default: ./connectors)`).option(`--builtin`,`Use the builtin (StackOne) version of the connector`).option(`--custom`,`Use the custom (organization) version of the connector`).option(`--owner <owner>`,`Owner to use for disambiguating connector versions`).description(`Pull a connector configuration from StackOne registry to local filesystem`).action(t=>{[t.builtin,t.custom,t.owner].filter(Boolean).length>1&&(e.h.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),r.execute({profile:t.profile,connector:t.connector,outputPath:t.output,apiUrl:t.apiUrl,apiKey:t.apiKey,owner:t.builtin?`builtin`:t.custom?`custom`:t.owner})}),this.program.command(`validate`).option(`-w, --watch`,`Run in watch mode`).addArgument(new a.Argument(`<path>`,`Connector file or directory with connectors to validate`)).description(`Validate a StackOne connector`).action((e,t)=>{c.execute({watchMode:t.watch,fileOrDir:e})}),this.program.command(`run`).option(`--connector <connector>`,`Connector file, inline YAML, or identifier (provider_key@version or provider_key for latest)`).option(`--action <action>`,`Action to execute on the connector (path to file or inline string action code)`).option(`--action-id <action-id>`,`Action ID to execute on the connector`).option(`--account <account>`,`Account details to use for running the connector (path to file or inline string account data)`).option(`--account-id <account-id>`,`Account ID to use for running the connector against (fetches connector from API if --connector not provided)`).option(`--params <params>`,`Action parameters (path to file or inline string with JSON parameters)`).option(`--credentials <credentials>`,`Credentials to use (path to file or inline string with JSON credentials)`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-o, --output-file <output-file>`,`File to write the output to`).option(`-d, --debug`,`Enables debug mode to include more details in the action execution output`).option(`--builtin`,`Use the builtin (StackOne) version of the connector`).option(`--custom`,`Use the custom (organization) version of the connector`).option(`--owner <owner>`,`Owner to use for disambiguating connector versions`).description(`Run a connector action`).action(t=>{[t.builtin,t.custom,t.owner].filter(Boolean).length>1&&(e.h.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),h.execute({connector:t.connector,action:t.action,actionId:t.actionId,account:t.account,accountId:t.accountId,params:t.params,credentials:t.credentials,profile:t.profile,outputFile:t.outputFile,debug:t.debug,apiUrl:t.apiUrl,apiKey:t.apiKey,owner:t.builtin?`builtin`:t.custom?`custom`:t.owner})});let _=this.program.command(`agent`).description(`StackOne agent commands`);_.command(`setup`).option(`-g, --global`,`Setup global configuration`).option(`-l, --local`,`Setup local project configuration`).description(`Setup StackOne agent (global or local)`).action(e=>{e.global?l.execute():u.execute()}),_.command(`cleanup`).description(`Remove all API keys and credentials from configurations`).action(()=>{d.execute()}),_.command(`run`).description(`Run the agent once with a prompt (non-interactive)`).argument(`<prompt>`,`What to do`).option(`-m, --mode <mode>`,`Mode: build, test, or research`,`build`).option(`--max-turns <n>`,`Max agent turns`,`25`).option(`-v, --verbose`,`Verbose output`).action(async(t,n)=>{let r=[`build`,`test`,`research`],a=n.mode??`build`;r.includes(a)||(e.h.error(`${i.default.red(`Invalid mode:`)} ${i.default.white(a)}. Valid modes are: ${r.join(`, `)}.`),process.exit(1));let o=n.maxTurns?parseInt(String(n.maxTurns),10):void 0;await p.execute({prompt:String(t),mode:a,maxTurns:o!==void 0&&!isNaN(o)?o:void 0,verbose:n.verbose})}),_.command(`skills`).description(`List available agent skills and optional recommendations by mode`).option(`-m, --mode <mode>`,`Show skills recommended for this mode`).action(async e=>{await m.execute({mode:e.mode})}),_.command(`chat`).option(`-m, --mode <mode>`,`Mode: build, test, or research`,`build`).option(`-c, --connector <name>`,`Connector name`).option(`-a, --action <name>`,`Action name`).option(`-g, --goal <goal>`,`Initial goal/message`).option(`-t, --temperature <number>`,`Temperature (0-1, default: 0.5)`,parseFloat).option(`-v, --verbose`,`Enable verbose logging`).description(`Start an interactive chat session with the agent (use /commands in chat)`).action(async t=>{let n=[`build`,`test`,`research`];t.mode&&!n.includes(t.mode)&&(e.h.error(`❌ Error: Invalid mode "${t.mode}". Must be one of: ${n.join(`, `)}`),process.exit(1)),t.temperature!==void 0&&(isNaN(t.temperature)&&(e.h.error(`❌ Error: Temperature must be a valid number`),process.exit(1)),(t.temperature<0||t.temperature>1)&&(e.h.error(`❌ Error: Temperature must be between 0 and 1`),process.exit(1))),f.execute({mode:t.mode,connector:t.connector,action:t.action,goal:t.goal,temperature:t.temperature,verbose:t.verbose})}),this.program.command(`update`).option(`-f, --force`,`Force reinstall even if already on latest version`).description(`Update the CLI to the latest version`).action(e=>{g.execute({force:e.force})}),this.program.command(`version`).description(`Show version information`).action(async()=>{e.h.log(`${i.default.inverse.greenBright(`StackOne`)} ${i.default.grey(`CLI`)} ${i.default.whiteBright(this.version)}`),Xe(!0),process.exit(0)})}run(){process.argv.includes(`version`)||Xe(),this.program.parse(process.argv)}};Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return nt}});
|