@zibby/cli 0.6.1 → 0.7.1
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 +19 -18
- package/dist/commands/app-auth.js +17 -0
- package/dist/commands/app.js +1 -1
- package/dist/commands/init.js +126 -118
- package/dist/commands/workflows/generate.js +143 -135
- package/dist/package.json +3 -2
- package/dist/templates/zibby-workflow-claude/agents-md-block.md +23 -23
- package/dist/templates/zibby-workflow-claude/claude/agents/zibby-workflow-builder.md +24 -24
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-add-node.md +18 -18
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-debug.md +10 -10
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-delete.md +7 -7
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-deploy.md +26 -26
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-list.md +8 -8
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-static-ip.md +13 -13
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-tail.md +13 -13
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-trigger.md +16 -16
- package/dist/templates/zibby-workflow-claude/cursor/rules/zibby-workflows.mdc +19 -19
- package/dist/templates/zibby-workflow-claude/manifest.json +1 -1
- package/package.json +3 -2
- package/templates/zibby-workflow-claude/agents-md-block.md +23 -23
- package/templates/zibby-workflow-claude/claude/agents/zibby-workflow-builder.md +24 -24
- package/templates/zibby-workflow-claude/claude/commands/zibby-add-node.md +18 -18
- package/templates/zibby-workflow-claude/claude/commands/zibby-debug.md +10 -10
- package/templates/zibby-workflow-claude/claude/commands/zibby-delete.md +7 -7
- package/templates/zibby-workflow-claude/claude/commands/zibby-deploy.md +26 -26
- package/templates/zibby-workflow-claude/claude/commands/zibby-list.md +8 -8
- package/templates/zibby-workflow-claude/claude/commands/zibby-static-ip.md +13 -13
- package/templates/zibby-workflow-claude/claude/commands/zibby-tail.md +13 -13
- package/templates/zibby-workflow-claude/claude/commands/zibby-trigger.md +16 -16
- package/templates/zibby-workflow-claude/cursor/rules/zibby-workflows.mdc +19 -19
- package/templates/zibby-workflow-claude/manifest.json +1 -1
|
@@ -1,176 +1,176 @@
|
|
|
1
|
-
var
|
|
2
|
-
`,"utf-8")}var
|
|
1
|
+
var mo=Object.defineProperty;var W=(t,e)=>()=>(t&&(e=t(t=0)),e);var G=(t,e)=>{for(var o in e)mo(t,o,{get:e[o],enumerable:!0})};import{existsSync as ho,readFileSync as wo,writeFileSync as bo,mkdirSync as ko}from"fs";import{join as Je}from"path";import{homedir as Xe}from"os";function Qe(){return Je(Xe(),".zibby","config.json")}function fe(){try{let t=Qe();return ho(t)?JSON.parse(wo(t,"utf-8")):{}}catch{return{}}}function et(t,e){let o=e?ge[e]:null;o&&Ce(o.envVar,t)}function Ce(t,e){if(!t||typeof t!="string"||!e||typeof e!="string")return;let o=Je(Xe(),".zibby");ko(o,{recursive:!0});let r=Qe(),n=fe();(!n.agentKeys||typeof n.agentKeys!="object")&&(n.agentKeys={}),n.agentKeys[t]=String(e).trim(),delete n.agentApiKey,bo(r,`${JSON.stringify(n,null,2)}
|
|
2
|
+
`,"utf-8")}var ge,tt=W(()=>{ge={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 Ae={};G(Ae,{resolveTemplate:()=>rt,templateAddCommand:()=>No,templateListCommand:()=>To,writeTemplateFiles:()=>it,writeTemplateFilesToDir:()=>st});import{mkdir as ot,writeFile as $o,readFile as vo}from"fs/promises";import{existsSync as ye,readdirSync as xo,statSync as Co,readFileSync as Ao}from"fs";import{join as te,dirname as So}from"path";import{fileURLToPath as Io}from"url";import{spawn as _o}from"child_process";import{createRequire as Po}from"module";import P from"chalk";import Eo from"ora";function Oo(t){return Ro.some(e=>e.test(t))}async function nt(t,e,o=null){let r=[];ye(e)||await ot(e,{recursive:!0});for(let n of xo(t)){if(Oo(n))continue;let s=te(t,n),l=te(e,n),d=Co(s);if(d.isDirectory()){let u=await nt(s,l,o);for(let i of u)r.push(`${n}/${i}`)}else if(d.isFile()){let u=await vo(s,"utf-8");o&&(u=o(n,u)),await $o(l,u),r.push(n)}}return r}async function rt(t){if(!t||typeof t!="string")throw new Error("Template name is required");if(/^(git\+|https?:)/.test(t))throw new Error(`Git/URL templates are not yet supported (got "${t}"). For now use a built-in template \u2014 see \`zibby template list\`.`);if(t.startsWith("@")||t.includes("/")||t.startsWith("zibby-template-"))throw new Error(`npm-package templates are not yet supported (got "${t}"). For now use a built-in template \u2014 see \`zibby template list\`.`);let{TemplateFactory:e}=await import("@zibby/workflow-templates");return e.getTemplateFiles(t)}async function st(t,e,o={}){let r=o.enableMemory!==!1,{template:n}=await rt(e);ye(t)||await ot(t,{recursive:!0});let s=await nt(n.path,t,(l,d)=>!r&&l==="execute-live.mjs"?d.replace("skills: [SKILLS.BROWSER, SKILLS.MEMORY],","skills: [SKILLS.BROWSER],"):d);return{template:n,copied:s}}async function it(t,e,o={}){return st(te(t,".zibby"),e,o)}async function To(){let{TemplateFactory:t}=await import("@zibby/workflow-templates"),e=t.listTemplates();console.log(""),console.log(P.bold.cyan(" Available templates")),console.log("");for(let o of e){if(console.log(` ${P.cyan(o.name)}`),console.log(` ${P.white(o.displayName)}`),o.description&&console.log(` ${P.gray(o.description)}`),o.features&&o.features.length)for(let n of o.features)console.log(P.gray(` \u2022 ${n}`));let r=o.defaultSlug||"your-workflow-name";console.log(""),console.log(` ${P.gray("Scaffold:")} ${P.cyan(`zibby workflow new ${r} -t ${o.name}`)}`),console.log("")}}async function No(t,e={}){t||(console.log(P.red(`
|
|
3
3
|
Missing template name.
|
|
4
|
-
`)),console.log(
|
|
5
|
-
`)),process.exit(1));let o=e.cwd||process.cwd(),
|
|
4
|
+
`)),console.log(P.gray(" Usage: zibby template add <name>")),console.log(P.gray(` See available templates: zibby template list
|
|
5
|
+
`)),process.exit(1));let o=e.cwd||process.cwd(),r=te(o,".zibby");ye(r)||(console.log(P.yellow(`
|
|
6
6
|
No .zibby/ directory in ${o}.
|
|
7
|
-
`)),console.log(
|
|
8
|
-
${
|
|
9
|
-
`)),console.log(
|
|
10
|
-
`)),process.exit(1)}console.log(""),console.log(
|
|
11
|
-
`);return
|
|
7
|
+
`)),console.log(P.gray(" Run `zibby init` first to bootstrap the project.\n")),process.exit(1));let n;try{n=await it(o,t,{enableMemory:e.enableMemory!==!1})}catch(s){console.log(P.red(`
|
|
8
|
+
${s.message}
|
|
9
|
+
`)),console.log(P.gray(` See available templates: zibby template list
|
|
10
|
+
`)),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 ${r}/`));for(let s of n.copied)console.log(P.gray(` \u2022 ${s}`));if(!e.skipInstall&&ye(te(o,"package.json"))){let s=!1;try{Po(te(o,"package.json")).resolve("@zibby/core/package.json"),s=!0}catch{}if(!s){let d=`@zibby/core@${JSON.parse(Ao(te(jo,"../../package.json"),"utf-8")).dependencies?.["@zibby/core"]||"latest"}`,u=Eo(` Installing ${d} (needed by .zibby/graph.mjs)...`).start();await new Promise(b=>{_o("npm",["install","--save-dev",d],{cwd:o,stdio:"pipe"}).on("close",h=>b(h??1))})===0?u.succeed(` Installed ${d}`):(u.warn(` Could not auto-install ${d}`),console.log(P.gray(` Run manually: npm install --save-dev ${d}`)))}}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 zo,jo,Ro,Se=W(()=>{zo=Io(import.meta.url),jo=So(zo),Ro=[/^__tests__$/,/^__mocks__$/,/^node_modules$/,/\.test\.[mc]?js$/,/\.spec\.[mc]?js$/,/^\.DS_Store$/,/^chat\.mjs$/]});var at={};G(at,{BLOCK_REGEX:()=>Ie,upsertManagedBlock:()=>Mo});function Mo(t,e){if(typeof e!="string")throw new TypeError("blockContent must be a string");if(t==null)return{content:e,action:"created"};if(Ie.test(t)){let r=t.replace(Ie,e.trimEnd()+`
|
|
11
|
+
`);return r===t?{content:t,action:"skipped"}:{content:r,action:"updated"}}let o=t.endsWith(`
|
|
12
12
|
`)?`
|
|
13
13
|
`:`
|
|
14
14
|
|
|
15
|
-
`;return{content:t+o+e,action:"updated"}}var
|
|
15
|
+
`;return{content:t+o+e,action:"updated"}}var Ie,lt=W(()=>{Ie=/<!--\s*BEGIN ZIBBY[^>]*-->[\s\S]*?<!--\s*END ZIBBY[^>]*-->\s*/i});var dt={};G(dt,{applyMemorySyncConfig:()=>Ko,validateMemorySyncConfig:()=>ut});function ut(t){if(!t||typeof t!="object")return{ok:!0,kind:"noop"};let e=t.remote;return Bo.includes(e)?{ok:!0,kind:"noop"}:typeof e!="string"?{ok:!1,error:`memorySync.remote must be null or a string, got ${typeof e}`}:e===Lo?{ok:!0,kind:"hosted"}:ct.some(o=>e.startsWith(o))?{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: ${ct.join(" / ")}.`}}async function Ko({cwd:t,projectId:e,block:o,memoryApi:r,hostedSetup:n,getSessionToken:s,logger:l=console}){let d=ut(o);if(!d.ok)return l.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 r?.memoryRemoteAdd?r.memoryRemoteAdd(t,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 s=="function"&&!s())return{action:"pending-login",reason:'memorySync.remote = "hosted" but the user is not logged in. Run `zibby login` then `zibby memory remote use --hosted`.'};if(typeof n!="function")return{action:"error",reason:"hostedSetup function not provided"};try{return await n({cwd:t,projectId:e}),{action:"hosted"}}catch(u){return{action:"error",reason:`hosted setup failed: ${u.message}`}}}return{action:"error",reason:`unhandled kind: ${d.kind}`}}var Bo,Lo,ct,pt=W(()=>{Bo=[null,void 0,"","none","off",!1],Lo="hosted",ct=["aws://","gs://","https://","http://","file://"]});var Pe={};G(Pe,{clearSession:()=>vt,default:()=>Wo,getMem0ProxyUrl:()=>At,getProjects:()=>It,getProxyUrl:()=>xt,getSessionToken:()=>_e,getUserInfo:()=>bt,isLoggedIn:()=>$t,loadConfig:()=>B,saveConfig:()=>q,saveMem0ProxyUrl:()=>St,saveProjects:()=>_t,saveProxyUrl:()=>Ct,saveSessionToken:()=>wt,saveUserInfo:()=>kt});import{existsSync as mt,mkdirSync as Do,readFileSync as Uo,writeFileSync as Yo}from"fs";import{homedir as gt}from"os";import{join as he}from"path";function ft(){return process.env.ZIBBY_CONFIG_DIR||he(gt(),".zibby")}function yt(){return he(ft(),"config.json")}function Ho(){let t=ft();mt(t)||Do(t,{recursive:!0})}function B(){try{let t=yt();if(mt(t)){let e=Uo(t,"utf-8");return JSON.parse(e)}}catch{}return{}}function q(t){Ho(),Yo(yt(),JSON.stringify(t,null,2))}function _e(){return B().sessionToken||null}function wt(t){let e=B();e.sessionToken=t,q(e)}function bt(){return B().user||null}function kt(t){let e=B();e.user=t,q(e)}function $t(){return _e()!==null}function vt(){let t=B();delete t.sessionToken,delete t.user,delete t.mem0ProxyUrl,q(t)}function xt(){return B().proxyUrl||null}function Ct(t){let e=B();e.proxyUrl=t,q(e)}function At(){return B().mem0ProxyUrl||null}function St(t){let e=B();e.mem0ProxyUrl=t,q(e)}function It(){return B().projects||[]}function _t(t){let e=B();e.projects=t,q(e)}var ht,Fo,Wo,Ee=W(()=>{ht=he(gt(),".zibby"),Fo=he(ht,"config.json");Wo={loadConfig:B,saveConfig:q,getSessionToken:_e,saveSessionToken:wt,getUserInfo:bt,saveUserInfo:kt,isLoggedIn:$t,clearSession:vt,getProxyUrl:xt,saveProxyUrl:Ct,getMem0ProxyUrl:At,saveMem0ProxyUrl:St,getProjects:It,saveProjects:_t,CONFIG_DIR:ht,CONFIG_FILE:Fo}});var Pt={};G(Pt,{ENVIRONMENTS:()=>O,getAccountApiUrl:()=>Go,getApiUrl:()=>Zo,getCurrentEnvironment:()=>Vo,getFrontendUrl:()=>qo});function Zo(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";O[e]?t=O[e].apiUrl:t=O.prod.apiUrl}try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),O.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),O.prod.apiUrl}}function Go(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let t=process.env.ZIBBY_ENV||"prod";return(O[t]||O.prod).accountApiUrl}function Vo(){let t=process.env.ZIBBY_ENV||"prod";return O[t]||O.prod}function qo(){let t;if(process.env.ZIBBY_FRONTEND_URL)t=process.env.ZIBBY_FRONTEND_URL;else{let e=process.env.ZIBBY_ENV||"prod";O[e]?t=O[e].frontendUrl:t=O.prod.frontendUrl}try{let e=new URL(t);if(e.protocol!=="http:"&&e.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${e.protocol} (only http/https allowed)`),O.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let r=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],n=e.hostname;if(!r.some(l=>n===l||n.endsWith(`.${l}`))&&!n.includes("localhost")&&n!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${n}`),"https://studio.zibby.dev"}return t}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${t}`),O.local.frontendUrl}}var O,Et=W(()=>{O={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}}});var Ne={};G(Ne,{__testing:()=>rn,buildDoltEnv:()=>nn,clearConfig:()=>on,getActiveCredentials:()=>Mt,isHosted:()=>en,readConfig:()=>Oe,refreshCredentials:()=>Nt,writeConfig:()=>tn});import{readFileSync as zt,writeFileSync as je,existsSync as Re,mkdirSync as jt,chmodSync as Jo}from"fs";import{join as ze}from"path";function ae(t){let e=ze(t,".zibby");return{dir:e,config:ze(e,Xo),creds:ze(e,Qo)}}function Oe(t){let{config:e}=ae(t);if(!Re(e))return null;try{let o=JSON.parse(zt(e,"utf-8"));return o.mode!=="hosted"?null:o}catch{return null}}function en(t){return!!Oe(t)}function tn(t,e){let{dir:o,config:r}=ae(t);jt(o,{recursive:!0}),je(r,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 on(t){let{config:e,creds:o}=ae(t);for(let r of[e,o])if(Re(r))try{je(r,"")}catch{}}function Te(t){let{creds:e}=ae(t);if(!Re(e))return null;try{let o=JSON.parse(zt(e,"utf-8"));return!o?.accessKeyId||!o?.secretAccessKey||!o?.sessionToken?null:o}catch{return null}}function Ot(t,e){let{dir:o,creds:r}=ae(t);jt(o,{recursive:!0}),je(r,JSON.stringify(e,null,2),"utf-8");try{Jo(r,384)}catch{}}function Tt(t){return t?.expiration?new Date(t.expiration).getTime()-Date.now()<Rt:!0}async function Nt({cwd:t,projectId:e,apiUrl:o,sessionToken:r,fetch:n=globalThis.fetch}){if(!e)throw new Error("refreshCredentials: projectId required");if(!o)throw new Error("refreshCredentials: apiUrl required");if(!r)throw new Error("refreshCredentials: sessionToken required (run `zibby login`)");let s=`${String(o).replace(/\/+$/,"")}/memory/sync-credentials`,l=await n(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({projectId:e})});if(!l.ok){let u=await l.text().catch(()=>"");throw new Error(`memory-sync credentials request failed (${l.status}): ${u||"no body"}`)}let d=await l.json();if(!d?.accessKeyId||!d?.secretAccessKey||!d?.sessionToken)throw new Error("memory-sync credentials response missing required fields");return Ot(t,{accessKeyId:d.accessKeyId,secretAccessKey:d.secretAccessKey,sessionToken:d.sessionToken,expiration:d.expiration||null,refreshedAt:new Date().toISOString()}),Te(t)}async function Mt({cwd:t,apiUrl:e,sessionToken:o,fetch:r}){let n=Oe(t);if(!n)return null;let s=Te(t);return(!s||Tt(s))&&(s=await Nt({cwd:t,projectId:n.projectId,apiUrl:e,sessionToken:o,fetch:r})),s}async function nn({cwd:t,apiUrl:e,sessionToken:o,fetch:r}){let n=await Mt({cwd:t,apiUrl:e,sessionToken:o,fetch:r});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 Xo,Qo,Rt,rn,Me=W(()=>{Xo="memory-sync.json",Qo="memory-sync-creds.json",Rt=120*1e3;rn={paths:ae,readCreds:Te,writeCreds:Ot,isExpiringSoon:Tt,REFRESH_HEADROOM_MS:Rt}});var Bt={};G(Bt,{memoryCompactCommand:()=>cn,memoryCostCommand:()=>un,memoryInitCommand:()=>hn,memoryPullCommand:()=>gn,memoryPushCommand:()=>yn,memoryRemoteAddCommand:()=>dn,memoryRemoteInfoCommand:()=>pn,memoryRemoteRemoveCommand:()=>mn,memoryRemoteUseHostedCommand:()=>fn,memoryResetCommand:()=>ln,memoryStatsCommand:()=>an});import a from"chalk";async function D(){try{return await import("@zibby/ui-memory")}catch{return console.log(a.yellow(`
|
|
16
16
|
@zibby/ui-memory is not installed.
|
|
17
|
-
`)),console.log(a.white(
|
|
17
|
+
`)),console.log(a.white(sn)),null}}async function an(){let t=await D();if(!t)return;let e=process.cwd(),o=t.getStats(e);if(!o.available){console.log(a.red(`
|
|
18
18
|
Dolt is not installed.
|
|
19
19
|
`)),console.log(a.white(" Install Dolt to enable test memory:")),console.log(a.gray(" brew install dolt # macOS")),console.log(a.gray(` curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash # Linux
|
|
20
20
|
`));return}if(!o.initialized){console.log(a.yellow(`
|
|
21
21
|
Memory database not initialized.
|
|
22
22
|
`)),console.log(a.white(" Run `zibby init` or `zibby memory init` to set it up.\n"));return}console.log(a.bold.cyan(`
|
|
23
23
|
Zibby Test Memory
|
|
24
|
-
`)),console.log(a.gray(` Dolt: ${o.doltVersion}`));let
|
|
25
|
-
${
|
|
26
|
-
${
|
|
27
|
-
${
|
|
28
|
-
`).filter(
|
|
24
|
+
`)),console.log(a.gray(` Dolt: ${o.doltVersion}`));let r=a.gray(` ${"\u2500".repeat(40)}`);console.log(r);let n=o.counts;if(console.log(a.white(` Test runs: ${a.cyan(n.runs)} (${a.green(`${n.passed} passed`)}, ${n.failed>0?a.red(`${n.failed} failed`):a.gray(`${n.failed} failed`)})`)),console.log(a.white(` Selectors: ${a.cyan(n.selectors)} tracked`)),console.log(a.white(` Pages: ${a.cyan(n.pages)} discovered`)),console.log(a.white(` Transitions: ${a.cyan(n.transitions)} mapped`)),console.log(a.white(` Insights: ${a.cyan(n.insights||0)} saved`)),o.recentRuns.length>0){console.log(`
|
|
25
|
+
${r}`),console.log(a.white(" Recent runs:"));for(let s of o.recentRuns){let l=s.passed?a.green("\u2713"):a.red("\u2717"),d=s.duration_ms?a.gray(`${(s.duration_ms/1e3).toFixed(1)}s`):"";console.log(` ${l} ${a.white(s.spec_path)} ${d}`)}}if(o.topSelectors.length>0){console.log(`
|
|
26
|
+
${r}`),console.log(a.white(" Top selectors:"));for(let s of o.topSelectors){let l=s.success_count+s.failure_count,d=Math.round(s.success_count/l*100);console.log(` ${a.cyan(s.stable_id||"?")} \u2192 ${s.element_desc} (${d}%, ${l} uses)`)}}if(o.log){console.log(`
|
|
27
|
+
${r}`),console.log(a.white(" Recent commits:"));let s=o.log.split(`
|
|
28
|
+
`).filter(l=>l.startsWith("commit")||l.trim().startsWith("run ")).slice(0,10);for(let l of s)console.log(a.gray(` ${l.trim()}`))}console.log("")}async function ln(t){let e=await D();if(!e)return;let o=process.cwd();if(!t.force){console.log(a.yellow(`
|
|
29
29
|
This will permanently delete the memory database.
|
|
30
30
|
`)),console.log(a.white(` Run with --force to confirm: zibby memory reset --force
|
|
31
|
-
`));return}let
|
|
31
|
+
`));return}let r=e.resetMemory(o);console.log(r?a.green(`
|
|
32
32
|
Memory database reset.
|
|
33
33
|
`):a.gray(`
|
|
34
34
|
No memory database found.
|
|
35
|
-
`))}async function
|
|
35
|
+
`))}async function cn(t){let e=await D();if(!e)return;let o=process.cwd(),r=e.getStats(o);if(!r.initialized){console.log(a.yellow(`
|
|
36
36
|
Memory database not initialized.
|
|
37
|
-
`));return}let n=t.maxRuns||50,
|
|
38
|
-
Compacting memory (keep last ${n} runs/spec, prune data older than ${
|
|
37
|
+
`));return}let n=t.maxRuns||50,s=t.maxAge||90;console.log(a.white(`
|
|
38
|
+
Compacting memory (keep last ${n} runs/spec, prune data older than ${s}d)...`));let l=r.counts;if(e.compactMemory(o,{maxRuns:n,maxAgeDays:s}).pruned){let u=e.getStats(o).counts,i=b=>l[b]-u[b];console.log(a.green(" Done.")),i("runs")>0&&console.log(a.gray(` Pruned ${i("runs")} old runs`)),i("selectors")>0&&console.log(a.gray(` Pruned ${i("selectors")} stale selectors`)),i("insights")>0&&console.log(a.gray(` Pruned ${i("insights")} old insights`)),i("transitions")>0&&console.log(a.gray(` Pruned ${i("transitions")} stale transitions`)),console.log(a.gray(` Dolt GC completed
|
|
39
39
|
`))}else console.log(a.gray(` Nothing to compact.
|
|
40
|
-
`))}async function
|
|
40
|
+
`))}async function un(){let t=await D();if(!t)return;let e=process.cwd(),o=t.getCostStats(e);if(!o){console.log(a.yellow(`
|
|
41
41
|
Memory database not initialized.
|
|
42
42
|
`)),console.log(a.white(" Run `zibby memory init` first.\n"));return}if(o.available===!1){console.log(a.yellow(`
|
|
43
43
|
No usage data yet${o.reason?` (${o.reason})`:""}.
|
|
44
44
|
`)),console.log(a.gray(" Run `zibby test <spec>` once to populate. Token counts come from")),console.log(a.gray(` the LLM SDK and are written to .zibby/output/sessions/<id>/execute_live/usage.json.
|
|
45
45
|
`));return}console.log(a.bold.cyan(`
|
|
46
46
|
Zibby \u2014 LLM Cost Report
|
|
47
|
-
`));let
|
|
48
|
-
${
|
|
49
|
-
${
|
|
50
|
-
${
|
|
47
|
+
`));let r=a.gray(` ${"\u2500".repeat(60)}`),n=o.totals;if(console.log(r),console.log(a.white(` Runs with usage data: ${a.cyan(n.runs)}`)),console.log(a.white(` Total input tokens: ${a.cyan(J(n.input))}`)),console.log(a.white(` Total output tokens: ${a.cyan(J(n.output))}`)),console.log(a.white(` Total cache reads: ${a.cyan(J(n.cache_read))} ${a.gray("(billed at ~10% of normal input rate)")}`)),console.log(a.white(` Total cache creation: ${a.cyan(J(n.cache_creation))} ${a.gray("(billed at ~125% of normal input rate)")}`)),o.by_domain.length>0){console.log(`
|
|
48
|
+
${r}`),console.log(a.white(" By domain:"));for(let s of o.by_domain.slice(0,10)){let l=s.runs>0?Math.round((s.input+s.output)/s.runs):0;console.log(` ${a.cyan(s.domain.padEnd(30))} ${a.gray(`${s.runs} runs \xB7 ~${J(l)}/run avg`)}`)}}if(o.by_spec.length>0){console.log(`
|
|
49
|
+
${r}`),console.log(a.white(" By spec:"));for(let s of o.by_spec.slice(0,10)){let l=s.runs>0?Math.round((s.input+s.output)/s.runs):0;console.log(` ${a.cyan(String(s.spec_path).padEnd(40))} ${a.gray(`${s.runs} runs \xB7 ~${J(l)}/run avg`)}`)}}if(o.recent.length>0){console.log(`
|
|
50
|
+
${r}`),console.log(a.white(" Last 10 runs:"));for(let s of o.recent.slice(0,10)){let l=s.passed?a.green("\u2713"):a.red("\u2717"),d=(s.input_tokens||0)+(s.output_tokens||0),u=(s.cache_read_tokens||0)>0?a.gray(` \xB7 cache read ${J(s.cache_read_tokens)}`):"";console.log(` ${l} ${a.gray(s.run_at.slice(0,16))} ${a.cyan(J(d).padStart(8))} ${a.white(s.spec_path||"")}${u}`)}}console.log("")}function J(t){return t==null?"\u2014":t<1e3?String(t):t<1e6?`${(t/1e3).toFixed(1)}K`:`${(t/1e6).toFixed(2)}M`}async function dn(t,e={}){let o=await D();if(!o)return;t||(console.log(a.red(`
|
|
51
51
|
Usage: zibby memory remote add <url> [--name origin]
|
|
52
|
-
`)),console.log(a.gray(" Supported: aws:// gs:// https:// file:///")),console.log(a.gray(" Example: zibby memory remote add aws://team-bucket/zibby/shop-prod")),console.log(""),process.exit(1));let
|
|
52
|
+
`)),console.log(a.gray(" Supported: aws:// gs:// https:// file:///")),console.log(a.gray(" Example: zibby memory remote add aws://team-bucket/zibby/shop-prod")),console.log(""),process.exit(1));let r=process.cwd(),n=e.name||"origin";if(!o.memoryRemoteAdd(r,t,n)){console.log(a.red("\n Failed to add remote. Is the memory DB initialized? Run `zibby memory init` first.\n"));return}console.log(""),console.log(a.green(` \u2713 Added remote ${a.bold(n)} \u2192 ${t}`)),console.log(a.gray(" Next step: zibby memory pull (or just run any test \u2014 middleware auto-pulls/pushes)")),console.log("")}async function pn(){let t=await D();if(!t)return;let e=t.memoryRemoteInfo(process.cwd());if(console.log(""),!e){console.log(a.yellow(` No memory remote configured.
|
|
53
53
|
`)),console.log(a.gray(" Set one with: zibby memory remote add <url>")),console.log(a.gray(` Without a remote, memory is local-only \u2014 team members won't see each other's learnings.
|
|
54
|
-
`));return}console.log(a.bold.cyan(" Memory remote")),console.log(` ${a.cyan(e.name||"origin")}: ${e.url||"(unknown)"}`),console.log("")}async function
|
|
54
|
+
`));return}console.log(a.bold.cyan(" Memory remote")),console.log(` ${a.cyan(e.name||"origin")}: ${e.url||"(unknown)"}`),console.log("")}async function mn(t="origin"){let e=await D();if(!e)return;let o=e.memoryRemoteRemove(process.cwd(),t);console.log(""),o?(console.log(a.green(` \u2713 Removed remote ${t}.`)),console.log(a.gray(" Memory is now local-only."))):console.log(a.gray(` No remote named ${t} to remove.`)),console.log("")}async function gn(){let t=await D();if(!t)return;console.log(a.cyan(`
|
|
55
55
|
Pulling team memory from remote...`));let e=t.memorySyncPull(process.cwd());e.pulled?console.log(a.green(` \u2713 Pulled latest. Local memory now reflects the team's shared knowledge.
|
|
56
|
-
`)):(console.log(a.yellow(` \u26A0 Pull skipped \u2014 ${e.error||"unknown reason"}.`)),console.log(a.gray(" Did you run `zibby memory remote add <url>` first?\n")))}async function
|
|
56
|
+
`)):(console.log(a.yellow(` \u26A0 Pull skipped \u2014 ${e.error||"unknown reason"}.`)),console.log(a.gray(" Did you run `zibby memory remote add <url>` first?\n")))}async function fn(t={}){let e=await D();if(!e)return;let{join:o}=await import("path"),{existsSync:r}=await import("fs"),n=t.cwd||process.cwd(),s=t.projectId;if(!s){let x=o(n,".zibby.config.mjs");if(r(x))try{let S=(await import(`file://${x}?t=${Date.now()}`)).default;s=S?.projectId||S?.project?.id}catch{}}s||(console.log(a.red(`
|
|
57
57
|
Could not determine projectId.
|
|
58
58
|
`)),console.log(a.gray(" Either run this from a project dir with `.zibby.config.mjs`")),console.log(a.gray(` containing { projectId: "..." }, or pass --project-id <id>.
|
|
59
|
-
`)),process.exit(1));let{getApiUrl:
|
|
59
|
+
`)),process.exit(1));let{getApiUrl:l}=await Promise.resolve().then(()=>(Et(),Pt)),{getSessionToken:d}=await Promise.resolve().then(()=>(Ee(),Pe)),u=l(),i=d();i||(console.log(a.red("\n Not logged in. Run `zibby login` first.\n")),console.log(a.gray(" Hosted memory-sync is for signed-in users only \u2014")),console.log(a.gray(` the backend needs your identity to scope per-tenant credentials.
|
|
60
60
|
`)),process.exit(1)),console.log(a.cyan(`
|
|
61
|
-
Configuring hosted memory-sync...`));let b;try{let
|
|
62
|
-
Failed: ${
|
|
63
|
-
`)),process.exit(1)}let{writeConfig:k}=await Promise.resolve().then(()=>(
|
|
64
|
-
Saved hosted-sync config, but failed to register Dolt remote.`)),console.log(a.gray(" Try `zibby memory init` first (the local Dolt DB must exist).\n")),process.exit(1));let{refreshCredentials:
|
|
65
|
-
Config saved, but initial credential fetch failed: ${
|
|
66
|
-
`))}console.log(""),console.log(a.green(" \u2713 Hosted memory-sync configured.")),console.log(a.gray(` Bucket: ${b.bucket}`)),console.log(a.gray(` Prefix: ${b.prefix} \u2190 your tenant slot`)),console.log(a.gray(` Dolt: ${b.doltUrl}`)),console.log(""),console.log(a.gray(" Every test run will auto-pull/push. Creds refresh automatically.")),console.log(a.gray(" To revert to local-only: zibby memory remote remove origin")),console.log("")}async function
|
|
61
|
+
Configuring hosted memory-sync...`));let b;try{let x=`${u.replace(/\/+$/,"")}/memory/sync-config?projectId=${encodeURIComponent(s)}`,w=await fetch(x,{headers:{Authorization:`Bearer ${i}`}});if(!w.ok){let S=await w.text().catch(()=>"");throw new Error(`backend returned ${w.status}: ${S||"no body"}`)}b=await w.json()}catch(x){console.log(a.red(`
|
|
62
|
+
Failed: ${x.message}
|
|
63
|
+
`)),process.exit(1)}let{writeConfig:k}=await Promise.resolve().then(()=>(Me(),Ne));k(n,{projectId:s,bucket:b.bucket,prefix:b.prefix,doltUrl:b.doltUrl}),e.memoryRemoteAdd(n,b.doltUrl)||(console.log(a.yellow(`
|
|
64
|
+
Saved hosted-sync config, but failed to register Dolt remote.`)),console.log(a.gray(" Try `zibby memory init` first (the local Dolt DB must exist).\n")),process.exit(1));let{refreshCredentials:h}=await Promise.resolve().then(()=>(Me(),Ne));try{await h({cwd:n,projectId:s,apiUrl:u,sessionToken:i})}catch(x){console.log(a.yellow(`
|
|
65
|
+
Config saved, but initial credential fetch failed: ${x.message}`)),console.log(a.gray(` Will retry on first push/pull.
|
|
66
|
+
`))}console.log(""),console.log(a.green(" \u2713 Hosted memory-sync configured.")),console.log(a.gray(` Bucket: ${b.bucket}`)),console.log(a.gray(` Prefix: ${b.prefix} \u2190 your tenant slot`)),console.log(a.gray(` Dolt: ${b.doltUrl}`)),console.log(""),console.log(a.gray(" Every test run will auto-pull/push. Creds refresh automatically.")),console.log(a.gray(" To revert to local-only: zibby memory remote remove origin")),console.log("")}async function yn(){let t=await D();if(!t)return;console.log(a.cyan(`
|
|
67
67
|
Pushing local memory to team remote...`));let e=t.memorySyncPush(process.cwd());e.pushed?console.log(a.green(" \u2713 Pushed. Team can now `zibby memory pull` to see your run's learnings.\n")):console.log(a.yellow(` \u26A0 Push skipped \u2014 ${e.error||"unknown reason"}.
|
|
68
|
-
`))}async function
|
|
68
|
+
`))}async function hn(){let t=await D();if(!t)return;let e=process.cwd();if(!t.DoltDB.isAvailable()){console.log(a.red(`
|
|
69
69
|
Dolt is not installed.
|
|
70
70
|
`)),console.log(a.white(" Install Dolt:")),console.log(a.gray(" brew install dolt # macOS")),console.log(a.gray(` curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash # Linux
|
|
71
|
-
`));return}let{created:o,available:
|
|
71
|
+
`));return}let{created:o,available:r}=t.initMemory(e);o?console.log(a.green(`
|
|
72
72
|
Memory database initialized at .zibby/memory/
|
|
73
|
-
`)):
|
|
73
|
+
`)):r&&console.log(a.gray(`
|
|
74
74
|
Memory database already initialized.
|
|
75
|
-
`))}var
|
|
75
|
+
`))}var sn,Lt=W(()=>{sn=`
|
|
76
76
|
Install @zibby/ui-memory and Dolt to enable test memory:
|
|
77
77
|
|
|
78
78
|
npm install @zibby/ui-memory # add the package
|
|
79
79
|
brew install dolt # macOS
|
|
80
80
|
# or: curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash
|
|
81
|
-
`});var
|
|
82
|
-
`,"utf-8")}async function
|
|
83
|
-
`).find(
|
|
84
|
-
`,"utf-8"),n}function
|
|
81
|
+
`});var Vt={};G(Vt,{setupCiCommand:()=>_n,setupPlaywrightMcpCommand:()=>Gt,testWithVideoCommand:()=>Pn});import{spawn as Le,execSync as Ke}from"child_process";import{join as oe,dirname as De,resolve as Ut}from"path";import{readFileSync as Yt,writeFileSync as Ft,existsSync as le,mkdirSync as Ht}from"fs";import{homedir as Wt}from"os";import{createRequire as wn}from"module";import R from"chalk";function bn(){try{return De(Be.resolve("@zibby/core/package.json"))}catch{return null}}function Zt(t){try{return Ke(`command -v ${t}`,{stdio:"pipe"}),!0}catch{return!1}}function kn(){try{let t=Be.resolve("@zibby/mcp-browser/dist/bin/mcp-browser-zibby.js");if(le(t))return t}catch{}try{let t=Be.resolve("@playwright/mcp/package.json"),e=De(t),o=JSON.parse(Yt(t,"utf-8")),r=typeof o.bin=="string"?o.bin:o.bin?.["playwright-mcp"];if(r){let s=oe(e,r);if(le(s))return s}let n=oe(e,"cli.js");if(le(n))return n}catch{}return null}function Kt(t,e,o={}){return new Promise((r,n)=>{let s=Le(t,e,{stdio:"inherit",...o});s.on("close",l=>r(l??1)),s.on("error",n)})}async function $n(t){return Zt("playwright")?await Kt("playwright",["install","ffmpeg"],{cwd:t})===0:await Kt("npx",["--yes","playwright","install","ffmpeg"],{cwd:t})===0}function vn({headed:t=!1,viewport:e=null}){let o=process.execPath,r=De(o),n=kn(),s=Number(e?.width)||1280,l=Number(e?.height)||720,d=`${s}x${l}`,u=[];u.push(`--viewport-size=${d}`,"--output-dir=test-results"),t||u.push("--headless");let i;n?i={command:o,args:[n,...u],env:{PATH:`${r}:/usr/bin:/bin:/usr/sbin:/sbin`}}:i={command:"npx",args:["-y","@playwright/mcp",...u],env:{PATH:`${r}:/usr/bin:/bin:/usr/sbin:/sbin`}},i.description="Zibby MCP Browser - Playwright MCP with Zibby defaults";let b=oe(Wt(),".cursor"),k=oe(b,"mcp.json");le(b)||Ht(b,{recursive:!0});let h={mcpServers:{}};if(le(k))try{h=JSON.parse(Yt(k,"utf-8")),(!h.mcpServers||typeof h.mcpServers!="object")&&(h.mcpServers={})}catch{h={mcpServers:{}}}h.mcpServers["playwright-official"]=i,Ft(k,`${JSON.stringify(h,null,2)}
|
|
82
|
+
`,"utf-8")}async function xn(){let t=bn();if(!t)return;let e=oe(t,"scripts","patch-cursor-mcp.js");if(le(e))try{await new Promise((o,r)=>{let n=Le(process.execPath,[e],{cwd:process.cwd(),stdio:"ignore"});n.on("close",s=>o(s??0)),n.on("error",r)})}catch{}}function Cn(t){return Ut(t).replace(/^\/+/,"").replace(/\//g,"-")}function An(t){let e=String(t||""),o=e.split(`
|
|
83
|
+
`).find(s=>/playwright-official/i.test(s)&&/APPROVAL|🔑/i.test(s));if(o){let s=o.match(/=>\s*(\S+)/);if(s)return s[1]}let r=e.match(/playwright-official[^=]*=>\s*(\S+)/);if(r)return r[1];let n=e.match(/playwright-official-[a-f0-9]+/i);return n?n[0]:null}function Sn(t,e){let o=Cn(t),r=oe(Wt(),".cursor","projects",o);Ht(r,{recursive:!0});let n=oe(r,"mcp-approvals.json");return Ft(n,`${JSON.stringify([e],null,2)}
|
|
84
|
+
`,"utf-8"),n}function Dt(t){try{return Ke("cursor-agent mcp list",{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:process.env,maxBuffer:2*1024*1024})}catch(e){let o=e.stdout!=null?String(e.stdout):"",r=e.stderr!=null?String(e.stderr):"";return o+r}}function In(t){try{return Ke("cursor-agent mcp enable playwright-official",{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:process.env,maxBuffer:1024*1024}),!0}catch{return!1}}async function Gt(t={}){let e=!!t.headed,o=t.viewport||{width:1280,height:720};if(!process.execPath)throw new Error("Node.js runtime not found");let r=await $n(process.cwd());console.log(r?R.gray(" \u2713 ffmpeg installed for Playwright video"):R.yellow(" \u26A0 Could not install ffmpeg (video may be unavailable)")),vn({headed:e,viewport:o}),await xn();let n=Ut(process.cwd());if(Zt("cursor-agent")){Dt(n);let s=In(n);s&&console.log(R.gray(" \u2713 cursor-agent: mcp enable playwright-official"));let l=Dt(n),d=An(l);if(d)try{let u=Sn(n,d);console.log(R.gray(` \u2713 MCP auto-approval key saved (${u})`))}catch(u){console.log(R.yellow(` \u26A0 Could not write mcp-approvals.json: ${u.message}`))}else s||(console.log(R.yellow(" \u26A0 Could not auto-approve MCP (mcp enable failed and no approval key in cursor-agent output)")),console.log(R.gray(" Try: cursor-agent mcp enable playwright-official")))}else console.log(R.yellow(" \u26A0 cursor-agent not found; install it to use Cursor MCP tools"))}async function _n(t){try{console.log(R.cyan(`
|
|
85
85
|
\u{1F680} Running CI setup...
|
|
86
|
-
`)),await
|
|
86
|
+
`)),await Gt({headed:!1,cloudSync:!0,viewport:{width:1280,height:720}}),console.log(R.green(`
|
|
87
87
|
\u2705 CI/CD setup complete!
|
|
88
88
|
`))}catch(e){console.log(R.red(`
|
|
89
89
|
\u274C Error: ${e.message}
|
|
90
|
-
`)),process.exit(1)}}async function
|
|
90
|
+
`)),process.exit(1)}}async function Pn(t,e){try{let o=["playwright","test",t||"tests/","--project=chromium"];e.headed&&o.push("--headed"),console.log(R.cyan(`
|
|
91
91
|
\u{1F3A5} Running tests with video recording...
|
|
92
|
-
`)),console.log(R.gray("\u2501".repeat(50)));let
|
|
92
|
+
`)),console.log(R.gray("\u2501".repeat(50)));let r=Le("npx",o,{cwd:process.cwd(),stdio:"inherit"});r.on("close",n=>{n===0?console.log(R.green(`
|
|
93
93
|
\u2705 Tests complete!
|
|
94
94
|
`)):(console.log(R.red(`
|
|
95
95
|
\u274C Tests failed with code ${n}
|
|
96
|
-
`)),process.exit(n))}),
|
|
96
|
+
`)),process.exit(n))}),r.on("error",n=>{console.log(R.red(`
|
|
97
97
|
\u274C Error: ${n.message}
|
|
98
98
|
`)),process.exit(1)})}catch(o){console.log(R.red(`
|
|
99
99
|
\u274C Error: ${o.message}
|
|
100
|
-
`)),process.exit(1)}}var Be,
|
|
101
|
-
`));return}console.log(
|
|
102
|
-
To add manually on Windows:`)),console.log(
|
|
103
|
-
`))):(console.log(
|
|
104
|
-
To add manually, run:`)),console.log(
|
|
105
|
-
`)));return}if(t){console.log(
|
|
106
|
-
`));return}let
|
|
100
|
+
`)),process.exit(1)}}var Be,qt=W(()=>{Be=wn(import.meta.url)});var Qt={};G(Qt,{generateConfig:()=>ke,initCommand:()=>Mn});import{mkdir as U,writeFile as z,readFile as L}from"fs/promises";import{existsSync as A,readdirSync as we}from"fs";import{join as f,resolve as Ue,dirname as En}from"path";import{homedir as Q}from"os";import ne from"inquirer";import c from"chalk";import X from"ora";import{spawn as pe,execSync as be}from"child_process";import{fileURLToPath as zn}from"url";import{createRequire as jn}from"module";async function Rn(){let t=fe(),e=process.env.ANTHROPIC_API_KEY||t.agentKeys?.ANTHROPIC_API_KEY,o=t.agentKeys?.CLAUDE_CODE_OAUTH_TOKEN||null;console.log(""),console.log(c.cyan(" Claude credentials \u2014 pick the type you have:")),console.log("");let{kind:r}=await ne.prompt([{type:"select",name:"kind",message:"Which Claude credential do you want to use?",choices:[{name:o?`OAuth ***${o.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:o?"oauth":e?"api":"oauth"}]);if(r==="skip")return{kind:"skip"};if(r==="oauth"){o||(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 d=o?`Press Enter to reuse saved token (***${o.slice(-4)}), or paste a new one:`:"Paste OAuth token from `claude setup-token` (or press Enter to skip):",{token:u}=await ne.prompt([{type:"password",name:"token",message:d,mask:"*"}]),i=(u||"").trim();return i?{kind:"oauth",token:i}:o?{kind:"oauth",token:o}:{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:s}=await ne.prompt([{type:"password",name:"token",message:n,mask:"*"}]),l=(s||"").trim();return l?{kind:"api",token:l}:e?{kind:"api",token:e}:{kind:"skip"}}async function Nn(){try{let t=process.platform==="win32",e=be("npm config get prefix",{encoding:"utf-8"}).trim(),o=t?e:`${e}/bin`,r=o.replace(/^~/,Q()),n=t?";":":";if(process.env.PATH.split(n).some(k=>{let h=k.replace(/^~/,Q());return h===r||h===o}))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: ${r}`)),console.log(c.gray(` Add it manually: export PATH="${r}:$PATH"
|
|
101
|
+
`));return}console.log(c.yellow("npm global bin not in PATH")),console.log(c.gray(` Location: ${r}`)),console.log();let{shouldAddPath:d}=await ne.prompt([{type:"confirm",name:"shouldAddPath",message:"Add npm global bin to your shell PATH automatically?",default:!0}]);if(!d){t?(console.log(c.gray(`
|
|
102
|
+
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: ${r}
|
|
103
|
+
`))):(console.log(c.gray(`
|
|
104
|
+
To add manually, run:`)),console.log(c.gray(` echo 'export PATH="${r}:$PATH"' >> ~/.zshrc`)),console.log(c.gray(` source ~/.zshrc
|
|
105
|
+
`)));return}if(t){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: ${r}
|
|
106
|
+
`));return}let u=process.env.SHELL||"",i="";if(u.includes("zsh"))i=f(Q(),".zshrc");else if(u.includes("bash"))i=A(f(Q(),".bashrc"))?f(Q(),".bashrc"):f(Q(),".bash_profile");else{console.log(c.yellow(`Unknown shell: ${u}`)),console.log(c.gray(" Please add manually:")),console.log(c.gray(` export PATH="${r}:$PATH"`));return}if(A(i)){let k=await L(i,"utf-8");if(k.includes(r)||k.includes("npm")&&k.includes("global")&&k.includes("bin")){console.log(c.yellow(`PATH entry found in ${i} but not active`)),console.log(c.gray(` Run: source ${i}
|
|
107
107
|
`));return}}let b=`
|
|
108
108
|
# npm global bin (added by zibby)
|
|
109
|
-
export PATH="${
|
|
110
|
-
`;await
|
|
111
|
-
Run this to activate in current session:`)),console.log(
|
|
112
|
-
`))}catch{}}async function
|
|
109
|
+
export PATH="${r}:$PATH"
|
|
110
|
+
`;await z(i,(A(i)?await L(i,"utf-8"):"")+b),console.log(c.green(`Added to ${i}`)),console.log(c.yellow(`
|
|
111
|
+
Run this to activate in current session:`)),console.log(c.gray(` source ${i}
|
|
112
|
+
`))}catch{}}async function Mn(t,e){let o=e.template==="browser-test-automation";console.log(o?`
|
|
113
113
|
Zibby Test Automation
|
|
114
114
|
`:`
|
|
115
115
|
Zibby Project Init
|
|
116
|
-
`);let
|
|
116
|
+
`);let r=!e.skipMemory,n=["dolt","mem0"].includes(String(e.memoryBackend||"").toLowerCase())?String(e.memoryBackend).toLowerCase():"mem0",s=e.infer===!0;await Nn();let l=t?Ue(process.cwd(),t):process.cwd(),d=t||"zibby-tests",u=!!t;u&&A(l)&&(console.log(c.red(`
|
|
117
117
|
Directory "${t}" already exists!
|
|
118
|
-
`)),process.exit(1)),!
|
|
118
|
+
`)),process.exit(1)),!u&&A(f(l,".zibby.config.mjs"))&&!e.force&&(console.log(c.yellow(`
|
|
119
119
|
Zibby is already initialized in this directory!
|
|
120
|
-
`)),console.log(
|
|
121
|
-
`)),process.exit(0)),e.force&&!
|
|
120
|
+
`)),console.log(c.white("Config file found: .zibby.config.mjs")),console.log(c.gray(`Use --force or -f to reinitialize
|
|
121
|
+
`)),process.exit(0)),e.force&&!u&&console.log(c.cyan(`
|
|
122
122
|
Reinitializing Zibby configuration...
|
|
123
|
-
`));let i;if(e.agent&&(e.headed||e.headless))console.log(
|
|
124
|
-
`)),i={agent:e.agent,browserMode:e.headless?"headless":"headed",apiKey:e.apiKey||null,cloudSync:!!(e.cloudSync||e.apiKey)};else{if(e.agent)i={agent:e.agent};else{let{agent:
|
|
123
|
+
`));let i;if(e.agent&&(e.headed||e.headless))console.log(c.cyan(`Setting up with provided options...
|
|
124
|
+
`)),i={agent:e.agent,browserMode:e.headless?"headless":"headed",apiKey:e.apiKey||null,cloudSync:!!(e.cloudSync||e.apiKey)};else{if(e.agent)i={agent:e.agent};else{let{agent:C}=await ne.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"}]);i={agent:C}}let x=ge[i.agent],w=!(process.env.CI||process.env.ZIBBY_CI||!process.stdin.isTTY);if(i.agent==="claude"&&!e.agentKey&&w){let C=await Rn();C?.kind==="oauth"&&C.token?(i.claudeOauthToken=C.token,i.agentAuth="oauth"):C?.kind==="api"&&C.token&&(i.agentKey=C.token,i.agentAuth="api")}else if(x&&!e.agentKey&&w){let C=fe(),E=process.env[x.envVar]||C.agentKeys?.[x.envVar],_=E?`***${E.slice(-4)}`:null,K=_?`${x.label} found (${_}). Press Enter to keep, or paste a new key:`:`Enter ${x.label} (from ${x.url}, or press Enter to skip):`,{agentKey:N}=await ne.prompt([{type:"password",name:"agentKey",message:K,mask:"*"}]);N&&N.trim()&&(i.agentKey=N.trim(),i.agentAuth="api")}let S=[];if(o&&!e.headed&&!e.headless&&S.push({type:"select",name:"browserMode",message:"Browser mode during live AI execution?",choices:[{name:"Headed - Visible browser (recommended for development)",value:"headed"},{name:"Headless - Hidden browser (for CI/CD)",value:"headless"}],default:"headed"}),o&&!e.apiKey&&S.push({type:"input",name:"apiKey",message:"Project ZIBBY_API_KEY for test-result cloud sync (uploads runs to your team's zibby.dev dashboard) \u2014 paste or press Enter to skip:"}),S.length>0){let C=await ne.prompt(S);Object.assign(i,C)}i.browserMode=e.headless?"headless":e.headed?"headed":i.browserMode,i.apiKey=e.apiKey||i.apiKey,i.cloudSync=!!(e.cloudSync||e.apiKey||i.apiKey&&i.apiKey.trim())}e.agentKey&&(i.agentKey=e.agentKey),e.agentOauthToken&&i.agent==="claude"&&(i.claudeOauthToken=e.agentOauthToken);let k=ge[i.agent];i.claudeOauthToken&&(Ce("CLAUDE_CODE_OAUTH_TOKEN",i.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"))),i.agentKey&&(et(i.agentKey,i.agent),console.log(c.gray(" Agent API key saved to ~/.zibby/config.json"))),i.mcp="playwright",i.setupMcp=i.agent==="cursor";let h=X("Setting up Zibby...").start();try{if(u&&await U(l,{recursive:!0}),o&&(await U(f(l,"test-specs/examples"),{recursive:!0}),await U(f(l,"tests"),{recursive:!0})),await U(f(l,".zibby/output"),{recursive:!0}),await U(f(l,".zibby/commands"),{recursive:!0}),r&&n==="dolt")try{let{initMemory:m,DoltDB:y}=await import("@zibby/ui-memory");if(y.isAvailable()){let{created:g}=m(l);g&&(h.text="Initialized test memory database (Dolt)...")}else h.text="Dolt not found \u2014 skipping memory database (brew install dolt)"}catch{}let x=e.template,w=x&&x!=="none"&&x!=="false";if(w){h.text=`Scaffolding workflow template: ${x}...`;try{let{writeTemplateFiles:m}=await Promise.resolve().then(()=>(Se(),Ae));await m(l,x,{enableMemory:r})}catch(m){throw h.fail(`Failed to scaffold template: ${m.message}`),m}}else await U(f(l,".zibby"),{recursive:!0});h.text="Generating configuration files...";let S=ke(i,e,{memoryBackend:n,memoryInfer:s});if(await z(f(l,".zibby.config.mjs"),S),await z(f(l,".env.example"),Bn(i,n,s)),i.apiKey&&i.apiKey.trim()){let m=f(l,".env"),y=i.apiKey.trim();if(A(m)){let g=await L(m,"utf8");/^ZIBBY_API_KEY=/m.test(g)?g=g.replace(/^ZIBBY_API_KEY=.*/m,`ZIBBY_API_KEY=${y}`):/^#\s*ZIBBY_API_KEY=/m.test(g)?g=g.replace(/^#\s*ZIBBY_API_KEY=.*/m,`ZIBBY_API_KEY=${y}`):g=`${g.trimEnd()}
|
|
125
125
|
|
|
126
126
|
# Zibby Cloud Sync
|
|
127
|
-
ZIBBY_API_KEY=${
|
|
128
|
-
`,await
|
|
127
|
+
ZIBBY_API_KEY=${y}
|
|
128
|
+
`,await z(m,g)}else await z(m,Ln(i,y,n,s))}if(i.agentKey&&k){let m=f(l,".env"),y=i.agentKey;if(A(m)){let g=await L(m,"utf8"),v=new RegExp(`^${k.envVar}=.*`,"m"),$=new RegExp(`^#\\s*${k.envVar}=.*`,"m");v.test(g)?g=g.replace(v,`${k.envVar}=${y}`):$.test(g)?g=g.replace($,`${k.envVar}=${y}`):g=`${g.trimEnd()}
|
|
129
129
|
|
|
130
130
|
# AI Agent Key
|
|
131
|
-
${
|
|
132
|
-
`,await
|
|
133
|
-
|
|
134
|
-
`))),!e.skipInstall&&o){let
|
|
131
|
+
${k.envVar}=${y}
|
|
132
|
+
`,await z(m,g)}}if(u){let m=Kn(d,i,{memoryBackend:n});await z(f(l,"package.json"),m)}if(!A(f(l,".gitignore"))){let m=Dn();await z(f(l,".gitignore"),m)}if(o){if(!A(f(l,"playwright.config.js"))){let m=Un("on");await z(f(l,"playwright.config.js"),m)}if(!A(f(l,"test-specs/examples/example-domain.txt"))){let m=Yn();await z(f(l,"test-specs/examples/example-domain.txt"),m)}}let C=Ue(Jt,"../../../../examples/.zibby/commands");if(A(C)){let m=we(C).filter(y=>y.toLowerCase().endsWith(".md"));for(let y of m){let g=f(l,".zibby/commands",y);if(e.force||!A(g)){let v=await L(f(C,y),"utf-8");await z(g,v)}}}if(!A(f(l,".zibby/commands/example.md"))){let m=Fn();await z(f(l,".zibby/commands/example.md"),m)}let E=Ue(Jt,"../../templates"),_=f(E,".claude"),K=!1,N=0,Z=0,ee=0,ve=null;if(A(_)){await U(f(l,".claude"),{recursive:!0}),await U(f(l,".claude","commands"),{recursive:!0}),await U(f(l,".claude","agents"),{recursive:!0});let m=f(_,"CLAUDE.md"),y=f(l,".claude","CLAUDE.md");if(A(m)&&(e.force||!A(y))){let $=await L(m,"utf-8");await z(y,$),K=!0}let g=f(_,"commands");if(A(g)){let $=we(g).filter(I=>I.toLowerCase().endsWith(".md"));for(let I of $){let H=f(l,".claude","commands",I);if(e.force||!A(H)){let M=await L(f(g,I),"utf-8");await z(H,M),N++}}}let v=f(_,"agents");if(A(v)){let $=we(v).filter(I=>I.toLowerCase().endsWith(".md"));for(let I of $){let H=f(l,".claude","agents",I);if(e.force||!A(H)){let M=await L(f(v,I),"utf-8");await z(H,M),Z++}}}}let xe=f(E,".cursor","rules");if(A(xe)){await U(f(l,".cursor","rules"),{recursive:!0});let m=we(xe).filter(y=>y.toLowerCase().endsWith(".mdc"));for(let y of m){let g=f(l,".cursor","rules",y);if(e.force||!A(g)){let v=await L(f(xe,y),"utf-8");await z(g,v),ee++}}}let Ge=f(E,"AGENTS.md");if(A(Ge)){let{upsertManagedBlock:m}=await Promise.resolve().then(()=>(lt(),at)),y=f(l,"AGENTS.md"),g=await L(Ge,"utf-8"),v=A(y)?await L(y,"utf-8"):null,{content:$,action:I}=m(v,g);I!=="skipped"&&await z(y,$),ve=I}if(K&&console.log(c.green(" \u2713 Wrote .claude/CLAUDE.md (workflow + apps knowledge)")),N>0&&console.log(c.green(` \u2713 Wrote .claude/commands/ (${N} slash command${N===1?"":"s"})`)),Z>0&&console.log(c.green(` \u2713 Wrote .claude/agents/ (${Z} subagent definition${Z===1?"":"s"})`)),ee>0&&console.log(c.green(` \u2713 Wrote .cursor/rules/ (${ee} Cursor rule${ee===1?"":"s"})`)),ve==="created"?console.log(c.green(" \u2713 Wrote AGENTS.md (Zibby section, managed block)")):ve==="updated"&&console.log(c.green(" \u2713 Updated AGENTS.md (Zibby section, your content preserved)")),u){let m=Hn(d,i);await z(f(l,"README.md"),m)}try{let{validateMemorySyncConfig:m,applyMemorySyncConfig:y}=await Promise.resolve().then(()=>(pt(),dt)),g=f(l,".zibby.config.mjs"),v=null;if(A(g))try{v=(await import(`file://${g}?t=${Date.now()}`)).default?.memorySync}catch{}let $=m(v);if($.ok&&$.kind!=="noop"){let I=await import("@zibby/ui-memory").catch(()=>null),{getSessionToken:H}=await Promise.resolve().then(()=>(Ee(),Pe)),M=await y({cwd:l,projectId:i.projectId,block:v,memoryApi:I,getSessionToken:H,hostedSetup:async({cwd:ue,projectId:de})=>{let{memoryRemoteUseHostedCommand:Ve}=await Promise.resolve().then(()=>(Lt(),Bt));await Ve({cwd:ue,projectId:de})},logger:{info:()=>{},warn:()=>{},error:()=>{}}});M.action==="hosted"?console.log(c.green(" \u2713 Hosted memory-sync configured from .zibby.config.mjs")):M.action==="byo"?console.log(c.green(` \u2713 Memory remote configured from .zibby.config.mjs \u2192 ${M.remote}`)):M.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."))):M.action==="error"&&console.log(c.yellow(` \u26A0 memorySync setup skipped: ${M.reason}`))}else $.ok||console.log(c.yellow(` \u26A0 memorySync config invalid: ${$.error}`))}catch(m){console.log(c.yellow(` \u26A0 memorySync auto-apply failed: ${m.message}`))}if(h.succeed(u?"Project created!":"Zibby initialized!"),w||(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("")),u&&!e.skipInstall){let m=X("Installing dependencies...").start();await new Promise((y,g)=>{pe("npm",["install"],{cwd:l,stdio:"pipe"}).on("close",$=>{$===0?(m.succeed("Dependencies installed!"),y()):(m.fail("Failed to install dependencies"),g(new Error("npm install failed")))})})}if(!u&&r&&n==="mem0"&&(console.log(c.yellow(`
|
|
133
|
+
The mem0 memory backend requires two dependencies in your project.`)),console.log(c.gray("Run this in your project when ready (or switch to the self-contained dolt backend with --memory-backend dolt):")),console.log(c.white(` npm install mem0ai@npm:@zibby/mem0ai@^3.0.5 better-sqlite3@^12.6.2
|
|
134
|
+
`))),!e.skipInstall&&o){let m=X("Installing Playwright browsers...").start();await new Promise(y=>{let g=pe("npx",["playwright","install","chromium"],{cwd:l,stdio:"pipe"}),v="";g.stdout.on("data",$=>{v+=$.toString()}),g.stderr.on("data",$=>{v+=$.toString()}),g.on("close",$=>{$===0?(v.includes("already installed")||v.includes("up to date")?m.succeed("Playwright browsers already installed"):m.succeed("Playwright browsers installed!"),y()):(m.warn("Could not verify Playwright browsers"),console.log(c.yellow(`
|
|
135
135
|
If tests fail, run: npx playwright install
|
|
136
|
-
`)),
|
|
137
|
-
`))}}}if(i.agent==="codex"&&!e.skipInstall){let
|
|
138
|
-
`))}}}if(i.agent==="gemini"&&!e.skipInstall){let
|
|
139
|
-
`))}}if(o){let
|
|
140
|
-
`,"utf-8");let ue="Gemini MCP configured";
|
|
141
|
-
`))}}}if(i.agent==="cursor"&&i.setupMcp&&o){let
|
|
136
|
+
`)),y())})})}if(i.agent==="cursor"&&!e.skipInstall){let m=X("Checking cursor-agent CLI...").start();try{be("cursor-agent --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),m.succeed("cursor-agent CLI already installed")}catch{m.text="Installing cursor-agent CLI...";try{await new Promise((y,g)=>{pe("bash",["-c","curl https://cursor.com/install -fsS | bash"],{stdio:"pipe"}).on("close",$=>{if($===0){let I=f(Q(),".local","bin");process.env.PATH.includes(I)||(process.env.PATH=`${I}:${process.env.PATH}`),m.succeed("cursor-agent CLI installed!"),y()}else g(new Error("cursor-agent install failed"))})})}catch{m.fail("Could not install cursor-agent CLI"),console.log(c.yellow(` Install manually: curl https://cursor.com/install -fsS | bash
|
|
137
|
+
`))}}}if(i.agent==="codex"&&!e.skipInstall){let m=X("Checking Codex CLI...").start();try{be("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),m.succeed("Codex CLI already installed")}catch{m.text="Installing Codex CLI...";try{await new Promise((y,g)=>{pe("npm",["install","-g","@openai/codex"],{stdio:"pipe"}).on("close",$=>{$===0?(m.succeed("Codex CLI installed!"),y()):g(new Error("npm install -g @openai/codex failed"))})})}catch{m.fail("Could not install Codex CLI"),console.log(c.yellow(` Install manually: npm install -g @openai/codex
|
|
138
|
+
`))}}}if(i.agent==="gemini"&&!e.skipInstall){let m=X("Checking Gemini CLI...").start();try{be("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),m.succeed("Gemini CLI already installed")}catch{m.text="Installing Gemini CLI...";try{await new Promise((y,g)=>{pe("npm",["install","-g","@google/gemini-cli"],{stdio:"pipe"}).on("close",$=>{$===0?(m.succeed("Gemini CLI installed!"),y()):g(new Error("npm install -g @google/gemini-cli failed"))})})}catch{m.fail("Could not install Gemini CLI"),console.log(c.yellow(` Install manually: npm install -g @google/gemini-cli
|
|
139
|
+
`))}}if(o){let y=X("Configuring Gemini MCP servers...").start();try{let g=f(Q(),".gemini"),v=f(g,"settings.json");A(g)||await U(g,{recursive:!0});let $={mcpServers:{}};if(A(v))try{let de=await L(v,"utf-8");$=JSON.parse(de),$.mcpServers||($.mcpServers={})}catch{}let I;try{let{createRequire:de}=await import("module");I=de(import.meta.url).resolve("@zibby/mcp-browser/bin/mcp-browser-zibby.js")}catch{I="@playwright/mcp"}let H=i.browserMode!=="headless",M=I==="@playwright/mcp"?["-y","@playwright/mcp","--isolated","--viewport-size=1280x720","--output-dir","test-results"]:[I,"--isolated","--viewport-size=1280x720","--output-dir=test-results"];H||M.push("--headless"),$.mcpServers["playwright-official"]={command:I==="@playwright/mcp"?"npx":"node",args:M},await z(v,`${JSON.stringify($,null,2)}
|
|
140
|
+
`,"utf-8");let ue="Gemini MCP configured";H?ue+=" (headed mode - visible browser)":ue+=" (headless mode - hidden browser)",y.succeed(ue)}catch(g){y.fail("MCP setup failed"),console.log(c.yellow(" You may need to configure ~/.gemini/settings.json manually")),console.log(c.gray(` Error: ${g.message}
|
|
141
|
+
`))}}}if(i.agent==="cursor"&&i.setupMcp&&o){let m=X("Setting up Playwright MCP...").start();try{let{setupPlaywrightMcpCommand:y}=await Promise.resolve().then(()=>(qt(),Vt)),g=i.cloudSync||!1,v=i.browserMode!=="headless";await y({headed:v,cloudSync:g,viewport:{width:1280,height:720}});let $="Playwright MCP configured";v?$+=" (headed mode - visible browser)":$+=" (headless mode - hidden browser)",g&&($+=" + Zibby MCP (cloud sync)"),m.succeed($),g&&!(i.apiKey&&i.apiKey.trim())&&console.log(c.gray(`
|
|
142
142
|
Copy .env.example to .env and set ZIBBY_API_KEY to enable uploads
|
|
143
|
-
`))}catch(
|
|
144
|
-
`)),console.log(
|
|
145
|
-
`))}}console.log(
|
|
143
|
+
`))}catch(y){m.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
|
|
144
|
+
`)),console.log(c.gray(` Error: ${y.message}
|
|
145
|
+
`))}}console.log(c.bold.green(`
|
|
146
146
|
All set!
|
|
147
|
-
`)),
|
|
148
|
-
`))),o?(console.log(
|
|
149
|
-
`)),console.log(
|
|
150
|
-
`))):(console.log(
|
|
151
|
-
`)),console.log(
|
|
152
|
-
Error: ${
|
|
153
|
-
`)),process.exit(1)}}function ke(t,e={},o={}){let
|
|
154
|
-
auth: '${t.agentAuth}', // 'oauth' (subscription) or 'api' (pay-per-token); cloud needs 'api'`:"",
|
|
147
|
+
`)),u&&(console.log(c.cyan("Get into the project:")),console.log(c.white(` cd ${t}
|
|
148
|
+
`))),o?(console.log(c.cyan("Run a test:")),console.log(c.white(` zibby test test-specs/examples/example-domain.txt
|
|
149
|
+
`)),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")}
|
|
150
|
+
`))):(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")}
|
|
151
|
+
`)),console.log(c.cyan("Cloud features (optional):")),console.log(c.white(` zibby login ${c.gray("# unlock workflow deploy, hosted memory, etc.")}`)),console.log(""))}catch(x){h.fail("Failed to create project"),console.error(c.red(`
|
|
152
|
+
Error: ${x.message}
|
|
153
|
+
`)),process.exit(1)}}function ke(t,e={},o={}){let r=["dolt","mem0"].includes(String(o.memoryBackend||"").toLowerCase())?String(o.memoryBackend).toLowerCase():"mem0",n=o.memoryInfer===!0,s=t.agentAuth==="oauth"||t.agentAuth==="api"?`
|
|
154
|
+
auth: '${t.agentAuth}', // 'oauth' (subscription) or 'api' (pay-per-token); cloud needs 'api'`:"",l={claude:`
|
|
155
155
|
claude: {
|
|
156
156
|
model: 'auto', // Options: 'auto', 'sonnet-4.6', 'opus-4.6', 'sonnet-4.5', 'opus-4.5'
|
|
157
|
-
maxTokens: 4096,${t.agent==="claude"?
|
|
157
|
+
maxTokens: 4096,${t.agent==="claude"?s:""}
|
|
158
158
|
},`,cursor:`
|
|
159
159
|
cursor: {
|
|
160
|
-
model: 'auto', // Options: 'auto', 'opus-4.5', 'opus-4.5-thinking', 'sonnet-4.5', 'sonnet-4.5-thinking', 'composer-1', 'gpt-5.2-codex', 'gpt-5.2', 'gpt-5.3', 'gpt-5.4', 'gemini-3-pro', 'gemini-3-flash'${t.agent==="cursor"?
|
|
160
|
+
model: 'auto', // Options: 'auto', 'opus-4.5', 'opus-4.5-thinking', 'sonnet-4.5', 'sonnet-4.5-thinking', 'composer-1', 'gpt-5.2-codex', 'gpt-5.2', 'gpt-5.3', 'gpt-5.4', 'gemini-3-pro', 'gemini-3-flash'${t.agent==="cursor"?s:""}
|
|
161
161
|
},`,codex:`
|
|
162
162
|
codex: {
|
|
163
|
-
model: 'gpt-5.2-codex', // Options: 'auto', 'o4-mini', 'o3', 'codex-mini', 'gpt-4o', 'gpt-5.2-codex', 'gpt-5.2', 'gpt-5.3', 'gpt-5.4'${t.agent==="codex"?
|
|
163
|
+
model: 'gpt-5.2-codex', // Options: 'auto', 'o4-mini', 'o3', 'codex-mini', 'gpt-4o', 'gpt-5.2-codex', 'gpt-5.2', 'gpt-5.3', 'gpt-5.4'${t.agent==="codex"?s:""}
|
|
164
164
|
},`,gemini:`
|
|
165
165
|
gemini: {
|
|
166
|
-
model: 'gemini-2.5-pro', // Options: 'auto', 'gemini-2.5-pro', 'gemini-2.5-flash'${t.agent==="gemini"?
|
|
167
|
-
},`},
|
|
168
|
-
`).map(
|
|
166
|
+
model: 'gemini-2.5-pro', // Options: 'auto', 'gemini-2.5-pro', 'gemini-2.5-flash'${t.agent==="gemini"?s:""}
|
|
167
|
+
},`},d=t.agent,u=Object.entries(l).filter(([i])=>i!==d).map(([,i])=>i.split(`
|
|
168
|
+
`).map(b=>b.trim()?` // ${b.trimStart()}`:b).join(`
|
|
169
169
|
`)).join(`
|
|
170
170
|
`);return`export default {
|
|
171
171
|
// AI agent settings
|
|
172
|
-
agent: {${
|
|
173
|
-
${
|
|
172
|
+
agent: {${l[d]}
|
|
173
|
+
${u}
|
|
174
174
|
strictMode: false,
|
|
175
175
|
},
|
|
176
176
|
|
|
@@ -183,7 +183,11 @@ ${c}
|
|
|
183
183
|
|
|
184
184
|
// Chat memory backend adapter (dolt | mem0)
|
|
185
185
|
memory: {
|
|
186
|
-
backend: '${
|
|
186
|
+
backend: '${r}',
|
|
187
|
+
// Smart memory (mem0 only): true = LLM distills/dedupes facts on store
|
|
188
|
+
// (costs tokens); false = store raw, embed-only, free. Default false.
|
|
189
|
+
// Env override: ZIBBY_MEM0_INFER=true
|
|
190
|
+
infer: ${n},
|
|
187
191
|
},
|
|
188
192
|
|
|
189
193
|
// UI-test memory remote sync \u2014 declarative team configuration.
|
|
@@ -253,7 +257,11 @@ ${c}
|
|
|
253
257
|
// Cloud sync - auto-upload test results & videos (requires ZIBBY_API_KEY in .env)
|
|
254
258
|
cloudSync: ${t.cloudSync||!1}
|
|
255
259
|
};
|
|
256
|
-
`}function
|
|
260
|
+
`}function Xt(t){return t?`# Smart memory: LLM distills/dedupes facts on store (mem0; costs tokens). false = embed-only, free.
|
|
261
|
+
ZIBBY_MEM0_INFER=true
|
|
262
|
+
`:`# Smart memory: set true to let the LLM distill/dedupe facts on store (mem0; costs tokens). Default off = embed-only, free.
|
|
263
|
+
# ZIBBY_MEM0_INFER=false
|
|
264
|
+
`}function Bn(t,e="mem0",o=!1){return`# Zibby Test Automation - Environment Variables
|
|
257
265
|
|
|
258
266
|
# AI Provider Keys
|
|
259
267
|
${{claude:"ANTHROPIC_API_KEY=sk-ant-your_key_here",cursor:`# Cursor Agent uses cursor-agent CLI \u2014 no API key needed
|
|
@@ -270,7 +278,7 @@ ${{claude:"ANTHROPIC_API_KEY=sk-ant-your_key_here",cursor:`# Cursor Agent uses c
|
|
|
270
278
|
|
|
271
279
|
# Chat memory backend
|
|
272
280
|
ZIBBY_MEMORY_BACKEND=${e}
|
|
273
|
-
`}function
|
|
281
|
+
${Xt(o)}`}function Ln(t,e,o="mem0",r=!1){return`# Zibby Test Automation - Environment Variables
|
|
274
282
|
|
|
275
283
|
# AI Provider Keys
|
|
276
284
|
${{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"}[t.agent]||""}
|
|
@@ -285,7 +293,7 @@ ZIBBY_API_KEY=${e}
|
|
|
285
293
|
|
|
286
294
|
# Chat memory backend
|
|
287
295
|
ZIBBY_MEMORY_BACKEND=${o}
|
|
288
|
-
`}function
|
|
296
|
+
${Xt(r)}`}function Kn(t,e,o={}){let n={"@zibby/cli":"latest","@zibby/core":Tn("../../package.json").dependencies?.["@zibby/core"]||"latest"};return o.memoryBackend==="mem0"&&(n.mem0ai="npm:@zibby/mem0ai@^3.0.5",n["better-sqlite3"]="^12.6.2"),JSON.stringify({name:t,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 Dn(){return`# Dependencies
|
|
289
297
|
node_modules/
|
|
290
298
|
|
|
291
299
|
# Test artifacts
|
|
@@ -313,7 +321,7 @@ Thumbs.db
|
|
|
313
321
|
# Zibby memory (Dolt DB synced separately via dolt remote, not git)
|
|
314
322
|
.zibby/memory/
|
|
315
323
|
.zibby/memory-context.md
|
|
316
|
-
`}function
|
|
324
|
+
`}function Un(t="off",e=null){return`import { defineConfig} from '@playwright/test';
|
|
317
325
|
|
|
318
326
|
export default defineConfig({
|
|
319
327
|
testDir: './tests',
|
|
@@ -335,7 +343,7 @@ ${e?` outputDir: '${e}',
|
|
|
335
343
|
['list']
|
|
336
344
|
],
|
|
337
345
|
});
|
|
338
|
-
`}function
|
|
346
|
+
`}function Yn(){return`Test Specification: Example Domain Navigation
|
|
339
347
|
==============================================
|
|
340
348
|
|
|
341
349
|
Application: Example Domain
|
|
@@ -372,7 +380,7 @@ Notes:
|
|
|
372
380
|
- Uses a stable, public domain (example.com) maintained by IANA
|
|
373
381
|
- No authentication required
|
|
374
382
|
- Suitable for CI/CD smoke testing
|
|
375
|
-
`}function
|
|
383
|
+
`}function Fn(){return`# Example command template
|
|
376
384
|
|
|
377
385
|
Use this command when the user asks for a concise testing task breakdown.
|
|
378
386
|
|
|
@@ -383,7 +391,7 @@ Required output format:
|
|
|
383
391
|
4. Expected result
|
|
384
392
|
|
|
385
393
|
Keep the response actionable and short.
|
|
386
|
-
`}function
|
|
394
|
+
`}function Hn(t,e){return`# ${t}
|
|
387
395
|
|
|
388
396
|
AI-powered test automation with Zibby.
|
|
389
397
|
|
|
@@ -472,24 +480,24 @@ ${t}/
|
|
|
472
480
|
|
|
473
481
|
- Documentation: https://docs.zibby.dev
|
|
474
482
|
- Examples: https://github.com/zibby/examples
|
|
475
|
-
`}var
|
|
483
|
+
`}var On,Jt,Tn,Ye=W(()=>{tt();On=zn(import.meta.url),Jt=En(On),Tn=jn(import.meta.url)});import{mkdir as Ze,writeFile as V,readFile as ar,readdir as lr}from"fs/promises";import{existsSync as me}from"fs";import{spawn as cr}from"child_process";import{join as j}from"path";import p from"chalk";import ro from"ora";import{input as so}from"@inquirer/prompts";import{existsSync as go}from"fs";import{join as fo}from"path";import{pathToFileURL as yo}from"url";async function qe(t){let e=fo(t,".zibby.config.mjs");if(!go(e))throw new Error(".zibby.config.mjs not found");try{let o=await import(yo(e).href);return o.default||o}catch(o){throw new Error(`Failed to load .zibby.config.mjs: ${o.message}`,{cause:o})}}Ye();import{readFileSync as re,existsSync as F,mkdirSync as Fe,writeFileSync as se,statSync as Wn,chmodSync as Zn}from"fs";import{join as T,dirname as $e}from"path";import{fileURLToPath as Gn}from"url";import Y from"chalk";var ce=["claude","cursor","codex"],Vn=$e(Gn(import.meta.url)),He=T(Vn,"..","..","..","templates","zibby-workflow-claude"),qn="<!-- BEGIN zibby-workflows",eo="<!-- END zibby-workflows -->";function Jn(t){let e=process.argv[1];if(!e||!F(e))return null;let o=T(t,".zibby","bin"),r=T(o,"zibby");Fe(o,{recursive:!0});let n=`#!/bin/sh
|
|
476
484
|
# Auto-generated by 'zibby workflow generate'. Re-runs of generate update this path.
|
|
477
485
|
# Lets agents (Claude / Cursor / Codex) and CI scripts call zibby reliably even
|
|
478
486
|
# when the CLI isn't on PATH. Delete this file or .zibby/bin/ to disable.
|
|
479
487
|
exec node ${JSON.stringify(e)} "$@"
|
|
480
|
-
`;
|
|
481
|
-
`;if(!
|
|
488
|
+
`;se(r,n);try{Wn(r)}catch{}try{Zn(r,493)}catch{}return r}function Xn(){let t=T(He,"manifest.json");return JSON.parse(re(t,"utf8"))}function to(t){let e=t.match(/<!--\s*(?:BEGIN zibby-workflows\s+)?zibby-template-version:\s*(\d+)\s*-->/);return e?parseInt(e[1],10):null}function Qn(t,e,o){if(!F(t))return{write:!0,reason:"new"};if(o)return{write:!0,reason:"force"};let r=re(t,"utf8"),n=to(r),s=to(e);return n==null?{write:!1,reason:"user-edited (no version marker)"}:s==null?{write:!1,reason:"shipped file has no version (skipping for safety)"}:n>s?{write:!1,reason:`current version ${n} > shipped ${s}`}:{write:!0,reason:n===s?"same version, refresh":`upgrade ${n} \u2192 ${s}`}}function er(t,e){let o=`${e.trim()}
|
|
489
|
+
`;if(!F(t))return se(t,o),"created";let r=re(t,"utf8"),n=r.indexOf(qn),s=r.indexOf(eo);if(n!==-1&&s!==-1&&s>n){let d=r.slice(0,n),u=r.slice(s+eo.length),i=d+o.trim()+u;return i===r?"unchanged":(se(t,i),"updated")}let l=r.endsWith(`
|
|
482
490
|
`)?`
|
|
483
491
|
`:`
|
|
484
492
|
|
|
485
|
-
`;return
|
|
493
|
+
`;return se(t,r+l+o),"appended"}function tr(t,e,o,r){let n=o.agents[t];if(!n)return[];let s=[],l=d=>T(He,d.split("/").map(u=>u.startsWith(".")?u.slice(1):u).join("/"));for(let d of n.files||[]){let u=l(d);if(!F(u))continue;let i=re(u,"utf8"),b=T(e,d),k=Qn(b,i,r);k.write?(Fe($e(b),{recursive:!0}),se(b,i),s.push({path:d,action:"write",detail:k.reason})):s.push({path:d,action:"skip",detail:k.reason})}for(let d of n.writeOnceFiles||[]){let u=l(d);if(!F(u))continue;let i=T(e,d);if(F(i)){s.push({path:d,action:"skip",detail:"write-once: already exists, leaving alone"});continue}Fe($e(i),{recursive:!0}),se(i,re(u,"utf8")),s.push({path:d,action:"write",detail:"write-once: created"})}if(n.rootBlock){let d=T(He,n.rootBlock.source),u=re(d,"utf8"),i=T(e,n.rootBlock.target),b=er(i,u);s.push({path:n.rootBlock.target,action:b})}return s}function or(t){let e=t;for(let o=0;o<6;o++){if(F(T(e,".git"))||F(T(e,".zibby.config.mjs"))||F(T(e,"package.json")))return e;let r=$e(e);if(r===e)break;e=r}return t}async function nr(t){let e=T(t,".zibby.config.mjs");if(!F(e))return null;try{return((await import(`file://${e}?t=${Date.now()}`)).default||{}).agentHelpers||null}catch(o){return console.log(Y.gray(` (couldn't parse .zibby.config.mjs agentHelpers section: ${o.message})`)),null}}function rr(t,e){let o=T(t,".zibby.config.mjs");if(!F(o)){console.log(Y.yellow(" \u26A0\uFE0F .zibby.config.mjs not found; agentHelpers state not persisted"));return}let r=re(o,"utf8"),n=` agentHelpers: {
|
|
486
494
|
templateVersion: ${e.templateVersion},
|
|
487
495
|
agents: ${JSON.stringify(e.agents)},
|
|
488
496
|
updatedAt: '${new Date().toISOString()}',
|
|
489
497
|
},
|
|
490
|
-
`,
|
|
491
|
-
${n}`);else{let
|
|
492
|
-
`:"")+n+
|
|
498
|
+
`,s=/\s*agentHelpers\s*:\s*\{[^}]*\}\s*,?\n?/m,l;if(s.test(r))l=r.replace(s,`
|
|
499
|
+
${n}`);else{let d=r.lastIndexOf("}");if(d===-1)return;let u=r.slice(0,d),i=u.replace(/\s+$/,"").slice(-1);l=u+(i&&i!==","&&i!=="{"?`,
|
|
500
|
+
`:"")+n+r.slice(d)}se(o,l)}function sr(t){if(t===!0)return["claude"];if(typeof t!="string")throw new Error(`agent-helpers flag value must be a string or true, got ${typeof t}`);let e=t.split(",").map(o=>o.trim()).filter(Boolean);if(e.length===0)return["claude"];if(e.length===1&&e[0]==="all")return[...ce];if(e.length===1&&e[0]==="none")return["none"];for(let o of e)if(!ce.includes(o))throw new Error(`unknown agent "${o}" \u2014 supported: ${ce.join(", ")}`);return Array.from(new Set(e))}function ir({agentHelpersFlag:t,noAgentHelpers:e,existingConfig:o,legacyAgent:r}={}){if(e===!0)return{install:!1,reason:"explicit-no"};if(t!==void 0&&t!==!1){let n=sr(t);return n.length===1&&n[0]==="none"?{install:!1,reason:"explicit-no"}:{install:!0,agents:n}}if(r){if(r==="none")return{install:!1,reason:"explicit-no"};if(r==="all")return{install:!0,agents:[...ce]};if(!ce.includes(r))throw new Error(`unknown agent "${r}" \u2014 supported: ${ce.join(", ")}`);return{install:!0,agents:[r]}}if(o&&Array.isArray(o.agents)&&o.agents.length>0){let n=o.agents.filter(s=>s!=="none");return n.length>0?{install:!0,agents:n,fromConfig:!0}:{install:!1,reason:"explicit-no"}}return{install:!1,reason:"no-config"}}async function oo(t={}){let{forcedAgents:e,force:o=!1,silent:r=!1}=t,n=t.projectRoot||or(process.cwd()),s=Xn(),l=await nr(n),d;if(e&&e.length>0?e.length===1&&e[0]==="none"?d={install:!1,reason:"explicit-no"}:d={install:!0,agents:e}:d=ir({agentHelpersFlag:t.agentHelpersFlag,noAgentHelpers:t.noAgentHelpers===!0,existingConfig:l,legacyAgent:t.legacyAgent}),!d.install)return d.reason==="explicit-no"?(t.noAgentHelpers===!0||t.legacyAgent==="none"||e&&e.length===1&&e[0],{action:"skipped-explicit-no"}):{action:"skipped-no-config"};let u=d.agents,i=Jn(n),b=[];for(let k of u){if(!s.agents[k])continue;tr(k,n,s,o).forEach(x=>b.push({...x,agent:k}))}if(rr(n,{templateVersion:s.templateVersion,agents:u}),!r){d.fromConfig&&console.log(Y.gray(` agent helpers: ${u.join(", ")} (from .zibby.config.mjs)`));let k=b.filter(w=>["write","created","updated","appended"].includes(w.action)),h=b.filter(w=>w.action==="skip"),x=b.filter(w=>w.action==="unchanged");if(k.length>0){console.log(Y.green(` \u2713 Wrote ${k.length} agent helper file(s):`));for(let w of k)console.log(Y.gray(` ${w.path} (${w.detail||w.action})`))}if(h.length>0){console.log(Y.yellow(` \u26A0\uFE0F Skipped ${h.length} (use --force-agents to overwrite):`));for(let w of h)console.log(Y.gray(` ${w.path} \u2014 ${w.detail}`))}k.length===0&&h.length===0&&x.length>0&&console.log(Y.gray(` Agent helpers up to date (template v${s.templateVersion}).`)),d.fromConfig||console.log(Y.gray(` agentHelpers: { agents: [${u.map(w=>`"${w}"`).join(", ")}] } saved to .zibby.config.mjs`)),i&&console.log(Y.gray(` CLI shim: ${i} (agents fall back to ./.zibby/bin/zibby if zibby isn't on PATH)`)),u.includes("claude")&&console.log(Y.gray(" \u2192 Run `claude` and try /zibby-add-node"))}return{action:d.fromConfig?"installed-from-config":"installed",agents:u}}var ie=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/;function no(t){if(typeof t!="string"||t.length===0)return{valid:!1,reason:"Name is required",suggestion:null};if(t.length<2)return{valid:!1,reason:"Name must be at least 2 characters",suggestion:null};if(t.length>64)return{valid:!1,reason:"Name must be at most 64 characters",suggestion:null};if(ie.test(t))return{valid:!0,reason:null,suggestion:null};let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");return{valid:!1,reason:"Name must be lowercase, start with a letter, end with a letter or digit, and use only a-z, 0-9, and hyphens",suggestion:ie.test(e)?e:null}}function We(t,e){let o=e instanceof Set?e:new Set(e||[]);if(!o.has(t))return t;let r=t.match(/^(.+)-(\d+)$/),n=r?r[1]:t;for(let s=2;s<=99;s+=1){let l=`${n}-${s}`;if(ie.test(l)&&!o.has(l))return l}return null}function ur(t){return new Promise(e=>{let o=cr("npm",["install","--no-audit","--no-fund"],{cwd:t,stdio:"pipe",shell:!1}),r="";o.stderr.on("data",n=>{r+=n.toString()}),o.on("error",()=>e({ok:!1,stderr:"npm not found on PATH"})),o.on("close",n=>e({ok:n===0,stderr:r}))})}var dr=ie;async function pr(t){try{let e=await import(`@zibby/workflow-templates/${t}/workflow.json`,{with:{type:"json"}}),o=e?.default||e,r=o?.defaultSlug||o?.name;return typeof r=="string"&&ie.test(r)?r:null}catch{return null}}var io=["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"],ao=["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 lo(){let t=io[Math.floor(Math.random()*io.length)],e=ao[Math.floor(Math.random()*ao.length)];return`${t}-${e}`}function mr(t){return`${t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}Workflow`}function po(t){return`${t.split("-").map((o,r)=>r===0?o:o.charAt(0).toUpperCase()+o.slice(1)).join("")}StateSchema`}function gr(t,e){let o=po(e);return`/**
|
|
493
501
|
* ${t}
|
|
494
502
|
*
|
|
495
503
|
* buildGraph() \u2014 define nodes, edges, conditional routing
|
|
@@ -522,7 +530,7 @@ export class ${t} extends WorkflowAgent {
|
|
|
522
530
|
console.log(\`[${e}] workflow complete \u2014 success: \${result.success !== false}\`);
|
|
523
531
|
}
|
|
524
532
|
}
|
|
525
|
-
`}function
|
|
533
|
+
`}function fr(t){return`/**
|
|
526
534
|
* Input state schema for this workflow.
|
|
527
535
|
*
|
|
528
536
|
* Declares the user-input fields callers can pass via:
|
|
@@ -546,7 +554,7 @@ export class ${t} extends WorkflowAgent {
|
|
|
546
554
|
|
|
547
555
|
import { z } from 'zod';
|
|
548
556
|
|
|
549
|
-
export const ${
|
|
557
|
+
export const ${po(t)} = z.object({
|
|
550
558
|
// Add user-input fields here. Examples:
|
|
551
559
|
//
|
|
552
560
|
// url: z.string().url().describe('Page to test'),
|
|
@@ -555,8 +563,8 @@ export const ${co(t)} = z.object({
|
|
|
555
563
|
//
|
|
556
564
|
// Then read them in any node via state.url / state.count / state.tags.
|
|
557
565
|
});
|
|
558
|
-
`}function
|
|
559
|
-
`}function
|
|
566
|
+
`}function yr(){return`export { exampleNode } from './example.mjs';
|
|
567
|
+
`}function hr(){return`import { z } from '@zibby/core';
|
|
560
568
|
|
|
561
569
|
const ExampleOutputSchema = z.object({
|
|
562
570
|
summary: z.string().describe('A short summary of the result'),
|
|
@@ -583,29 +591,29 @@ Analyze the input and return a summary with a status.\`,
|
|
|
583
591
|
|
|
584
592
|
outputSchema: ExampleOutputSchema,
|
|
585
593
|
};
|
|
586
|
-
`}function
|
|
587
|
-
`}var
|
|
594
|
+
`}function co(t,e){return`${JSON.stringify({name:t,description:`${e} workflow`,entryClass:e,triggers:{api:!0}},null,2)}
|
|
595
|
+
`}var wr=new Set(["cwd","sessionPath","outputPath","context","input"]);async function br(t){try{let e=await ar(j(t,"graph.mjs"),"utf-8"),o=new Set,r=/addNode\(\s*['"`]([A-Za-z_][\w-]*)['"`]/g,n;for(;(n=r.exec(e))!==null;)o.add(n[1]);return o}catch{return new Set}}async function kr(t){try{let e=await import(`@zibby/workflow-templates/${t}/state.js`),o=d=>{if(!d||typeof d!="object")return!1;try{let u=d.shape;return u&&typeof u=="object"&&Object.keys(u).length>0}catch{return!1}},r=null,n=null,s=null;for(let[d,u]of Object.entries(e))o(u)&&(s||(s=u),!r&&/InputSchema$/.test(d)&&(r=u),!n&&/StateSchema$/.test(d)&&(n=u));let l=r||n||s;return l?{schema:l,shape:l.shape}:null}catch{return null}}function $r(t,e){try{let o=[],r=[];for(let[n,s]of Object.entries(t)){if(wr.has(n)||e.has(n))continue;let l=!1;try{l=s?.isOptional?.()===!0}catch{}l?r.push(n):o.push(n)}return{required:o,optional:r}}catch{return null}}async function vr(t,e,o){let r=null;if(e)try{let n=await kr(e);if(n){let s=await br(o);r=$r(n.shape,s)}}catch{r=null}if(console.log(p.white(" Pass inputs:")),r&&r.required.length+r.optional.length>0){let{required:n,optional:s}=r,l=n[0]||s[0],d=`<${l}>`;console.log(p.gray(` ${p.white(`zibby workflow run ${t} -p ${l}="${d}"`)}`));let u=[...n.slice(0,3),...s.slice(0,1)],i={};for(let h of u)h==="model"?i[h]="opus-4.6":i[h]=`<${h}>`;console.log(p.gray(` ${p.white(`zibby workflow run ${t} --input '${JSON.stringify(i)}'`)}`)),console.log(p.gray(` ${p.white(`zibby workflow run ${t} --input-file inputs.json`)}`)),console.log(p.gray(` Same flags work on ${p.white("zibby workflow trigger <uuid>")} for cloud runs.`));let b=u,k=b.length>0?`${b.map(h=>p.white(`state.${h}`)).join(", ")}, etc`:p.white("state.<field>");console.log(p.gray(` Inside any node, read ${k} \u2014 top-level.`)),console.log(p.gray(` See workflows/${t}/state.js for the full input schema.
|
|
588
596
|
`))}else console.log(p.gray(` ${p.white(`zibby workflow run ${t} -p name=alice -p count=5`)}`)),console.log(p.gray(` ${p.white(`zibby workflow run ${t} --input '{"url":"https://example.com"}'`)}`)),console.log(p.gray(` ${p.white(`zibby workflow run ${t} --input-file inputs.json`)}`)),console.log(p.gray(` Same flags work on ${p.white("zibby workflow trigger <uuid>")} for cloud runs.`)),console.log(p.gray(` Inside your node, read ${p.white("state.name")}, ${p.white("state.count")}, etc \u2014 top-level.
|
|
589
|
-
`))}function
|
|
590
|
-
`}async function
|
|
597
|
+
`))}function uo(t){let e={"@zibby/core":"^0.3.0",...t};return`${JSON.stringify({type:"module",dependencies:e},null,2)}
|
|
598
|
+
`}async function Ss(t,e={}){if(!e.skipInitCheck){let{homedir:w}=await import("os"),S=process.env.ZIBBY_CONFIG_DIR?j(process.env.ZIBBY_CONFIG_DIR,"config.json"):j(w(),".zibby","config.json");if(!me(S)){console.log(p.gray(`
|
|
591
599
|
Looks like first run on this machine \u2014 let's do a quick setup so the
|
|
592
600
|
scaffolded workflow can actually run. (Skip with --skip-init-check.)
|
|
593
|
-
`));let{initCommand:
|
|
594
|
-
Init failed: ${
|
|
595
|
-
`)),console.log(p.gray(" Run `zibby init` manually, then re-run this command.\n")),process.exit(1)}}}let o=e.template&&String(e.template).trim();async function
|
|
596
|
-
No name provided \u2014 generated: ${p.white(n)}`));
|
|
601
|
+
`));let{initCommand:C}=await Promise.resolve().then(()=>(Ye(),Qt));try{await C(void 0,{...e,template:void 0})}catch(E){console.log(p.red(`
|
|
602
|
+
Init failed: ${E.message}
|
|
603
|
+
`)),console.log(p.gray(" Run `zibby init` manually, then re-run this command.\n")),process.exit(1)}}}let o=e.template&&String(e.template).trim();async function r(){let w=new Set;for(let S of["workflows",".zibby/workflows"])try{let C=await lr(j(process.cwd(),S),{withFileTypes:!0});for(let E of C)E.isDirectory()&&ie.test(E.name)&&w.add(E.name)}catch{}return w}let n;if(t)n=t.toLowerCase();else if(o&&process.stdin.isTTY&&!e.skipInitCheck){let w=await r(),S=await pr(o),C=S?We(S,w)||S:lo(),_=(await so({message:`Name this workflow ${p.gray(`[Enter for ${C}]`)}`,validate:K=>{let N=(K||"").trim();if(N==="")return!0;let Z=no(N);if(!Z.valid)return Z.reason+(Z.suggestion?` \u2014 try "${Z.suggestion}"`:"");if(w.has(N)){let ee=We(N,w);return ee?`Already exists locally \u2014 try "${ee}"`:"Already exists locally \u2014 pick a different name"}return!0}})||"").trim();n=_===""?C:_.toLowerCase()}else n=lo(),console.log(p.gray(`
|
|
604
|
+
No name provided \u2014 generated: ${p.white(n)}`));dr.test(n)||(console.log(p.red(`
|
|
597
605
|
Invalid workflow name: "${t||n}"`)),console.log(p.gray(" Must be lowercase, start with a letter, use only a-z, 0-9, hyphens")),console.log(p.gray(" Length: 2\u201364 characters")),console.log(p.gray(` Example: ticket-triage, pr-review, deploy-checker
|
|
598
|
-
`)),process.exit(1));let
|
|
606
|
+
`)),process.exit(1));let s=process.cwd(),l=j(s,".zibby.config.mjs"),d=me(l),u="workflows";if(d)try{let w=await qe(s);w?.paths?.workflows&&(u=w.paths.workflows)}catch(w){console.log(p.yellow(` \u26A0\uFE0F Could not load .zibby.config.mjs: ${w.message}`)),console.log(p.gray(` Using default path: ${u}`))}else if(process.stdin.isTTY){console.log(p.gray(`
|
|
599
607
|
Common picks: ${p.white("workflows")} (visible at project root, default) \xB7 ${p.white(".zibby/workflows")} (hidden under runtime dir)
|
|
600
|
-
`));let
|
|
601
|
-
Workflow already exists: ${
|
|
602
|
-
`)),process.exit(1));let k=
|
|
603
|
-
Created:`)),console.log(p.white(` ${
|
|
604
|
-
`)[0]||"unknown error"})`),console.log(p.gray(` Run manually: cd ${
|
|
605
|
-
${
|
|
606
|
-
`)),process.exit(1)),console.log(p.yellow(` \u26A0\uFE0F Agent helpers setup failed: ${
|
|
607
|
-
Next steps:`));let
|
|
608
|
-
`)),await
|
|
609
|
-
`)))}catch(
|
|
610
|
-
${
|
|
611
|
-
`)),process.exit(1)}}export{
|
|
608
|
+
`));let S=(await so({message:`Where to save workflows? ${p.gray("[Enter for workflows]")}`})).trim();u=S===""?"workflows":S}else console.log(p.gray(` Using default workflows path: ${u} (run interactively to customize)`));let i=j(s,u,n),b=j(i,"nodes");me(i)&&(console.log(p.red(`
|
|
609
|
+
Workflow already exists: ${u}/${n}/`)),console.log(p.gray(` Choose a different name or delete the existing folder.
|
|
610
|
+
`)),process.exit(1));let k=mr(n),h=o,x=ro(h?` Scaffolding workflow "${n}" from template ${p.cyan(h)}...`:` Scaffolding workflow "${n}"...`).start();try{if(await Ze(j(s,u),{recursive:!0}),h){let{writeTemplateFilesToDir:_}=await Promise.resolve().then(()=>(Se(),Ae));await Ze(i,{recursive:!0});let{template:K}=await _(i,h);me(j(i,"workflow.json"))||await V(j(i,"workflow.json"),co(n,k)),me(j(i,"package.json"))||await V(j(i,"package.json"),uo(K?.deps||{}))}else await Ze(b,{recursive:!0}),await Promise.all([V(j(i,"graph.mjs"),gr(k,n)),V(j(i,"state.js"),fr(n)),V(j(b,"index.mjs"),yr()),V(j(b,"example.mjs"),hr()),V(j(i,"workflow.json"),co(n,k)),V(j(i,"package.json"),uo({zod:"^3.23.0"}))]);let w=!1;if(!d){let _=ke({agent:"claude",browserMode:"headless",workflowsPath:u},{},{memoryBackend:"dolt"});await V(l,_),w=!0}x.succeed(h?` Scaffolded ${p.bold(n)} from template ${p.cyan(h)}`:` Scaffolded ${p.bold(n)}`),console.log(p.green(`
|
|
611
|
+
Created:`)),console.log(p.white(` ${u}/${n}/`)),h?(console.log(p.gray(` graph.mjs (from template ${h})`)),console.log(p.gray(` nodes/ (from template ${h})`)),console.log(p.gray(" workflow.json manifest")),console.log(p.gray(" package.json dependencies (@zibby/core)"))):(console.log(p.gray(` graph.mjs ${k} (entry)`)),console.log(p.gray(" state.js input schema (Zod) \u2014 declare your fields here")),console.log(p.gray(" nodes/index.mjs barrel export")),console.log(p.gray(" nodes/example.mjs starter node (prompt + schema)")),console.log(p.gray(" workflow.json manifest")),console.log(p.gray(" package.json dependencies (@zibby/core, zod)"))),w&&console.log(p.white(" .zibby.config.mjs project config (agent: claude \u2014 edit to switch)"));let S=!1;if(e.skipInstall)console.log(p.gray(` Skipped npm install (--skip-install). Run manually: cd ${u}/${n} && npm install`));else{let _=ro({text:` Installing dependencies in ${u}/${n}/...`,prefixText:""}).start(),K=await ur(i);K.ok?(_.succeed(` Installed dependencies in ${u}/${n}/`),S=!0):(_.warn(` Could not install dependencies (${K.stderr.trim().split(`
|
|
612
|
+
`)[0]||"unknown error"})`),console.log(p.gray(` Run manually: cd ${u}/${n} && npm install`)))}let C={action:"skipped-no-config"};try{C=await oo({projectRoot:s,agentHelpersFlag:e.agentHelpers,noAgentHelpers:e.agentHelpers===!1,legacyAgent:e.agent,force:e.forceClaude===!0||e.forceAgents===!0})||C}catch(_){/^unknown agent /.test(_.message)&&(console.log(p.red(`
|
|
613
|
+
${_.message}
|
|
614
|
+
`)),process.exit(1)),console.log(p.yellow(` \u26A0\uFE0F Agent helpers setup failed: ${_.message}`)),console.log(p.gray(" Run `zibby agents add` later to retry."))}console.log(p.white(`
|
|
615
|
+
Next steps:`));let E=1;!S&&e.skipInstall!==!0&&console.log(p.cyan(` ${E++}. Install deps: cd ${u}/${n} && npm install`)),console.log(p.cyan(` ${E++}. Edit nodes in ${u}/${n}/nodes/`)),console.log(p.cyan(` ${E++}. Wire them in graph.mjs`)),console.log(p.cyan(` ${E++}. Run locally: zibby workflow run ${n}`)),console.log(p.cyan(` ${E++}. Deploy to cloud: zibby workflow deploy ${n}
|
|
616
|
+
`)),await vr(n,h,i),C.action==="skipped-no-config"&&(console.log(p.gray(" Tip: Using Claude Code or Cursor? Set up slash commands + agent context:")),console.log(p.gray(" zibby workflow new <name> --agent-helpers claude")),console.log(p.gray(` (commits agentHelpers to .zibby.config.mjs \u2014 auto-applies to future workflows)
|
|
617
|
+
`)))}catch(w){x.fail(" Scaffold failed"),console.log(p.red(`
|
|
618
|
+
${w.message}
|
|
619
|
+
`)),process.exit(1)}}export{Ss as generateWorkflowCommand};
|