@zibby/cli 0.1.95 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/auth/cli-login.js +7 -7
- package/dist/auth/ensure-auth.js +6 -6
- package/dist/bin/zibby.js +3 -3
- package/dist/commands/chat-agents.js +1 -0
- package/dist/commands/chat-sandbox-attach.js +5 -0
- package/dist/commands/chat.js +79 -69
- package/dist/commands/credentials-api.js +1 -0
- package/dist/commands/credentials-file.js +1 -0
- package/dist/commands/creds.js +1 -0
- package/dist/commands/init.js +1 -1
- package/dist/commands/list-projects.js +5 -5
- package/dist/commands/project.js +3 -3
- package/dist/commands/run.js +54 -54
- package/dist/commands/studio.js +2 -2
- package/dist/commands/upload.js +4 -4
- package/dist/commands/workflow.js +23 -23
- package/dist/commands/workflows/dedicated-egress.js +6 -6
- package/dist/commands/workflows/delete.js +4 -4
- package/dist/commands/workflows/deploy.js +19 -19
- package/dist/commands/workflows/env.js +7 -7
- package/dist/commands/workflows/generate.js +1 -1
- package/dist/commands/workflows/list.js +6 -6
- package/dist/commands/workflows/run-local.js +19 -19
- package/dist/commands/workflows/start.js +15 -15
- package/dist/commands/workflows/trigger.js +7 -7
- package/dist/config/environments.js +1 -1
- package/dist/package.json +5 -5
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-static-ip.md +1 -1
- package/dist/utils/credentials-loader.js +1 -0
- package/package.json +5 -5
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import s from"chalk";import C from"ora";var r={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.
|
|
1
|
+
import s from"chalk";import C from"ora";var r={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 u(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let n=process.env.ZIBBY_ENV||"prod";r[n]?o=r[n].apiUrl:o=r.prod.apiUrl}try{let n=new URL(o);return n.protocol!=="http:"&&n.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${n.protocol} (only http/https allowed)`),r.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),r.prod.apiUrl}}import{existsSync as g,mkdirSync as A,readFileSync as E,writeFileSync as $}from"fs";import{homedir as U}from"os";import{join as i}from"path";function m(){return process.env.ZIBBY_CONFIG_DIR||i(U(),".zibby")}function I(){return i(m(),"config.json")}var L=i(U(),".zibby"),Z=i(L,"config.json");function T(){let o=m();g(o)||A(o,{recursive:!0})}function f(){try{let o=I();if(g(o)){let n=E(o,"utf-8");return JSON.parse(n)}}catch{}return{}}function k(o){T(),$(I(),JSON.stringify(o,null,2))}function h(){return f().sessionToken||null}function v(){return f().user||null}function y(o){let n=f();n.projects=o,k(n)}async function G(){let o=C("Fetching projects...").start();try{let n=h(),c=v();n||(o.fail("Not logged in"),console.log(s.yellow(`
|
|
2
2
|
Please log in first:`)),console.log(s.gray(` zibby login
|
|
3
3
|
`)),process.exit(1)),c&&(console.log(s.gray(`Logged in as: ${c.email}`)),c.account_id&&console.log(s.gray(`Account ID: ${c.account_id}
|
|
4
|
-
`)));let
|
|
5
|
-
No projects found`),console.log(`Create a project at: https://zibby.
|
|
6
|
-
`);return}let
|
|
4
|
+
`)));let _=u(),l=await fetch(`${_}/projects`,{headers:{Authorization:`Bearer ${n}`}});if(!l.ok){let e=await l.json().catch(()=>({}));throw new Error(e.error||"Failed to fetch projects")}let t=(await l.json()).projects||[],b=t.map(e=>({name:e.name,projectId:e.projectId,apiToken:e.apiToken}));if(y(b),o.stop(),t.length===0){console.log(`
|
|
5
|
+
No projects found`),console.log(`Create a project at: https://zibby.dev/projects
|
|
6
|
+
`);return}let j=e=>e&&e.length>8?`${e.substring(0,8)}\u2022\u2022\u2022\u2022`:e||"-",p=Math.max(4,...t.map(e=>e.name.length)),a=36,d=14,x=` ${"Name".padEnd(p)} ${"Project ID".padEnd(a)} ${"API Token".padEnd(d)}`,B=` ${"\u2500".repeat(p)} ${"\u2500".repeat(a)} ${"\u2500".repeat(d)}`;console.log(`
|
|
7
7
|
Your Projects (${t.length})
|
|
8
|
-
`),console.log(
|
|
8
|
+
`),console.log(x),console.log(B);for(let e of t){let P=e.name.padEnd(p),N=e.projectId.padEnd(a),R=j(e.apiToken).padEnd(d);console.log(` ${P} ${N} ${R}`)}console.log(""),console.log("\u{1F4A1} Use the Project ID with --project flag:"),console.log(` zibby run test-specs/login.txt --project <project-id> --sync
|
|
9
9
|
`)}catch(n){o.fail("Failed to fetch projects"),console.error(s.red(`
|
|
10
10
|
\u274C Error: ${n.message}
|
|
11
11
|
`)),process.exit(1)}}export{G as listProjectsCommand};
|
package/dist/commands/project.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import a from"dotenv";var s={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.
|
|
1
|
+
import a from"dotenv";var s={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 c(){let r;if(process.env.ZIBBY_API_URL)r=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";s[e]?r=s[e].apiUrl:r=s.prod.apiUrl}try{let e=new URL(r);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),s.prod.apiUrl):r}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${r}`),s.prod.apiUrl}}a.config();function d(r){let e=r.apiKey||process.env.ZIBBY_API_KEY;return e||(console.log(`
|
|
2
2
|
Error: API key is required`),console.log(` Set ZIBBY_API_KEY environment variable or use --api-key flag
|
|
3
|
-
`),process.exit(1)),{apiKey:e}}async function
|
|
3
|
+
`),process.exit(1)),{apiKey:e}}async function v(r={}){let{apiKey:e}=d(r),p=c();try{let t=await fetch(`${p}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}});if(!t.ok){let n=await t.json().catch(()=>({}));console.log(`
|
|
4
4
|
Error: ${n.message||t.statusText}
|
|
5
5
|
`),process.exit(1)}let o=await t.json();if(Array.isArray(o)||(o.projects&&Array.isArray(o.projects)?o=o.projects:o.data&&Array.isArray(o.data)?o=o.data:(console.log(`
|
|
6
6
|
Error: Unexpected response format
|
|
@@ -12,4 +12,4 @@ import a from"dotenv";var s={local:{name:"Local Development",apiUrl:"http://loca
|
|
|
12
12
|
Total: ${o.length} project${o.length===1?"":"s"}
|
|
13
13
|
`)}catch(t){console.log(`
|
|
14
14
|
Error: ${t.message}
|
|
15
|
-
`),process.exit(1)}}export{
|
|
15
|
+
`),process.exit(1)}}export{v as projectListCommand};
|
package/dist/commands/run.js
CHANGED
|
@@ -1,78 +1,78 @@
|
|
|
1
|
-
import{runTest as
|
|
2
|
-
`,"utf8")}function
|
|
3
|
-
`,"utf8")}import{readFileSync as
|
|
1
|
+
var Fe=Object.defineProperty;var pe=(t,o)=>()=>(t&&(o=t(t=0)),o);var De=(t,o)=>{for(var s in o)Fe(t,s,{get:o[s],enumerable:!0})};import no from"node:fs/promises";import so from"node:path";import ro from"node:os";function co(t){if(!t)return[];let o=[],s=new Set,c=String(t).split(/\r?\n/);for(let l of c){let r=l.trim();if(!r||r.startsWith("#"))continue;let n=r.indexOf("=");if(n<1)continue;let d=r.slice(0,n).trim(),u=r.slice(n+1).trim();if((u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),!u)continue;let p=Ee[d];if(!p)continue;let A=d.endsWith("_POOL")?u.split(",").map(m=>m.trim()).filter(Boolean):[u];for(let m of A)m.length<8||s.has(m)||(s.add(m),o.push({type:p,token:m,source_var:d}))}return o}async function lo(t=io){let o;try{o=await no.readFile(t,"utf8")}catch(s){if(s.code==="ENOENT")return[];throw s}return co(o)}async function be({filepath:t,env:o=process.env}={}){let s=await lo(t),c=new Set(s.map(r=>r.token)),l=[];for(let[r,n]of Object.entries(Ee)){let d=o[r];if(!d)continue;let u=r.endsWith("_POOL")?d.split(",").map(p=>p.trim()).filter(Boolean):[d];for(let p of u)p.length<8||c.has(p)||(c.add(p),l.push({type:n,token:p,source_var:r,source:"process.env"}))}return{file:s.map(r=>({...r,source:"file"})),env:l,all:[...s.map(r=>({...r,source:"file"})),...l]}}var io,Ee,Ae=pe(()=>{io=so.join(ro.homedir(),".zibby","credentials.env"),Ee={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 Se={};De(Se,{_resetLoaderCacheForTests:()=>uo,loadCredentialsIntoEnv:()=>ao});async function ao(t={}){let{verbose:o=!1,force:s=!1,filepath:c}=t;if(H&&!s)return F;if(!!(process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL||process.env.ANTHROPIC_API_KEY_POOL||process.env.CLAUDE_CODE_OAUTH_TOKEN||process.env.ANTHROPIC_API_KEY))return H=!0,F={oauthCount:0,apiCount:0,source:"cloud-env"},o&&console.log("[credentials-loader] env vars already set \u2014 skipping local discovery"),F;let r;try{r=await be(c?{filepath:c}:void 0)}catch(m){return o&&console.warn(`[credentials-loader] discovery failed: ${m.message}`),H=!0,F={oauthCount:0,apiCount:0,source:"none"},F}let n=r.all.filter(m=>m.type==="oauth").map(m=>m.token),d=r.all.filter(m=>m.type==="api").map(m=>m.token);n.length>0&&(process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL=n.join(",")),d.length>0&&(process.env.ANTHROPIC_API_KEY_POOL=d.join(","));let u=r.file.length,p=r.env.length,A=u>0&&p>0?"local-file+shell-env":u>0?"local-file":p>0?"shell-env":"none";return H=!0,F={oauthCount:n.length,apiCount:d.length,source:A},o&&(n.length||d.length)&&console.log(`[credentials-loader] loaded ${n.length} OAuth + ${d.length} API from ${A} (~/.zibby/credentials.env)`),F}function uo(){H=!1,F=null}var H,F,Te=pe(()=>{Ae();H=!1,F=null});import{runTest as po,logger as C,DEFAULT_OUTPUT_BASE as fo,SESSIONS_DIR as go}from"@zibby/core";import{zibbyScratchSpecsDir as ae}from"@zibby/core/constants/zibby-scratch.js";import{createCliRunIndexPipelineProgressAppender as ho,postCliInterruptedRunIndex as Ue}from"@zibby/core/utils/run-index-post-cli.js";import{createWriteStream as Ke,mkdirSync as ze}from"fs";import{join as fe,isAbsolute as Ge}from"path";var Me="studio-cli.log";function Ze(t,o){if(!t||typeof t!="string")return null;let s=t.trim();return s?Ge(s)?s:fe(o,s):null}function He(t){if(!t)return()=>{};ze(t,{recursive:!0});let o=fe(t,Me),s=Ke(o,{flags:"a"}),c=process.stdout.write.bind(process.stdout),l=process.stderr.write.bind(process.stderr),r=n=>function(u,p,A){typeof p=="function"&&(A=p,p=void 0);try{Buffer.isBuffer(u)?s.write(u):s.write(String(u),p||"utf8")}catch{}return n(u,p,A)};return process.stdout.write=r(c),process.stderr.write=r(l),()=>{process.stdout.write=c,process.stderr.write=l;try{s.end()}catch{}}}function oe(t,o,s){let c=null;function l(r){if(!c&&r?.sessionPath){let n=Ze(r.sessionPath,o);n&&(c=He(n))}typeof t=="function"&&t(r)}return l.dispose=()=>{typeof c=="function"&&(c(),c=null)},l}import{existsSync as ge,mkdirSync as We,readFileSync as Ve,readdirSync as Yo,unlinkSync as qe,writeFileSync as he}from"fs";import{join as ye}from"path";import{execSync as Ko}from"child_process";import{DEFAULT_OUTPUT_BASE as Je}from"@zibby/core";function me(t){return t?.paths?.output||Je}function te(t,o,s){return ye(t,o,`.zibby-chat-run-pids-${s}.json`)}function Ie(t,o,s){let c=te(t,o,s);if(!ge(c))return[];try{let l=JSON.parse(Ve(c,"utf8"));return(Array.isArray(l?.pids)?l.pids:[]).map(n=>Number(n)).filter(n=>Number.isFinite(n)&&n>0)}catch{return[]}}function we(t,o,s,c={}){let l=Number(o),r=Number(s);if(!Number.isFinite(l)||l<=0||!Number.isFinite(r)||r<=0)return;let n=me(c),d=ye(t,n);We(d,{recursive:!0});let u=Ie(t,n,l);u.includes(r)||u.push(r),he(te(t,n,l),`${JSON.stringify({v:1,pids:u})}
|
|
2
|
+
`,"utf8")}function ve(t,o,s,c={}){let l=Number(o),r=Number(s);if(!Number.isFinite(l)||l<=0||!Number.isFinite(r)||r<=0)return;let n=me(c),d=te(t,n,l);if(!ge(d))return;let u=Ie(t,n,l).filter(p=>p!==r);if(u.length===0)try{qe(d)}catch{}else he(d,`${JSON.stringify({v:1,pids:u})}
|
|
3
|
+
`,"utf8")}import{readFileSync as T,existsSync as v,statSync as Ce,mkdirSync as Oe,writeFileSync as $e,appendFileSync as yo,rmSync as ke}from"fs";import{resolve as B,join as N,dirname as mo,isAbsolute as Be}from"path";import{fileURLToPath as Io}from"url";import{glob as X}from"glob";import e from"chalk";import Re from"ora";import wo from"dotenv";import vo from"open";var S={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 q(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";S[o]?t=S[o].apiUrl:t=S.prod.apiUrl}try{let o=new URL(t);return o.protocol!=="http:"&&o.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${o.protocol} (only http/https allowed)`),S.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),S.prod.apiUrl}}function _e(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let t=process.env.ZIBBY_ENV||"prod";return(S[t]||S.prod).accountApiUrl}function ne(){let t=process.env.ZIBBY_ENV||"prod";return S[t]||S.prod}function se(){let t;if(process.env.ZIBBY_FRONTEND_URL)t=process.env.ZIBBY_FRONTEND_URL;else{let o=process.env.ZIBBY_ENV||"prod";S[o]?t=S[o].frontendUrl:t=S.prod.frontendUrl}try{let o=new URL(t);if(o.protocol!=="http:"&&o.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${o.protocol} (only http/https allowed)`),S.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let c=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],l=o.hostname;if(!c.some(n=>l===n||l.endsWith(`.${n}`))&&!l.includes("localhost")&&l!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${l}`),"https://studio.zibby.dev"}return t}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${t}`),S.local.frontendUrl}}import{existsSync as Xe,mkdirSync as Ho,readFileSync as Qe,writeFileSync as Wo}from"fs";import{homedir as xe}from"os";import{join as J}from"path";function eo(){return process.env.ZIBBY_CONFIG_DIR||J(xe(),".zibby")}function oo(){return J(eo(),"config.json")}var to=J(xe(),".zibby"),Jo=J(to,"config.json");function Pe(){try{let t=oo();if(Xe(t)){let o=Qe(t,"utf-8");return JSON.parse(o)}}catch{}return{}}function re(){return Pe().sessionToken||null}function ie(){return Pe().user||null}var _o=Io(import.meta.url),xo=mo(_o),Po=JSON.parse(T(N(xo,"../../package.json"),"utf-8"));function Eo(t){let o=s=>s?typeof s.message=="string"&&s.message.includes("Interrupted by user")?!0:Array.isArray(s.errors)?s.errors.some(o):s.cause?o(s.cause):!1:!1;return o(t)}function Ne(t,o){if(t==null)return null;let s=String(t).trim();return s?Be(s)?s:B(o,s):null}function bo(t,o){try{if(!t||!v(t))return;let s=N(t,"studio-cli.log"),c=`
|
|
4
4
|
[CLI_FATAL] ${new Date().toISOString()}
|
|
5
5
|
Error: ${String(o?.message||o)}
|
|
6
6
|
${o?.stack?`${String(o.stack)}
|
|
7
|
-
`:""}`;
|
|
7
|
+
`:""}`;yo(s,c,"utf8")}catch{}}process.env.DOTENV_CONFIG_QUIET="true";var Ao=process.env.NODE_ENV||"development",So=[B(process.cwd(),".env.local"),B(process.cwd(),`.env.${Ao}`),B(process.cwd(),".env")];So.forEach(t=>{v(t)&&wo.config({path:t,override:!1})});function To(t,o){let s=o?.paths?.specs||"test-specs",c=o?.paths?.generated||"tests";return t.replace(s,c).replace(/\.txt$/,".spec.js")}async function Uo(t,o){let s=se(),c=/^[0-9A-HJKMNP-TV-Z]{26}$/,l=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(!c.test(t)&&!l.test(t))return console.log(e.red(`
|
|
8
8
|
\u274C Invalid execution ID format (security check)
|
|
9
|
-
`)),!1;if(!
|
|
9
|
+
`)),!1;if(!l.test(o))return console.log(e.red(`
|
|
10
10
|
\u274C Invalid project ID format (security check)
|
|
11
|
-
`)),!1;let
|
|
11
|
+
`)),!1;let r=new URL(s);if(!s.includes("localhost")&&!s.includes("127.0.0.1")&&r.protocol!=="https:")return console.log(e.red(`
|
|
12
12
|
\u274C Frontend URL must use HTTPS in production
|
|
13
|
-
`)),!1;let
|
|
14
|
-
Opening test results in browser...`)),console.log(e.gray(` ${
|
|
15
|
-
`)),await
|
|
16
|
-
`)),!1}}function
|
|
17
|
-
${
|
|
13
|
+
`)),!1;let d=`${s}/projects/${o}/runs/${t}`;try{return console.log(e.cyan(`
|
|
14
|
+
Opening test results in browser...`)),console.log(e.gray(` ${d}
|
|
15
|
+
`)),await vo(d),!0}catch{return console.log(e.yellow("Could not open browser automatically")),console.log(e.gray(` Please open manually: ${d}
|
|
16
|
+
`)),!1}}function ce(t,o){let s=o?.paths?.specs||"test-specs",c=o?.paths?.generated||"tests";return t.replace(c,s).replace(/\.spec\.js$/,".txt")}async function Co({apiKey:t,specPath:o,fullSpecPath:s,collectionIdOrName:c,folder:l,agent:r,config:n,result:d,shouldOpen:u}){let p=q(),A=ne(),m=process.env.ZIBBY_USER_TOKEN||re(),L=ie();console.log(L?e.gray(`Authenticated: ${L.email} (${L.name||"User"})`):e.gray("Authenticated: Using Personal Access Token"));let _=Re(`Uploading to ${A.name}...`).start();try{let h=process.cwd(),U=null;if(d?.state?.sessionPath){let a=d.state.sessionPath;U=a.startsWith(h)?a.slice(h.length+1):a}if(!U){let y=`${n.paths?.output||fo}/${go}/*`,k=X.sync(y,{cwd:h}).filter($=>Ce(N(h,$)).isDirectory()&&!/session_/.test($)).map($=>({path:$,stat:Ce(N(h,$))})).sort(($,de)=>de.stat.mtimeMs-$.stat.mtimeMs);if(k.length===0){_.warn("No session folder found, skipping upload");return}U=k[0].path}let O=X.sync(`${U}/execute_live/videos/*.webm`,{cwd:h});O.length===0&&(O=X.sync(`${U}/execute_live/*.webm`,{cwd:h})),O.length===0&&(O=X.sync(`${U}/*.webm`,{cwd:h}));let j=N(h,U,"execute_live","events.json"),K=N(h,U,"execute_live","result.json"),D=N(h,U,"title.txt"),W=To(o,n),i=N(h,W),f=v(i);if(O.length===0){_.warn("No video file found in session folder, skipping upload");return}let I=N(h,O[0]),E=v(D)?T(D,"utf-8").trim():null;C.debug(`Video exists: ${v(I)}`),C.debug(`Events exists: ${v(j)}`);let x=null,Y=null;if(c){_.text="Resolving collection...";let a=_e(),y=await fetch(`${a}/collections/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({collectionIdOrName:c})});if(!y.ok){let $=await y.json().catch(()=>({}));throw new Error($.error||"Failed to resolve collection")}let k=await y.json();x=k.collectionId,Y=k.collectionName,k.isNew&&(_.text=`Created new collection: ${Y}`)}_.text="Preparing upload...";let w={video:v(I)?T(I).length:0,events:v(j)?T(j).length:0,instructions:(()=>{let a=ce(o,n),y=N(h,a);return v(y)?T(y).length:0})(),result:v(K)?T(K).length:0},b=w.video+w.events+w.instructions+w.result,V=(b/1024/1024).toFixed(2);if(w.video>50*1024*1024)throw new Error(`Video file too large: ${(w.video/1024/1024).toFixed(2)}MB (max: 50MB)`);if(b>60*1024*1024)throw new Error(`Total upload size too large: ${V}MB (max: 60MB)`);_.text=`Getting upload URLs... (${V}MB)`;let g={"Content-Type":"application/json",Authorization:`Bearer ${t}`};m&&(g["X-User-Token"]=m);let P=typeof r=="object"?r.provider:r||"cursor",M=typeof r=="object"&&r[P]?.model||null,Le=M==="auto"?null:M,Z=await fetch(`${p}/executions/upload`,{method:"POST",headers:g,body:JSON.stringify({collectionId:x||null,specPath:o,specContent:(()=>{let a=ce(o,n),y=N(h,a);return v(y)?T(y,"utf-8"):v(s)?T(s,"utf-8"):""})(),title:E||null,agentType:P,model:Le,metadata:{agent:r||"cursor",timestamp:new Date().toISOString(),folder:l||null,collectionName:Y||null},fileSizes:w})});if(!Z.ok){let a=await Z.json();if(Z.status===413)throw a.details&&Array.isArray(a.details)?new Error(`File size limit exceeded:
|
|
17
|
+
${a.details.map(y=>` \u2022 ${y}`).join(`
|
|
18
18
|
`)}
|
|
19
19
|
|
|
20
|
-
Compress your files or reduce recording quality.`):new Error(
|
|
21
|
-
Plan: ${
|
|
22
|
-
Upgrade at: https://studio.zibby.
|
|
23
|
-
Current usage: ${
|
|
24
|
-
This upload: ${
|
|
25
|
-
Plan: ${
|
|
26
|
-
Upgrade at: https://studio.zibby.
|
|
27
|
-
${"\u2501".repeat(50)}`)),console.log(e.white(`Execution ID: ${e.cyan(
|
|
28
|
-
`)),{success:!0,executionId:
|
|
29
|
-
`)),{success:!1}}}async function
|
|
20
|
+
Compress your files or reduce recording quality.`):new Error(a.error||"Upload files too large");if(Z.status===429){if(a.quotaInfo)throw new Error(`Video verification quota exceeded (${a.quotaInfo.used}/${a.quotaInfo.limit}).
|
|
21
|
+
Plan: ${a.quotaInfo.planId}. Resets: ${new Date(a.quotaInfo.periodEnd).toLocaleDateString()}
|
|
22
|
+
Upgrade at: https://studio.zibby.dev/billing`);if(a.storageInfo){let y=(a.storageInfo.used/1073741824).toFixed(2),k=(a.storageInfo.limit/(1024*1024*1024)).toFixed(2),$=(a.storageInfo.uploadSize/(1024*1024)).toFixed(2);throw new Error(`Storage quota would be exceeded.
|
|
23
|
+
Current usage: ${y}GB / ${k}GB
|
|
24
|
+
This upload: ${$}MB
|
|
25
|
+
Plan: ${a.storageInfo.planId}
|
|
26
|
+
Upgrade at: https://studio.zibby.dev/billing`)}}throw new Error(a.error||"Failed to initiate upload")}let{executionId:z,uploadUrls:R,isOrphan:je,projectId:Q}=await Z.json();_.text=`Uploading video... (${z})`;let ee=T(I);C.debug(`Video buffer size: ${ee.length} bytes`),C.debug("Upload URL received (redacted)");let G=await fetch(R.video,{method:"PUT",body:ee,headers:{"Content-Type":"video/webm","Content-Length":ee.length.toString()}});if(C.debug(`Video upload status: ${G.status} ${G.statusText}`),!G.ok){let a=await G.text();throw new Error(`Failed to upload video: ${G.status} ${G.statusText} - ${a}`)}if(C.info("Video uploaded successfully"),v(j)&&R.events){_.text="Uploading events...";let a=T(j),y=await fetch(R.events,{method:"PUT",body:a,headers:{"Content-Type":"application/json","Content-Length":a.length.toString()}});if(C.debug(`Events upload status: ${y.status} ${y.statusText}`),!y.ok)throw new Error("Failed to upload events");C.info("Events uploaded successfully")}else C.debug(`Skipping events upload - exists: ${v(j)}, hasUrl: ${!!R.events}`);if(f&&R.generatedTest){_.text="Uploading generated test...";let a=T(i);if(!(await fetch(R.generatedTest,{method:"PUT",body:a,headers:{"Content-Type":"application/javascript","Content-Length":a.length.toString()}})).ok)throw new Error("Failed to upload generated test")}if(R.testInstructions){let a=ce(o,n),y=N(h,a);if(v(y)){_.text="Uploading test instructions...";let k=T(y);(await fetch(R.testInstructions,{method:"PUT",body:k,headers:{"Content-Type":"text/plain","Content-Length":k.length.toString()}})).ok?C.debug("Test instructions uploaded successfully"):C.warn("Failed to upload test instructions (non-blocking)")}else console.log(`\u2139\uFE0F No source test instructions found at ${a}`)}if(R.result&&v(K)){_.text="Uploading test results...";let a=T(K);(await fetch(R.result,{method:"PUT",body:a,headers:{"Content-Type":"application/json","Content-Length":a.length.toString()}})).ok?C.debug("result.json uploaded successfully"):C.warn("Failed to upload result.json (non-blocking)")}if(_.text="Confirming upload...",!(await fetch(`${p}/executions/${z}/confirm`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({status:"completed",metadata:{uploadedAt:new Date().toISOString()},fileSizes:w})})).ok)throw new Error("Failed to confirm upload");_.succeed("Uploaded to Zibby Cloud!"),console.log(e.gray(`
|
|
27
|
+
${"\u2501".repeat(50)}`)),console.log(e.white(`Execution ID: ${e.cyan(z)}`));let ue=se();console.log(je?e.white(`Location: ${e.yellow("History tab")}`):e.white(`Collection: ${e.cyan(x)}`));let Ye=Q?`${ue}/projects/${Q}/runs/${z}`:`${ue}/history?execution=${z}`;return console.log(e.white(`View execution: ${e.cyan(Ye)}`)),console.log(e.gray(`${"\u2501".repeat(50)}
|
|
28
|
+
`)),{success:!0,executionId:z,projectId:Q||null}}catch(h){return _.fail("Upload failed"),console.log(e.red(` ${h.message}`)),process.env.DEBUG&&console.log(e.gray(` Stack: ${h.stack}`)),console.log(e.gray(` Continuing without upload...
|
|
29
|
+
`)),{success:!1}}}async function Oo(t,o,s){let c=q(),l=o.join(","),r=await fetch(`${c}/executions/${t}/test-cases?ids=${l}`,{headers:{Authorization:`Bearer ${s}`}});if(!r.ok)throw new Error(`Failed to fetch test cases: ${r.status} ${r.statusText}`);return(await r.json()).testCases||[]}async function $o(t,o){let s=ne();console.log(e.bold.cyan(`
|
|
30
30
|
Zibby Test Automation
|
|
31
|
-
`)),console.log(e.gray(`@zibby/cli v${
|
|
31
|
+
`)),console.log(e.gray(`@zibby/cli v${Po.version} | Node.js ${process.version}`)),console.log(e.gray("\u2501".repeat(50)));try{let{loadCredentialsIntoEnv:i}=await Promise.resolve().then(()=>(Te(),Se));await i({verbose:!!process.env.ZIBBY_DEBUG})}catch{}if(o.sources){o.execution||(console.log(e.red(`
|
|
32
32
|
\u274C --execution <id> is required when using --sources
|
|
33
|
-
`)),process.exit(1));let
|
|
33
|
+
`)),process.exit(1));let i=o.project||process.env.ZIBBY_API_KEY;i||(console.log(e.red(`
|
|
34
34
|
\u274C --project <id> or ZIBBY_API_KEY required when using --sources
|
|
35
|
-
`)),process.exit(1));let
|
|
35
|
+
`)),process.exit(1));let f=o.sources.split(",").map(x=>x.trim());console.log(e.white(`Fetching ${f.length} test case(s) from execution ${e.cyan(o.execution)}...`));let I=await Oo(o.execution,f,i);I.length===0&&(console.log(e.red(`
|
|
36
36
|
No test cases found for the given IDs
|
|
37
|
-
`)),process.exit(1)),console.log(e.green(`\u2713 Fetched ${
|
|
37
|
+
`)),process.exit(1)),console.log(e.green(`\u2713 Fetched ${I.length} test case(s)`));let E=ae(process.cwd());Oe(E,{recursive:!0});for(let x of I){let Y=`# ${x.title}
|
|
38
38
|
|
|
39
|
-
${
|
|
40
|
-
Running: ${e.cyan(
|
|
39
|
+
${x.content}`,w=B(E,`${x.id}.txt`);$e(w,Y,"utf-8"),console.log(e.gray("\u2501".repeat(50))),console.log(e.white(`
|
|
40
|
+
Running: ${e.cyan(x.title)} (${x.id})`));let b={...o,sources:void 0,execution:void 0};b.sync=!0,await $o(w,b)}ke(E,{recursive:!0,force:!0});return}!t&&!o.sources&&(console.log(e.red(`
|
|
41
41
|
\u274C Missing test spec path
|
|
42
42
|
`)),console.log(e.white("Usage:")),console.log(e.gray(" zibby test test-specs/login.txt Run a spec file")),console.log(e.gray(` zibby test "login and check dashboard" Run inline spec
|
|
43
|
-
`)),process.exit(1));let
|
|
43
|
+
`)),process.exit(1));let c=t&&!t.endsWith(".txt")&&!v(B(process.cwd(),t))&&t.includes(" ");if(c){let i=ae(process.cwd());Oe(i,{recursive:!0});let f=B(i,`inline-${Date.now()}.txt`);$e(f,t,"utf-8"),t=f}let l=B(process.cwd(),t);v(l)||(console.log(e.red(`
|
|
44
44
|
\u274C Test spec not found: ${t}
|
|
45
|
-
`)),process.exit(1));let
|
|
45
|
+
`)),process.exit(1));let r=T(l,"utf-8"),n={headless:o.headless||!1,playwrightArtifacts:!0},d=B(process.cwd(),o.config);if(v(d))try{let i=await import(d),f=I=>I?.provider?I.provider:I?.gemini?"gemini":I?.codex?"codex":I?.claude?"claude":I?.cursor?"cursor":null;n={...n,...i.default,agent:i.default?.agent?{...i.default.agent,provider:o.agent||f(i.default.agent)}:{provider:o.agent||"cursor"},mcp:i.default?.browser?.mcp||"playwright",headless:o.headless!==void 0?o.headless:i.default?.browser?.headless,paths:i.default?.paths||{specs:"test-specs",generated:"tests"},cloudSync:i.default?.cloudSync||!1}}catch{console.log(e.yellow(`\u26A0\uFE0F Could not load config from ${o.config}`)),n.agent={provider:o.agent||"cursor"},n.cloudSync=!1}else n.agent={provider:o.agent||"cursor"},n.cloudSync=!1;let u=process.env.ZIBBY_API_KEY,p=o.sync||n.cloudSync===!0&&o.sync!==!1;if(o.project&&o.project.startsWith("zby_")&&(u=o.project,console.log(e.gray("Using --project as API token (overriding .env)"))),p&&!u&&(console.log(e.red(`
|
|
46
46
|
\u274C Error: Cloud sync is enabled but ZIBBY_API_KEY not set
|
|
47
47
|
`)),console.log(e.white("Cloud sync is enabled in .zibby.config.js")),console.log(e.white(`You need to set ZIBBY_API_KEY in .env file
|
|
48
48
|
`)),console.log(e.white("Option 1: Add to .env file:")),console.log(e.gray(` ZIBBY_API_KEY=zby_your_key_here
|
|
49
49
|
`)),console.log(e.white("Option 2: Disable cloud sync:")),console.log(e.gray(` Edit .zibby.config.js \u2192 cloudSync: false
|
|
50
50
|
`)),console.log(e.white(`Get your API key from: https://zibby.dev/dashboard
|
|
51
|
-
`)),process.exit(1)),
|
|
51
|
+
`)),process.exit(1)),p&&u){let i=process.env.ZIBBY_USER_TOKEN,f;i?console.log(e.gray("Using Personal Access Token from ZIBBY_USER_TOKEN")):(i=re(),f=ie(),(!i||!f)&&(console.log(e.red(`
|
|
52
52
|
\u274C Error: User authentication required for uploads
|
|
53
53
|
`)),console.log(e.gray(`Choose one of these options:
|
|
54
54
|
`)),console.log(e.cyan(" Option 1 (Local Development):")),console.log(e.gray(` zibby login
|
|
55
|
-
`)),console.log(e.cyan(" Option 2 (CI/CD):")),console.log(e.gray(" 1. Generate a Personal Access Token at:")),console.log(e.gray(" https://zibby.
|
|
56
|
-
`)),process.exit(1)),
|
|
55
|
+
`)),console.log(e.cyan(" Option 2 (CI/CD):")),console.log(e.gray(" 1. Generate a Personal Access Token at:")),console.log(e.gray(" https://zibby.dev/settings/tokens")),console.log(e.gray(" 2. Set environment variable:")),console.log(e.gray(` export ZIBBY_USER_TOKEN=zby_pat_xxxxx
|
|
56
|
+
`)),process.exit(1)),f&&console.log(e.gray(`Authenticated: ${f.email} (${f.name||"User"})`)))}if(p&&u){let i=q();try{u.startsWith("zby_")||(console.log(e.red(`
|
|
57
57
|
\u274C Invalid API token format
|
|
58
58
|
`)),console.log(e.white('This CLI requires a project API token (starts with "zby_").')),console.log(e.gray(` Format: zby_***
|
|
59
59
|
`)),console.log(e.white(`Get your project API token from settings:
|
|
60
|
-
`)),console.log(e.gray(" Local: http://localhost:3001/settings")),console.log(e.gray(` Prod: https://
|
|
61
|
-
`)),process.exit(1));let
|
|
60
|
+
`)),console.log(e.gray(" Local: http://localhost:3001/settings")),console.log(e.gray(` Prod: https://studio.zibby.dev/settings
|
|
61
|
+
`)),process.exit(1));let f=await fetch(`${i}/projects`,{headers:{Authorization:`Bearer ${u}`}});f.ok||(console.log(e.red(`
|
|
62
62
|
\u274C Unauthorized: Invalid project API token
|
|
63
63
|
`)),console.log(e.white("Your project API token is invalid or does not have access.")),console.log(e.gray(` Token format: zby_***
|
|
64
64
|
`)),console.log(e.white(`Get your project API token from settings:
|
|
65
|
-
`)),console.log(e.gray(" Local: http://localhost:3001/settings")),console.log(e.gray(` Prod: https://
|
|
66
|
-
`)),process.exit(1));let
|
|
65
|
+
`)),console.log(e.gray(" Local: http://localhost:3001/settings")),console.log(e.gray(` Prod: https://studio.zibby.dev/settings
|
|
66
|
+
`)),process.exit(1));let E=(await f.json()).projects||[];(!E||E.length===0)&&(console.log(e.red(`
|
|
67
67
|
\u274C No projects found for this token
|
|
68
|
-
`)),process.exit(1));let
|
|
69
|
-
\u274C Failed to validate API credentials: ${
|
|
70
|
-
`)),process.exit(1)}}let
|
|
68
|
+
`)),process.exit(1));let x=E[0];console.log(e.green(`\u2713 Authorized for project: ${x.name} (${x.projectId})`))}catch(f){console.log(e.red(`
|
|
69
|
+
\u274C Failed to validate API credentials: ${f.message}
|
|
70
|
+
`)),process.exit(1)}}let A=typeof n.agent=="object"?n.agent.provider:n.agent;if(A==="claude"&&!process.env.ANTHROPIC_API_KEY&&(console.log(e.red(`
|
|
71
71
|
\u274C Error: ANTHROPIC_API_KEY not set
|
|
72
72
|
`)),console.log(e.white("Set your API key:")),console.log(e.gray(` export ANTHROPIC_API_KEY="sk-ant-..."
|
|
73
73
|
`)),console.log(e.white("Or add to .env file:")),console.log(e.gray(` ANTHROPIC_API_KEY=sk-ant-...
|
|
74
74
|
`)),console.log(e.white(`Get your API key from: https://console.anthropic.com/
|
|
75
|
-
`)),process.exit(1)),
|
|
75
|
+
`)),process.exit(1)),A==="codex"){try{let{execSync:i}=await import("child_process");i("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"})}catch{console.log(e.red(`
|
|
76
76
|
\u274C Error: Codex CLI not installed
|
|
77
77
|
`)),console.log(e.white("Install the Codex CLI:")),console.log(e.gray(` npm install -g @openai/codex
|
|
78
78
|
`)),console.log(e.white("Then verify:")),console.log(e.gray(` codex --version
|
|
@@ -81,7 +81,7 @@ Running: ${e.cyan(w.title)} (${w.id})`));let P={...o,sources:void 0,execution:vo
|
|
|
81
81
|
`)),console.log(e.white("Set your API key:")),console.log(e.gray(` export OPENAI_API_KEY="sk-..."
|
|
82
82
|
`)),console.log(e.white("Or add to .env file:")),console.log(e.gray(` OPENAI_API_KEY=sk-...
|
|
83
83
|
`)),console.log(e.white(`Get your API key from: https://platform.openai.com/api-keys
|
|
84
|
-
`)),process.exit(1))}if(
|
|
84
|
+
`)),process.exit(1))}if(A==="gemini"){if(process.env.GEMINI_API_KEY&&process.env.GOOGLE_API_KEY){let i=String(process.env.GEMINI_API_KEY).trim(),f=String(process.env.GOOGLE_API_KEY).trim();i&&f&&i!==f&&(process.env.GOOGLE_API_KEY=i,console.log(e.yellow("\u26A0\uFE0F Both GOOGLE_API_KEY and GEMINI_API_KEY are set; forcing GOOGLE_API_KEY to GEMINI_API_KEY for this run.")))}try{let{execSync:i}=await import("child_process");i("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"})}catch{console.log(e.red(`
|
|
85
85
|
\u274C Error: Gemini CLI not installed
|
|
86
86
|
`)),console.log(e.white("Install the Gemini CLI:")),console.log(e.gray(` npm install -g @google/gemini-cli
|
|
87
87
|
`)),console.log(e.white("Then verify:")),console.log(e.gray(` gemini --version
|
|
@@ -90,25 +90,25 @@ Running: ${e.cyan(w.title)} (${w.id})`));let P={...o,sources:void 0,execution:vo
|
|
|
90
90
|
`)),console.log(e.white("Set your API key:")),console.log(e.gray(` export GEMINI_API_KEY="your_key_here"
|
|
91
91
|
`)),console.log(e.white("Or add to .env file:")),console.log(e.gray(` GEMINI_API_KEY=your_key_here
|
|
92
92
|
`)),console.log(e.white(`Get your API key from: https://aistudio.google.com/app/apikey
|
|
93
|
-
`)),process.exit(1))}if(
|
|
93
|
+
`)),process.exit(1))}if(A==="cursor"){let{checkCursorAgentInstalled:i,getCursorAgentInstallInstructions:f}=await import("@zibby/core");await i()||(console.log(e.red(f())),process.exit(1));let E=process.env.CI||process.env.GITLAB_CI||process.env.CIRCLECI||process.env.GITHUB_ACTIONS;process.env.CURSOR_API_KEY||(E?(console.log(e.red(`
|
|
94
94
|
\u274C Error: CURSOR_API_KEY not set
|
|
95
95
|
`)),console.log(e.white("In CI/CD, you must provide your Cursor API key:")),console.log(e.gray(` export CURSOR_API_KEY="your-cursor-token-here"
|
|
96
96
|
`)),console.log(e.white(`Get your API key from: https://cursor.com/settings
|
|
97
97
|
`)),console.log(e.white(`Add it to your CI/CD environment variables.
|
|
98
98
|
`)),process.exit(1)):console.log(e.yellow(`\u26A0\uFE0F CURSOR_API_KEY not set (using locally stored Cursor credentials)
|
|
99
|
-
`)))}console.log(e.white(`Test Spec: ${e.cyan(t)}`));let
|
|
100
|
-
${"\u2501".repeat(50)}`)),V&&
|
|
101
|
-
`)),console.log(e.cyan("Next steps:")),console.log(e.white(` 1. Review generated test: ${
|
|
102
|
-
`));else{let
|
|
103
|
-
Execution Summary:`)),console.log(e.white(` Steps: ${
|
|
104
|
-
\u{1F4DD} ${
|
|
105
|
-
\u26A0\uFE0F ${
|
|
99
|
+
`)))}console.log(e.white(`Test Spec: ${e.cyan(t)}`));let m=typeof n.agent=="object"?n.agent.provider:n.agent;console.log(e.white(`Agent: ${e.cyan(m)}`)),console.log(e.white(`Browser: ${e.cyan(n.mcp||"playwright")} ${n.headless?e.gray("(headless)"):e.gray("(headed)")}`)),n.cloudSync&&console.log(e.white(`Cloud Sync: ${e.green("enabled")}`)),o.autoApprove&&console.log(e.white(`Auto-approve: ${e.yellow("enabled (CI/CD mode)")}`)),o.collection?console.log(e.white(`Collection: ${e.cyan(o.collection)}${o.folder?` / ${o.folder}`:""}`)):console.log(e.gray("Mode: Orphan execution (History tab)"));let L;if(o.sessionPath!=null&&String(o.sessionPath).trim()!==""){let i=String(o.sessionPath).trim();L=Be(i)?B(i):B(process.cwd(),i),console.log(e.white(`Session path: ${e.cyan(L)}`))}console.log(e.gray("\u2501".repeat(50)));let _=Re({text:"Initializing...",stream:process.stdout}).start(),h=()=>{try{Ue({cwd:process.cwd(),config:n})}catch{}},U=process.env.ZIBBY_CHAT_OWNER_PID,O=U!=null&&String(U).trim()!==""?Number(U):null,j=O!=null&&Number.isFinite(O)&&O>0,K=()=>{if(j)try{ve(process.cwd(),O,process.pid,n)}catch{}},D=null,W=Ne(L,process.cwd());try{_.stop();let{waitUntilRunCapacity:i}=await import("@zibby/core/utils/run-capacity-coordinator.js"),{basename:f}=await import("path");await i({cwd:process.cwd(),config:n,meta:{source:process.env.ZIBBY_RUN_SOURCE||"cli",specHint:t?f(t):"",studioTestCaseId:process.env.ZIBBY_STUDIO_TEST_CASE_ID||null},log:g=>console.log(e.gray(g))});let I=await import("@zibby/core/templates/browser-test-automation/graph.mjs").catch(()=>null);if(j)try{we(process.cwd(),O,process.pid,n)}catch{}process.on("SIGINT",h),process.on("SIGTERM",h);let E=process.cwd(),x={},Y=g=>{let P=Ne(g?.sessionPath,E);P&&(W=P)};if(typeof n.onPipelineProgress=="function"){let g=oe(n.onPipelineProgress,E,n);D=()=>g.dispose(),x.onPipelineProgress=P=>{Y(P),g({...P,specPath:t,taskDescription:r})}}else if(n.runIndex?.pipelineProgress!==!1){let g=ho({cwd:E,config:n}),P=oe(g,E,n);D=()=>P.dispose(),x.onPipelineProgress=M=>{Y(M),P({...M,specPath:t,taskDescription:r})}}let w=await po(l,{...n,...x,specPath:t,apiKey:process.env.ANTHROPIC_API_KEY,autoApprove:o.autoApprove,force:o.autoApprove,singleNode:o.node,sessionId:o.session,...L?{sessionPath:L}:{},workflow:o.workflow,contextConfig:n.context,fallbackAgentModule:I}),b=w.outputPath||null;b&&(b=b.replace(/\/+/g,"/"),b.includes(process.cwd())&&(b=b.replace(`${process.cwd()}/`,"")));let V=w.state?.generate_script?.scriptPath||w.state?.verify_script?.success;if(console.log(e.gray(`
|
|
100
|
+
${"\u2501".repeat(50)}`)),V&&b)console.log(e.green("\u2713 Test execution completed")),console.log(e.white(`Generated test: ${e.cyan(b)}`)),w.toolCount!==void 0&&console.log(e.white(`Tools used: ${e.cyan(w.toolCount)}`)),console.log(e.gray(`${"\u2501".repeat(50)}
|
|
101
|
+
`)),console.log(e.cyan("Next steps:")),console.log(e.white(` 1. Review generated test: ${b}`)),console.log(e.white(` 2. Run with Playwright: npx playwright test ${b}`)),console.log(e.white(` 3. View report: npx playwright show-report
|
|
102
|
+
`));else{let g=w.state?.execute_live;g?g.steps?.length>0||g.actions?.length>0?(console.log(e.white(`
|
|
103
|
+
Execution Summary:`)),console.log(e.white(` Steps: ${g.steps?.length||0}`)),console.log(e.white(` Actions: ${g.actions?.length||0}`)),g.finalUrl&&console.log(e.white(` Final URL: ${g.finalUrl}`)),g.notes&&console.log(e.white(`
|
|
104
|
+
\u{1F4DD} ${g.notes}`))):(console.log(e.red("\u2716 Workflow did not complete")),console.log(e.yellow(`
|
|
105
|
+
\u26A0\uFE0F ${g.notes||"Test execution failed"}`))):console.log(e.red("\u2716 Workflow did not complete")),console.log(e.gray(`${"\u2501".repeat(50)}
|
|
106
106
|
`))}if(o.node)console.log(e.gray(`
|
|
107
107
|
Note: Upload skipped for single node execution`)),console.log(e.gray(` Run full workflow to upload all artifacts
|
|
108
|
-
`));else if(
|
|
108
|
+
`));else if(p){let g=o.project||process.env.ZIBBY_API_KEY;if(!g)console.log(e.yellow(`
|
|
109
109
|
Cloud sync enabled but no API key provided`)),console.log(e.gray(" Option 1: Use --project flag: --project zby_xxx")),console.log(e.gray(` Option 2: Add to .env: ZIBBY_API_KEY=zby_xxx
|
|
110
|
-
`));else{let
|
|
110
|
+
`));else{let P=await Co({apiKey:g,specPath:t,fullSpecPath:l,projectId:null,collectionIdOrName:o.collection||null,folder:o.folder,agent:n.agent,config:n,result:w,shouldOpen:o.open});o.open&&P?.success&&P.executionId&&P.projectId&&await Uo(P.executionId,P.projectId)}}}catch(i){if(_.isSpinning&&_.stop(),console.log(e.red(`
|
|
111
111
|
\u2716 Test failed
|
|
112
|
-
`)),
|
|
113
|
-
`));try{
|
|
114
|
-
`)),
|
|
112
|
+
`)),Eo(i)){console.log(e.yellow(`Test execution was interrupted
|
|
113
|
+
`));try{Ue({cwd:process.cwd(),config:n})}catch{}le(c),process.exit(130)}bo(W,i),console.log(e.red(`Error: ${i.message}
|
|
114
|
+
`)),i.stack&&console.log(e.gray(i.stack)),le(c),process.exit(1)}finally{typeof D=="function"&&D(),K(),process.off("SIGINT",h),process.off("SIGTERM",h)}le(c)}function le(t){if(t)try{ke(ae(process.cwd()),{recursive:!0,force:!0})}catch{}}export{$o as runCommand};
|
package/dist/commands/studio.js
CHANGED
|
@@ -5,9 +5,9 @@ var fe=Object.defineProperty;var me=(a,r)=>()=>(a&&(r=a(a=0)),r);var ge=(a,r)=>{
|
|
|
5
5
|
\u{1F4E6} Downloading Zibby Studio...`));try{let p=await fetch(a);if(!p.ok)throw new Error(`Download failed: ${p.status} ${p.statusText}`);let S=parseInt(p.headers.get("content-length")||"0",10),w=$.join(U.tmpdir(),r),h=0,_=Se(w);for await(let E of p.body)if(h+=E.length,_.write(E),S>0){let F=(h/S*100).toFixed(1),k=(h/1024/1024).toFixed(1),Y=(S/1024/1024).toFixed(1);process.stdout.write(`\r \u{1F4E5} ${F}% (${k}MB / ${Y}MB)`)}if(await new Promise((E,F)=>{_.on("finish",E),_.on("error",F),_.end()}),console.log(""),tt(O)&&Ie(O,{recursive:!0,force:!0}),be(O,{recursive:!0}),console.log(C.cyan(" \u{1F4C2} Installing...")),w.endsWith(".zip"))if(U.platform()==="darwin"||U.platform()==="linux"){if(Ut("unzip",["-oq",w,"-d",O]),U.platform()==="darwin")try{Ut("xattr",["-cr",O])}catch{}}else{let E=(await import("adm-zip")).default;new E(w).extractAllTo(O,!0)}else if(w.endsWith(".AppImage")){let{copyFileSync:E,chmodSync:F}=await import("fs"),k=$.join(O,r);E(w,k),F(k,493)}try{we(w)}catch{}return console.log(C.green(` \u2705 Zibby Studio installed!
|
|
6
6
|
`)),!0}catch(p){throw console.log(C.red(`
|
|
7
7
|
\u274C Installation failed: ${p.message}
|
|
8
|
-
`)),p}}function et(){let a=ot();return!!(a&&tt(a))}function ot(){if(U.platform()==="darwin")return $.join(O,"Zibby Studio.app");if(U.platform()==="win32")return $.join(O,"Zibby Studio.exe");if(U.platform()==="linux"){if(!tt(O))return null;let a=ye(O).find(r=>r.endsWith(".AppImage"));return a?$.join(O,a):null}return null}function Ae(){let a=$.join(O,"version.txt");return tt(a)?he(a,"utf-8").trim():"unknown"}var Pe,O,nt=me(()=>{Pe=process.env.ZIBBY_STUDIO_CDN||"https://dl.zibby.app",O=$.join(U.homedir(),".zibby","studio")});nt();import Gt from"express";import{createServer as ke}from"http";import{WebSocketServer as Ee}from"ws";import{spawn as ht,execSync as rt}from"child_process";import{readFileSync as x,existsSync as f,readdirSync as W,statSync as Z,createReadStream as Ue,createWriteStream as Be,mkdirSync as Wt,openSync as Le,readSync as Ce,closeSync as $e,writeFileSync as st,unlinkSync as Fe}from"fs";import{join as u,resolve as B,dirname as yt,basename as ze}from"path";import{homedir as De}from"os";import{inspect as Ze}from"util";import{fileURLToPath as Ye,pathToFileURL as Mt}from"url";import Ge from"dotenv";nt();import{spawn as Dt,execFileSync as $t}from"child_process";import mt from"os";import Zt from"path";import{existsSync as Ne,mkdirSync as Te,writeFileSync as Re}from"fs";var Ft=Zt.join(mt.homedir(),".zibby","studio-launch.json");function Oe(a){let r={};a.projectRoot&&(r.projectRoot=a.projectRoot),a.port&&(r.port=a.port),r.launchedAt=Date.now();let p=Zt.dirname(Ft);Te(p,{recursive:!0}),Re(Ft,JSON.stringify(r,null,2))}function xe(a){if(mt.platform()==="darwin"){try{$t("xattr",["-cr",a])}catch{}try{$t("spctl",["--add","--label","ZibbyStudio",a])}catch{}}}function zt(a,r){return new Promise(p=>{let S=Dt("open",["-a",a,"--env",`ZIBBY_STUDIO_PROJECT_ROOT=${r.projectRoot}`],{stdio:["ignore","pipe","pipe"]}),w="";S.stderr?.on("data",h=>{w+=h.toString()}),S.on("close",h=>p({code:h,stderr:w})),S.on("error",h=>p({code:1,stderr:h.message}))})}async function Yt(a={}){let r=ot();if(!r)throw new Error("Studio not installed");if(!Ne(r))throw new Error(`Studio app not found at ${r}`);Oe(a);let p=a.projectRoot||process.cwd();if(mt.platform()==="darwin"){let S=await zt(r,{projectRoot:p});if(S.code!==0&&S.stderr.includes("Launch failed")&&(xe(r),S=await zt(r,{projectRoot:p})),S.code!==0){let w=S.stderr.trim();w&&console.error(`[Studio Desktop] ${w}`),console.error(`Zibby Studio exited with code ${S.code}`)}}else{let S=Dt(r,[],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,ZIBBY_STUDIO_PROJECT_ROOT:p}});S.unref(),S.stderr?.on("data",w=>{let h=w.toString().trim();h&&console.error(`[Studio Desktop] ${h}`)}),S.on("error",w=>{console.error(`Failed to open Zibby Studio: ${w.message}`)})}}import{mergeSessionRunState as K,listRunningSessionStatesFromSessionsRoot as We}from"@zibby/core/utils/run-state-session.js";import{liveRunsFromSessionStateRows as Me}from"@zibby/core/utils/session-state-live-runs.js";import{findLatestLiveFrameFileSync as Jt,readLatestLiveFramePayloadSync as Kt}from"@zibby/core/utils/live-frame-discovery.js";var J={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.
|
|
8
|
+
`)),p}}function et(){let a=ot();return!!(a&&tt(a))}function ot(){if(U.platform()==="darwin")return $.join(O,"Zibby Studio.app");if(U.platform()==="win32")return $.join(O,"Zibby Studio.exe");if(U.platform()==="linux"){if(!tt(O))return null;let a=ye(O).find(r=>r.endsWith(".AppImage"));return a?$.join(O,a):null}return null}function Ae(){let a=$.join(O,"version.txt");return tt(a)?he(a,"utf-8").trim():"unknown"}var Pe,O,nt=me(()=>{Pe=process.env.ZIBBY_STUDIO_CDN||"https://dl.zibby.app",O=$.join(U.homedir(),".zibby","studio")});nt();import Gt from"express";import{createServer as ke}from"http";import{WebSocketServer as Ee}from"ws";import{spawn as ht,execSync as rt}from"child_process";import{readFileSync as x,existsSync as f,readdirSync as W,statSync as Z,createReadStream as Ue,createWriteStream as Be,mkdirSync as Wt,openSync as Le,readSync as Ce,closeSync as $e,writeFileSync as st,unlinkSync as Fe}from"fs";import{join as u,resolve as B,dirname as yt,basename as ze}from"path";import{homedir as De}from"os";import{inspect as Ze}from"util";import{fileURLToPath as Ye,pathToFileURL as Mt}from"url";import Ge from"dotenv";nt();import{spawn as Dt,execFileSync as $t}from"child_process";import mt from"os";import Zt from"path";import{existsSync as Ne,mkdirSync as Te,writeFileSync as Re}from"fs";var Ft=Zt.join(mt.homedir(),".zibby","studio-launch.json");function Oe(a){let r={};a.projectRoot&&(r.projectRoot=a.projectRoot),a.port&&(r.port=a.port),r.launchedAt=Date.now();let p=Zt.dirname(Ft);Te(p,{recursive:!0}),Re(Ft,JSON.stringify(r,null,2))}function xe(a){if(mt.platform()==="darwin"){try{$t("xattr",["-cr",a])}catch{}try{$t("spctl",["--add","--label","ZibbyStudio",a])}catch{}}}function zt(a,r){return new Promise(p=>{let S=Dt("open",["-a",a,"--env",`ZIBBY_STUDIO_PROJECT_ROOT=${r.projectRoot}`],{stdio:["ignore","pipe","pipe"]}),w="";S.stderr?.on("data",h=>{w+=h.toString()}),S.on("close",h=>p({code:h,stderr:w})),S.on("error",h=>p({code:1,stderr:h.message}))})}async function Yt(a={}){let r=ot();if(!r)throw new Error("Studio not installed");if(!Ne(r))throw new Error(`Studio app not found at ${r}`);Oe(a);let p=a.projectRoot||process.cwd();if(mt.platform()==="darwin"){let S=await zt(r,{projectRoot:p});if(S.code!==0&&S.stderr.includes("Launch failed")&&(xe(r),S=await zt(r,{projectRoot:p})),S.code!==0){let w=S.stderr.trim();w&&console.error(`[Studio Desktop] ${w}`),console.error(`Zibby Studio exited with code ${S.code}`)}}else{let S=Dt(r,[],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,ZIBBY_STUDIO_PROJECT_ROOT:p}});S.unref(),S.stderr?.on("data",w=>{let h=w.toString().trim();h&&console.error(`[Studio Desktop] ${h}`)}),S.on("error",w=>{console.error(`Failed to open Zibby Studio: ${w.message}`)})}}import{mergeSessionRunState as K,listRunningSessionStatesFromSessionsRoot as We}from"@zibby/core/utils/run-state-session.js";import{liveRunsFromSessionStateRows as Me}from"@zibby/core/utils/session-state-live-runs.js";import{findLatestLiveFrameFileSync as Jt,readLatestLiveFramePayloadSync as Kt}from"@zibby/core/utils/live-frame-discovery.js";var J={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 gt(){let a;if(process.env.ZIBBY_API_URL)a=process.env.ZIBBY_API_URL;else{let r=process.env.ZIBBY_ENV||"prod";J[r]?a=J[r].apiUrl:a=J.prod.apiUrl}try{let r=new URL(a);return r.protocol!=="http:"&&r.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${r.protocol} (only http/https allowed)`),J.prod.apiUrl):a}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${a}`),J.prod.apiUrl}}var Je=Ye(import.meta.url),Ke=yt(Je);function Ht(a){let r=u(a,"video.webm");if(f(r))return r;let p=u(a,"execute_live");if(!f(p))return null;try{let S=W(p).filter(h=>h.endsWith(".webm"));return S.length===0?null:S.map(h=>{let _=u(p,h);try{return{p:_,mtime:Z(_).mtimeMs}}catch{return{p:_,mtime:0}}}).sort((h,_)=>_.mtime-h.mtime)[0].p}catch{return null}}function Vt(a){if(process.platform==="win32")try{let r=rt("netstat -ano",{encoding:"utf8"}),p=new Set;for(let S of r.split(`
|
|
9
9
|
`)){if(!S.includes("LISTENING"))continue;let w=S.trim().split(/\s+/);if(!(w[1]||"").endsWith(`:${a}`))continue;let _=w[w.length-1];/^\d+$/.test(_)&&p.add(parseInt(_,10))}return[...p].filter(S=>S!==process.pid)}catch{return[]}try{let r=rt(`lsof -tiTCP:${a} -sTCP:LISTEN`,{encoding:"utf8"}).trim();return[...new Set(r.split(`
|
|
10
|
-
`).filter(Boolean))].map(p=>parseInt(p,10)).filter(p=>!Number.isNaN(p)&&p!==process.pid)}catch{return[]}}async function qt(a){let r=Vt(a);if(r.length!==0){console.log(`[Studio] Port ${a} in use \u2014 stopping previous Studio listener(s): ${r.join(", ")}`);for(let p of r)try{process.kill(p,"SIGTERM")}catch{}await new Promise(p=>setTimeout(p,450)),r=Vt(a);for(let p of r)try{process.kill(p,"SIGKILL")}catch{}await new Promise(p=>setTimeout(p,200))}}async function No(a={}){let r=Gt(),p=ke(r),S=new Ee({server:p}),w=a.port||3847,h=process.cwd(),_=De();process.env.DOTENV_CONFIG_QUIET="true";let E=process.env.NODE_ENV||"development";[B(h,".env.local"),B(h,`.env.${E}`),B(h,".env")].forEach(o=>{f(o)&&Ge.config({path:o,override:!1})});let k=new Map,Y=new Map,Qt=null,H=96e3,St="studio-cli.log",V="studio-run.json",Xt=".zibby-
|
|
10
|
+
`).filter(Boolean))].map(p=>parseInt(p,10)).filter(p=>!Number.isNaN(p)&&p!==process.pid)}catch{return[]}}async function qt(a){let r=Vt(a);if(r.length!==0){console.log(`[Studio] Port ${a} in use \u2014 stopping previous Studio listener(s): ${r.join(", ")}`);for(let p of r)try{process.kill(p,"SIGTERM")}catch{}await new Promise(p=>setTimeout(p,450)),r=Vt(a);for(let p of r)try{process.kill(p,"SIGKILL")}catch{}await new Promise(p=>setTimeout(p,200))}}async function No(a={}){let r=Gt(),p=ke(r),S=new Ee({server:p}),w=a.port||3847,h=process.cwd(),_=De();process.env.DOTENV_CONFIG_QUIET="true";let E=process.env.NODE_ENV||"development";[B(h,".env.local"),B(h,`.env.${E}`),B(h,".env")].forEach(o=>{f(o)&&Ge.config({path:o,override:!1})});let k=new Map,Y=new Map,Qt=null,H=96e3,St="studio-cli.log",V="studio-run.json",Xt=".zibby-stop",it=512*1024;r.use(Gt.json()),r.get("/api/session-run-states",(o,t)=>{try{let e=L();try{let i=new URL(o.url,"http://zibby.studio").searchParams.get("sessionsRoot");if(i&&String(i).trim()){let l=B(decodeURIComponent(String(i).trim()));f(l)&&Z(l).isDirectory()&&(e=l)}}catch{}let s=We(e),{liveIdList:n,progressByKey:c}=Me(s);t.json({rows:s,liveIdList:n,progressByKey:c,sessionsRoot:e,unavailable:!1})}catch(e){t.status(500).json({error:e.message,rows:[],liveIdList:[],progressByKey:{},unavailable:!0})}}),r.get("/api/workflow/graph",async(o,t)=>{try{let e=null,s=u(h,".zibby","graph.mjs");if(f(s))try{let n=await import(Mt(s).href),c=n.BrowserTestAutomationAgent||n.default;if(c&&typeof c=="function"){let i=new c().buildGraph();i&&typeof i.serialize=="function"&&(e=i.serialize())}}catch{}if(!e)try{let{createRequire:n}=await import("module"),c=n(import.meta.url),d=u(yt(c.resolve("@zibby/core/package.json")),"templates","browser-test-automation","run_test.json");f(d)&&(e=JSON.parse(x(d,"utf-8")))}catch{}t.json({graph:e})}catch{t.json({graph:null})}}),r.use((o,t,e)=>(t.header("Access-Control-Allow-Origin","*"),t.header("Access-Control-Allow-Methods","GET, POST, PUT, DELETE"),t.header("Access-Control-Allow-Headers","Content-Type"),e()));let ct=u(Ke,"../../../../studio"),bt=f(u(ct,"package.json"));function te(){let o=u(ct,"node_modules",".bin",process.platform==="win32"?"electron.cmd":"electron"),t=f(o),n=ht(t?o:"npx",t?["."]:["electron","."],{cwd:ct,detached:!0,stdio:"ignore",shell:!1,env:{...process.env,ZIBBY_STUDIO_PROJECT_ROOT:h,ZIBBY_STUDIO_API_BASE:`http://localhost:${w}/api`}});n.unref(),Qt=n}async function ee(){if(bt){te();return}if(a.update||!et()){if(a.update&&et()){console.log(`
|
|
11
11
|
Updating Zibby Studio...
|
|
12
12
|
`);let{installStudio:o}=await Promise.resolve().then(()=>(nt(),Ct));await o()}else if(!await ft()){p.close(),process.exit(0);return}}console.log(`
|
|
13
13
|
\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\u2557
|
package/dist/commands/upload.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{readFileSync as m,existsSync as l,statSync as
|
|
1
|
+
import{readFileSync as m,existsSync as l,statSync as b}from"fs";import{join as p,basename as j}from"path";import{glob as z}from"glob";import e from"chalk";import F from"ora";import k from"dotenv";var r={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 A(){let n;if(process.env.ZIBBY_API_URL)n=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";r[o]?n=r[o].apiUrl:n=r.prod.apiUrl}try{let o=new URL(n);return o.protocol!=="http:"&&o.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${o.protocol} (only http/https allowed)`),r.prod.apiUrl):n}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${n}`),r.prod.apiUrl}}function R(){let n=process.env.ZIBBY_ENV||"prod";return r[n]||r.prod}function E(){let n;if(process.env.ZIBBY_FRONTEND_URL)n=process.env.ZIBBY_FRONTEND_URL;else{let o=process.env.ZIBBY_ENV||"prod";r[o]?n=r[o].frontendUrl:n=r.prod.frontendUrl}try{let o=new URL(n);if(o.protocol!=="http:"&&o.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${o.protocol} (only http/https allowed)`),r.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let s=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],i=o.hostname;if(!s.some(u=>i===u||i.endsWith(`.${u}`))&&!i.includes("localhost")&&i!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${i}`),"https://studio.zibby.dev"}return n}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${n}`),r.local.frontendUrl}}import{existsSync as O,mkdirSync as q,readFileSync as D,writeFileSync as J}from"fs";import{homedir as $}from"os";import{join as y}from"path";function Y(){return process.env.ZIBBY_CONFIG_DIR||y($(),".zibby")}function S(){return y(Y(),"config.json")}var Z=y($(),".zibby"),H=y(Z,"config.json");function T(){try{let n=S();if(O(n)){let o=D(n,"utf-8");return JSON.parse(o)}}catch{}return{}}function w(){return T().sessionToken||null}function C(){return T().user||null}k.config();function V(n,o){let d=o?.paths?.specs||"test-specs",s=o?.paths?.generated||"tests";return n.replace(d,s).replace(/\.txt$/,".spec.js")}async function lo(n,o){let d=R();console.log(e.bold.cyan(`
|
|
2
2
|
\u{1F4E4} Zibby Cloud Upload
|
|
3
3
|
`)),console.log(e.gray("\u2501".repeat(50))),console.log(e.white(`Environment: ${e.cyan(d.name)}
|
|
4
4
|
`));let s=process.cwd(),i=o.project||process.env.ZIBBY_API_KEY;i||(console.log(e.red(`\u274C Error: Project API key required
|
|
@@ -9,11 +9,11 @@ import{readFileSync as m,existsSync as l,statSync as P}from"fs";import{join as p
|
|
|
9
9
|
`)),console.log(e.cyan("Option 2 (CI/CD):")),console.log(e.gray(` export ZIBBY_USER_TOKEN=zby_pat_xxxxx
|
|
10
10
|
`)),process.exit(1)),console.log(u?e.gray(`Authenticated: ${u.email}
|
|
11
11
|
`):e.gray(`Authenticated: Using Personal Access Token
|
|
12
|
-
`));let
|
|
12
|
+
`));let P=z.sync("test-results/sessions/*",{cwd:s}).filter(t=>b(p(s,t)).isDirectory()&&!/session_/.test(t)).sort((t,g)=>{let a=b(p(s,t));return b(p(s,g)).mtimeMs-a.mtimeMs});P.length===0&&(console.log(e.red(`\u274C No test results found
|
|
13
13
|
`)),console.log(e.white(`Run a test first: zibby run <spec-path>
|
|
14
|
-
`)),process.exit(1));let I=
|
|
14
|
+
`)),process.exit(1));let I=P[0],f=p(s,I,"execute_live");l(f)||(console.log(e.red(`\u274C No execution data found in ${I}
|
|
15
15
|
`)),process.exit(1));let x=p(f,"recording.webm"),h=p(f,"events.json"),N=p(f,"title.txt"),_=V(n,{});console.log(e.white("Found artifacts:")),console.log(e.gray(` Session: ${j(I)}`)),console.log(e.gray(` Video: ${l(x)?"\u2713":"\u2717"}`)),console.log(e.gray(` Events: ${l(h)?"\u2713":"\u2717"}`)),console.log(e.gray(` Test: ${l(_)?"\u2713":"\u2717"}
|
|
16
|
-
`));let B=
|
|
16
|
+
`));let B=F(`Uploading to ${d.name}...`).start();try{let t=new FormData;if(t.append("specPath",n),t.append("agent",o.agent||"cursor"),t.append("agentType",o.agent||"cursor"),o.collection&&t.append("collectionIdOrName",o.collection),o.folder&&t.append("folder",o.folder),l(x)){let c=new Blob([m(x)]);t.append("video",c,"recording.webm")}if(l(h)){let c=m(h,"utf-8");t.append("events",c)}if(l(_)){let c=m(_,"utf-8");t.append("testCode",c)}if(l(N)){let c=m(N,"utf-8").trim();t.append("title",c)}let g=A(),a=await fetch(`${g}/executions/upload`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"X-User-Token":v},body:t});if(!a.ok){let c=await a.text();B.fail(`Upload failed: ${a.status}`),console.log(e.red(`${c}
|
|
17
17
|
`)),process.exit(1)}let U=await a.json();B.succeed("Upload complete!"),console.log(e.green(`
|
|
18
18
|
\u2713 Test uploaded successfully`)),console.log(e.gray(` Execution ID: ${U.executionId}`));let L=`${E()}/projects/${U.projectId}/runs/${U.executionId}`;console.log(e.cyan(`
|
|
19
19
|
View results: ${L}
|
|
@@ -1,48 +1,48 @@
|
|
|
1
|
-
import{readFileSync as Y,writeFileSync as U,existsSync as k,mkdirSync as x}from"fs";import{resolve as S,join as w}from"path";import o from"chalk";import
|
|
1
|
+
import{readFileSync as Y,writeFileSync as U,existsSync as k,mkdirSync as x}from"fs";import{resolve as S,join as w}from"path";import o from"chalk";import I from"ora";import F from"dotenv";import L from"inquirer";var v={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 j(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";v[e]?t=v[e].apiUrl:t=v.prod.apiUrl}try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),v.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),v.prod.apiUrl}}function b(){let t=process.env.ZIBBY_ENV||"prod";return v[t]||v.prod}import{existsSync as T}from"fs";import{join as R}from"path";import{pathToFileURL as N}from"url";async function P(t){let e=R(t,".zibby.config.mjs");if(!T(e))throw new Error(".zibby.config.mjs not found");try{let n=await import(N(e).href);return n.default||n}catch(n){throw new Error(`Failed to load .zibby.config.mjs: ${n.message}`,{cause:n})}}import{validateGraphConfig as Z,generateWorkflowCode as O,generateNodeConfigsJson as K}from"@zibby/agent-workflow";import"@zibby/core/templates/register-nodes.js";F.config();async function J(t){let e=j(),n=I("Fetching projects...").start();try{let l=await fetch(`${e}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});l.ok||(n.fail("Failed to fetch projects"),process.exit(1));let r=await l.json();Array.isArray(r)||(r.projects&&Array.isArray(r.projects)?r=r.projects:r.data&&Array.isArray(r.data)?r=r.data:(n.fail("Unexpected response format"),process.exit(1))),(!r||r.length===0)&&(n.fail("No projects found"),process.exit(1)),n.stop();let p=r.map(a=>({name:`${a.name||"Unnamed"} (${a.id||"no-id"})`,value:a.id})),{projectId:c}=await L.prompt([{type:"list",name:"projectId",message:"Select a project:",choices:p}]);return c}catch(l){n.fail(`Error: ${l.message}`),process.exit(1)}}function B(t){let e=t.apiKey||process.env.ZIBBY_API_KEY;e||(console.log(o.red(`
|
|
2
2
|
ZIBBY_API_KEY not set`)),console.log(o.gray(` Add to .env: ZIBBY_API_KEY=zby_xxx
|
|
3
|
-
`)),process.exit(1));let t
|
|
3
|
+
`)),process.exit(1));let n=t.project||process.env.ZIBBY_PROJECT_ID;return n||(console.log(o.red(`
|
|
4
4
|
--project or ZIBBY_PROJECT_ID is required`)),console.log(o.gray(` Example: zibby workflow download --project <id> --type analysis
|
|
5
|
-
`)),process.exit(1)),{apiKey:e,projectId:
|
|
5
|
+
`)),process.exit(1)),{apiKey:e,projectId:n}}async function W(t){let e=t.apiKey||process.env.ZIBBY_API_KEY;e||(console.log(o.red(`
|
|
6
6
|
ZIBBY_API_KEY not set`)),console.log(o.gray(` Add to .env: ZIBBY_API_KEY=zby_xxx
|
|
7
|
-
`)),process.exit(1));let t
|
|
7
|
+
`)),process.exit(1));let n=t.project||process.env.ZIBBY_PROJECT_ID;return n||(n=await J(e)),{apiKey:e,projectId:n}}var _=["analysis","implementation","run_test"],G=/^[a-z][a-z0-9_-]{0,62}[a-z0-9]$/;function D(t){let e=t.type;return e||(console.log(o.red(`
|
|
8
8
|
--type is required`)),console.log(o.gray(` Built-in types: ${_.join(", ")}`)),console.log(o.gray(` Custom workflows: any lowercase slug (e.g., ticket-triage)
|
|
9
9
|
`)),process.exit(1)),!_.includes(e)&&!G.test(e)&&(console.log(o.red(`
|
|
10
10
|
Invalid workflow type: "${e}"`)),console.log(o.gray(` Built-in: ${_.join(", ")}`)),console.log(o.gray(` Custom: lowercase letters, digits, hyphens (2\u201364 chars)
|
|
11
|
-
`)),process.exit(1)),e}var V=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function q(
|
|
12
|
-
'${
|
|
13
|
-
`)),process.exit(1)),r=
|
|
14
|
-
Workflow with UUID '${
|
|
15
|
-
`)),process.exit(1)),
|
|
11
|
+
`)),process.exit(1)),e}var V=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function q(t,e){let n=j(),l={"Content-Type":"application/json",Authorization:`Bearer ${e}`},r=await fetch(`${n}/projects`,{method:"GET",headers:l});if(!r.ok)throw new Error(`Failed to list projects: HTTP ${r.status}`);let{projects:p=[]}=await r.json();for(let c of p){let a=await fetch(`${n}/projects/${c.projectId}/workflows`,{method:"GET",headers:l});if(!a.ok)continue;let s=await a.json(),d=(Array.isArray(s)?s:[]).find(i=>i.uuid===t);if(d){let i=d.workflowType||d.name;return{projectId:c.projectId,workflowType:i}}}return null}async function go(t){let e=b(),n,l,r;if(t.uuid){V.test(t.uuid)||(console.log(o.red(`
|
|
12
|
+
'${t.uuid}' is not a UUID.`)),console.log(o.gray(" Cloud workflows are identified by UUID. Run `zibby workflow list` to find yours,")),console.log(o.gray(` or use --type <built-in> for built-in workflow types.
|
|
13
|
+
`)),process.exit(1)),r=t.apiKey||process.env.ZIBBY_API_KEY,r||(r=B({...t,project:"pending"}).apiKey);let c=await q(t.uuid,r);c||(console.log(o.red(`
|
|
14
|
+
Workflow with UUID '${t.uuid}' not found in any of your projects.`)),console.log(o.gray(` Check: zibby workflow list
|
|
15
|
+
`)),process.exit(1)),n=c.projectId,l=c.workflowType}else{let c=B(t);r=c.apiKey,n=c.projectId,l=D(t)}console.log(o.bold.cyan(`
|
|
16
16
|
Zibby Workflow Download
|
|
17
|
-
`)),console.log(o.gray(" ".padEnd(52,"-"))),console.log(o.white(` Environment: ${o.cyan(e.name)}`)),console.log(o.white(` Project: ${o.cyan(
|
|
17
|
+
`)),console.log(o.gray(" ".padEnd(52,"-"))),console.log(o.white(` Environment: ${o.cyan(e.name)}`)),console.log(o.white(` Project: ${o.cyan(n)}`)),console.log(o.white(` Type: ${o.cyan(l)}`)),console.log(o.gray(" ".padEnd(52,"-")));let p=I(" Fetching workflow from cloud...").start();try{let c=j(),a=await fetch(`${c}/projects/${n}/workflows/${l}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`}});if(!a.ok){let i=await a.text();p.fail(` API error: ${a.status}`),console.log(o.red(` ${i}
|
|
18
18
|
`)),process.exit(1)}let s=await a.json();!s.graph&&s.isDefault?p.info(" No custom workflow saved -- downloading default graph"):p.succeed(` Fetched workflow (v${s.version||0})`);let d=s.graph||null;if(!d){console.log(o.yellow(`
|
|
19
19
|
No graph config available for this workflow.`)),console.log(o.gray(" The project is using the built-in default graph.")),console.log(o.gray(` Edit the graph in the UI first, or use --include-default to download the default.
|
|
20
|
-
`)),
|
|
20
|
+
`)),t.includeDefault||process.exit(0),p.start(" Fetching default graph...");let{getDefaultGraph:i}=await import("@zibby/core/templates/graphs/index.js"),g=i(l);return g||(p.fail(` No default graph found for type "${l}"`),process.exit(1)),C(l,{graph:g,version:0,isDefault:!0,projectId:n,workflowType:l,sources:null,uuid:null},t)}return C(l,{graph:d,version:s.version||0,isDefault:s.isDefault||!1,projectId:n,workflowType:l,sources:s.sources||null,uuid:s.uuid||s.workflowUuid||null},t)}catch(c){p.fail(" Download failed"),console.log(o.red(`
|
|
21
21
|
${c.message}
|
|
22
|
-
`)),process.exit(1)}}async function C(
|
|
23
|
-
`,"utf-8"),s.push("workflow.config.json")}if(e.uuid){let i={uuid:e.uuid,name:
|
|
24
|
-
`,"utf-8"),s.push(".zibby-deploy.json")}let d=`.zibby/workflows/${
|
|
25
|
-
Downloaded to ${o.bold(d)}`));for(let i of s)console.log(o.gray(` ${i}`));console.log(""),console.log(o.gray(` Version: ${e.version}`)),console.log(o.gray(` Nodes: ${e.graph.nodes?.length||0}`)),console.log(o.gray(` Edges: ${e.graph.edges?.length||0}`)),e.uuid&&console.log(o.gray(` UUID: ${e.uuid}`)),console.log(""),console.log(o.white(" Next steps:")),console.log(o.cyan(` cd ${d} && npm install `)+o.gray("Install workflow deps")),console.log(o.cyan(` zibby workflow run ${
|
|
22
|
+
`)),process.exit(1)}}async function C(t,e,n){let l=process.cwd(),r=".zibby/workflows";if(!n.output)try{r=(await P(l))?.paths?.workflows||".zibby/workflows"}catch{}let p=n.output||w(l,r),c=w(p,t);k(c)||x(c,{recursive:!0});let a={projectId:e.projectId,workflowType:e.workflowType,version:e.version,isDefault:e.isDefault},s=[];if(e.sources&&typeof e.sources=="object"&&Object.keys(e.sources).length>0)for(let[i,g]of Object.entries(e.sources)){if(i.includes("..")||i.startsWith("/")){console.log(o.yellow(` \u26A0 Skipping unsafe source path: ${i}`));continue}let y=w(c,i),h=w(y,"..");k(h)||x(h,{recursive:!0}),U(y,g,"utf-8"),s.push(i)}else{let i=w(c,"graph.mjs");U(i,O(e.graph,a),"utf-8"),s.push("graph.mjs");let g=e.graph.nodeConfigs||{},y=K(g),h=w(c,"workflow.config.json");U(h,`${JSON.stringify(y,null,2)}
|
|
23
|
+
`,"utf-8"),s.push("workflow.config.json")}if(e.uuid){let i={uuid:e.uuid,name:t,projectId:e.projectId,version:e.version,downloadedAt:new Date().toISOString()};U(w(c,".zibby-deploy.json"),`${JSON.stringify(i,null,2)}
|
|
24
|
+
`,"utf-8"),s.push(".zibby-deploy.json")}let d=`.zibby/workflows/${t}/`;console.log(o.green(`
|
|
25
|
+
Downloaded to ${o.bold(d)}`));for(let i of s)console.log(o.gray(` ${i}`));console.log(""),console.log(o.gray(` Version: ${e.version}`)),console.log(o.gray(` Nodes: ${e.graph.nodes?.length||0}`)),console.log(o.gray(` Edges: ${e.graph.edges?.length||0}`)),e.uuid&&console.log(o.gray(` UUID: ${e.uuid}`)),console.log(""),console.log(o.white(" Next steps:")),console.log(o.cyan(` cd ${d} && npm install `)+o.gray("Install workflow deps")),console.log(o.cyan(` zibby workflow run ${t} `)+o.gray("Run locally")),console.log(o.cyan(` zibby workflow deploy ${t} `)+o.gray("Re-deploy after changes (same UUID)")),console.log("")}async function uo(t){let e=b(),{apiKey:n,projectId:l}=await W(t),r=D(t);console.log(o.bold.cyan(`
|
|
26
26
|
Zibby Workflow Upload
|
|
27
|
-
`)),console.log(o.gray(" ".padEnd(52,"-"))),console.log(o.white(` Environment: ${o.cyan(e.name)}`)),console.log(o.white(` Project: ${o.cyan(l)}`)),console.log(o.white(` Type: ${o.cyan(r)}`)),console.log(o.gray(" ".padEnd(52,"-")));let p=process.cwd(),c=w(p,".zibby",`workflow-${r}.json`),a=w(p,".zibby",`workflow-${r}.js`),s=
|
|
27
|
+
`)),console.log(o.gray(" ".padEnd(52,"-"))),console.log(o.white(` Environment: ${o.cyan(e.name)}`)),console.log(o.white(` Project: ${o.cyan(l)}`)),console.log(o.white(` Type: ${o.cyan(r)}`)),console.log(o.gray(" ".padEnd(52,"-")));let p=process.cwd(),c=w(p,".zibby",`workflow-${r}.json`),a=w(p,".zibby",`workflow-${r}.js`),s=t.file||(k(a)?a:c);k(s)||(console.log(o.red(`
|
|
28
28
|
File not found: ${s}`)),console.log(o.gray(` Download a workflow first: zibby workflow download --project <id> --type <type>
|
|
29
|
-
`)),process.exit(1));let d=s.endsWith(".js")||s.endsWith(".mjs"),i;if(d){let f=
|
|
29
|
+
`)),process.exit(1));let d=s.endsWith(".js")||s.endsWith(".mjs"),i;if(d){let f=I(" Loading JS workflow module...").start();try{let{pathToFileURL:u}=await import("url"),m=await import(u(S(s)).href),$=m.buildGraph();i=$.serialize();let E=m.nodeConfigs||{};if(Object.keys(E).length>0)for(let[A,z]of Object.entries(E))i.nodeConfigs[A]={...z,...i.nodeConfigs[A]};f.succeed(` Loaded JS module (${$.nodes.size} nodes)`)}catch(u){f.fail(" Failed to load JS module"),console.log(o.red(`
|
|
30
30
|
${u.message}
|
|
31
|
-
`)),process.exit(1)}}else{let f;try{f=JSON.parse(Y(s,"utf-8"))}catch(
|
|
32
|
-
Failed to parse ${s}: ${
|
|
31
|
+
`)),process.exit(1)}}else{let f;try{f=JSON.parse(Y(s,"utf-8"))}catch($){console.log(o.red(`
|
|
32
|
+
Failed to parse ${s}: ${$.message}
|
|
33
33
|
`)),process.exit(1)}let{_meta:u,...m}=f;i=m}(!i.nodes||!i.edges)&&(console.log(o.red(`
|
|
34
34
|
Invalid workflow file: missing nodes or edges`)),console.log(o.gray(` The file should contain { nodes: [...], edges: [...], nodeConfigs: {...} }
|
|
35
35
|
`)),process.exit(1)),console.log(o.gray(`
|
|
36
|
-
File: ${s}`)),console.log(o.gray(` Format: ${d?"JavaScript (serialized via graph.serialize())":"JSON"}`)),console.log(o.gray(` Nodes: ${i.nodes.length}`)),console.log(o.gray(` Edges: ${i.edges.length}`));let g=
|
|
36
|
+
File: ${s}`)),console.log(o.gray(` Format: ${d?"JavaScript (serialized via graph.serialize())":"JSON"}`)),console.log(o.gray(` Nodes: ${i.nodes.length}`)),console.log(o.gray(` Edges: ${i.edges.length}`));let g=I(" Validating graph...").start(),y=Z(i);if(!y.valid){g.fail(" Graph validation failed"),console.log("");for(let f of y.errors)console.log(o.red(` ${f}`));console.log(o.gray(`
|
|
37
37
|
Fix the errors above and try again.
|
|
38
|
-
`)),process.exit(1)}g.succeed(" Graph is valid");let h=
|
|
38
|
+
`)),process.exit(1)}g.succeed(" Graph is valid");let h=I(" Uploading to cloud...").start();try{let f=j(),u=await fetch(`${f}/projects/${l}/workflows/${r}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({graph:i})});if(!u.ok){let $=await u.text();h.fail(` API error: ${u.status}`),console.log(o.red(` ${$}
|
|
39
39
|
`)),process.exit(1)}let m=await u.json();h.succeed(` Uploaded successfully (v${m.version})`),console.log(o.green(`
|
|
40
40
|
Workflow "${r}" updated to version ${m.version}`)),console.log(o.gray(` Project: ${l}
|
|
41
41
|
`))}catch(f){h.fail(" Upload failed"),console.log(o.red(`
|
|
42
42
|
${f.message}
|
|
43
|
-
`)),process.exit(1)}}var M=["analysis","implementation","run_test"];async function wo(
|
|
43
|
+
`)),process.exit(1)}}var M=["analysis","implementation","run_test"];async function wo(t){let e=b(),{apiKey:n,projectId:l}=B(t);console.log(o.bold.cyan(`
|
|
44
44
|
Zibby Workflows
|
|
45
|
-
`));let r=
|
|
45
|
+
`));let r=I(" Fetching workflows...").start();try{let p=j(),c=[];for(let a of M){let s=await fetch(`${p}/projects/${l}/workflows/${a}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});if(s.ok){let d=await s.json();c.push({type:a,version:d.version||0,isDefault:d.isDefault!==!1&&!d.graph,nodes:d.graph?.nodes?.length||0,updatedAt:d.updatedAt||null})}}r.succeed(` Fetched workflows
|
|
46
46
|
`),console.log(o.gray(" ".padEnd(70,"-"))),console.log(o.white(" Type".padEnd(20))+o.white("Version".padEnd(10))+o.white("Nodes".padEnd(10))+o.white("Status".padEnd(15))+o.white("Updated")),console.log(o.gray(" ".padEnd(70,"-")));for(let a of c){let s=a.isDefault?o.gray("default"):o.green("custom"),d=a.updatedAt?new Date(a.updatedAt).toLocaleDateString():o.gray("-");console.log(` ${o.cyan(a.type.padEnd(18))}${String(a.version).padEnd(10)}${String(a.nodes).padEnd(10)}${s.padEnd(15)}${d}`)}console.log(o.gray(" ".padEnd(70,"-"))),console.log("")}catch(p){r.fail(" Failed to fetch workflows"),console.log(o.red(`
|
|
47
47
|
${p.message}
|
|
48
48
|
`)),process.exit(1)}}export{go as workflowDownloadCommand,wo as workflowListCommand,uo as workflowUploadCommand};
|