@zibby/cli 0.4.7 → 0.4.11
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/dist/bin/zibby.js +3 -3
- package/dist/commands/init.js +135 -140
- package/dist/commands/template.js +7 -7
- package/dist/commands/workflow.js +3 -3
- package/dist/commands/workflows/cloud-creds-check.js +2 -2
- package/dist/commands/workflows/deploy-helpers.js +3 -3
- package/dist/commands/workflows/deploy.js +44 -44
- package/dist/commands/workflows/generate.js +464 -43
- package/dist/commands/workflows/list.js +12 -12
- package/dist/commands/workflows/run-local.js +8 -8
- package/dist/commands/workflows/run.js +5 -5
- package/dist/commands/workflows/start.js +1 -1
- package/dist/package.json +2 -2
- package/dist/utils/session-uploader.js +1 -0
- package/package.json +2 -2
package/dist/commands/init.js
CHANGED
|
@@ -1,176 +1,171 @@
|
|
|
1
|
-
var
|
|
1
|
+
var bo=Object.defineProperty;var B=(e,o)=>()=>(e&&(o=e(e=0)),o);var N=(e,o)=>{for(var t in o)bo(e,t,{get:o[t],enumerable:!0})};var Pe={};N(Pe,{resolveTemplate:()=>_e,templateAddCommand:()=>No,templateListCommand:()=>Bo,writeTemplateFiles:()=>Ae,writeTemplateFilesToDir:()=>Ie});import{mkdir as ke,writeFile as _o,readFile as Io}from"fs/promises";import{existsSync as X,readdirSync as Ao,statSync as Po,readFileSync as Co}from"fs";import{join as j,dirname as $o}from"path";import{fileURLToPath as So}from"url";import{spawn as Eo}from"child_process";import{createRequire as Ro}from"module";import x from"chalk";import zo from"ora";function Mo(e){return Ko.some(o=>o.test(e))}async function xe(e,o,t=null){let i=[];X(o)||await ke(o,{recursive:!0});for(let s of Ao(e)){if(Mo(s))continue;let n=j(e,s),u=j(o,s),d=Po(n);if(d.isDirectory()){let l=await xe(n,u,t);for(let m of l)i.push(`${s}/${m}`)}else if(d.isFile()){let l=await Io(n,"utf-8");t&&(l=t(s,l)),await _o(u,l),i.push(s)}}return i}async function _e(e){if(!e||typeof e!="string")throw new Error("Template name is required");if(/^(git\+|https?:)/.test(e))throw new Error(`Git/URL templates are not yet supported (got "${e}"). For now use a built-in template \u2014 see \`zibby template list\`.`);if(e.startsWith("@")||e.includes("/")||e.startsWith("zibby-template-"))throw new Error(`npm-package templates are not yet supported (got "${e}"). For now use a built-in template \u2014 see \`zibby template list\`.`);let{TemplateFactory:o}=await import("@zibby/core/templates");return o.getTemplateFiles(e)}async function Ie(e,o,t={}){let i=t.enableMemory!==!1,{template:s}=await _e(o);X(e)||await ke(e,{recursive:!0});let n=await xe(s.path,e,(u,d)=>!i&&u==="execute-live.mjs"?d.replace("skills: [SKILLS.BROWSER, SKILLS.MEMORY],","skills: [SKILLS.BROWSER],"):d);return{template:s,copied:n}}async function Ae(e,o,t={}){return Ie(j(e,".zibby"),o,t)}async function Bo(){let{TemplateFactory:e}=await import("@zibby/core/templates"),o=e.listTemplates();console.log(""),console.log(x.bold.cyan(" Available templates")),console.log("");for(let t of o){if(console.log(` ${x.cyan(t.name)}`),console.log(` ${x.white(t.displayName)}`),t.description&&console.log(` ${x.gray(t.description)}`),t.features&&t.features.length)for(let s of t.features)console.log(x.gray(` \u2022 ${s}`));let i=t.defaultSlug||"your-workflow-name";console.log(""),console.log(` ${x.gray("Scaffold:")} ${x.cyan(`zibby workflow new ${i} -t ${t.name}`)}`),console.log("")}}async function No(e,o={}){e||(console.log(x.red(`
|
|
2
2
|
Missing template name.
|
|
3
|
-
`)),console.log(
|
|
4
|
-
`)),process.exit(1));let t=
|
|
3
|
+
`)),console.log(x.gray(" Usage: zibby template add <name>")),console.log(x.gray(` See available templates: zibby template list
|
|
4
|
+
`)),process.exit(1));let t=o.cwd||process.cwd(),i=j(t,".zibby");X(i)||(console.log(x.yellow(`
|
|
5
5
|
No .zibby/ directory in ${t}.
|
|
6
|
-
`)),console.log(
|
|
7
|
-
${
|
|
8
|
-
`)),console.log(
|
|
9
|
-
`)),process.exit(1)}console.log(""),console.log(k.green(` \u2713 Added template ${k.bold(i.template.name)}`)),console.log(k.gray(` ${i.copied.length} files written to ${a}/`));for(let s of i.copied)console.log(k.gray(` \u2022 ${s}`));console.log(""),console.log(k.gray(" Re-running `zibby template add <name>` overwrites existing files \u2014")),console.log(k.gray(" use this to refresh after `npm update @zibby/core`.")),console.log("")}var Ce=j(()=>{});var Se={};D(Se,{applyMemorySyncConfig:()=>So,validateMemorySyncConfig:()=>$e});function $e(o){if(!o||typeof o!="object")return{ok:!0,kind:"noop"};let e=o.remote;return _o.includes(e)?{ok:!0,kind:"noop"}:typeof e!="string"?{ok:!1,error:`memorySync.remote must be null or a string, got ${typeof e}`}:e===$o?{ok:!0,kind:"hosted"}:_e.some(t=>e.startsWith(t))?{ok:!0,kind:"byo",remote:e}:{ok:!1,error:`memorySync.remote = ${JSON.stringify(e)} is not recognized. Use null, 'hosted', or a URL beginning with one of: ${_e.join(" / ")}.`}}async function So({cwd:o,projectId:e,block:t,memoryApi:a,hostedSetup:i,getSessionToken:s,logger:p=console}){let u=$e(t);if(!u.ok)return p.warn?.(`[memory-sync] config invalid: ${u.error}`),{action:"error",reason:u.error};if(u.kind==="noop")return{action:"skipped",reason:"memorySync.remote not set"};if(u.kind==="byo")return a?.memoryRemoteAdd?a.memoryRemoteAdd(o,u.remote)?{action:"byo",remote:u.remote}:{action:"error",reason:"memoryRemoteAdd returned false (memory DB not initialized?)"}:{action:"error",reason:"@zibby/ui-memory not loaded"};if(u.kind==="hosted"){if(typeof s=="function"&&!s())return{action:"pending-login",reason:'memorySync.remote = "hosted" but the user is not logged in. Run `zibby login` then `zibby memory remote use --hosted`.'};if(typeof i!="function")return{action:"error",reason:"hostedSetup function not provided"};try{return await i({cwd:o,projectId:e}),{action:"hosted"}}catch(l){return{action:"error",reason:`hosted setup failed: ${l.message}`}}}return{action:"error",reason:`unhandled kind: ${u.kind}`}}var _o,$o,_e,Ee=j(()=>{_o=[null,void 0,"","none","off",!1],$o="hosted",_e=["aws://","gs://","https://","http://","file://"]});var re={};D(re,{clearSession:()=>De,default:()=>Ko,getMem0ProxyUrl:()=>Ye,getProjects:()=>He,getProxyUrl:()=>Le,getSessionToken:()=>se,getUserInfo:()=>Be,isLoggedIn:()=>je,loadConfig:()=>S,saveConfig:()=>K,saveMem0ProxyUrl:()=>Ze,saveProjects:()=>Fe,saveProxyUrl:()=>Ue,saveSessionToken:()=>Me,saveUserInfo:()=>Ne});import{existsSync as ze,mkdirSync as Eo,readFileSync as zo,writeFileSync as Ro}from"fs";import{homedir as Re}from"os";import{join as ee}from"path";function Oe(){return process.env.ZIBBY_CONFIG_DIR||ee(Re(),".zibby")}function Te(){return ee(Oe(),"config.json")}function To(){let o=Oe();ze(o)||Eo(o,{recursive:!0})}function S(){try{let o=Te();if(ze(o)){let e=zo(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function K(o){To(),Ro(Te(),JSON.stringify(o,null,2))}function se(){return S().sessionToken||null}function Me(o){let e=S();e.sessionToken=o,K(e)}function Be(){return S().user||null}function Ne(o){let e=S();e.user=o,K(e)}function je(){return se()!==null}function De(){let o=S();delete o.sessionToken,delete o.user,delete o.mem0ProxyUrl,K(o)}function Le(){return S().proxyUrl||null}function Ue(o){let e=S();e.proxyUrl=o,K(e)}function Ye(){return S().mem0ProxyUrl||null}function Ze(o){let e=S();e.mem0ProxyUrl=o,K(e)}function He(){return S().projects||[]}function Fe(o){let e=S();e.projects=o,K(e)}var Ke,Oo,Ko,ie=j(()=>{Ke=ee(Re(),".zibby"),Oo=ee(Ke,"config.json");Ko={loadConfig:S,saveConfig:K,getSessionToken:se,saveSessionToken:Me,getUserInfo:Be,saveUserInfo:Ne,isLoggedIn:je,clearSession:De,getProxyUrl:Le,saveProxyUrl:Ue,getMem0ProxyUrl:Ye,saveMem0ProxyUrl:Ze,getProjects:He,saveProjects:Fe,CONFIG_DIR:Ke,CONFIG_FILE:Oo}});var Ge={};D(Ge,{ENVIRONMENTS:()=>_,getAccountApiUrl:()=>Bo,getApiUrl:()=>Mo,getCurrentEnvironment:()=>No,getFrontendUrl:()=>jo});function Mo(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";_[e]?o=_[e].apiUrl:o=_.prod.apiUrl}try{let e=new URL(o);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),_.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),_.prod.apiUrl}}function Bo(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let o=process.env.ZIBBY_ENV||"prod";return(_[o]||_.prod).accountApiUrl}function No(){let o=process.env.ZIBBY_ENV||"prod";return _[o]||_.prod}function jo(){let o;if(process.env.ZIBBY_FRONTEND_URL)o=process.env.ZIBBY_FRONTEND_URL;else{let e=process.env.ZIBBY_ENV||"prod";_[e]?o=_[e].frontendUrl:o=_.prod.frontendUrl}try{let e=new URL(o);if(e.protocol!=="http:"&&e.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${e.protocol} (only http/https allowed)`),_.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let a=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],i=e.hostname;if(!a.some(p=>i===p||i.endsWith(`.${p}`))&&!i.includes("localhost")&&i!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${i}`),"https://studio.zibby.dev"}return o}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${o}`),_.local.frontendUrl}}var _,Ve=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"}}});var pe={};D(pe,{__testing:()=>Go,buildDoltEnv:()=>Fo,clearConfig:()=>Ho,getActiveCredentials:()=>oo,isHosted:()=>Yo,readConfig:()=>de,refreshCredentials:()=>eo,writeConfig:()=>Zo});import{readFileSync as We,writeFileSync as le,existsSync as ce,mkdirSync as qe,chmodSync as Do}from"fs";import{join as ae}from"path";function H(o){let e=ae(o,".zibby");return{dir:e,config:ae(e,Lo),creds:ae(e,Uo)}}function de(o){let{config:e}=H(o);if(!ce(e))return null;try{let t=JSON.parse(We(e,"utf-8"));return t.mode!=="hosted"?null:t}catch{return null}}function Yo(o){return!!de(o)}function Zo(o,e){let{dir:t,config:a}=H(o);qe(t,{recursive:!0}),le(a,JSON.stringify({mode:"hosted",projectId:e.projectId,bucket:e.bucket,prefix:e.prefix,doltUrl:e.doltUrl,configuredAt:new Date().toISOString()},null,2),"utf-8")}function Ho(o){let{config:e,creds:t}=H(o);for(let a of[e,t])if(ce(a))try{le(a,"")}catch{}}function ue(o){let{creds:e}=H(o);if(!ce(e))return null;try{let t=JSON.parse(We(e,"utf-8"));return!t?.accessKeyId||!t?.secretAccessKey||!t?.sessionToken?null:t}catch{return null}}function Xe(o,e){let{dir:t,creds:a}=H(o);qe(t,{recursive:!0}),le(a,JSON.stringify(e,null,2),"utf-8");try{Do(a,384)}catch{}}function Qe(o){return o?.expiration?new Date(o.expiration).getTime()-Date.now()<Je:!0}async function eo({cwd:o,projectId:e,apiUrl:t,sessionToken:a,fetch:i=globalThis.fetch}){if(!e)throw new Error("refreshCredentials: projectId required");if(!t)throw new Error("refreshCredentials: apiUrl required");if(!a)throw new Error("refreshCredentials: sessionToken required (run `zibby login`)");let s=`${String(t).replace(/\/+$/,"")}/memory/sync-credentials`,p=await i(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({projectId:e})});if(!p.ok){let l=await p.text().catch(()=>"");throw new Error(`memory-sync credentials request failed (${p.status}): ${l||"no body"}`)}let u=await p.json();if(!u?.accessKeyId||!u?.secretAccessKey||!u?.sessionToken)throw new Error("memory-sync credentials response missing required fields");return Xe(o,{accessKeyId:u.accessKeyId,secretAccessKey:u.secretAccessKey,sessionToken:u.sessionToken,expiration:u.expiration||null,refreshedAt:new Date().toISOString()}),ue(o)}async function oo({cwd:o,apiUrl:e,sessionToken:t,fetch:a}){let i=de(o);if(!i)return null;let s=ue(o);return(!s||Qe(s))&&(s=await eo({cwd:o,projectId:i.projectId,apiUrl:e,sessionToken:t,fetch:a})),s}async function Fo({cwd:o,apiUrl:e,sessionToken:t,fetch:a}){let i=await oo({cwd:o,apiUrl:e,sessionToken:t,fetch:a});return i?{AWS_ACCESS_KEY_ID:i.accessKeyId,AWS_SECRET_ACCESS_KEY:i.secretAccessKey,AWS_SESSION_TOKEN:i.sessionToken,AWS_REGION:process.env.AWS_REGION||"ap-southeast-2"}:null}var Lo,Uo,Je,Go,ge=j(()=>{Lo="memory-sync.json",Uo="memory-sync-creds.json",Je=120*1e3;Go={paths:H,readCreds:ue,writeCreds:Xe,isExpiringSoon:Qe,REFRESH_HEADROOM_MS:Je}});var to={};D(to,{memoryCompactCommand:()=>Jo,memoryCostCommand:()=>Xo,memoryInitCommand:()=>rt,memoryPullCommand:()=>tt,memoryPushCommand:()=>st,memoryRemoteAddCommand:()=>Qo,memoryRemoteInfoCommand:()=>et,memoryRemoteRemoveCommand:()=>ot,memoryRemoteUseHostedCommand:()=>nt,memoryResetCommand:()=>qo,memoryStatsCommand:()=>Wo});import n from"chalk";async function z(){try{return await import("@zibby/ui-memory")}catch{return console.log(n.yellow(`
|
|
6
|
+
`)),console.log(x.gray(" Run `zibby init` first to bootstrap the project.\n")),process.exit(1));let s;try{s=await Ae(t,e,{enableMemory:o.enableMemory!==!1})}catch(n){console.log(x.red(`
|
|
7
|
+
${n.message}
|
|
8
|
+
`)),console.log(x.gray(` See available templates: zibby template list
|
|
9
|
+
`)),process.exit(1)}console.log(""),console.log(x.green(` \u2713 Added template ${x.bold(s.template.name)}`)),console.log(x.gray(` ${s.copied.length} files written to ${i}/`));for(let n of s.copied)console.log(x.gray(` \u2022 ${n}`));if(!o.skipInstall&&X(j(t,"package.json"))){let n=!1;try{Ro(j(t,"package.json")).resolve("@zibby/core/package.json"),n=!0}catch{}if(!n){let d=`@zibby/core@${JSON.parse(Co(j(Oo,"../../package.json"),"utf-8")).dependencies?.["@zibby/core"]||"latest"}`,l=zo(` Installing ${d} (needed by .zibby/graph.mjs)...`).start();await new Promise(w=>{Eo("npm",["install","--save-dev",d],{cwd:t,stdio:"pipe"}).on("close",h=>w(h??1))})===0?l.succeed(` Installed ${d}`):(l.warn(` Could not auto-install ${d}`),console.log(x.gray(` Run manually: npm install --save-dev ${d}`)))}}console.log(""),console.log(x.gray(" Re-running `zibby template add <name>` overwrites existing files \u2014")),console.log(x.gray(" use this to refresh after `npm update @zibby/core`.")),console.log("")}var To,Oo,Ko,Ce=B(()=>{To=So(import.meta.url),Oo=$o(To),Ko=[/^__tests__$/,/^__mocks__$/,/^node_modules$/,/\.test\.[mc]?js$/,/\.spec\.[mc]?js$/,/^\.DS_Store$/,/^chat\.mjs$/]});var Ee={};N(Ee,{applyMemorySyncConfig:()=>Do,validateMemorySyncConfig:()=>Se});function Se(e){if(!e||typeof e!="object")return{ok:!0,kind:"noop"};let o=e.remote;return jo.includes(o)?{ok:!0,kind:"noop"}:typeof o!="string"?{ok:!1,error:`memorySync.remote must be null or a string, got ${typeof o}`}:o===Lo?{ok:!0,kind:"hosted"}:$e.some(t=>o.startsWith(t))?{ok:!0,kind:"byo",remote:o}:{ok:!1,error:`memorySync.remote = ${JSON.stringify(o)} is not recognized. Use null, 'hosted', or a URL beginning with one of: ${$e.join(" / ")}.`}}async function Do({cwd:e,projectId:o,block:t,memoryApi:i,hostedSetup:s,getSessionToken:n,logger:u=console}){let d=Se(t);if(!d.ok)return u.warn?.(`[memory-sync] config invalid: ${d.error}`),{action:"error",reason:d.error};if(d.kind==="noop")return{action:"skipped",reason:"memorySync.remote not set"};if(d.kind==="byo")return i?.memoryRemoteAdd?i.memoryRemoteAdd(e,d.remote)?{action:"byo",remote:d.remote}:{action:"error",reason:"memoryRemoteAdd returned false (memory DB not initialized?)"}:{action:"error",reason:"@zibby/ui-memory not loaded"};if(d.kind==="hosted"){if(typeof n=="function"&&!n())return{action:"pending-login",reason:'memorySync.remote = "hosted" but the user is not logged in. Run `zibby login` then `zibby memory remote use --hosted`.'};if(typeof s!="function")return{action:"error",reason:"hostedSetup function not provided"};try{return await s({cwd:e,projectId:o}),{action:"hosted"}}catch(l){return{action:"error",reason:`hosted setup failed: ${l.message}`}}}return{action:"error",reason:`unhandled kind: ${d.kind}`}}var jo,Lo,$e,Re=B(()=>{jo=[null,void 0,"","none","off",!1],Lo="hosted",$e=["aws://","gs://","https://","http://","file://"]});var ne={};N(ne,{clearSession:()=>De,default:()=>Go,getMem0ProxyUrl:()=>Ze,getProjects:()=>He,getProxyUrl:()=>Ue,getSessionToken:()=>te,getUserInfo:()=>Ne,isLoggedIn:()=>Le,loadConfig:()=>$,saveConfig:()=>T,saveMem0ProxyUrl:()=>Fe,saveProjects:()=>Ge,saveProxyUrl:()=>Ye,saveSessionToken:()=>Be,saveUserInfo:()=>je});import{existsSync as ze,mkdirSync as Uo,readFileSync as Yo,writeFileSync as Zo}from"fs";import{homedir as Te}from"os";import{join as Q}from"path";function Oe(){return process.env.ZIBBY_CONFIG_DIR||Q(Te(),".zibby")}function Ke(){return Q(Oe(),"config.json")}function Ho(){let e=Oe();ze(e)||Uo(e,{recursive:!0})}function $(){try{let e=Ke();if(ze(e)){let o=Yo(e,"utf-8");return JSON.parse(o)}}catch{}return{}}function T(e){Ho(),Zo(Ke(),JSON.stringify(e,null,2))}function te(){return $().sessionToken||null}function Be(e){let o=$();o.sessionToken=e,T(o)}function Ne(){return $().user||null}function je(e){let o=$();o.user=e,T(o)}function Le(){return te()!==null}function De(){let e=$();delete e.sessionToken,delete e.user,delete e.mem0ProxyUrl,T(e)}function Ue(){return $().proxyUrl||null}function Ye(e){let o=$();o.proxyUrl=e,T(o)}function Ze(){return $().mem0ProxyUrl||null}function Fe(e){let o=$();o.mem0ProxyUrl=e,T(o)}function He(){return $().projects||[]}function Ge(e){let o=$();o.projects=e,T(o)}var Me,Fo,Go,re=B(()=>{Me=Q(Te(),".zibby"),Fo=Q(Me,"config.json");Go={loadConfig:$,saveConfig:T,getSessionToken:te,saveSessionToken:Be,getUserInfo:Ne,saveUserInfo:je,isLoggedIn:Le,clearSession:De,getProxyUrl:Ue,saveProxyUrl:Ye,getMem0ProxyUrl:Ze,saveMem0ProxyUrl:Fe,getProjects:He,saveProjects:Ge,CONFIG_DIR:Me,CONFIG_FILE:Fo}});var Ve={};N(Ve,{ENVIRONMENTS:()=>A,getAccountApiUrl:()=>Wo,getApiUrl:()=>Vo,getCurrentEnvironment:()=>qo,getFrontendUrl:()=>Jo});function Vo(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";A[o]?e=A[o].apiUrl:e=A.prod.apiUrl}try{let o=new URL(e);return o.protocol!=="http:"&&o.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${o.protocol} (only http/https allowed)`),A.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),A.prod.apiUrl}}function Wo(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let e=process.env.ZIBBY_ENV||"prod";return(A[e]||A.prod).accountApiUrl}function qo(){let e=process.env.ZIBBY_ENV||"prod";return A[e]||A.prod}function Jo(){let e;if(process.env.ZIBBY_FRONTEND_URL)e=process.env.ZIBBY_FRONTEND_URL;else{let o=process.env.ZIBBY_ENV||"prod";A[o]?e=A[o].frontendUrl:e=A.prod.frontendUrl}try{let o=new URL(e);if(o.protocol!=="http:"&&o.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${o.protocol} (only http/https allowed)`),A.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let i=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],s=o.hostname;if(!i.some(u=>s===u||s.endsWith(`.${u}`))&&!s.includes("localhost")&&s!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${s}`),"https://studio.zibby.dev"}return e}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${e}`),A.local.frontendUrl}}var A,We=B(()=>{A={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"}}});var de={};N(de,{__testing:()=>st,buildDoltEnv:()=>rt,clearConfig:()=>nt,getActiveCredentials:()=>to,isHosted:()=>ot,readConfig:()=>le,refreshCredentials:()=>oo,writeConfig:()=>tt});import{readFileSync as qe,writeFileSync as ie,existsSync as ae,mkdirSync as Je,chmodSync as Xo}from"fs";import{join as se}from"path";function Y(e){let o=se(e,".zibby");return{dir:o,config:se(o,Qo),creds:se(o,et)}}function le(e){let{config:o}=Y(e);if(!ae(o))return null;try{let t=JSON.parse(qe(o,"utf-8"));return t.mode!=="hosted"?null:t}catch{return null}}function ot(e){return!!le(e)}function tt(e,o){let{dir:t,config:i}=Y(e);Je(t,{recursive:!0}),ie(i,JSON.stringify({mode:"hosted",projectId:o.projectId,bucket:o.bucket,prefix:o.prefix,doltUrl:o.doltUrl,configuredAt:new Date().toISOString()},null,2),"utf-8")}function nt(e){let{config:o,creds:t}=Y(e);for(let i of[o,t])if(ae(i))try{ie(i,"")}catch{}}function ce(e){let{creds:o}=Y(e);if(!ae(o))return null;try{let t=JSON.parse(qe(o,"utf-8"));return!t?.accessKeyId||!t?.secretAccessKey||!t?.sessionToken?null:t}catch{return null}}function Qe(e,o){let{dir:t,creds:i}=Y(e);Je(t,{recursive:!0}),ie(i,JSON.stringify(o,null,2),"utf-8");try{Xo(i,384)}catch{}}function eo(e){return e?.expiration?new Date(e.expiration).getTime()-Date.now()<Xe:!0}async function oo({cwd:e,projectId:o,apiUrl:t,sessionToken:i,fetch:s=globalThis.fetch}){if(!o)throw new Error("refreshCredentials: projectId required");if(!t)throw new Error("refreshCredentials: apiUrl required");if(!i)throw new Error("refreshCredentials: sessionToken required (run `zibby login`)");let n=`${String(t).replace(/\/+$/,"")}/memory/sync-credentials`,u=await s(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({projectId:o})});if(!u.ok){let l=await u.text().catch(()=>"");throw new Error(`memory-sync credentials request failed (${u.status}): ${l||"no body"}`)}let d=await u.json();if(!d?.accessKeyId||!d?.secretAccessKey||!d?.sessionToken)throw new Error("memory-sync credentials response missing required fields");return Qe(e,{accessKeyId:d.accessKeyId,secretAccessKey:d.secretAccessKey,sessionToken:d.sessionToken,expiration:d.expiration||null,refreshedAt:new Date().toISOString()}),ce(e)}async function to({cwd:e,apiUrl:o,sessionToken:t,fetch:i}){let s=le(e);if(!s)return null;let n=ce(e);return(!n||eo(n))&&(n=await oo({cwd:e,projectId:s.projectId,apiUrl:o,sessionToken:t,fetch:i})),n}async function rt({cwd:e,apiUrl:o,sessionToken:t,fetch:i}){let s=await to({cwd:e,apiUrl:o,sessionToken:t,fetch:i});return s?{AWS_ACCESS_KEY_ID:s.accessKeyId,AWS_SECRET_ACCESS_KEY:s.secretAccessKey,AWS_SESSION_TOKEN:s.sessionToken,AWS_REGION:process.env.AWS_REGION||"ap-southeast-2"}:null}var Qo,et,Xe,st,ue=B(()=>{Qo="memory-sync.json",et="memory-sync-creds.json",Xe=120*1e3;st={paths:Y,readCreds:ce,writeCreds:Qe,isExpiringSoon:eo,REFRESH_HEADROOM_MS:Xe}});var no={};N(no,{memoryCompactCommand:()=>ct,memoryCostCommand:()=>dt,memoryInitCommand:()=>ht,memoryPullCommand:()=>gt,memoryPushCommand:()=>ft,memoryRemoteAddCommand:()=>ut,memoryRemoteInfoCommand:()=>pt,memoryRemoteRemoveCommand:()=>mt,memoryRemoteUseHostedCommand:()=>yt,memoryResetCommand:()=>lt,memoryStatsCommand:()=>at});import r from"chalk";async function R(){try{return await import("@zibby/ui-memory")}catch{return console.log(r.yellow(`
|
|
10
10
|
@zibby/ui-memory is not installed.
|
|
11
|
-
`)),console.log(
|
|
11
|
+
`)),console.log(r.white(it)),null}}async function at(){let e=await R();if(!e)return;let o=process.cwd(),t=e.getStats(o);if(!t.available){console.log(r.red(`
|
|
12
12
|
Dolt is not installed.
|
|
13
|
-
`)),console.log(
|
|
14
|
-
`));return}if(!t.initialized){console.log(
|
|
13
|
+
`)),console.log(r.white(" Install Dolt to enable test memory:")),console.log(r.gray(" brew install dolt # macOS")),console.log(r.gray(` curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash # Linux
|
|
14
|
+
`));return}if(!t.initialized){console.log(r.yellow(`
|
|
15
15
|
Memory database not initialized.
|
|
16
|
-
`)),console.log(
|
|
16
|
+
`)),console.log(r.white(" Run `zibby init` or `zibby memory init` to set it up.\n"));return}console.log(r.bold.cyan(`
|
|
17
17
|
Zibby Test Memory
|
|
18
|
-
`)),console.log(
|
|
19
|
-
${
|
|
20
|
-
${
|
|
21
|
-
${
|
|
22
|
-
`).filter(
|
|
18
|
+
`)),console.log(r.gray(` Dolt: ${t.doltVersion}`));let i=r.gray(` ${"\u2500".repeat(40)}`);console.log(i);let s=t.counts;if(console.log(r.white(` Test runs: ${r.cyan(s.runs)} (${r.green(`${s.passed} passed`)}, ${s.failed>0?r.red(`${s.failed} failed`):r.gray(`${s.failed} failed`)})`)),console.log(r.white(` Selectors: ${r.cyan(s.selectors)} tracked`)),console.log(r.white(` Pages: ${r.cyan(s.pages)} discovered`)),console.log(r.white(` Transitions: ${r.cyan(s.transitions)} mapped`)),console.log(r.white(` Insights: ${r.cyan(s.insights||0)} saved`)),t.recentRuns.length>0){console.log(`
|
|
19
|
+
${i}`),console.log(r.white(" Recent runs:"));for(let n of t.recentRuns){let u=n.passed?r.green("\u2713"):r.red("\u2717"),d=n.duration_ms?r.gray(`${(n.duration_ms/1e3).toFixed(1)}s`):"";console.log(` ${u} ${r.white(n.spec_path)} ${d}`)}}if(t.topSelectors.length>0){console.log(`
|
|
20
|
+
${i}`),console.log(r.white(" Top selectors:"));for(let n of t.topSelectors){let u=n.success_count+n.failure_count,d=Math.round(n.success_count/u*100);console.log(` ${r.cyan(n.stable_id||"?")} \u2192 ${n.element_desc} (${d}%, ${u} uses)`)}}if(t.log){console.log(`
|
|
21
|
+
${i}`),console.log(r.white(" Recent commits:"));let n=t.log.split(`
|
|
22
|
+
`).filter(u=>u.startsWith("commit")||u.trim().startsWith("run ")).slice(0,10);for(let u of n)console.log(r.gray(` ${u.trim()}`))}console.log("")}async function lt(e){let o=await R();if(!o)return;let t=process.cwd();if(!e.force){console.log(r.yellow(`
|
|
23
23
|
This will permanently delete the memory database.
|
|
24
|
-
`)),console.log(
|
|
25
|
-
`));return}let
|
|
24
|
+
`)),console.log(r.white(` Run with --force to confirm: zibby memory reset --force
|
|
25
|
+
`));return}let i=o.resetMemory(t);console.log(i?r.green(`
|
|
26
26
|
Memory database reset.
|
|
27
|
-
`):
|
|
27
|
+
`):r.gray(`
|
|
28
28
|
No memory database found.
|
|
29
|
-
`))}async function
|
|
29
|
+
`))}async function ct(e){let o=await R();if(!o)return;let t=process.cwd(),i=o.getStats(t);if(!i.initialized){console.log(r.yellow(`
|
|
30
30
|
Memory database not initialized.
|
|
31
|
-
`));return}let
|
|
32
|
-
Compacting memory (keep last ${
|
|
33
|
-
`))}else console.log(
|
|
34
|
-
`))}async function
|
|
31
|
+
`));return}let s=e.maxRuns||50,n=e.maxAge||90;console.log(r.white(`
|
|
32
|
+
Compacting memory (keep last ${s} runs/spec, prune data older than ${n}d)...`));let u=i.counts;if(o.compactMemory(t,{maxRuns:s,maxAgeDays:n}).pruned){let l=o.getStats(t).counts,m=w=>u[w]-l[w];console.log(r.green(" Done.")),m("runs")>0&&console.log(r.gray(` Pruned ${m("runs")} old runs`)),m("selectors")>0&&console.log(r.gray(` Pruned ${m("selectors")} stale selectors`)),m("insights")>0&&console.log(r.gray(` Pruned ${m("insights")} old insights`)),m("transitions")>0&&console.log(r.gray(` Pruned ${m("transitions")} stale transitions`)),console.log(r.gray(` Dolt GC completed
|
|
33
|
+
`))}else console.log(r.gray(` Nothing to compact.
|
|
34
|
+
`))}async function dt(){let e=await R();if(!e)return;let o=process.cwd(),t=e.getCostStats(o);if(!t){console.log(r.yellow(`
|
|
35
35
|
Memory database not initialized.
|
|
36
|
-
`)),console.log(
|
|
36
|
+
`)),console.log(r.white(" Run `zibby memory init` first.\n"));return}if(t.available===!1){console.log(r.yellow(`
|
|
37
37
|
No usage data yet${t.reason?` (${t.reason})`:""}.
|
|
38
|
-
`)),console.log(
|
|
39
|
-
`));return}console.log(
|
|
38
|
+
`)),console.log(r.gray(" Run `zibby test <spec>` once to populate. Token counts come from")),console.log(r.gray(` the LLM SDK and are written to .zibby/output/sessions/<id>/execute_live/usage.json.
|
|
39
|
+
`));return}console.log(r.bold.cyan(`
|
|
40
40
|
Zibby \u2014 LLM Cost Report
|
|
41
|
-
`));let
|
|
42
|
-
${
|
|
43
|
-
${
|
|
44
|
-
${
|
|
41
|
+
`));let i=r.gray(` ${"\u2500".repeat(60)}`),s=t.totals;if(console.log(i),console.log(r.white(` Runs with usage data: ${r.cyan(s.runs)}`)),console.log(r.white(` Total input tokens: ${r.cyan(O(s.input))}`)),console.log(r.white(` Total output tokens: ${r.cyan(O(s.output))}`)),console.log(r.white(` Total cache reads: ${r.cyan(O(s.cache_read))} ${r.gray("(billed at ~10% of normal input rate)")}`)),console.log(r.white(` Total cache creation: ${r.cyan(O(s.cache_creation))} ${r.gray("(billed at ~125% of normal input rate)")}`)),t.by_domain.length>0){console.log(`
|
|
42
|
+
${i}`),console.log(r.white(" By domain:"));for(let n of t.by_domain.slice(0,10)){let u=n.runs>0?Math.round((n.input+n.output)/n.runs):0;console.log(` ${r.cyan(n.domain.padEnd(30))} ${r.gray(`${n.runs} runs \xB7 ~${O(u)}/run avg`)}`)}}if(t.by_spec.length>0){console.log(`
|
|
43
|
+
${i}`),console.log(r.white(" By spec:"));for(let n of t.by_spec.slice(0,10)){let u=n.runs>0?Math.round((n.input+n.output)/n.runs):0;console.log(` ${r.cyan(String(n.spec_path).padEnd(40))} ${r.gray(`${n.runs} runs \xB7 ~${O(u)}/run avg`)}`)}}if(t.recent.length>0){console.log(`
|
|
44
|
+
${i}`),console.log(r.white(" Last 10 runs:"));for(let n of t.recent.slice(0,10)){let u=n.passed?r.green("\u2713"):r.red("\u2717"),d=(n.input_tokens||0)+(n.output_tokens||0),l=(n.cache_read_tokens||0)>0?r.gray(` \xB7 cache read ${O(n.cache_read_tokens)}`):"";console.log(` ${u} ${r.gray(n.run_at.slice(0,16))} ${r.cyan(O(d).padStart(8))} ${r.white(n.spec_path||"")}${l}`)}}console.log("")}function O(e){return e==null?"\u2014":e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}K`:`${(e/1e6).toFixed(2)}M`}async function ut(e,o={}){let t=await R();if(!t)return;e||(console.log(r.red(`
|
|
45
45
|
Usage: zibby memory remote add <url> [--name origin]
|
|
46
|
-
`)),console.log(
|
|
47
|
-
`)),console.log(
|
|
48
|
-
`));return}console.log(
|
|
49
|
-
Pulling team memory from remote...`));let e
|
|
50
|
-
`)):(console.log(
|
|
46
|
+
`)),console.log(r.gray(" Supported: aws:// gs:// https:// file:///")),console.log(r.gray(" Example: zibby memory remote add aws://team-bucket/zibby/shop-prod")),console.log(""),process.exit(1));let i=process.cwd(),s=o.name||"origin";if(!t.memoryRemoteAdd(i,e,s)){console.log(r.red("\n Failed to add remote. Is the memory DB initialized? Run `zibby memory init` first.\n"));return}console.log(""),console.log(r.green(` \u2713 Added remote ${r.bold(s)} \u2192 ${e}`)),console.log(r.gray(" Next step: zibby memory pull (or just run any test \u2014 middleware auto-pulls/pushes)")),console.log("")}async function pt(){let e=await R();if(!e)return;let o=e.memoryRemoteInfo(process.cwd());if(console.log(""),!o){console.log(r.yellow(` No memory remote configured.
|
|
47
|
+
`)),console.log(r.gray(" Set one with: zibby memory remote add <url>")),console.log(r.gray(` Without a remote, memory is local-only \u2014 team members won't see each other's learnings.
|
|
48
|
+
`));return}console.log(r.bold.cyan(" Memory remote")),console.log(` ${r.cyan(o.name||"origin")}: ${o.url||"(unknown)"}`),console.log("")}async function mt(e="origin"){let o=await R();if(!o)return;let t=o.memoryRemoteRemove(process.cwd(),e);console.log(""),t?(console.log(r.green(` \u2713 Removed remote ${e}.`)),console.log(r.gray(" Memory is now local-only."))):console.log(r.gray(` No remote named ${e} to remove.`)),console.log("")}async function gt(){let e=await R();if(!e)return;console.log(r.cyan(`
|
|
49
|
+
Pulling team memory from remote...`));let o=e.memorySyncPull(process.cwd());o.pulled?console.log(r.green(` \u2713 Pulled latest. Local memory now reflects the team's shared knowledge.
|
|
50
|
+
`)):(console.log(r.yellow(` \u26A0 Pull skipped \u2014 ${o.error||"unknown reason"}.`)),console.log(r.gray(" Did you run `zibby memory remote add <url>` first?\n")))}async function yt(e={}){let o=await R();if(!o)return;let{join:t}=await import("path"),{existsSync:i}=await import("fs"),s=e.cwd||process.cwd(),n=e.projectId;if(!n){let P=t(s,".zibby.config.mjs");if(i(P))try{let k=(await import(`file://${P}?t=${Date.now()}`)).default;n=k?.projectId||k?.project?.id}catch{}}n||(console.log(r.red(`
|
|
51
51
|
Could not determine projectId.
|
|
52
|
-
`)),console.log(
|
|
53
|
-
`)),process.exit(1));let{getApiUrl:
|
|
54
|
-
`)),process.exit(1)),console.log(
|
|
55
|
-
Configuring hosted memory-sync...`));let
|
|
56
|
-
Failed: ${
|
|
57
|
-
`)),process.exit(1)}let{writeConfig:v}=await Promise.resolve().then(()=>(
|
|
58
|
-
Saved hosted-sync config, but failed to register Dolt remote.`)),console.log(
|
|
59
|
-
Config saved, but initial credential fetch failed: ${
|
|
60
|
-
`))}console.log(""),console.log(
|
|
61
|
-
Pushing local memory to team remote...`));let e
|
|
62
|
-
`))}async function
|
|
52
|
+
`)),console.log(r.gray(" Either run this from a project dir with `.zibby.config.mjs`")),console.log(r.gray(` containing { projectId: "..." }, or pass --project-id <id>.
|
|
53
|
+
`)),process.exit(1));let{getApiUrl:u}=await Promise.resolve().then(()=>(We(),Ve)),{getSessionToken:d}=await Promise.resolve().then(()=>(re(),ne)),l=u(),m=d();m||(console.log(r.red("\n Not logged in. Run `zibby login` first.\n")),console.log(r.gray(" Hosted memory-sync is for signed-in users only \u2014")),console.log(r.gray(` the backend needs your identity to scope per-tenant credentials.
|
|
54
|
+
`)),process.exit(1)),console.log(r.cyan(`
|
|
55
|
+
Configuring hosted memory-sync...`));let w;try{let P=`${l.replace(/\/+$/,"")}/memory/sync-config?projectId=${encodeURIComponent(n)}`,S=await fetch(P,{headers:{Authorization:`Bearer ${m}`}});if(!S.ok){let k=await S.text().catch(()=>"");throw new Error(`backend returned ${S.status}: ${k||"no body"}`)}w=await S.json()}catch(P){console.log(r.red(`
|
|
56
|
+
Failed: ${P.message}
|
|
57
|
+
`)),process.exit(1)}let{writeConfig:v}=await Promise.resolve().then(()=>(ue(),de));v(s,{projectId:n,bucket:w.bucket,prefix:w.prefix,doltUrl:w.doltUrl}),o.memoryRemoteAdd(s,w.doltUrl)||(console.log(r.yellow(`
|
|
58
|
+
Saved hosted-sync config, but failed to register Dolt remote.`)),console.log(r.gray(" Try `zibby memory init` first (the local Dolt DB must exist).\n")),process.exit(1));let{refreshCredentials:h}=await Promise.resolve().then(()=>(ue(),de));try{await h({cwd:s,projectId:n,apiUrl:l,sessionToken:m})}catch(P){console.log(r.yellow(`
|
|
59
|
+
Config saved, but initial credential fetch failed: ${P.message}`)),console.log(r.gray(` Will retry on first push/pull.
|
|
60
|
+
`))}console.log(""),console.log(r.green(" \u2713 Hosted memory-sync configured.")),console.log(r.gray(` Bucket: ${w.bucket}`)),console.log(r.gray(` Prefix: ${w.prefix} \u2190 your tenant slot`)),console.log(r.gray(` Dolt: ${w.doltUrl}`)),console.log(""),console.log(r.gray(" Every test run will auto-pull/push. Creds refresh automatically.")),console.log(r.gray(" To revert to local-only: zibby memory remote remove origin")),console.log("")}async function ft(){let e=await R();if(!e)return;console.log(r.cyan(`
|
|
61
|
+
Pushing local memory to team remote...`));let o=e.memorySyncPush(process.cwd());o.pushed?console.log(r.green(" \u2713 Pushed. Team can now `zibby memory pull` to see your run's learnings.\n")):console.log(r.yellow(` \u26A0 Push skipped \u2014 ${o.error||"unknown reason"}.
|
|
62
|
+
`))}async function ht(){let e=await R();if(!e)return;let o=process.cwd();if(!e.DoltDB.isAvailable()){console.log(r.red(`
|
|
63
63
|
Dolt is not installed.
|
|
64
|
-
`)),console.log(
|
|
65
|
-
`));return}let{created:t,available:
|
|
64
|
+
`)),console.log(r.white(" Install Dolt:")),console.log(r.gray(" brew install dolt # macOS")),console.log(r.gray(` curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash # Linux
|
|
65
|
+
`));return}let{created:t,available:i}=e.initMemory(o);t?console.log(r.green(`
|
|
66
66
|
Memory database initialized at .zibby/memory/
|
|
67
|
-
`)):
|
|
67
|
+
`)):i&&console.log(r.gray(`
|
|
68
68
|
Memory database already initialized.
|
|
69
|
-
`))}var
|
|
69
|
+
`))}var it,ro=B(()=>{it=`
|
|
70
70
|
Install @zibby/ui-memory and Dolt to enable test memory:
|
|
71
71
|
|
|
72
72
|
npm install @zibby/ui-memory # add the package
|
|
73
73
|
brew install dolt # macOS
|
|
74
74
|
# or: curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash
|
|
75
|
-
`});var
|
|
76
|
-
`,"utf-8")}async function
|
|
77
|
-
`).find(
|
|
78
|
-
`,"utf-8"),
|
|
75
|
+
`});var yo={};N(yo,{setupCiCommand:()=>$t,setupPlaywrightMcpCommand:()=>go,testWithVideoCommand:()=>St});import{spawn as me,execSync as ge}from"child_process";import{join as L,dirname as ye,resolve as ao}from"path";import{readFileSync as lo,writeFileSync as co,existsSync as Z,mkdirSync as uo}from"fs";import{homedir as po}from"os";import{createRequire as bt}from"module";import _ from"chalk";function wt(){try{return ye(pe.resolve("@zibby/core/package.json"))}catch{return null}}function mo(e){try{return ge(`command -v ${e}`,{stdio:"pipe"}),!0}catch{return!1}}function vt(){try{let e=pe.resolve("@zibby/mcp-browser/bin/mcp-browser-zibby.js");if(Z(e))return e}catch{}try{let e=pe.resolve("@playwright/mcp/package.json"),o=ye(e),t=JSON.parse(lo(e,"utf-8")),i=typeof t.bin=="string"?t.bin:t.bin?.["playwright-mcp"];if(i){let n=L(o,i);if(Z(n))return n}let s=L(o,"cli.js");if(Z(s))return s}catch{}return null}function so(e,o,t={}){return new Promise((i,s)=>{let n=me(e,o,{stdio:"inherit",...t});n.on("close",u=>i(u??1)),n.on("error",s)})}async function kt(e){return mo("playwright")?await so("playwright",["install","ffmpeg"],{cwd:e})===0:await so("npx",["--yes","playwright","install","ffmpeg"],{cwd:e})===0}function xt({headed:e=!1,viewport:o=null}){let t=process.execPath,i=ye(t),s=vt(),n=Number(o?.width)||1280,u=Number(o?.height)||720,d=`${n}x${u}`,l=[];l.push(`--viewport-size=${d}`,"--output-dir=test-results"),e||l.push("--headless");let m;s?m={command:t,args:[s,...l],env:{PATH:`${i}:/usr/bin:/bin:/usr/sbin:/sbin`}}:m={command:"npx",args:["-y","@playwright/mcp",...l],env:{PATH:`${i}:/usr/bin:/bin:/usr/sbin:/sbin`}},m.description="Zibby MCP Browser - Playwright MCP with Zibby defaults";let w=L(po(),".cursor"),v=L(w,"mcp.json");Z(w)||uo(w,{recursive:!0});let h={mcpServers:{}};if(Z(v))try{h=JSON.parse(lo(v,"utf-8")),(!h.mcpServers||typeof h.mcpServers!="object")&&(h.mcpServers={})}catch{h={mcpServers:{}}}h.mcpServers["playwright-official"]=m,co(v,`${JSON.stringify(h,null,2)}
|
|
76
|
+
`,"utf-8")}async function _t(){let e=wt();if(!e)return;let o=L(e,"scripts","patch-cursor-mcp.js");if(Z(o))try{await new Promise((t,i)=>{let s=me(process.execPath,[o],{cwd:process.cwd(),stdio:"ignore"});s.on("close",n=>t(n??0)),s.on("error",i)})}catch{}}function It(e){return ao(e).replace(/^\/+/,"").replace(/\//g,"-")}function At(e){let o=String(e||""),t=o.split(`
|
|
77
|
+
`).find(n=>/playwright-official/i.test(n)&&/APPROVAL|🔑/i.test(n));if(t){let n=t.match(/=>\s*(\S+)/);if(n)return n[1]}let i=o.match(/playwright-official[^=]*=>\s*(\S+)/);if(i)return i[1];let s=o.match(/playwright-official-[a-f0-9]+/i);return s?s[0]:null}function Pt(e,o){let t=It(e),i=L(po(),".cursor","projects",t);uo(i,{recursive:!0});let s=L(i,"mcp-approvals.json");return co(s,`${JSON.stringify([o],null,2)}
|
|
78
|
+
`,"utf-8"),s}function io(e){try{return ge("cursor-agent mcp list",{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:process.env,maxBuffer:2*1024*1024})}catch(o){let t=o.stdout!=null?String(o.stdout):"",i=o.stderr!=null?String(o.stderr):"";return t+i}}function Ct(e){try{return ge("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 go(e={}){let o=!!e.headed,t=e.viewport||{width:1280,height:720};if(!process.execPath)throw new Error("Node.js runtime not found");let i=await kt(process.cwd());console.log(i?_.gray(" \u2713 ffmpeg installed for Playwright video"):_.yellow(" \u26A0 Could not install ffmpeg (video may be unavailable)")),xt({headed:o,viewport:t}),await _t();let s=ao(process.cwd());if(mo("cursor-agent")){io(s);let n=Ct(s);n&&console.log(_.gray(" \u2713 cursor-agent: mcp enable playwright-official"));let u=io(s),d=At(u);if(d)try{let l=Pt(s,d);console.log(_.gray(` \u2713 MCP auto-approval key saved (${l})`))}catch(l){console.log(_.yellow(` \u26A0 Could not write mcp-approvals.json: ${l.message}`))}else n||(console.log(_.yellow(" \u26A0 Could not auto-approve MCP (mcp enable failed and no approval key in cursor-agent output)")),console.log(_.gray(" Try: cursor-agent mcp enable playwright-official")))}else console.log(_.yellow(" \u26A0 cursor-agent not found; install it to use Cursor MCP tools"))}async function $t(e){try{console.log(_.cyan(`
|
|
79
79
|
\u{1F680} Running CI setup...
|
|
80
|
-
`)),await go({headed:!1,cloudSync:!0,viewport:{width:1280,height:720}}),console.log(
|
|
80
|
+
`)),await go({headed:!1,cloudSync:!0,viewport:{width:1280,height:720}}),console.log(_.green(`
|
|
81
81
|
\u2705 CI/CD setup complete!
|
|
82
|
-
`))}catch(
|
|
83
|
-
\u274C Error: ${
|
|
84
|
-
`)),process.exit(1)}}async function
|
|
82
|
+
`))}catch(o){console.log(_.red(`
|
|
83
|
+
\u274C Error: ${o.message}
|
|
84
|
+
`)),process.exit(1)}}async function St(e,o){try{let t=["playwright","test",e||"tests/","--project=chromium"];o.headed&&t.push("--headed"),console.log(_.cyan(`
|
|
85
85
|
\u{1F3A5} Running tests with video recording...
|
|
86
|
-
`)),console.log(
|
|
86
|
+
`)),console.log(_.gray("\u2501".repeat(50)));let i=me("npx",t,{cwd:process.cwd(),stdio:"inherit"});i.on("close",s=>{s===0?console.log(_.green(`
|
|
87
87
|
\u2705 Tests complete!
|
|
88
|
-
`)):(console.log(
|
|
89
|
-
\u274C Tests failed with code ${
|
|
90
|
-
`)),process.exit(
|
|
91
|
-
\u274C Error: ${
|
|
92
|
-
`)),process.exit(1)})}catch(t){console.log(
|
|
88
|
+
`)):(console.log(_.red(`
|
|
89
|
+
\u274C Tests failed with code ${s}
|
|
90
|
+
`)),process.exit(s))}),i.on("error",s=>{console.log(_.red(`
|
|
91
|
+
\u274C Error: ${s.message}
|
|
92
|
+
`)),process.exit(1)})}catch(t){console.log(_.red(`
|
|
93
93
|
\u274C Error: ${t.message}
|
|
94
|
-
`)),process.exit(1)}}var
|
|
95
|
-
`,"utf-8")}async function
|
|
96
|
-
`));return}console.log(
|
|
97
|
-
To add manually on Windows:`)),console.log(
|
|
98
|
-
`))):(console.log(
|
|
99
|
-
To add manually, run:`)),console.log(
|
|
100
|
-
`)));return}if(
|
|
101
|
-
`));return}let l=process.env.SHELL||"",
|
|
102
|
-
`));return}}let
|
|
94
|
+
`)),process.exit(1)}}var pe,fo=B(()=>{pe=bt(import.meta.url)});import{mkdir as D,writeFile as C,readFile as F}from"fs/promises";import{existsSync as I,readdirSync as Et}from"fs";import{join as f,resolve as ho,dirname as Rt}from"path";import{homedir as M}from"os";import U from"inquirer";import a from"chalk";import K from"ora";import{spawn as V,execSync as ee}from"child_process";import{fileURLToPath as zt}from"url";import{createRequire as Tt}from"module";import{existsSync as wo,readFileSync as vo,writeFileSync as ko,mkdirSync as xo}from"fs";import{join as he}from"path";import{homedir as be}from"os";var q={cursor:{envVar:"CURSOR_API_KEY",label:"Cursor API Key",url:"https://cursor.com/settings"},claude:{envVar:"ANTHROPIC_API_KEY",label:"Anthropic API Key",url:"https://console.anthropic.com/settings/keys"},codex:{envVar:"OPENAI_API_KEY",label:"OpenAI API Key",url:"https://platform.openai.com/api-keys"},gemini:{envVar:"GEMINI_API_KEY",label:"Gemini API Key",url:"https://aistudio.google.com/app/apikey"}};function we(){return he(be(),".zibby","config.json")}function J(){try{let e=we();return wo(e)?JSON.parse(vo(e,"utf-8")):{}}catch{return{}}}function ve(e,o){let t=o?q[o]:null;t&&oe(t.envVar,e)}function oe(e,o){if(!e||typeof e!="string"||!o||typeof o!="string")return;let t=he(be(),".zibby");xo(t,{recursive:!0});let i=we(),s=J();(!s.agentKeys||typeof s.agentKeys!="object")&&(s.agentKeys={}),s.agentKeys[e]=String(o).trim(),delete s.agentApiKey,ko(i,`${JSON.stringify(s,null,2)}
|
|
95
|
+
`,"utf-8")}async function Ot(){let e=J(),o=process.env.ANTHROPIC_API_KEY||e.agentKeys?.ANTHROPIC_API_KEY,t=e.agentKeys?.CLAUDE_CODE_OAUTH_TOKEN||null;console.log(""),console.log(a.cyan(" Claude credentials \u2014 pick the type you have:")),console.log("");let{kind:i}=await U.prompt([{type:"select",name:"kind",message:"Which Claude credential do you want to use?",choices:[{name:t?`OAuth ***${t.slice(-4)} \xB7 Pro/Max plan`:"OAuth \xB7 Pro/Max plan (long-lived token)",value:"oauth"},{name:o?`API key ***${o.slice(-4)} \xB7 pay-per-token`:"API key \xB7 pay-per-token",value:"api"}],default:t?"oauth":o?"api":"oauth"}]);if(i==="skip")return{kind:"skip"};if(i==="oauth"){t||(console.log(""),console.log(a.gray(" How to generate a long-lived OAuth token (cloud-compatible):")),console.log(a.gray(" 1. Install claude (skip if you already have it):")),console.log(a.gray(" npm install -g @anthropic-ai/claude-code")),console.log(a.gray(" 2. Run:")),console.log(a.gray(" claude setup-token")),console.log(a.gray(" \u2192 confirms in your browser \u2192 prints a token starting with sk-ant-oat01-\u2026")),console.log(a.gray(" 3. Paste that token below.")),console.log(""),console.log(a.yellow(" Note: do NOT paste the short-lived token from `claude` browser-login \u2014")),console.log(a.yellow(" it works locally but Anthropic rejects it from non-login IPs (cloud).")),console.log(""));let d=t?`Press Enter to reuse saved token (***${t.slice(-4)}), or paste a new one:`:"Paste OAuth token from `claude setup-token` (or press Enter to skip):",{token:l}=await U.prompt([{type:"password",name:"token",message:d,mask:"*"}]),m=(l||"").trim();return m?{kind:"oauth",token:m}:t?{kind:"oauth",token:t}:{kind:"skip"}}let s=o?`Press Enter to reuse saved API key (***${o.slice(-4)}), or paste a new one:`:"Paste Anthropic API key (from https://console.anthropic.com/settings/keys, or press Enter to skip):",{token:n}=await U.prompt([{type:"password",name:"token",message:s,mask:"*"}]),u=(n||"").trim();return u?{kind:"api",token:u}:o?{kind:"api",token:o}:{kind:"skip"}}var Kt=zt(import.meta.url),Mt=Rt(Kt),Bt=Tt(import.meta.url);async function Nt(){try{let e=process.platform==="win32",o=ee("npm config get prefix",{encoding:"utf-8"}).trim(),t=e?o:`${o}/bin`,i=t.replace(/^~/,M()),s=e?";":":";if(process.env.PATH.split(s).some(v=>{let h=v.replace(/^~/,M());return h===i||h===t}))return;if(process.env.CI||process.env.ZIBBY_CI||!process.stdin.isTTY){console.log(a.yellow("npm global bin not in PATH")),console.log(a.gray(` Location: ${i}`)),console.log(a.gray(` Add it manually: export PATH="${i}:$PATH"
|
|
96
|
+
`));return}console.log(a.yellow("npm global bin not in PATH")),console.log(a.gray(` Location: ${i}`)),console.log();let{shouldAddPath:d}=await U.prompt([{type:"confirm",name:"shouldAddPath",message:"Add npm global bin to your shell PATH automatically?",default:!0}]);if(!d){e?(console.log(a.gray(`
|
|
97
|
+
To add manually on Windows:`)),console.log(a.gray(' 1. Search "Environment Variables" in Start menu')),console.log(a.gray(' 2. Edit "Path" in User variables')),console.log(a.gray(` 3. Add: ${i}
|
|
98
|
+
`))):(console.log(a.gray(`
|
|
99
|
+
To add manually, run:`)),console.log(a.gray(` echo 'export PATH="${i}:$PATH"' >> ~/.zshrc`)),console.log(a.gray(` source ~/.zshrc
|
|
100
|
+
`)));return}if(e){console.log(a.yellow("Cannot auto-add PATH on Windows")),console.log(a.gray(" Please add manually:")),console.log(a.gray(' 1. Search "Environment Variables" in Start menu')),console.log(a.gray(' 2. Edit "Path" in User variables')),console.log(a.gray(` 3. Add: ${i}
|
|
101
|
+
`));return}let l=process.env.SHELL||"",m="";if(l.includes("zsh"))m=f(M(),".zshrc");else if(l.includes("bash"))m=I(f(M(),".bashrc"))?f(M(),".bashrc"):f(M(),".bash_profile");else{console.log(a.yellow(`Unknown shell: ${l}`)),console.log(a.gray(" Please add manually:")),console.log(a.gray(` export PATH="${i}:$PATH"`));return}if(I(m)){let v=await F(m,"utf-8");if(v.includes(i)||v.includes("npm")&&v.includes("global")&&v.includes("bin")){console.log(a.yellow(`PATH entry found in ${m} but not active`)),console.log(a.gray(` Run: source ${m}
|
|
102
|
+
`));return}}let w=`
|
|
103
103
|
# npm global bin (added by zibby)
|
|
104
|
-
export PATH="${
|
|
105
|
-
`;await
|
|
106
|
-
Run this to activate in current session:`)),console.log(
|
|
107
|
-
`))}catch{}}async function
|
|
104
|
+
export PATH="${i}:$PATH"
|
|
105
|
+
`;await C(m,(I(m)?await F(m,"utf-8"):"")+w),console.log(a.green(`Added to ${m}`)),console.log(a.yellow(`
|
|
106
|
+
Run this to activate in current session:`)),console.log(a.gray(` source ${m}
|
|
107
|
+
`))}catch{}}async function Rn(e,o){let t=o.template==="browser-test-automation";console.log(t?`
|
|
108
108
|
Zibby Test Automation
|
|
109
109
|
`:`
|
|
110
110
|
Zibby Project Init
|
|
111
|
-
`);let
|
|
112
|
-
Directory "${
|
|
113
|
-
`)),process.exit(1)),!
|
|
111
|
+
`);let i=!o.skipMemory,s=["dolt","mem0"].includes(String(o.memoryBackend||"").toLowerCase())?String(o.memoryBackend).toLowerCase():"dolt";await Nt();let n=e?ho(process.cwd(),e):process.cwd(),u=e||"zibby-tests",d=!!e;d&&I(n)&&(console.log(a.red(`
|
|
112
|
+
Directory "${e}" already exists!
|
|
113
|
+
`)),process.exit(1)),!d&&I(f(n,".zibby.config.mjs"))&&!o.force&&(console.log(a.yellow(`
|
|
114
114
|
Zibby is already initialized in this directory!
|
|
115
|
-
`)),console.log(
|
|
116
|
-
`)),process.exit(0)),
|
|
115
|
+
`)),console.log(a.white("Config file found: .zibby.config.mjs")),console.log(a.gray(`Use --force or -f to reinitialize
|
|
116
|
+
`)),process.exit(0)),o.force&&!d&&console.log(a.cyan(`
|
|
117
117
|
Reinitializing Zibby configuration...
|
|
118
|
-
`));let l;if(
|
|
119
|
-
`)),l={agent:
|
|
118
|
+
`));let l;if(o.agent&&(o.headed||o.headless))console.log(a.cyan(`Setting up with provided options...
|
|
119
|
+
`)),l={agent:o.agent,browserMode:o.headless?"headless":"headed",apiKey:o.apiKey||null,cloudSync:!!(o.cloudSync||o.apiKey)};else{if(o.agent)l={agent:o.agent};else{let{agent:k}=await U.prompt([{type:"select",name:"agent",message:"Which AI agent do you prefer?",choices:[{name:"Claude (Anthropic)",value:"claude"},{name:"Cursor",value:"cursor"},{name:"Codex (OpenAI)",value:"codex"},{name:"Gemini (Google)",value:"gemini"}],default:"claude"}]);l={agent:k}}let h=q[l.agent],P=!(process.env.CI||process.env.ZIBBY_CI||!process.stdin.isTTY);if(l.agent==="claude"&&!o.agentKey&&P){let k=await Ot();k?.kind==="oauth"&&k.token?(l.claudeOauthToken=k.token,l.agentAuth="oauth"):k?.kind==="api"&&k.token&&(l.agentKey=k.token,l.agentAuth="api")}else if(h&&!o.agentKey&&P){let k=J(),c=process.env[h.envVar]||k.agentKeys?.[h.envVar],g=c?`***${c.slice(-4)}`:null,p=g?`${h.label} found (${g}). Press Enter to keep, or paste a new key:`:`Enter ${h.label} (from ${h.url}, or press Enter to skip):`,{agentKey:b}=await U.prompt([{type:"password",name:"agentKey",message:p,mask:"*"}]);b&&b.trim()&&(l.agentKey=b.trim(),l.agentAuth="api")}let S=[];if(t&&!o.headed&&!o.headless&&S.push({type:"select",name:"browserMode",message:"Browser mode during live AI execution?",choices:[{name:"Headed - Visible browser (recommended for development)",value:"headed"},{name:"Headless - Hidden browser (for CI/CD)",value:"headless"}],default:"headed"}),t&&!o.apiKey&&S.push({type:"input",name:"apiKey",message:"Project ZIBBY_API_KEY for test-result cloud sync (uploads runs to your team's zibby.dev dashboard) \u2014 paste or press Enter to skip:"}),S.length>0){let k=await U.prompt(S);Object.assign(l,k)}l.browserMode=o.headless?"headless":o.headed?"headed":l.browserMode,l.apiKey=o.apiKey||l.apiKey,l.cloudSync=!!(o.cloudSync||o.apiKey||l.apiKey&&l.apiKey.trim())}o.agentKey&&(l.agentKey=o.agentKey),o.agentOauthToken&&l.agent==="claude"&&(l.claudeOauthToken=o.agentOauthToken);let w=q[l.agent];l.claudeOauthToken&&(oe("CLAUDE_CODE_OAUTH_TOKEN",l.claudeOauthToken),console.log(a.gray(" Claude OAuth subscription token saved to ~/.zibby/config.json")),console.log(a.gray(" Used by: zibby test / chat / workflow run / workflow start"))),l.agentKey&&(ve(l.agentKey,l.agent),console.log(a.gray(" Agent API key saved to ~/.zibby/config.json"))),l.mcp="playwright",l.setupMcp=l.agent==="cursor";let v=K("Setting up Zibby...").start();try{if(d&&await D(n,{recursive:!0}),t&&(await D(f(n,"test-specs/examples"),{recursive:!0}),await D(f(n,"tests"),{recursive:!0})),await D(f(n,".zibby/output"),{recursive:!0}),await D(f(n,".zibby/commands"),{recursive:!0}),i&&s==="dolt")try{let{initMemory:c,DoltDB:g}=await import("@zibby/ui-memory");if(g.isAvailable()){let{created:p}=c(n);p&&(v.text="Initialized test memory database (Dolt)...")}else v.text="Dolt not found \u2014 skipping memory database (brew install dolt)"}catch{}let h=o.template,P=h&&h!=="none"&&h!=="false";if(P){v.text=`Scaffolding workflow template: ${h}...`;try{let{writeTemplateFiles:c}=await Promise.resolve().then(()=>(Ce(),Pe));await c(n,h,{enableMemory:i})}catch(c){throw v.fail(`Failed to scaffold template: ${c.message}`),c}}else await D(f(n,".zibby"),{recursive:!0});v.text="Generating configuration files...";let S=jt(l,o,{memoryBackend:s});if(await C(f(n,".zibby.config.mjs"),S),await C(f(n,".env.example"),Lt(l,s)),l.apiKey&&l.apiKey.trim()){let c=f(n,".env"),g=l.apiKey.trim();if(I(c)){let p=await F(c,"utf8");/^ZIBBY_API_KEY=/m.test(p)?p=p.replace(/^ZIBBY_API_KEY=.*/m,`ZIBBY_API_KEY=${g}`):/^#\s*ZIBBY_API_KEY=/m.test(p)?p=p.replace(/^#\s*ZIBBY_API_KEY=.*/m,`ZIBBY_API_KEY=${g}`):p=`${p.trimEnd()}
|
|
120
120
|
|
|
121
121
|
# Zibby Cloud Sync
|
|
122
122
|
ZIBBY_API_KEY=${g}
|
|
123
|
-
`,await
|
|
123
|
+
`,await C(c,p)}else await C(c,Dt(l,g,s))}if(l.agentKey&&w){let c=f(n,".env"),g=l.agentKey;if(I(c)){let p=await F(c,"utf8"),b=new RegExp(`^${w.envVar}=.*`,"m"),y=new RegExp(`^#\\s*${w.envVar}=.*`,"m");b.test(p)?p=p.replace(b,`${w.envVar}=${g}`):y.test(p)?p=p.replace(y,`${w.envVar}=${g}`):p=`${p.trimEnd()}
|
|
124
124
|
|
|
125
125
|
# AI Agent Key
|
|
126
|
-
${
|
|
127
|
-
`,await
|
|
128
|
-
|
|
129
|
-
`))
|
|
130
|
-
`)))}}}if(!u&&a&&i==="mem0"&&(console.log(r.yellow(`
|
|
131
|
-
Using mem0 backend requires mem0ai in your project dependencies.`)),console.log(r.gray("Run this manually in your project when ready:")),console.log(r.white(` npm install mem0ai
|
|
132
|
-
`))),!e.skipInstall&&t){let c=T("Installing Playwright browsers...").start();await new Promise(g=>{let d=G("npx",["playwright","install","chromium"],{cwd:s,stdio:"pipe"}),f="";d.stdout.on("data",m=>{f+=m.toString()}),d.stderr.on("data",m=>{f+=m.toString()}),d.on("close",m=>{m===0?(f.includes("already installed")||f.includes("up to date")?c.succeed("Playwright browsers already installed"):c.succeed("Playwright browsers installed!"),g()):(c.warn("Could not verify Playwright browsers"),console.log(r.yellow(`
|
|
126
|
+
${w.envVar}=${g}
|
|
127
|
+
`,await C(c,p)}}if(d){let c=Ut(u,l,{memoryBackend:s});await C(f(n,"package.json"),c)}if(!I(f(n,".gitignore"))){let c=Yt();await C(f(n,".gitignore"),c)}if(t){if(!I(f(n,"playwright.config.js"))){let c=Zt("on");await C(f(n,"playwright.config.js"),c)}if(!I(f(n,"test-specs/examples/example-domain.txt"))){let c=Ft();await C(f(n,"test-specs/examples/example-domain.txt"),c)}}let k=ho(Mt,"../../../../examples/.zibby/commands");if(I(k)){let c=Et(k).filter(g=>g.toLowerCase().endsWith(".md"));for(let g of c){let p=f(n,".zibby/commands",g);if(o.force||!I(p)){let b=await F(f(k,g),"utf-8");await C(p,b)}}}if(!I(f(n,".zibby/commands/example.md"))){let c=Ht();await C(f(n,".zibby/commands/example.md"),c)}if(d){let c=Gt(u,l);await C(f(n,"README.md"),c)}try{let{validateMemorySyncConfig:c,applyMemorySyncConfig:g}=await Promise.resolve().then(()=>(Re(),Ee)),p=f(n,".zibby.config.mjs"),b=null;if(I(p))try{b=(await import(`file://${p}?t=${Date.now()}`)).default?.memorySync}catch{}let y=c(b);if(y.ok&&y.kind!=="noop"){let E=await import("@zibby/ui-memory").catch(()=>null),{getSessionToken:W}=await Promise.resolve().then(()=>(re(),ne)),z=await g({cwd:n,projectId:l.projectId,block:b,memoryApi:E,getSessionToken:W,hostedSetup:async({cwd:H,projectId:G})=>{let{memoryRemoteUseHostedCommand:fe}=await Promise.resolve().then(()=>(ro(),no));await fe({cwd:H,projectId:G})},logger:{info:()=>{},warn:()=>{},error:()=>{}}});z.action==="hosted"?console.log(a.green(" \u2713 Hosted memory-sync configured from .zibby.config.mjs")):z.action==="byo"?console.log(a.green(` \u2713 Memory remote configured from .zibby.config.mjs \u2192 ${z.remote}`)):z.action==="pending-login"?(console.log(a.yellow(` \u26A0 memorySync.remote = "hosted" but you're not logged in.`)),console.log(a.gray(" Run `zibby login` then `zibby memory remote use --hosted` to finish."))):z.action==="error"&&console.log(a.yellow(` \u26A0 memorySync setup skipped: ${z.reason}`))}else y.ok||console.log(a.yellow(` \u26A0 memorySync config invalid: ${y.error}`))}catch(c){console.log(a.yellow(` \u26A0 memorySync auto-apply failed: ${c.message}`))}if(v.succeed(d?"Project created!":"Zibby initialized!"),P||(console.log(""),console.log(a.gray(" No workflow scaffolded. Add one when ready:")),console.log(a.gray(" zibby template list # see available")),console.log(a.gray(" zibby workflow new <slug> -t <template> # named, deployable copy")),console.log("")),d&&!o.skipInstall){let c=K("Installing dependencies...").start();await new Promise((g,p)=>{V("npm",["install"],{cwd:n,stdio:"pipe"}).on("close",y=>{y===0?(c.succeed("Dependencies installed!"),g()):(c.fail("Failed to install dependencies"),p(new Error("npm install failed")))})})}if(!d&&i&&s==="mem0"&&(console.log(a.yellow(`
|
|
128
|
+
Using mem0 backend requires mem0ai in your project dependencies.`)),console.log(a.gray("Run this manually in your project when ready:")),console.log(a.white(` npm install mem0ai
|
|
129
|
+
`))),!o.skipInstall&&t){let c=K("Installing Playwright browsers...").start();await new Promise(g=>{let p=V("npx",["playwright","install","chromium"],{cwd:n,stdio:"pipe"}),b="";p.stdout.on("data",y=>{b+=y.toString()}),p.stderr.on("data",y=>{b+=y.toString()}),p.on("close",y=>{y===0?(b.includes("already installed")||b.includes("up to date")?c.succeed("Playwright browsers already installed"):c.succeed("Playwright browsers installed!"),g()):(c.warn("Could not verify Playwright browsers"),console.log(a.yellow(`
|
|
133
130
|
If tests fail, run: npx playwright install
|
|
134
|
-
`)),g())})})}if(l.agent==="cursor"&&!
|
|
135
|
-
`))}}}if(l.agent==="codex"&&!
|
|
136
|
-
`))}}}if(l.agent==="gemini"&&!
|
|
137
|
-
`))}}if(t){let g=
|
|
138
|
-
`,"utf-8");let
|
|
139
|
-
`))}}}if(l.agent==="cursor"&&l.setupMcp&&t){let c=
|
|
131
|
+
`)),g())})})}if(l.agent==="cursor"&&!o.skipInstall){let c=K("Checking cursor-agent CLI...").start();try{ee("cursor-agent --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),c.succeed("cursor-agent CLI already installed")}catch{c.text="Installing cursor-agent CLI...";try{await new Promise((g,p)=>{V("bash",["-c","curl https://cursor.com/install -fsS | bash"],{stdio:"pipe"}).on("close",y=>{if(y===0){let E=f(M(),".local","bin");process.env.PATH.includes(E)||(process.env.PATH=`${E}:${process.env.PATH}`),c.succeed("cursor-agent CLI installed!"),g()}else p(new Error("cursor-agent install failed"))})})}catch{c.fail("Could not install cursor-agent CLI"),console.log(a.yellow(` Install manually: curl https://cursor.com/install -fsS | bash
|
|
132
|
+
`))}}}if(l.agent==="codex"&&!o.skipInstall){let c=K("Checking Codex CLI...").start();try{ee("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),c.succeed("Codex CLI already installed")}catch{c.text="Installing Codex CLI...";try{await new Promise((g,p)=>{V("npm",["install","-g","@openai/codex"],{stdio:"pipe"}).on("close",y=>{y===0?(c.succeed("Codex CLI installed!"),g()):p(new Error("npm install -g @openai/codex failed"))})})}catch{c.fail("Could not install Codex CLI"),console.log(a.yellow(` Install manually: npm install -g @openai/codex
|
|
133
|
+
`))}}}if(l.agent==="gemini"&&!o.skipInstall){let c=K("Checking Gemini CLI...").start();try{ee("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),c.succeed("Gemini CLI already installed")}catch{c.text="Installing Gemini CLI...";try{await new Promise((g,p)=>{V("npm",["install","-g","@google/gemini-cli"],{stdio:"pipe"}).on("close",y=>{y===0?(c.succeed("Gemini CLI installed!"),g()):p(new Error("npm install -g @google/gemini-cli failed"))})})}catch{c.fail("Could not install Gemini CLI"),console.log(a.yellow(` Install manually: npm install -g @google/gemini-cli
|
|
134
|
+
`))}}if(t){let g=K("Configuring Gemini MCP servers...").start();try{let p=f(M(),".gemini"),b=f(p,"settings.json");I(p)||await D(p,{recursive:!0});let y={mcpServers:{}};if(I(b))try{let G=await F(b,"utf-8");y=JSON.parse(G),y.mcpServers||(y.mcpServers={})}catch{}let E;try{let{createRequire:G}=await import("module");E=G(import.meta.url).resolve("@zibby/mcp-browser/bin/mcp-browser-zibby.js")}catch{E="@playwright/mcp"}let W=l.browserMode!=="headless",z=E==="@playwright/mcp"?["-y","@playwright/mcp","--isolated","--viewport-size=1280x720","--output-dir","test-results"]:[E,"--isolated","--viewport-size=1280x720","--output-dir=test-results"];W||z.push("--headless"),y.mcpServers["playwright-official"]={command:E==="@playwright/mcp"?"npx":"node",args:z},await C(b,`${JSON.stringify(y,null,2)}
|
|
135
|
+
`,"utf-8");let H="Gemini MCP configured";W?H+=" (headed mode - visible browser)":H+=" (headless mode - hidden browser)",g.succeed(H)}catch(p){g.fail("MCP setup failed"),console.log(a.yellow(" You may need to configure ~/.gemini/settings.json manually")),console.log(a.gray(` Error: ${p.message}
|
|
136
|
+
`))}}}if(l.agent==="cursor"&&l.setupMcp&&t){let c=K("Setting up Playwright MCP...").start();try{let{setupPlaywrightMcpCommand:g}=await Promise.resolve().then(()=>(fo(),yo)),p=l.cloudSync||!1,b=l.browserMode!=="headless";await g({headed:b,cloudSync:p,viewport:{width:1280,height:720}});let y="Playwright MCP configured";b?y+=" (headed mode - visible browser)":y+=" (headless mode - hidden browser)",p&&(y+=" + Zibby MCP (cloud sync)"),c.succeed(y),p&&!(l.apiKey&&l.apiKey.trim())&&console.log(a.gray(`
|
|
140
137
|
Copy .env.example to .env and set ZIBBY_API_KEY to enable uploads
|
|
141
|
-
`))}catch(g){c.fail("MCP setup script failed"),console.log(
|
|
142
|
-
`)),console.log(
|
|
143
|
-
`))}}console.log(
|
|
138
|
+
`))}catch(g){c.fail("MCP setup script failed"),console.log(a.yellow(" Check if MCP is already configured:")),console.log(a.gray(' \u2022 Open Cursor settings \u2192 Check "playwright-official" MCP')),console.log(a.gray(" \u2022 Run: cursor-agent mcp list")),console.log(a.gray(` \u2022 Or run manually: zibby setup-playwright
|
|
139
|
+
`)),console.log(a.gray(` Error: ${g.message}
|
|
140
|
+
`))}}console.log(a.bold.green(`
|
|
144
141
|
All set!
|
|
145
|
-
`)),
|
|
146
|
-
`))),t?(console.log(
|
|
147
|
-
`)),console.log(
|
|
148
|
-
`))):(console.log(
|
|
149
|
-
`)),console.log(
|
|
150
|
-
|
|
151
|
-
`)))}
|
|
152
|
-
|
|
153
|
-
`)),process.exit(1)}}function Pt(o,e={},t={}){let a=["dolt","mem0"].includes(String(t.memoryBackend||"").toLowerCase())?String(t.memoryBackend).toLowerCase():"dolt",i=o.agentAuth==="oauth"||o.agentAuth==="api"?`
|
|
154
|
-
auth: '${o.agentAuth}', // 'oauth' (subscription) or 'api' (pay-per-token); cloud needs 'api'`:"",s={claude:`
|
|
142
|
+
`)),d&&(console.log(a.cyan("Get into the project:")),console.log(a.white(` cd ${e}
|
|
143
|
+
`))),t?(console.log(a.cyan("Run a test:")),console.log(a.white(` zibby test test-specs/examples/example-domain.txt
|
|
144
|
+
`)),console.log(a.cyan("Cloud features (optional):")),console.log(a.white(` zibby login ${a.gray("# unlock workflow deploy, hosted memory, etc.")}`)),console.log(""),console.log(a.cyan("Next steps:")),console.log(a.white(` 1. cp .env.example .env ${a.gray("# then add your API keys")}`)),console.log(a.white(` 2. Write test specs in ${a.bold("test-specs/")}`)),console.log(a.white(` 3. Run: ${a.bold("zibby test <spec-file>")}`)),console.log(a.white(` 4. Or chat: ${a.bold("zibby")}
|
|
145
|
+
`))):(console.log(a.cyan("Add a workflow when ready:")),console.log(a.white(` zibby template list ${a.gray("# see available")}`)),console.log(a.white(` zibby workflow new my-pipeline ${a.gray("# blank scaffold")}`)),console.log(a.white(` zibby workflow new my-pip -t <name> ${a.gray("# from a template")}
|
|
146
|
+
`)),console.log(a.cyan("Cloud features (optional):")),console.log(a.white(` zibby login ${a.gray("# unlock workflow deploy, hosted memory, etc.")}`)),console.log(""))}catch(h){v.fail("Failed to create project"),console.error(a.red(`
|
|
147
|
+
Error: ${h.message}
|
|
148
|
+
`)),process.exit(1)}}function jt(e,o={},t={}){let i=["dolt","mem0"].includes(String(t.memoryBackend||"").toLowerCase())?String(t.memoryBackend).toLowerCase():"dolt",s=e.agentAuth==="oauth"||e.agentAuth==="api"?`
|
|
149
|
+
auth: '${e.agentAuth}', // 'oauth' (subscription) or 'api' (pay-per-token); cloud needs 'api'`:"",n={claude:`
|
|
155
150
|
claude: {
|
|
156
151
|
model: 'auto', // Options: 'auto', 'sonnet-4.6', 'opus-4.6', 'sonnet-4.5', 'opus-4.5'
|
|
157
|
-
maxTokens: 4096,${
|
|
152
|
+
maxTokens: 4096,${e.agent==="claude"?s:""}
|
|
158
153
|
},`,cursor:`
|
|
159
154
|
cursor: {
|
|
160
|
-
model: 'auto', // Options: 'auto', 'opus-4.5', 'opus-4.5-thinking', 'sonnet-4.5', 'sonnet-4.5-thinking', 'composer-1', 'gpt-5.2-codex', 'gpt-5.2', 'gpt-5.3', 'gpt-5.4', 'gemini-3-pro', 'gemini-3-flash'${
|
|
155
|
+
model: 'auto', // Options: 'auto', 'opus-4.5', 'opus-4.5-thinking', 'sonnet-4.5', 'sonnet-4.5-thinking', 'composer-1', 'gpt-5.2-codex', 'gpt-5.2', 'gpt-5.3', 'gpt-5.4', 'gemini-3-pro', 'gemini-3-flash'${e.agent==="cursor"?s:""}
|
|
161
156
|
},`,codex:`
|
|
162
157
|
codex: {
|
|
163
|
-
model: 'gpt-5.2-codex', // Options: 'auto', 'o4-mini', 'o3', 'codex-mini', 'gpt-4o', 'gpt-5.2-codex', 'gpt-5.2', 'gpt-5.3', 'gpt-5.4'${
|
|
158
|
+
model: 'gpt-5.2-codex', // Options: 'auto', 'o4-mini', 'o3', 'codex-mini', 'gpt-4o', 'gpt-5.2-codex', 'gpt-5.2', 'gpt-5.3', 'gpt-5.4'${e.agent==="codex"?s:""}
|
|
164
159
|
},`,gemini:`
|
|
165
160
|
gemini: {
|
|
166
|
-
model: 'gemini-2.5-pro', // Options: 'auto', 'gemini-2.5-pro', 'gemini-2.5-flash'${
|
|
167
|
-
},`},
|
|
168
|
-
`).map(
|
|
161
|
+
model: 'gemini-2.5-pro', // Options: 'auto', 'gemini-2.5-pro', 'gemini-2.5-flash'${e.agent==="gemini"?s:""}
|
|
162
|
+
},`},u=e.agent,d=Object.entries(n).filter(([l])=>l!==u).map(([,l])=>l.split(`
|
|
163
|
+
`).map(m=>m.trim()?` // ${m.trimStart()}`:m).join(`
|
|
169
164
|
`)).join(`
|
|
170
165
|
`);return`export default {
|
|
171
166
|
// AI agent settings
|
|
172
|
-
agent: {${
|
|
173
|
-
${
|
|
167
|
+
agent: {${n[u]}
|
|
168
|
+
${d}
|
|
174
169
|
strictMode: false,
|
|
175
170
|
},
|
|
176
171
|
|
|
@@ -178,12 +173,12 @@ ${u}
|
|
|
178
173
|
// and workflow config. Runtime strategies attach MCP per run (no global Gemini settings mutation).
|
|
179
174
|
browser: {
|
|
180
175
|
mcp: 'playwright',
|
|
181
|
-
headless: ${
|
|
176
|
+
headless: ${e.browserMode==="headless"},
|
|
182
177
|
},
|
|
183
178
|
|
|
184
179
|
// Chat memory backend adapter (dolt | mem0)
|
|
185
180
|
memory: {
|
|
186
|
-
backend: '${
|
|
181
|
+
backend: '${i}',
|
|
187
182
|
},
|
|
188
183
|
|
|
189
184
|
// UI-test memory remote sync \u2014 declarative team configuration.
|
|
@@ -216,7 +211,7 @@ ${u}
|
|
|
216
211
|
specs: 'test-specs', // Where your .txt test specs are
|
|
217
212
|
generated: 'tests', // Where generated .spec.js files go
|
|
218
213
|
output: '.zibby/output', // Where workflow execution results are saved (default: .zibby/output)
|
|
219
|
-
workflows: '${
|
|
214
|
+
workflows: '${e.workflowsPath||"workflows"}', // Where custom workflows are stored (visible at project root; .zibby/ is runtime/scratch only)
|
|
220
215
|
// sessionPrefix: 'run', // Optional: prefix for session folders (e.g., run_1772788458045)
|
|
221
216
|
},
|
|
222
217
|
|
|
@@ -251,13 +246,13 @@ ${u}
|
|
|
251
246
|
},
|
|
252
247
|
|
|
253
248
|
// Cloud sync - auto-upload test results & videos (requires ZIBBY_API_KEY in .env)
|
|
254
|
-
cloudSync: ${
|
|
249
|
+
cloudSync: ${e.cloudSync||!1}
|
|
255
250
|
};
|
|
256
|
-
`}function
|
|
251
|
+
`}function Lt(e,o="dolt"){return`# Zibby Test Automation - Environment Variables
|
|
257
252
|
|
|
258
253
|
# AI Provider Keys
|
|
259
254
|
${{claude:"ANTHROPIC_API_KEY=sk-ant-your_key_here",cursor:`# Cursor Agent uses cursor-agent CLI \u2014 no API key needed
|
|
260
|
-
# Install: curl https://cursor.com/install -fsS | bash`,codex:"OPENAI_API_KEY=sk-your_key_here",gemini:"GEMINI_API_KEY=your_key_here"}[
|
|
255
|
+
# Install: curl https://cursor.com/install -fsS | bash`,codex:"OPENAI_API_KEY=sk-your_key_here",gemini:"GEMINI_API_KEY=your_key_here"}[e.agent]||""}
|
|
261
256
|
|
|
262
257
|
# Zibby Cloud Sync (for uploading test results & videos)
|
|
263
258
|
# Get your API key from: https://zibby.dev/settings/tokens
|
|
@@ -269,14 +264,14 @@ ${{claude:"ANTHROPIC_API_KEY=sk-ant-your_key_here",cursor:`# Cursor Agent uses c
|
|
|
269
264
|
# ZIBBY_MEMORY_COMPACT_EVERY=1500 # Auto-compact every N runs (0 to disable)
|
|
270
265
|
|
|
271
266
|
# Chat memory backend
|
|
272
|
-
ZIBBY_MEMORY_BACKEND=${
|
|
273
|
-
`}function
|
|
267
|
+
ZIBBY_MEMORY_BACKEND=${o}
|
|
268
|
+
`}function Dt(e,o,t="dolt"){return`# Zibby Test Automation - Environment Variables
|
|
274
269
|
|
|
275
270
|
# AI Provider Keys
|
|
276
|
-
${{claude:"ANTHROPIC_API_KEY=sk-ant-your_key_here",cursor:"# Cursor Agent uses cursor-agent CLI \u2014 no API key needed",codex:"OPENAI_API_KEY=sk-your_key_here",gemini:"GEMINI_API_KEY=your_key_here"}[
|
|
271
|
+
${{claude:"ANTHROPIC_API_KEY=sk-ant-your_key_here",cursor:"# Cursor Agent uses cursor-agent CLI \u2014 no API key needed",codex:"OPENAI_API_KEY=sk-your_key_here",gemini:"GEMINI_API_KEY=your_key_here"}[e.agent]||""}
|
|
277
272
|
|
|
278
273
|
# Zibby Cloud Sync
|
|
279
|
-
ZIBBY_API_KEY=${
|
|
274
|
+
ZIBBY_API_KEY=${o}
|
|
280
275
|
|
|
281
276
|
# Test Memory (Dolt DB) - Auto-compaction settings
|
|
282
277
|
# ZIBBY_MEMORY_MAX_RUNS=3000 # Max test runs to keep per spec
|
|
@@ -285,7 +280,7 @@ ZIBBY_API_KEY=${e}
|
|
|
285
280
|
|
|
286
281
|
# Chat memory backend
|
|
287
282
|
ZIBBY_MEMORY_BACKEND=${t}
|
|
288
|
-
`}function
|
|
283
|
+
`}function Ut(e,o,t={}){let s={"@zibby/cli":"latest","@zibby/core":Bt("../../package.json").dependencies?.["@zibby/core"]||"latest"};return t.memoryBackend==="mem0"&&(s.mem0ai="^2.4.6"),JSON.stringify({name:e,version:"1.0.0",type:"module",private:!0,scripts:{"test:spec":"zibby run",test:"playwright test","test:headed":"playwright test --headed"},dependencies:s,devDependencies:{"@playwright/test":"^1.49.0",dotenv:"^17.2.3"}},null,2)}function Yt(){return`# Dependencies
|
|
289
284
|
node_modules/
|
|
290
285
|
|
|
291
286
|
# Test artifacts
|
|
@@ -313,11 +308,11 @@ Thumbs.db
|
|
|
313
308
|
# Zibby memory (Dolt DB synced separately via dolt remote, not git)
|
|
314
309
|
.zibby/memory/
|
|
315
310
|
.zibby/memory-context.md
|
|
316
|
-
`}function
|
|
311
|
+
`}function Zt(e="off",o=null){return`import { defineConfig} from '@playwright/test';
|
|
317
312
|
|
|
318
313
|
export default defineConfig({
|
|
319
314
|
testDir: './tests',
|
|
320
|
-
${
|
|
315
|
+
${o?` outputDir: '${o}',
|
|
321
316
|
`:` outputDir: 'test-results/playwright', // Keep Playwright artifacts separate from Zibby workflow output
|
|
322
317
|
`} timeout: 30000,
|
|
323
318
|
retries: 0,
|
|
@@ -335,7 +330,7 @@ ${e?` outputDir: '${e}',
|
|
|
335
330
|
['list']
|
|
336
331
|
],
|
|
337
332
|
});
|
|
338
|
-
`}function
|
|
333
|
+
`}function Ft(){return`Test Specification: Example Domain Navigation
|
|
339
334
|
==============================================
|
|
340
335
|
|
|
341
336
|
Application: Example Domain
|
|
@@ -372,7 +367,7 @@ Notes:
|
|
|
372
367
|
- Uses a stable, public domain (example.com) maintained by IANA
|
|
373
368
|
- No authentication required
|
|
374
369
|
- Suitable for CI/CD smoke testing
|
|
375
|
-
`}function
|
|
370
|
+
`}function Ht(){return`# Example command template
|
|
376
371
|
|
|
377
372
|
Use this command when the user asks for a concise testing task breakdown.
|
|
378
373
|
|
|
@@ -383,7 +378,7 @@ Required output format:
|
|
|
383
378
|
4. Expected result
|
|
384
379
|
|
|
385
380
|
Keep the response actionable and short.
|
|
386
|
-
`}function
|
|
381
|
+
`}function Gt(e,o){return`# ${e}
|
|
387
382
|
|
|
388
383
|
AI-powered test automation with Zibby.
|
|
389
384
|
|
|
@@ -397,7 +392,7 @@ npm install
|
|
|
397
392
|
2. Configure environment:
|
|
398
393
|
\`\`\`bash
|
|
399
394
|
cp .env.example .env
|
|
400
|
-
# Edit .env and add your ${{claude:"ANTHROPIC_API_KEY",codex:"OPENAI_API_KEY",gemini:"GEMINI_API_KEY",cursor:"CURSOR_API_KEY (optional)"}[
|
|
395
|
+
# Edit .env and add your ${{claude:"ANTHROPIC_API_KEY",codex:"OPENAI_API_KEY",gemini:"GEMINI_API_KEY",cursor:"CURSOR_API_KEY (optional)"}[o.agent]}
|
|
401
396
|
\`\`\`
|
|
402
397
|
|
|
403
398
|
3. Run example test:
|
|
@@ -448,13 +443,13 @@ npx playwright test --ui
|
|
|
448
443
|
Edit \`.zibby.config.mjs\` to customize:
|
|
449
444
|
- Agent settings (model, temperature)
|
|
450
445
|
- Browser settings (headless, viewport)
|
|
451
|
-
- Cloud sync${
|
|
446
|
+
- Cloud sync${o.cloudSync?" (enabled)":" (disabled)"}
|
|
452
447
|
- Self-healing behavior
|
|
453
448
|
|
|
454
449
|
## Project Structure
|
|
455
450
|
|
|
456
451
|
\`\`\`
|
|
457
|
-
${
|
|
452
|
+
${e}/
|
|
458
453
|
\u251C\u2500\u2500 .zibby/
|
|
459
454
|
\u2502 \u251C\u2500\u2500 graph.mjs # Workflow definition
|
|
460
455
|
\u2502 \u251C\u2500\u2500 nodes/ # Custom nodes
|
|
@@ -472,4 +467,4 @@ ${o}/
|
|
|
472
467
|
|
|
473
468
|
- Documentation: https://docs.zibby.dev
|
|
474
469
|
- Examples: https://github.com/zibby/examples
|
|
475
|
-
`}export{
|
|
470
|
+
`}export{jt as generateConfig,Rn as initCommand};
|