@zibby/cli 0.4.16 → 0.4.18
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 +2 -2
- package/dist/commands/init.js +64 -64
- package/dist/commands/workflows/generate.js +108 -108
- package/dist/commands/workflows/schedule.js +10 -0
- package/dist/commands/workflows/validate-helpers.js +1 -0
- package/dist/commands/workflows/validate.js +4 -0
- package/dist/package.json +5 -3
- package/dist/templates/.claude/CLAUDE.md +425 -0
- package/dist/templates/.claude/commands/add-node.md +63 -0
- package/dist/templates/.claude/commands/add-skill.md +83 -0
- package/dist/templates/.claude/commands/new-workflow.md +61 -0
- package/dist/templates/.claude/commands/validate-workflow.md +67 -0
- package/package.json +5 -3
- package/templates/.claude/CLAUDE.md +425 -0
- package/templates/.claude/commands/add-node.md +63 -0
- package/templates/.claude/commands/add-skill.md +83 -0
- package/templates/.claude/commands/new-workflow.md +61 -0
- package/templates/.claude/commands/validate-workflow.md +67 -0
- package/templates/zibby-workflow-claude/agents-md-block.md +173 -0
- package/templates/zibby-workflow-claude/claude/agents/zibby-test-author.md +87 -0
- package/templates/zibby-workflow-claude/claude/agents/zibby-workflow-builder.md +101 -0
- package/templates/zibby-workflow-claude/claude/commands/zibby-add-node.md +75 -0
- package/templates/zibby-workflow-claude/claude/commands/zibby-debug.md +67 -0
- package/templates/zibby-workflow-claude/claude/commands/zibby-delete.md +37 -0
- package/templates/zibby-workflow-claude/claude/commands/zibby-deploy.md +87 -0
- package/templates/zibby-workflow-claude/claude/commands/zibby-list.md +30 -0
- package/templates/zibby-workflow-claude/claude/commands/zibby-memory-cost.md +39 -0
- package/templates/zibby-workflow-claude/claude/commands/zibby-memory-pull.md +47 -0
- package/templates/zibby-workflow-claude/claude/commands/zibby-memory-remote-use-hosted.md +61 -0
- package/templates/zibby-workflow-claude/claude/commands/zibby-memory-stats.md +38 -0
- package/templates/zibby-workflow-claude/claude/commands/zibby-static-ip.md +70 -0
- package/templates/zibby-workflow-claude/claude/commands/zibby-tail.md +53 -0
- package/templates/zibby-workflow-claude/claude/commands/zibby-test-debug.md +59 -0
- package/templates/zibby-workflow-claude/claude/commands/zibby-test-generate.md +39 -0
- package/templates/zibby-workflow-claude/claude/commands/zibby-test-run.md +49 -0
- package/templates/zibby-workflow-claude/claude/commands/zibby-test-write.md +46 -0
- package/templates/zibby-workflow-claude/claude/commands/zibby-trigger.md +56 -0
- package/templates/zibby-workflow-claude/claude/settings.json +10 -0
- package/templates/zibby-workflow-claude/cursor/rules/zibby-workflows.mdc +119 -0
- package/templates/zibby-workflow-claude/manifest.json +47 -0
package/dist/commands/init.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
var
|
|
1
|
+
var ko=Object.defineProperty;var j=(e,o)=>()=>(e&&(o=e(e=0)),o);var L=(e,o)=>{for(var t in o)ko(e,t,{get:o[t],enumerable:!0})};var $e={};L($e,{resolveTemplate:()=>Ie,templateAddCommand:()=>Do,templateListCommand:()=>Lo,writeTemplateFiles:()=>Pe,writeTemplateFilesToDir:()=>Ce});import{mkdir as _e,writeFile as Co,readFile as Po}from"fs/promises";import{existsSync as Q,readdirSync as $o,statSync as So,readFileSync as Eo}from"fs";import{join as D,dirname as Ro}from"path";import{fileURLToPath as zo}from"url";import{spawn as To}from"child_process";import{createRequire as Oo}from"module";import x from"chalk";import Ko from"ora";function jo(e){return No.some(o=>o.test(e))}async function Ae(e,o,t=null){let i=[];Q(o)||await _e(o,{recursive:!0});for(let s of $o(e)){if(jo(s))continue;let n=D(e,s),p=D(o,s),d=So(n);if(d.isDirectory()){let l=await Ae(n,p,t);for(let m of l)i.push(`${s}/${m}`)}else if(d.isFile()){let l=await Po(n,"utf-8");t&&(l=t(s,l)),await Co(p,l),i.push(s)}}return i}async function Ie(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 Ce(e,o,t={}){let i=t.enableMemory!==!1,{template:s}=await Ie(o);Q(e)||await _e(e,{recursive:!0});let n=await Ae(s.path,e,(p,d)=>!i&&p==="execute-live.mjs"?d.replace("skills: [SKILLS.BROWSER, SKILLS.MEMORY],","skills: [SKILLS.BROWSER],"):d);return{template:s,copied:n}}async function Pe(e,o,t={}){return Ce(D(e,".zibby"),o,t)}async function Lo(){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 Do(e,o={}){e||(console.log(x.red(`
|
|
2
2
|
Missing template name.
|
|
3
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=
|
|
4
|
+
`)),process.exit(1));let t=o.cwd||process.cwd(),i=D(t,".zibby");Q(i)||(console.log(x.yellow(`
|
|
5
5
|
No .zibby/ directory in ${t}.
|
|
6
|
-
`)),console.log(x.gray(" Run `zibby init` first to bootstrap the project.\n")),process.exit(1));let s;try{s=await
|
|
6
|
+
`)),console.log(x.gray(" Run `zibby init` first to bootstrap the project.\n")),process.exit(1));let s;try{s=await Pe(t,e,{enableMemory:o.enableMemory!==!1})}catch(n){console.log(x.red(`
|
|
7
7
|
${n.message}
|
|
8
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(`
|
|
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&&Q(D(t,"package.json"))){let n=!1;try{Oo(D(t,"package.json")).resolve("@zibby/core/package.json"),n=!0}catch{}if(!n){let d=`@zibby/core@${JSON.parse(Eo(D(Bo,"../../package.json"),"utf-8")).dependencies?.["@zibby/core"]||"latest"}`,l=Ko(` Installing ${d} (needed by .zibby/graph.mjs)...`).start();await new Promise(w=>{To("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 Mo,Bo,No,Se=j(()=>{Mo=zo(import.meta.url),Bo=Ro(Mo),No=[/^__tests__$/,/^__mocks__$/,/^node_modules$/,/\.test\.[mc]?js$/,/\.spec\.[mc]?js$/,/^\.DS_Store$/,/^chat\.mjs$/]});var ze={};L(ze,{applyMemorySyncConfig:()=>Fo,validateMemorySyncConfig:()=>Re});function Re(e){if(!e||typeof e!="object")return{ok:!0,kind:"noop"};let o=e.remote;return Uo.includes(o)?{ok:!0,kind:"noop"}:typeof o!="string"?{ok:!1,error:`memorySync.remote must be null or a string, got ${typeof o}`}:o===Yo?{ok:!0,kind:"hosted"}:Ee.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: ${Ee.join(" / ")}.`}}async function Fo({cwd:e,projectId:o,block:t,memoryApi:i,hostedSetup:s,getSessionToken:n,logger:p=console}){let d=Re(t);if(!d.ok)return p.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 Uo,Yo,Ee,Te=j(()=>{Uo=[null,void 0,"","none","off",!1],Yo="hosted",Ee=["aws://","gs://","https://","http://","file://"]});var re={};L(re,{clearSession:()=>Ye,default:()=>qo,getMem0ProxyUrl:()=>He,getProjects:()=>Ve,getProxyUrl:()=>Fe,getSessionToken:()=>ne,getUserInfo:()=>Le,isLoggedIn:()=>Ue,loadConfig:()=>S,saveConfig:()=>O,saveMem0ProxyUrl:()=>Ge,saveProjects:()=>We,saveProxyUrl:()=>Ze,saveSessionToken:()=>je,saveUserInfo:()=>De});import{existsSync as Oe,mkdirSync as Zo,readFileSync as Ho,writeFileSync as Go}from"fs";import{homedir as Ke}from"os";import{join as ee}from"path";function Me(){return process.env.ZIBBY_CONFIG_DIR||ee(Ke(),".zibby")}function Be(){return ee(Me(),"config.json")}function Wo(){let e=Me();Oe(e)||Zo(e,{recursive:!0})}function S(){try{let e=Be();if(Oe(e)){let o=Ho(e,"utf-8");return JSON.parse(o)}}catch{}return{}}function O(e){Wo(),Go(Be(),JSON.stringify(e,null,2))}function ne(){return S().sessionToken||null}function je(e){let o=S();o.sessionToken=e,O(o)}function Le(){return S().user||null}function De(e){let o=S();o.user=e,O(o)}function Ue(){return ne()!==null}function Ye(){let e=S();delete e.sessionToken,delete e.user,delete e.mem0ProxyUrl,O(e)}function Fe(){return S().proxyUrl||null}function Ze(e){let o=S();o.proxyUrl=e,O(o)}function He(){return S().mem0ProxyUrl||null}function Ge(e){let o=S();o.mem0ProxyUrl=e,O(o)}function Ve(){return S().projects||[]}function We(e){let o=S();o.projects=e,O(o)}var Ne,Vo,qo,se=j(()=>{Ne=ee(Ke(),".zibby"),Vo=ee(Ne,"config.json");qo={loadConfig:S,saveConfig:O,getSessionToken:ne,saveSessionToken:je,getUserInfo:Le,saveUserInfo:De,isLoggedIn:Ue,clearSession:Ye,getProxyUrl:Fe,saveProxyUrl:Ze,getMem0ProxyUrl:He,saveMem0ProxyUrl:Ge,getProjects:Ve,saveProjects:We,CONFIG_DIR:Ne,CONFIG_FILE:Vo}});var qe={};L(qe,{ENVIRONMENTS:()=>C,getAccountApiUrl:()=>Xo,getApiUrl:()=>Jo,getCurrentEnvironment:()=>Qo,getFrontendUrl:()=>et});function Jo(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";C[o]?e=C[o].apiUrl:e=C.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)`),C.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),C.prod.apiUrl}}function Xo(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let e=process.env.ZIBBY_ENV||"prod";return(C[e]||C.prod).accountApiUrl}function Qo(){let e=process.env.ZIBBY_ENV||"prod";return C[e]||C.prod}function et(){let e;if(process.env.ZIBBY_FRONTEND_URL)e=process.env.ZIBBY_FRONTEND_URL;else{let o=process.env.ZIBBY_ENV||"prod";C[o]?e=C[o].frontendUrl:e=C.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)`),C.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(p=>s===p||s.endsWith(`.${p}`))&&!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}`),C.local.frontendUrl}}var C,Je=j(()=>{C={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 ue={};L(ue,{__testing:()=>lt,buildDoltEnv:()=>at,clearConfig:()=>it,getActiveCredentials:()=>ro,isHosted:()=>rt,readConfig:()=>ce,refreshCredentials:()=>no,writeConfig:()=>st});import{readFileSync as Xe,writeFileSync as ae,existsSync as le,mkdirSync as Qe,chmodSync as ot}from"fs";import{join as ie}from"path";function H(e){let o=ie(e,".zibby");return{dir:o,config:ie(o,tt),creds:ie(o,nt)}}function ce(e){let{config:o}=H(e);if(!le(o))return null;try{let t=JSON.parse(Xe(o,"utf-8"));return t.mode!=="hosted"?null:t}catch{return null}}function rt(e){return!!ce(e)}function st(e,o){let{dir:t,config:i}=H(e);Qe(t,{recursive:!0}),ae(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 it(e){let{config:o,creds:t}=H(e);for(let i of[o,t])if(le(i))try{ae(i,"")}catch{}}function de(e){let{creds:o}=H(e);if(!le(o))return null;try{let t=JSON.parse(Xe(o,"utf-8"));return!t?.accessKeyId||!t?.secretAccessKey||!t?.sessionToken?null:t}catch{return null}}function oo(e,o){let{dir:t,creds:i}=H(e);Qe(t,{recursive:!0}),ae(i,JSON.stringify(o,null,2),"utf-8");try{ot(i,384)}catch{}}function to(e){return e?.expiration?new Date(e.expiration).getTime()-Date.now()<eo:!0}async function no({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`,p=await s(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({projectId:o})});if(!p.ok){let l=await p.text().catch(()=>"");throw new Error(`memory-sync credentials request failed (${p.status}): ${l||"no body"}`)}let d=await p.json();if(!d?.accessKeyId||!d?.secretAccessKey||!d?.sessionToken)throw new Error("memory-sync credentials response missing required fields");return oo(e,{accessKeyId:d.accessKeyId,secretAccessKey:d.secretAccessKey,sessionToken:d.sessionToken,expiration:d.expiration||null,refreshedAt:new Date().toISOString()}),de(e)}async function ro({cwd:e,apiUrl:o,sessionToken:t,fetch:i}){let s=ce(e);if(!s)return null;let n=de(e);return(!n||to(n))&&(n=await no({cwd:e,projectId:s.projectId,apiUrl:o,sessionToken:t,fetch:i})),n}async function at({cwd:e,apiUrl:o,sessionToken:t,fetch:i}){let s=await ro({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 tt,nt,eo,lt,pe=j(()=>{tt="memory-sync.json",nt="memory-sync-creds.json",eo=120*1e3;lt={paths:H,readCreds:de,writeCreds:oo,isExpiringSoon:to,REFRESH_HEADROOM_MS:eo}});var so={};L(so,{memoryCompactCommand:()=>pt,memoryCostCommand:()=>mt,memoryInitCommand:()=>vt,memoryPullCommand:()=>ht,memoryPushCommand:()=>wt,memoryRemoteAddCommand:()=>gt,memoryRemoteInfoCommand:()=>yt,memoryRemoteRemoveCommand:()=>ft,memoryRemoteUseHostedCommand:()=>bt,memoryResetCommand:()=>ut,memoryStatsCommand:()=>dt});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(r.white(
|
|
11
|
+
`)),console.log(r.white(ct)),null}}async function dt(){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
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
14
|
`));return}if(!t.initialized){console.log(r.yellow(`
|
|
@@ -16,124 +16,124 @@ var bo=Object.defineProperty;var B=(e,o)=>()=>(e&&(o=e(e=0)),o);var N=(e,o)=>{fo
|
|
|
16
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
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
|
|
20
|
-
${i}`),console.log(r.white(" Top selectors:"));for(let n of t.topSelectors){let
|
|
19
|
+
${i}`),console.log(r.white(" Recent runs:"));for(let n of t.recentRuns){let p=n.passed?r.green("\u2713"):r.red("\u2717"),d=n.duration_ms?r.gray(`${(n.duration_ms/1e3).toFixed(1)}s`):"";console.log(` ${p} ${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 p=n.success_count+n.failure_count,d=Math.round(n.success_count/p*100);console.log(` ${r.cyan(n.stable_id||"?")} \u2192 ${n.element_desc} (${d}%, ${p} uses)`)}}if(t.log){console.log(`
|
|
21
21
|
${i}`),console.log(r.white(" Recent commits:"));let n=t.log.split(`
|
|
22
|
-
`).filter(
|
|
22
|
+
`).filter(p=>p.startsWith("commit")||p.trim().startsWith("run ")).slice(0,10);for(let p of n)console.log(r.gray(` ${p.trim()}`))}console.log("")}async function ut(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
24
|
`)),console.log(r.white(` Run with --force to confirm: zibby memory reset --force
|
|
25
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 pt(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
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
|
|
32
|
+
Compacting memory (keep last ${s} runs/spec, prune data older than ${n}d)...`));let p=i.counts;if(o.compactMemory(t,{maxRuns:s,maxAgeDays:n}).pruned){let l=o.getStats(t).counts,m=w=>p[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
33
|
`))}else console.log(r.gray(` Nothing to compact.
|
|
34
|
-
`))}async function
|
|
34
|
+
`))}async function mt(){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
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
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
39
|
`));return}console.log(r.bold.cyan(`
|
|
40
40
|
Zibby \u2014 LLM Cost Report
|
|
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(
|
|
42
|
-
${i}`),console.log(r.white(" By domain:"));for(let n of t.by_domain.slice(0,10)){let
|
|
43
|
-
${i}`),console.log(r.white(" By spec:"));for(let n of t.by_spec.slice(0,10)){let
|
|
44
|
-
${i}`),console.log(r.white(" Last 10 runs:"));for(let n of t.recent.slice(0,10)){let
|
|
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(K(s.input))}`)),console.log(r.white(` Total output tokens: ${r.cyan(K(s.output))}`)),console.log(r.white(` Total cache reads: ${r.cyan(K(s.cache_read))} ${r.gray("(billed at ~10% of normal input rate)")}`)),console.log(r.white(` Total cache creation: ${r.cyan(K(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 p=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 ~${K(p)}/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 p=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 ~${K(p)}/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 p=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 ${K(n.cache_read_tokens)}`):"";console.log(` ${p} ${r.gray(n.run_at.slice(0,16))} ${r.cyan(K(d).padStart(8))} ${r.white(n.spec_path||"")}${l}`)}}console.log("")}function K(e){return e==null?"\u2014":e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}K`:`${(e/1e6).toFixed(2)}M`}async function gt(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(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
|
|
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 yt(){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
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
|
|
48
|
+
`));return}console.log(r.bold.cyan(" Memory remote")),console.log(` ${r.cyan(o.name||"origin")}: ${o.url||"(unknown)"}`),console.log("")}async function ft(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 ht(){let e=await R();if(!e)return;console.log(r.cyan(`
|
|
49
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
|
|
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 bt(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
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:
|
|
53
|
+
`)),process.exit(1));let{getApiUrl:p}=await Promise.resolve().then(()=>(Je(),qe)),{getSessionToken:d}=await Promise.resolve().then(()=>(se(),re)),l=p(),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
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)}`,
|
|
55
|
+
Configuring hosted memory-sync...`));let w;try{let P=`${l.replace(/\/+$/,"")}/memory/sync-config?projectId=${encodeURIComponent(n)}`,E=await fetch(P,{headers:{Authorization:`Bearer ${m}`}});if(!E.ok){let k=await E.text().catch(()=>"");throw new Error(`backend returned ${E.status}: ${k||"no body"}`)}w=await E.json()}catch(P){console.log(r.red(`
|
|
56
56
|
Failed: ${P.message}
|
|
57
|
-
`)),process.exit(1)}let{writeConfig:v}=await Promise.resolve().then(()=>(
|
|
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(()=>(
|
|
57
|
+
`)),process.exit(1)}let{writeConfig:v}=await Promise.resolve().then(()=>(pe(),ue));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(()=>(pe(),ue));try{await h({cwd:s,projectId:n,apiUrl:l,sessionToken:m})}catch(P){console.log(r.yellow(`
|
|
59
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
|
|
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 wt(){let e=await R();if(!e)return;console.log(r.cyan(`
|
|
61
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
|
|
62
|
+
`))}async function vt(){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
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
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 ct,io=j(()=>{ct=`
|
|
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(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
|
|
78
|
-
`,"utf-8"),s}function
|
|
75
|
+
`});var ho={};L(ho,{setupCiCommand:()=>Rt,setupPlaywrightMcpCommand:()=>fo,testWithVideoCommand:()=>zt});import{spawn as ge,execSync as ye}from"child_process";import{join as U,dirname as fe,resolve as co}from"path";import{readFileSync as uo,writeFileSync as po,existsSync as G,mkdirSync as mo}from"fs";import{homedir as go}from"os";import{createRequire as kt}from"module";import A from"chalk";function xt(){try{return fe(me.resolve("@zibby/core/package.json"))}catch{return null}}function yo(e){try{return ye(`command -v ${e}`,{stdio:"pipe"}),!0}catch{return!1}}function _t(){try{let e=me.resolve("@zibby/mcp-browser/dist/bin/mcp-browser-zibby.js");if(G(e))return e}catch{}try{let e=me.resolve("@playwright/mcp/package.json"),o=fe(e),t=JSON.parse(uo(e,"utf-8")),i=typeof t.bin=="string"?t.bin:t.bin?.["playwright-mcp"];if(i){let n=U(o,i);if(G(n))return n}let s=U(o,"cli.js");if(G(s))return s}catch{}return null}function ao(e,o,t={}){return new Promise((i,s)=>{let n=ge(e,o,{stdio:"inherit",...t});n.on("close",p=>i(p??1)),n.on("error",s)})}async function At(e){return yo("playwright")?await ao("playwright",["install","ffmpeg"],{cwd:e})===0:await ao("npx",["--yes","playwright","install","ffmpeg"],{cwd:e})===0}function It({headed:e=!1,viewport:o=null}){let t=process.execPath,i=fe(t),s=_t(),n=Number(o?.width)||1280,p=Number(o?.height)||720,d=`${n}x${p}`,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=U(go(),".cursor"),v=U(w,"mcp.json");G(w)||mo(w,{recursive:!0});let h={mcpServers:{}};if(G(v))try{h=JSON.parse(uo(v,"utf-8")),(!h.mcpServers||typeof h.mcpServers!="object")&&(h.mcpServers={})}catch{h={mcpServers:{}}}h.mcpServers["playwright-official"]=m,po(v,`${JSON.stringify(h,null,2)}
|
|
76
|
+
`,"utf-8")}async function Ct(){let e=xt();if(!e)return;let o=U(e,"scripts","patch-cursor-mcp.js");if(G(o))try{await new Promise((t,i)=>{let s=ge(process.execPath,[o],{cwd:process.cwd(),stdio:"ignore"});s.on("close",n=>t(n??0)),s.on("error",i)})}catch{}}function Pt(e){return co(e).replace(/^\/+/,"").replace(/\//g,"-")}function $t(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 St(e,o){let t=Pt(e),i=U(go(),".cursor","projects",t);mo(i,{recursive:!0});let s=U(i,"mcp-approvals.json");return po(s,`${JSON.stringify([o],null,2)}
|
|
78
|
+
`,"utf-8"),s}function lo(e){try{return ye("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 Et(e){try{return ye("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 fo(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 At(process.cwd());console.log(i?A.gray(" \u2713 ffmpeg installed for Playwright video"):A.yellow(" \u26A0 Could not install ffmpeg (video may be unavailable)")),It({headed:o,viewport:t}),await Ct();let s=co(process.cwd());if(yo("cursor-agent")){lo(s);let n=Et(s);n&&console.log(A.gray(" \u2713 cursor-agent: mcp enable playwright-official"));let p=lo(s),d=$t(p);if(d)try{let l=St(s,d);console.log(A.gray(` \u2713 MCP auto-approval key saved (${l})`))}catch(l){console.log(A.yellow(` \u26A0 Could not write mcp-approvals.json: ${l.message}`))}else n||(console.log(A.yellow(" \u26A0 Could not auto-approve MCP (mcp enable failed and no approval key in cursor-agent output)")),console.log(A.gray(" Try: cursor-agent mcp enable playwright-official")))}else console.log(A.yellow(" \u26A0 cursor-agent not found; install it to use Cursor MCP tools"))}async function Rt(e){try{console.log(A.cyan(`
|
|
79
79
|
\u{1F680} Running CI setup...
|
|
80
|
-
`)),await
|
|
80
|
+
`)),await fo({headed:!1,cloudSync:!0,viewport:{width:1280,height:720}}),console.log(A.green(`
|
|
81
81
|
\u2705 CI/CD setup complete!
|
|
82
|
-
`))}catch(o){console.log(
|
|
82
|
+
`))}catch(o){console.log(A.red(`
|
|
83
83
|
\u274C Error: ${o.message}
|
|
84
|
-
`)),process.exit(1)}}async function
|
|
84
|
+
`)),process.exit(1)}}async function zt(e,o){try{let t=["playwright","test",e||"tests/","--project=chromium"];o.headed&&t.push("--headed"),console.log(A.cyan(`
|
|
85
85
|
\u{1F3A5} Running tests with video recording...
|
|
86
|
-
`)),console.log(
|
|
86
|
+
`)),console.log(A.gray("\u2501".repeat(50)));let i=ge("npx",t,{cwd:process.cwd(),stdio:"inherit"});i.on("close",s=>{s===0?console.log(A.green(`
|
|
87
87
|
\u2705 Tests complete!
|
|
88
|
-
`)):(console.log(
|
|
88
|
+
`)):(console.log(A.red(`
|
|
89
89
|
\u274C Tests failed with code ${s}
|
|
90
|
-
`)),process.exit(s))}),i.on("error",s=>{console.log(
|
|
90
|
+
`)),process.exit(s))}),i.on("error",s=>{console.log(A.red(`
|
|
91
91
|
\u274C Error: ${s.message}
|
|
92
|
-
`)),process.exit(1)})}catch(t){console.log(
|
|
92
|
+
`)),process.exit(1)})}catch(t){console.log(A.red(`
|
|
93
93
|
\u274C Error: ${t.message}
|
|
94
|
-
`)),process.exit(1)}}var
|
|
95
|
-
`,"utf-8")}async function
|
|
96
|
-
`));return}console.log(a.yellow("npm global bin not in PATH")),console.log(a.gray(` Location: ${i}`)),console.log();let{shouldAddPath:d}=await
|
|
94
|
+
`)),process.exit(1)}}var me,bo=j(()=>{me=kt(import.meta.url)});import{mkdir as T,writeFile as I,readFile as B}from"fs/promises";import{existsSync as _,readdirSync as wo}from"fs";import{join as f,resolve as he,dirname as Tt}from"path";import{homedir as N}from"os";import Y from"inquirer";import a from"chalk";import M from"ora";import{spawn as q,execSync as oe}from"child_process";import{fileURLToPath as Ot}from"url";import{createRequire as Kt}from"module";import{existsSync as xo,readFileSync as _o,writeFileSync as Ao,mkdirSync as Io}from"fs";import{join as we}from"path";import{homedir as ve}from"os";var J={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 ke(){return we(ve(),".zibby","config.json")}function X(){try{let e=ke();return xo(e)?JSON.parse(_o(e,"utf-8")):{}}catch{return{}}}function xe(e,o){let t=o?J[o]:null;t&&te(t.envVar,e)}function te(e,o){if(!e||typeof e!="string"||!o||typeof o!="string")return;let t=we(ve(),".zibby");Io(t,{recursive:!0});let i=ke(),s=X();(!s.agentKeys||typeof s.agentKeys!="object")&&(s.agentKeys={}),s.agentKeys[e]=String(o).trim(),delete s.agentApiKey,Ao(i,`${JSON.stringify(s,null,2)}
|
|
95
|
+
`,"utf-8")}async function Mt(){let e=X(),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 Y.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 Y.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 Y.prompt([{type:"password",name:"token",message:s,mask:"*"}]),p=(n||"").trim();return p?{kind:"api",token:p}:o?{kind:"api",token:o}:{kind:"skip"}}var Bt=Ot(import.meta.url),vo=Tt(Bt),Nt=Kt(import.meta.url);async function jt(){try{let e=process.platform==="win32",o=oe("npm config get prefix",{encoding:"utf-8"}).trim(),t=e?o:`${o}/bin`,i=t.replace(/^~/,N()),s=e?";":":";if(process.env.PATH.split(s).some(v=>{let h=v.replace(/^~/,N());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 Y.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
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
98
|
`))):(console.log(a.gray(`
|
|
99
99
|
To add manually, run:`)),console.log(a.gray(` echo 'export PATH="${i}:$PATH"' >> ~/.zshrc`)),console.log(a.gray(` source ~/.zshrc
|
|
100
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(
|
|
101
|
+
`));return}let l=process.env.SHELL||"",m="";if(l.includes("zsh"))m=f(N(),".zshrc");else if(l.includes("bash"))m=_(f(N(),".bashrc"))?f(N(),".bashrc"):f(N(),".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(_(m)){let v=await B(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
102
|
`));return}}let w=`
|
|
103
103
|
# npm global bin (added by zibby)
|
|
104
104
|
export PATH="${i}:$PATH"
|
|
105
|
-
`;await
|
|
105
|
+
`;await I(m,(_(m)?await B(m,"utf-8"):"")+w),console.log(a.green(`Added to ${m}`)),console.log(a.yellow(`
|
|
106
106
|
Run this to activate in current session:`)),console.log(a.gray(` source ${m}
|
|
107
|
-
`))}catch{}}async function
|
|
107
|
+
`))}catch{}}async function zn(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 i=!o.skipMemory,s=["dolt","mem0"].includes(String(o.memoryBackend||"").toLowerCase())?String(o.memoryBackend).toLowerCase():"dolt";await
|
|
111
|
+
`);let i=!o.skipMemory,s=["dolt","mem0"].includes(String(o.memoryBackend||"").toLowerCase())?String(o.memoryBackend).toLowerCase():"dolt";await jt();let n=e?he(process.cwd(),e):process.cwd(),p=e||"zibby-tests",d=!!e;d&&_(n)&&(console.log(a.red(`
|
|
112
112
|
Directory "${e}" already exists!
|
|
113
|
-
`)),process.exit(1)),!d&&
|
|
113
|
+
`)),process.exit(1)),!d&&_(f(n,".zibby.config.mjs"))&&!o.force&&(console.log(a.yellow(`
|
|
114
114
|
Zibby is already initialized in this directory!
|
|
115
115
|
`)),console.log(a.white("Config file found: .zibby.config.mjs")),console.log(a.gray(`Use --force or -f to reinitialize
|
|
116
116
|
`)),process.exit(0)),o.force&&!d&&console.log(a.cyan(`
|
|
117
117
|
Reinitializing Zibby configuration...
|
|
118
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
|
|
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 Y.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=J[l.agent],P=!(process.env.CI||process.env.ZIBBY_CI||!process.stdin.isTTY);if(l.agent==="claude"&&!o.agentKey&&P){let k=await Mt();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=X(),F=process.env[h.envVar]||k.agentKeys?.[h.envVar],c=F?`***${F.slice(-4)}`:null,g=c?`${h.label} found (${c}). Press Enter to keep, or paste a new key:`:`Enter ${h.label} (from ${h.url}, or press Enter to skip):`,{agentKey:u}=await Y.prompt([{type:"password",name:"agentKey",message:g,mask:"*"}]);u&&u.trim()&&(l.agentKey=u.trim(),l.agentAuth="api")}let E=[];if(t&&!o.headed&&!o.headless&&E.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&&E.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:"}),E.length>0){let k=await Y.prompt(E);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=J[l.agent];l.claudeOauthToken&&(te("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&&(xe(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=M("Setting up Zibby...").start();try{if(d&&await T(n,{recursive:!0}),t&&(await T(f(n,"test-specs/examples"),{recursive:!0}),await T(f(n,"tests"),{recursive:!0})),await T(f(n,".zibby/output"),{recursive:!0}),await T(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:u}=c(n);u&&(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(()=>(Se(),$e));await c(n,h,{enableMemory:i})}catch(c){throw v.fail(`Failed to scaffold template: ${c.message}`),c}}else await T(f(n,".zibby"),{recursive:!0});v.text="Generating configuration files...";let E=Lt(l,o,{memoryBackend:s});if(await I(f(n,".zibby.config.mjs"),E),await I(f(n,".env.example"),Dt(l,s)),l.apiKey&&l.apiKey.trim()){let c=f(n,".env"),g=l.apiKey.trim();if(_(c)){let u=await B(c,"utf8");/^ZIBBY_API_KEY=/m.test(u)?u=u.replace(/^ZIBBY_API_KEY=.*/m,`ZIBBY_API_KEY=${g}`):/^#\s*ZIBBY_API_KEY=/m.test(u)?u=u.replace(/^#\s*ZIBBY_API_KEY=.*/m,`ZIBBY_API_KEY=${g}`):u=`${u.trimEnd()}
|
|
120
120
|
|
|
121
121
|
# Zibby Cloud Sync
|
|
122
122
|
ZIBBY_API_KEY=${g}
|
|
123
|
-
`,await
|
|
123
|
+
`,await I(c,u)}else await I(c,Ut(l,g,s))}if(l.agentKey&&w){let c=f(n,".env"),g=l.agentKey;if(_(c)){let u=await B(c,"utf8"),b=new RegExp(`^${w.envVar}=.*`,"m"),y=new RegExp(`^#\\s*${w.envVar}=.*`,"m");b.test(u)?u=u.replace(b,`${w.envVar}=${g}`):y.test(u)?u=u.replace(y,`${w.envVar}=${g}`):u=`${u.trimEnd()}
|
|
124
124
|
|
|
125
125
|
# AI Agent Key
|
|
126
126
|
${w.envVar}=${g}
|
|
127
|
-
`,await
|
|
127
|
+
`,await I(c,u)}}if(d){let c=Yt(p,l,{memoryBackend:s});await I(f(n,"package.json"),c)}if(!_(f(n,".gitignore"))){let c=Ft();await I(f(n,".gitignore"),c)}if(t){if(!_(f(n,"playwright.config.js"))){let c=Zt("on");await I(f(n,"playwright.config.js"),c)}if(!_(f(n,"test-specs/examples/example-domain.txt"))){let c=Ht();await I(f(n,"test-specs/examples/example-domain.txt"),c)}}let k=he(vo,"../../../../examples/.zibby/commands");if(_(k)){let c=wo(k).filter(g=>g.toLowerCase().endsWith(".md"));for(let g of c){let u=f(n,".zibby/commands",g);if(o.force||!_(u)){let b=await B(f(k,g),"utf-8");await I(u,b)}}}if(!_(f(n,".zibby/commands/example.md"))){let c=Gt();await I(f(n,".zibby/commands/example.md"),c)}let F=he(vo,"../../templates/.claude");if(_(F)){await T(f(n,".claude"),{recursive:!0}),await T(f(n,".claude","commands"),{recursive:!0});let c=f(F,"CLAUDE.md"),g=f(n,".claude","CLAUDE.md");if(_(c)&&(o.force||!_(g))){let b=await B(c,"utf-8");await I(g,b)}let u=f(F,"commands");if(_(u)){let b=wo(u).filter(y=>y.toLowerCase().endsWith(".md"));for(let y of b){let $=f(n,".claude","commands",y);if(o.force||!_($)){let Z=await B(f(u,y),"utf-8");await I($,Z)}}}}if(d){let c=Vt(p,l);await I(f(n,"README.md"),c)}try{let{validateMemorySyncConfig:c,applyMemorySyncConfig:g}=await Promise.resolve().then(()=>(Te(),ze)),u=f(n,".zibby.config.mjs"),b=null;if(_(u))try{b=(await import(`file://${u}?t=${Date.now()}`)).default?.memorySync}catch{}let y=c(b);if(y.ok&&y.kind!=="noop"){let $=await import("@zibby/ui-memory").catch(()=>null),{getSessionToken:Z}=await Promise.resolve().then(()=>(se(),re)),z=await g({cwd:n,projectId:l.projectId,block:b,memoryApi:$,getSessionToken:Z,hostedSetup:async({cwd:V,projectId:W})=>{let{memoryRemoteUseHostedCommand:be}=await Promise.resolve().then(()=>(io(),so));await be({cwd:V,projectId:W})},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=M("Installing dependencies...").start();await new Promise((g,u)=>{q("npm",["install"],{cwd:n,stdio:"pipe"}).on("close",y=>{y===0?(c.succeed("Dependencies installed!"),g()):(c.fail("Failed to install dependencies"),u(new Error("npm install failed")))})})}if(!d&&i&&s==="mem0"&&(console.log(a.yellow(`
|
|
128
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=
|
|
129
|
+
`))),!o.skipInstall&&t){let c=M("Installing Playwright browsers...").start();await new Promise(g=>{let u=q("npx",["playwright","install","chromium"],{cwd:n,stdio:"pipe"}),b="";u.stdout.on("data",y=>{b+=y.toString()}),u.stderr.on("data",y=>{b+=y.toString()}),u.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(`
|
|
130
130
|
If tests fail, run: npx playwright install
|
|
131
|
-
`)),g())})})}if(l.agent==="cursor"&&!o.skipInstall){let c=
|
|
132
|
-
`))}}}if(l.agent==="codex"&&!o.skipInstall){let c=
|
|
133
|
-
`))}}}if(l.agent==="gemini"&&!o.skipInstall){let c=
|
|
134
|
-
`))}}if(t){let g=
|
|
135
|
-
`,"utf-8");let
|
|
136
|
-
`))}}}if(l.agent==="cursor"&&l.setupMcp&&t){let c=
|
|
131
|
+
`)),g())})})}if(l.agent==="cursor"&&!o.skipInstall){let c=M("Checking cursor-agent CLI...").start();try{oe("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,u)=>{q("bash",["-c","curl https://cursor.com/install -fsS | bash"],{stdio:"pipe"}).on("close",y=>{if(y===0){let $=f(N(),".local","bin");process.env.PATH.includes($)||(process.env.PATH=`${$}:${process.env.PATH}`),c.succeed("cursor-agent CLI installed!"),g()}else u(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=M("Checking Codex CLI...").start();try{oe("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,u)=>{q("npm",["install","-g","@openai/codex"],{stdio:"pipe"}).on("close",y=>{y===0?(c.succeed("Codex CLI installed!"),g()):u(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=M("Checking Gemini CLI...").start();try{oe("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,u)=>{q("npm",["install","-g","@google/gemini-cli"],{stdio:"pipe"}).on("close",y=>{y===0?(c.succeed("Gemini CLI installed!"),g()):u(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=M("Configuring Gemini MCP servers...").start();try{let u=f(N(),".gemini"),b=f(u,"settings.json");_(u)||await T(u,{recursive:!0});let y={mcpServers:{}};if(_(b))try{let W=await B(b,"utf-8");y=JSON.parse(W),y.mcpServers||(y.mcpServers={})}catch{}let $;try{let{createRequire:W}=await import("module");$=W(import.meta.url).resolve("@zibby/mcp-browser/bin/mcp-browser-zibby.js")}catch{$="@playwright/mcp"}let Z=l.browserMode!=="headless",z=$==="@playwright/mcp"?["-y","@playwright/mcp","--isolated","--viewport-size=1280x720","--output-dir","test-results"]:[$,"--isolated","--viewport-size=1280x720","--output-dir=test-results"];Z||z.push("--headless"),y.mcpServers["playwright-official"]={command:$==="@playwright/mcp"?"npx":"node",args:z},await I(b,`${JSON.stringify(y,null,2)}
|
|
135
|
+
`,"utf-8");let V="Gemini MCP configured";Z?V+=" (headed mode - visible browser)":V+=" (headless mode - hidden browser)",g.succeed(V)}catch(u){g.fail("MCP setup failed"),console.log(a.yellow(" You may need to configure ~/.gemini/settings.json manually")),console.log(a.gray(` Error: ${u.message}
|
|
136
|
+
`))}}}if(l.agent==="cursor"&&l.setupMcp&&t){let c=M("Setting up Playwright MCP...").start();try{let{setupPlaywrightMcpCommand:g}=await Promise.resolve().then(()=>(bo(),ho)),u=l.cloudSync||!1,b=l.browserMode!=="headless";await g({headed:b,cloudSync:u,viewport:{width:1280,height:720}});let y="Playwright MCP configured";b?y+=" (headed mode - visible browser)":y+=" (headless mode - hidden browser)",u&&(y+=" + Zibby MCP (cloud sync)"),c.succeed(y),u&&!(l.apiKey&&l.apiKey.trim())&&console.log(a.gray(`
|
|
137
137
|
Copy .env.example to .env and set ZIBBY_API_KEY to enable uploads
|
|
138
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
139
|
`)),console.log(a.gray(` Error: ${g.message}
|
|
@@ -145,7 +145,7 @@ All set!
|
|
|
145
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
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
147
|
Error: ${h.message}
|
|
148
|
-
`)),process.exit(1)}}function
|
|
148
|
+
`)),process.exit(1)}}function Lt(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
149
|
auth: '${e.agentAuth}', // 'oauth' (subscription) or 'api' (pay-per-token); cloud needs 'api'`:"",n={claude:`
|
|
150
150
|
claude: {
|
|
151
151
|
model: 'auto', // Options: 'auto', 'sonnet-4.6', 'opus-4.6', 'sonnet-4.5', 'opus-4.5'
|
|
@@ -159,12 +159,12 @@ Error: ${h.message}
|
|
|
159
159
|
},`,gemini:`
|
|
160
160
|
gemini: {
|
|
161
161
|
model: 'gemini-2.5-pro', // Options: 'auto', 'gemini-2.5-pro', 'gemini-2.5-flash'${e.agent==="gemini"?s:""}
|
|
162
|
-
},`},
|
|
162
|
+
},`},p=e.agent,d=Object.entries(n).filter(([l])=>l!==p).map(([,l])=>l.split(`
|
|
163
163
|
`).map(m=>m.trim()?` // ${m.trimStart()}`:m).join(`
|
|
164
164
|
`)).join(`
|
|
165
165
|
`);return`export default {
|
|
166
166
|
// AI agent settings
|
|
167
|
-
agent: {${n[
|
|
167
|
+
agent: {${n[p]}
|
|
168
168
|
${d}
|
|
169
169
|
strictMode: false,
|
|
170
170
|
},
|
|
@@ -248,7 +248,7 @@ ${d}
|
|
|
248
248
|
// Cloud sync - auto-upload test results & videos (requires ZIBBY_API_KEY in .env)
|
|
249
249
|
cloudSync: ${e.cloudSync||!1}
|
|
250
250
|
};
|
|
251
|
-
`}function
|
|
251
|
+
`}function Dt(e,o="dolt"){return`# Zibby Test Automation - Environment Variables
|
|
252
252
|
|
|
253
253
|
# AI Provider Keys
|
|
254
254
|
${{claude:"ANTHROPIC_API_KEY=sk-ant-your_key_here",cursor:`# Cursor Agent uses cursor-agent CLI \u2014 no API key needed
|
|
@@ -265,7 +265,7 @@ ${{claude:"ANTHROPIC_API_KEY=sk-ant-your_key_here",cursor:`# Cursor Agent uses c
|
|
|
265
265
|
|
|
266
266
|
# Chat memory backend
|
|
267
267
|
ZIBBY_MEMORY_BACKEND=${o}
|
|
268
|
-
`}function
|
|
268
|
+
`}function Ut(e,o,t="dolt"){return`# Zibby Test Automation - Environment Variables
|
|
269
269
|
|
|
270
270
|
# AI Provider Keys
|
|
271
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]||""}
|
|
@@ -280,7 +280,7 @@ ZIBBY_API_KEY=${o}
|
|
|
280
280
|
|
|
281
281
|
# Chat memory backend
|
|
282
282
|
ZIBBY_MEMORY_BACKEND=${t}
|
|
283
|
-
`}function
|
|
283
|
+
`}function Yt(e,o,t={}){let s={"@zibby/cli":"latest","@zibby/core":Nt("../../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 Ft(){return`# Dependencies
|
|
284
284
|
node_modules/
|
|
285
285
|
|
|
286
286
|
# Test artifacts
|
|
@@ -330,7 +330,7 @@ ${o?` outputDir: '${o}',
|
|
|
330
330
|
['list']
|
|
331
331
|
],
|
|
332
332
|
});
|
|
333
|
-
`}function
|
|
333
|
+
`}function Ht(){return`Test Specification: Example Domain Navigation
|
|
334
334
|
==============================================
|
|
335
335
|
|
|
336
336
|
Application: Example Domain
|
|
@@ -367,7 +367,7 @@ Notes:
|
|
|
367
367
|
- Uses a stable, public domain (example.com) maintained by IANA
|
|
368
368
|
- No authentication required
|
|
369
369
|
- Suitable for CI/CD smoke testing
|
|
370
|
-
`}function
|
|
370
|
+
`}function Gt(){return`# Example command template
|
|
371
371
|
|
|
372
372
|
Use this command when the user asks for a concise testing task breakdown.
|
|
373
373
|
|
|
@@ -378,7 +378,7 @@ Required output format:
|
|
|
378
378
|
4. Expected result
|
|
379
379
|
|
|
380
380
|
Keep the response actionable and short.
|
|
381
|
-
`}function
|
|
381
|
+
`}function Vt(e,o){return`# ${e}
|
|
382
382
|
|
|
383
383
|
AI-powered test automation with Zibby.
|
|
384
384
|
|
|
@@ -467,4 +467,4 @@ ${e}/
|
|
|
467
467
|
|
|
468
468
|
- Documentation: https://docs.zibby.dev
|
|
469
469
|
- Examples: https://github.com/zibby/examples
|
|
470
|
-
`}export{
|
|
470
|
+
`}export{Lt as generateConfig,zn as initCommand};
|