@zibby/cli 0.1.60 → 0.1.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/auth/cli-login.js +12 -12
  2. package/dist/bin/zibby.js +2 -2
  3. package/dist/commands/agent-reliability.js +4 -4
  4. package/dist/commands/analyze-graph.js +14 -14
  5. package/dist/commands/chat-session-store.js +1 -1
  6. package/dist/commands/chat.js +71 -62
  7. package/dist/commands/ci-setup.js +3 -3
  8. package/dist/commands/generate.js +60 -21
  9. package/dist/commands/implement.js +15 -15
  10. package/dist/commands/init.js +88 -67
  11. package/dist/commands/list-projects.js +9 -9
  12. package/dist/commands/memory.js +13 -13
  13. package/dist/commands/project.js +8 -8
  14. package/dist/commands/run-capacity-queue-cli.js +2 -2
  15. package/dist/commands/run.js +52 -50
  16. package/dist/commands/setup-scripts.js +6 -6
  17. package/dist/commands/studio.js +21 -15
  18. package/dist/commands/uninstall.js +10 -10
  19. package/dist/commands/upload.js +15 -15
  20. package/dist/commands/video.js +1 -1
  21. package/dist/commands/workflow.js +35 -35
  22. package/dist/commands/workflows/delete.js +8 -0
  23. package/dist/commands/workflows/deploy.js +10 -10
  24. package/dist/commands/workflows/generate.js +17 -17
  25. package/dist/commands/workflows/list.js +15 -15
  26. package/dist/commands/workflows/logs.js +13 -13
  27. package/dist/commands/workflows/run.js +7 -7
  28. package/dist/commands/workflows/start.js +6 -6
  29. package/dist/commands/workflows/trigger.js +14 -8
  30. package/dist/config/config-loader.js +1 -1
  31. package/dist/config/config.js +1 -1
  32. package/dist/config/environments.js +1 -1
  33. package/dist/package.json +2 -2
  34. package/dist/utils/agent-credentials.js +3 -3
  35. package/dist/utils/chat-run-lifecycle.js +3 -3
  36. package/dist/utils/execution-context.js +1 -1
  37. package/dist/utils/progress-reporter.js +1 -1
  38. package/dist/utils/studio-cli-log-mirror.js +1 -1
  39. package/dist/utils/studio-installer.js +5 -5
  40. package/dist/utils/studio-launcher.js +1 -1
  41. package/package.json +2 -2
@@ -1,4 +1,4 @@
1
- import o from"chalk";const y=`
1
+ import o from"chalk";var y=`
2
2
  Install @zibby/memory and Dolt to enable test memory:
3
3
 
4
4
  npm install @zibby/memory # add the package
@@ -6,33 +6,33 @@ import o from"chalk";const y=`
6
6
  # or: curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash
7
7
  `;async function d(){try{return await import("@zibby/memory")}catch{return console.log(o.yellow(`
8
8
  @zibby/memory is not installed.
9
- `)),console.log(o.white(y)),null}}async function h(){const s=await d();if(!s)return;const l=process.cwd(),e=s.getStats(l);if(!e.available){console.log(o.red(`
9
+ `)),console.log(o.white(y)),null}}async function h(){let s=await d();if(!s)return;let l=process.cwd(),e=s.getStats(l);if(!e.available){console.log(o.red(`
10
10
  Dolt is not installed.
11
11
  `)),console.log(o.white(" Install Dolt to enable test memory:")),console.log(o.gray(" brew install dolt # macOS")),console.log(o.gray(` curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash # Linux
12
12
  `));return}if(!e.initialized){console.log(o.yellow(`
13
13
  Memory database not initialized.
14
14
  `)),console.log(o.white(" Run `zibby init` or `zibby memory init` to set it up.\n"));return}console.log(o.bold.cyan(`
15
15
  Zibby Test Memory
16
- `)),console.log(o.gray(` Dolt: ${e.doltVersion}`));const a=o.gray(` ${"\u2500".repeat(40)}`);console.log(a);const n=e.counts;if(console.log(o.white(` Test runs: ${o.cyan(n.runs)} (${o.green(`${n.passed} passed`)}, ${n.failed>0?o.red(`${n.failed} failed`):o.gray(`${n.failed} failed`)})`)),console.log(o.white(` Selectors: ${o.cyan(n.selectors)} tracked`)),console.log(o.white(` Pages: ${o.cyan(n.pages)} discovered`)),console.log(o.white(` Transitions: ${o.cyan(n.transitions)} mapped`)),console.log(o.white(` Insights: ${o.cyan(n.insights||0)} saved`)),e.recentRuns.length>0){console.log(`
17
- ${a}`),console.log(o.white(" Recent runs:"));for(const t of e.recentRuns){const c=t.passed?o.green("\u2713"):o.red("\u2717"),r=t.duration_ms?o.gray(`${(t.duration_ms/1e3).toFixed(1)}s`):"";console.log(` ${c} ${o.white(t.spec_path)} ${r}`)}}if(e.topSelectors.length>0){console.log(`
18
- ${a}`),console.log(o.white(" Top selectors:"));for(const t of e.topSelectors){const c=t.success_count+t.failure_count,r=Math.round(t.success_count/c*100);console.log(` ${o.cyan(t.stable_id||"?")} \u2192 ${t.element_desc} (${r}%, ${c} uses)`)}}if(e.log){console.log(`
19
- ${a}`),console.log(o.white(" Recent commits:"));const t=e.log.split(`
20
- `).filter(c=>c.startsWith("commit")||c.trim().startsWith("run ")).slice(0,10);for(const c of t)console.log(o.gray(` ${c.trim()}`))}console.log("")}async function f(s){const l=await d();if(!l)return;const e=process.cwd();if(!s.force){console.log(o.yellow(`
16
+ `)),console.log(o.gray(` Dolt: ${e.doltVersion}`));let a=o.gray(` ${"\u2500".repeat(40)}`);console.log(a);let n=e.counts;if(console.log(o.white(` Test runs: ${o.cyan(n.runs)} (${o.green(`${n.passed} passed`)}, ${n.failed>0?o.red(`${n.failed} failed`):o.gray(`${n.failed} failed`)})`)),console.log(o.white(` Selectors: ${o.cyan(n.selectors)} tracked`)),console.log(o.white(` Pages: ${o.cyan(n.pages)} discovered`)),console.log(o.white(` Transitions: ${o.cyan(n.transitions)} mapped`)),console.log(o.white(` Insights: ${o.cyan(n.insights||0)} saved`)),e.recentRuns.length>0){console.log(`
17
+ ${a}`),console.log(o.white(" Recent runs:"));for(let t of e.recentRuns){let c=t.passed?o.green("\u2713"):o.red("\u2717"),r=t.duration_ms?o.gray(`${(t.duration_ms/1e3).toFixed(1)}s`):"";console.log(` ${c} ${o.white(t.spec_path)} ${r}`)}}if(e.topSelectors.length>0){console.log(`
18
+ ${a}`),console.log(o.white(" Top selectors:"));for(let t of e.topSelectors){let c=t.success_count+t.failure_count,r=Math.round(t.success_count/c*100);console.log(` ${o.cyan(t.stable_id||"?")} \u2192 ${t.element_desc} (${r}%, ${c} uses)`)}}if(e.log){console.log(`
19
+ ${a}`),console.log(o.white(" Recent commits:"));let t=e.log.split(`
20
+ `).filter(c=>c.startsWith("commit")||c.trim().startsWith("run ")).slice(0,10);for(let c of t)console.log(o.gray(` ${c.trim()}`))}console.log("")}async function f(s){let l=await d();if(!l)return;let e=process.cwd();if(!s.force){console.log(o.yellow(`
21
21
  This will permanently delete the memory database.
22
22
  `)),console.log(o.white(` Run with --force to confirm: zibby memory reset --force
23
- `));return}const a=l.resetMemory(e);console.log(a?o.green(`
23
+ `));return}let a=l.resetMemory(e);console.log(a?o.green(`
24
24
  Memory database reset.
25
25
  `):o.gray(`
26
26
  No memory database found.
27
- `))}async function b(s){const l=await d();if(!l)return;const e=process.cwd(),a=l.getStats(e);if(!a.initialized){console.log(o.yellow(`
27
+ `))}async function b(s){let l=await d();if(!l)return;let e=process.cwd(),a=l.getStats(e);if(!a.initialized){console.log(o.yellow(`
28
28
  Memory database not initialized.
29
- `));return}const n=s.maxRuns||50,t=s.maxAge||90;console.log(o.white(`
30
- Compacting memory (keep last ${n} runs/spec, prune data older than ${t}d)...`));const c=a.counts;if(l.compactMemory(e,{maxRuns:n,maxAgeDays:t}).pruned){const m=l.getStats(e).counts,i=g=>c[g]-m[g];console.log(o.green(" Done.")),i("runs")>0&&console.log(o.gray(` Pruned ${i("runs")} old runs`)),i("selectors")>0&&console.log(o.gray(` Pruned ${i("selectors")} stale selectors`)),i("insights")>0&&console.log(o.gray(` Pruned ${i("insights")} old insights`)),i("transitions")>0&&console.log(o.gray(` Pruned ${i("transitions")} stale transitions`)),console.log(o.gray(` Dolt GC completed
29
+ `));return}let n=s.maxRuns||50,t=s.maxAge||90;console.log(o.white(`
30
+ Compacting memory (keep last ${n} runs/spec, prune data older than ${t}d)...`));let c=a.counts;if(l.compactMemory(e,{maxRuns:n,maxAgeDays:t}).pruned){let m=l.getStats(e).counts,i=g=>c[g]-m[g];console.log(o.green(" Done.")),i("runs")>0&&console.log(o.gray(` Pruned ${i("runs")} old runs`)),i("selectors")>0&&console.log(o.gray(` Pruned ${i("selectors")} stale selectors`)),i("insights")>0&&console.log(o.gray(` Pruned ${i("insights")} old insights`)),i("transitions")>0&&console.log(o.gray(` Pruned ${i("transitions")} stale transitions`)),console.log(o.gray(` Dolt GC completed
31
31
  `))}else console.log(o.gray(` Nothing to compact.
32
- `))}async function p(){const s=await d();if(!s)return;const l=process.cwd();if(!s.DoltDB.isAvailable()){console.log(o.red(`
32
+ `))}async function p(){let s=await d();if(!s)return;let l=process.cwd();if(!s.DoltDB.isAvailable()){console.log(o.red(`
33
33
  Dolt is not installed.
34
34
  `)),console.log(o.white(" Install Dolt:")),console.log(o.gray(" brew install dolt # macOS")),console.log(o.gray(` curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash # Linux
35
- `));return}const{created:e,available:a}=s.initMemory(l);e?console.log(o.green(`
35
+ `));return}let{created:e,available:a}=s.initMemory(l);e?console.log(o.green(`
36
36
  Memory database initialized at .zibby/memory/
37
37
  `)):a&&console.log(o.gray(`
38
38
  Memory database already initialized.
@@ -1,15 +1,15 @@
1
- import l from"dotenv";import{getApiUrl as i}from"../config/environments.js";l.config();function p(t){const r=t.apiKey||process.env.ZIBBY_API_KEY;return r||(console.log(`
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.app",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:r}}async function f(t={}){const{apiKey:r}=p(t),s=i();try{const n=await fetch(`${s}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`}});if(!n.ok){const e=await n.json().catch(()=>({}));console.log(`
4
- Error: ${e.message||n.statusText}
5
- `),process.exit(1)}let o=await n.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(`
3
+ `),process.exit(1)),{apiKey:e}}async function _(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
+ Error: ${n.message||t.statusText}
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
7
7
  `),console.log(" Response:",JSON.stringify(o,null,2)),process.exit(1))),!o||o.length===0){console.log(`
8
8
  No projects found
9
9
  `);return}console.log(`
10
10
  Projects
11
- `),console.log(" ".padEnd(80,"-")),console.log(`${" ID".padEnd(30)+"Name".padEnd(30)}Created`),console.log(" ".padEnd(80,"-"));for(const e of o){const a=e.createdAt?new Date(e.createdAt).toLocaleDateString():"-",c=e.projectId||e.id||"";console.log(` ${c.padEnd(28)}${(e.name||"-").padEnd(30)}${a}`)}console.log(" ".padEnd(80,"-")),console.log(`
11
+ `),console.log(" ".padEnd(80,"-")),console.log(`${" ID".padEnd(30)+"Name".padEnd(30)}Created`),console.log(" ".padEnd(80,"-"));for(let n of o){let l=n.createdAt?new Date(n.createdAt).toLocaleDateString():"-",i=n.projectId||n.id||"";console.log(` ${i.padEnd(28)}${(n.name||"-").padEnd(30)}${l}`)}console.log(" ".padEnd(80,"-")),console.log(`
12
12
  Total: ${o.length} project${o.length===1?"":"s"}
13
- `)}catch(n){console.log(`
14
- Error: ${n.message}
15
- `),process.exit(1)}}export{f as projectListCommand};
13
+ `)}catch(t){console.log(`
14
+ Error: ${t.message}
15
+ `),process.exit(1)}}export{_ as projectListCommand};
@@ -1,4 +1,4 @@
1
- import{resolve as p}from"path";import{existsSync as l}from"fs";import t from"chalk";import{readRunCapacityWaitSnapshot as u}from"@zibby/core/utils/run-capacity-queue.js";import{resolveRunCapacityPaths as g}from"@zibby/core/utils/run-capacity-coordinator.js";async function C(r){const n=process.cwd(),c=p(n,r.config||".zibby.config.mjs");let s={paths:{output:".zibby/output",specs:"test-specs",generated:"tests"}};if(l(c))try{const e=(await import(c)).default||{};s={...s,...e,paths:{...s.paths,...e.paths||{}}}}catch(o){console.log(t.yellow(`Could not load config: ${o.message}`))}const{outputAbs:i}=g(n,s),a=u(i);if(console.log(t.bold.cyan(`
1
+ import{resolve as p}from"path";import{existsSync as l}from"fs";import t from"chalk";import{readRunCapacityWaitSnapshot as u}from"@zibby/core/utils/run-capacity-queue.js";import{resolveRunCapacityPaths as g}from"@zibby/core/utils/run-capacity-coordinator.js";async function C(r){let n=process.cwd(),c=p(n,r.config||".zibby.config.mjs"),s={paths:{output:".zibby/output",specs:"test-specs",generated:"tests"}};if(l(c))try{let e=(await import(c)).default||{};s={...s,...e,paths:{...s.paths,...e.paths||{}}}}catch(o){console.log(t.yellow(`Could not load config: ${o.message}`))}let{outputAbs:i}=g(n,s),a=u(i);if(console.log(t.bold.cyan(`
2
2
  Run capacity wait queue`)),console.log(t.gray(`Output: ${i}
3
3
  `)),a.length===0){console.log(t.gray(`(empty \u2014 no CLI processes are waiting for capacity)
4
- `));return}for(const o of a){const e=[t.cyan(String(o.id||"").slice(0,8)),o.specHint?t.white(o.specHint):"",o.source?t.gray(`[${o.source}]`):"",o.studioTestCaseId?t.gray(`tc:${String(o.studioTestCaseId).slice(0,8)}\u2026`):"",`pid ${o.pid}`].filter(Boolean).join(" ");console.log(e)}console.log()}export{C as runCapacityQueueListCommand};
4
+ `));return}for(let o of a){let e=[t.cyan(String(o.id||"").slice(0,8)),o.specHint?t.white(o.specHint):"",o.source?t.gray(`[${o.source}]`):"",o.studioTestCaseId?t.gray(`tc:${String(o.studioTestCaseId).slice(0,8)}\u2026`):"",`pid ${o.pid}`].filter(Boolean).join(" ");console.log(e)}console.log()}export{C as runCapacityQueueListCommand};
@@ -1,76 +1,78 @@
1
- import{runTest as Ie,logger as $,DEFAULT_OUTPUT_BASE as me,SESSIONS_DIR as ve}from"@zibby/core";import{zibbyScratchSpecsDir as W}from"@zibby/core/constants/zibby-scratch.js";import{createCliRunIndexPipelineProgressAppender as _e,postCliInterruptedRunIndex as te}from"@zibby/core/utils/run-index-post-cli.js";import{composePipelineProgressWithStudioCliLog as ne}from"../utils/studio-cli-log-mirror.js";import{registerChatOrchestratedRun as xe,unregisterChatOrchestratedRun as $e}from"../utils/chat-run-lifecycle.js";import{readFileSync as _,existsSync as p,statSync as se,mkdirSync as re,writeFileSync as le,appendFileSync as Pe,rmSync as ce}from"fs";import{resolve as T,join as A,dirname as Ee,isAbsolute as ie}from"path";import{fileURLToPath as Ae}from"url";import{glob as q}from"glob";import e from"chalk";import ae from"ora";import Se from"dotenv";import be from"open";import{getApiUrl as J,getAccountApiUrl as Te,getCurrentEnvironment as de,getFrontendUrl as ue}from"../config/environments.js";import{getSessionToken as ge,getUserInfo as pe}from"../config/config.js";const Ce=Ae(import.meta.url),ke=Ee(Ce),Ue=JSON.parse(_(A(ke,"../../package.json"),"utf-8"));function Oe(n){const o=l=>l?typeof l.message=="string"&&l.message.includes("Interrupted by user")?!0:Array.isArray(l.errors)?l.errors.some(o):l.cause?o(l.cause):!1:!1;return o(n)}function fe(n,o){if(n==null)return null;const l=String(n).trim();return l?ie(l)?l:T(o,l):null}function Be(n,o){try{if(!n||!p(n))return;const l=A(n,"studio-cli.log"),w=`
1
+ import{runTest as Ve,logger as U,DEFAULT_OUTPUT_BASE as He,SESSIONS_DIR as We}from"@zibby/core";import{zibbyScratchSpecsDir as ce}from"@zibby/core/constants/zibby-scratch.js";import{createCliRunIndexPipelineProgressAppender as qe,postCliInterruptedRunIndex as _e}from"@zibby/core/utils/run-index-post-cli.js";import{createWriteStream as Ne,mkdirSync as ke}from"fs";import{join as ue,isAbsolute as Be}from"path";var Oe="studio-cli.log";function Re(t,o){if(!t||typeof t!="string")return null;let s=t.trim();return s?Be(s)?s:ue(o,s):null}function je(t){if(!t)return()=>{};ke(t,{recursive:!0});let o=ue(t,Oe),s=Ne(o,{flags:"a"}),l=process.stdout.write.bind(process.stdout),c=process.stderr.write.bind(process.stderr),a=n=>function(g,b,O){typeof b=="function"&&(O=b,b=void 0);try{Buffer.isBuffer(g)?s.write(g):s.write(String(g),b||"utf8")}catch{}return n(g,b,O)};return process.stdout.write=a(l),process.stderr.write=a(c),()=>{process.stdout.write=l,process.stderr.write=c;try{s.end()}catch{}}}function Q(t,o,s){let l=null;function c(a){if(!l&&a?.sessionPath){let n=Re(a.sessionPath,o);n&&(l=je(n))}typeof t=="function"&&t(a)}return c.dispose=()=>{typeof l=="function"&&(l(),l=null)},c}import{existsSync as de,mkdirSync as Ye,readFileSync as Fe,readdirSync as vo,unlinkSync as Le,writeFileSync as pe}from"fs";import{join as fe}from"path";import{DEFAULT_OUTPUT_BASE as De}from"@zibby/core";function ge(t){return t?.paths?.output||De}function ee(t,o,s){return fe(t,o,`.zibby-chat-run-pids-${s}.json`)}function he(t,o,s){let l=ee(t,o,s);if(!de(l))return[];try{let c=JSON.parse(Fe(l,"utf8"));return(Array.isArray(c?.pids)?c.pids:[]).map(n=>Number(n)).filter(n=>Number.isFinite(n)&&n>0)}catch{return[]}}function ye(t,o,s,l={}){let c=Number(o),a=Number(s);if(!Number.isFinite(c)||c<=0||!Number.isFinite(a)||a<=0)return;let n=ge(l),_=fe(t,n);Ye(_,{recursive:!0});let g=he(t,n,c);g.includes(a)||g.push(a),pe(ee(t,n,c),`${JSON.stringify({v:1,pids:g})}
2
+ `,"utf8")}function me(t,o,s,l={}){let c=Number(o),a=Number(s);if(!Number.isFinite(c)||c<=0||!Number.isFinite(a)||a<=0)return;let n=ge(l),_=ee(t,n,c);if(!de(_))return;let g=he(t,n,c).filter(b=>b!==a);if(g.length===0)try{Le(_)}catch{}else pe(_,`${JSON.stringify({v:1,pids:g})}
3
+ `,"utf8")}import{readFileSync as A,existsSync as m,statSync as xe,mkdirSync as Pe,writeFileSync as be,appendFileSync as Je,rmSync as Ae}from"fs";import{resolve as k,join as C,dirname as Xe,isAbsolute as Ee}from"path";import{fileURLToPath as Qe}from"url";import{glob as q}from"glob";import e from"chalk";import Ue from"ora";import eo from"dotenv";import oo 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.app",description:"Production environment"}};function H(){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 Ie(){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 oe(){let t=process.env.ZIBBY_ENV||"prod";return S[t]||S.prod}function te(){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 l=["zibby.app","studio.zibby.app","studio-staging.zibby.app"],c=o.hostname;if(!l.some(n=>c===n||c.endsWith(`.${n}`))&&!c.includes("localhost")&&c!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${c}`),"https://studio.zibby.app"}return t}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${t}`),S.local.frontendUrl}}import{existsSync as Ge,mkdirSync as Ao,readFileSync as ze,writeFileSync as Eo}from"fs";import{homedir as we}from"os";import{join as W}from"path";function Ke(){return process.env.ZIBBY_CONFIG_DIR||W(we(),".zibby")}function Me(){return W(Ke(),"config.json")}var Ze=W(we(),".zibby"),To=W(Ze,"config.json");function ve(){try{let t=Me();if(Ge(t)){let o=ze(t,"utf-8");return JSON.parse(o)}}catch{}return{}}function ne(){return ve().sessionToken||null}function se(){return ve().user||null}var to=Qe(import.meta.url),no=Xe(to),so=JSON.parse(A(C(no,"../../package.json"),"utf-8"));function ro(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 Se(t,o){if(t==null)return null;let s=String(t).trim();return s?Ee(s)?s:k(o,s):null}function io(t,o){try{if(!t||!m(t))return;let s=C(t,"studio-cli.log"),l=`
2
4
  [CLI_FATAL] ${new Date().toISOString()}
3
5
  Error: ${String(o?.message||o)}
4
6
  ${o?.stack?`${String(o.stack)}
5
- `:""}`;Pe(l,w,"utf8")}catch{}}process.env.DOTENV_CONFIG_QUIET="true";const je=process.env.NODE_ENV||"development",Re=[T(process.cwd(),".env.local"),T(process.cwd(),`.env.${je}`),T(process.cwd(),".env")];Re.forEach(n=>{p(n)&&Se.config({path:n,override:!1})});function Ye(n,o){const l=o?.paths?.specs||"test-specs",w=o?.paths?.generated||"tests";return n.replace(l,w).replace(/\.txt$/,".spec.js")}async function Ne(n,o){const l=ue(),w=/^[0-9A-HJKMNP-TV-Z]{26}$/,S=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(!w.test(n)&&!S.test(n))return console.log(e.red(`
7
+ `:""}`;Je(s,l,"utf8")}catch{}}process.env.DOTENV_CONFIG_QUIET="true";var co=process.env.NODE_ENV||"development",lo=[k(process.cwd(),".env.local"),k(process.cwd(),`.env.${co}`),k(process.cwd(),".env")];lo.forEach(t=>{m(t)&&eo.config({path:t,override:!1})});function ao(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 uo(t,o){let s=te(),l=/^[0-9A-HJKMNP-TV-Z]{26}$/,c=/^[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)&&!c.test(t))return console.log(e.red(`
6
8
  \u274C Invalid execution ID format (security check)
7
- `)),!1;if(!S.test(o))return console.log(e.red(`
9
+ `)),!1;if(!c.test(o))return console.log(e.red(`
8
10
  \u274C Invalid project ID format (security check)
9
- `)),!1;const I=new URL(l);if(!l.includes("localhost")&&!l.includes("127.0.0.1")&&I.protocol!=="https:")return console.log(e.red(`
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(`
10
12
  \u274C Frontend URL must use HTTPS in production
11
- `)),!1;const k=`${l}/projects/${o}/runs/${n}`;try{return console.log(e.cyan(`
12
- Opening test results in browser...`)),console.log(e.gray(` ${k}
13
- `)),await be(k),!0}catch{return console.log(e.yellow("Could not open browser automatically")),console.log(e.gray(` Please open manually: ${k}
14
- `)),!1}}function X(n,o){const l=o?.paths?.specs||"test-specs",w=o?.paths?.generated||"tests";return n.replace(w,l).replace(/\.spec\.js$/,".txt")}async function Ge({apiKey:n,specPath:o,fullSpecPath:l,collectionIdOrName:w,folder:S,agent:I,config:r,result:k,shouldOpen:B}){const R=J(),N=de(),F=process.env.ZIBBY_USER_TOKEN||ge(),U=pe();console.log(U?e.gray(`Authenticated: ${U.email} (${U.name||"User"})`):e.gray("Authenticated: Using Personal Access Token"));const f=ae(`Uploading to ${N.name}...`).start();try{const a=process.cwd();let x=null;if(k?.state?.sessionPath){const s=k.state.sessionPath;x=s.startsWith(a)?s.slice(a.length+1):s}if(!x){const d=`${r.paths?.output||me}/${ve}/*`,b=q.sync(d,{cwd:a}).filter(E=>se(A(a,E)).isDirectory()&&!/session_/.test(E)).map(E=>({path:E,stat:se(A(a,E))})).sort((E,oe)=>oe.stat.mtimeMs-E.stat.mtimeMs);if(b.length===0){f.warn("No session folder found, skipping upload");return}x=b[0].path}let P=q.sync(`${x}/execute_live/videos/*.webm`,{cwd:a});P.length===0&&(P=q.sync(`${x}/execute_live/*.webm`,{cwd:a})),P.length===0&&(P=q.sync(`${x}/*.webm`,{cwd:a}));const O=A(a,x,"execute_live","events.json"),G=A(a,x,"execute_live","result.json"),Y=A(a,x,"title.txt"),M=Ye(o,r),t=A(a,M),c=p(t);if(P.length===0){f.warn("No video file found in session folder, skipping upload");return}const u=A(a,P[0]),m=p(Y)?_(Y,"utf-8").trim():null;$.debug(`Video exists: ${p(u)}`),$.debug(`Events exists: ${p(O)}`);let h=null,j=null;if(w){f.text="Resolving collection...";const s=Te(),d=await fetch(`${s}/collections/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({collectionIdOrName:w})});if(!d.ok){const E=await d.json().catch(()=>({}));throw new Error(E.error||"Failed to resolve collection")}const b=await d.json();h=b.collectionId,j=b.collectionName,b.isNew&&(f.text=`Created new collection: ${j}`)}f.text="Preparing upload...";const g={video:p(u)?_(u).length:0,events:p(O)?_(O).length:0,instructions:(()=>{const s=X(o,r),d=A(a,s);return p(d)?_(d).length:0})(),result:p(G)?_(G).length:0},v=g.video+g.events+g.instructions+g.result,Z=(v/1024/1024).toFixed(2);if(g.video>50*1024*1024)throw new Error(`Video file too large: ${(g.video/1024/1024).toFixed(2)}MB (max: 50MB)`);if(v>60*1024*1024)throw new Error(`Total upload size too large: ${Z}MB (max: 60MB)`);f.text=`Getting upload URLs... (${Z}MB)`;const i={"Content-Type":"application/json",Authorization:`Bearer ${n}`};F&&(i["X-User-Token"]=F);const y=typeof I=="object"?I.provider:I||"cursor",z=typeof I=="object"&&I[y]?.model||null,he=z==="auto"?null:z,L=await fetch(`${R}/executions/upload`,{method:"POST",headers:i,body:JSON.stringify({collectionId:h||null,specPath:o,specContent:(()=>{const s=X(o,r),d=A(a,s);return p(d)?_(d,"utf-8"):p(l)?_(l,"utf-8"):""})(),title:m||null,agentType:y,model:he,metadata:{agent:I||"cursor",timestamp:new Date().toISOString(),folder:S||null,collectionName:j||null},fileSizes:g})});if(!L.ok){const s=await L.json();if(L.status===413)throw s.details&&Array.isArray(s.details)?new Error(`File size limit exceeded:
15
- ${s.details.map(d=>` \u2022 ${d}`).join(`
13
+ `)),!1;let _=`${s}/projects/${o}/runs/${t}`;try{return console.log(e.cyan(`
14
+ Opening test results in browser...`)),console.log(e.gray(` ${_}
15
+ `)),await oo(_),!0}catch{return console.log(e.yellow("Could not open browser automatically")),console.log(e.gray(` Please open manually: ${_}
16
+ `)),!1}}function re(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 po({apiKey:t,specPath:o,fullSpecPath:s,collectionIdOrName:l,folder:c,agent:a,config:n,result:_,shouldOpen:g}){let b=H(),O=oe(),M=process.env.ZIBBY_USER_TOKEN||ne(),R=se();console.log(R?e.gray(`Authenticated: ${R.email} (${R.name||"User"})`):e.gray("Authenticated: Using Personal Access Token"));let I=Ue(`Uploading to ${O.name}...`).start();try{let p=process.cwd(),E=null;if(_?.state?.sessionPath){let i=_.state.sessionPath;E=i.startsWith(p)?i.slice(p.length+1):i}if(!E){let f=`${n.paths?.output||He}/${We}/*`,N=q.sync(f,{cwd:p}).filter(T=>xe(C(p,T)).isDirectory()&&!/session_/.test(T)).map(T=>({path:T,stat:xe(C(p,T))})).sort((T,ae)=>ae.stat.mtimeMs-T.stat.mtimeMs);if(N.length===0){I.warn("No session folder found, skipping upload");return}E=N[0].path}let $=q.sync(`${E}/execute_live/videos/*.webm`,{cwd:p});$.length===0&&($=q.sync(`${E}/execute_live/*.webm`,{cwd:p})),$.length===0&&($=q.sync(`${E}/*.webm`,{cwd:p}));let j=C(p,E,"execute_live","events.json"),L=C(p,E,"execute_live","result.json"),F=C(p,E,"title.txt"),Z=ao(o,n),r=C(p,Z),u=m(r);if($.length===0){I.warn("No video file found in session folder, skipping upload");return}let h=C(p,$[0]),x=m(F)?A(F,"utf-8").trim():null;U.debug(`Video exists: ${m(h)}`),U.debug(`Events exists: ${m(j)}`);let w=null,Y=null;if(l){I.text="Resolving collection...";let i=Ie(),f=await fetch(`${i}/collections/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({collectionIdOrName:l})});if(!f.ok){let T=await f.json().catch(()=>({}));throw new Error(T.error||"Failed to resolve collection")}let N=await f.json();w=N.collectionId,Y=N.collectionName,N.isNew&&(I.text=`Created new collection: ${Y}`)}I.text="Preparing upload...";let y={video:m(h)?A(h).length:0,events:m(j)?A(j).length:0,instructions:(()=>{let i=re(o,n),f=C(p,i);return m(f)?A(f).length:0})(),result:m(L)?A(L).length:0},P=y.video+y.events+y.instructions+y.result,V=(P/1024/1024).toFixed(2);if(y.video>50*1024*1024)throw new Error(`Video file too large: ${(y.video/1024/1024).toFixed(2)}MB (max: 50MB)`);if(P>60*1024*1024)throw new Error(`Total upload size too large: ${V}MB (max: 60MB)`);I.text=`Getting upload URLs... (${V}MB)`;let d={"Content-Type":"application/json",Authorization:`Bearer ${t}`};M&&(d["X-User-Token"]=M);let v=typeof a=="object"?a.provider:a||"cursor",z=typeof a=="object"&&a[v]?.model||null,$e=z==="auto"?null:z,K=await fetch(`${b}/executions/upload`,{method:"POST",headers:d,body:JSON.stringify({collectionId:w||null,specPath:o,specContent:(()=>{let i=re(o,n),f=C(p,i);return m(f)?A(f,"utf-8"):m(s)?A(s,"utf-8"):""})(),title:x||null,agentType:v,model:$e,metadata:{agent:a||"cursor",timestamp:new Date().toISOString(),folder:c||null,collectionName:Y||null},fileSizes:y})});if(!K.ok){let i=await K.json();if(K.status===413)throw i.details&&Array.isArray(i.details)?new Error(`File size limit exceeded:
17
+ ${i.details.map(f=>` \u2022 ${f}`).join(`
16
18
  `)}
17
19
 
18
- Compress your files or reduce recording quality.`):new Error(s.error||"Upload files too large");if(L.status===429){if(s.quotaInfo)throw new Error(`Video verification quota exceeded (${s.quotaInfo.used}/${s.quotaInfo.limit}).
19
- Plan: ${s.quotaInfo.planId}. Resets: ${new Date(s.quotaInfo.periodEnd).toLocaleDateString()}
20
- Upgrade at: https://studio.zibby.app/billing`);if(s.storageInfo){const d=(s.storageInfo.used/1073741824).toFixed(2),b=(s.storageInfo.limit/(1024*1024*1024)).toFixed(2),E=(s.storageInfo.uploadSize/(1024*1024)).toFixed(2);throw new Error(`Storage quota would be exceeded.
21
- Current usage: ${d}GB / ${b}GB
22
- This upload: ${E}MB
23
- Plan: ${s.storageInfo.planId}
24
- Upgrade at: https://studio.zibby.app/billing`)}}throw new Error(s.error||"Failed to initiate upload")}const{executionId:K,uploadUrls:C,isOrphan:ye,projectId:H}=await L.json();f.text=`Uploading video... (${K})`;const V=_(u);$.debug(`Video buffer size: ${V.length} bytes`),$.debug("Upload URL received (redacted)");const D=await fetch(C.video,{method:"PUT",body:V,headers:{"Content-Type":"video/webm","Content-Length":V.length.toString()}});if($.debug(`Video upload status: ${D.status} ${D.statusText}`),!D.ok){const s=await D.text();throw new Error(`Failed to upload video: ${D.status} ${D.statusText} - ${s}`)}if($.info("Video uploaded successfully"),p(O)&&C.events){f.text="Uploading events...";const s=_(O),d=await fetch(C.events,{method:"PUT",body:s,headers:{"Content-Type":"application/json","Content-Length":s.length.toString()}});if($.debug(`Events upload status: ${d.status} ${d.statusText}`),!d.ok)throw new Error("Failed to upload events");$.info("Events uploaded successfully")}else $.debug(`Skipping events upload - exists: ${p(O)}, hasUrl: ${!!C.events}`);if(c&&C.generatedTest){f.text="Uploading generated test...";const s=_(t);if(!(await fetch(C.generatedTest,{method:"PUT",body:s,headers:{"Content-Type":"application/javascript","Content-Length":s.length.toString()}})).ok)throw new Error("Failed to upload generated test")}if(C.testInstructions){const s=X(o,r),d=A(a,s);if(p(d)){f.text="Uploading test instructions...";const b=_(d);(await fetch(C.testInstructions,{method:"PUT",body:b,headers:{"Content-Type":"text/plain","Content-Length":b.length.toString()}})).ok?$.debug("Test instructions uploaded successfully"):$.warn("Failed to upload test instructions (non-blocking)")}else console.log(`\u2139\uFE0F No source test instructions found at ${s}`)}if(C.result&&p(G)){f.text="Uploading test results...";const s=_(G);(await fetch(C.result,{method:"PUT",body:s,headers:{"Content-Type":"application/json","Content-Length":s.length.toString()}})).ok?$.debug("result.json uploaded successfully"):$.warn("Failed to upload result.json (non-blocking)")}if(f.text="Confirming upload...",!(await fetch(`${R}/executions/${K}/confirm`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({status:"completed",metadata:{uploadedAt:new Date().toISOString()},fileSizes:g})})).ok)throw new Error("Failed to confirm upload");f.succeed("Uploaded to Zibby Cloud!"),console.log(e.gray(`
25
- ${"\u2501".repeat(50)}`)),console.log(e.white(`Execution ID: ${e.cyan(K)}`));const ee=ue();console.log(ye?e.white(`Location: ${e.yellow("History tab")}`):e.white(`Collection: ${e.cyan(h)}`));const we=H?`${ee}/projects/${H}/runs/${K}`:`${ee}/history?execution=${K}`;return console.log(e.white(`View execution: ${e.cyan(we)}`)),console.log(e.gray(`${"\u2501".repeat(50)}
26
- `)),{success:!0,executionId:K,projectId:H||null}}catch(a){return f.fail("Upload failed"),console.log(e.red(` ${a.message}`)),process.env.DEBUG&&console.log(e.gray(` Stack: ${a.stack}`)),console.log(e.gray(` Continuing without upload...
27
- `)),{success:!1}}}async function Ke(n,o,l){const w=J(),S=o.join(","),I=await fetch(`${w}/executions/${n}/test-cases?ids=${S}`,{headers:{Authorization:`Bearer ${l}`}});if(!I.ok)throw new Error(`Failed to fetch test cases: ${I.status} ${I.statusText}`);return(await I.json()).testCases||[]}async function De(n,o){const l=de();if(console.log(e.bold.cyan(`
20
+ Compress your files or reduce recording quality.`):new Error(i.error||"Upload files too large");if(K.status===429){if(i.quotaInfo)throw new Error(`Video verification quota exceeded (${i.quotaInfo.used}/${i.quotaInfo.limit}).
21
+ Plan: ${i.quotaInfo.planId}. Resets: ${new Date(i.quotaInfo.periodEnd).toLocaleDateString()}
22
+ Upgrade at: https://studio.zibby.app/billing`);if(i.storageInfo){let f=(i.storageInfo.used/1073741824).toFixed(2),N=(i.storageInfo.limit/(1024*1024*1024)).toFixed(2),T=(i.storageInfo.uploadSize/(1024*1024)).toFixed(2);throw new Error(`Storage quota would be exceeded.
23
+ Current usage: ${f}GB / ${N}GB
24
+ This upload: ${T}MB
25
+ Plan: ${i.storageInfo.planId}
26
+ Upgrade at: https://studio.zibby.app/billing`)}}throw new Error(i.error||"Failed to initiate upload")}let{executionId:D,uploadUrls:B,isOrphan:Te,projectId:J}=await K.json();I.text=`Uploading video... (${D})`;let X=A(h);U.debug(`Video buffer size: ${X.length} bytes`),U.debug("Upload URL received (redacted)");let G=await fetch(B.video,{method:"PUT",body:X,headers:{"Content-Type":"video/webm","Content-Length":X.length.toString()}});if(U.debug(`Video upload status: ${G.status} ${G.statusText}`),!G.ok){let i=await G.text();throw new Error(`Failed to upload video: ${G.status} ${G.statusText} - ${i}`)}if(U.info("Video uploaded successfully"),m(j)&&B.events){I.text="Uploading events...";let i=A(j),f=await fetch(B.events,{method:"PUT",body:i,headers:{"Content-Type":"application/json","Content-Length":i.length.toString()}});if(U.debug(`Events upload status: ${f.status} ${f.statusText}`),!f.ok)throw new Error("Failed to upload events");U.info("Events uploaded successfully")}else U.debug(`Skipping events upload - exists: ${m(j)}, hasUrl: ${!!B.events}`);if(u&&B.generatedTest){I.text="Uploading generated test...";let i=A(r);if(!(await fetch(B.generatedTest,{method:"PUT",body:i,headers:{"Content-Type":"application/javascript","Content-Length":i.length.toString()}})).ok)throw new Error("Failed to upload generated test")}if(B.testInstructions){let i=re(o,n),f=C(p,i);if(m(f)){I.text="Uploading test instructions...";let N=A(f);(await fetch(B.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 ${i}`)}if(B.result&&m(L)){I.text="Uploading test results...";let i=A(L);(await fetch(B.result,{method:"PUT",body:i,headers:{"Content-Type":"application/json","Content-Length":i.length.toString()}})).ok?U.debug("result.json uploaded successfully"):U.warn("Failed to upload result.json (non-blocking)")}if(I.text="Confirming upload...",!(await fetch(`${b}/executions/${D}/confirm`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({status:"completed",metadata:{uploadedAt:new Date().toISOString()},fileSizes:y})})).ok)throw new Error("Failed to confirm upload");I.succeed("Uploaded to Zibby Cloud!"),console.log(e.gray(`
27
+ ${"\u2501".repeat(50)}`)),console.log(e.white(`Execution ID: ${e.cyan(D)}`));let le=te();console.log(Te?e.white(`Location: ${e.yellow("History tab")}`):e.white(`Collection: ${e.cyan(w)}`));let Ce=J?`${le}/projects/${J}/runs/${D}`:`${le}/history?execution=${D}`;return console.log(e.white(`View execution: ${e.cyan(Ce)}`)),console.log(e.gray(`${"\u2501".repeat(50)}
28
+ `)),{success:!0,executionId:D,projectId:J||null}}catch(p){return I.fail("Upload failed"),console.log(e.red(` ${p.message}`)),process.env.DEBUG&&console.log(e.gray(` Stack: ${p.stack}`)),console.log(e.gray(` Continuing without upload...
29
+ `)),{success:!1}}}async function fo(t,o,s){let l=H(),c=o.join(","),a=await fetch(`${l}/executions/${t}/test-cases?ids=${c}`,{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 go(t,o){let s=oe();if(console.log(e.bold.cyan(`
28
30
  Zibby Test Automation
29
- `)),console.log(e.gray(`@zibby/cli v${Ue.version} | Node.js ${process.version}`)),console.log(e.gray("\u2501".repeat(50))),o.sources){o.execution||(console.log(e.red(`
31
+ `)),console.log(e.gray(`@zibby/cli v${so.version} | Node.js ${process.version}`)),console.log(e.gray("\u2501".repeat(50))),o.sources){o.execution||(console.log(e.red(`
30
32
  \u274C --execution <id> is required when using --sources
31
- `)),process.exit(1));const t=o.project||process.env.ZIBBY_API_KEY;t||(console.log(e.red(`
33
+ `)),process.exit(1));let r=o.project||process.env.ZIBBY_API_KEY;r||(console.log(e.red(`
32
34
  \u274C --project <id> or ZIBBY_API_KEY required when using --sources
33
- `)),process.exit(1));const c=o.sources.split(",").map(h=>h.trim());console.log(e.white(`Fetching ${c.length} test case(s) from execution ${e.cyan(o.execution)}...`));const u=await Ke(o.execution,c,t);u.length===0&&(console.log(e.red(`
35
+ `)),process.exit(1));let u=o.sources.split(",").map(w=>w.trim());console.log(e.white(`Fetching ${u.length} test case(s) from execution ${e.cyan(o.execution)}...`));let h=await fo(o.execution,u,r);h.length===0&&(console.log(e.red(`
34
36
  No test cases found for the given IDs
35
- `)),process.exit(1)),console.log(e.green(`\u2713 Fetched ${u.length} test case(s)`));const m=W(process.cwd());re(m,{recursive:!0});for(const h of u){const j=`# ${h.title}
37
+ `)),process.exit(1)),console.log(e.green(`\u2713 Fetched ${h.length} test case(s)`));let x=ce(process.cwd());Pe(x,{recursive:!0});for(let w of h){let Y=`# ${w.title}
36
38
 
37
- ${h.content}`,g=T(m,`${h.id}.txt`);le(g,j,"utf-8"),console.log(e.gray("\u2501".repeat(50))),console.log(e.white(`
38
- Running: ${e.cyan(h.title)} (${h.id})`));const v={...o,sources:void 0,execution:void 0};v.sync=!0,await De(g,v)}ce(m,{recursive:!0,force:!0});return}!n&&!o.sources&&(console.log(e.red(`
39
+ ${w.content}`,y=k(x,`${w.id}.txt`);be(y,Y,"utf-8"),console.log(e.gray("\u2501".repeat(50))),console.log(e.white(`
40
+ Running: ${e.cyan(w.title)} (${w.id})`));let P={...o,sources:void 0,execution:void 0};P.sync=!0,await go(y,P)}Ae(x,{recursive:!0,force:!0});return}!t&&!o.sources&&(console.log(e.red(`
39
41
  \u274C Missing test spec path
40
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
41
- `)),process.exit(1));const w=n&&!n.endsWith(".txt")&&!p(T(process.cwd(),n))&&n.includes(" ");if(w){const t=W(process.cwd());re(t,{recursive:!0});const c=T(t,`inline-${Date.now()}.txt`);le(c,n,"utf-8"),n=c}const S=T(process.cwd(),n);p(S)||(console.log(e.red(`
42
- \u274C Test spec not found: ${n}
43
- `)),process.exit(1));const I=_(S,"utf-8");let r={headless:o.headless||!1,playwrightArtifacts:!0};const k=T(process.cwd(),o.config);if(p(k))try{const t=await import(k),c=u=>u?.provider?u.provider:u?.gemini?"gemini":u?.codex?"codex":u?.claude?"claude":u?.cursor?"cursor":null;r={...r,...t.default,agent:t.default?.agent?{...t.default.agent,provider:o.agent||c(t.default.agent)}:{provider:o.agent||"cursor"},mcp:t.default?.browser?.mcp||"playwright",headless:o.headless!==void 0?o.headless:t.default?.browser?.headless,paths:t.default?.paths||{specs:"test-specs",generated:"tests"},cloudSync:t.default?.cloudSync||!1}}catch{console.log(e.yellow(`\u26A0\uFE0F Could not load config from ${o.config}`)),r.agent={provider:o.agent||"cursor"},r.cloudSync=!1}else r.agent={provider:o.agent||"cursor"},r.cloudSync=!1;let B=process.env.ZIBBY_API_KEY;const R=o.sync||r.cloudSync===!0&&o.sync!==!1;if(o.project&&o.project.startsWith("zby_")&&(B=o.project,console.log(e.gray("Using --project as API token (overriding .env)"))),R&&!B&&(console.log(e.red(`
43
+ `)),process.exit(1));let l=t&&!t.endsWith(".txt")&&!m(k(process.cwd(),t))&&t.includes(" ");if(l){let r=ce(process.cwd());Pe(r,{recursive:!0});let u=k(r,`inline-${Date.now()}.txt`);be(u,t,"utf-8"),t=u}let c=k(process.cwd(),t);m(c)||(console.log(e.red(`
44
+ \u274C Test spec not found: ${t}
45
+ `)),process.exit(1));let a=A(c,"utf-8"),n={headless:o.headless||!1,playwrightArtifacts:!0},_=k(process.cwd(),o.config);if(m(_))try{let r=await import(_),u=h=>h?.provider?h.provider:h?.gemini?"gemini":h?.codex?"codex":h?.claude?"claude":h?.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 g=process.env.ZIBBY_API_KEY,b=o.sync||n.cloudSync===!0&&o.sync!==!1;if(o.project&&o.project.startsWith("zby_")&&(g=o.project,console.log(e.gray("Using --project as API token (overriding .env)"))),b&&!g&&(console.log(e.red(`
44
46
  \u274C Error: Cloud sync is enabled but ZIBBY_API_KEY not set
45
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
46
48
  `)),console.log(e.white("Option 1: Add to .env file:")),console.log(e.gray(` ZIBBY_API_KEY=zby_your_key_here
47
49
  `)),console.log(e.white("Option 2: Disable cloud sync:")),console.log(e.gray(` Edit .zibby.config.js \u2192 cloudSync: false
48
50
  `)),console.log(e.white(`Get your API key from: https://zibby.dev/dashboard
49
- `)),process.exit(1)),R&&B){let t=process.env.ZIBBY_USER_TOKEN,c;t?console.log(e.gray("Using Personal Access Token from ZIBBY_USER_TOKEN")):(t=ge(),c=pe(),(!t||!c)&&(console.log(e.red(`
51
+ `)),process.exit(1)),b&&g){let r=process.env.ZIBBY_USER_TOKEN,u;r?console.log(e.gray("Using Personal Access Token from ZIBBY_USER_TOKEN")):(r=ne(),u=se(),(!r||!u)&&(console.log(e.red(`
50
52
  \u274C Error: User authentication required for uploads
51
53
  `)),console.log(e.gray(`Choose one of these options:
52
54
  `)),console.log(e.cyan(" Option 1 (Local Development):")),console.log(e.gray(` zibby login
53
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.app/settings/tokens")),console.log(e.gray(" 2. Set environment variable:")),console.log(e.gray(` export ZIBBY_USER_TOKEN=zby_pat_xxxxx
54
- `)),process.exit(1)),c&&console.log(e.gray(`Authenticated: ${c.email} (${c.name||"User"})`)))}if(R&&B){const t=J();try{B.startsWith("zby_")||(console.log(e.red(`
56
+ `)),process.exit(1)),u&&console.log(e.gray(`Authenticated: ${u.email} (${u.name||"User"})`)))}if(b&&g){let r=H();try{g.startsWith("zby_")||(console.log(e.red(`
55
57
  \u274C Invalid API token format
56
58
  `)),console.log(e.white('This CLI requires a project API token (starts with "zby_").')),console.log(e.gray(` Format: zby_***
57
59
  `)),console.log(e.white(`Get your project API token from settings:
58
60
  `)),console.log(e.gray(" Local: http://localhost:3001/settings")),console.log(e.gray(` Prod: https://app.zibby.app/settings
59
- `)),process.exit(1));const c=await fetch(`${t}/projects`,{headers:{Authorization:`Bearer ${B}`}});c.ok||(console.log(e.red(`
61
+ `)),process.exit(1));let u=await fetch(`${r}/projects`,{headers:{Authorization:`Bearer ${g}`}});u.ok||(console.log(e.red(`
60
62
  \u274C Unauthorized: Invalid project API token
61
63
  `)),console.log(e.white("Your project API token is invalid or does not have access.")),console.log(e.gray(` Token format: zby_***
62
64
  `)),console.log(e.white(`Get your project API token from settings:
63
65
  `)),console.log(e.gray(" Local: http://localhost:3001/settings")),console.log(e.gray(` Prod: https://app.zibby.app/settings
64
- `)),process.exit(1));const m=(await c.json()).projects||[];(!m||m.length===0)&&(console.log(e.red(`
66
+ `)),process.exit(1));let x=(await u.json()).projects||[];(!x||x.length===0)&&(console.log(e.red(`
65
67
  \u274C No projects found for this token
66
- `)),process.exit(1));const h=m[0];console.log(e.green(`\u2713 Authorized for project: ${h.name} (${h.projectId})`))}catch(c){console.log(e.red(`
67
- \u274C Failed to validate API credentials: ${c.message}
68
- `)),process.exit(1)}}const N=typeof r.agent=="object"?r.agent.provider:r.agent;if(N==="claude"&&!process.env.ANTHROPIC_API_KEY&&(console.log(e.red(`
68
+ `)),process.exit(1));let w=x[0];console.log(e.green(`\u2713 Authorized for project: ${w.name} (${w.projectId})`))}catch(u){console.log(e.red(`
69
+ \u274C Failed to validate API credentials: ${u.message}
70
+ `)),process.exit(1)}}let O=typeof n.agent=="object"?n.agent.provider:n.agent;if(O==="claude"&&!process.env.ANTHROPIC_API_KEY&&(console.log(e.red(`
69
71
  \u274C Error: ANTHROPIC_API_KEY not set
70
72
  `)),console.log(e.white("Set your API key:")),console.log(e.gray(` export ANTHROPIC_API_KEY="sk-ant-..."
71
73
  `)),console.log(e.white("Or add to .env file:")),console.log(e.gray(` ANTHROPIC_API_KEY=sk-ant-...
72
74
  `)),console.log(e.white(`Get your API key from: https://console.anthropic.com/
73
- `)),process.exit(1)),N==="codex"){try{const{execSync:t}=await import("child_process");t("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"})}catch{console.log(e.red(`
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(`
74
76
  \u274C Error: Codex CLI not installed
75
77
  `)),console.log(e.white("Install the Codex CLI:")),console.log(e.gray(` npm install -g @openai/codex
76
78
  `)),console.log(e.white("Then verify:")),console.log(e.gray(` codex --version
@@ -79,7 +81,7 @@ Running: ${e.cyan(h.title)} (${h.id})`));const v={...o,sources:void 0,execution:
79
81
  `)),console.log(e.white("Set your API key:")),console.log(e.gray(` export OPENAI_API_KEY="sk-..."
80
82
  `)),console.log(e.white("Or add to .env file:")),console.log(e.gray(` OPENAI_API_KEY=sk-...
81
83
  `)),console.log(e.white(`Get your API key from: https://platform.openai.com/api-keys
82
- `)),process.exit(1))}if(N==="gemini"){if(process.env.GEMINI_API_KEY&&process.env.GOOGLE_API_KEY){const t=String(process.env.GEMINI_API_KEY).trim(),c=String(process.env.GOOGLE_API_KEY).trim();t&&c&&t!==c&&(process.env.GOOGLE_API_KEY=t,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{const{execSync:t}=await import("child_process");t("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"})}catch{console.log(e.red(`
84
+ `)),process.exit(1))}if(O==="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(`
83
85
  \u274C Error: Gemini CLI not installed
84
86
  `)),console.log(e.white("Install the Gemini CLI:")),console.log(e.gray(` npm install -g @google/gemini-cli
85
87
  `)),console.log(e.white("Then verify:")),console.log(e.gray(` gemini --version
@@ -88,25 +90,25 @@ Running: ${e.cyan(h.title)} (${h.id})`));const v={...o,sources:void 0,execution:
88
90
  `)),console.log(e.white("Set your API key:")),console.log(e.gray(` export GEMINI_API_KEY="your_key_here"
89
91
  `)),console.log(e.white("Or add to .env file:")),console.log(e.gray(` GEMINI_API_KEY=your_key_here
90
92
  `)),console.log(e.white(`Get your API key from: https://aistudio.google.com/app/apikey
91
- `)),process.exit(1))}if(N==="cursor"){const{checkCursorAgentInstalled:t,getCursorAgentInstallInstructions:c}=await import("@zibby/core");await t()||(console.log(e.red(c())),process.exit(1));const m=process.env.CI||process.env.GITLAB_CI||process.env.CIRCLECI||process.env.GITHUB_ACTIONS;process.env.CURSOR_API_KEY||(m?(console.log(e.red(`
93
+ `)),process.exit(1))}if(O==="cursor"){let{checkCursorAgentInstalled:r,getCursorAgentInstallInstructions:u}=await import("@zibby/core");await r()||(console.log(e.red(u())),process.exit(1));let x=process.env.CI||process.env.GITLAB_CI||process.env.CIRCLECI||process.env.GITHUB_ACTIONS;process.env.CURSOR_API_KEY||(x?(console.log(e.red(`
92
94
  \u274C Error: CURSOR_API_KEY not set
93
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"
94
96
  `)),console.log(e.white(`Get your API key from: https://cursor.com/settings
95
97
  `)),console.log(e.white(`Add it to your CI/CD environment variables.
96
98
  `)),process.exit(1)):console.log(e.yellow(`\u26A0\uFE0F CURSOR_API_KEY not set (using locally stored Cursor credentials)
97
- `)))}console.log(e.white(`Test Spec: ${e.cyan(n)}`));const F=typeof r.agent=="object"?r.agent.provider:r.agent;console.log(e.white(`Agent: ${e.cyan(F)}`)),console.log(e.white(`Browser: ${e.cyan(r.mcp||"playwright")} ${r.headless?e.gray("(headless)"):e.gray("(headed)")}`)),r.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 U;if(o.sessionPath!=null&&String(o.sessionPath).trim()!==""){const t=String(o.sessionPath).trim();U=ie(t)?T(t):T(process.cwd(),t),console.log(e.white(`Session path: ${e.cyan(U)}`))}console.log(e.gray("\u2501".repeat(50)));const f=ae({text:"Initializing...",stream:process.stdout}).start(),a=()=>{try{te({cwd:process.cwd(),config:r})}catch{}},x=process.env.ZIBBY_CHAT_OWNER_PID,P=x!=null&&String(x).trim()!==""?Number(x):null,O=P!=null&&Number.isFinite(P)&&P>0,G=()=>{if(O)try{$e(process.cwd(),P,process.pid,r)}catch{}};let Y=null,M=fe(U,process.cwd());try{f.stop();const{waitUntilRunCapacity:t}=await import("@zibby/core/utils/run-capacity-coordinator.js"),{basename:c}=await import("path");await t({cwd:process.cwd(),config:r,meta:{source:process.env.ZIBBY_RUN_SOURCE||"cli",specHint:n?c(n):"",studioTestCaseId:process.env.ZIBBY_STUDIO_TEST_CASE_ID||null},log:i=>console.log(e.gray(i))});const u=await import("@zibby/core/templates/browser-test-automation/graph.mjs").catch(()=>null);if(O)try{xe(process.cwd(),P,process.pid,r)}catch{}process.on("SIGINT",a),process.on("SIGTERM",a);const m=process.cwd(),h={},j=i=>{const y=fe(i?.sessionPath,m);y&&(M=y)};if(typeof r.onPipelineProgress=="function"){const i=ne(r.onPipelineProgress,m,r);Y=()=>i.dispose(),h.onPipelineProgress=y=>{j(y),i({...y,specPath:n,taskDescription:I})}}else if(r.runIndex?.pipelineProgress!==!1){const i=_e({cwd:m,config:r}),y=ne(i,m,r);Y=()=>y.dispose(),h.onPipelineProgress=z=>{j(z),y({...z,specPath:n,taskDescription:I})}}const g=await Ie(S,{...r,...h,specPath:n,apiKey:process.env.ANTHROPIC_API_KEY,autoApprove:o.autoApprove,force:o.autoApprove,singleNode:o.node,sessionId:o.session,...U?{sessionPath:U}:{},workflow:o.workflow,contextConfig:r.context,fallbackAgentModule:u});let v=g.outputPath||null;v&&(v=v.replace(/\/+/g,"/"),v.includes(process.cwd())&&(v=v.replace(`${process.cwd()}/`,"")));const Z=g.state?.generate_script?.scriptPath||g.state?.verify_script?.success;if(console.log(e.gray(`
98
- ${"\u2501".repeat(50)}`)),Z&&v)console.log(e.green("\u2713 Test execution completed")),console.log(e.white(`Generated test: ${e.cyan(v)}`)),g.toolCount!==void 0&&console.log(e.white(`Tools used: ${e.cyan(g.toolCount)}`)),console.log(e.gray(`${"\u2501".repeat(50)}
99
- `)),console.log(e.cyan("Next steps:")),console.log(e.white(` 1. Review generated test: ${v}`)),console.log(e.white(` 2. Run with Playwright: npx playwright test ${v}`)),console.log(e.white(` 3. View report: npx playwright show-report
100
- `));else{const i=g.state?.execute_live;i?i.steps?.length>0||i.actions?.length>0?(console.log(e.white(`
101
- Execution Summary:`)),console.log(e.white(` Steps: ${i.steps?.length||0}`)),console.log(e.white(` Actions: ${i.actions?.length||0}`)),i.finalUrl&&console.log(e.white(` Final URL: ${i.finalUrl}`)),i.notes&&console.log(e.white(`
102
- \u{1F4DD} ${i.notes}`))):(console.log(e.red("\u2716 Workflow did not complete")),console.log(e.yellow(`
103
- \u26A0\uFE0F ${i.notes||"Test execution failed"}`))):console.log(e.red("\u2716 Workflow did not complete")),console.log(e.gray(`${"\u2501".repeat(50)}
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 R;if(o.sessionPath!=null&&String(o.sessionPath).trim()!==""){let r=String(o.sessionPath).trim();R=Ee(r)?k(r):k(process.cwd(),r),console.log(e.white(`Session path: ${e.cyan(R)}`))}console.log(e.gray("\u2501".repeat(50)));let I=Ue({text:"Initializing...",stream:process.stdout}).start(),p=()=>{try{_e({cwd:process.cwd(),config:n})}catch{}},E=process.env.ZIBBY_CHAT_OWNER_PID,$=E!=null&&String(E).trim()!==""?Number(E):null,j=$!=null&&Number.isFinite($)&&$>0,L=()=>{if(j)try{me(process.cwd(),$,process.pid,n)}catch{}},F=null,Z=Se(R,process.cwd());try{I.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:d=>console.log(e.gray(d))});let h=await import("@zibby/core/templates/browser-test-automation/graph.mjs").catch(()=>null);if(j)try{ye(process.cwd(),$,process.pid,n)}catch{}process.on("SIGINT",p),process.on("SIGTERM",p);let x=process.cwd(),w={},Y=d=>{let v=Se(d?.sessionPath,x);v&&(Z=v)};if(typeof n.onPipelineProgress=="function"){let d=Q(n.onPipelineProgress,x,n);F=()=>d.dispose(),w.onPipelineProgress=v=>{Y(v),d({...v,specPath:t,taskDescription:a})}}else if(n.runIndex?.pipelineProgress!==!1){let d=qe({cwd:x,config:n}),v=Q(d,x,n);F=()=>v.dispose(),w.onPipelineProgress=z=>{Y(z),v({...z,specPath:t,taskDescription:a})}}let y=await Ve(c,{...n,...w,specPath:t,apiKey:process.env.ANTHROPIC_API_KEY,autoApprove:o.autoApprove,force:o.autoApprove,singleNode:o.node,sessionId:o.session,...R?{sessionPath:R}:{},workflow:o.workflow,contextConfig:n.context,fallbackAgentModule:h}),P=y.outputPath||null;P&&(P=P.replace(/\/+/g,"/"),P.includes(process.cwd())&&(P=P.replace(`${process.cwd()}/`,"")));let V=y.state?.generate_script?.scriptPath||y.state?.verify_script?.success;if(console.log(e.gray(`
100
+ ${"\u2501".repeat(50)}`)),V&&P)console.log(e.green("\u2713 Test execution completed")),console.log(e.white(`Generated test: ${e.cyan(P)}`)),y.toolCount!==void 0&&console.log(e.white(`Tools used: ${e.cyan(y.toolCount)}`)),console.log(e.gray(`${"\u2501".repeat(50)}
101
+ `)),console.log(e.cyan("Next steps:")),console.log(e.white(` 1. Review generated test: ${P}`)),console.log(e.white(` 2. Run with Playwright: npx playwright test ${P}`)),console.log(e.white(` 3. View report: npx playwright show-report
102
+ `));else{let d=y.state?.execute_live;d?d.steps?.length>0||d.actions?.length>0?(console.log(e.white(`
103
+ Execution Summary:`)),console.log(e.white(` Steps: ${d.steps?.length||0}`)),console.log(e.white(` Actions: ${d.actions?.length||0}`)),d.finalUrl&&console.log(e.white(` Final URL: ${d.finalUrl}`)),d.notes&&console.log(e.white(`
104
+ \u{1F4DD} ${d.notes}`))):(console.log(e.red("\u2716 Workflow did not complete")),console.log(e.yellow(`
105
+ \u26A0\uFE0F ${d.notes||"Test execution failed"}`))):console.log(e.red("\u2716 Workflow did not complete")),console.log(e.gray(`${"\u2501".repeat(50)}
104
106
  `))}if(o.node)console.log(e.gray(`
105
107
  Note: Upload skipped for single node execution`)),console.log(e.gray(` Run full workflow to upload all artifacts
106
- `));else if(R){const i=o.project||process.env.ZIBBY_API_KEY;if(!i)console.log(e.yellow(`
108
+ `));else if(b){let d=o.project||process.env.ZIBBY_API_KEY;if(!d)console.log(e.yellow(`
107
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
108
- `));else{const y=await Ge({apiKey:i,specPath:n,fullSpecPath:S,projectId:null,collectionIdOrName:o.collection||null,folder:o.folder,agent:r.agent,config:r,result:g,shouldOpen:o.open});o.open&&y?.success&&y.executionId&&y.projectId&&await Ne(y.executionId,y.projectId)}}}catch(t){if(f.isSpinning&&f.stop(),console.log(e.red(`
110
+ `));else{let v=await po({apiKey:d,specPath:t,fullSpecPath:c,projectId:null,collectionIdOrName:o.collection||null,folder:o.folder,agent:n.agent,config:n,result:y,shouldOpen:o.open});o.open&&v?.success&&v.executionId&&v.projectId&&await uo(v.executionId,v.projectId)}}}catch(r){if(I.isSpinning&&I.stop(),console.log(e.red(`
109
111
  \u2716 Test failed
110
- `)),Oe(t)){console.log(e.yellow(`Test execution was interrupted
111
- `));try{te({cwd:process.cwd(),config:r})}catch{}Q(w),process.exit(130)}Be(M,t),console.log(e.red(`Error: ${t.message}
112
- `)),t.stack&&console.log(e.gray(t.stack)),Q(w),process.exit(1)}finally{typeof Y=="function"&&Y(),G(),process.off("SIGINT",a),process.off("SIGTERM",a)}Q(w)}function Q(n){if(n)try{ce(W(process.cwd()),{recursive:!0,force:!0})}catch{}}export{De as runCommand};
112
+ `)),ro(r)){console.log(e.yellow(`Test execution was interrupted
113
+ `));try{_e({cwd:process.cwd(),config:n})}catch{}ie(l),process.exit(130)}io(Z,r),console.log(e.red(`Error: ${r.message}
114
+ `)),r.stack&&console.log(e.gray(r.stack)),ie(l),process.exit(1)}finally{typeof F=="function"&&F(),L(),process.off("SIGINT",p),process.off("SIGTERM",p)}ie(l)}function ie(t){if(t)try{Ae(ce(process.cwd()),{recursive:!0,force:!0})}catch{}}export{go as runCommand};
@@ -1,15 +1,15 @@
1
- import{spawn as m,execSync as y}from"child_process";import{join as l,dirname as w,resolve as b}from"path";import{readFileSync as P,writeFileSync as C,existsSync as p,mkdirSync as S}from"fs";import{homedir as x}from"os";import{createRequire as M}from"module";import c from"chalk";const v=M(import.meta.url);function A(){try{return w(v.resolve("@zibby/core/package.json"))}catch{return null}}function j(e){try{return y(`command -v ${e}`,{stdio:"pipe"}),!0}catch{return!1}}function B(){try{const e=v.resolve("@zibby/mcp-browser/bin/mcp-browser-zibby.js");if(p(e))return e}catch{}try{const e=v.resolve("@playwright/mcp/package.json"),r=w(e),o=JSON.parse(P(e,"utf-8")),n=typeof o.bin=="string"?o.bin:o.bin?.["playwright-mcp"];if(n){const s=l(r,n);if(p(s))return s}const t=l(r,"cli.js");if(p(t))return t}catch{}return null}function $(e,r,o={}){return new Promise((n,t)=>{const s=m(e,r,{stdio:"inherit",...o});s.on("close",u=>n(u??1)),s.on("error",t)})}async function E(e){return j("playwright")?await $("playwright",["install","ffmpeg"],{cwd:e})===0:await $("npx",["--yes","playwright","install","ffmpeg"],{cwd:e})===0}function N({headed:e=!1,viewport:r=null}){const o=process.execPath,n=w(o),t=B(),s=Number(r?.width)||1280,u=Number(r?.height)||720,f=`${s}x${u}`,i=[];i.push(`--viewport-size=${f}`,"--output-dir=test-results"),e||i.push("--headless");let g;t?g={command:o,args:[t,...i],env:{PATH:`${n}:/usr/bin:/bin:/usr/sbin:/sbin`}}:g={command:"npx",args:["-y","@playwright/mcp",...i],env:{PATH:`${n}:/usr/bin:/bin:/usr/sbin:/sbin`}},g.description="Zibby MCP Browser - Playwright MCP with Zibby defaults";const d=l(x(),".cursor"),h=l(d,"mcp.json");p(d)||S(d,{recursive:!0});let a={mcpServers:{}};if(p(h))try{a=JSON.parse(P(h,"utf-8")),(!a.mcpServers||typeof a.mcpServers!="object")&&(a.mcpServers={})}catch{a={mcpServers:{}}}a.mcpServers["playwright-official"]=g,C(h,`${JSON.stringify(a,null,2)}
2
- `,"utf-8")}async function O(){const e=A();if(!e)return;const r=l(e,"scripts","patch-cursor-mcp.js");if(p(r))try{await new Promise((o,n)=>{const t=m(process.execPath,[r],{cwd:process.cwd(),stdio:"ignore"});t.on("close",s=>o(s??0)),t.on("error",n)})}catch{}}function R(e){return b(e).replace(/^\/+/,"").replace(/\//g,"-")}function z(e){const r=String(e||""),o=r.split(`
3
- `).find(s=>/playwright-official/i.test(s)&&/APPROVAL|🔑/i.test(s));if(o){const s=o.match(/=>\s*(\S+)/);if(s)return s[1]}const n=r.match(/playwright-official[^=]*=>\s*(\S+)/);if(n)return n[1];const t=r.match(/playwright-official-[a-f0-9]+/i);return t?t[0]:null}function J(e,r){const o=R(e),n=l(x(),".cursor","projects",o);S(n,{recursive:!0});const t=l(n,"mcp-approvals.json");return C(t,`${JSON.stringify([r],null,2)}
4
- `,"utf-8"),t}function k(e){try{return y("cursor-agent mcp list",{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:process.env,maxBuffer:2*1024*1024})}catch(r){const o=r.stdout!=null?String(r.stdout):"",n=r.stderr!=null?String(r.stderr):"";return o+n}}function T(e){try{return y("cursor-agent mcp enable playwright-official",{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:process.env,maxBuffer:1024*1024}),!0}catch{return!1}}async function D(e={}){const r=!!e.headed,o=e.viewport||{width:1280,height:720};if(!process.execPath)throw new Error("Node.js runtime not found");const n=await E(process.cwd());console.log(n?c.gray(" \u2713 ffmpeg installed for Playwright video"):c.yellow(" \u26A0 Could not install ffmpeg (video may be unavailable)")),N({headed:r,viewport:o}),await O();const t=b(process.cwd());if(j("cursor-agent")){k(t);const s=T(t);s&&console.log(c.gray(" \u2713 cursor-agent: mcp enable playwright-official"));const u=k(t),f=z(u);if(f)try{const i=J(t,f);console.log(c.gray(` \u2713 MCP auto-approval key saved (${i})`))}catch(i){console.log(c.yellow(` \u26A0 Could not write mcp-approvals.json: ${i.message}`))}else s||(console.log(c.yellow(" \u26A0 Could not auto-approve MCP (mcp enable failed and no approval key in cursor-agent output)")),console.log(c.gray(" Try: cursor-agent mcp enable playwright-official")))}else console.log(c.yellow(" \u26A0 cursor-agent not found; install it to use Cursor MCP tools"))}async function K(e){try{console.log(c.cyan(`
1
+ import{spawn as y,execSync as w}from"child_process";import{join as l,dirname as v,resolve as C}from"path";import{readFileSync as S,writeFileSync as x,existsSync as p,mkdirSync as j}from"fs";import{homedir as $}from"os";import{createRequire as M}from"module";import c from"chalk";var m=M(import.meta.url);function A(){try{return v(m.resolve("@zibby/core/package.json"))}catch{return null}}function k(e){try{return w(`command -v ${e}`,{stdio:"pipe"}),!0}catch{return!1}}function B(){try{let e=m.resolve("@zibby/mcp-browser/bin/mcp-browser-zibby.js");if(p(e))return e}catch{}try{let e=m.resolve("@playwright/mcp/package.json"),r=v(e),o=JSON.parse(S(e,"utf-8")),n=typeof o.bin=="string"?o.bin:o.bin?.["playwright-mcp"];if(n){let s=l(r,n);if(p(s))return s}let t=l(r,"cli.js");if(p(t))return t}catch{}return null}function b(e,r,o={}){return new Promise((n,t)=>{let s=y(e,r,{stdio:"inherit",...o});s.on("close",u=>n(u??1)),s.on("error",t)})}async function E(e){return k("playwright")?await b("playwright",["install","ffmpeg"],{cwd:e})===0:await b("npx",["--yes","playwright","install","ffmpeg"],{cwd:e})===0}function N({headed:e=!1,viewport:r=null}){let o=process.execPath,n=v(o),t=B(),s=Number(r?.width)||1280,u=Number(r?.height)||720,f=`${s}x${u}`,i=[];i.push(`--viewport-size=${f}`,"--output-dir=test-results"),e||i.push("--headless");let g;t?g={command:o,args:[t,...i],env:{PATH:`${n}:/usr/bin:/bin:/usr/sbin:/sbin`}}:g={command:"npx",args:["-y","@playwright/mcp",...i],env:{PATH:`${n}:/usr/bin:/bin:/usr/sbin:/sbin`}},g.description="Zibby MCP Browser - Playwright MCP with Zibby defaults";let d=l($(),".cursor"),h=l(d,"mcp.json");p(d)||j(d,{recursive:!0});let a={mcpServers:{}};if(p(h))try{a=JSON.parse(S(h,"utf-8")),(!a.mcpServers||typeof a.mcpServers!="object")&&(a.mcpServers={})}catch{a={mcpServers:{}}}a.mcpServers["playwright-official"]=g,x(h,`${JSON.stringify(a,null,2)}
2
+ `,"utf-8")}async function O(){let e=A();if(!e)return;let r=l(e,"scripts","patch-cursor-mcp.js");if(p(r))try{await new Promise((o,n)=>{let t=y(process.execPath,[r],{cwd:process.cwd(),stdio:"ignore"});t.on("close",s=>o(s??0)),t.on("error",n)})}catch{}}function R(e){return C(e).replace(/^\/+/,"").replace(/\//g,"-")}function z(e){let r=String(e||""),o=r.split(`
3
+ `).find(s=>/playwright-official/i.test(s)&&/APPROVAL|🔑/i.test(s));if(o){let s=o.match(/=>\s*(\S+)/);if(s)return s[1]}let n=r.match(/playwright-official[^=]*=>\s*(\S+)/);if(n)return n[1];let t=r.match(/playwright-official-[a-f0-9]+/i);return t?t[0]:null}function J(e,r){let o=R(e),n=l($(),".cursor","projects",o);j(n,{recursive:!0});let t=l(n,"mcp-approvals.json");return x(t,`${JSON.stringify([r],null,2)}
4
+ `,"utf-8"),t}function P(e){try{return w("cursor-agent mcp list",{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:process.env,maxBuffer:2*1024*1024})}catch(r){let o=r.stdout!=null?String(r.stdout):"",n=r.stderr!=null?String(r.stderr):"";return o+n}}function T(e){try{return w("cursor-agent mcp enable playwright-official",{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:process.env,maxBuffer:1024*1024}),!0}catch{return!1}}async function D(e={}){let r=!!e.headed,o=e.viewport||{width:1280,height:720};if(!process.execPath)throw new Error("Node.js runtime not found");let n=await E(process.cwd());console.log(n?c.gray(" \u2713 ffmpeg installed for Playwright video"):c.yellow(" \u26A0 Could not install ffmpeg (video may be unavailable)")),N({headed:r,viewport:o}),await O();let t=C(process.cwd());if(k("cursor-agent")){P(t);let s=T(t);s&&console.log(c.gray(" \u2713 cursor-agent: mcp enable playwright-official"));let u=P(t),f=z(u);if(f)try{let i=J(t,f);console.log(c.gray(` \u2713 MCP auto-approval key saved (${i})`))}catch(i){console.log(c.yellow(` \u26A0 Could not write mcp-approvals.json: ${i.message}`))}else s||(console.log(c.yellow(" \u26A0 Could not auto-approve MCP (mcp enable failed and no approval key in cursor-agent output)")),console.log(c.gray(" Try: cursor-agent mcp enable playwright-official")))}else console.log(c.yellow(" \u26A0 cursor-agent not found; install it to use Cursor MCP tools"))}async function K(e){try{console.log(c.cyan(`
5
5
  \u{1F680} Running CI setup...
6
6
  `)),await D({headed:!1,cloudSync:!0,viewport:{width:1280,height:720}}),console.log(c.green(`
7
7
  \u2705 CI/CD setup complete!
8
8
  `))}catch(r){console.log(c.red(`
9
9
  \u274C Error: ${r.message}
10
- `)),process.exit(1)}}async function L(e,r){try{const o=["playwright","test",e||"tests/","--project=chromium"];r.headed&&o.push("--headed"),console.log(c.cyan(`
10
+ `)),process.exit(1)}}async function L(e,r){try{let o=["playwright","test",e||"tests/","--project=chromium"];r.headed&&o.push("--headed"),console.log(c.cyan(`
11
11
  \u{1F3A5} Running tests with video recording...
12
- `)),console.log(c.gray("\u2501".repeat(50)));const n=m("npx",o,{cwd:process.cwd(),stdio:"inherit"});n.on("close",t=>{t===0?console.log(c.green(`
12
+ `)),console.log(c.gray("\u2501".repeat(50)));let n=y("npx",o,{cwd:process.cwd(),stdio:"inherit"});n.on("close",t=>{t===0?console.log(c.green(`
13
13
  \u2705 Tests complete!
14
14
  `)):(console.log(c.red(`
15
15
  \u274C Tests failed with code ${t}