@zibby/cli 0.4.10 → 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 +2 -2
- package/dist/commands/init.js +118 -123
- package/dist/commands/template.js +5 -5
- package/dist/commands/workflow.js +3 -3
- package/dist/commands/workflows/deploy-helpers.js +3 -3
- package/dist/commands/workflows/deploy.js +37 -37
- package/dist/commands/workflows/generate.js +467 -54
- package/dist/commands/workflows/list.js +9 -9
- package/dist/commands/workflows/run-local.js +8 -8
- package/dist/commands/workflows/run.js +1 -1
- package/dist/commands/workflows/start.js +1 -1
- package/dist/package.json +2 -2
- package/package.json +2 -2
|
@@ -1,32 +1,171 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Zo=Object.defineProperty;var M=(o,e)=>()=>(o&&(e=o(o=0)),e);var L=(o,e)=>{for(var t in e)Zo(o,t,{get:e[t],enumerable:!0})};import{existsSync as Jo,readFileSync as qo,writeFileSync as Xo,mkdirSync as Qo}from"fs";import{join as Ne}from"path";import{homedir as Be}from"os";function Me(){return Ne(Be(),".zibby","config.json")}function ae(){try{let o=Me();return Jo(o)?JSON.parse(qo(o,"utf-8")):{}}catch{return{}}}function Ke(o,e){let t=e?ie[e]:null;t&&ge(t.envVar,o)}function ge(o,e){if(!o||typeof o!="string"||!e||typeof e!="string")return;let t=Ne(Be(),".zibby");Qo(t,{recursive:!0});let s=Me(),n=ae();(!n.agentKeys||typeof n.agentKeys!="object")&&(n.agentKeys={}),n.agentKeys[o]=String(e).trim(),delete n.agentApiKey,Xo(s,`${JSON.stringify(n,null,2)}
|
|
2
|
+
`,"utf-8")}var ie,Le=M(()=>{ie={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"}}});var me={};L(me,{resolveTemplate:()=>Ye,templateAddCommand:()=>ft,templateListCommand:()=>mt,writeTemplateFiles:()=>He,writeTemplateFilesToDir:()=>Fe});import{mkdir as De,writeFile as et,readFile as ot}from"fs/promises";import{existsSync as le,readdirSync as tt,statSync as nt,readFileSync as rt}from"fs";import{join as H,dirname as st}from"path";import{fileURLToPath as it}from"url";import{spawn as at}from"child_process";import{createRequire as lt}from"module";import C from"chalk";import ct from"ora";function gt(o){return pt.some(e=>e.test(o))}async function Ue(o,e,t=null){let s=[];le(e)||await De(e,{recursive:!0});for(let n of tt(o)){if(gt(n))continue;let r=H(o,n),u=H(e,n),l=nt(r);if(l.isDirectory()){let a=await Ue(r,u,t);for(let g of a)s.push(`${n}/${g}`)}else if(l.isFile()){let a=await ot(r,"utf-8");t&&(a=t(n,a)),await et(u,a),s.push(n)}}return s}async function Ye(o){if(!o||typeof o!="string")throw new Error("Template name is required");if(/^(git\+|https?:)/.test(o))throw new Error(`Git/URL templates are not yet supported (got "${o}"). For now use a built-in template \u2014 see \`zibby template list\`.`);if(o.startsWith("@")||o.includes("/")||o.startsWith("zibby-template-"))throw new Error(`npm-package templates are not yet supported (got "${o}"). For now use a built-in template \u2014 see \`zibby template list\`.`);let{TemplateFactory:e}=await import("@zibby/core/templates");return e.getTemplateFiles(o)}async function Fe(o,e,t={}){let s=t.enableMemory!==!1,{template:n}=await Ye(e);le(o)||await De(o,{recursive:!0});let r=await Ue(n.path,o,(u,l)=>!s&&u==="execute-live.mjs"?l.replace("skills: [SKILLS.BROWSER, SKILLS.MEMORY],","skills: [SKILLS.BROWSER],"):l);return{template:n,copied:r}}async function He(o,e,t={}){return Fe(H(o,".zibby"),e,t)}async function mt(){let{TemplateFactory:o}=await import("@zibby/core/templates"),e=o.listTemplates();console.log(""),console.log(C.bold.cyan(" Available templates")),console.log("");for(let t of e){if(console.log(` ${C.cyan(t.name)}`),console.log(` ${C.white(t.displayName)}`),t.description&&console.log(` ${C.gray(t.description)}`),t.features&&t.features.length)for(let n of t.features)console.log(C.gray(` \u2022 ${n}`));let s=t.defaultSlug||"your-workflow-name";console.log(""),console.log(` ${C.gray("Scaffold:")} ${C.cyan(`zibby workflow new ${s} -t ${t.name}`)}`),console.log("")}}async function ft(o,e={}){o||(console.log(C.red(`
|
|
2
3
|
Missing template name.
|
|
3
|
-
`)),console.log(
|
|
4
|
-
`)),process.exit(1));let
|
|
5
|
-
No .zibby/ directory in ${
|
|
6
|
-
`)),console.log(
|
|
7
|
-
${
|
|
8
|
-
`)),console.log(
|
|
9
|
-
`)),process.exit(1)}console.log(""),console.log(p.green(` \u2713 Added template ${p.bold(n.template.name)}`)),console.log(p.gray(` ${n.copied.length} files written to ${s}/`));for(let a of n.copied)console.log(p.gray(` \u2022 ${a}`));console.log(""),console.log(p.gray(" Re-running `zibby template add <name>` overwrites existing files \u2014")),console.log(p.gray(" use this to refresh after `npm update @zibby/core`.")),console.log("")}var Pe,U=Q(()=>{Pe=[/^__tests__$/,/^__mocks__$/,/^node_modules$/,/\.test\.[mc]?js$/,/\.spec\.[mc]?js$/,/^\.DS_Store$/]});import{mkdir as j,writeFile as A}from"fs/promises";import{existsSync as S}from"fs";import{spawn as ze}from"child_process";import{join as h}from"path";import i from"chalk";import F from"ora";import{input as Oe}from"@inquirer/prompts";import{existsSync as te}from"fs";import{join as oe}from"path";import{pathToFileURL as ne}from"url";async function K(e){let t=oe(e,".zibby.config.mjs");if(!te(t))throw new Error(".zibby.config.mjs not found");try{let o=await import(ne(t).href);return o.default||o}catch(o){throw new Error(`Failed to load .zibby.config.mjs: ${o.message}`,{cause:o})}}import{mkdir as at,writeFile as lt,readFile as ct}from"fs/promises";import{existsSync as gt,readdirSync as pt}from"fs";import{join as mt,resolve as ft,dirname as se}from"path";import{homedir as ht}from"os";import wt from"inquirer";import xt from"chalk";import vt from"ora";import{spawn as Ct,execSync as It}from"child_process";import{fileURLToPath as re}from"url";import{createRequire as ie}from"module";import{existsSync as Fe,readFileSync as We,writeFileSync as Ve,mkdirSync as qe}from"fs";import{join as Xe}from"path";import{homedir as et}from"os";var ae=re(import.meta.url),St=se(ae),zt=ie(import.meta.url);function R(e,t={},o={}){let s=["dolt","mem0"].includes(String(o.memoryBackend||"").toLowerCase())?String(o.memoryBackend).toLowerCase():"dolt",n=e.agentAuth==="oauth"||e.agentAuth==="api"?`
|
|
10
|
-
|
|
4
|
+
`)),console.log(C.gray(" Usage: zibby template add <name>")),console.log(C.gray(` See available templates: zibby template list
|
|
5
|
+
`)),process.exit(1));let t=e.cwd||process.cwd(),s=H(t,".zibby");le(s)||(console.log(C.yellow(`
|
|
6
|
+
No .zibby/ directory in ${t}.
|
|
7
|
+
`)),console.log(C.gray(" Run `zibby init` first to bootstrap the project.\n")),process.exit(1));let n;try{n=await He(t,o,{enableMemory:e.enableMemory!==!1})}catch(r){console.log(C.red(`
|
|
8
|
+
${r.message}
|
|
9
|
+
`)),console.log(C.gray(` See available templates: zibby template list
|
|
10
|
+
`)),process.exit(1)}console.log(""),console.log(C.green(` \u2713 Added template ${C.bold(n.template.name)}`)),console.log(C.gray(` ${n.copied.length} files written to ${s}/`));for(let r of n.copied)console.log(C.gray(` \u2022 ${r}`));if(!e.skipInstall&&le(H(t,"package.json"))){let r=!1;try{lt(H(t,"package.json")).resolve("@zibby/core/package.json"),r=!0}catch{}if(!r){let l=`@zibby/core@${JSON.parse(rt(H(dt,"../../package.json"),"utf-8")).dependencies?.["@zibby/core"]||"latest"}`,a=ct(` Installing ${l} (needed by .zibby/graph.mjs)...`).start();await new Promise(f=>{at("npm",["install","--save-dev",l],{cwd:t,stdio:"pipe"}).on("close",m=>f(m??1))})===0?a.succeed(` Installed ${l}`):(a.warn(` Could not auto-install ${l}`),console.log(C.gray(` Run manually: npm install --save-dev ${l}`)))}}console.log(""),console.log(C.gray(" Re-running `zibby template add <name>` overwrites existing files \u2014")),console.log(C.gray(" use this to refresh after `npm update @zibby/core`.")),console.log("")}var ut,dt,pt,fe=M(()=>{ut=it(import.meta.url),dt=st(ut),pt=[/^__tests__$/,/^__mocks__$/,/^node_modules$/,/\.test\.[mc]?js$/,/\.spec\.[mc]?js$/,/^\.DS_Store$/,/^chat\.mjs$/]});var We={};L(We,{applyMemorySyncConfig:()=>wt,validateMemorySyncConfig:()=>Ge});function Ge(o){if(!o||typeof o!="object")return{ok:!0,kind:"noop"};let e=o.remote;return yt.includes(e)?{ok:!0,kind:"noop"}:typeof e!="string"?{ok:!1,error:`memorySync.remote must be null or a string, got ${typeof e}`}:e===ht?{ok:!0,kind:"hosted"}:Ze.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: ${Ze.join(" / ")}.`}}async function wt({cwd:o,projectId:e,block:t,memoryApi:s,hostedSetup:n,getSessionToken:r,logger:u=console}){let l=Ge(t);if(!l.ok)return u.warn?.(`[memory-sync] config invalid: ${l.error}`),{action:"error",reason:l.error};if(l.kind==="noop")return{action:"skipped",reason:"memorySync.remote not set"};if(l.kind==="byo")return s?.memoryRemoteAdd?s.memoryRemoteAdd(o,l.remote)?{action:"byo",remote:l.remote}:{action:"error",reason:"memoryRemoteAdd returned false (memory DB not initialized?)"}:{action:"error",reason:"@zibby/ui-memory not loaded"};if(l.kind==="hosted"){if(typeof r=="function"&&!r())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 n!="function")return{action:"error",reason:"hostedSetup function not provided"};try{return await n({cwd:o,projectId:e}),{action:"hosted"}}catch(a){return{action:"error",reason:`hosted setup failed: ${a.message}`}}}return{action:"error",reason:`unhandled kind: ${l.kind}`}}var yt,ht,Ze,Ve=M(()=>{yt=[null,void 0,"","none","off",!1],ht="hosted",Ze=["aws://","gs://","https://","http://","file://"]});var he={};L(he,{clearSession:()=>so,default:()=>At,getMem0ProxyUrl:()=>lo,getProjects:()=>uo,getProxyUrl:()=>io,getSessionToken:()=>ye,getUserInfo:()=>to,isLoggedIn:()=>ro,loadConfig:()=>j,saveConfig:()=>D,saveMem0ProxyUrl:()=>co,saveProjects:()=>po,saveProxyUrl:()=>ao,saveSessionToken:()=>oo,saveUserInfo:()=>no});import{existsSync as Je,mkdirSync as bt,readFileSync as kt,writeFileSync as xt}from"fs";import{homedir as qe}from"os";import{join as ce}from"path";function Xe(){return process.env.ZIBBY_CONFIG_DIR||ce(qe(),".zibby")}function Qe(){return ce(Xe(),"config.json")}function $t(){let o=Xe();Je(o)||bt(o,{recursive:!0})}function j(){try{let o=Qe();if(Je(o)){let e=kt(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function D(o){$t(),xt(Qe(),JSON.stringify(o,null,2))}function ye(){return j().sessionToken||null}function oo(o){let e=j();e.sessionToken=o,D(e)}function to(){return j().user||null}function no(o){let e=j();e.user=o,D(e)}function ro(){return ye()!==null}function so(){let o=j();delete o.sessionToken,delete o.user,delete o.mem0ProxyUrl,D(o)}function io(){return j().proxyUrl||null}function ao(o){let e=j();e.proxyUrl=o,D(e)}function lo(){return j().mem0ProxyUrl||null}function co(o){let e=j();e.mem0ProxyUrl=o,D(e)}function uo(){return j().projects||[]}function po(o){let e=j();e.projects=o,D(e)}var eo,vt,At,we=M(()=>{eo=ce(qe(),".zibby"),vt=ce(eo,"config.json");At={loadConfig:j,saveConfig:D,getSessionToken:ye,saveSessionToken:oo,getUserInfo:to,saveUserInfo:no,isLoggedIn:ro,clearSession:so,getProxyUrl:io,saveProxyUrl:ao,getMem0ProxyUrl:lo,saveMem0ProxyUrl:co,getProjects:uo,saveProjects:po,CONFIG_DIR:eo,CONFIG_FILE:vt}});var go={};L(go,{ENVIRONMENTS:()=>_,getAccountApiUrl:()=>It,getApiUrl:()=>Ct,getCurrentEnvironment:()=>St,getFrontendUrl:()=>Pt});function Ct(){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 It(){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 St(){let o=process.env.ZIBBY_ENV||"prod";return _[o]||_.prod}function Pt(){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 s=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],n=e.hostname;if(!s.some(u=>n===u||n.endsWith(`.${u}`))&&!n.includes("localhost")&&n!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${n}`),"https://studio.zibby.dev"}return o}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${o}`),_.local.frontendUrl}}var _,mo=M(()=>{_={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 Ae={};L(Ae,{__testing:()=>Nt,buildDoltEnv:()=>Tt,clearConfig:()=>Rt,getActiveCredentials:()=>xo,isHosted:()=>jt,readConfig:()=>ve,refreshCredentials:()=>ko,writeConfig:()=>Ot});import{readFileSync as fo,writeFileSync as ke,existsSync as xe,mkdirSync as yo,chmodSync as _t}from"fs";import{join as be}from"path";function q(o){let e=be(o,".zibby");return{dir:e,config:be(e,Et),creds:be(e,zt)}}function ve(o){let{config:e}=q(o);if(!xe(e))return null;try{let t=JSON.parse(fo(e,"utf-8"));return t.mode!=="hosted"?null:t}catch{return null}}function jt(o){return!!ve(o)}function Ot(o,e){let{dir:t,config:s}=q(o);yo(t,{recursive:!0}),ke(s,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 Rt(o){let{config:e,creds:t}=q(o);for(let s of[e,t])if(xe(s))try{ke(s,"")}catch{}}function $e(o){let{creds:e}=q(o);if(!xe(e))return null;try{let t=JSON.parse(fo(e,"utf-8"));return!t?.accessKeyId||!t?.secretAccessKey||!t?.sessionToken?null:t}catch{return null}}function wo(o,e){let{dir:t,creds:s}=q(o);yo(t,{recursive:!0}),ke(s,JSON.stringify(e,null,2),"utf-8");try{_t(s,384)}catch{}}function bo(o){return o?.expiration?new Date(o.expiration).getTime()-Date.now()<ho:!0}async function ko({cwd:o,projectId:e,apiUrl:t,sessionToken:s,fetch:n=globalThis.fetch}){if(!e)throw new Error("refreshCredentials: projectId required");if(!t)throw new Error("refreshCredentials: apiUrl required");if(!s)throw new Error("refreshCredentials: sessionToken required (run `zibby login`)");let r=`${String(t).replace(/\/+$/,"")}/memory/sync-credentials`,u=await n(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({projectId:e})});if(!u.ok){let a=await u.text().catch(()=>"");throw new Error(`memory-sync credentials request failed (${u.status}): ${a||"no body"}`)}let l=await u.json();if(!l?.accessKeyId||!l?.secretAccessKey||!l?.sessionToken)throw new Error("memory-sync credentials response missing required fields");return wo(o,{accessKeyId:l.accessKeyId,secretAccessKey:l.secretAccessKey,sessionToken:l.sessionToken,expiration:l.expiration||null,refreshedAt:new Date().toISOString()}),$e(o)}async function xo({cwd:o,apiUrl:e,sessionToken:t,fetch:s}){let n=ve(o);if(!n)return null;let r=$e(o);return(!r||bo(r))&&(r=await ko({cwd:o,projectId:n.projectId,apiUrl:e,sessionToken:t,fetch:s})),r}async function Tt({cwd:o,apiUrl:e,sessionToken:t,fetch:s}){let n=await xo({cwd:o,apiUrl:e,sessionToken:t,fetch:s});return n?{AWS_ACCESS_KEY_ID:n.accessKeyId,AWS_SECRET_ACCESS_KEY:n.secretAccessKey,AWS_SESSION_TOKEN:n.sessionToken,AWS_REGION:process.env.AWS_REGION||"ap-southeast-2"}:null}var Et,zt,ho,Nt,Ce=M(()=>{Et="memory-sync.json",zt="memory-sync-creds.json",ho=120*1e3;Nt={paths:q,readCreds:$e,writeCreds:wo,isExpiringSoon:bo,REFRESH_HEADROOM_MS:ho}});var vo={};L(vo,{memoryCompactCommand:()=>Lt,memoryCostCommand:()=>Dt,memoryInitCommand:()=>Wt,memoryPullCommand:()=>Ht,memoryPushCommand:()=>Gt,memoryRemoteAddCommand:()=>Ut,memoryRemoteInfoCommand:()=>Yt,memoryRemoteRemoveCommand:()=>Ft,memoryRemoteUseHostedCommand:()=>Zt,memoryResetCommand:()=>Kt,memoryStatsCommand:()=>Mt});import i from"chalk";async function R(){try{return await import("@zibby/ui-memory")}catch{return console.log(i.yellow(`
|
|
11
|
+
@zibby/ui-memory is not installed.
|
|
12
|
+
`)),console.log(i.white(Bt)),null}}async function Mt(){let o=await R();if(!o)return;let e=process.cwd(),t=o.getStats(e);if(!t.available){console.log(i.red(`
|
|
13
|
+
Dolt is not installed.
|
|
14
|
+
`)),console.log(i.white(" Install Dolt to enable test memory:")),console.log(i.gray(" brew install dolt # macOS")),console.log(i.gray(` curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash # Linux
|
|
15
|
+
`));return}if(!t.initialized){console.log(i.yellow(`
|
|
16
|
+
Memory database not initialized.
|
|
17
|
+
`)),console.log(i.white(" Run `zibby init` or `zibby memory init` to set it up.\n"));return}console.log(i.bold.cyan(`
|
|
18
|
+
Zibby Test Memory
|
|
19
|
+
`)),console.log(i.gray(` Dolt: ${t.doltVersion}`));let s=i.gray(` ${"\u2500".repeat(40)}`);console.log(s);let n=t.counts;if(console.log(i.white(` Test runs: ${i.cyan(n.runs)} (${i.green(`${n.passed} passed`)}, ${n.failed>0?i.red(`${n.failed} failed`):i.gray(`${n.failed} failed`)})`)),console.log(i.white(` Selectors: ${i.cyan(n.selectors)} tracked`)),console.log(i.white(` Pages: ${i.cyan(n.pages)} discovered`)),console.log(i.white(` Transitions: ${i.cyan(n.transitions)} mapped`)),console.log(i.white(` Insights: ${i.cyan(n.insights||0)} saved`)),t.recentRuns.length>0){console.log(`
|
|
20
|
+
${s}`),console.log(i.white(" Recent runs:"));for(let r of t.recentRuns){let u=r.passed?i.green("\u2713"):i.red("\u2717"),l=r.duration_ms?i.gray(`${(r.duration_ms/1e3).toFixed(1)}s`):"";console.log(` ${u} ${i.white(r.spec_path)} ${l}`)}}if(t.topSelectors.length>0){console.log(`
|
|
21
|
+
${s}`),console.log(i.white(" Top selectors:"));for(let r of t.topSelectors){let u=r.success_count+r.failure_count,l=Math.round(r.success_count/u*100);console.log(` ${i.cyan(r.stable_id||"?")} \u2192 ${r.element_desc} (${l}%, ${u} uses)`)}}if(t.log){console.log(`
|
|
22
|
+
${s}`),console.log(i.white(" Recent commits:"));let r=t.log.split(`
|
|
23
|
+
`).filter(u=>u.startsWith("commit")||u.trim().startsWith("run ")).slice(0,10);for(let u of r)console.log(i.gray(` ${u.trim()}`))}console.log("")}async function Kt(o){let e=await R();if(!e)return;let t=process.cwd();if(!o.force){console.log(i.yellow(`
|
|
24
|
+
This will permanently delete the memory database.
|
|
25
|
+
`)),console.log(i.white(` Run with --force to confirm: zibby memory reset --force
|
|
26
|
+
`));return}let s=e.resetMemory(t);console.log(s?i.green(`
|
|
27
|
+
Memory database reset.
|
|
28
|
+
`):i.gray(`
|
|
29
|
+
No memory database found.
|
|
30
|
+
`))}async function Lt(o){let e=await R();if(!e)return;let t=process.cwd(),s=e.getStats(t);if(!s.initialized){console.log(i.yellow(`
|
|
31
|
+
Memory database not initialized.
|
|
32
|
+
`));return}let n=o.maxRuns||50,r=o.maxAge||90;console.log(i.white(`
|
|
33
|
+
Compacting memory (keep last ${n} runs/spec, prune data older than ${r}d)...`));let u=s.counts;if(e.compactMemory(t,{maxRuns:n,maxAgeDays:r}).pruned){let a=e.getStats(t).counts,g=f=>u[f]-a[f];console.log(i.green(" Done.")),g("runs")>0&&console.log(i.gray(` Pruned ${g("runs")} old runs`)),g("selectors")>0&&console.log(i.gray(` Pruned ${g("selectors")} stale selectors`)),g("insights")>0&&console.log(i.gray(` Pruned ${g("insights")} old insights`)),g("transitions")>0&&console.log(i.gray(` Pruned ${g("transitions")} stale transitions`)),console.log(i.gray(` Dolt GC completed
|
|
34
|
+
`))}else console.log(i.gray(` Nothing to compact.
|
|
35
|
+
`))}async function Dt(){let o=await R();if(!o)return;let e=process.cwd(),t=o.getCostStats(e);if(!t){console.log(i.yellow(`
|
|
36
|
+
Memory database not initialized.
|
|
37
|
+
`)),console.log(i.white(" Run `zibby memory init` first.\n"));return}if(t.available===!1){console.log(i.yellow(`
|
|
38
|
+
No usage data yet${t.reason?` (${t.reason})`:""}.
|
|
39
|
+
`)),console.log(i.gray(" Run `zibby test <spec>` once to populate. Token counts come from")),console.log(i.gray(` the LLM SDK and are written to .zibby/output/sessions/<id>/execute_live/usage.json.
|
|
40
|
+
`));return}console.log(i.bold.cyan(`
|
|
41
|
+
Zibby \u2014 LLM Cost Report
|
|
42
|
+
`));let s=i.gray(` ${"\u2500".repeat(60)}`),n=t.totals;if(console.log(s),console.log(i.white(` Runs with usage data: ${i.cyan(n.runs)}`)),console.log(i.white(` Total input tokens: ${i.cyan(U(n.input))}`)),console.log(i.white(` Total output tokens: ${i.cyan(U(n.output))}`)),console.log(i.white(` Total cache reads: ${i.cyan(U(n.cache_read))} ${i.gray("(billed at ~10% of normal input rate)")}`)),console.log(i.white(` Total cache creation: ${i.cyan(U(n.cache_creation))} ${i.gray("(billed at ~125% of normal input rate)")}`)),t.by_domain.length>0){console.log(`
|
|
43
|
+
${s}`),console.log(i.white(" By domain:"));for(let r of t.by_domain.slice(0,10)){let u=r.runs>0?Math.round((r.input+r.output)/r.runs):0;console.log(` ${i.cyan(r.domain.padEnd(30))} ${i.gray(`${r.runs} runs \xB7 ~${U(u)}/run avg`)}`)}}if(t.by_spec.length>0){console.log(`
|
|
44
|
+
${s}`),console.log(i.white(" By spec:"));for(let r of t.by_spec.slice(0,10)){let u=r.runs>0?Math.round((r.input+r.output)/r.runs):0;console.log(` ${i.cyan(String(r.spec_path).padEnd(40))} ${i.gray(`${r.runs} runs \xB7 ~${U(u)}/run avg`)}`)}}if(t.recent.length>0){console.log(`
|
|
45
|
+
${s}`),console.log(i.white(" Last 10 runs:"));for(let r of t.recent.slice(0,10)){let u=r.passed?i.green("\u2713"):i.red("\u2717"),l=(r.input_tokens||0)+(r.output_tokens||0),a=(r.cache_read_tokens||0)>0?i.gray(` \xB7 cache read ${U(r.cache_read_tokens)}`):"";console.log(` ${u} ${i.gray(r.run_at.slice(0,16))} ${i.cyan(U(l).padStart(8))} ${i.white(r.spec_path||"")}${a}`)}}console.log("")}function U(o){return o==null?"\u2014":o<1e3?String(o):o<1e6?`${(o/1e3).toFixed(1)}K`:`${(o/1e6).toFixed(2)}M`}async function Ut(o,e={}){let t=await R();if(!t)return;o||(console.log(i.red(`
|
|
46
|
+
Usage: zibby memory remote add <url> [--name origin]
|
|
47
|
+
`)),console.log(i.gray(" Supported: aws:// gs:// https:// file:///")),console.log(i.gray(" Example: zibby memory remote add aws://team-bucket/zibby/shop-prod")),console.log(""),process.exit(1));let s=process.cwd(),n=e.name||"origin";if(!t.memoryRemoteAdd(s,o,n)){console.log(i.red("\n Failed to add remote. Is the memory DB initialized? Run `zibby memory init` first.\n"));return}console.log(""),console.log(i.green(` \u2713 Added remote ${i.bold(n)} \u2192 ${o}`)),console.log(i.gray(" Next step: zibby memory pull (or just run any test \u2014 middleware auto-pulls/pushes)")),console.log("")}async function Yt(){let o=await R();if(!o)return;let e=o.memoryRemoteInfo(process.cwd());if(console.log(""),!e){console.log(i.yellow(` No memory remote configured.
|
|
48
|
+
`)),console.log(i.gray(" Set one with: zibby memory remote add <url>")),console.log(i.gray(` Without a remote, memory is local-only \u2014 team members won't see each other's learnings.
|
|
49
|
+
`));return}console.log(i.bold.cyan(" Memory remote")),console.log(` ${i.cyan(e.name||"origin")}: ${e.url||"(unknown)"}`),console.log("")}async function Ft(o="origin"){let e=await R();if(!e)return;let t=e.memoryRemoteRemove(process.cwd(),o);console.log(""),t?(console.log(i.green(` \u2713 Removed remote ${o}.`)),console.log(i.gray(" Memory is now local-only."))):console.log(i.gray(` No remote named ${o} to remove.`)),console.log("")}async function Ht(){let o=await R();if(!o)return;console.log(i.cyan(`
|
|
50
|
+
Pulling team memory from remote...`));let e=o.memorySyncPull(process.cwd());e.pulled?console.log(i.green(` \u2713 Pulled latest. Local memory now reflects the team's shared knowledge.
|
|
51
|
+
`)):(console.log(i.yellow(` \u26A0 Pull skipped \u2014 ${e.error||"unknown reason"}.`)),console.log(i.gray(" Did you run `zibby memory remote add <url>` first?\n")))}async function Zt(o={}){let e=await R();if(!e)return;let{join:t}=await import("path"),{existsSync:s}=await import("fs"),n=o.cwd||process.cwd(),r=o.projectId;if(!r){let A=t(n,".zibby.config.mjs");if(s(A))try{let v=(await import(`file://${A}?t=${Date.now()}`)).default;r=v?.projectId||v?.project?.id}catch{}}r||(console.log(i.red(`
|
|
52
|
+
Could not determine projectId.
|
|
53
|
+
`)),console.log(i.gray(" Either run this from a project dir with `.zibby.config.mjs`")),console.log(i.gray(` containing { projectId: "..." }, or pass --project-id <id>.
|
|
54
|
+
`)),process.exit(1));let{getApiUrl:u}=await Promise.resolve().then(()=>(mo(),go)),{getSessionToken:l}=await Promise.resolve().then(()=>(we(),he)),a=u(),g=l();g||(console.log(i.red("\n Not logged in. Run `zibby login` first.\n")),console.log(i.gray(" Hosted memory-sync is for signed-in users only \u2014")),console.log(i.gray(` the backend needs your identity to scope per-tenant credentials.
|
|
55
|
+
`)),process.exit(1)),console.log(i.cyan(`
|
|
56
|
+
Configuring hosted memory-sync...`));let f;try{let A=`${a.replace(/\/+$/,"")}/memory/sync-config?projectId=${encodeURIComponent(r)}`,b=await fetch(A,{headers:{Authorization:`Bearer ${g}`}});if(!b.ok){let v=await b.text().catch(()=>"");throw new Error(`backend returned ${b.status}: ${v||"no body"}`)}f=await b.json()}catch(A){console.log(i.red(`
|
|
57
|
+
Failed: ${A.message}
|
|
58
|
+
`)),process.exit(1)}let{writeConfig:w}=await Promise.resolve().then(()=>(Ce(),Ae));w(n,{projectId:r,bucket:f.bucket,prefix:f.prefix,doltUrl:f.doltUrl}),e.memoryRemoteAdd(n,f.doltUrl)||(console.log(i.yellow(`
|
|
59
|
+
Saved hosted-sync config, but failed to register Dolt remote.`)),console.log(i.gray(" Try `zibby memory init` first (the local Dolt DB must exist).\n")),process.exit(1));let{refreshCredentials:m}=await Promise.resolve().then(()=>(Ce(),Ae));try{await m({cwd:n,projectId:r,apiUrl:a,sessionToken:g})}catch(A){console.log(i.yellow(`
|
|
60
|
+
Config saved, but initial credential fetch failed: ${A.message}`)),console.log(i.gray(` Will retry on first push/pull.
|
|
61
|
+
`))}console.log(""),console.log(i.green(" \u2713 Hosted memory-sync configured.")),console.log(i.gray(` Bucket: ${f.bucket}`)),console.log(i.gray(` Prefix: ${f.prefix} \u2190 your tenant slot`)),console.log(i.gray(` Dolt: ${f.doltUrl}`)),console.log(""),console.log(i.gray(" Every test run will auto-pull/push. Creds refresh automatically.")),console.log(i.gray(" To revert to local-only: zibby memory remote remove origin")),console.log("")}async function Gt(){let o=await R();if(!o)return;console.log(i.cyan(`
|
|
62
|
+
Pushing local memory to team remote...`));let e=o.memorySyncPush(process.cwd());e.pushed?console.log(i.green(" \u2713 Pushed. Team can now `zibby memory pull` to see your run's learnings.\n")):console.log(i.yellow(` \u26A0 Push skipped \u2014 ${e.error||"unknown reason"}.
|
|
63
|
+
`))}async function Wt(){let o=await R();if(!o)return;let e=process.cwd();if(!o.DoltDB.isAvailable()){console.log(i.red(`
|
|
64
|
+
Dolt is not installed.
|
|
65
|
+
`)),console.log(i.white(" Install Dolt:")),console.log(i.gray(" brew install dolt # macOS")),console.log(i.gray(` curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash # Linux
|
|
66
|
+
`));return}let{created:t,available:s}=o.initMemory(e);t?console.log(i.green(`
|
|
67
|
+
Memory database initialized at .zibby/memory/
|
|
68
|
+
`)):s&&console.log(i.gray(`
|
|
69
|
+
Memory database already initialized.
|
|
70
|
+
`))}var Bt,$o=M(()=>{Bt=`
|
|
71
|
+
Install @zibby/ui-memory and Dolt to enable test memory:
|
|
72
|
+
|
|
73
|
+
npm install @zibby/ui-memory # add the package
|
|
74
|
+
brew install dolt # macOS
|
|
75
|
+
# or: curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash
|
|
76
|
+
`});var Oo={};L(Oo,{setupCiCommand:()=>sn,setupPlaywrightMcpCommand:()=>jo,testWithVideoCommand:()=>an});import{spawn as Se,execSync as Pe}from"child_process";import{join as Z,dirname as _e,resolve as Io}from"path";import{readFileSync as So,writeFileSync as Po,existsSync as X,mkdirSync as _o}from"fs";import{homedir as Eo}from"os";import{createRequire as Vt}from"module";import I from"chalk";function Jt(){try{return _e(Ie.resolve("@zibby/core/package.json"))}catch{return null}}function zo(o){try{return Pe(`command -v ${o}`,{stdio:"pipe"}),!0}catch{return!1}}function qt(){try{let o=Ie.resolve("@zibby/mcp-browser/bin/mcp-browser-zibby.js");if(X(o))return o}catch{}try{let o=Ie.resolve("@playwright/mcp/package.json"),e=_e(o),t=JSON.parse(So(o,"utf-8")),s=typeof t.bin=="string"?t.bin:t.bin?.["playwright-mcp"];if(s){let r=Z(e,s);if(X(r))return r}let n=Z(e,"cli.js");if(X(n))return n}catch{}return null}function Ao(o,e,t={}){return new Promise((s,n)=>{let r=Se(o,e,{stdio:"inherit",...t});r.on("close",u=>s(u??1)),r.on("error",n)})}async function Xt(o){return zo("playwright")?await Ao("playwright",["install","ffmpeg"],{cwd:o})===0:await Ao("npx",["--yes","playwright","install","ffmpeg"],{cwd:o})===0}function Qt({headed:o=!1,viewport:e=null}){let t=process.execPath,s=_e(t),n=qt(),r=Number(e?.width)||1280,u=Number(e?.height)||720,l=`${r}x${u}`,a=[];a.push(`--viewport-size=${l}`,"--output-dir=test-results"),o||a.push("--headless");let g;n?g={command:t,args:[n,...a],env:{PATH:`${s}:/usr/bin:/bin:/usr/sbin:/sbin`}}:g={command:"npx",args:["-y","@playwright/mcp",...a],env:{PATH:`${s}:/usr/bin:/bin:/usr/sbin:/sbin`}},g.description="Zibby MCP Browser - Playwright MCP with Zibby defaults";let f=Z(Eo(),".cursor"),w=Z(f,"mcp.json");X(f)||_o(f,{recursive:!0});let m={mcpServers:{}};if(X(w))try{m=JSON.parse(So(w,"utf-8")),(!m.mcpServers||typeof m.mcpServers!="object")&&(m.mcpServers={})}catch{m={mcpServers:{}}}m.mcpServers["playwright-official"]=g,Po(w,`${JSON.stringify(m,null,2)}
|
|
77
|
+
`,"utf-8")}async function en(){let o=Jt();if(!o)return;let e=Z(o,"scripts","patch-cursor-mcp.js");if(X(e))try{await new Promise((t,s)=>{let n=Se(process.execPath,[e],{cwd:process.cwd(),stdio:"ignore"});n.on("close",r=>t(r??0)),n.on("error",s)})}catch{}}function on(o){return Io(o).replace(/^\/+/,"").replace(/\//g,"-")}function tn(o){let e=String(o||""),t=e.split(`
|
|
78
|
+
`).find(r=>/playwright-official/i.test(r)&&/APPROVAL|🔑/i.test(r));if(t){let r=t.match(/=>\s*(\S+)/);if(r)return r[1]}let s=e.match(/playwright-official[^=]*=>\s*(\S+)/);if(s)return s[1];let n=e.match(/playwright-official-[a-f0-9]+/i);return n?n[0]:null}function nn(o,e){let t=on(o),s=Z(Eo(),".cursor","projects",t);_o(s,{recursive:!0});let n=Z(s,"mcp-approvals.json");return Po(n,`${JSON.stringify([e],null,2)}
|
|
79
|
+
`,"utf-8"),n}function Co(o){try{return Pe("cursor-agent mcp list",{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:process.env,maxBuffer:2*1024*1024})}catch(e){let t=e.stdout!=null?String(e.stdout):"",s=e.stderr!=null?String(e.stderr):"";return t+s}}function rn(o){try{return Pe("cursor-agent mcp enable playwright-official",{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:process.env,maxBuffer:1024*1024}),!0}catch{return!1}}async function jo(o={}){let e=!!o.headed,t=o.viewport||{width:1280,height:720};if(!process.execPath)throw new Error("Node.js runtime not found");let s=await Xt(process.cwd());console.log(s?I.gray(" \u2713 ffmpeg installed for Playwright video"):I.yellow(" \u26A0 Could not install ffmpeg (video may be unavailable)")),Qt({headed:e,viewport:t}),await en();let n=Io(process.cwd());if(zo("cursor-agent")){Co(n);let r=rn(n);r&&console.log(I.gray(" \u2713 cursor-agent: mcp enable playwright-official"));let u=Co(n),l=tn(u);if(l)try{let a=nn(n,l);console.log(I.gray(` \u2713 MCP auto-approval key saved (${a})`))}catch(a){console.log(I.yellow(` \u26A0 Could not write mcp-approvals.json: ${a.message}`))}else r||(console.log(I.yellow(" \u26A0 Could not auto-approve MCP (mcp enable failed and no approval key in cursor-agent output)")),console.log(I.gray(" Try: cursor-agent mcp enable playwright-official")))}else console.log(I.yellow(" \u26A0 cursor-agent not found; install it to use Cursor MCP tools"))}async function sn(o){try{console.log(I.cyan(`
|
|
80
|
+
\u{1F680} Running CI setup...
|
|
81
|
+
`)),await jo({headed:!1,cloudSync:!0,viewport:{width:1280,height:720}}),console.log(I.green(`
|
|
82
|
+
\u2705 CI/CD setup complete!
|
|
83
|
+
`))}catch(e){console.log(I.red(`
|
|
84
|
+
\u274C Error: ${e.message}
|
|
85
|
+
`)),process.exit(1)}}async function an(o,e){try{let t=["playwright","test",o||"tests/","--project=chromium"];e.headed&&t.push("--headed"),console.log(I.cyan(`
|
|
86
|
+
\u{1F3A5} Running tests with video recording...
|
|
87
|
+
`)),console.log(I.gray("\u2501".repeat(50)));let s=Se("npx",t,{cwd:process.cwd(),stdio:"inherit"});s.on("close",n=>{n===0?console.log(I.green(`
|
|
88
|
+
\u2705 Tests complete!
|
|
89
|
+
`)):(console.log(I.red(`
|
|
90
|
+
\u274C Tests failed with code ${n}
|
|
91
|
+
`)),process.exit(n))}),s.on("error",n=>{console.log(I.red(`
|
|
92
|
+
\u274C Error: ${n.message}
|
|
93
|
+
`)),process.exit(1)})}catch(t){console.log(I.red(`
|
|
94
|
+
\u274C Error: ${t.message}
|
|
95
|
+
`)),process.exit(1)}}var Ie,Ro=M(()=>{Ie=Vt(import.meta.url)});var No={};L(No,{generateConfig:()=>de,initCommand:()=>hn});import{mkdir as G,writeFile as E,readFile as Q}from"fs/promises";import{existsSync as P,readdirSync as ln}from"fs";import{join as x,resolve as To,dirname as cn}from"path";import{homedir as F}from"os";import W from"inquirer";import c from"chalk";import Y from"ora";import{spawn as ne,execSync as ue}from"child_process";import{fileURLToPath as un}from"url";import{createRequire as dn}from"module";async function pn(){let o=ae(),e=process.env.ANTHROPIC_API_KEY||o.agentKeys?.ANTHROPIC_API_KEY,t=o.agentKeys?.CLAUDE_CODE_OAUTH_TOKEN||null;console.log(""),console.log(c.cyan(" Claude credentials \u2014 pick the type you have:")),console.log("");let{kind:s}=await W.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:e?`API key ***${e.slice(-4)} \xB7 pay-per-token`:"API key \xB7 pay-per-token",value:"api"}],default:t?"oauth":e?"api":"oauth"}]);if(s==="skip")return{kind:"skip"};if(s==="oauth"){t||(console.log(""),console.log(c.gray(" How to generate a long-lived OAuth token (cloud-compatible):")),console.log(c.gray(" 1. Install claude (skip if you already have it):")),console.log(c.gray(" npm install -g @anthropic-ai/claude-code")),console.log(c.gray(" 2. Run:")),console.log(c.gray(" claude setup-token")),console.log(c.gray(" \u2192 confirms in your browser \u2192 prints a token starting with sk-ant-oat01-\u2026")),console.log(c.gray(" 3. Paste that token below.")),console.log(""),console.log(c.yellow(" Note: do NOT paste the short-lived token from `claude` browser-login \u2014")),console.log(c.yellow(" it works locally but Anthropic rejects it from non-login IPs (cloud).")),console.log(""));let l=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:a}=await W.prompt([{type:"password",name:"token",message:l,mask:"*"}]),g=(a||"").trim();return g?{kind:"oauth",token:g}:t?{kind:"oauth",token:t}:{kind:"skip"}}let n=e?`Press Enter to reuse saved API key (***${e.slice(-4)}), or paste a new one:`:"Paste Anthropic API key (from https://console.anthropic.com/settings/keys, or press Enter to skip):",{token:r}=await W.prompt([{type:"password",name:"token",message:n,mask:"*"}]),u=(r||"").trim();return u?{kind:"api",token:u}:e?{kind:"api",token:e}:{kind:"skip"}}async function yn(){try{let o=process.platform==="win32",e=ue("npm config get prefix",{encoding:"utf-8"}).trim(),t=o?e:`${e}/bin`,s=t.replace(/^~/,F()),n=o?";":":";if(process.env.PATH.split(n).some(w=>{let m=w.replace(/^~/,F());return m===s||m===t}))return;if(process.env.CI||process.env.ZIBBY_CI||!process.stdin.isTTY){console.log(c.yellow("npm global bin not in PATH")),console.log(c.gray(` Location: ${s}`)),console.log(c.gray(` Add it manually: export PATH="${s}:$PATH"
|
|
96
|
+
`));return}console.log(c.yellow("npm global bin not in PATH")),console.log(c.gray(` Location: ${s}`)),console.log();let{shouldAddPath:l}=await W.prompt([{type:"confirm",name:"shouldAddPath",message:"Add npm global bin to your shell PATH automatically?",default:!0}]);if(!l){o?(console.log(c.gray(`
|
|
97
|
+
To add manually on Windows:`)),console.log(c.gray(' 1. Search "Environment Variables" in Start menu')),console.log(c.gray(' 2. Edit "Path" in User variables')),console.log(c.gray(` 3. Add: ${s}
|
|
98
|
+
`))):(console.log(c.gray(`
|
|
99
|
+
To add manually, run:`)),console.log(c.gray(` echo 'export PATH="${s}:$PATH"' >> ~/.zshrc`)),console.log(c.gray(` source ~/.zshrc
|
|
100
|
+
`)));return}if(o){console.log(c.yellow("Cannot auto-add PATH on Windows")),console.log(c.gray(" Please add manually:")),console.log(c.gray(' 1. Search "Environment Variables" in Start menu')),console.log(c.gray(' 2. Edit "Path" in User variables')),console.log(c.gray(` 3. Add: ${s}
|
|
101
|
+
`));return}let a=process.env.SHELL||"",g="";if(a.includes("zsh"))g=x(F(),".zshrc");else if(a.includes("bash"))g=P(x(F(),".bashrc"))?x(F(),".bashrc"):x(F(),".bash_profile");else{console.log(c.yellow(`Unknown shell: ${a}`)),console.log(c.gray(" Please add manually:")),console.log(c.gray(` export PATH="${s}:$PATH"`));return}if(P(g)){let w=await Q(g,"utf-8");if(w.includes(s)||w.includes("npm")&&w.includes("global")&&w.includes("bin")){console.log(c.yellow(`PATH entry found in ${g} but not active`)),console.log(c.gray(` Run: source ${g}
|
|
102
|
+
`));return}}let f=`
|
|
103
|
+
# npm global bin (added by zibby)
|
|
104
|
+
export PATH="${s}:$PATH"
|
|
105
|
+
`;await E(g,(P(g)?await Q(g,"utf-8"):"")+f),console.log(c.green(`Added to ${g}`)),console.log(c.yellow(`
|
|
106
|
+
Run this to activate in current session:`)),console.log(c.gray(` source ${g}
|
|
107
|
+
`))}catch{}}async function hn(o,e){let t=e.template==="browser-test-automation";console.log(t?`
|
|
108
|
+
Zibby Test Automation
|
|
109
|
+
`:`
|
|
110
|
+
Zibby Project Init
|
|
111
|
+
`);let s=!e.skipMemory,n=["dolt","mem0"].includes(String(e.memoryBackend||"").toLowerCase())?String(e.memoryBackend).toLowerCase():"dolt";await yn();let r=o?To(process.cwd(),o):process.cwd(),u=o||"zibby-tests",l=!!o;l&&P(r)&&(console.log(c.red(`
|
|
112
|
+
Directory "${o}" already exists!
|
|
113
|
+
`)),process.exit(1)),!l&&P(x(r,".zibby.config.mjs"))&&!e.force&&(console.log(c.yellow(`
|
|
114
|
+
Zibby is already initialized in this directory!
|
|
115
|
+
`)),console.log(c.white("Config file found: .zibby.config.mjs")),console.log(c.gray(`Use --force or -f to reinitialize
|
|
116
|
+
`)),process.exit(0)),e.force&&!l&&console.log(c.cyan(`
|
|
117
|
+
Reinitializing Zibby configuration...
|
|
118
|
+
`));let a;if(e.agent&&(e.headed||e.headless))console.log(c.cyan(`Setting up with provided options...
|
|
119
|
+
`)),a={agent:e.agent,browserMode:e.headless?"headless":"headed",apiKey:e.apiKey||null,cloudSync:!!(e.cloudSync||e.apiKey)};else{if(e.agent)a={agent:e.agent};else{let{agent:v}=await W.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"}]);a={agent:v}}let m=ie[a.agent],A=!(process.env.CI||process.env.ZIBBY_CI||!process.stdin.isTTY);if(a.agent==="claude"&&!e.agentKey&&A){let v=await pn();v?.kind==="oauth"&&v.token?(a.claudeOauthToken=v.token,a.agentAuth="oauth"):v?.kind==="api"&&v.token&&(a.agentKey=v.token,a.agentAuth="api")}else if(m&&!e.agentKey&&A){let v=ae(),p=process.env[m.envVar]||v.agentKeys?.[m.envVar],h=p?`***${p.slice(-4)}`:null,y=h?`${m.label} found (${h}). Press Enter to keep, or paste a new key:`:`Enter ${m.label} (from ${m.url}, or press Enter to skip):`,{agentKey:$}=await W.prompt([{type:"password",name:"agentKey",message:y,mask:"*"}]);$&&$.trim()&&(a.agentKey=$.trim(),a.agentAuth="api")}let b=[];if(t&&!e.headed&&!e.headless&&b.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&&!e.apiKey&&b.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:"}),b.length>0){let v=await W.prompt(b);Object.assign(a,v)}a.browserMode=e.headless?"headless":e.headed?"headed":a.browserMode,a.apiKey=e.apiKey||a.apiKey,a.cloudSync=!!(e.cloudSync||e.apiKey||a.apiKey&&a.apiKey.trim())}e.agentKey&&(a.agentKey=e.agentKey),e.agentOauthToken&&a.agent==="claude"&&(a.claudeOauthToken=e.agentOauthToken);let f=ie[a.agent];a.claudeOauthToken&&(ge("CLAUDE_CODE_OAUTH_TOKEN",a.claudeOauthToken),console.log(c.gray(" Claude OAuth subscription token saved to ~/.zibby/config.json")),console.log(c.gray(" Used by: zibby test / chat / workflow run / workflow start"))),a.agentKey&&(Ke(a.agentKey,a.agent),console.log(c.gray(" Agent API key saved to ~/.zibby/config.json"))),a.mcp="playwright",a.setupMcp=a.agent==="cursor";let w=Y("Setting up Zibby...").start();try{if(l&&await G(r,{recursive:!0}),t&&(await G(x(r,"test-specs/examples"),{recursive:!0}),await G(x(r,"tests"),{recursive:!0})),await G(x(r,".zibby/output"),{recursive:!0}),await G(x(r,".zibby/commands"),{recursive:!0}),s&&n==="dolt")try{let{initMemory:p,DoltDB:h}=await import("@zibby/ui-memory");if(h.isAvailable()){let{created:y}=p(r);y&&(w.text="Initialized test memory database (Dolt)...")}else w.text="Dolt not found \u2014 skipping memory database (brew install dolt)"}catch{}let m=e.template,A=m&&m!=="none"&&m!=="false";if(A){w.text=`Scaffolding workflow template: ${m}...`;try{let{writeTemplateFiles:p}=await Promise.resolve().then(()=>(fe(),me));await p(r,m,{enableMemory:s})}catch(p){throw w.fail(`Failed to scaffold template: ${p.message}`),p}}else await G(x(r,".zibby"),{recursive:!0});w.text="Generating configuration files...";let b=de(a,e,{memoryBackend:n});if(await E(x(r,".zibby.config.mjs"),b),await E(x(r,".env.example"),wn(a,n)),a.apiKey&&a.apiKey.trim()){let p=x(r,".env"),h=a.apiKey.trim();if(P(p)){let y=await Q(p,"utf8");/^ZIBBY_API_KEY=/m.test(y)?y=y.replace(/^ZIBBY_API_KEY=.*/m,`ZIBBY_API_KEY=${h}`):/^#\s*ZIBBY_API_KEY=/m.test(y)?y=y.replace(/^#\s*ZIBBY_API_KEY=.*/m,`ZIBBY_API_KEY=${h}`):y=`${y.trimEnd()}
|
|
120
|
+
|
|
121
|
+
# Zibby Cloud Sync
|
|
122
|
+
ZIBBY_API_KEY=${h}
|
|
123
|
+
`,await E(p,y)}else await E(p,bn(a,h,n))}if(a.agentKey&&f){let p=x(r,".env"),h=a.agentKey;if(P(p)){let y=await Q(p,"utf8"),$=new RegExp(`^${f.envVar}=.*`,"m"),k=new RegExp(`^#\\s*${f.envVar}=.*`,"m");$.test(y)?y=y.replace($,`${f.envVar}=${h}`):k.test(y)?y=y.replace(k,`${f.envVar}=${h}`):y=`${y.trimEnd()}
|
|
124
|
+
|
|
125
|
+
# AI Agent Key
|
|
126
|
+
${f.envVar}=${h}
|
|
127
|
+
`,await E(p,y)}}if(l){let p=kn(u,a,{memoryBackend:n});await E(x(r,"package.json"),p)}if(!P(x(r,".gitignore"))){let p=xn();await E(x(r,".gitignore"),p)}if(t){if(!P(x(r,"playwright.config.js"))){let p=vn("on");await E(x(r,"playwright.config.js"),p)}if(!P(x(r,"test-specs/examples/example-domain.txt"))){let p=$n();await E(x(r,"test-specs/examples/example-domain.txt"),p)}}let v=To(mn,"../../../../examples/.zibby/commands");if(P(v)){let p=ln(v).filter(h=>h.toLowerCase().endsWith(".md"));for(let h of p){let y=x(r,".zibby/commands",h);if(e.force||!P(y)){let $=await Q(x(v,h),"utf-8");await E(y,$)}}}if(!P(x(r,".zibby/commands/example.md"))){let p=An();await E(x(r,".zibby/commands/example.md"),p)}if(l){let p=Cn(u,a);await E(x(r,"README.md"),p)}try{let{validateMemorySyncConfig:p,applyMemorySyncConfig:h}=await Promise.resolve().then(()=>(Ve(),We)),y=x(r,".zibby.config.mjs"),$=null;if(P(y))try{$=(await import(`file://${y}?t=${Date.now()}`)).default?.memorySync}catch{}let k=p($);if(k.ok&&k.kind!=="noop"){let O=await import("@zibby/ui-memory").catch(()=>null),{getSessionToken:se}=await Promise.resolve().then(()=>(we(),he)),B=await h({cwd:r,projectId:a.projectId,block:$,memoryApi:O,getSessionToken:se,hostedSetup:async({cwd:oe,projectId:te})=>{let{memoryRemoteUseHostedCommand:Re}=await Promise.resolve().then(()=>($o(),vo));await Re({cwd:oe,projectId:te})},logger:{info:()=>{},warn:()=>{},error:()=>{}}});B.action==="hosted"?console.log(c.green(" \u2713 Hosted memory-sync configured from .zibby.config.mjs")):B.action==="byo"?console.log(c.green(` \u2713 Memory remote configured from .zibby.config.mjs \u2192 ${B.remote}`)):B.action==="pending-login"?(console.log(c.yellow(` \u26A0 memorySync.remote = "hosted" but you're not logged in.`)),console.log(c.gray(" Run `zibby login` then `zibby memory remote use --hosted` to finish."))):B.action==="error"&&console.log(c.yellow(` \u26A0 memorySync setup skipped: ${B.reason}`))}else k.ok||console.log(c.yellow(` \u26A0 memorySync config invalid: ${k.error}`))}catch(p){console.log(c.yellow(` \u26A0 memorySync auto-apply failed: ${p.message}`))}if(w.succeed(l?"Project created!":"Zibby initialized!"),A||(console.log(""),console.log(c.gray(" No workflow scaffolded. Add one when ready:")),console.log(c.gray(" zibby template list # see available")),console.log(c.gray(" zibby workflow new <slug> -t <template> # named, deployable copy")),console.log("")),l&&!e.skipInstall){let p=Y("Installing dependencies...").start();await new Promise((h,y)=>{ne("npm",["install"],{cwd:r,stdio:"pipe"}).on("close",k=>{k===0?(p.succeed("Dependencies installed!"),h()):(p.fail("Failed to install dependencies"),y(new Error("npm install failed")))})})}if(!l&&s&&n==="mem0"&&(console.log(c.yellow(`
|
|
128
|
+
Using mem0 backend requires mem0ai in your project dependencies.`)),console.log(c.gray("Run this manually in your project when ready:")),console.log(c.white(` npm install mem0ai
|
|
129
|
+
`))),!e.skipInstall&&t){let p=Y("Installing Playwright browsers...").start();await new Promise(h=>{let y=ne("npx",["playwright","install","chromium"],{cwd:r,stdio:"pipe"}),$="";y.stdout.on("data",k=>{$+=k.toString()}),y.stderr.on("data",k=>{$+=k.toString()}),y.on("close",k=>{k===0?($.includes("already installed")||$.includes("up to date")?p.succeed("Playwright browsers already installed"):p.succeed("Playwright browsers installed!"),h()):(p.warn("Could not verify Playwright browsers"),console.log(c.yellow(`
|
|
130
|
+
If tests fail, run: npx playwright install
|
|
131
|
+
`)),h())})})}if(a.agent==="cursor"&&!e.skipInstall){let p=Y("Checking cursor-agent CLI...").start();try{ue("cursor-agent --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),p.succeed("cursor-agent CLI already installed")}catch{p.text="Installing cursor-agent CLI...";try{await new Promise((h,y)=>{ne("bash",["-c","curl https://cursor.com/install -fsS | bash"],{stdio:"pipe"}).on("close",k=>{if(k===0){let O=x(F(),".local","bin");process.env.PATH.includes(O)||(process.env.PATH=`${O}:${process.env.PATH}`),p.succeed("cursor-agent CLI installed!"),h()}else y(new Error("cursor-agent install failed"))})})}catch{p.fail("Could not install cursor-agent CLI"),console.log(c.yellow(` Install manually: curl https://cursor.com/install -fsS | bash
|
|
132
|
+
`))}}}if(a.agent==="codex"&&!e.skipInstall){let p=Y("Checking Codex CLI...").start();try{ue("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),p.succeed("Codex CLI already installed")}catch{p.text="Installing Codex CLI...";try{await new Promise((h,y)=>{ne("npm",["install","-g","@openai/codex"],{stdio:"pipe"}).on("close",k=>{k===0?(p.succeed("Codex CLI installed!"),h()):y(new Error("npm install -g @openai/codex failed"))})})}catch{p.fail("Could not install Codex CLI"),console.log(c.yellow(` Install manually: npm install -g @openai/codex
|
|
133
|
+
`))}}}if(a.agent==="gemini"&&!e.skipInstall){let p=Y("Checking Gemini CLI...").start();try{ue("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),p.succeed("Gemini CLI already installed")}catch{p.text="Installing Gemini CLI...";try{await new Promise((h,y)=>{ne("npm",["install","-g","@google/gemini-cli"],{stdio:"pipe"}).on("close",k=>{k===0?(p.succeed("Gemini CLI installed!"),h()):y(new Error("npm install -g @google/gemini-cli failed"))})})}catch{p.fail("Could not install Gemini CLI"),console.log(c.yellow(` Install manually: npm install -g @google/gemini-cli
|
|
134
|
+
`))}}if(t){let h=Y("Configuring Gemini MCP servers...").start();try{let y=x(F(),".gemini"),$=x(y,"settings.json");P(y)||await G(y,{recursive:!0});let k={mcpServers:{}};if(P($))try{let te=await Q($,"utf-8");k=JSON.parse(te),k.mcpServers||(k.mcpServers={})}catch{}let O;try{let{createRequire:te}=await import("module");O=te(import.meta.url).resolve("@zibby/mcp-browser/bin/mcp-browser-zibby.js")}catch{O="@playwright/mcp"}let se=a.browserMode!=="headless",B=O==="@playwright/mcp"?["-y","@playwright/mcp","--isolated","--viewport-size=1280x720","--output-dir","test-results"]:[O,"--isolated","--viewport-size=1280x720","--output-dir=test-results"];se||B.push("--headless"),k.mcpServers["playwright-official"]={command:O==="@playwright/mcp"?"npx":"node",args:B},await E($,`${JSON.stringify(k,null,2)}
|
|
135
|
+
`,"utf-8");let oe="Gemini MCP configured";se?oe+=" (headed mode - visible browser)":oe+=" (headless mode - hidden browser)",h.succeed(oe)}catch(y){h.fail("MCP setup failed"),console.log(c.yellow(" You may need to configure ~/.gemini/settings.json manually")),console.log(c.gray(` Error: ${y.message}
|
|
136
|
+
`))}}}if(a.agent==="cursor"&&a.setupMcp&&t){let p=Y("Setting up Playwright MCP...").start();try{let{setupPlaywrightMcpCommand:h}=await Promise.resolve().then(()=>(Ro(),Oo)),y=a.cloudSync||!1,$=a.browserMode!=="headless";await h({headed:$,cloudSync:y,viewport:{width:1280,height:720}});let k="Playwright MCP configured";$?k+=" (headed mode - visible browser)":k+=" (headless mode - hidden browser)",y&&(k+=" + Zibby MCP (cloud sync)"),p.succeed(k),y&&!(a.apiKey&&a.apiKey.trim())&&console.log(c.gray(`
|
|
137
|
+
Copy .env.example to .env and set ZIBBY_API_KEY to enable uploads
|
|
138
|
+
`))}catch(h){p.fail("MCP setup script failed"),console.log(c.yellow(" Check if MCP is already configured:")),console.log(c.gray(' \u2022 Open Cursor settings \u2192 Check "playwright-official" MCP')),console.log(c.gray(" \u2022 Run: cursor-agent mcp list")),console.log(c.gray(` \u2022 Or run manually: zibby setup-playwright
|
|
139
|
+
`)),console.log(c.gray(` Error: ${h.message}
|
|
140
|
+
`))}}console.log(c.bold.green(`
|
|
141
|
+
All set!
|
|
142
|
+
`)),l&&(console.log(c.cyan("Get into the project:")),console.log(c.white(` cd ${o}
|
|
143
|
+
`))),t?(console.log(c.cyan("Run a test:")),console.log(c.white(` zibby test test-specs/examples/example-domain.txt
|
|
144
|
+
`)),console.log(c.cyan("Cloud features (optional):")),console.log(c.white(` zibby login ${c.gray("# unlock workflow deploy, hosted memory, etc.")}`)),console.log(""),console.log(c.cyan("Next steps:")),console.log(c.white(` 1. cp .env.example .env ${c.gray("# then add your API keys")}`)),console.log(c.white(` 2. Write test specs in ${c.bold("test-specs/")}`)),console.log(c.white(` 3. Run: ${c.bold("zibby test <spec-file>")}`)),console.log(c.white(` 4. Or chat: ${c.bold("zibby")}
|
|
145
|
+
`))):(console.log(c.cyan("Add a workflow when ready:")),console.log(c.white(` zibby template list ${c.gray("# see available")}`)),console.log(c.white(` zibby workflow new my-pipeline ${c.gray("# blank scaffold")}`)),console.log(c.white(` zibby workflow new my-pip -t <name> ${c.gray("# from a template")}
|
|
146
|
+
`)),console.log(c.cyan("Cloud features (optional):")),console.log(c.white(` zibby login ${c.gray("# unlock workflow deploy, hosted memory, etc.")}`)),console.log(""))}catch(m){w.fail("Failed to create project"),console.error(c.red(`
|
|
147
|
+
Error: ${m.message}
|
|
148
|
+
`)),process.exit(1)}}function de(o,e={},t={}){let s=["dolt","mem0"].includes(String(t.memoryBackend||"").toLowerCase())?String(t.memoryBackend).toLowerCase():"dolt",n=o.agentAuth==="oauth"||o.agentAuth==="api"?`
|
|
149
|
+
auth: '${o.agentAuth}', // 'oauth' (subscription) or 'api' (pay-per-token); cloud needs 'api'`:"",r={claude:`
|
|
11
150
|
claude: {
|
|
12
151
|
model: 'auto', // Options: 'auto', 'sonnet-4.6', 'opus-4.6', 'sonnet-4.5', 'opus-4.5'
|
|
13
|
-
maxTokens: 4096,${
|
|
152
|
+
maxTokens: 4096,${o.agent==="claude"?n:""}
|
|
14
153
|
},`,cursor:`
|
|
15
154
|
cursor: {
|
|
16
|
-
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'${o.agent==="cursor"?n:""}
|
|
17
156
|
},`,codex:`
|
|
18
157
|
codex: {
|
|
19
|
-
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'${o.agent==="codex"?n:""}
|
|
20
159
|
},`,gemini:`
|
|
21
160
|
gemini: {
|
|
22
|
-
model: 'gemini-2.5-pro', // Options: 'auto', 'gemini-2.5-pro', 'gemini-2.5-flash'${
|
|
23
|
-
},`},
|
|
24
|
-
`).map(
|
|
161
|
+
model: 'gemini-2.5-pro', // Options: 'auto', 'gemini-2.5-pro', 'gemini-2.5-flash'${o.agent==="gemini"?n:""}
|
|
162
|
+
},`},u=o.agent,l=Object.entries(r).filter(([a])=>a!==u).map(([,a])=>a.split(`
|
|
163
|
+
`).map(g=>g.trim()?` // ${g.trimStart()}`:g).join(`
|
|
25
164
|
`)).join(`
|
|
26
165
|
`);return`export default {
|
|
27
166
|
// AI agent settings
|
|
28
|
-
agent: {${
|
|
29
|
-
${
|
|
167
|
+
agent: {${r[u]}
|
|
168
|
+
${l}
|
|
30
169
|
strictMode: false,
|
|
31
170
|
},
|
|
32
171
|
|
|
@@ -34,7 +173,7 @@ ${r}
|
|
|
34
173
|
// and workflow config. Runtime strategies attach MCP per run (no global Gemini settings mutation).
|
|
35
174
|
browser: {
|
|
36
175
|
mcp: 'playwright',
|
|
37
|
-
headless: ${
|
|
176
|
+
headless: ${o.browserMode==="headless"},
|
|
38
177
|
},
|
|
39
178
|
|
|
40
179
|
// Chat memory backend adapter (dolt | mem0)
|
|
@@ -72,7 +211,7 @@ ${r}
|
|
|
72
211
|
specs: 'test-specs', // Where your .txt test specs are
|
|
73
212
|
generated: 'tests', // Where generated .spec.js files go
|
|
74
213
|
output: '.zibby/output', // Where workflow execution results are saved (default: .zibby/output)
|
|
75
|
-
workflows: '${
|
|
214
|
+
workflows: '${o.workflowsPath||"workflows"}', // Where custom workflows are stored (visible at project root; .zibby/ is runtime/scratch only)
|
|
76
215
|
// sessionPrefix: 'run', // Optional: prefix for session folders (e.g., run_1772788458045)
|
|
77
216
|
},
|
|
78
217
|
|
|
@@ -107,38 +246,264 @@ ${r}
|
|
|
107
246
|
},
|
|
108
247
|
|
|
109
248
|
// Cloud sync - auto-upload test results & videos (requires ZIBBY_API_KEY in .env)
|
|
110
|
-
cloudSync: ${
|
|
249
|
+
cloudSync: ${o.cloudSync||!1}
|
|
111
250
|
};
|
|
112
|
-
`}
|
|
251
|
+
`}function wn(o,e="dolt"){return`# Zibby Test Automation - Environment Variables
|
|
252
|
+
|
|
253
|
+
# AI Provider Keys
|
|
254
|
+
${{claude:"ANTHROPIC_API_KEY=sk-ant-your_key_here",cursor:`# Cursor Agent uses cursor-agent CLI \u2014 no API key needed
|
|
255
|
+
# Install: curl https://cursor.com/install -fsS | bash`,codex:"OPENAI_API_KEY=sk-your_key_here",gemini:"GEMINI_API_KEY=your_key_here"}[o.agent]||""}
|
|
256
|
+
|
|
257
|
+
# Zibby Cloud Sync (for uploading test results & videos)
|
|
258
|
+
# Get your API key from: https://zibby.dev/settings/tokens
|
|
259
|
+
# ZIBBY_API_KEY=zby_your_api_key_here
|
|
260
|
+
|
|
261
|
+
# Test Memory (Dolt DB) - Auto-compaction settings
|
|
262
|
+
# ZIBBY_MEMORY_MAX_RUNS=3000 # Max test runs to keep per spec
|
|
263
|
+
# ZIBBY_MEMORY_MAX_AGE=1095 # Max age in days for stale data (~3 years)
|
|
264
|
+
# ZIBBY_MEMORY_COMPACT_EVERY=1500 # Auto-compact every N runs (0 to disable)
|
|
265
|
+
|
|
266
|
+
# Chat memory backend
|
|
267
|
+
ZIBBY_MEMORY_BACKEND=${e}
|
|
268
|
+
`}function bn(o,e,t="dolt"){return`# Zibby Test Automation - Environment Variables
|
|
269
|
+
|
|
270
|
+
# AI Provider Keys
|
|
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"}[o.agent]||""}
|
|
272
|
+
|
|
273
|
+
# Zibby Cloud Sync
|
|
274
|
+
ZIBBY_API_KEY=${e}
|
|
275
|
+
|
|
276
|
+
# Test Memory (Dolt DB) - Auto-compaction settings
|
|
277
|
+
# ZIBBY_MEMORY_MAX_RUNS=3000 # Max test runs to keep per spec
|
|
278
|
+
# ZIBBY_MEMORY_MAX_AGE=1095 # Max age in days for stale data (~3 years)
|
|
279
|
+
# ZIBBY_MEMORY_COMPACT_EVERY=1500 # Auto-compact every N runs (0 to disable)
|
|
280
|
+
|
|
281
|
+
# Chat memory backend
|
|
282
|
+
ZIBBY_MEMORY_BACKEND=${t}
|
|
283
|
+
`}function kn(o,e,t={}){let n={"@zibby/cli":"latest","@zibby/core":fn("../../package.json").dependencies?.["@zibby/core"]||"latest"};return t.memoryBackend==="mem0"&&(n.mem0ai="^2.4.6"),JSON.stringify({name:o,version:"1.0.0",type:"module",private:!0,scripts:{"test:spec":"zibby run",test:"playwright test","test:headed":"playwright test --headed"},dependencies:n,devDependencies:{"@playwright/test":"^1.49.0",dotenv:"^17.2.3"}},null,2)}function xn(){return`# Dependencies
|
|
284
|
+
node_modules/
|
|
285
|
+
|
|
286
|
+
# Test artifacts
|
|
287
|
+
.zibby/output/
|
|
288
|
+
playwright-report/
|
|
289
|
+
tests/
|
|
290
|
+
*.webm
|
|
291
|
+
*.mp4
|
|
292
|
+
|
|
293
|
+
# Environment variables
|
|
294
|
+
.env
|
|
295
|
+
|
|
296
|
+
# OS
|
|
297
|
+
.DS_Store
|
|
298
|
+
Thumbs.db
|
|
299
|
+
|
|
300
|
+
# IDE
|
|
301
|
+
.vscode/
|
|
302
|
+
.idea/
|
|
303
|
+
|
|
304
|
+
# Zibby cache
|
|
305
|
+
.zibby/cache/
|
|
306
|
+
.zibby/tenancy.json
|
|
307
|
+
|
|
308
|
+
# Zibby memory (Dolt DB synced separately via dolt remote, not git)
|
|
309
|
+
.zibby/memory/
|
|
310
|
+
.zibby/memory-context.md
|
|
311
|
+
`}function vn(o="off",e=null){return`import { defineConfig} from '@playwright/test';
|
|
312
|
+
|
|
313
|
+
export default defineConfig({
|
|
314
|
+
testDir: './tests',
|
|
315
|
+
${e?` outputDir: '${e}',
|
|
316
|
+
`:` outputDir: 'test-results/playwright', // Keep Playwright artifacts separate from Zibby workflow output
|
|
317
|
+
`} timeout: 30000,
|
|
318
|
+
retries: 0,
|
|
319
|
+
workers: 1,
|
|
320
|
+
|
|
321
|
+
use: {
|
|
322
|
+
headless: process.env.PLAYWRIGHT_HEADLESS === '1' ? true : false,
|
|
323
|
+
viewport: { width: 1280, height: 720 },
|
|
324
|
+
screenshot: 'off',
|
|
325
|
+
video: 'off',
|
|
326
|
+
},
|
|
327
|
+
|
|
328
|
+
reporter: [
|
|
329
|
+
['html'],
|
|
330
|
+
['list']
|
|
331
|
+
],
|
|
332
|
+
});
|
|
333
|
+
`}function $n(){return`Test Specification: Example Domain Navigation
|
|
334
|
+
==============================================
|
|
335
|
+
|
|
336
|
+
Application: Example Domain
|
|
337
|
+
URL: https://example.com
|
|
338
|
+
Feature: Basic navigation and link verification
|
|
339
|
+
|
|
340
|
+
Test Objective:
|
|
341
|
+
---------------
|
|
342
|
+
Verify that the example.com website loads correctly, displays expected content,
|
|
343
|
+
and navigational links function as intended.
|
|
344
|
+
|
|
345
|
+
Test Steps:
|
|
346
|
+
-----------
|
|
347
|
+
1. Navigate to https://example.com
|
|
348
|
+
2. Verify the page title contains "Example Domain"
|
|
349
|
+
3. Verify the main heading is visible and contains "Example Domain"
|
|
350
|
+
4. Locate and verify the "More information..." link is present
|
|
351
|
+
5. Click the "More information..." link
|
|
352
|
+
6. Verify navigation to IANA domain information page
|
|
353
|
+
7. Verify the new page URL contains "iana.org"
|
|
354
|
+
8. Verify the page loaded successfully (no errors)
|
|
355
|
+
|
|
356
|
+
Expected Results:
|
|
357
|
+
-----------------
|
|
358
|
+
- Initial page loads within 3 seconds
|
|
359
|
+
- "Example Domain" heading is clearly visible
|
|
360
|
+
- "More information..." link is clickable and visible
|
|
361
|
+
- Navigation to IANA page succeeds
|
|
362
|
+
- No console errors or network failures
|
|
363
|
+
- Page title updates after navigation
|
|
364
|
+
|
|
365
|
+
Notes:
|
|
366
|
+
------
|
|
367
|
+
- Uses a stable, public domain (example.com) maintained by IANA
|
|
368
|
+
- No authentication required
|
|
369
|
+
- Suitable for CI/CD smoke testing
|
|
370
|
+
`}function An(){return`# Example command template
|
|
371
|
+
|
|
372
|
+
Use this command when the user asks for a concise testing task breakdown.
|
|
373
|
+
|
|
374
|
+
Required output format:
|
|
375
|
+
1. Goal
|
|
376
|
+
2. Risks
|
|
377
|
+
3. Steps
|
|
378
|
+
4. Expected result
|
|
379
|
+
|
|
380
|
+
Keep the response actionable and short.
|
|
381
|
+
`}function Cn(o,e){return`# ${o}
|
|
382
|
+
|
|
383
|
+
AI-powered test automation with Zibby.
|
|
384
|
+
|
|
385
|
+
## Setup
|
|
386
|
+
|
|
387
|
+
1. Install dependencies:
|
|
388
|
+
\`\`\`bash
|
|
389
|
+
npm install
|
|
390
|
+
\`\`\`
|
|
391
|
+
|
|
392
|
+
2. Configure environment:
|
|
393
|
+
\`\`\`bash
|
|
394
|
+
cp .env.example .env
|
|
395
|
+
# Edit .env and add your ${{claude:"ANTHROPIC_API_KEY",codex:"OPENAI_API_KEY",gemini:"GEMINI_API_KEY",cursor:"CURSOR_API_KEY (optional)"}[e.agent]}
|
|
396
|
+
\`\`\`
|
|
397
|
+
|
|
398
|
+
3. Run example test:
|
|
399
|
+
\`\`\`bash
|
|
400
|
+
npx zibby run test-specs/examples/example-domain.txt
|
|
401
|
+
\`\`\`
|
|
402
|
+
|
|
403
|
+
## Usage
|
|
404
|
+
|
|
405
|
+
### Run Test Specs
|
|
406
|
+
|
|
407
|
+
\`\`\`bash
|
|
408
|
+
# Run a test spec (executes + generates + verifies)
|
|
409
|
+
npx zibby run test-specs/auth/login.txt
|
|
410
|
+
|
|
411
|
+
# Run in headless mode
|
|
412
|
+
npx zibby run test-specs/auth/login.txt --headless
|
|
413
|
+
\`\`\`
|
|
414
|
+
|
|
415
|
+
### Write Test Specs
|
|
416
|
+
|
|
417
|
+
Create test specifications in \`test-specs/\`:
|
|
418
|
+
|
|
419
|
+
\`\`\`
|
|
420
|
+
test-specs/
|
|
421
|
+
auth/
|
|
422
|
+
login.txt
|
|
423
|
+
logout.txt
|
|
424
|
+
dashboard/
|
|
425
|
+
overview.txt
|
|
426
|
+
\`\`\`
|
|
427
|
+
|
|
428
|
+
### Run Generated Tests
|
|
429
|
+
|
|
430
|
+
\`\`\`bash
|
|
431
|
+
# Run all generated tests
|
|
432
|
+
npx playwright test
|
|
433
|
+
|
|
434
|
+
# Run specific test
|
|
435
|
+
npx playwright test tests/auth/login.spec.js
|
|
436
|
+
|
|
437
|
+
# Run with UI
|
|
438
|
+
npx playwright test --ui
|
|
439
|
+
\`\`\`
|
|
440
|
+
|
|
441
|
+
## Configuration
|
|
442
|
+
|
|
443
|
+
Edit \`.zibby.config.mjs\` to customize:
|
|
444
|
+
- Agent settings (model, temperature)
|
|
445
|
+
- Browser settings (headless, viewport)
|
|
446
|
+
- Cloud sync${e.cloudSync?" (enabled)":" (disabled)"}
|
|
447
|
+
- Self-healing behavior
|
|
448
|
+
|
|
449
|
+
## Project Structure
|
|
450
|
+
|
|
451
|
+
\`\`\`
|
|
452
|
+
${o}/
|
|
453
|
+
\u251C\u2500\u2500 .zibby/
|
|
454
|
+
\u2502 \u251C\u2500\u2500 graph.mjs # Workflow definition
|
|
455
|
+
\u2502 \u251C\u2500\u2500 nodes/ # Custom nodes
|
|
456
|
+
\u2502 \u2514\u2500\u2500 output/ # Workflow execution results (gitignored)
|
|
457
|
+
\u2502 \u2514\u2500\u2500 sessions/ # Session artifacts & recordings
|
|
458
|
+
\u251C\u2500\u2500 .zibby.config.mjs # Configuration
|
|
459
|
+
\u251C\u2500\u2500 .env.example # Environment template (cp to .env and configure)
|
|
460
|
+
\u251C\u2500\u2500 test-specs/ # Test specifications (committed)
|
|
461
|
+
\u2502 \u2514\u2500\u2500 examples/
|
|
462
|
+
\u2502 \u2514\u2500\u2500 example-domain.txt
|
|
463
|
+
\u2514\u2500\u2500 tests/ # Generated tests (gitignored)
|
|
464
|
+
\`\`\`
|
|
465
|
+
|
|
466
|
+
## Learn More
|
|
467
|
+
|
|
468
|
+
- Documentation: https://docs.zibby.dev
|
|
469
|
+
- Examples: https://github.com/zibby/examples
|
|
470
|
+
`}var gn,mn,fn,Ee=M(()=>{Le();gn=un(import.meta.url),mn=cn(gn),fn=dn(import.meta.url)});import{mkdir as Oe,writeFile as K,readFile as Dn}from"fs/promises";import{existsSync as re}from"fs";import{spawn as Un}from"child_process";import{join as S}from"path";import d from"chalk";import Lo from"ora";import{input as Yn}from"@inquirer/prompts";import{existsSync as Go}from"fs";import{join as Wo}from"path";import{pathToFileURL as Vo}from"url";async function Te(o){let e=Wo(o,".zibby.config.mjs");if(!Go(e))throw new Error(".zibby.config.mjs not found");try{let t=await import(Vo(e).href);return t.default||t}catch(t){throw new Error(`Failed to load .zibby.config.mjs: ${t.message}`,{cause:t})}}Ee();import{readFileSync as V,existsSync as N,mkdirSync as ze,writeFileSync as J,statSync as In,chmodSync as Sn}from"fs";import{join as z,dirname as pe}from"path";import{fileURLToPath as Pn}from"url";import T from"chalk";var ee=["claude","cursor","codex"],_n=pe(Pn(import.meta.url)),je=z(_n,"..","..","..","templates","zibby-workflow-claude"),En="<!-- BEGIN zibby-workflows",Bo="<!-- END zibby-workflows -->";function zn(o){let e=process.argv[1];if(!e||!N(e))return null;let t=z(o,".zibby","bin"),s=z(t,"zibby");ze(t,{recursive:!0});let n=`#!/bin/sh
|
|
113
471
|
# Auto-generated by 'zibby workflow generate'. Re-runs of generate update this path.
|
|
114
472
|
# Lets agents (Claude / Cursor / Codex) and CI scripts call zibby reliably even
|
|
115
473
|
# when the CLI isn't on PATH. Delete this file or .zibby/bin/ to disable.
|
|
116
|
-
exec node ${JSON.stringify(
|
|
117
|
-
|
|
118
|
-
`;if(!
|
|
474
|
+
exec node ${JSON.stringify(e)} "$@"
|
|
475
|
+
`;J(s,n);try{In(s)}catch{}try{Sn(s,493)}catch{}return s}function jn(){let o=z(je,"manifest.json");return JSON.parse(V(o,"utf8"))}function Mo(o){let e=o.match(/<!--\s*(?:BEGIN zibby-workflows\s+)?zibby-template-version:\s*(\d+)\s*-->/);return e?parseInt(e[1],10):null}function On(o,e,t){if(!N(o))return{write:!0,reason:"new"};if(t)return{write:!0,reason:"force"};let s=V(o,"utf8"),n=Mo(s),r=Mo(e);return n==null?{write:!1,reason:"user-edited (no version marker)"}:r==null?{write:!1,reason:"shipped file has no version (skipping for safety)"}:n>r?{write:!1,reason:`current version ${n} > shipped ${r}`}:{write:!0,reason:n===r?"same version, refresh":`upgrade ${n} \u2192 ${r}`}}function Rn(o,e){let t=`${e.trim()}
|
|
476
|
+
`;if(!N(o))return J(o,t),"created";let s=V(o,"utf8"),n=s.indexOf(En),r=s.indexOf(Bo);if(n!==-1&&r!==-1&&r>n){let l=s.slice(0,n),a=s.slice(r+Bo.length),g=l+t.trim()+a;return g===s?"unchanged":(J(o,g),"updated")}let u=s.endsWith(`
|
|
119
477
|
`)?`
|
|
120
478
|
`:`
|
|
121
479
|
|
|
122
|
-
`;return
|
|
123
|
-
templateVersion: ${
|
|
124
|
-
agents: ${JSON.stringify(
|
|
480
|
+
`;return J(o,s+u+t),"appended"}function Tn(o,e,t,s){let n=t.agents[o];if(!n)return[];let r=[],u=l=>z(je,l.split("/").map(a=>a.startsWith(".")?a.slice(1):a).join("/"));for(let l of n.files||[]){let a=u(l);if(!N(a))continue;let g=V(a,"utf8"),f=z(e,l),w=On(f,g,s);w.write?(ze(pe(f),{recursive:!0}),J(f,g),r.push({path:l,action:"write",detail:w.reason})):r.push({path:l,action:"skip",detail:w.reason})}for(let l of n.writeOnceFiles||[]){let a=u(l);if(!N(a))continue;let g=z(e,l);if(N(g)){r.push({path:l,action:"skip",detail:"write-once: already exists, leaving alone"});continue}ze(pe(g),{recursive:!0}),J(g,V(a,"utf8")),r.push({path:l,action:"write",detail:"write-once: created"})}if(n.rootBlock){let l=z(je,n.rootBlock.source),a=V(l,"utf8"),g=z(e,n.rootBlock.target),f=Rn(g,a);r.push({path:n.rootBlock.target,action:f})}return r}function Nn(o){let e=o;for(let t=0;t<6;t++){if(N(z(e,".git"))||N(z(e,".zibby.config.mjs"))||N(z(e,"package.json")))return e;let s=pe(e);if(s===e)break;e=s}return o}async function Bn(o){let e=z(o,".zibby.config.mjs");if(!N(e))return null;try{return((await import(`file://${e}?t=${Date.now()}`)).default||{}).agentHelpers||null}catch(t){return console.log(T.gray(` (couldn't parse .zibby.config.mjs agentHelpers section: ${t.message})`)),null}}function Mn(o,e){let t=z(o,".zibby.config.mjs");if(!N(t)){console.log(T.yellow(" \u26A0\uFE0F .zibby.config.mjs not found; agentHelpers state not persisted"));return}let s=V(t,"utf8"),n=` agentHelpers: {
|
|
481
|
+
templateVersion: ${e.templateVersion},
|
|
482
|
+
agents: ${JSON.stringify(e.agents)},
|
|
125
483
|
updatedAt: '${new Date().toISOString()}',
|
|
126
484
|
},
|
|
127
|
-
`,
|
|
128
|
-
${n}`);else{let
|
|
129
|
-
`:"")+n+s.slice(
|
|
130
|
-
* ${
|
|
485
|
+
`,r=/\s*agentHelpers\s*:\s*\{[^}]*\}\s*,?\n?/m,u;if(r.test(s))u=s.replace(r,`
|
|
486
|
+
${n}`);else{let l=s.lastIndexOf("}");if(l===-1)return;let a=s.slice(0,l),g=a.replace(/\s+$/,"").slice(-1);u=a+(g&&g!==","&&g!=="{"?`,
|
|
487
|
+
`:"")+n+s.slice(l)}J(t,u)}function Kn(o){if(o===!0)return["claude"];if(typeof o!="string")throw new Error(`agent-helpers flag value must be a string or true, got ${typeof o}`);let e=o.split(",").map(t=>t.trim()).filter(Boolean);if(e.length===0)return["claude"];if(e.length===1&&e[0]==="all")return[...ee];if(e.length===1&&e[0]==="none")return["none"];for(let t of e)if(!ee.includes(t))throw new Error(`unknown agent "${t}" \u2014 supported: ${ee.join(", ")}`);return Array.from(new Set(e))}function Ln({agentHelpersFlag:o,noAgentHelpers:e,existingConfig:t,legacyAgent:s}={}){if(e===!0)return{install:!1,reason:"explicit-no"};if(o!==void 0&&o!==!1){let n=Kn(o);return n.length===1&&n[0]==="none"?{install:!1,reason:"explicit-no"}:{install:!0,agents:n}}if(s){if(s==="none")return{install:!1,reason:"explicit-no"};if(s==="all")return{install:!0,agents:[...ee]};if(!ee.includes(s))throw new Error(`unknown agent "${s}" \u2014 supported: ${ee.join(", ")}`);return{install:!0,agents:[s]}}if(t&&Array.isArray(t.agents)&&t.agents.length>0){let n=t.agents.filter(r=>r!=="none");return n.length>0?{install:!0,agents:n,fromConfig:!0}:{install:!1,reason:"explicit-no"}}return{install:!1,reason:"no-config"}}async function Ko(o={}){let{forcedAgents:e,force:t=!1,silent:s=!1}=o,n=o.projectRoot||Nn(process.cwd()),r=jn(),u=await Bn(n),l;if(e&&e.length>0?e.length===1&&e[0]==="none"?l={install:!1,reason:"explicit-no"}:l={install:!0,agents:e}:l=Ln({agentHelpersFlag:o.agentHelpersFlag,noAgentHelpers:o.noAgentHelpers===!0,existingConfig:u,legacyAgent:o.legacyAgent}),!l.install)return l.reason==="explicit-no"?(o.noAgentHelpers===!0||o.legacyAgent==="none"||e&&e.length===1&&e[0],{action:"skipped-explicit-no"}):{action:"skipped-no-config"};let a=l.agents,g=zn(n),f=[];for(let w of a){if(!r.agents[w])continue;Tn(w,n,r,t).forEach(A=>f.push({...A,agent:w}))}if(Mn(n,{templateVersion:r.templateVersion,agents:a}),!s){l.fromConfig&&console.log(T.gray(` agent helpers: ${a.join(", ")} (from .zibby.config.mjs)`));let w=f.filter(b=>["write","created","updated","appended"].includes(b.action)),m=f.filter(b=>b.action==="skip"),A=f.filter(b=>b.action==="unchanged");if(w.length>0){console.log(T.green(` \u2713 Wrote ${w.length} agent helper file(s):`));for(let b of w)console.log(T.gray(` ${b.path} (${b.detail||b.action})`))}if(m.length>0){console.log(T.yellow(` \u26A0\uFE0F Skipped ${m.length} (use --force-agents to overwrite):`));for(let b of m)console.log(T.gray(` ${b.path} \u2014 ${b.detail}`))}w.length===0&&m.length===0&&A.length>0&&console.log(T.gray(` Agent helpers up to date (template v${r.templateVersion}).`)),l.fromConfig||console.log(T.gray(` agentHelpers: { agents: [${a.map(b=>`"${b}"`).join(", ")}] } saved to .zibby.config.mjs`)),g&&console.log(T.gray(` CLI shim: ${g} (agents fall back to ./.zibby/bin/zibby if zibby isn't on PATH)`)),a.includes("claude")&&console.log(T.gray(" \u2192 Run `claude` and try /zibby-add-node"))}return{action:l.fromConfig?"installed-from-config":"installed",agents:a}}function Fn(o){return new Promise(e=>{let t=Un("npm",["install","--no-audit","--no-fund"],{cwd:o,stdio:"pipe",shell:!1}),s="";t.stderr.on("data",n=>{s+=n.toString()}),t.on("error",()=>e({ok:!1,stderr:"npm not found on PATH"})),t.on("close",n=>e({ok:n===0,stderr:s}))})}var Hn=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/,Do=["stellar","quantum","cosmic","nova","nebula","solar","lunar","atomic","plasma","fusion","pulse","flux","spark","blaze","ember","radiant","luminous","electric","magnetic","kinetic","neon","cyber","pixel","matrix","vector","synth","neural","prism","zenith","phoenix","catalyst","nexus","echo","wave","crystal","jade","ruby","emerald","onyx","amber","silver","turbo","lightning","thunder","storm","arcane","mystic","ethereal","celestial","swift","crimson","iron","cobalt"],Uo=["flow","runner","pipeline","stream","circuit","engine","beacon","forge","relay","shuttle","conduit","gateway","sentinel","scout","pilot","voyager","ranger","dispatch","signal","pulse","agent","daemon","spark","orbit","vector","nexus","matrix","grid","mesh","bridge","link","node","craft","bolt","ray","arc","wave","hook","probe","shard"];function Zn(){let o=Do[Math.floor(Math.random()*Do.length)],e=Uo[Math.floor(Math.random()*Uo.length)];return`${o}-${e}`}function Gn(o){return`${o.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}Workflow`}function Ho(o){return`${o.split("-").map((t,s)=>s===0?t:t.charAt(0).toUpperCase()+t.slice(1)).join("")}StateSchema`}function Wn(o,e){let t=Ho(e);return`/**
|
|
488
|
+
* ${o}
|
|
131
489
|
*
|
|
132
490
|
* buildGraph() \u2014 define nodes, edges, conditional routing
|
|
133
491
|
* onComplete(result) \u2014 post-processing after the graph finishes
|
|
492
|
+
*
|
|
493
|
+
* Inputs (passed via -p / --input / --input-file on
|
|
494
|
+
* \`zibby workflow run\` or \`zibby workflow trigger\`) land at the
|
|
495
|
+
* top of state. Declare them in state.js, read them in nodes via
|
|
496
|
+
* \`state.<key>\` \u2014 see nodes/example.mjs for a demo.
|
|
134
497
|
*/
|
|
135
498
|
|
|
136
499
|
import { WorkflowAgent, WorkflowGraph } from '@zibby/core';
|
|
137
500
|
import { exampleNode } from './nodes/index.mjs';
|
|
501
|
+
import { ${t} } from './state.js';
|
|
138
502
|
|
|
139
|
-
export class ${
|
|
503
|
+
export class ${o} extends WorkflowAgent {
|
|
140
504
|
buildGraph() {
|
|
141
505
|
const graph = new WorkflowGraph();
|
|
506
|
+
graph.setStateSchema(${t});
|
|
142
507
|
|
|
143
508
|
graph.addNode('example', exampleNode);
|
|
144
509
|
|
|
@@ -149,11 +514,44 @@ export class ${e} extends WorkflowAgent {
|
|
|
149
514
|
}
|
|
150
515
|
|
|
151
516
|
async onComplete(result) {
|
|
152
|
-
console.log(\`[${
|
|
517
|
+
console.log(\`[${e}] workflow complete \u2014 success: \${result.success !== false}\`);
|
|
153
518
|
}
|
|
154
519
|
}
|
|
155
|
-
`}function
|
|
156
|
-
|
|
520
|
+
`}function Vn(o){return`/**
|
|
521
|
+
* Input state schema for this workflow.
|
|
522
|
+
*
|
|
523
|
+
* Declares the user-input fields callers can pass via:
|
|
524
|
+
* zibby workflow run <slug> -p <key>=<value>
|
|
525
|
+
* zibby workflow run <slug> --input '{"<key>":"<value>"}'
|
|
526
|
+
* zibby workflow run <slug> --input-file inputs.json
|
|
527
|
+
*
|
|
528
|
+
* The runner spreads those at the top of state, so a node's
|
|
529
|
+
* \`state.<key>\` reads whatever the caller passed. The schema
|
|
530
|
+
* here is enforced at run time by graph.setStateSchema(...) in
|
|
531
|
+
* graph.mjs \u2014 invalid inputs fail fast with a Zod error.
|
|
532
|
+
*
|
|
533
|
+
* Add fields below. Required = bare type (e.g. z.string()).
|
|
534
|
+
* Optional = chain .optional() (e.g. z.number().optional()).
|
|
535
|
+
*
|
|
536
|
+
* Naming: export name MUST be picked up by the cheatsheet's
|
|
537
|
+
* "first export with .shape" detection \u2014 any zod object schema
|
|
538
|
+
* works, but stick with the \`<slug>StateSchema\` convention so
|
|
539
|
+
* future tooling can locate it predictably.
|
|
540
|
+
*/
|
|
541
|
+
|
|
542
|
+
import { z } from 'zod';
|
|
543
|
+
|
|
544
|
+
export const ${Ho(o)} = z.object({
|
|
545
|
+
// Add user-input fields here. Examples:
|
|
546
|
+
//
|
|
547
|
+
// url: z.string().url().describe('Page to test'),
|
|
548
|
+
// count: z.number().int().positive().default(1).describe('How many times to retry'),
|
|
549
|
+
// tags: z.array(z.string()).optional().describe('Optional tag filter'),
|
|
550
|
+
//
|
|
551
|
+
// Then read them in any node via state.url / state.count / state.tags.
|
|
552
|
+
});
|
|
553
|
+
`}function Jn(){return`export { exampleNode } from './example.mjs';
|
|
554
|
+
`}function qn(){return`import { z } from '@zibby/core';
|
|
157
555
|
|
|
158
556
|
const ExampleOutputSchema = z.object({
|
|
159
557
|
summary: z.string().describe('A short summary of the result'),
|
|
@@ -163,6 +561,14 @@ const ExampleOutputSchema = z.object({
|
|
|
163
561
|
export const exampleNode = {
|
|
164
562
|
name: 'example',
|
|
165
563
|
|
|
564
|
+
// Reading user input:
|
|
565
|
+
// The CLI flags -p key=value / --input '{"key":"value"}' /
|
|
566
|
+
// --input-file path.json all land at the TOP of state \u2014 so
|
|
567
|
+
// \`zibby workflow run my-pip -p url=https://example.com\` makes
|
|
568
|
+
// \`state.url\` available below. \`state.input\` also holds the same
|
|
569
|
+
// object as a nested copy if you prefer the explicit form.
|
|
570
|
+
// See ../state.js for the schema declaring which fields are
|
|
571
|
+
// required vs optional (validated at run time).
|
|
166
572
|
prompt: (state) => \`You are a helpful workflow node.
|
|
167
573
|
|
|
168
574
|
Input:
|
|
@@ -172,22 +578,29 @@ Analyze the input and return a summary with a status.\`,
|
|
|
172
578
|
|
|
173
579
|
outputSchema: ExampleOutputSchema,
|
|
174
580
|
};
|
|
175
|
-
`}function
|
|
176
|
-
`}function
|
|
177
|
-
`}
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
`));let
|
|
183
|
-
|
|
184
|
-
`)),
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
${
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
`)))}
|
|
192
|
-
${f.
|
|
193
|
-
`)),
|
|
581
|
+
`}function Yo(o,e){return`${JSON.stringify({name:o,description:`${e} workflow`,entryClass:e,triggers:{api:!0}},null,2)}
|
|
582
|
+
`}var Xn=new Set(["cwd","sessionPath","outputPath","context","input"]);async function Qn(o){try{let e=await Dn(S(o,"graph.mjs"),"utf-8"),t=new Set,s=/addNode\(\s*['"`]([A-Za-z_][\w-]*)['"`]/g,n;for(;(n=s.exec(e))!==null;)t.add(n[1]);return t}catch{return new Set}}async function er(o){try{let e=await import(`@zibby/core/templates/${o}/state.js`);for(let t of Object.values(e))if(!(!t||typeof t!="object"))try{let s=t.shape;if(s&&typeof s=="object"&&Object.keys(s).length>0)return{schema:t,shape:s}}catch{}return null}catch{return null}}function or(o,e){try{let t=[],s=[];for(let[n,r]of Object.entries(o)){if(Xn.has(n)||e.has(n))continue;let u=!1;try{u=r?.isOptional?.()===!0}catch{}u?s.push(n):t.push(n)}return{required:t,optional:s}}catch{return null}}async function tr(o,e,t){let s=null;if(e)try{let n=await er(e);if(n){let r=await Qn(t);s=or(n.shape,r)}}catch{s=null}if(console.log(d.white(" Pass inputs:")),s&&s.required.length+s.optional.length>0){let{required:n,optional:r}=s,u=n[0]||r[0],l=`<${u}>`;console.log(d.gray(` ${d.white(`zibby workflow run ${o} -p ${u}="${l}"`)}`));let a=[...n.slice(0,3),...r.slice(0,1)],g={};for(let m of a)m==="model"?g[m]="opus-4.6":g[m]=`<${m}>`;console.log(d.gray(` ${d.white(`zibby workflow run ${o} --input '${JSON.stringify(g)}'`)}`)),console.log(d.gray(` ${d.white(`zibby workflow run ${o} --input-file inputs.json`)}`)),console.log(d.gray(` Same flags work on ${d.white("zibby workflow trigger <uuid>")} for cloud runs.`));let f=a,w=f.length>0?f.map(m=>d.white(`state.${m}`)).join(", ")+", etc":d.white("state.<field>");console.log(d.gray(` Inside any node, read ${w} \u2014 top-level.`)),console.log(d.gray(` See workflows/${o}/state.js for the full input schema.
|
|
583
|
+
`))}else console.log(d.gray(` ${d.white(`zibby workflow run ${o} -p name=alice -p count=5`)}`)),console.log(d.gray(` ${d.white(`zibby workflow run ${o} --input '{"url":"https://example.com"}'`)}`)),console.log(d.gray(` ${d.white(`zibby workflow run ${o} --input-file inputs.json`)}`)),console.log(d.gray(` Same flags work on ${d.white("zibby workflow trigger <uuid>")} for cloud runs.`)),console.log(d.gray(` Inside your node, read ${d.white("state.name")}, ${d.white("state.count")}, etc \u2014 top-level.
|
|
584
|
+
`))}function Fo(o){let e={"@zibby/core":"^0.3.0",...o};return`${JSON.stringify({type:"module",dependencies:e},null,2)}
|
|
585
|
+
`}async function rs(o,e={}){if(!e.skipInitCheck){let{homedir:m}=await import("os"),A=process.env.ZIBBY_CONFIG_DIR?S(process.env.ZIBBY_CONFIG_DIR,"config.json"):S(m(),".zibby","config.json");if(!re(A)){console.log(d.gray(`
|
|
586
|
+
Looks like first run on this machine \u2014 let's do a quick setup so the
|
|
587
|
+
scaffolded workflow can actually run. (Skip with --skip-init-check.)
|
|
588
|
+
`));let{initCommand:b}=await Promise.resolve().then(()=>(Ee(),No));try{await b(void 0,{...e,template:void 0})}catch(v){console.log(d.red(`
|
|
589
|
+
Init failed: ${v.message}
|
|
590
|
+
`)),console.log(d.gray(" Run `zibby init` manually, then re-run this command.\n")),process.exit(1)}}}let t;o?t=o.toLowerCase():(t=Zn(),console.log(d.gray(`
|
|
591
|
+
No name provided \u2014 generated: ${d.white(t)}`))),Hn.test(t)||(console.log(d.red(`
|
|
592
|
+
Invalid workflow name: "${o}"`)),console.log(d.gray(" Must be lowercase, start with a letter, use only a-z, 0-9, hyphens")),console.log(d.gray(" Length: 2\u201364 characters")),console.log(d.gray(` Example: ticket-triage, pr-review, deploy-checker
|
|
593
|
+
`)),process.exit(1));let s=process.cwd(),n=S(s,".zibby.config.mjs"),r=re(n),u="workflows";if(r)try{let m=await Te(s);m?.paths?.workflows&&(u=m.paths.workflows)}catch(m){console.log(d.yellow(` \u26A0\uFE0F Could not load .zibby.config.mjs: ${m.message}`)),console.log(d.gray(` Using default path: ${u}`))}else if(process.stdin.isTTY){console.log(d.gray(`
|
|
594
|
+
Common picks: ${d.white("workflows")} (visible at project root, default) \xB7 ${d.white(".zibby/workflows")} (hidden under runtime dir)
|
|
595
|
+
`));let A=(await Yn({message:`Where to save workflows? ${d.gray("[Enter for workflows]")}`})).trim();u=A===""?"workflows":A}else console.log(d.gray(` Using default workflows path: ${u} (run interactively to customize)`));let l=S(s,u,t),a=S(l,"nodes");re(l)&&(console.log(d.red(`
|
|
596
|
+
Workflow already exists: ${u}/${t}/`)),console.log(d.gray(` Choose a different name or delete the existing folder.
|
|
597
|
+
`)),process.exit(1));let g=Gn(t),f=e.template&&String(e.template).trim(),w=Lo(f?` Scaffolding workflow "${t}" from template ${d.cyan(f)}...`:` Scaffolding workflow "${t}"...`).start();try{if(await Oe(S(s,u),{recursive:!0}),f){let{writeTemplateFilesToDir:p}=await Promise.resolve().then(()=>(fe(),me));await Oe(l,{recursive:!0});let{template:h}=await p(l,f);re(S(l,"workflow.json"))||await K(S(l,"workflow.json"),Yo(t,g)),re(S(l,"package.json"))||await K(S(l,"package.json"),Fo(h?.deps||{}))}else await Oe(a,{recursive:!0}),await Promise.all([K(S(l,"graph.mjs"),Wn(g,t)),K(S(l,"state.js"),Vn(t)),K(S(a,"index.mjs"),Jn()),K(S(a,"example.mjs"),qn()),K(S(l,"workflow.json"),Yo(t,g)),K(S(l,"package.json"),Fo({zod:"^3.23.0"}))]);let m=!1;if(!r){let p=de({agent:"claude",browserMode:"headless",workflowsPath:u},{},{memoryBackend:"dolt"});await K(n,p),m=!0}w.succeed(f?` Scaffolded ${d.bold(t)} from template ${d.cyan(f)}`:` Scaffolded ${d.bold(t)}`),console.log(d.green(`
|
|
598
|
+
Created:`)),console.log(d.white(` ${u}/${t}/`)),f?(console.log(d.gray(` graph.mjs (from template ${f})`)),console.log(d.gray(` nodes/ (from template ${f})`)),console.log(d.gray(" workflow.json manifest")),console.log(d.gray(" package.json dependencies (@zibby/core)"))):(console.log(d.gray(` graph.mjs ${g} (entry)`)),console.log(d.gray(" state.js input schema (Zod) \u2014 declare your fields here")),console.log(d.gray(" nodes/index.mjs barrel export")),console.log(d.gray(" nodes/example.mjs starter node (prompt + schema)")),console.log(d.gray(" workflow.json manifest")),console.log(d.gray(" package.json dependencies (@zibby/core, zod)"))),m&&console.log(d.white(" .zibby.config.mjs project config (agent: claude \u2014 edit to switch)"));let A=!1;if(e.skipInstall)console.log(d.gray(` Skipped npm install (--skip-install). Run manually: cd ${u}/${t} && npm install`));else{let p=Lo({text:` Installing dependencies in ${u}/${t}/...`,prefixText:""}).start(),h=await Fn(l);h.ok?(p.succeed(` Installed dependencies in ${u}/${t}/`),A=!0):(p.warn(` Could not install dependencies (${h.stderr.trim().split(`
|
|
599
|
+
`)[0]||"unknown error"})`),console.log(d.gray(` Run manually: cd ${u}/${t} && npm install`)))}let b={action:"skipped-no-config"};try{b=await Ko({projectRoot:s,agentHelpersFlag:e.agentHelpers,noAgentHelpers:e.agentHelpers===!1,legacyAgent:e.agent,force:e.forceClaude===!0||e.forceAgents===!0})||b}catch(p){/^unknown agent /.test(p.message)&&(console.log(d.red(`
|
|
600
|
+
${p.message}
|
|
601
|
+
`)),process.exit(1)),console.log(d.yellow(` \u26A0\uFE0F Agent helpers setup failed: ${p.message}`)),console.log(d.gray(" Run `zibby agents add` later to retry."))}console.log(d.white(`
|
|
602
|
+
Next steps:`));let v=1;!A&&e.skipInstall!==!0&&console.log(d.cyan(` ${v++}. Install deps: cd ${u}/${t} && npm install`)),console.log(d.cyan(` ${v++}. Edit nodes in ${u}/${t}/nodes/`)),console.log(d.cyan(` ${v++}. Wire them in graph.mjs`)),console.log(d.cyan(` ${v++}. Run locally: zibby workflow run ${t}`)),console.log(d.cyan(` ${v++}. Deploy to cloud: zibby workflow deploy ${t}
|
|
603
|
+
`)),await tr(t,f,l),b.action==="skipped-no-config"&&(console.log(d.gray(" Tip: Using Claude Code or Cursor? Set up slash commands + agent context:")),console.log(d.gray(" zibby workflow new <name> --agent-helpers claude")),console.log(d.gray(` (commits agentHelpers to .zibby.config.mjs \u2014 auto-applies to future workflows)
|
|
604
|
+
`)))}catch(m){w.fail(" Scaffold failed"),console.log(d.red(`
|
|
605
|
+
${m.message}
|
|
606
|
+
`)),process.exit(1)}}export{rs as generateWorkflowCommand};
|