@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.
- 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 +83 -75
- package/dist/commands/list-projects.js +5 -5
- package/dist/commands/memory.js +28 -18
- package/dist/commands/project.js +3 -3
- package/dist/commands/run.js +52 -55
- package/dist/commands/studio.js +1 -1
- package/dist/commands/template.js +9 -0
- 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 +13 -13
- package/dist/commands/workflows/list.js +6 -6
- package/dist/commands/workflows/run-local.js +15 -15
- package/dist/commands/workflows/start.js +16 -16
- package/dist/commands/workflows/trigger.js +7 -7
- package/dist/config/environments.js +1 -1
- package/dist/package.json +4 -4
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-static-ip.md +1 -1
- package/dist/utils/agent-credentials.js +4 -3
- package/dist/utils/credentials-loader.js +1 -0
- package/package.json +4 -4
package/dist/commands/run.js
CHANGED
|
@@ -1,78 +1,75 @@
|
|
|
1
|
-
import{runTest as
|
|
2
|
-
`,"utf8")}function
|
|
3
|
-
`,"utf8")}import{readFileSync as
|
|
1
|
+
var De=Object.defineProperty;var je=(t,o)=>()=>(t&&(o=t(t=0)),o);var Ye=(t,o)=>{for(var s in o)De(t,s,{get:o[s],enumerable:!0})};var xe={};Ye(xe,{_resetLoaderCacheForTests:()=>lo,loadCredentialsIntoEnv:()=>co});import Pe from"node:fs";import to from"node:path";import no from"node:os";async function Ee(){if(!(process.env.__ZIBBY_CLAUDE_PLAN||process.platform!=="darwin"||!(process.env.CLAUDE_CODE_OAUTH_TOKEN||process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL||process.env.ANTHROPIC_AUTH_TOKEN)))try{let{execSync:o}=await import("node:child_process"),s=o('security find-generic-password -s "Claude Code-credentials" -w',{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(s){let i=JSON.parse(s)?.claudeAiOauth?.subscriptionType;i&&(process.env.__ZIBBY_CLAUDE_PLAN=i)}}catch{}}function io(t){try{if(!Pe.existsSync(t))return{};let o=Pe.readFileSync(t,"utf-8"),s=JSON.parse(o);return s&&s.agentKeys&&typeof s.agentKeys=="object"?s.agentKeys:{}}catch{return{}}}async function co(t={}){let{verbose:o=!1,force:s=!1,configPath:l}=t;if(q&&!s)return G;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||process.env.ANTHROPIC_AUTH_TOKEN))return await Ee(),q=!0,G={oauthCount:0,apiCount:0,source:"cloud-env"},o&&console.log("[credentials-loader] env vars already set \u2014 skipping local discovery"),G;let a=l||to.join(no.homedir(),".zibby","config.json"),n=io(a),y="none",d=0,m=0;for(let h of so)n[h]&&!process.env[h]&&(process.env[h]=String(n[h]).trim(),y="config.json",h.endsWith("_POOL")?d+=String(n[h]).split(",").filter(D=>D.trim()).length:d+=1);for(let h of ro)n[h]&&!process.env[h]&&(process.env[h]=String(n[h]).trim(),y="config.json",h.endsWith("_POOL")?m+=String(n[h]).split(",").filter(D=>D.trim()).length:m+=1);return await Ee(),q=!0,G={oauthCount:d,apiCount:m,source:y},o&&d+m>0&&console.log(`[credentials-loader] loaded ${d} OAuth + ${m} API from ${y} (~/.zibby/config.json)`),G}function lo(){q=!1,G=null}var q,G,so,ro,be=je(()=>{q=!1,G=null,so=["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN_POOL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_AUTH_TOKEN_POOL"],ro=["ANTHROPIC_API_KEY","ANTHROPIC_API_KEY_POOL"]});import{runTest as ao,logger as U,DEFAULT_OUTPUT_BASE as uo,SESSIONS_DIR as po}from"@zibby/core";import{zibbyScratchSpecsDir as ae}from"@zibby/core/constants/zibby-scratch.js";import{createCliRunIndexPipelineProgressAppender as fo,postCliInterruptedRunIndex as Oe}from"@zibby/core/utils/run-index-post-cli.js";import{createWriteStream as Ke,mkdirSync as Fe}from"fs";import{join as pe,isAbsolute as ze}from"path";var Ge="studio-cli.log";function He(t,o){if(!t||typeof t!="string")return null;let s=t.trim();return s?ze(s)?s:pe(o,s):null}function Ze(t){if(!t)return()=>{};Fe(t,{recursive:!0});let o=pe(t,Ge),s=Ke(o,{flags:"a"}),l=process.stdout.write.bind(process.stdout),i=process.stderr.write.bind(process.stderr),a=n=>function(d,m,h){typeof m=="function"&&(h=m,m=void 0);try{Buffer.isBuffer(d)?s.write(d):s.write(String(d),m||"utf8")}catch{}return n(d,m,h)};return process.stdout.write=a(l),process.stderr.write=a(i),()=>{process.stdout.write=l,process.stderr.write=i;try{s.end()}catch{}}}function oe(t,o,s){let l=null;function i(a){if(!l&&a?.sessionPath){let n=He(a.sessionPath,o);n&&(l=Ze(n))}typeof t=="function"&&t(a)}return i.dispose=()=>{typeof l=="function"&&(l(),l=null)},i}import{existsSync as fe,mkdirSync as Me,readFileSync as Ve,readdirSync as Lo,unlinkSync as We,writeFileSync as ge}from"fs";import{join as he}from"path";import{execSync as Yo}from"child_process";import{DEFAULT_OUTPUT_BASE as Je}from"@zibby/core";function ye(t){return t?.paths?.output||Je}function te(t,o,s){return he(t,o,`.zibby-chat-run-pids-${s}.json`)}function me(t,o,s){let l=te(t,o,s);if(!fe(l))return[];try{let i=JSON.parse(Ve(l,"utf8"));return(Array.isArray(i?.pids)?i.pids:[]).map(n=>Number(n)).filter(n=>Number.isFinite(n)&&n>0)}catch{return[]}}function Ie(t,o,s,l={}){let i=Number(o),a=Number(s);if(!Number.isFinite(i)||i<=0||!Number.isFinite(a)||a<=0)return;let n=ye(l),y=he(t,n);Me(y,{recursive:!0});let d=me(t,n,i);d.includes(a)||d.push(a),ge(te(t,n,i),`${JSON.stringify({v:1,pids:d})}
|
|
2
|
+
`,"utf8")}function _e(t,o,s,l={}){let i=Number(o),a=Number(s);if(!Number.isFinite(i)||i<=0||!Number.isFinite(a)||a<=0)return;let n=ye(l),y=te(t,n,i);if(!fe(y))return;let d=me(t,n,i).filter(m=>m!==a);if(d.length===0)try{We(y)}catch{}else ge(y,`${JSON.stringify({v:1,pids:d})}
|
|
3
|
+
`,"utf8")}import{readFileSync as O,existsSync as w,statSync as Te,mkdirSync as Ue,writeFileSync as Se,appendFileSync as go,rmSync as $e}from"fs";import{resolve as B,join as $,dirname as ho,isAbsolute as Ne}from"path";import{fileURLToPath as yo}from"url";import{glob as X}from"glob";import e from"chalk";import Be from"ora";import mo from"dotenv";import Io from"open";var b={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 W(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";b[o]?t=b[o].apiUrl:t=b.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)`),b.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),b.prod.apiUrl}}function we(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let t=process.env.ZIBBY_ENV||"prod";return(b[t]||b.prod).accountApiUrl}function ne(){let t=process.env.ZIBBY_ENV||"prod";return b[t]||b.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";b[o]?t=b[o].frontendUrl:t=b.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)`),b.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let l=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],i=o.hostname;if(!l.some(n=>i===n||i.endsWith(`.${n}`))&&!i.includes("localhost")&&i!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${i}`),"https://studio.zibby.dev"}return t}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${t}`),b.local.frontendUrl}}import{existsSync as qe,mkdirSync as Ho,readFileSync as Xe,writeFileSync as Zo}from"fs";import{homedir as ve}from"os";import{join as J}from"path";function Qe(){return process.env.ZIBBY_CONFIG_DIR||J(ve(),".zibby")}function eo(){return J(Qe(),"config.json")}var oo=J(ve(),".zibby"),Wo=J(oo,"config.json");function Ae(){try{let t=eo();if(qe(t)){let o=Xe(t,"utf-8");return JSON.parse(o)}}catch{}return{}}function re(){return Ae().sessionToken||null}function ie(){return Ae().user||null}var _o=yo(import.meta.url),wo=ho(_o),vo=JSON.parse(O($(wo,"../../package.json"),"utf-8"));function Ao(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 Ce(t,o){if(t==null)return null;let s=String(t).trim();return s?Ne(s)?s:B(o,s):null}function Po(t,o){try{if(!t||!w(t))return;let s=$(t,"studio-cli.log"),l=`
|
|
4
4
|
[CLI_FATAL] ${new Date().toISOString()}
|
|
5
5
|
Error: ${String(o?.message||o)}
|
|
6
6
|
${o?.stack?`${String(o.stack)}
|
|
7
|
-
`:""}`;
|
|
7
|
+
`:""}`;go(s,l,"utf8")}catch{}}process.env.DOTENV_CONFIG_QUIET="true";var Eo=process.env.NODE_ENV||"development",xo=[B(process.cwd(),".env.local"),B(process.cwd(),`.env.${Eo}`),B(process.cwd(),".env")];xo.forEach(t=>{w(t)&&mo.config({path:t,override:!1})});function bo(t,o){let s=o?.paths?.specs||"test-specs",l=o?.paths?.generated||"tests";return t.replace(s,l).replace(/\.txt$/,".spec.js")}async function Oo(t,o){let s=se(),l=/^[0-9A-HJKMNP-TV-Z]{26}$/,i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(!l.test(t)&&!i.test(t))return console.log(e.red(`
|
|
8
8
|
\u274C Invalid execution ID format (security check)
|
|
9
|
-
`)),!1;if(!
|
|
9
|
+
`)),!1;if(!i.test(o))return console.log(e.red(`
|
|
10
10
|
\u274C Invalid project ID format (security check)
|
|
11
11
|
`)),!1;let a=new URL(s);if(!s.includes("localhost")&&!s.includes("127.0.0.1")&&a.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 y=`${s}/projects/${o}/runs/${t}`;try{return console.log(e.cyan(`
|
|
14
|
+
Opening test results in browser...`)),console.log(e.gray(` ${y}
|
|
15
|
+
`)),await Io(y),!0}catch{return console.log(e.yellow("Could not open browser automatically")),console.log(e.gray(` Please open manually: ${y}
|
|
16
|
+
`)),!1}}function ce(t,o){let s=o?.paths?.specs||"test-specs",l=o?.paths?.generated||"tests";return t.replace(l,s).replace(/\.spec\.js$/,".txt")}async function To({apiKey:t,specPath:o,fullSpecPath:s,collectionIdOrName:l,folder:i,agent:a,config:n,result:y,shouldOpen:d}){let m=W(),h=ne(),D=process.env.ZIBBY_USER_TOKEN||re(),k=ie();console.log(k?e.gray(`Authenticated: ${k.email} (${k.name||"User"})`):e.gray("Authenticated: Using Personal Access Token"));let v=Be(`Uploading to ${h.name}...`).start();try{let f=process.cwd(),T=null;if(y?.state?.sessionPath){let c=y.state.sessionPath;T=c.startsWith(f)?c.slice(f.length+1):c}if(!T){let g=`${n.paths?.output||uo}/${po}/*`,N=X.sync(g,{cwd:f}).filter(C=>Te($(f,C)).isDirectory()&&!/session_/.test(C)).map(C=>({path:C,stat:Te($(f,C))})).sort((C,de)=>de.stat.mtimeMs-C.stat.mtimeMs);if(N.length===0){v.warn("No session folder found, skipping upload");return}T=N[0].path}let S=X.sync(`${T}/execute_live/videos/*.webm`,{cwd:f});S.length===0&&(S=X.sync(`${T}/execute_live/*.webm`,{cwd:f})),S.length===0&&(S=X.sync(`${T}/*.webm`,{cwd:f}));let L=$(f,T,"execute_live","events.json"),K=$(f,T,"execute_live","result.json"),Y=$(f,T,"title.txt"),M=bo(o,n),r=$(f,M),u=w(r);if(S.length===0){v.warn("No video file found in session folder, skipping upload");return}let I=$(f,S[0]),E=w(Y)?O(Y,"utf-8").trim():null;U.debug(`Video exists: ${w(I)}`),U.debug(`Events exists: ${w(L)}`);let A=null,j=null;if(l){v.text="Resolving collection...";let c=we(),g=await fetch(`${c}/collections/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({collectionIdOrName:l})});if(!g.ok){let C=await g.json().catch(()=>({}));throw new Error(C.error||"Failed to resolve collection")}let N=await g.json();A=N.collectionId,j=N.collectionName,N.isNew&&(v.text=`Created new collection: ${j}`)}v.text="Preparing upload...";let _={video:w(I)?O(I).length:0,events:w(L)?O(L).length:0,instructions:(()=>{let c=ce(o,n),g=$(f,c);return w(g)?O(g).length:0})(),result:w(K)?O(K).length:0},x=_.video+_.events+_.instructions+_.result,V=(x/1024/1024).toFixed(2);if(_.video>50*1024*1024)throw new Error(`Video file too large: ${(_.video/1024/1024).toFixed(2)}MB (max: 50MB)`);if(x>60*1024*1024)throw new Error(`Total upload size too large: ${V}MB (max: 60MB)`);v.text=`Getting upload URLs... (${V}MB)`;let p={"Content-Type":"application/json",Authorization:`Bearer ${t}`};D&&(p["X-User-Token"]=D);let P=typeof a=="object"?a.provider:a||"cursor",H=typeof a=="object"&&a[P]?.model||null,Re=H==="auto"?null:H,Z=await fetch(`${m}/executions/upload`,{method:"POST",headers:p,body:JSON.stringify({collectionId:A||null,specPath:o,specContent:(()=>{let c=ce(o,n),g=$(f,c);return w(g)?O(g,"utf-8"):w(s)?O(s,"utf-8"):""})(),title:E||null,agentType:P,model:Re,metadata:{agent:a||"cursor",timestamp:new Date().toISOString(),folder:i||null,collectionName:j||null},fileSizes:_})});if(!Z.ok){let c=await Z.json();if(Z.status===413)throw c.details&&Array.isArray(c.details)?new Error(`File size limit exceeded:
|
|
17
|
+
${c.details.map(g=>` \u2022 ${g}`).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(c.error||"Upload files too large");if(Z.status===429){if(c.quotaInfo)throw new Error(`Video verification quota exceeded (${c.quotaInfo.used}/${c.quotaInfo.limit}).
|
|
21
|
+
Plan: ${c.quotaInfo.planId}. Resets: ${new Date(c.quotaInfo.periodEnd).toLocaleDateString()}
|
|
22
|
+
Upgrade at: https://studio.zibby.dev/billing`);if(c.storageInfo){let g=(c.storageInfo.used/1073741824).toFixed(2),N=(c.storageInfo.limit/(1024*1024*1024)).toFixed(2),C=(c.storageInfo.uploadSize/(1024*1024)).toFixed(2);throw new Error(`Storage quota would be exceeded.
|
|
23
|
+
Current usage: ${g}GB / ${N}GB
|
|
24
|
+
This upload: ${C}MB
|
|
25
|
+
Plan: ${c.storageInfo.planId}
|
|
26
|
+
Upgrade at: https://studio.zibby.dev/billing`)}}throw new Error(c.error||"Failed to initiate upload")}let{executionId:F,uploadUrls:R,isOrphan:ke,projectId:Q}=await Z.json();v.text=`Uploading video... (${F})`;let ee=O(I);U.debug(`Video buffer size: ${ee.length} bytes`),U.debug("Upload URL received (redacted)");let z=await fetch(R.video,{method:"PUT",body:ee,headers:{"Content-Type":"video/webm","Content-Length":ee.length.toString()}});if(U.debug(`Video upload status: ${z.status} ${z.statusText}`),!z.ok){let c=await z.text();throw new Error(`Failed to upload video: ${z.status} ${z.statusText} - ${c}`)}if(U.info("Video uploaded successfully"),w(L)&&R.events){v.text="Uploading events...";let c=O(L),g=await fetch(R.events,{method:"PUT",body:c,headers:{"Content-Type":"application/json","Content-Length":c.length.toString()}});if(U.debug(`Events upload status: ${g.status} ${g.statusText}`),!g.ok)throw new Error("Failed to upload events");U.info("Events uploaded successfully")}else U.debug(`Skipping events upload - exists: ${w(L)}, hasUrl: ${!!R.events}`);if(u&&R.generatedTest){v.text="Uploading generated test...";let c=O(r);if(!(await fetch(R.generatedTest,{method:"PUT",body:c,headers:{"Content-Type":"application/javascript","Content-Length":c.length.toString()}})).ok)throw new Error("Failed to upload generated test")}if(R.testInstructions){let c=ce(o,n),g=$(f,c);if(w(g)){v.text="Uploading test instructions...";let N=O(g);(await fetch(R.testInstructions,{method:"PUT",body:N,headers:{"Content-Type":"text/plain","Content-Length":N.length.toString()}})).ok?U.debug("Test instructions uploaded successfully"):U.warn("Failed to upload test instructions (non-blocking)")}else console.log(`\u2139\uFE0F No source test instructions found at ${c}`)}if(R.result&&w(K)){v.text="Uploading test results...";let c=O(K);(await fetch(R.result,{method:"PUT",body:c,headers:{"Content-Type":"application/json","Content-Length":c.length.toString()}})).ok?U.debug("result.json uploaded successfully"):U.warn("Failed to upload result.json (non-blocking)")}if(v.text="Confirming upload...",!(await fetch(`${m}/executions/${F}/confirm`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({status:"completed",metadata:{uploadedAt:new Date().toISOString()},fileSizes:_})})).ok)throw new Error("Failed to confirm upload");v.succeed("Uploaded to Zibby Cloud!"),console.log(e.gray(`
|
|
27
|
+
${"\u2501".repeat(50)}`)),console.log(e.white(`Execution ID: ${e.cyan(F)}`));let ue=se();console.log(ke?e.white(`Location: ${e.yellow("History tab")}`):e.white(`Collection: ${e.cyan(A)}`));let Le=Q?`${ue}/projects/${Q}/runs/${F}`:`${ue}/history?execution=${F}`;return console.log(e.white(`View execution: ${e.cyan(Le)}`)),console.log(e.gray(`${"\u2501".repeat(50)}
|
|
28
|
+
`)),{success:!0,executionId:F,projectId:Q||null}}catch(f){return v.fail("Upload failed"),console.log(e.red(` ${f.message}`)),process.env.DEBUG&&console.log(e.gray(` Stack: ${f.stack}`)),console.log(e.gray(` Continuing without upload...
|
|
29
|
+
`)),{success:!1}}}async function Uo(t,o,s){let l=W(),i=o.join(","),a=await fetch(`${l}/executions/${t}/test-cases?ids=${i}`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch test cases: ${a.status} ${a.statusText}`);return(await a.json()).testCases||[]}async function So(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${vo.version} | Node.js ${process.version}`)),console.log(e.gray("\u2501".repeat(50)));try{let{loadCredentialsIntoEnv:r}=await Promise.resolve().then(()=>(be(),xe));await r({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
33
|
`)),process.exit(1));let r=o.project||process.env.ZIBBY_API_KEY;r||(console.log(e.red(`
|
|
34
34
|
\u274C --project <id> or ZIBBY_API_KEY required when using --sources
|
|
35
|
-
`)),process.exit(1));let u=o.sources.split(",").map(
|
|
35
|
+
`)),process.exit(1));let u=o.sources.split(",").map(A=>A.trim());console.log(e.white(`Fetching ${u.length} test case(s) from execution ${e.cyan(o.execution)}...`));let I=await Uo(o.execution,u,r);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());Ue(E,{recursive:!0});for(let A of I){let j=`# ${A.title}
|
|
38
38
|
|
|
39
|
-
${
|
|
40
|
-
Running: ${e.cyan(
|
|
39
|
+
${A.content}`,_=B(E,`${A.id}.txt`);Se(_,j,"utf-8"),console.log(e.gray("\u2501".repeat(50))),console.log(e.white(`
|
|
40
|
+
Running: ${e.cyan(A.title)} (${A.id})`));let x={...o,sources:void 0,execution:void 0};x.sync=!0,await So(_,x)}$e(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 l=t&&!t.endsWith(".txt")&&!
|
|
43
|
+
`)),process.exit(1));let l=t&&!t.endsWith(".txt")&&!w(B(process.cwd(),t))&&t.includes(" ");if(l){let r=ae(process.cwd());Ue(r,{recursive:!0});let u=B(r,`inline-${Date.now()}.txt`);Se(u,t,"utf-8"),t=u}let i=B(process.cwd(),t);w(i)||(console.log(e.red(`
|
|
44
44
|
\u274C Test spec not found: ${t}
|
|
45
|
-
`)),process.exit(1));let a=
|
|
45
|
+
`)),process.exit(1));let a=O(i,"utf-8"),n={headless:o.headless||!1,playwrightArtifacts:!0},y=B(process.cwd(),o.config);if(w(y))try{let r=await import(y),u=I=>I?.provider?I.provider:I?.gemini?"gemini":I?.codex?"codex":I?.claude?"claude":I?.cursor?"cursor":null;n={...n,...r.default,agent:r.default?.agent?{...r.default.agent,provider:o.agent||u(r.default.agent)}:{provider:o.agent||"cursor"},mcp:r.default?.browser?.mcp||"playwright",headless:o.headless!==void 0?o.headless:r.default?.browser?.headless,paths:r.default?.paths||{specs:"test-specs",generated:"tests"},cloudSync:r.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 d=process.env.ZIBBY_API_KEY,m=o.sync||n.cloudSync===!0&&o.sync!==!1;if(o.project&&o.project.startsWith("zby_")&&(d=o.project,console.log(e.gray("Using --project as API token (overriding .env)"))),m&&!d&&(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)),m&&d){let r=process.env.ZIBBY_USER_TOKEN,u;r?console.log(e.gray("Using Personal Access Token from ZIBBY_USER_TOKEN")):(r=re(),u=ie(),(!r||!u)&&(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)),u&&console.log(e.gray(`Authenticated: ${u.email} (${u.name||"User"})`)))}if(
|
|
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)),u&&console.log(e.gray(`Authenticated: ${u.email} (${u.name||"User"})`)))}if(m&&d){let r=W();try{d.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 u=await fetch(`${r}/projects`,{headers:{Authorization:`Bearer ${
|
|
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 u=await fetch(`${r}/projects`,{headers:{Authorization:`Bearer ${d}`}});u.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 u.json()).projects||[];(!E||E.length===0)&&(console.log(e.red(`
|
|
67
67
|
\u274C No projects found for this token
|
|
68
|
-
`)),process.exit(1));let
|
|
68
|
+
`)),process.exit(1));let A=E[0];console.log(e.green(`\u2713 Authorized for project: ${A.name} (${A.projectId})`))}catch(u){console.log(e.red(`
|
|
69
69
|
\u274C Failed to validate API credentials: ${u.message}
|
|
70
|
-
`)),process.exit(1)}}let
|
|
71
|
-
|
|
72
|
-
`)),console.log(e.white("
|
|
73
|
-
`)),console.log(e.white("Or add to .env file:")),console.log(e.gray(` ANTHROPIC_API_KEY=sk-ant-...
|
|
74
|
-
`)),console.log(e.white(`Get your API key from: https://console.anthropic.com/
|
|
75
|
-
`)),process.exit(1)),O==="codex"){try{let{execSync:r}=await import("child_process");r("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"})}catch{console.log(e.red(`
|
|
70
|
+
`)),process.exit(1)}}let h=typeof n.agent=="object"?n.agent.provider:n.agent;if(h==="claude"){let r=!!process.env.ANTHROPIC_API_KEY||!!process.env.ANTHROPIC_API_KEY_POOL,u=!!process.env.CLAUDE_CODE_OAUTH_TOKEN||!!process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,I=!!process.env.ANTHROPIC_AUTH_TOKEN||!!process.env.ANTHROPIC_AUTH_TOKEN_POOL;r||u||I||(console.log(e.red(`
|
|
71
|
+
Error: no Claude credentials found
|
|
72
|
+
`)),console.log(e.white("Run `zibby init` to set up credentials interactively.")),console.log(e.gray(" Pick Claude \u2192 Subscription (OAuth) or API key.")),console.log(""),console.log(e.gray("Or export ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN in your shell.")),console.log(""),process.exit(1))}if(h==="codex"){try{let{execSync:r}=await import("child_process");r("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"})}catch{console.log(e.red(`
|
|
76
73
|
\u274C Error: Codex CLI not installed
|
|
77
74
|
`)),console.log(e.white("Install the Codex CLI:")),console.log(e.gray(` npm install -g @openai/codex
|
|
78
75
|
`)),console.log(e.white("Then verify:")),console.log(e.gray(` codex --version
|
|
@@ -81,7 +78,7 @@ Running: ${e.cyan(w.title)} (${w.id})`));let P={...o,sources:void 0,execution:vo
|
|
|
81
78
|
`)),console.log(e.white("Set your API key:")),console.log(e.gray(` export OPENAI_API_KEY="sk-..."
|
|
82
79
|
`)),console.log(e.white("Or add to .env file:")),console.log(e.gray(` OPENAI_API_KEY=sk-...
|
|
83
80
|
`)),console.log(e.white(`Get your API key from: https://platform.openai.com/api-keys
|
|
84
|
-
`)),process.exit(1))}if(
|
|
81
|
+
`)),process.exit(1))}if(h==="gemini"){if(process.env.GEMINI_API_KEY&&process.env.GOOGLE_API_KEY){let r=String(process.env.GEMINI_API_KEY).trim(),u=String(process.env.GOOGLE_API_KEY).trim();r&&u&&r!==u&&(process.env.GOOGLE_API_KEY=r,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:r}=await import("child_process");r("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"})}catch{console.log(e.red(`
|
|
85
82
|
\u274C Error: Gemini CLI not installed
|
|
86
83
|
`)),console.log(e.white("Install the Gemini CLI:")),console.log(e.gray(` npm install -g @google/gemini-cli
|
|
87
84
|
`)),console.log(e.white("Then verify:")),console.log(e.gray(` gemini --version
|
|
@@ -90,25 +87,25 @@ Running: ${e.cyan(w.title)} (${w.id})`));let P={...o,sources:void 0,execution:vo
|
|
|
90
87
|
`)),console.log(e.white("Set your API key:")),console.log(e.gray(` export GEMINI_API_KEY="your_key_here"
|
|
91
88
|
`)),console.log(e.white("Or add to .env file:")),console.log(e.gray(` GEMINI_API_KEY=your_key_here
|
|
92
89
|
`)),console.log(e.white(`Get your API key from: https://aistudio.google.com/app/apikey
|
|
93
|
-
`)),process.exit(1))}if(
|
|
90
|
+
`)),process.exit(1))}if(h==="cursor"){let{checkCursorAgentInstalled:r,getCursorAgentInstallInstructions:u}=await import("@zibby/core");await r()||(console.log(e.red(u())),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
91
|
\u274C Error: CURSOR_API_KEY not set
|
|
95
92
|
`)),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
93
|
`)),console.log(e.white(`Get your API key from: https://cursor.com/settings
|
|
97
94
|
`)),console.log(e.white(`Add it to your CI/CD environment variables.
|
|
98
95
|
`)),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 ${
|
|
96
|
+
`)))}console.log(e.white(`Test Spec: ${e.cyan(t)}`));let D=typeof n.agent=="object"?n.agent.provider:n.agent;console.log(e.white(`Agent: ${e.cyan(D)}`)),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 k;if(o.sessionPath!=null&&String(o.sessionPath).trim()!==""){let r=String(o.sessionPath).trim();k=Ne(r)?B(r):B(process.cwd(),r),console.log(e.white(`Session path: ${e.cyan(k)}`))}console.log(e.gray("\u2501".repeat(50)));let v=Be({text:"Initializing...",stream:process.stdout}).start(),f=()=>{try{Oe({cwd:process.cwd(),config:n})}catch{}},T=process.env.ZIBBY_CHAT_OWNER_PID,S=T!=null&&String(T).trim()!==""?Number(T):null,L=S!=null&&Number.isFinite(S)&&S>0,K=()=>{if(L)try{_e(process.cwd(),S,process.pid,n)}catch{}},Y=null,M=Ce(k,process.cwd());try{v.stop();let{waitUntilRunCapacity:r}=await import("@zibby/core/utils/run-capacity-coordinator.js"),{basename:u}=await import("path");await r({cwd:process.cwd(),config:n,meta:{source:process.env.ZIBBY_RUN_SOURCE||"cli",specHint:t?u(t):"",studioTestCaseId:process.env.ZIBBY_STUDIO_TEST_CASE_ID||null},log:p=>console.log(e.gray(p))});let I=await import("@zibby/core/templates/browser-test-automation/graph.mjs").catch(()=>null);if(L)try{Ie(process.cwd(),S,process.pid,n)}catch{}process.on("SIGINT",f),process.on("SIGTERM",f);let E=process.cwd(),A={},j=p=>{let P=Ce(p?.sessionPath,E);P&&(M=P)};if(typeof n.onPipelineProgress=="function"){let p=oe(n.onPipelineProgress,E,n);Y=()=>p.dispose(),A.onPipelineProgress=P=>{j(P),p({...P,specPath:t,taskDescription:a})}}else if(n.runIndex?.pipelineProgress!==!1){let p=fo({cwd:E,config:n}),P=oe(p,E,n);Y=()=>P.dispose(),A.onPipelineProgress=H=>{j(H),P({...H,specPath:t,taskDescription:a})}}let _=await ao(i,{...n,...A,specPath:t,apiKey:process.env.ANTHROPIC_API_KEY,autoApprove:o.autoApprove,force:o.autoApprove,singleNode:o.node,sessionId:o.session,...k?{sessionPath:k}:{},workflow:o.workflow,contextConfig:n.context,fallbackAgentModule:I}),x=_.outputPath||null;x&&(x=x.replace(/\/+/g,"/"),x.includes(process.cwd())&&(x=x.replace(`${process.cwd()}/`,"")));let V=_.state?.generate_script?.scriptPath||_.state?.verify_script?.success;if(console.log(e.gray(`
|
|
97
|
+
${"\u2501".repeat(50)}`)),V&&x)console.log(e.green("\u2713 Test execution completed")),console.log(e.white(`Generated test: ${e.cyan(x)}`)),_.toolCount!==void 0&&console.log(e.white(`Tools used: ${e.cyan(_.toolCount)}`)),console.log(e.gray(`${"\u2501".repeat(50)}
|
|
98
|
+
`)),console.log(e.cyan("Next steps:")),console.log(e.white(` 1. Review generated test: ${x}`)),console.log(e.white(` 2. Run with Playwright: npx playwright test ${x}`)),console.log(e.white(` 3. View report: npx playwright show-report
|
|
99
|
+
`));else{let p=_.state?.execute_live;p?p.steps?.length>0||p.actions?.length>0?(console.log(e.white(`
|
|
100
|
+
Execution Summary:`)),console.log(e.white(` Steps: ${p.steps?.length||0}`)),console.log(e.white(` Actions: ${p.actions?.length||0}`)),p.finalUrl&&console.log(e.white(` Final URL: ${p.finalUrl}`)),p.notes&&console.log(e.white(`
|
|
101
|
+
\u{1F4DD} ${p.notes}`))):(console.log(e.red("\u2716 Workflow did not complete")),console.log(e.yellow(`
|
|
102
|
+
\u26A0\uFE0F ${p.notes||"Test execution failed"}`))):console.log(e.red("\u2716 Workflow did not complete")),console.log(e.gray(`${"\u2501".repeat(50)}
|
|
106
103
|
`))}if(o.node)console.log(e.gray(`
|
|
107
104
|
Note: Upload skipped for single node execution`)),console.log(e.gray(` Run full workflow to upload all artifacts
|
|
108
|
-
`));else if(
|
|
105
|
+
`));else if(m){let p=o.project||process.env.ZIBBY_API_KEY;if(!p)console.log(e.yellow(`
|
|
109
106
|
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
|
|
107
|
+
`));else{let P=await To({apiKey:p,specPath:t,fullSpecPath:i,projectId:null,collectionIdOrName:o.collection||null,folder:o.folder,agent:n.agent,config:n,result:_,shouldOpen:o.open});o.open&&P?.success&&P.executionId&&P.projectId&&await Oo(P.executionId,P.projectId)}}}catch(r){if(v.isSpinning&&v.stop(),console.log(e.red(`
|
|
111
108
|
\u2716 Test failed
|
|
112
|
-
`)),
|
|
113
|
-
`));try{
|
|
114
|
-
`)),r.stack&&console.log(e.gray(r.stack)),
|
|
109
|
+
`)),Ao(r)){console.log(e.yellow(`Test execution was interrupted
|
|
110
|
+
`));try{Oe({cwd:process.cwd(),config:n})}catch{}le(l),process.exit(130)}Po(M,r),console.log(e.red(`Error: ${r.message}
|
|
111
|
+
`)),r.stack&&console.log(e.gray(r.stack)),le(l),process.exit(1)}finally{typeof Y=="function"&&Y(),K(),process.off("SIGINT",f),process.off("SIGTERM",f)}le(l)}function le(t){if(t)try{$e(ae(process.cwd()),{recursive:!0,force:!0})}catch{}}export{So as runCommand};
|
package/dist/commands/studio.js
CHANGED
|
@@ -5,7 +5,7 @@ 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
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...
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{mkdir as S,writeFile as m,readFile as p}from"fs/promises";import{existsSync as f,readdirSync as j}from"fs";import{join as o}from"path";import e from"chalk";async function z(s,n,t={}){let i=t.enableMemory!==!1,{TemplateFactory:a}=await import("@zibby/core/templates"),{graphPath:c,nodesPath:y,readmePath:$,resultHandlerPath:b,template:u}=a.getTemplateFiles(n),l=o(s,".zibby");f(l)||await S(l,{recursive:!0});let r=[];await m(o(l,"graph.mjs"),await p(c,"utf-8")),r.push("graph.mjs"),b&&(await m(o(l,"result-handler.mjs"),await p(b,"utf-8")),r.push("result-handler.mjs")),await m(o(l,"README.md"),await p($,"utf-8")),r.push("README.md");let h=o(l,"nodes");await S(h,{recursive:!0});for(let g of j(y)){let d=await p(o(y,g),"utf-8");!i&&g==="execute-live.mjs"&&(d=d.replace("skills: [SKILLS.BROWSER, SKILLS.MEMORY],","skills: [SKILLS.BROWSER],")),await m(o(h,g),d),r.push(`nodes/${g}`)}let w=o(u.path,"chat.mjs");return f(w)&&(await m(o(l,"chat.mjs"),await p(w,"utf-8")),r.push("chat.mjs")),{template:u,copied:r}}async function E(){let{TemplateFactory:s}=await import("@zibby/core/templates"),n=s.listTemplates();console.log(""),console.log(e.bold.cyan(" Available templates")),console.log("");for(let t of n){let i=t.default?e.gray(" (default)"):"";if(console.log(` ${e.cyan(t.name)}${i}`),console.log(` ${e.white(t.displayName)}`),t.description&&console.log(` ${e.gray(t.description)}`),t.features&&t.features.length)for(let a of t.features)console.log(e.gray(` \u2022 ${a}`));console.log("")}console.log(e.gray(" Use: zibby template add <name> (or pass -t <name> to zibby init)")),console.log("")}async function L(s,n={}){s||(console.log(e.red(`
|
|
2
|
+
Missing template name.
|
|
3
|
+
`)),console.log(e.gray(" Usage: zibby template add <name>")),console.log(e.gray(` See available templates: zibby template list
|
|
4
|
+
`)),process.exit(1));let t=n.cwd||process.cwd(),i=o(t,".zibby");f(i)||(console.log(e.yellow(`
|
|
5
|
+
No .zibby/ directory in ${t}.
|
|
6
|
+
`)),console.log(e.gray(" Run `zibby init` first to bootstrap the project.\n")),process.exit(1));let a;try{a=await z(t,s,{enableMemory:n.enableMemory!==!1})}catch(c){console.log(e.red(`
|
|
7
|
+
${c.message}
|
|
8
|
+
`)),console.log(e.gray(` See available templates: zibby template list
|
|
9
|
+
`)),process.exit(1)}console.log(""),console.log(e.green(` \u2713 Added template ${e.bold(a.template.name)}`)),console.log(e.gray(` ${a.copied.length} files written to ${i}/`));for(let c of a.copied)console.log(e.gray(` \u2022 ${c}`));console.log(""),console.log(e.gray(" Re-running `zibby template add <name>` overwrites existing files \u2014")),console.log(e.gray(" use this to refresh after `npm update @zibby/core`.")),console.log("")}export{L as templateAddCommand,E as templateListCommand,z as writeTemplateFiles};
|
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};
|
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import g from"ora";import h from"inquirer";import{readFileSync as I,existsSync as
|
|
1
|
+
import g from"ora";import h from"inquirer";import{readFileSync as I,existsSync as y}from"fs";import{join as E}from"path";import{homedir as P}from"os";var p={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 b(){let s;if(process.env.ZIBBY_API_URL)s=process.env.ZIBBY_API_URL;else{let t=process.env.ZIBBY_ENV||"prod";p[t]?s=p[t].apiUrl:s=p.prod.apiUrl}try{let t=new URL(s);return t.protocol!=="http:"&&t.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${t.protocol} (only http/https allowed)`),p.prod.apiUrl):s}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${s}`),p.prod.apiUrl}}function m(){let s=E(P(),".zibby","config.json");if(y(s))try{let n=JSON.parse(I(s,"utf-8"));if(n.sessionToken)return n.sessionToken}catch{}let t=process.env.ZIBBY_API_KEY;if(t)return t;console.log(`
|
|
2
2
|
Not authenticated`),console.log(" Run: zibby login"),console.log(` OR set ZIBBY_API_KEY env var
|
|
3
|
-
`),process.exit(1)}async function L(s,t){let n=
|
|
3
|
+
`),process.exit(1)}async function L(s,t){let n=m(),e=b(),o={"Content-Type":"application/json",Authorization:`Bearer ${n}`};switch(s){case"enable":return v(e,o);case"status":return $(e,o);case"disable":return w(e,o);case"use":case"unuse":return U(e,o,s,t);default:console.log(`
|
|
4
4
|
Error: Unknown action "${s}"`),console.log(` Valid actions: enable | status | disable | use | unuse
|
|
5
|
-
`),process.exit(1)}}async function
|
|
5
|
+
`),process.exit(1)}}async function v(s,t){console.log(`
|
|
6
6
|
Dedicated Egress IP \u2014 Enable
|
|
7
7
|
`);let n=g("Checking account...").start(),e;try{let c=await fetch(`${s}/addons/dedicated-egress/status`,{method:"GET",headers:t});if(!c.ok){let a=await c.json().catch(()=>({}));n.fail("Check failed"),console.log(` Error: ${a.message||c.statusText}
|
|
8
8
|
`),process.exit(1)}e=await c.json()}catch(c){n.fail("Check failed"),console.log(` Error: ${c.message}
|
|
9
|
-
`),process.exit(1)}if(n.stop(),e.enabled&&!e.cancelAtPeriodEnd){console.log(" Already active."),e.elasticIp&&console.log(` Your static IP: ${e.elasticIp}`),console.log("");return}e.hasProSub||(console.log(" Dedicated egress requires an active Pro subscription."),console.log(` Upgrade at: https://zibby.
|
|
9
|
+
`),process.exit(1)}if(n.stop(),e.enabled&&!e.cancelAtPeriodEnd){console.log(" Already active."),e.elasticIp&&console.log(` Your static IP: ${e.elasticIp}`),console.log("");return}e.hasProSub||(console.log(" Dedicated egress requires an active Pro subscription."),console.log(` Upgrade at: https://zibby.dev/billing
|
|
10
10
|
`),process.exit(1));let o=e.pricing?.priceUSD??50,i=e.pricing?.billingPeriod??"month",r=e.pricing?.description||"Static outbound IP for allowlisting on corporate firewalls.",l=e.enabled&&e.cancelAtPeriodEnd;console.log(` ${r}`),console.log(` Cost: $${o} per ${i} (prorated from today, billed via Stripe)
|
|
11
11
|
`);let{confirm:d}=await h.prompt([{type:"confirm",name:"confirm",message:l?`Re-enable dedicated egress at $${o}/${i}?`:`Enable dedicated egress at $${o}/${i}?`,default:!1}]);if(!d){console.log(`
|
|
12
12
|
Cancelled.
|
|
13
13
|
`);return}let u=g("Requesting dedicated egress IP for your account...").start();try{let c=await fetch(`${s}/addons/dedicated-egress/enable`,{method:"POST",headers:t});if(!c.ok){let f=await c.json().catch(()=>({}));u.fail("Enable failed"),f.code==="PAYMENT_METHOD_REQUIRED"?(console.log(`
|
|
14
|
-
No payment method on file.`),console.log(` Add a card first at: https://zibby.
|
|
14
|
+
No payment method on file.`),console.log(` Add a card first at: https://zibby.dev/billing
|
|
15
15
|
`)):console.log(` Error: ${f.error||f.message||c.statusText}
|
|
16
16
|
`),process.exit(1)}let a=await c.json();u.succeed(l?"Re-enabled":"Provisioning started"),console.log(""),l&&a.elasticIp?console.log(` Your static IP is back online: ${a.elasticIp}
|
|
17
17
|
`):(console.log(` This takes 2-3 minutes.
|
|
@@ -19,7 +19,7 @@ import g from"ora";import h from"inquirer";import{readFileSync as I,existsSync a
|
|
|
19
19
|
`))),console.log(" Then opt each project in:"),console.log(` zibby deploy --dedicated-ip use --project <project-id>
|
|
20
20
|
`),console.log(" Check status:"),console.log(` zibby deploy --dedicated-ip status
|
|
21
21
|
`)}catch(c){u.fail("Enable failed"),console.log(` Error: ${c.message}
|
|
22
|
-
`),process.exit(1)}}async function
|
|
22
|
+
`),process.exit(1)}}async function $(s,t){let n=g("Fetching dedicated egress status...").start();try{let e=await fetch(`${s}/addons/dedicated-egress/status`,{method:"GET",headers:t});if(!e.ok){let r=await e.json().catch(()=>({}));n.fail("Status check failed"),console.log(` Error: ${r.message||e.statusText}
|
|
23
23
|
`),process.exit(1)}let o=await e.json();if(n.stop(),console.log(""),!o.enabled){console.log(` Dedicated egress IP: not enabled
|
|
24
24
|
`),console.log(" Enable it with:"),console.log(` zibby deploy --dedicated-ip enable
|
|
25
25
|
`);return}if(o.status==="provisioning"){console.log(` Dedicated egress IP: provisioning (2-3 min)
|