@zibby/cli 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +2 -2
  2. package/dist/auth/cli-login.js +7 -7
  3. package/dist/auth/ensure-auth.js +6 -6
  4. package/dist/bin/zibby.js +3 -3
  5. package/dist/commands/chat-agents.js +1 -0
  6. package/dist/commands/chat-sandbox-attach.js +5 -0
  7. package/dist/commands/chat.js +79 -69
  8. package/dist/commands/credentials-api.js +1 -0
  9. package/dist/commands/credentials-file.js +1 -0
  10. package/dist/commands/creds.js +1 -0
  11. package/dist/commands/init.js +83 -75
  12. package/dist/commands/list-projects.js +5 -5
  13. package/dist/commands/memory.js +28 -18
  14. package/dist/commands/project.js +3 -3
  15. package/dist/commands/run.js +52 -55
  16. package/dist/commands/studio.js +1 -1
  17. package/dist/commands/template.js +9 -0
  18. package/dist/commands/upload.js +4 -4
  19. package/dist/commands/workflow.js +23 -23
  20. package/dist/commands/workflows/dedicated-egress.js +6 -6
  21. package/dist/commands/workflows/delete.js +4 -4
  22. package/dist/commands/workflows/deploy.js +19 -19
  23. package/dist/commands/workflows/env.js +7 -7
  24. package/dist/commands/workflows/generate.js +13 -13
  25. package/dist/commands/workflows/list.js +6 -6
  26. package/dist/commands/workflows/run-local.js +15 -15
  27. package/dist/commands/workflows/start.js +16 -16
  28. package/dist/commands/workflows/trigger.js +7 -7
  29. package/dist/config/environments.js +1 -1
  30. package/dist/package.json +4 -4
  31. package/dist/templates/zibby-workflow-claude/claude/commands/zibby-static-ip.md +1 -1
  32. package/dist/utils/agent-credentials.js +4 -3
  33. package/dist/utils/credentials-loader.js +1 -0
  34. package/package.json +4 -4
package/README.md CHANGED
@@ -28,7 +28,7 @@ export ZIBBY_USER_TOKEN=zby_pat_xxxxx
28
28
  zibby workflow trigger <uuid>
29
29
  ```
30
30
 
31
- Generate a PAT at https://zibby.app/settings/tokens.
31
+ Generate a PAT at https://zibby.dev/settings/tokens.
32
32
 
33
33
  ## Workflow lifecycle
34
34
 
@@ -111,7 +111,7 @@ zibby deploy --dedicated-ip disable # cancel at end of b
111
111
 
112
112
  ## Studio (test recipe only today)
113
113
 
114
- [Zibby Studio](https://zibby.app/studio) is the desktop UI for the test recipe — visualise live + past test runs, stop a workflow from a button. Broader workflow support is on the roadmap.
114
+ [Zibby Studio](https://zibby.dev/studio) is the desktop UI for the test recipe — visualise live + past test runs, stop a workflow from a button. Broader workflow support is on the roadmap.
115
115
 
116
116
  ```bash
117
117
  zibby studio # open Studio
@@ -1,18 +1,18 @@
1
- import n from"chalk";import I from"ora";import{spawn as q}from"child_process";var y={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.app",description:"Production environment"}};function h(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";y[e]?o=y[e].apiUrl:o=y.prod.apiUrl}try{let e=new URL(o);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),y.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),y.prod.apiUrl}}import{existsSync as P,mkdirSync as Z,readFileSync as F,writeFileSync as V}from"fs";import{homedir as T}from"os";import{join as m}from"path";function A(){return process.env.ZIBBY_CONFIG_DIR||m(T(),".zibby")}function _(){return m(A(),"config.json")}var J=m(T(),".zibby"),ro=m(J,"config.json");function M(){let o=A();P(o)||Z(o,{recursive:!0})}function u(){try{let o=_();if(P(o)){let e=F(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function f(o){M(),V(_(),JSON.stringify(o,null,2))}function w(){return u().sessionToken||null}function B(o){let e=u();e.sessionToken=o,f(e)}function N(){return u().user||null}function L(o){let e=u();e.user=o,f(e)}function U(){let o=u();delete o.sessionToken,delete o.user,delete o.mem0ProxyUrl,f(o)}function C(o){let e=u();e.proxyUrl=o,f(e)}function R(o){let e=u();e.mem0ProxyUrl=o,f(e)}function z(o){let e=u();e.projects=o,f(e)}import{existsSync as G,mkdirSync as co,readFileSync as lo,writeFileSync as ao,unlinkSync as H}from"fs";import{resolve as $}from"path";import{homedir as W}from"os";function O(){let o=[$(process.cwd(),".zibby","output","active-skills.json"),$(W(),".zibby","output","active-skills.json")];for(let e of o)try{G(e)&&H(e)}catch{}}function K(o){let e=process.platform;try{let t,s;return e==="darwin"?(t="open",s=[o]):e==="win32"?(t="cmd",s=["/c","start","",o]):(t="xdg-open",s=[o]),q(t,s,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function S(){let o=w(),e=N();return o&&e?{loggedIn:!0,user:e,token:o}:{loggedIn:!1}}async function Uo(){try{console.log(n.cyan(`
1
+ import n from"chalk";import I from"ora";import{spawn as q}from"child_process";var y={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function h(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";y[e]?o=y[e].apiUrl:o=y.prod.apiUrl}try{let e=new URL(o);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),y.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),y.prod.apiUrl}}import{existsSync as P,mkdirSync as Z,readFileSync as F,writeFileSync as V}from"fs";import{homedir as T}from"os";import{join as m}from"path";function A(){return process.env.ZIBBY_CONFIG_DIR||m(T(),".zibby")}function _(){return m(A(),"config.json")}var J=m(T(),".zibby"),ro=m(J,"config.json");function M(){let o=A();P(o)||Z(o,{recursive:!0})}function u(){try{let o=_();if(P(o)){let e=F(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function f(o){M(),V(_(),JSON.stringify(o,null,2))}function w(){return u().sessionToken||null}function B(o){let e=u();e.sessionToken=o,f(e)}function N(){return u().user||null}function L(o){let e=u();e.user=o,f(e)}function U(){let o=u();delete o.sessionToken,delete o.user,delete o.mem0ProxyUrl,f(o)}function C(o){let e=u();e.proxyUrl=o,f(e)}function R(o){let e=u();e.mem0ProxyUrl=o,f(e)}function z(o){let e=u();e.projects=o,f(e)}import{existsSync as G,mkdirSync as co,readFileSync as lo,writeFileSync as ao,unlinkSync as H}from"fs";import{resolve as $}from"path";import{homedir as W}from"os";function O(){let o=[$(process.cwd(),".zibby","output","active-skills.json"),$(W(),".zibby","output","active-skills.json")];for(let e of o)try{G(e)&&H(e)}catch{}}function K(o){let e=process.platform;try{let t,s;return e==="darwin"?(t="open",s=[o]):e==="win32"?(t="cmd",s=["/c","start","",o]):(t="xdg-open",s=[o]),q(t,s,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function b(){let o=w(),e=N();return o&&e?{loggedIn:!0,user:e,token:o}:{loggedIn:!1}}async function Uo(){try{console.log(n.cyan(`
2
2
  \u{1F510} Initiating login...
3
- `));let o=S();if(o.loggedIn){console.log(n.green("\u2705 Already logged in!")),console.log(n.gray(`User: ${o.user.email}`)),console.log(n.gray(`Name: ${o.user.name}
3
+ `));let o=b();if(o.loggedIn){console.log(n.green("\u2705 Already logged in!")),console.log(n.gray(`User: ${o.user.email}`)),console.log(n.gray(`Name: ${o.user.name}
4
4
  `));let{createInterface:e}=await import("readline"),t=e({input:process.stdin,output:process.stdout});return new Promise((s,a)=>{let r=()=>{t.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},i=()=>{console.log(n.yellow(`
5
5
 
6
6
  \u26A0\uFE0F Login cancelled
7
7
  `)),r(),process.exit(0)};process.on("SIGINT",i),t.question(n.yellow("Continue with this session? (Y/n): "),async l=>{process.removeListener("SIGINT",i),r();try{if(l.toLowerCase()==="n"||l.toLowerCase()==="no"){console.log(n.gray(`Starting new login...
8
8
  `));let d=await E();s(d)}else console.log(n.green(`Using existing session.
9
9
  `)),s({success:!0,...o})}catch(d){a(d)}})})}return await E()}catch(o){return console.error(n.red(`
10
- \u274C Login failed:`,o.message)),{success:!1,error:o.message}}}async function X(o){let e=h();try{let t=await fetch(`${e}/projects`,{headers:{Authorization:`Bearer ${o}`}});if(t.ok){let a=((await t.json()).projects||[]).map(r=>({name:r.name,projectId:r.projectId,apiToken:r.apiToken}));return z(a),a}}catch(t){console.log(n.gray(`\u26A0\uFE0F Could not fetch projects: ${t.message}`))}return[]}async function E(){let o=h(),e=I("Requesting login code...").start(),t=await fetch(`${o}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){e.fail("Failed to request login code");let g=await t.json();throw new Error(g.error||"Failed to initiate login")}let{deviceCode:s,userCode:a,verificationUrl:r,expiresIn:i,interval:l}=await t.json();e.succeed("Login code generated"),console.log(""),console.log(n.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")),console.log(n.cyan("\u2551")+n.white.bold(" Complete login in your browser ")+n.cyan("\u2551")),console.log(n.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")),console.log(""),console.log(n.white("Opening browser to login page...")),console.log(n.gray(`Code expires in ${Math.floor(i/60)} minutes`)),console.log(""),await K(r)||(console.log(n.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(n.white("Please open this URL manually: ")+n.blue(r)),console.log(""));let p=I("Waiting for authorization...").start(),D=(l||3)*1e3,Y=Math.floor(i/(l||3)),x=0,b=!1,k=()=>{b=!0,p.stop(),console.log(n.yellow(`
10
+ \u274C Login failed:`,o.message)),{success:!1,error:o.message}}}async function X(o){let e=h();try{let t=await fetch(`${e}/projects`,{headers:{Authorization:`Bearer ${o}`}});if(t.ok){let a=((await t.json()).projects||[]).map(r=>({name:r.name,projectId:r.projectId,apiToken:r.apiToken}));return z(a),a}}catch(t){console.log(n.gray(`\u26A0\uFE0F Could not fetch projects: ${t.message}`))}return[]}async function E(){let o=h(),e=I("Requesting login code...").start(),t=await fetch(`${o}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){e.fail("Failed to request login code");let g=await t.json();throw new Error(g.error||"Failed to initiate login")}let{deviceCode:s,userCode:a,verificationUrl:r,expiresIn:i,interval:l}=await t.json();e.succeed("Login code generated"),console.log(""),console.log(n.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")),console.log(n.cyan("\u2551")+n.white.bold(" Complete login in your browser ")+n.cyan("\u2551")),console.log(n.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")),console.log(""),console.log(n.white("Opening browser to login page...")),console.log(n.gray(`Code expires in ${Math.floor(i/60)} minutes`)),console.log(""),await K(r)||(console.log(n.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(n.white("Please open this URL manually: ")+n.blue(r)),console.log(""));let p=I("Waiting for authorization...").start(),D=(l||3)*1e3,Y=Math.floor(i/(l||3)),S=0,x=!1,k=()=>{x=!0,p.stop(),console.log(n.yellow(`
11
11
 
12
12
  \u26A0\uFE0F Login cancelled
13
- `)),process.exit(0)};process.on("SIGINT",k);try{for(;x<Y&&!b;){await Q(D),x++;let g=await fetch(`${o}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:s})});if(g.status===202)continue;if(!g.ok){p.fail("Authorization failed");let v=await g.json();throw new Error(v.error||"Authorization failed")}let c=await g.json();if(c.status==="authorized"){p.succeed(n.white("Authorization successful!")),B(c.token),L(c.user),c.proxyUrl&&C(c.proxyUrl),c.mem0ProxyUrl&&R(c.mem0ProxyUrl),console.log(""),console.log(n.gray(`User: ${c.user.email}`));let v=I("Fetching projects...").start(),j=await X(c.token);return v.succeed(`Fetched ${j.length} project${j.length!==1?"s":""}`),console.log(n.gray(`Session saved to: ~/.zibby/config.json
14
- `)),{success:!0,loggedIn:!0,user:c.user,token:c.token}}if(c.status==="denied")throw p.fail("Authorization denied"),new Error("User denied authorization")}throw p.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",k)}}function Io(){if(!S().loggedIn){console.log(n.yellow(`
13
+ `)),process.exit(0)};process.on("SIGINT",k);try{for(;S<Y&&!x;){await Q(D),S++;let g=await fetch(`${o}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:s})});if(g.status===202)continue;if(!g.ok){p.fail("Authorization failed");let v=await g.json();throw new Error(v.error||"Authorization failed")}let c=await g.json();if(c.status==="authorized"){p.succeed(n.white("Authorization successful!")),B(c.token),L(c.user),c.proxyUrl&&C(c.proxyUrl),c.mem0ProxyUrl&&R(c.mem0ProxyUrl),console.log(""),console.log(n.gray(`User: ${c.user.email}`));let v=I("Fetching projects...").start(),j=await X(c.token);return v.succeed(`Fetched ${j.length} project${j.length!==1?"s":""}`),console.log(n.gray(`Session saved to: ~/.zibby/config.json
14
+ `)),{success:!0,loggedIn:!0,user:c.user,token:c.token}}if(c.status==="denied")throw p.fail("Authorization denied"),new Error("User denied authorization")}throw p.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",k)}}function Io(){if(!b().loggedIn){console.log(n.yellow(`
15
15
  \u26A0\uFE0F Not logged in.
16
16
  `));return}U(),O(),console.log(n.green("\u2714")+n.white(" Logged out successfully!")),console.log(n.gray(`Session cleared from ~/.zibby/config.json
17
- `))}async function So(o={}){let e=S(),t=process.env.ZIBBY_USER_TOKEN,s=h(),a=t||e.token;if(o.json){let r={authenticated:!!(e.loggedIn||t),user:e.user||null,tokenSource:t?"environment":e.token?"session":null,tokenType:t?"PAT":e.token?"JWT":null,apiUrl:s,configPath:e.loggedIn?"~/.zibby/config.json":null};if(a)try{let i=await fetch(`${s}/projects`,{headers:{Authorization:`Bearer ${a}`}});if(r.tokenValid=i.ok,i.ok){let l=await i.json();r.projectCount=(l.projects||[]).length}}catch(i){r.tokenValid=!1,r.error=i.message}else r.tokenValid=!1;console.log(JSON.stringify(r,null,2));return}if(console.log(""),!e.loggedIn&&!t){console.log(n.yellow("\u26A0\uFE0F Not authenticated")),console.log(""),console.log(n.white("To authenticate:")),console.log(n.gray(" Local: zibby login")),console.log(n.gray(` CI/CD: Set ZIBBY_USER_TOKEN env variable
18
- `));return}if(console.log(n.green("\u2705 Authenticated")),console.log(""),console.log(n.bold.white("User Details:")),e.user?(console.log(n.gray(` Email: ${e.user.email}`)),e.user.userId&&console.log(n.gray(` User ID: ${e.user.userId}`)),e.user.name&&console.log(n.gray(` Name: ${e.user.name}`))):t&&console.log(n.gray(" (User details not available with PAT token)")),console.log(""),console.log(n.bold.white("Token Source:")),t?(console.log(n.gray(" Type: Personal Access Token (PAT)")),console.log(n.gray(" Location: ZIBBY_USER_TOKEN environment variable")),console.log(n.gray(` Preview: ${t.substring(0,8)}\u2022\u2022\u2022\u2022`))):(console.log(n.gray(" Type: Session Token (JWT)")),console.log(n.gray(" Location: ~/.zibby/config.json")),e.token&&console.log(n.gray(` Preview: ${e.token.substring(0,8)}\u2022\u2022\u2022\u2022`))),console.log(""),a)try{let r=(await import("ora")).default,i=r("Verifying authentication...").start(),l=await fetch(`${s}/projects`,{headers:{Authorization:`Bearer ${a}`}});if(l.ok){let p=((await l.json()).projects||[]).length;i.succeed(n.white("Token verified")),console.log(n.gray(` Projects: ${p} accessible`))}else i.fail(n.white("Token verification failed")),console.log(n.yellow(` Status: Invalid or expired (HTTP ${l.status})`))}catch(r){console.log(n.yellow(` Status: Could not verify (${r.message})`))}console.log(""),console.log(n.gray("\u{1F4A1} Run 'zibby list' to see your projects")),console.log("")}async function xo(){let o=w();if(!o)return{valid:!1};let e=h();try{return(await fetch(`${e}/projects`,{headers:{Authorization:`Bearer ${o}`}})).ok?{valid:!0}:(U(),{valid:!1})}catch{return{valid:!1}}}function Q(o){return new Promise(e=>setTimeout(e,o))}export{S as checkExistingSession,Uo as loginCli,Io as logoutCli,So as showLoginStatus,xo as validateSession};
17
+ `))}async function bo(o={}){let e=b(),t=process.env.ZIBBY_USER_TOKEN,s=h(),a=t||e.token;if(o.json){let r={authenticated:!!(e.loggedIn||t),user:e.user||null,tokenSource:t?"environment":e.token?"session":null,tokenType:t?"PAT":e.token?"JWT":null,apiUrl:s,configPath:e.loggedIn?"~/.zibby/config.json":null};if(a)try{let i=await fetch(`${s}/projects`,{headers:{Authorization:`Bearer ${a}`}});if(r.tokenValid=i.ok,i.ok){let l=await i.json();r.projectCount=(l.projects||[]).length}}catch(i){r.tokenValid=!1,r.error=i.message}else r.tokenValid=!1;console.log(JSON.stringify(r,null,2));return}if(console.log(""),!e.loggedIn&&!t){console.log(n.yellow("\u26A0\uFE0F Not authenticated")),console.log(""),console.log(n.white("To authenticate:")),console.log(n.gray(" Local: zibby login")),console.log(n.gray(` CI/CD: Set ZIBBY_USER_TOKEN env variable
18
+ `));return}if(console.log(n.green("\u2705 Authenticated")),console.log(""),console.log(n.bold.white("User Details:")),e.user?(console.log(n.gray(` Email: ${e.user.email}`)),e.user.userId&&console.log(n.gray(` User ID: ${e.user.userId}`)),e.user.name&&console.log(n.gray(` Name: ${e.user.name}`))):t&&console.log(n.gray(" (User details not available with PAT token)")),console.log(""),console.log(n.bold.white("Token Source:")),t?(console.log(n.gray(" Type: Personal Access Token (PAT)")),console.log(n.gray(" Location: ZIBBY_USER_TOKEN environment variable")),console.log(n.gray(` Preview: ${t.substring(0,8)}\u2022\u2022\u2022\u2022`))):(console.log(n.gray(" Type: Session Token (JWT)")),console.log(n.gray(" Location: ~/.zibby/config.json")),e.token&&console.log(n.gray(` Preview: ${e.token.substring(0,8)}\u2022\u2022\u2022\u2022`))),console.log(""),a)try{let r=(await import("ora")).default,i=r("Verifying authentication...").start(),l=await fetch(`${s}/projects`,{headers:{Authorization:`Bearer ${a}`}});if(l.ok){let p=((await l.json()).projects||[]).length;i.succeed(n.white("Token verified")),console.log(n.gray(` Projects: ${p} accessible`))}else i.fail(n.white("Token verification failed")),console.log(n.yellow(` Status: Invalid or expired (HTTP ${l.status})`))}catch(r){console.log(n.yellow(` Status: Could not verify (${r.message})`))}console.log(""),console.log(n.gray("\u{1F4A1} Run 'zibby list' to see your projects")),console.log("")}async function So(){let o=w();if(!o)return{valid:!1};let e=h();try{return(await fetch(`${e}/projects`,{headers:{Authorization:`Bearer ${o}`}})).ok?{valid:!0}:(U(),{valid:!1})}catch{return{valid:!1}}}function Q(o){return new Promise(e=>setTimeout(e,o))}export{b as checkExistingSession,Uo as loginCli,Io as logoutCli,bo as showLoginStatus,So as validateSession};
@@ -1,17 +1,17 @@
1
- import{existsSync as X,readFileSync as Q}from"fs";import{join as oo}from"path";import U from"chalk";import{confirm as eo}from"@inquirer/prompts";import t from"chalk";import w from"ora";import{spawn as M}from"child_process";var f={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.app",description:"Production environment"}};function v(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";f[e]?o=f[e].apiUrl:o=f.prod.apiUrl}try{let e=new URL(o);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),f.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),f.prod.apiUrl}}import{existsSync as T,mkdirSync as F,readFileSync as Z,writeFileSync as J}from"fs";import{homedir as P}from"os";import{join as h}from"path";function A(){return process.env.ZIBBY_CONFIG_DIR||h(P(),".zibby")}function j(){return h(A(),"config.json")}var K=h(P(),".zibby"),io=h(K,"config.json");function V(){let o=A();T(o)||F(o,{recursive:!0})}function c(){try{let o=j();if(T(o)){let e=Z(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function d(o){V(),J(j(),JSON.stringify(o,null,2))}function _(){return c().sessionToken||null}function B(o){let e=c();e.sessionToken=o,d(e)}function N(){return c().user||null}function L(o){let e=c();e.user=o,d(e)}function R(o){let e=c();e.proxyUrl=o,d(e)}function C(o){let e=c();e.mem0ProxyUrl=o,d(e)}function O(o){let e=c();e.projects=o,d(e)}import{existsSync as ao,mkdirSync as uo,readFileSync as po,writeFileSync as go,unlinkSync as fo}from"fs";import{resolve as ho}from"path";import{homedir as vo}from"os";function G(o){let e=process.platform;try{let n,r;return e==="darwin"?(n="open",r=[o]):e==="win32"?(n="cmd",r=["/c","start","",o]):(n="xdg-open",r=[o]),M(n,r,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function H(){let o=_(),e=N();return o&&e?{loggedIn:!0,user:e,token:o}:{loggedIn:!1}}async function $(){try{console.log(t.cyan(`
1
+ import{existsSync as X,readFileSync as Q}from"fs";import{join as oo}from"path";import U from"chalk";import{confirm as eo}from"@inquirer/prompts";import t from"chalk";import w from"ora";import{spawn as M}from"child_process";var f={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function v(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";f[e]?o=f[e].apiUrl:o=f.prod.apiUrl}try{let e=new URL(o);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),f.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),f.prod.apiUrl}}import{existsSync as T,mkdirSync as F,readFileSync as Z,writeFileSync as J}from"fs";import{homedir as P}from"os";import{join as h}from"path";function A(){return process.env.ZIBBY_CONFIG_DIR||h(P(),".zibby")}function j(){return h(A(),"config.json")}var K=h(P(),".zibby"),io=h(K,"config.json");function V(){let o=A();T(o)||F(o,{recursive:!0})}function c(){try{let o=j();if(T(o)){let e=Z(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function d(o){V(),J(j(),JSON.stringify(o,null,2))}function _(){return c().sessionToken||null}function B(o){let e=c();e.sessionToken=o,d(e)}function N(){return c().user||null}function L(o){let e=c();e.user=o,d(e)}function R(o){let e=c();e.proxyUrl=o,d(e)}function C(o){let e=c();e.mem0ProxyUrl=o,d(e)}function z(o){let e=c();e.projects=o,d(e)}import{existsSync as ao,mkdirSync as uo,readFileSync as po,writeFileSync as go,unlinkSync as fo}from"fs";import{resolve as ho}from"path";import{homedir as vo}from"os";function G(o){let e=process.platform;try{let n,r;return e==="darwin"?(n="open",r=[o]):e==="win32"?(n="cmd",r=["/c","start","",o]):(n="xdg-open",r=[o]),M(n,r,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function H(){let o=_(),e=N();return o&&e?{loggedIn:!0,user:e,token:o}:{loggedIn:!1}}async function $(){try{console.log(t.cyan(`
2
2
  \u{1F510} Initiating login...
3
3
  `));let o=H();if(o.loggedIn){console.log(t.green("\u2705 Already logged in!")),console.log(t.gray(`User: ${o.user.email}`)),console.log(t.gray(`Name: ${o.user.name}
4
4
  `));let{createInterface:e}=await import("readline"),n=e({input:process.stdin,output:process.stdout});return new Promise((r,a)=>{let i=()=>{n.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},u=()=>{console.log(t.yellow(`
5
5
 
6
6
  \u26A0\uFE0F Login cancelled
7
7
  `)),i(),process.exit(0)};process.on("SIGINT",u),n.question(t.yellow("Continue with this session? (Y/n): "),async p=>{process.removeListener("SIGINT",u),i();try{if(p.toLowerCase()==="n"||p.toLowerCase()==="no"){console.log(t.gray(`Starting new login...
8
- `));let y=await z();r(y)}else console.log(t.green(`Using existing session.
9
- `)),r({success:!0,...o})}catch(y){a(y)}})})}return await z()}catch(o){return console.error(t.red(`
10
- \u274C Login failed:`,o.message)),{success:!1,error:o.message}}}async function W(o){let e=v();try{let n=await fetch(`${e}/projects`,{headers:{Authorization:`Bearer ${o}`}});if(n.ok){let a=((await n.json()).projects||[]).map(i=>({name:i.name,projectId:i.projectId,apiToken:i.apiToken}));return O(a),a}}catch(n){console.log(t.gray(`\u26A0\uFE0F Could not fetch projects: ${n.message}`))}return[]}async function z(){let o=v(),e=w("Requesting login code...").start(),n=await fetch(`${o}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!n.ok){e.fail("Failed to request login code");let l=await n.json();throw new Error(l.error||"Failed to initiate login")}let{deviceCode:r,userCode:a,verificationUrl:i,expiresIn:u,interval:p}=await n.json();e.succeed("Login code generated"),console.log(""),console.log(t.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")),console.log(t.cyan("\u2551")+t.white.bold(" Complete login in your browser ")+t.cyan("\u2551")),console.log(t.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")),console.log(""),console.log(t.white("Opening browser to login page...")),console.log(t.gray(`Code expires in ${Math.floor(u/60)} minutes`)),console.log(""),await G(i)||(console.log(t.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(t.white("Please open this URL manually: ")+t.blue(i)),console.log(""));let g=w("Waiting for authorization...").start(),Y=(p||3)*1e3,D=Math.floor(u/(p||3)),k=0,S=!1,x=()=>{S=!0,g.stop(),console.log(t.yellow(`
8
+ `));let y=await O();r(y)}else console.log(t.green(`Using existing session.
9
+ `)),r({success:!0,...o})}catch(y){a(y)}})})}return await O()}catch(o){return console.error(t.red(`
10
+ \u274C Login failed:`,o.message)),{success:!1,error:o.message}}}async function W(o){let e=v();try{let n=await fetch(`${e}/projects`,{headers:{Authorization:`Bearer ${o}`}});if(n.ok){let a=((await n.json()).projects||[]).map(i=>({name:i.name,projectId:i.projectId,apiToken:i.apiToken}));return z(a),a}}catch(n){console.log(t.gray(`\u26A0\uFE0F Could not fetch projects: ${n.message}`))}return[]}async function O(){let o=v(),e=w("Requesting login code...").start(),n=await fetch(`${o}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!n.ok){e.fail("Failed to request login code");let l=await n.json();throw new Error(l.error||"Failed to initiate login")}let{deviceCode:r,userCode:a,verificationUrl:i,expiresIn:u,interval:p}=await n.json();e.succeed("Login code generated"),console.log(""),console.log(t.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")),console.log(t.cyan("\u2551")+t.white.bold(" Complete login in your browser ")+t.cyan("\u2551")),console.log(t.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")),console.log(""),console.log(t.white("Opening browser to login page...")),console.log(t.gray(`Code expires in ${Math.floor(u/60)} minutes`)),console.log(""),await G(i)||(console.log(t.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(t.white("Please open this URL manually: ")+t.blue(i)),console.log(""));let g=w("Waiting for authorization...").start(),Y=(p||3)*1e3,D=Math.floor(u/(p||3)),b=0,k=!1,S=()=>{k=!0,g.stop(),console.log(t.yellow(`
11
11
 
12
12
  \u26A0\uFE0F Login cancelled
13
- `)),process.exit(0)};process.on("SIGINT",x);try{for(;k<D&&!S;){await q(Y),k++;let l=await fetch(`${o}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:r})});if(l.status===202)continue;if(!l.ok){g.fail("Authorization failed");let m=await l.json();throw new Error(m.error||"Authorization failed")}let s=await l.json();if(s.status==="authorized"){g.succeed(t.white("Authorization successful!")),B(s.token),L(s.user),s.proxyUrl&&R(s.proxyUrl),s.mem0ProxyUrl&&C(s.mem0ProxyUrl),console.log(""),console.log(t.gray(`User: ${s.user.email}`));let m=w("Fetching projects...").start(),b=await W(s.token);return m.succeed(`Fetched ${b.length} project${b.length!==1?"s":""}`),console.log(t.gray(`Session saved to: ~/.zibby/config.json
14
- `)),{success:!0,loggedIn:!0,user:s.user,token:s.token}}if(s.status==="denied")throw g.fail("Authorization denied"),new Error("User denied authorization")}throw g.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",x)}}function q(o){return new Promise(e=>setTimeout(e,o))}function E(){try{let o=process.env.HOME||process.env.USERPROFILE;if(!o)return null;let e=oo(o,".zibby","config.json");return X(e)&&JSON.parse(Q(e,"utf-8")).sessionToken||null}catch{return null}}function I(){console.log(`
13
+ `)),process.exit(0)};process.on("SIGINT",S);try{for(;b<D&&!k;){await q(Y),b++;let l=await fetch(`${o}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:r})});if(l.status===202)continue;if(!l.ok){g.fail("Authorization failed");let m=await l.json();throw new Error(m.error||"Authorization failed")}let s=await l.json();if(s.status==="authorized"){g.succeed(t.white("Authorization successful!")),B(s.token),L(s.user),s.proxyUrl&&R(s.proxyUrl),s.mem0ProxyUrl&&C(s.mem0ProxyUrl),console.log(""),console.log(t.gray(`User: ${s.user.email}`));let m=w("Fetching projects...").start(),x=await W(s.token);return m.succeed(`Fetched ${x.length} project${x.length!==1?"s":""}`),console.log(t.gray(`Session saved to: ~/.zibby/config.json
14
+ `)),{success:!0,loggedIn:!0,user:s.user,token:s.token}}if(s.status==="denied")throw g.fail("Authorization denied"),new Error("User denied authorization")}throw g.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",S)}}function q(o){return new Promise(e=>setTimeout(e,o))}function E(){try{let o=process.env.HOME||process.env.USERPROFILE;if(!o)return null;let e=oo(o,".zibby","config.json");return X(e)&&JSON.parse(Q(e,"utf-8")).sessionToken||null}catch{return null}}function I(){console.log(`
15
15
  Not authenticated.`),console.log(` Run ${U.cyan("zibby login")} or set ${U.cyan("ZIBBY_API_KEY")} in your environment.
16
16
  `)}async function Ro(o={}){let e=o.apiKey||process.env.ZIBBY_API_KEY||null,n=E();if(n||e)return{sessionToken:n,apiKey:e};if(!process.stdin.isTTY){if(o.optional)return{sessionToken:null,apiKey:null};I(),process.exit(1)}console.log(U.yellow(`
17
17
  Not logged in.`));let r;try{r=await eo({message:"Open browser to log in now?",default:!0})}catch{r=!1}if(!r){if(o.optional)return{sessionToken:null,apiKey:null};I(),process.exit(1)}if(await $(),n=E(),!n){if(o.optional)return{sessionToken:null,apiKey:null};I(),process.exit(1)}return{sessionToken:n,apiKey:null}}export{Ro as ensureAuthenticated};
package/dist/bin/zibby.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- process.stdout.on("error",o=>{o.code}),process.stderr.on("error",o=>{o.code}),process.env.DOTENV_CONFIG_QUIET="true";import"@zibby/skills";import{Command as w}from"commander";import{initCommand as f}from"../commands/init.js";import{runCommand as y}from"../commands/run.js";import{videoCommand as g}from"../commands/video.js";import{uploadCommand as k}from"../commands/upload.js";import{ciSetupCommand as h}from"../commands/ci-setup.js";import{setupPlaywrightMcpCommand as b,setupCiCommand as v,testWithVideoCommand as I}from"../commands/setup-scripts.js";import{readFileSync as C}from"fs";import{fileURLToPath as P}from"url";import{dirname as S,join as B}from"path";import{bootstrapAgentEnv as A}from"../utils/agent-credentials.js";const _=P(import.meta.url),j=S(_),d=JSON.parse(C(B(j,"../package.json"),"utf-8"));function s(o,e){return e.push(o),e}const m=`zibby v${d.version}`,i=process.argv.slice(2),x=i.includes("-h")||i.includes("--help"),E=i.includes("-v")||i.includes("-V")||i.includes("--version");E&&(console.log(m),process.exit(0));const u=i[0],D=i[1],Y=["logs","uninstall"],Z=u==="workflow"&&D==="list";!Y.includes(u)&&!Z&&console.log(`${m}
3
- `),A(process.cwd());const O=i[0]==="chat",z=["--verbose","--agent","--stream","-s"],R=i.length>0&&i.every(o=>z.includes(o)||i[i.indexOf(o)-1]==="--agent"),J=i.length===0||O||R;if(J&&!x){const o={},e=i.indexOf("--agent");e!==-1&&i[e+1]&&(o.agent=i[e+1]),i.includes("--verbose")&&(o.verbose=!0),(i.includes("--stream")||i.includes("-s"))&&(o.stream=!0);const{chatCommand:t}=await import("../commands/chat.js");await t(o),process.exit(0)}const n=new w;n.name("zibby").description("Zibby \u2014 the cloud pipeline for Claude Code, Cursor, Codex, and Gemini. Compose them into structured workflows with schema-enforced handoff.").version(d.version,"-V, --version"),n.configureHelp({visibleCommands:()=>[]}),n.addHelpText("after",`
2
+ process.stdout.on("error",o=>{o.code}),process.stderr.on("error",o=>{o.code}),process.env.DOTENV_CONFIG_QUIET="true";import"@zibby/skills";import{Command as y}from"commander";import{initCommand as g}from"../commands/init.js";import{runCommand as k}from"../commands/run.js";import{videoCommand as b}from"../commands/video.js";import{uploadCommand as h}from"../commands/upload.js";import{ciSetupCommand as v}from"../commands/ci-setup.js";import{setupPlaywrightMcpCommand as I,setupCiCommand as C,testWithVideoCommand as P}from"../commands/setup-scripts.js";import{readFileSync as S}from"fs";import{fileURLToPath as A}from"url";import{dirname as B,join as _}from"path";import{bootstrapAgentEnv as j}from"../utils/agent-credentials.js";const x=A(import.meta.url),E=B(x),m=JSON.parse(S(_(E,"../package.json"),"utf-8"));function s(o,e){return e.push(o),e}const u=`zibby v${m.version}`,i=process.argv.slice(2),D=i.includes("-h")||i.includes("--help"),z=i.includes("-v")||i.includes("-V")||i.includes("--version");z&&(console.log(u),process.exit(0));const w=i[0],Y=i[1],Z=["logs","uninstall"],O=w==="workflow"&&Y==="list";!Z.includes(w)&&!O&&console.log(`${u}
3
+ `),j(process.cwd());const R=i[0]==="chat",L=["--verbose","--agent","--stream","-s"],M=i.length>0&&i.every(o=>L.includes(o)||i[i.indexOf(o)-1]==="--agent"),J=i.length===0||R||M;if(J&&!D){const o={},e=i.indexOf("--agent");e!==-1&&i[e+1]&&(o.agent=i[e+1]),i.includes("--verbose")&&(o.verbose=!0),(i.includes("--stream")||i.includes("-s"))&&(o.stream=!0);const{chatCommand:t}=await import("../commands/chat.js");await t(o),process.exit(0)}const n=new y;n.name("zibby").description("Zibby \u2014 the cloud pipeline for Claude Code, Cursor, Codex, and Gemini. Compose them into structured workflows with schema-enforced handoff.").version(m.version,"-V, --version"),n.configureHelp({visibleCommands:()=>[]}),n.addHelpText("after",`
4
4
  Workflow (the platform):
5
5
  workflow new <name> Scaffold a new workflow at .zibby/workflows/<name>/
6
6
  workflow run <name> Run a workflow locally (one-shot, mirrors trigger flags)
@@ -45,4 +45,4 @@ Examples:
45
45
 
46
46
  Docs: https://docs.zibby.app
47
47
  GitHub: https://github.com/ZibbyHQ/zibby-agent
48
- `),n.command("init").description("Initialize a new Zibby test project (like rails new)").argument("[project-name]","Project name (optional, uses current directory if not provided)").option("--agent <type>","Agent to use (claude, cursor, codex, gemini)").option("--memory-backend <backend>","Memory backend to configure (dolt, mem0)","dolt").option("--skip-install","Skip npm install").option("--skip-memory","Skip test memory setup during initialization").option("-f, --force","Force reinitialize (overwrite existing config)").option("--headed","Run MCP browser in headed mode (visible browser)").option("--headless","Run MCP browser in headless mode (hidden browser)").option("--api-key <key>","Zibby API key for cloud sync").option("--cloud-sync","Enable cloud sync and install Zibby MCP").action(f),n.command("test").description("Run a test specification").argument("[spec-path]","Path to test spec file or inline test description in quotes").option("--sources <ids>","Comma-separated test case IDs to fetch from cloud").option("--execution <id>","Execution ID containing the test cases (required with --sources)").option("--agent <type>","Agent to use (claude, cursor, codex, gemini) - overrides config").option("--workflow <name>","Workflow to use (e.g., QuickSmokeWorkflow, quick-smoke)").option("--headless","Run browser in headless mode").option("--node <name>","Run only a specific node (e.g., execute_live, generate_script)").option("--session <id>",'Use existing session (e.g., 1768974629717 or "last") - requires --node').option("--session-path <dir>","Use this session folder (absolute or relative to cwd); Studio pins artifacts here").option("--project <id>","Project ID (optional, auto-detected from ZIBBY_API_KEY)").option("--collection <id-or-name>","Collection ID or name (creates new if name doesn't exist)").option("--folder <path>","Folder path within collection (optional, requires --collection)").option("--sync","Force upload to cloud (overrides cloudSync: false)").option("--no-sync","Skip upload to cloud (overrides cloudSync: true)").option("--config <path>","Path to config file",".zibby.config.mjs").option("--auto-approve","Auto-approve MCP tools (for CI/CD)").option("-o, --open","Open test results in browser after completion").option("--verbose","Show info level logs").option("--debug","Show debug level logs (most verbose)").option("-m, --mem","Enable test memory (Dolt-backed knowledge from previous runs)").action((o,e)=>(e.debug?process.env.ZIBBY_DEBUG="true":e.verbose&&(process.env.ZIBBY_VERBOSE="true"),y(o,e))),n.command("implement").description("Implement a Jira ticket using AI agent (runs in ECS container)").action(async(...o)=>{const{implementCommand:e}=await import("../commands/implement.js");return e(...o)}),n.command("analyze").description("Analyze a Jira ticket against the codebase (runs in ECS container)").option("--workflow <path>","Path to a local workflow JSON file (e.g., .zibby/workflow-analysis.json)").action(async(...o)=>{const{analyzeCommand:e}=await import("../commands/analyze-graph.js");return e(...o)}),n.command("video").description("Organize test videos next to test files").action(g),n.command("upload <spec-path>").description("Upload existing test artifacts to Zibby Cloud").option("--project <id>","Project ID (REQUIRED - use flag or ZIBBY_PROJECT_ID env)").option("--collection <id-or-name>","Collection ID or name (creates new if name doesn't exist)").option("--folder <path>","Folder path within collection (optional)").option("--agent <type>","Agent used (for metadata)").action(k),n.command("login").description("Log in to Zibby (opens browser for authentication)").action(async()=>{const{loginCli:o}=await import("../auth/cli-login.js");await o(),process.exit(0)}),n.command("logout").description("Log out from Zibby (clears saved session)").action(async()=>{const{logoutCli:o}=await import("../auth/cli-login.js");o(),process.exit(0)}),n.command("status").description("Show current authentication status and token details").option("--json","Output in JSON format (for scripts)").action(async o=>{const{showLoginStatus:e}=await import("../auth/cli-login.js");await e(o),process.exit(0)}),n.command("list").description("List your projects and API tokens").action(async()=>{const{listProjectsCommand:o}=await import("../commands/list-projects.js");await o()}),n.command("ci-setup").description("Setup Cursor Agent for CI/CD (patch and configure)").option("--get-keys","Get MCP approval keys").option("--save","Save approval keys to project").action(h),n.command("setup-playwright").description("Setup official Playwright MCP (from cursor-agent-package)").option("--headed","Configure MCP in headed mode (visible browser)").option("--viewport-width <width>","Viewport width (default: 1280)","1280").option("--viewport-height <height>","Viewport height (default: 720)","720").action(o=>{const e={width:parseInt(o.viewportWidth,10)||1280,height:parseInt(o.viewportHeight,10)||720};return b({...o,viewport:e})}),n.command("setup-ci-full").description("Complete CI/CD setup from scratch").action(v),n.command("test-video").description("Run Playwright tests with video recording").argument("[test-file]","Test file to run (default: tests/)").option("--headed","Run in headed mode (visible browser)").action(I),n.command("generate").description("Generate test specs from a ticket + codebase (local analysis using real AI agent)").option("-t, --ticket <key>","Jira ticket key (fetches automatically)").option("-i, --input <file>","Input file with ticket description/requirements").option("-d, --description <text>","Inline ticket description").option("--repo <path>","Path to the codebase (default: current directory)").option("--agent <type>","Agent to use (codex, claude, cursor, gemini)").option("--model <model>","Model override").option("-o, --output <dir>","Output directory for spec files (default: test-specs)").action(async o=>{const{generateCommand:e}=await import("../commands/generate.js");return e(o)}),n.command("studio").description("Launch Zibby Studio desktop (installs from CDN if needed). Uses this folder as the Zibby project.").option("-p, --port <port>","Port for the Studio API bridge (default: 3847)").option("--no-open","Start the API only; do not launch desktop app").option("--update","Force re-download of the latest Studio binary").action(async o=>{const{studioCommand:e}=await import("../commands/studio.js");return e(o)});const U=n.command("g").description("Generate scaffolds");U.command("workflow [name]").description("Scaffold a new custom workflow in .zibby/workflows/<name>/ (auto-generates name if omitted)").option("--skip-install","Skip running `npm install` in the new workflow folder").option("--agent <agent>","Set up agent helpers without prompting: claude | cursor | codex | all | none").option("--force-agents","Overwrite user-edited agent helper files (use with --agent)").action(async(o,e)=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(o,e)}),n.command("start <workflow-name>").description("Start a local dev server for a custom workflow").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(o,e)=>{const{startWorkflowCommand:t}=await import("../commands/workflows/start.js");return t(o,e)}),n.command("run <workflow-name>").description("Run a workflow locally \u2014 one-shot (alias of `zibby workflow run`)").option("-p, --param <key=value>","Input param (repeatable)",s,[]).option("--input <json>","Input as JSON string").option("--input-file <path>","Input as JSON file").action(async(o,e)=>{const{runLocalWorkflowCommand:t}=await import("../commands/workflows/run-local.js");return t(o,e)}),n.command("deploy [workflow-name]").description("Deploy a custom workflow to Zibby Cloud (interactive selection if workflow-name not provided)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--dedicated-ip <action>","Manage dedicated egress IP addon: enable | status | disable | use | unuse").option("--env <path>","Path to a .env file to sync into per-workflow env vars after deploy (repeatable)",s,[]).option("--verbose","Show raw CodeBuild logs during the bundle build").action(async(o,e)=>{if(e.dedicatedIp){const{dedicatedEgressCommand:a}=await import("../commands/workflows/dedicated-egress.js");return a(e.dedicatedIp,e.project)}const{deployWorkflowCommand:t}=await import("../commands/workflows/deploy.js");return t(o,e)}),n.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (interactive selection if not provided). Get UUIDs from `zibby workflow list`.").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").action(async(o,e)=>{const{triggerWorkflowCommand:t}=await import("../commands/workflows/trigger.js");return t(o,e)}),n.command("logs [jobId]").description("Fetch and display logs from a workflow execution (use -t to stream in real-time)").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (fetches the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --follow","Stream logs in real-time (like Heroku logs -t)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(o,e)=>{const{logsCommand:t}=await import("../commands/workflows/logs.js");return t(o,e)}),n.command("run-workflow").description("Run a deployed workflow from S3 sources (used by ECS containers)").action(async()=>{const{runWorkflowCommand:o}=await import("../commands/workflows/run.js");return o()});const l=n.command("memory").description("Test memory database \u2014 version-controlled knowledge from runs");l.command("stats").description("Show memory database statistics").action(async()=>{const{memoryStatsCommand:o}=await import("../commands/memory.js");return o()}),l.command("init").description("Initialize the memory database (Dolt)").action(async()=>{const{memoryInitCommand:o}=await import("../commands/memory.js");return o()}),l.command("compact").description("Prune old data and run Dolt GC to reclaim storage").option("--max-runs <n>","Keep last N runs per spec (default: 50)",parseInt).option("--max-age <days>","Remove data older than N days (default: 90)",parseInt).action(async o=>{const{memoryCompactCommand:e}=await import("../commands/memory.js");return e(o)}),l.command("reset").description("Wipe the memory database").option("-f, --force","Confirm reset").action(async o=>{const{memoryResetCommand:e}=await import("../commands/memory.js");return e(o)});const L=n.command("agents").description("Manage Claude/Cursor/Codex helper files for working with Zibby workflows");L.command("add [agent]").description("Add agent helpers (claude | cursor | codex | all). Prompts if no agent given.").option("--force","Overwrite user-edited helper files").action(async(o,e)=>{const{runAgentHelpers:t,addAgent:a}=await import("../commands/workflows/agent-helpers.js");if(o){const p=["claude","cursor","codex","all","none"];p.includes(o)||(console.error(`Unknown agent "${o}". Valid: ${p.join(", ")}`),process.exit(1)),o==="none"?await t({forcedAgents:["none"],force:e.force===!0}):o==="all"?await t({forcedAgents:["claude","cursor","codex"],force:e.force===!0}):await a(o,{force:e.force===!0})}else await t({forcedAgents:void 0,force:e.force===!0,forcePrompt:!0})});const r=n.command("workflow").description("Manage workflow graphs \u2014 new, start, deploy, trigger, logs, list, download, delete");r.command("new [name]").description("Scaffold a new custom workflow (alias of `zibby g workflow`)").option("--skip-install","Skip running `npm install` in the new workflow folder").option("--agent <agent>","Set up agent helpers without prompting: claude | cursor | codex | all | none").option("--force-agents","Overwrite user-edited agent helper files (use with --agent)").action(async(o,e)=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(o,e)}),r.command("run <workflow-name>").description("Run a workflow locally \u2014 one-shot, same input flags as `workflow trigger`").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON file \u2014 lowest precedence").action(async(o,e)=>{const{runLocalWorkflowCommand:t}=await import("../commands/workflows/run-local.js");return t(o,e)}),r.command("start <workflow-name>").description("Start a long-lived local dev server (Studio integration). Prefer `workflow run` for one-shots.").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(o,e)=>{const{startWorkflowCommand:t}=await import("../commands/workflows/start.js");return t(o,e)}),r.command("deploy [workflow-name]").description("Deploy a workflow to Zibby Cloud (alias of `zibby deploy`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--env <path>","Path to a .env file to sync into per-workflow env vars after deploy (repeatable)",s,[]).option("--verbose","Show raw CodeBuild logs during the bundle build").action(async(o,e)=>{const{deployWorkflowCommand:t}=await import("../commands/workflows/deploy.js");return t(o,e)}),r.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (alias of `zibby trigger`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").action(async(o,e)=>{const{triggerWorkflowCommand:t}=await import("../commands/workflows/trigger.js");return t(o,e)}),r.command("logs [jobId]").description("Tail logs from a workflow execution (alias of `zibby logs`)").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (fetches the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --follow","Stream logs in real-time (like Heroku logs -t)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(o,e)=>{const{logsCommand:t}=await import("../commands/workflows/logs.js");return t(o,e)}),r.command("download [uuid]").description("Download a workflow from Zibby Cloud to .zibby/workflows/<name>/. Pass a UUID (from `zibby workflow list`) for custom workflows, or use --type for built-ins.").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--type <type>","Built-in workflow type: analysis, implementation, run_test (alternative to positional <uuid>)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--output <dir>","Output directory base (default: .zibby/workflows)").option("--include-default","Download the built-in default graph if no custom one exists").action(async(o,e)=>{const{workflowDownloadCommand:t}=await import("../commands/workflow.js");return t({...e,uuid:o})}),r.command("list").description("List all workflows (local + remote if credentials available)").option("--local-only","Show only local workflows").option("--remote-only","Show only remote workflows (requires --project)").option("--project <id>","Project ID (optional, uses ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async o=>{if(o.remoteOnly){const{workflowListCommand:t}=await import("../commands/workflow.js");return t(o)}if(o.localOnly){const{listLocalWorkflowsCommand:t}=await import("../commands/workflows/list.js");return t(o)}const{listAllWorkflowsCommand:e}=await import("../commands/workflows/list.js");return e(o)}),r.command("delete <uuid>").description("Delete a deployed workflow by UUID").action(async o=>{const{deleteWorkflowCommand:e}=await import("../commands/workflows/delete.js");return e(o,{})});const c=r.command("env").description("Manage per-workflow encrypted env vars (set ANTHROPIC_API_KEY, DATABASE_URL, etc. per workflow)");c.command("list <uuid>").description("List env var key names for a workflow (values never returned)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(o,e)=>{const{listEnvCommand:t}=await import("../commands/workflows/env.js");return t(o,e)}),c.command("set <uuid> <kv>").description("Set or update one env var: zibby workflow env set <uuid> KEY=value").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(o,e,t)=>{const{setEnvCommand:a}=await import("../commands/workflows/env.js");return a(o,e,t)}),c.command("unset <uuid> <key>").description("Remove one env var from a workflow").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(o,e,t)=>{const{unsetEnvCommand:a}=await import("../commands/workflows/env.js");return a(o,e,t)}),c.command("push <uuid>").description("Bulk-replace env from one or more .env files (later files override). Removes any keys not in the new map.").option("--file <path>","Path to a .env file (repeatable, e.g. --file .env --file .env.prod)",s,[]).option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(o,e)=>{const{pushEnvCommand:t}=await import("../commands/workflows/env.js");return t(o,e)});const W=n.command("project").description("Manage Zibby projects");W.command("list").description("List all projects").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async o=>{const{projectListCommand:e}=await import("../commands/project.js");return e(o)});const M=n.command("run-queue").description("Parallel capacity \u2014 on-disk wait queue (see parallel.waitWhenAtCapacity in .zibby.config.mjs)");M.command("list").description("List CLI processes waiting for a run slot").option("--config <path>","Path to config file",".zibby.config.mjs").action(async o=>{const{runCapacityQueueListCommand:e}=await import("../commands/run-capacity-queue-cli.js");await e(o),process.exit(0)}),n.command("uninstall").description("Remove all Zibby data: global CLI, ~/.zibby, Cursor MCP config, Studio, and current project").option("--dry-run","Show what would be deleted without deleting").option("--deep","Also remove npx cache dirs containing zibby").action(async o=>{const{uninstallCommand:e}=await import("../commands/uninstall.js");await e(o),process.exit(0)}),n.parse();
48
+ `),n.command("init").description("Initialize a new Zibby project (config + credentials + workflow template)").argument("[project-name]","Project name (optional, uses current directory if not provided)").option("--agent <type>","Agent to use (claude, cursor, codex, gemini)").option("--memory-backend <backend>","Memory backend to configure (dolt, mem0)","dolt").option("-t, --template <name>","Workflow template to scaffold (see `zibby template list`)","browser-test-automation").option("--skip-install","Skip npm install").option("--skip-memory","Skip test memory setup during initialization").option("-f, --force","Force reinitialize (overwrite existing config)").option("--headed","Run MCP browser in headed mode (visible browser)").option("--headless","Run MCP browser in headless mode (hidden browser)").option("--api-key <key>","Zibby API key for cloud sync").option("--cloud-sync","Enable cloud sync and install Zibby MCP").option("--agent-key <key>","Agent API key (non-interactive). For Claude this is the per-token API key").option("--agent-oauth-token <token>","Claude OAuth subscription token (non-interactive). Saves to ~/.zibby/config.json").action(g),n.command("test").description("Run a test specification").argument("[spec-path]","Path to test spec file or inline test description in quotes").option("--sources <ids>","Comma-separated test case IDs to fetch from cloud").option("--execution <id>","Execution ID containing the test cases (required with --sources)").option("--agent <type>","Agent to use (claude, cursor, codex, gemini) - overrides config").option("--workflow <name>","Workflow to use (e.g., QuickSmokeWorkflow, quick-smoke)").option("--headless","Run browser in headless mode").option("--node <name>","Run only a specific node (e.g., execute_live, generate_script)").option("--session <id>",'Use existing session (e.g., 1768974629717 or "last") - requires --node').option("--session-path <dir>","Use this session folder (absolute or relative to cwd); Studio pins artifacts here").option("--project <id>","Project ID (optional, auto-detected from ZIBBY_API_KEY)").option("--collection <id-or-name>","Collection ID or name (creates new if name doesn't exist)").option("--folder <path>","Folder path within collection (optional, requires --collection)").option("--sync","Force upload to cloud (overrides cloudSync: false)").option("--no-sync","Skip upload to cloud (overrides cloudSync: true)").option("--config <path>","Path to config file",".zibby.config.mjs").option("--auto-approve","Auto-approve MCP tools (for CI/CD)").option("-o, --open","Open test results in browser after completion").option("--verbose","Show info level logs").option("--debug","Show debug level logs (most verbose)").option("-m, --mem","Enable test memory (Dolt-backed knowledge from previous runs)").action((o,e)=>(e.debug?process.env.ZIBBY_DEBUG="true":e.verbose&&(process.env.ZIBBY_VERBOSE="true"),k(o,e))),n.command("implement").description("Implement a Jira ticket using AI agent (runs in ECS container)").action(async(...o)=>{const{implementCommand:e}=await import("../commands/implement.js");return e(...o)}),n.command("analyze").description("Analyze a Jira ticket against the codebase (runs in ECS container)").option("--workflow <path>","Path to a local workflow JSON file (e.g., .zibby/workflow-analysis.json)").action(async(...o)=>{const{analyzeCommand:e}=await import("../commands/analyze-graph.js");return e(...o)}),n.command("video").description("Organize test videos next to test files").action(b),n.command("upload <spec-path>").description("Upload existing test artifacts to Zibby Cloud").option("--project <id>","Project ID (REQUIRED - use flag or ZIBBY_PROJECT_ID env)").option("--collection <id-or-name>","Collection ID or name (creates new if name doesn't exist)").option("--folder <path>","Folder path within collection (optional)").option("--agent <type>","Agent used (for metadata)").action(h),n.command("login").description("Log in to Zibby (opens browser for authentication)").action(async()=>{const{loginCli:o}=await import("../auth/cli-login.js");await o(),process.exit(0)}),n.command("logout").description("Log out from Zibby (clears saved session)").action(async()=>{const{logoutCli:o}=await import("../auth/cli-login.js");o(),process.exit(0)}),n.command("status").description("Show current authentication status and token details").option("--json","Output in JSON format (for scripts)").action(async o=>{const{showLoginStatus:e}=await import("../auth/cli-login.js");await e(o),process.exit(0)}),n.command("list").description("List your projects and API tokens").action(async()=>{const{listProjectsCommand:o}=await import("../commands/list-projects.js");await o()}),n.command("ci-setup").description("Setup Cursor Agent for CI/CD (patch and configure)").option("--get-keys","Get MCP approval keys").option("--save","Save approval keys to project").action(v),n.command("setup-playwright").description("Setup official Playwright MCP (from cursor-agent-package)").option("--headed","Configure MCP in headed mode (visible browser)").option("--viewport-width <width>","Viewport width (default: 1280)","1280").option("--viewport-height <height>","Viewport height (default: 720)","720").action(o=>{const e={width:parseInt(o.viewportWidth,10)||1280,height:parseInt(o.viewportHeight,10)||720};return I({...o,viewport:e})}),n.command("setup-ci-full").description("Complete CI/CD setup from scratch").action(C),n.command("test-video").description("Run Playwright tests with video recording").argument("[test-file]","Test file to run (default: tests/)").option("--headed","Run in headed mode (visible browser)").action(P),n.command("generate").description("Generate test specs from a ticket + codebase (local analysis using real AI agent)").option("-t, --ticket <key>","Jira ticket key (fetches automatically)").option("-i, --input <file>","Input file with ticket description/requirements").option("-d, --description <text>","Inline ticket description").option("--repo <path>","Path to the codebase (default: current directory)").option("--agent <type>","Agent to use (codex, claude, cursor, gemini)").option("--model <model>","Model override").option("-o, --output <dir>","Output directory for spec files (default: test-specs)").action(async o=>{const{generateCommand:e}=await import("../commands/generate.js");return e(o)}),n.command("studio").description("Launch Zibby Studio desktop (installs from CDN if needed). Uses this folder as the Zibby project.").option("-p, --port <port>","Port for the Studio API bridge (default: 3847)").option("--no-open","Start the API only; do not launch desktop app").option("--update","Force re-download of the latest Studio binary").action(async o=>{const{studioCommand:e}=await import("../commands/studio.js");return e(o)});const p=n.command("creds").description("Manage credentials Zibby has stored for your workspace (KMS-encrypted)");p.command("list").description("List credentials stored for your workspace (masked)").action(async()=>{const{listCmd:o}=await import("../commands/creds.js");await o(),process.exit(0)}),p.command("sync").description("Re-read ~/.zibby/credentials.env and upload any new tokens").action(async()=>{const{syncCmd:o}=await import("../commands/creds.js");await o(),process.exit(0)}),p.command("remove <type> <index>").description("Remove a stored credential. e.g. zibby creds remove oauth 0").action(async(o,e)=>{const{removeCmd:t}=await import("../commands/creds.js");await t(o,e),process.exit(0)});const U=n.command("g").description("Generate scaffolds");U.command("workflow [name]").description("Scaffold a new custom workflow in .zibby/workflows/<name>/ (auto-generates name if omitted)").option("--skip-install","Skip running `npm install` in the new workflow folder").option("--agent <agent>","Set up agent helpers without prompting: claude | cursor | codex | all | none").option("--force-agents","Overwrite user-edited agent helper files (use with --agent)").action(async(o,e)=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(o,e)}),n.command("start <workflow-name>").description("Start a local dev server for a custom workflow").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(o,e)=>{const{startWorkflowCommand:t}=await import("../commands/workflows/start.js");return t(o,e)}),n.command("run <workflow-name>").description("Run a workflow locally \u2014 one-shot (alias of `zibby workflow run`)").option("-p, --param <key=value>","Input param (repeatable)",s,[]).option("--input <json>","Input as JSON string").option("--input-file <path>","Input as JSON file").action(async(o,e)=>{const{runLocalWorkflowCommand:t}=await import("../commands/workflows/run-local.js");return t(o,e)}),n.command("deploy [workflow-name]").description("Deploy a custom workflow to Zibby Cloud (interactive selection if workflow-name not provided)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--dedicated-ip <action>","Manage dedicated egress IP addon: enable | status | disable | use | unuse").option("--env <path>","Path to a .env file to sync into per-workflow env vars after deploy (repeatable)",s,[]).option("--verbose","Show raw CodeBuild logs during the bundle build").action(async(o,e)=>{if(e.dedicatedIp){const{dedicatedEgressCommand:a}=await import("../commands/workflows/dedicated-egress.js");return a(e.dedicatedIp,e.project)}const{deployWorkflowCommand:t}=await import("../commands/workflows/deploy.js");return t(o,e)}),n.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (interactive selection if not provided). Get UUIDs from `zibby workflow list`.").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").action(async(o,e)=>{const{triggerWorkflowCommand:t}=await import("../commands/workflows/trigger.js");return t(o,e)}),n.command("logs [jobId]").description("Fetch and display logs from a workflow execution (use -t to stream in real-time)").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (fetches the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --follow","Stream logs in real-time (like Heroku logs -t)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(o,e)=>{const{logsCommand:t}=await import("../commands/workflows/logs.js");return t(o,e)}),n.command("run-workflow").description("Run a deployed workflow from S3 sources (used by ECS containers)").action(async()=>{const{runWorkflowCommand:o}=await import("../commands/workflows/run.js");return o()});const f=n.command("template").description("Manage workflow templates in this project");f.command("list").description("List available workflow templates").action(async()=>{const{templateListCommand:o}=await import("../commands/template.js");return o()}),f.command("add").argument("<name>","Template name (see `zibby template list`)").description("Copy a workflow template into this project's .zibby/ (overwrites existing files = doubles as update)").option("--skip-memory","Strip SKILLS.MEMORY from copied execute-live.mjs (browser-test only)").action(async(o,e)=>{const{templateAddCommand:t}=await import("../commands/template.js");return t(o,{enableMemory:!e.skipMemory})});const c=n.command("memory").description("Test memory database \u2014 version-controlled knowledge from runs");c.command("stats").description("Show memory database statistics").action(async()=>{const{memoryStatsCommand:o}=await import("../commands/memory.js");return o()}),c.command("init").description("Initialize the memory database (Dolt)").action(async()=>{const{memoryInitCommand:o}=await import("../commands/memory.js");return o()}),c.command("compact").description("Prune old data and run Dolt GC to reclaim storage").option("--max-runs <n>","Keep last N runs per spec (default: 50)",parseInt).option("--max-age <days>","Remove data older than N days (default: 90)",parseInt).action(async o=>{const{memoryCompactCommand:e}=await import("../commands/memory.js");return e(o)}),c.command("reset").description("Wipe the memory database").option("-f, --force","Confirm reset").action(async o=>{const{memoryResetCommand:e}=await import("../commands/memory.js");return e(o)}),c.command("cost").description("Show real LLM token usage from past runs (input/output/cache)").action(async()=>{const{memoryCostCommand:o}=await import("../commands/memory.js");return o()});const W=n.command("agents").description("Manage Claude/Cursor/Codex helper files for working with Zibby workflows");W.command("add [agent]").description("Add agent helpers (claude | cursor | codex | all). Prompts if no agent given.").option("--force","Overwrite user-edited helper files").action(async(o,e)=>{const{runAgentHelpers:t,addAgent:a}=await import("../commands/workflows/agent-helpers.js");if(o){const d=["claude","cursor","codex","all","none"];d.includes(o)||(console.error(`Unknown agent "${o}". Valid: ${d.join(", ")}`),process.exit(1)),o==="none"?await t({forcedAgents:["none"],force:e.force===!0}):o==="all"?await t({forcedAgents:["claude","cursor","codex"],force:e.force===!0}):await a(o,{force:e.force===!0})}else await t({forcedAgents:void 0,force:e.force===!0,forcePrompt:!0})});const r=n.command("workflow").description("Manage workflow graphs \u2014 new, start, deploy, trigger, logs, list, download, delete");r.command("new [name]").description("Scaffold a new custom workflow (alias of `zibby g workflow`)").option("--skip-install","Skip running `npm install` in the new workflow folder").option("--agent <agent>","Set up agent helpers without prompting: claude | cursor | codex | all | none").option("--force-agents","Overwrite user-edited agent helper files (use with --agent)").action(async(o,e)=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(o,e)}),r.command("run <workflow-name>").description("Run a workflow locally \u2014 one-shot, same input flags as `workflow trigger`").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON file \u2014 lowest precedence").action(async(o,e)=>{const{runLocalWorkflowCommand:t}=await import("../commands/workflows/run-local.js");return t(o,e)}),r.command("start <workflow-name>").description("Start a long-lived local dev server (Studio integration). Prefer `workflow run` for one-shots.").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(o,e)=>{const{startWorkflowCommand:t}=await import("../commands/workflows/start.js");return t(o,e)}),r.command("deploy [workflow-name]").description("Deploy a workflow to Zibby Cloud (alias of `zibby deploy`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--env <path>","Path to a .env file to sync into per-workflow env vars after deploy (repeatable)",s,[]).option("--verbose","Show raw CodeBuild logs during the bundle build").action(async(o,e)=>{const{deployWorkflowCommand:t}=await import("../commands/workflows/deploy.js");return t(o,e)}),r.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (alias of `zibby trigger`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").action(async(o,e)=>{const{triggerWorkflowCommand:t}=await import("../commands/workflows/trigger.js");return t(o,e)}),r.command("logs [jobId]").description("Tail logs from a workflow execution (alias of `zibby logs`)").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (fetches the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --follow","Stream logs in real-time (like Heroku logs -t)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(o,e)=>{const{logsCommand:t}=await import("../commands/workflows/logs.js");return t(o,e)}),r.command("download [uuid]").description("Download a workflow from Zibby Cloud to .zibby/workflows/<name>/. Pass a UUID (from `zibby workflow list`) for custom workflows, or use --type for built-ins.").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--type <type>","Built-in workflow type: analysis, implementation, run_test (alternative to positional <uuid>)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--output <dir>","Output directory base (default: .zibby/workflows)").option("--include-default","Download the built-in default graph if no custom one exists").action(async(o,e)=>{const{workflowDownloadCommand:t}=await import("../commands/workflow.js");return t({...e,uuid:o})}),r.command("list").description("List all workflows (local + remote if credentials available)").option("--local-only","Show only local workflows").option("--remote-only","Show only remote workflows (requires --project)").option("--project <id>","Project ID (optional, uses ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async o=>{if(o.remoteOnly){const{workflowListCommand:t}=await import("../commands/workflow.js");return t(o)}if(o.localOnly){const{listLocalWorkflowsCommand:t}=await import("../commands/workflows/list.js");return t(o)}const{listAllWorkflowsCommand:e}=await import("../commands/workflows/list.js");return e(o)}),r.command("delete <uuid>").description("Delete a deployed workflow by UUID").action(async o=>{const{deleteWorkflowCommand:e}=await import("../commands/workflows/delete.js");return e(o,{})});const l=r.command("env").description("Manage per-workflow encrypted env vars (set ANTHROPIC_API_KEY, DATABASE_URL, etc. per workflow)");l.command("list <uuid>").description("List env var key names for a workflow (values never returned)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(o,e)=>{const{listEnvCommand:t}=await import("../commands/workflows/env.js");return t(o,e)}),l.command("set <uuid> <kv>").description("Set or update one env var: zibby workflow env set <uuid> KEY=value").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(o,e,t)=>{const{setEnvCommand:a}=await import("../commands/workflows/env.js");return a(o,e,t)}),l.command("unset <uuid> <key>").description("Remove one env var from a workflow").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(o,e,t)=>{const{unsetEnvCommand:a}=await import("../commands/workflows/env.js");return a(o,e,t)}),l.command("push <uuid>").description("Bulk-replace env from one or more .env files (later files override). Removes any keys not in the new map.").option("--file <path>","Path to a .env file (repeatable, e.g. --file .env --file .env.prod)",s,[]).option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(o,e)=>{const{pushEnvCommand:t}=await import("../commands/workflows/env.js");return t(o,e)});const T=n.command("project").description("Manage Zibby projects");T.command("list").description("List all projects").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async o=>{const{projectListCommand:e}=await import("../commands/project.js");return e(o)});const K=n.command("run-queue").description("Parallel capacity \u2014 on-disk wait queue (see parallel.waitWhenAtCapacity in .zibby.config.mjs)");K.command("list").description("List CLI processes waiting for a run slot").option("--config <path>","Path to config file",".zibby.config.mjs").action(async o=>{const{runCapacityQueueListCommand:e}=await import("../commands/run-capacity-queue-cli.js");await e(o),process.exit(0)}),n.command("uninstall").description("Remove all Zibby data: global CLI, ~/.zibby, Cursor MCP config, Studio, and current project").option("--dry-run","Show what would be deleted without deleting").option("--deep","Also remove npx cache dirs containing zibby").action(async o=>{const{uninstallCommand:e}=await import("../commands/uninstall.js");await e(o),process.exit(0)}),n.parse();
@@ -0,0 +1 @@
1
+ var P=Object.defineProperty;var h=(s,n)=>()=>(s&&(n=s(s=0)),n);var b=(s,n)=>{for(var t in n)P(s,t,{get:n[t],enumerable:!0})};var _={};b(_,{DEFAULT_CONFIG_PATH:()=>w,discoverCredentials:()=>z,maskToken:()=>R,parseConfigJson:()=>$,readCredentialsConfig:()=>x});import T from"node:fs/promises";import U from"node:path";import j from"node:os";function $(s){if(!s)return[];let n;try{n=JSON.parse(s)}catch{return[]}let t=n?.agentKeys;if(!t||typeof t!="object")return[];let r=[],i=new Set;for(let[e,c]of Object.entries(m)){let a=t[e];if(!a||typeof a!="string")continue;let d=e.endsWith("_POOL")?a.split(",").map(l=>l.trim()).filter(Boolean):[a.trim()];for(let l of d)l.length<8||i.has(l)||(i.add(l),r.push({type:c,token:l,source_var:e}))}return r}async function x(s=w){let n;try{n=await T.readFile(s,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return $(n)}async function z({filepath:s,env:n=process.env}={}){let t=await x(s),r=new Set(t.map(e=>e.token)),i=[];for(let[e,c]of Object.entries(m)){let a=n[e];if(!a)continue;let d=e.endsWith("_POOL")?a.split(",").map(l=>l.trim()).filter(Boolean):[a];for(let l of d)l.length<8||r.has(l)||(r.add(l),i.push({type:c,token:l,source_var:e,source:"process.env"}))}return{config:t.map(e=>({...e,source:"config.json"})),env:i,all:[...t.map(e=>({...e,source:"config.json"})),...i]}}function R(s){return!s||typeof s!="string"||s.length<=4?"***":`***${s.slice(-4)}`}var w,m,C=h(()=>{w=U.join(j.homedir(),".zibby","config.json"),m={CLAUDE_CODE_OAUTH_TOKEN:"oauth",CLAUDE_CODE_OAUTH_TOKEN_POOL:"oauth",ANTHROPIC_AUTH_TOKEN:"oauth",ANTHROPIC_API_KEY:"api",ANTHROPIC_API_KEY_POOL:"api"}});var A={};b(A,{addCredential:()=>S,deleteCredential:()=>D,listCredentials:()=>N,syncFromLocal:()=>L});function g(s,n=""){return`${String(s).replace(/\/+$/,"")}/agents/credentials${n}`}function y(){let s=new Error("Session expired \u2014 run zibby login");return s.code="AUTH_EXPIRED",s}async function N({apiUrl:s,sessionToken:n}){if(!n)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let t=await fetch(g(s),{headers:{Authorization:`Bearer ${n}`}});if(t.status===401)throw y();if(t.status===404)return{credentials:[],by_type:{oauth:[],api:[]},total:0};if(!t.ok){let r=new Error(`List credentials failed (${t.status})`);throw r.status=t.status,r}return t.json()}async function S({apiUrl:s,sessionToken:n,type:t,token:r,source:i="~/.zibby/config.json"}){if(!n)throw new Error("No session token \u2014 run zibby login first");let e=await fetch(g(s),{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({type:t,token:r,source:i})});if(e.status===401)throw y();if(!e.ok){let c=`Add credential failed (${e.status})`;try{let d=await e.json();d?.error&&(c=`${c}: ${d.error}`)}catch{}let a=new Error(c);throw a.status=e.status,a}return e.json()}async function D({apiUrl:s,sessionToken:n,type:t,index:r}){if(!n)throw new Error("No session token \u2014 run zibby login first");let i=await fetch(g(s,`/${encodeURIComponent(t)}/${encodeURIComponent(r)}`),{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(i.status===401)throw y();if(!i.ok){let e=new Error(`Delete credential failed (${i.status})`);throw e.status=i.status,e}return i.json()}async function L({apiUrl:s,sessionToken:n,credentials:t}){let r=0,i=0,e=[];for(let c of t)try{let a=await S({apiUrl:s,sessionToken:n,type:c.type,token:c.token,source:c.source_var||c.source||"local"});a.deduped?i+=1:a.added&&(r+=1)}catch(a){e.push({masked:c.token?`***${c.token.slice(-4)}`:"***",error:a.message})}return{added:r,deduped:i,errors:e}}var E=h(()=>{});import{select as v,confirm as p,Separator as I}from"@inquirer/prompts";import o from"chalk";var u=[{id:"zibby",name:"Zibby Chat",short:"default",description:"Built-in chat using Anthropic SDK directly \xB7 BYOK \xB7 included with workspace",pricePerMonth:0,deployment:"instant"},{id:"claude-code",name:"Claude Code",short:"add-on",description:"Anthropic's Claude Code CLI deployed in your private sandbox",pricePerMonth:20,deployment:"fargate-warm"}];async function X({apiUrl:s,sessionToken:n,currentAgentId:t="zibby"}={}){let r;try{r=await K({apiUrl:s,sessionToken:n})}catch(e){if(/login/i.test(e.message))throw e;console.warn(o.gray(` (could not fetch sessions: ${e.message})`)),r=[]}let i=[];if(r.length>0){for(let e of r){let a=u.find(k=>k.id===e.agent_type)?.name||e.agent_type,d=Z(e.last_active),l=typeof e.message_count=="number"&&e.message_count>0?o.gray(` \xB7 ${e.message_count} msg`):"",O=e.label?o.gray(` \xB7 "${e.label}"`):"";i.push({name:`${o.cyan("\u2726")} ${a} ${o.gray(`(${d})`)}${O}${l}`,value:{action:"resume",agentType:e.agent_type,sessionId:e.session_id,session:e},description:o.gray(` Resume your ${a} session`)})}i.push(new I)}for(let e of u)e.id!=="zibby"&&i.push({name:`${o.dim("+")} New ${e.name} session${e.pricePerMonth>0?o.yellow(` (+$${e.pricePerMonth}/mo)`):""}`,value:{action:"create",agentType:e.id},description:o.gray(` ${e.description}`)});i.push(new I),i.push({name:`${o.green("\u2190")} Back to Zibby Chat (default)${t==="zibby"?o.dim(" [current]"):""}`,value:{action:"switch",agentType:"zibby"},description:o.gray(" Built-in chat using Anthropic SDK directly")});try{return await v({message:"Select chat agent:",choices:i})}catch(e){if(e?.name==="ExitPromptError")return{action:"cancel"};throw e}}async function Q(s="zibby"){let n=await v({message:"Select chat agent for this workspace:",default:s,choices:u.map(t=>{let r=t.pricePerMonth===0?o.green(" (included)"):o.yellow(` (+$${t.pricePerMonth}/mo)`),i=t.id===s?o.dim(" [current]"):"";return{name:`${t.name}${r}${i}`,value:t.id,description:o.gray(` ${t.description}`)}})});return u.find(t=>t.id===n)}async function V({workspaceId:s,sessionToken:n,apiUrl:t}){let r=await M({addon:"claude-code",workspaceId:s,sessionToken:n,apiUrl:t});if(r.configured&&r.sandboxState==="ready")return console.log(""),console.log(o.green(" \u2713 Claude Code is already deployed for your team.")),console.log(o.gray(` Sandbox: ${r.sandboxId} \xB7 state: ${r.sandboxState}`)),console.log(""),{ready:!0,sandboxId:r.sandboxId};if(r.configured&&r.sandboxState!=="ready")return console.log(""),console.log(o.cyan(` \u2699 Claude Code sandbox is ${r.sandboxState}...`)),console.log(o.gray(" You can keep using Zibby Chat \u2014 we'll switch when it's ready.")),console.log(""),{ready:!1,provisioning:!0,sandboxId:r.sandboxId};if(console.log(""),console.log(o.yellow(" Claude Code add-on is not enabled for your workspace.")),console.log(""),console.log(o.white(" About this add-on:")),console.log(o.gray(" \u2022 Anthropic's official Claude Code CLI runs in YOUR isolated sandbox")),console.log(o.gray(" \u2022 YOU provide your own Anthropic credentials (in ~/.zibby/config.json)")),console.log(o.gray(" \u2022 Zibby NEVER accesses Anthropic on your behalf \u2014 your tokens, your API calls")),console.log(o.gray(" \u2022 Zibby stores credentials KMS-encrypted, decrypts only inside YOUR sandbox")),console.log(o.gray(" \u2022 You're responsible for ToS compliance with the credentials you provide:")),console.log(o.gray(" https://www.anthropic.com/legal/commercial-terms")),console.log(""),console.log(o.cyan(" Pricing:")),console.log(o.white(" $20 / month per workspace ")+o.gray("\xB7 Zibby infrastructure fee, billed via Stripe")),console.log(o.gray(" Your Anthropic usage bills directly to your Anthropic account")),console.log(""),!await p({message:"Do you agree to Anthropic's Commercial Terms of Service?",default:!1}))return console.log(o.gray(" Cancelled. Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0};if(!await p({message:"Enable Claude Code add-on at $20/month?",default:!1}))return console.log(o.gray(" Cancelled. Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0};console.log(""),console.log(o.cyan(" Enabling Claude Code add-on..."));let c;try{c=await Y({addon:"claude-code",workspaceId:s,sessionToken:n,apiUrl:t,accept:{tos:!0,billing:!0}})}catch(a){if(a?.code==="BILLING_REQUIRED"){console.log("");let d=a.upgradeUrl?.startsWith("http")?a.upgradeUrl:"https://zibby.dev/billing";return a.needsSubscription?(console.log(o.yellow(" \u26A0 You need an active Pro subscription to enable Claude Code.")),console.log(o.gray(` Upgrade here: ${d}`))):a.needsPaymentMethod?(console.log(o.yellow(" \u26A0 Your card was declined or no payment method is on file.")),console.log(o.gray(` Update billing: ${d}`))):(console.log(o.yellow(` \u26A0 ${a.message}`)),console.log(o.gray(` Manage billing: ${d}`))),console.log(""),console.log(o.gray(" Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0,billingRequired:!0}}throw a}return console.log(""),console.log(o.green(" \u2713 Stripe subscription created")),console.log(o.gray(` sub_id: ${c.subscriptionId}`)),console.log(o.green(" \u2713 Lambda invoked: zibby-prod-provision-sandbox")),console.log(o.gray(` request: ${c.requestId}`)),console.log(o.cyan(" \u2699 Fargate task launching: zibby/agent-runtime:claude-code-v1")),console.log(o.gray(` sandbox_id: ${c.sandboxId}`)),console.log(""),await B({apiUrl:t,sessionToken:n}),console.log(""),console.log(o.gray(" Sandbox provisioning in the background. Zibby Chat (default) is active until ready.")),console.log(""),{ready:!1,provisioning:!0,sandboxId:c.sandboxId,deploymentId:c.requestId}}async function B({apiUrl:s,sessionToken:n}){let t;try{let{discoverCredentials:e}=await Promise.resolve().then(()=>(C(),_));t=await e()}catch(e){console.log(o.gray(` (could not scan local credentials: ${e.message})`));return}let r=t.all.length;if(r===0){console.log(o.yellow(" \u26A0 No Anthropic credentials found locally.")),console.log(""),console.log(o.white(" Two ways to authenticate Claude Code in your sandbox:")),console.log(""),console.log(o.bold(" Option A \u2014 provide your own (recommended):")),console.log(o.gray(" 1. Run: zibby init")),console.log(o.gray(" Pick Claude \u2192 Subscription (OAuth) or API key")),console.log(o.gray(" 2. Run: zibby creds sync (uploads to your workspace)")),console.log(o.gray(" 3. Re-run /agents in chat")),console.log(""),console.log(o.bold(" Option B \u2014 in-sandbox login (legacy):")),console.log(o.gray(" Skip this step. When sandbox is ready and you start")),console.log(o.gray(" Claude Code, it will prompt you to open a URL in your")),console.log(o.gray(" laptop browser to authenticate.")),console.log("");return}console.log(o.green(` \u2713 Found ${r} Anthropic ${r===1?"credential":"credentials"} in your local environment:`));for(let e of t.all){let c=e.source==="config.json"?`~/.zibby/config.json (${e.source_var})`:`process.env.${e.source_var}`;console.log(o.gray(` ${e.type} ***${e.token.slice(-4)} ${c}`))}if(console.log(""),console.log(o.white(" By proceeding you confirm:")),console.log(o.gray(" \u2022 These are YOUR credentials to use")),console.log(o.gray(" \u2022 You comply with Anthropic's ToS for the tier of these tokens")),console.log(o.gray(" \u2022 Zibby will store encrypted (AWS KMS) and inject into YOUR sandbox only")),console.log(""),!await p({message:"Upload these credentials to your Zibby workspace?",default:!0})){console.log(o.gray(" Skipped credential upload. Sandbox will fall back to in-sandbox login."));return}console.log(""),console.log(o.cyan(" Uploading (KMS-encrypted)..."));try{let{syncFromLocal:e}=await Promise.resolve().then(()=>(E(),A)),c=await e({apiUrl:s,sessionToken:n,credentials:t.all});console.log(o.green(` \u2713 ${c.added} new, ${c.deduped} already stored`)),c.errors.length>0&&console.log(o.yellow(` ${c.errors.length} failed \u2014 retry with 'zibby creds sync'`))}catch(e){console.log(o.red(` \u2717 Upload failed: ${e.message}`)),console.log(o.gray(" Sandbox will fall back to in-sandbox login when ready."))}}async function M({addon:s,sessionToken:n,apiUrl:t}){let r=process.env.ZIBBY_CLAUDE_CODE_STUB_STATUS;if(r==="ready")return{configured:!0,sandboxState:"ready",sandboxId:"sb_stub_acme_001"};if(r==="provisioning")return{configured:!0,sandboxState:"provisioning",sandboxId:"sb_stub_acme_001"};if(!t||!n)return{configured:!1,sandboxState:null,sandboxId:null};let i=`${String(t).replace(/\/+$/,"")}/agents/addons/${encodeURIComponent(s)}`,e;try{e=await fetch(i,{headers:{Authorization:`Bearer ${n}`}})}catch{return{configured:!1,sandboxState:null,sandboxId:null}}if(e.status===401){let a=new Error("Session expired \u2014 run zibby login");throw a.code="AUTH_EXPIRED",a}if(e.status===404)return{configured:!1,sandboxState:null,sandboxId:null};if(!e.ok)return{configured:!1,sandboxState:null,sandboxId:null};let c=await e.json();return{configured:!!c.configured,sandboxState:c.sandbox_state||null,sandboxId:c.sandbox_id||null,subscriptionId:c.subscription_id||null,enabledAt:c.enabled_at||null}}async function Y({addon:s,workspaceId:n,sessionToken:t,apiUrl:r}){if(!r||!t)return await new Promise(a=>setTimeout(a,500)),{subscriptionId:`sub_${Math.random().toString(36).slice(2,10)}`,sandboxId:`sb_${Math.random().toString(36).slice(2,10)}`,requestId:`req_offline_${Date.now().toString(36)}`};let i=`${String(r).replace(/\/+$/,"")}/agents/addons/${encodeURIComponent(s)}/enable`,e=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({workspace_id:n||null})});if(e.status===401){let a=new Error("Session expired \u2014 run zibby login");throw a.code="AUTH_EXPIRED",a}if(e.status===402){let a;try{a=await e.json()}catch{a={}}let d;try{d=typeof a.error=="string"?JSON.parse(a.error):a.error||a}catch{d={message:a.error||"Payment required"}}let l=new Error(d.message||"Payment required");throw l.code="BILLING_REQUIRED",l.status=402,l.needsSubscription=!!d.needs_subscription,l.needsPaymentMethod=!!d.needs_payment_method,l.upgradeUrl=d.upgrade_url||"/billing",l}if(!e.ok){let a=new Error(`Enable addon failed (${e.status})`);throw a.status=e.status,a}let c=await e.json();return{subscriptionId:c.subscription_id||null,sandboxId:c.sandbox_id||null,stripeSubscriptionItemId:c.stripe_subscription_item_id||null,requestId:c.request_id||`req_${Date.now().toString(36)}`}}function f(s,n){let t=String(s).replace(/\/+$/,"");return n?`${t}/agents/sessions/${encodeURIComponent(n)}`:`${t}/agents/sessions`}async function K({apiUrl:s,sessionToken:n}){if(!n)return[];let t=await fetch(f(s),{headers:{Authorization:`Bearer ${n}`}});if(t.status===401)throw new Error("Not authenticated. Run `zibby login` again.");if(t.status===404)return[];if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`Failed to list agent sessions (${t.status}): ${i.slice(0,200)}`)}let r=await t.json();return Array.isArray(r.sessions)?r.sessions:[]}async function ee({apiUrl:s,sessionToken:n,agentType:t,fields:r={}}){if(!n)throw new Error("Not authenticated");let i=await fetch(f(s,t),{method:"PUT",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok){let c=await i.text().catch(()=>"");throw new Error(`Failed to save agent session (${i.status}): ${c.slice(0,200)}`)}return(await i.json()).session}async function oe({apiUrl:s,sessionToken:n,agentType:t}){if(!n)throw new Error("Not authenticated");let r=await fetch(f(s,t),{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!r.ok){let e=await r.text().catch(()=>"");throw new Error(`Failed to delete agent session (${r.status}): ${e.slice(0,200)}`)}return(await r.json()).deleted===!0}function Z(s){if(!s)return"never";let n=new Date(s).getTime();if(Number.isNaN(n))return"unknown";let t=Math.max(0,(Date.now()-n)/1e3);if(t<60)return"just now";let r=t/60;if(r<60)return`${Math.round(r)}m ago`;let i=r/60;if(i<24)return`${Math.round(i)}h ago`;let e=i/24;if(e<30)return`${Math.round(e)}d ago`;let c=e/30;return`${Math.round(c)}mo ago`}export{u as AGENTS,oe as deleteAgentSession,K as fetchMyAgentSessions,Z as formatRelativeTime,V as handleClaudeCodeAddon,Q as pickAgent,X as pickAgentWithSessions,ee as upsertAgentSession};
@@ -0,0 +1,5 @@
1
+ import m from"ws";import g from"chalk";function S({sandboxEndpoint:r,sessionId:e,useTls:c=!1}){return`${c?"wss":"ws"}://${r}/stream/${encodeURIComponent(e)}`}async function x({sandboxEndpoint:r,sessionToken:e,agentType:c="claude-code",args:i=[],cwd:u="/workspace",useTls:a=!1}){let f=`${a?"https":"http"}://${r}/spawn`,d=await fetch(f,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({agent_type:c,args:i,cwd:u})});if(!d.ok){let l=await d.text().catch(()=>"");throw new Error(`spawn failed (${d.status}): ${l}`)}return await d.json()}async function $({sandboxEndpoint:r,sessionId:e,sessionToken:c,useTls:i=!1,showBanner:u=!0}){let a=S({sandboxEndpoint:r,sessionId:e,useTls:i}),t=new m(a,{headers:{Authorization:`Bearer ${c}`}});return new Promise((f,d)=>{let p=!1,l=!1,w=null,h=null,y=s=>{if(!p){p=!0;try{process.stdin.isTTY&&process.stdin.setRawMode&&process.stdin.setRawMode(l)}catch{}w&&process.stdin.off("data",w),h&&process.stdout.off("resize",h);try{process.stdin.pause()}catch{}try{t.close()}catch{}f(s)}};t.on("open",()=>{u&&(process.stdout.write(g.green(`
2
+ \u2713 Connected to cloud sandbox session ${e}
3
+ `)),process.stdout.write(g.gray(` Press Ctrl+\\ to detach (session keeps running).
4
+
5
+ `)));let s=()=>{let n=process.stdout.columns||80,o=process.stdout.rows||24;try{t.send(JSON.stringify({type:"resize",cols:n,rows:o}))}catch{}};s(),h=()=>s(),process.stdout.on("resize",h),process.stdin.isTTY&&process.stdin.setRawMode&&(l=!!process.stdin.isRaw,process.stdin.setRawMode(!0)),process.stdin.resume();try{process.stdin.setEncoding("utf8")}catch{}w=n=>{let o=n.toString("utf8");if(o.includes("")){y({reason:"detach"});return}try{t.send(o)}catch{}},process.stdin.on("data",w)}),t.on("message",s=>{let n=s.toString("utf8");if(n.startsWith("{")&&n.endsWith("}"))try{let o=JSON.parse(n);if(o&&o.type==="exit"){y({reason:"remote-exit",exitCode:o.exitCode,signal:o.signal});return}}catch{}try{process.stdout.write(n)}catch{}}),t.on("close",()=>{y({reason:"remote-close"})}),t.on("error",s=>{p||y({reason:"ws-error",message:s?.message||String(s)})}),setTimeout(()=>{if(t.readyState===m.CONNECTING){try{t.terminate()}catch{}p||(p=!0,d(new Error("WS connect timed out after 30s")))}},3e4).unref()})}async function z({sandboxEndpoint:r,sessionToken:e,agentType:c,args:i,cwd:u,useTls:a}){let t=await x({sandboxEndpoint:r,sessionToken:e,agentType:c,args:i,cwd:u,useTls:a});return{...await $({sandboxEndpoint:r,sessionId:t.session_id,sessionToken:e,useTls:a}),sessionId:t.session_id}}export{$ as attachToSession,x as spawnAgentSession,z as spawnAndAttach};