@zibby/cli 0.5.8 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/zibby.js +3 -3
- package/dist/commands/app-run.js +19 -0
- package/dist/commands/app-solo.js +19 -0
- package/dist/commands/app.js +22 -20
- package/dist/commands/init.js +100 -95
- package/dist/commands/workflows/generate.js +156 -151
- package/dist/config/soloTiers.js +1 -0
- package/dist/config/warmPool.js +1 -0
- package/dist/lib/api-client.js +17 -0
- package/dist/lib/find-app-link.js +2 -0
- package/dist/lib/framework-commands.js +1 -0
- package/dist/package.json +2 -2
- package/dist/templates/.claude/CLAUDE.md +318 -10
- package/dist/templates/.claude/agents/zibby-test-author.md +87 -0
- package/dist/templates/.claude/agents/zibby-workflow-builder.md +101 -0
- package/dist/templates/.claude/commands/{add-node.md → zibby-add-node.md} +1 -1
- package/dist/templates/.claude/commands/{add-skill.md → zibby-add-skill.md} +1 -1
- package/dist/templates/.claude/commands/zibby-app-destroy.md +60 -0
- package/dist/templates/.claude/commands/zibby-app-list.md +80 -0
- package/dist/templates/.claude/commands/zibby-app-logs.md +60 -0
- package/dist/templates/.claude/commands/zibby-app-status.md +53 -0
- package/dist/templates/.claude/commands/zibby-app-upgrade.md +67 -0
- package/dist/templates/.claude/commands/zibby-debug.md +67 -0
- package/dist/templates/.claude/commands/zibby-delete.md +37 -0
- package/dist/templates/.claude/commands/zibby-deploy-app.md +92 -0
- package/dist/templates/.claude/commands/zibby-deploy.md +87 -0
- package/dist/templates/.claude/commands/zibby-list.md +30 -0
- package/dist/templates/.claude/commands/zibby-login.md +68 -0
- package/dist/templates/.claude/commands/zibby-mcp-install.md +93 -0
- package/dist/templates/.claude/commands/zibby-memory-cost.md +39 -0
- package/dist/templates/.claude/commands/zibby-memory-pull.md +47 -0
- package/dist/templates/.claude/commands/zibby-memory-remote-use-hosted.md +61 -0
- package/dist/templates/.claude/commands/zibby-memory-stats.md +38 -0
- package/{templates/.claude/commands/new-workflow.md → dist/templates/.claude/commands/zibby-new-workflow.md} +1 -1
- package/dist/templates/.claude/commands/zibby-set-auth.md +85 -0
- package/dist/templates/.claude/commands/zibby-static-ip.md +70 -0
- package/dist/templates/.claude/commands/zibby-status.md +54 -0
- package/dist/templates/.claude/commands/zibby-tail.md +53 -0
- package/dist/templates/.claude/commands/zibby-test-debug.md +59 -0
- package/dist/templates/.claude/commands/zibby-test-generate.md +39 -0
- package/dist/templates/.claude/commands/zibby-test-run.md +49 -0
- package/dist/templates/.claude/commands/zibby-test-write.md +46 -0
- package/dist/templates/.claude/commands/zibby-trigger.md +56 -0
- package/{templates/.claude/commands/validate-workflow.md → dist/templates/.claude/commands/zibby-validate-workflow.md} +1 -1
- package/dist/templates/.cursor/rules/zibby.mdc +127 -0
- package/dist/templates/AGENTS.md +248 -0
- package/dist/utils/managed-block.js +6 -0
- package/package.json +2 -2
- package/templates/.claude/CLAUDE.md +318 -10
- package/templates/.claude/agents/zibby-test-author.md +87 -0
- package/templates/.claude/agents/zibby-workflow-builder.md +101 -0
- package/templates/.claude/commands/{add-node.md → zibby-add-node.md} +1 -1
- package/templates/.claude/commands/{add-skill.md → zibby-add-skill.md} +1 -1
- package/templates/.claude/commands/zibby-app-destroy.md +60 -0
- package/templates/.claude/commands/zibby-app-list.md +80 -0
- package/templates/.claude/commands/zibby-app-logs.md +60 -0
- package/templates/.claude/commands/zibby-app-status.md +53 -0
- package/templates/.claude/commands/zibby-app-upgrade.md +67 -0
- package/templates/.claude/commands/zibby-debug.md +67 -0
- package/templates/.claude/commands/zibby-delete.md +37 -0
- package/templates/.claude/commands/zibby-deploy-app.md +92 -0
- package/templates/.claude/commands/zibby-deploy.md +87 -0
- package/templates/.claude/commands/zibby-list.md +30 -0
- package/templates/.claude/commands/zibby-login.md +68 -0
- package/templates/.claude/commands/zibby-mcp-install.md +93 -0
- package/templates/.claude/commands/zibby-memory-cost.md +39 -0
- package/templates/.claude/commands/zibby-memory-pull.md +47 -0
- package/templates/.claude/commands/zibby-memory-remote-use-hosted.md +61 -0
- package/templates/.claude/commands/zibby-memory-stats.md +38 -0
- package/{dist/templates/.claude/commands/new-workflow.md → templates/.claude/commands/zibby-new-workflow.md} +1 -1
- package/templates/.claude/commands/zibby-set-auth.md +85 -0
- package/templates/.claude/commands/zibby-static-ip.md +70 -0
- package/templates/.claude/commands/zibby-status.md +54 -0
- package/templates/.claude/commands/zibby-tail.md +53 -0
- package/templates/.claude/commands/zibby-test-debug.md +59 -0
- package/templates/.claude/commands/zibby-test-generate.md +39 -0
- package/templates/.claude/commands/zibby-test-run.md +49 -0
- package/templates/.claude/commands/zibby-test-write.md +46 -0
- package/templates/.claude/commands/zibby-trigger.md +56 -0
- package/{dist/templates/.claude/commands/validate-workflow.md → templates/.claude/commands/zibby-validate-workflow.md} +1 -1
- package/templates/.cursor/rules/zibby.mdc +127 -0
- package/templates/AGENTS.md +248 -0
|
@@ -1,171 +1,176 @@
|
|
|
1
|
-
var
|
|
2
|
-
`,"utf-8")}var
|
|
1
|
+
var uo=Object.defineProperty;var H=(t,e)=>()=>(t&&(e=t(t=0)),e);var G=(t,e)=>{for(var o in e)uo(t,o,{get:e[o],enumerable:!0})};import{existsSync as fo,readFileSync as yo,writeFileSync as ho,mkdirSync as wo}from"fs";import{join as Je}from"path";import{homedir as qe}from"os";function Xe(){return Je(qe(),".zibby","config.json")}function fe(){try{let t=Xe();return fo(t)?JSON.parse(yo(t,"utf-8")):{}}catch{return{}}}function Qe(t,e){let o=e?me[e]:null;o&&xe(o.envVar,t)}function xe(t,e){if(!t||typeof t!="string"||!e||typeof e!="string")return;let o=Je(qe(),".zibby");wo(o,{recursive:!0});let s=Xe(),n=fe();(!n.agentKeys||typeof n.agentKeys!="object")&&(n.agentKeys={}),n.agentKeys[t]=String(e).trim(),delete n.agentApiKey,ho(s,`${JSON.stringify(n,null,2)}
|
|
2
|
+
`,"utf-8")}var me,et=H(()=>{me={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 Ce={};G(Ce,{resolveTemplate:()=>nt,templateAddCommand:()=>Oo,templateListCommand:()=>Ro,writeTemplateFiles:()=>st,writeTemplateFilesToDir:()=>rt});import{mkdir as tt,writeFile as bo,readFile as ko}from"fs/promises";import{existsSync as ye,readdirSync as $o,statSync as vo,readFileSync as xo}from"fs";import{join as ee,dirname as Co}from"path";import{fileURLToPath as Ao}from"url";import{spawn as So}from"child_process";import{createRequire as Io}from"module";import I from"chalk";import _o from"ora";function jo(t){return zo.some(e=>e.test(t))}async function ot(t,e,o=null){let s=[];ye(e)||await tt(e,{recursive:!0});for(let n of $o(t)){if(jo(n))continue;let r=ee(t,n),u=ee(e,n),c=vo(r);if(c.isDirectory()){let i=await ot(r,u,o);for(let d of i)s.push(`${n}/${d}`)}else if(c.isFile()){let i=await ko(r,"utf-8");o&&(i=o(n,i)),await bo(u,i),s.push(n)}}return s}async function nt(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 rt(t,e,o={}){let s=o.enableMemory!==!1,{template:n}=await nt(e);ye(t)||await tt(t,{recursive:!0});let r=await ot(n.path,t,(u,c)=>!s&&u==="execute-live.mjs"?c.replace("skills: [SKILLS.BROWSER, SKILLS.MEMORY],","skills: [SKILLS.BROWSER],"):c);return{template:n,copied:r}}async function st(t,e,o={}){return rt(ee(t,".zibby"),e,o)}async function Ro(){let{TemplateFactory:t}=await import("@zibby/workflow-templates"),e=t.listTemplates();console.log(""),console.log(I.bold.cyan(" Available templates")),console.log("");for(let o of e){if(console.log(` ${I.cyan(o.name)}`),console.log(` ${I.white(o.displayName)}`),o.description&&console.log(` ${I.gray(o.description)}`),o.features&&o.features.length)for(let n of o.features)console.log(I.gray(` \u2022 ${n}`));let s=o.defaultSlug||"your-workflow-name";console.log(""),console.log(` ${I.gray("Scaffold:")} ${I.cyan(`zibby workflow new ${s} -t ${o.name}`)}`),console.log("")}}async function Oo(t,e={}){t||(console.log(I.red(`
|
|
3
3
|
Missing template name.
|
|
4
|
-
`)),console.log(
|
|
5
|
-
`)),process.exit(1));let
|
|
6
|
-
No .zibby/ directory in ${
|
|
7
|
-
`)),console.log(
|
|
4
|
+
`)),console.log(I.gray(" Usage: zibby template add <name>")),console.log(I.gray(` See available templates: zibby template list
|
|
5
|
+
`)),process.exit(1));let o=e.cwd||process.cwd(),s=ee(o,".zibby");ye(s)||(console.log(I.yellow(`
|
|
6
|
+
No .zibby/ directory in ${o}.
|
|
7
|
+
`)),console.log(I.gray(" Run `zibby init` first to bootstrap the project.\n")),process.exit(1));let n;try{n=await st(o,t,{enableMemory:e.enableMemory!==!1})}catch(r){console.log(I.red(`
|
|
8
8
|
${r.message}
|
|
9
|
-
`)),console.log(
|
|
10
|
-
`)),process.exit(1)}console.log(""),console.log(A.green(` \u2713 Added template ${A.bold(n.template.name)}`)),console.log(A.gray(` ${n.copied.length} files written to ${s}/`));for(let r of n.copied)console.log(A.gray(` \u2022 ${r}`));if(!e.skipInstall&&ue(G(t,"package.json"))){let r=!1;try{yt(G(t,"package.json")).resolve("@zibby/core/package.json"),r=!0}catch{}if(!r){let l=`@zibby/core@${JSON.parse(pt(G(bt,"../../package.json"),"utf-8")).dependencies?.["@zibby/core"]||"latest"}`,i=ht(` Installing ${l} (needed by .zibby/graph.mjs)...`).start();await new Promise(w=>{ft("npm",["install","--save-dev",l],{cwd:t,stdio:"pipe"}).on("close",y=>w(y??1))})===0?i.succeed(` Installed ${l}`):(i.warn(` Could not auto-install ${l}`),console.log(A.gray(` Run manually: npm install --save-dev ${l}`)))}}console.log(""),console.log(A.gray(" Re-running `zibby template add <name>` overwrites existing files \u2014")),console.log(A.gray(" use this to refresh after `npm update @zibby/core`.")),console.log("")}var wt,bt,kt,he=K(()=>{wt=mt(import.meta.url),bt=gt(wt),kt=[/^__tests__$/,/^__mocks__$/,/^node_modules$/,/\.test\.[mc]?js$/,/\.spec\.[mc]?js$/,/^\.DS_Store$/,/^chat\.mjs$/]});var Xe={};U(Xe,{applyMemorySyncConfig:()=>St,validateMemorySyncConfig:()=>qe});function qe(o){if(!o||typeof o!="object")return{ok:!0,kind:"noop"};let e=o.remote;return Ct.includes(e)?{ok:!0,kind:"noop"}:typeof e!="string"?{ok:!1,error:`memorySync.remote must be null or a string, got ${typeof e}`}:e===At?{ok:!0,kind:"hosted"}:Je.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: ${Je.join(" / ")}.`}}async function St({cwd:o,projectId:e,block:t,memoryApi:s,hostedSetup:n,getSessionToken:r,logger:u=console}){let l=qe(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(i){return{action:"error",reason:`hosted setup failed: ${i.message}`}}}return{action:"error",reason:`unhandled kind: ${l.kind}`}}var Ct,At,Je,Qe=K(()=>{Ct=[null,void 0,"","none","off",!1],At="hosted",Je=["aws://","gs://","https://","http://","file://"]});var be={};U(be,{clearSession:()=>co,default:()=>jt,getMem0ProxyUrl:()=>go,getProjects:()=>fo,getProxyUrl:()=>uo,getSessionToken:()=>we,getUserInfo:()=>io,isLoggedIn:()=>lo,loadConfig:()=>R,saveConfig:()=>Y,saveMem0ProxyUrl:()=>mo,saveProjects:()=>yo,saveProxyUrl:()=>po,saveSessionToken:()=>so,saveUserInfo:()=>ao});import{existsSync as eo,mkdirSync as It,readFileSync as _t,writeFileSync as Pt}from"fs";import{homedir as oo}from"os";import{join as de}from"path";function to(){return process.env.ZIBBY_CONFIG_DIR||de(oo(),".zibby")}function no(){return de(to(),"config.json")}function zt(){let o=to();eo(o)||It(o,{recursive:!0})}function R(){try{let o=no();if(eo(o)){let e=_t(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function Y(o){zt(),Pt(no(),JSON.stringify(o,null,2))}function we(){return R().sessionToken||null}function so(o){let e=R();e.sessionToken=o,Y(e)}function io(){return R().user||null}function ao(o){let e=R();e.user=o,Y(e)}function lo(){return we()!==null}function co(){let o=R();delete o.sessionToken,delete o.user,delete o.mem0ProxyUrl,Y(o)}function uo(){return R().proxyUrl||null}function po(o){let e=R();e.proxyUrl=o,Y(e)}function go(){return R().mem0ProxyUrl||null}function mo(o){let e=R();e.mem0ProxyUrl=o,Y(e)}function fo(){return R().projects||[]}function yo(o){let e=R();e.projects=o,Y(e)}var ro,Et,jt,ke=K(()=>{ro=de(oo(),".zibby"),Et=de(ro,"config.json");jt={loadConfig:R,saveConfig:Y,getSessionToken:we,saveSessionToken:so,getUserInfo:io,saveUserInfo:ao,isLoggedIn:lo,clearSession:co,getProxyUrl:uo,saveProxyUrl:po,getMem0ProxyUrl:go,saveMem0ProxyUrl:mo,getProjects:fo,saveProjects:yo,CONFIG_DIR:ro,CONFIG_FILE:Et}});var ho={};U(ho,{ENVIRONMENTS:()=>j,getAccountApiUrl:()=>Rt,getApiUrl:()=>Ot,getCurrentEnvironment:()=>Tt,getFrontendUrl:()=>Nt});function Ot(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";j[e]?o=j[e].apiUrl:o=j.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)`),j.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),j.prod.apiUrl}}function Rt(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let o=process.env.ZIBBY_ENV||"prod";return(j[o]||j.prod).accountApiUrl}function Tt(){let o=process.env.ZIBBY_ENV||"prod";return j[o]||j.prod}function Nt(){let o;if(process.env.ZIBBY_FRONTEND_URL)o=process.env.ZIBBY_FRONTEND_URL;else{let e=process.env.ZIBBY_ENV||"prod";j[e]?o=j[e].frontendUrl:o=j.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)`),j.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}`),j.local.frontendUrl}}var j,wo=K(()=>{j={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}}});var Se={};U(Se,{__testing:()=>Ft,buildDoltEnv:()=>Yt,clearConfig:()=>Ut,getActiveCredentials:()=>Ao,isHosted:()=>Lt,readConfig:()=>Ce,refreshCredentials:()=>Co,writeConfig:()=>Dt});import{readFileSync as bo,writeFileSync as xe,existsSync as $e,mkdirSync as ko,chmodSync as Bt}from"fs";import{join as ve}from"path";function oe(o){let e=ve(o,".zibby");return{dir:e,config:ve(e,Mt),creds:ve(e,Kt)}}function Ce(o){let{config:e}=oe(o);if(!$e(e))return null;try{let t=JSON.parse(bo(e,"utf-8"));return t.mode!=="hosted"?null:t}catch{return null}}function Lt(o){return!!Ce(o)}function Dt(o,e){let{dir:t,config:s}=oe(o);ko(t,{recursive:!0}),xe(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 Ut(o){let{config:e,creds:t}=oe(o);for(let s of[e,t])if($e(s))try{xe(s,"")}catch{}}function Ae(o){let{creds:e}=oe(o);if(!$e(e))return null;try{let t=JSON.parse(bo(e,"utf-8"));return!t?.accessKeyId||!t?.secretAccessKey||!t?.sessionToken?null:t}catch{return null}}function xo(o,e){let{dir:t,creds:s}=oe(o);ko(t,{recursive:!0}),xe(s,JSON.stringify(e,null,2),"utf-8");try{Bt(s,384)}catch{}}function $o(o){return o?.expiration?new Date(o.expiration).getTime()-Date.now()<vo:!0}async function Co({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 i=await u.text().catch(()=>"");throw new Error(`memory-sync credentials request failed (${u.status}): ${i||"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 xo(o,{accessKeyId:l.accessKeyId,secretAccessKey:l.secretAccessKey,sessionToken:l.sessionToken,expiration:l.expiration||null,refreshedAt:new Date().toISOString()}),Ae(o)}async function Ao({cwd:o,apiUrl:e,sessionToken:t,fetch:s}){let n=Ce(o);if(!n)return null;let r=Ae(o);return(!r||$o(r))&&(r=await Co({cwd:o,projectId:n.projectId,apiUrl:e,sessionToken:t,fetch:s})),r}async function Yt({cwd:o,apiUrl:e,sessionToken:t,fetch:s}){let n=await Ao({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 Mt,Kt,vo,Ft,Ie=K(()=>{Mt="memory-sync.json",Kt="memory-sync-creds.json",vo=120*1e3;Ft={paths:oe,readCreds:Ae,writeCreds:xo,isExpiringSoon:$o,REFRESH_HEADROOM_MS:vo}});var So={};U(So,{memoryCompactCommand:()=>Gt,memoryCostCommand:()=>Vt,memoryInitCommand:()=>tn,memoryPullCommand:()=>Qt,memoryPushCommand:()=>on,memoryRemoteAddCommand:()=>Jt,memoryRemoteInfoCommand:()=>qt,memoryRemoteRemoveCommand:()=>Xt,memoryRemoteUseHostedCommand:()=>en,memoryResetCommand:()=>Zt,memoryStatsCommand:()=>Wt});import a from"chalk";async function T(){try{return await import("@zibby/ui-memory")}catch{return console.log(a.yellow(`
|
|
9
|
+
`)),console.log(I.gray(` See available templates: zibby template list
|
|
10
|
+
`)),process.exit(1)}console.log(""),console.log(I.green(` \u2713 Added template ${I.bold(n.template.name)}`)),console.log(I.gray(` ${n.copied.length} files written to ${s}/`));for(let r of n.copied)console.log(I.gray(` \u2022 ${r}`));if(!e.skipInstall&&ye(ee(o,"package.json"))){let r=!1;try{Io(ee(o,"package.json")).resolve("@zibby/core/package.json"),r=!0}catch{}if(!r){let c=`@zibby/core@${JSON.parse(xo(ee(Eo,"../../package.json"),"utf-8")).dependencies?.["@zibby/core"]||"latest"}`,i=_o(` Installing ${c} (needed by .zibby/graph.mjs)...`).start();await new Promise(b=>{So("npm",["install","--save-dev",c],{cwd:o,stdio:"pipe"}).on("close",f=>b(f??1))})===0?i.succeed(` Installed ${c}`):(i.warn(` Could not auto-install ${c}`),console.log(I.gray(` Run manually: npm install --save-dev ${c}`)))}}console.log(""),console.log(I.gray(" Re-running `zibby template add <name>` overwrites existing files \u2014")),console.log(I.gray(" use this to refresh after `npm update @zibby/core`.")),console.log("")}var Po,Eo,zo,Ae=H(()=>{Po=Ao(import.meta.url),Eo=Co(Po),zo=[/^__tests__$/,/^__mocks__$/,/^node_modules$/,/\.test\.[mc]?js$/,/\.spec\.[mc]?js$/,/^\.DS_Store$/,/^chat\.mjs$/]});var it={};G(it,{BLOCK_REGEX:()=>Se,upsertManagedBlock:()=>To});function To(t,e){if(typeof e!="string")throw new TypeError("blockContent must be a string");if(t==null)return{content:e,action:"created"};if(Se.test(t)){let s=t.replace(Se,e.trimEnd()+`
|
|
11
|
+
`);return s===t?{content:t,action:"skipped"}:{content:s,action:"updated"}}let o=t.endsWith(`
|
|
12
|
+
`)?`
|
|
13
|
+
`:`
|
|
14
|
+
|
|
15
|
+
`;return{content:t+o+e,action:"updated"}}var Se,at=H(()=>{Se=/<!--\s*BEGIN ZIBBY[^>]*-->[\s\S]*?<!--\s*END ZIBBY[^>]*-->\s*/i});var ut={};G(ut,{applyMemorySyncConfig:()=>Mo,validateMemorySyncConfig:()=>ct});function ct(t){if(!t||typeof t!="object")return{ok:!0,kind:"noop"};let e=t.remote;return No.includes(e)?{ok:!0,kind:"noop"}:typeof e!="string"?{ok:!1,error:`memorySync.remote must be null or a string, got ${typeof e}`}:e===Bo?{ok:!0,kind:"hosted"}:lt.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: ${lt.join(" / ")}.`}}async function Mo({cwd:t,projectId:e,block:o,memoryApi:s,hostedSetup:n,getSessionToken:r,logger:u=console}){let c=ct(o);if(!c.ok)return u.warn?.(`[memory-sync] config invalid: ${c.error}`),{action:"error",reason:c.error};if(c.kind==="noop")return{action:"skipped",reason:"memorySync.remote not set"};if(c.kind==="byo")return s?.memoryRemoteAdd?s.memoryRemoteAdd(t,c.remote)?{action:"byo",remote:c.remote}:{action:"error",reason:"memoryRemoteAdd returned false (memory DB not initialized?)"}:{action:"error",reason:"@zibby/ui-memory not loaded"};if(c.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:t,projectId:e}),{action:"hosted"}}catch(i){return{action:"error",reason:`hosted setup failed: ${i.message}`}}}return{action:"error",reason:`unhandled kind: ${c.kind}`}}var No,Bo,lt,dt=H(()=>{No=[null,void 0,"","none","off",!1],Bo="hosted",lt=["aws://","gs://","https://","http://","file://"]});var _e={};G(_e,{clearSession:()=>$t,default:()=>Fo,getMem0ProxyUrl:()=>Ct,getProjects:()=>St,getProxyUrl:()=>vt,getSessionToken:()=>Ie,getUserInfo:()=>wt,isLoggedIn:()=>kt,loadConfig:()=>M,saveConfig:()=>J,saveMem0ProxyUrl:()=>At,saveProjects:()=>It,saveProxyUrl:()=>xt,saveSessionToken:()=>ht,saveUserInfo:()=>bt});import{existsSync as pt,mkdirSync as Ko,readFileSync as Lo,writeFileSync as Do}from"fs";import{homedir as gt}from"os";import{join as he}from"path";function mt(){return process.env.ZIBBY_CONFIG_DIR||he(gt(),".zibby")}function ft(){return he(mt(),"config.json")}function Yo(){let t=mt();pt(t)||Ko(t,{recursive:!0})}function M(){try{let t=ft();if(pt(t)){let e=Lo(t,"utf-8");return JSON.parse(e)}}catch{}return{}}function J(t){Yo(),Do(ft(),JSON.stringify(t,null,2))}function Ie(){return M().sessionToken||null}function ht(t){let e=M();e.sessionToken=t,J(e)}function wt(){return M().user||null}function bt(t){let e=M();e.user=t,J(e)}function kt(){return Ie()!==null}function $t(){let t=M();delete t.sessionToken,delete t.user,delete t.mem0ProxyUrl,J(t)}function vt(){return M().proxyUrl||null}function xt(t){let e=M();e.proxyUrl=t,J(e)}function Ct(){return M().mem0ProxyUrl||null}function At(t){let e=M();e.mem0ProxyUrl=t,J(e)}function St(){return M().projects||[]}function It(t){let e=M();e.projects=t,J(e)}var yt,Uo,Fo,Pe=H(()=>{yt=he(gt(),".zibby"),Uo=he(yt,"config.json");Fo={loadConfig:M,saveConfig:J,getSessionToken:Ie,saveSessionToken:ht,getUserInfo:wt,saveUserInfo:bt,isLoggedIn:kt,clearSession:$t,getProxyUrl:vt,saveProxyUrl:xt,getMem0ProxyUrl:Ct,saveMem0ProxyUrl:At,getProjects:St,saveProjects:It,CONFIG_DIR:yt,CONFIG_FILE:Uo}});var _t={};G(_t,{ENVIRONMENTS:()=>T,getAccountApiUrl:()=>Wo,getApiUrl:()=>Ho,getCurrentEnvironment:()=>Zo,getFrontendUrl:()=>Go});function Ho(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";T[e]?t=T[e].apiUrl:t=T.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)`),T.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),T.prod.apiUrl}}function Wo(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let t=process.env.ZIBBY_ENV||"prod";return(T[t]||T.prod).accountApiUrl}function Zo(){let t=process.env.ZIBBY_ENV||"prod";return T[t]||T.prod}function Go(){let t;if(process.env.ZIBBY_FRONTEND_URL)t=process.env.ZIBBY_FRONTEND_URL;else{let e=process.env.ZIBBY_ENV||"prod";T[e]?t=T[e].frontendUrl:t=T.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)`),T.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 t}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${t}`),T.local.frontendUrl}}var T,Pt=H(()=>{T={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 Te={};G(Te,{__testing:()=>on,buildDoltEnv:()=>tn,clearConfig:()=>en,getActiveCredentials:()=>Nt,isHosted:()=>Xo,readConfig:()=>Re,refreshCredentials:()=>Tt,writeConfig:()=>Qo});import{readFileSync as Et,writeFileSync as ze,existsSync as je,mkdirSync as zt,chmodSync as Vo}from"fs";import{join as Ee}from"path";function ae(t){let e=Ee(t,".zibby");return{dir:e,config:Ee(e,Jo),creds:Ee(e,qo)}}function Re(t){let{config:e}=ae(t);if(!je(e))return null;try{let o=JSON.parse(Et(e,"utf-8"));return o.mode!=="hosted"?null:o}catch{return null}}function Xo(t){return!!Re(t)}function Qo(t,e){let{dir:o,config:s}=ae(t);zt(o,{recursive:!0}),ze(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 en(t){let{config:e,creds:o}=ae(t);for(let s of[e,o])if(je(s))try{ze(s,"")}catch{}}function Oe(t){let{creds:e}=ae(t);if(!je(e))return null;try{let o=JSON.parse(Et(e,"utf-8"));return!o?.accessKeyId||!o?.secretAccessKey||!o?.sessionToken?null:o}catch{return null}}function Rt(t,e){let{dir:o,creds:s}=ae(t);zt(o,{recursive:!0}),ze(s,JSON.stringify(e,null,2),"utf-8");try{Vo(s,384)}catch{}}function Ot(t){return t?.expiration?new Date(t.expiration).getTime()-Date.now()<jt:!0}async function Tt({cwd:t,projectId:e,apiUrl:o,sessionToken:s,fetch:n=globalThis.fetch}){if(!e)throw new Error("refreshCredentials: projectId required");if(!o)throw new Error("refreshCredentials: apiUrl required");if(!s)throw new Error("refreshCredentials: sessionToken required (run `zibby login`)");let r=`${String(o).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 i=await u.text().catch(()=>"");throw new Error(`memory-sync credentials request failed (${u.status}): ${i||"no body"}`)}let c=await u.json();if(!c?.accessKeyId||!c?.secretAccessKey||!c?.sessionToken)throw new Error("memory-sync credentials response missing required fields");return Rt(t,{accessKeyId:c.accessKeyId,secretAccessKey:c.secretAccessKey,sessionToken:c.sessionToken,expiration:c.expiration||null,refreshedAt:new Date().toISOString()}),Oe(t)}async function Nt({cwd:t,apiUrl:e,sessionToken:o,fetch:s}){let n=Re(t);if(!n)return null;let r=Oe(t);return(!r||Ot(r))&&(r=await Tt({cwd:t,projectId:n.projectId,apiUrl:e,sessionToken:o,fetch:s})),r}async function tn({cwd:t,apiUrl:e,sessionToken:o,fetch:s}){let n=await Nt({cwd:t,apiUrl:e,sessionToken:o,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 Jo,qo,jt,on,Ne=H(()=>{Jo="memory-sync.json",qo="memory-sync-creds.json",jt=120*1e3;on={paths:ae,readCreds:Oe,writeCreds:Rt,isExpiringSoon:Ot,REFRESH_HEADROOM_MS:jt}});var Bt={};G(Bt,{memoryCompactCommand:()=>an,memoryCostCommand:()=>ln,memoryInitCommand:()=>fn,memoryPullCommand:()=>pn,memoryPushCommand:()=>mn,memoryRemoteAddCommand:()=>cn,memoryRemoteInfoCommand:()=>un,memoryRemoteRemoveCommand:()=>dn,memoryRemoteUseHostedCommand:()=>gn,memoryResetCommand:()=>sn,memoryStatsCommand:()=>rn});import a from"chalk";async function L(){try{return await import("@zibby/ui-memory")}catch{return console.log(a.yellow(`
|
|
11
16
|
@zibby/ui-memory is not installed.
|
|
12
|
-
`)),console.log(a.white(
|
|
17
|
+
`)),console.log(a.white(nn)),null}}async function rn(){let t=await L();if(!t)return;let e=process.cwd(),o=t.getStats(e);if(!o.available){console.log(a.red(`
|
|
13
18
|
Dolt is not installed.
|
|
14
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
|
|
15
|
-
`));return}if(!
|
|
20
|
+
`));return}if(!o.initialized){console.log(a.yellow(`
|
|
16
21
|
Memory database not initialized.
|
|
17
22
|
`)),console.log(a.white(" Run `zibby init` or `zibby memory init` to set it up.\n"));return}console.log(a.bold.cyan(`
|
|
18
23
|
Zibby Test Memory
|
|
19
|
-
`)),console.log(a.gray(` Dolt: ${
|
|
20
|
-
${s}`),console.log(a.white(" Recent runs:"));for(let r of
|
|
21
|
-
${s}`),console.log(a.white(" Top selectors:"));for(let r of
|
|
22
|
-
${s}`),console.log(a.white(" Recent commits:"));let r=
|
|
23
|
-
`).filter(u=>u.startsWith("commit")||u.trim().startsWith("run ")).slice(0,10);for(let u of r)console.log(a.gray(` ${u.trim()}`))}console.log("")}async function
|
|
24
|
+
`)),console.log(a.gray(` Dolt: ${o.doltVersion}`));let s=a.gray(` ${"\u2500".repeat(40)}`);console.log(s);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
|
+
${s}`),console.log(a.white(" Recent runs:"));for(let r of o.recentRuns){let u=r.passed?a.green("\u2713"):a.red("\u2717"),c=r.duration_ms?a.gray(`${(r.duration_ms/1e3).toFixed(1)}s`):"";console.log(` ${u} ${a.white(r.spec_path)} ${c}`)}}if(o.topSelectors.length>0){console.log(`
|
|
26
|
+
${s}`),console.log(a.white(" Top selectors:"));for(let r of o.topSelectors){let u=r.success_count+r.failure_count,c=Math.round(r.success_count/u*100);console.log(` ${a.cyan(r.stable_id||"?")} \u2192 ${r.element_desc} (${c}%, ${u} uses)`)}}if(o.log){console.log(`
|
|
27
|
+
${s}`),console.log(a.white(" Recent commits:"));let r=o.log.split(`
|
|
28
|
+
`).filter(u=>u.startsWith("commit")||u.trim().startsWith("run ")).slice(0,10);for(let u of r)console.log(a.gray(` ${u.trim()}`))}console.log("")}async function sn(t){let e=await L();if(!e)return;let o=process.cwd();if(!t.force){console.log(a.yellow(`
|
|
24
29
|
This will permanently delete the memory database.
|
|
25
30
|
`)),console.log(a.white(` Run with --force to confirm: zibby memory reset --force
|
|
26
|
-
`));return}let s=e.resetMemory(
|
|
31
|
+
`));return}let s=e.resetMemory(o);console.log(s?a.green(`
|
|
27
32
|
Memory database reset.
|
|
28
33
|
`):a.gray(`
|
|
29
34
|
No memory database found.
|
|
30
|
-
`))}async function
|
|
35
|
+
`))}async function an(t){let e=await L();if(!e)return;let o=process.cwd(),s=e.getStats(o);if(!s.initialized){console.log(a.yellow(`
|
|
31
36
|
Memory database not initialized.
|
|
32
|
-
`));return}let n=
|
|
33
|
-
Compacting memory (keep last ${n} runs/spec, prune data older than ${r}d)...`));let u=s.counts;if(e.compactMemory(
|
|
37
|
+
`));return}let n=t.maxRuns||50,r=t.maxAge||90;console.log(a.white(`
|
|
38
|
+
Compacting memory (keep last ${n} runs/spec, prune data older than ${r}d)...`));let u=s.counts;if(e.compactMemory(o,{maxRuns:n,maxAgeDays:r}).pruned){let i=e.getStats(o).counts,d=b=>u[b]-i[b];console.log(a.green(" Done.")),d("runs")>0&&console.log(a.gray(` Pruned ${d("runs")} old runs`)),d("selectors")>0&&console.log(a.gray(` Pruned ${d("selectors")} stale selectors`)),d("insights")>0&&console.log(a.gray(` Pruned ${d("insights")} old insights`)),d("transitions")>0&&console.log(a.gray(` Pruned ${d("transitions")} stale transitions`)),console.log(a.gray(` Dolt GC completed
|
|
34
39
|
`))}else console.log(a.gray(` Nothing to compact.
|
|
35
|
-
`))}async function
|
|
40
|
+
`))}async function ln(){let t=await L();if(!t)return;let e=process.cwd(),o=t.getCostStats(e);if(!o){console.log(a.yellow(`
|
|
36
41
|
Memory database not initialized.
|
|
37
|
-
`)),console.log(a.white(" Run `zibby memory init` first.\n"));return}if(
|
|
38
|
-
No usage data yet${
|
|
42
|
+
`)),console.log(a.white(" Run `zibby memory init` first.\n"));return}if(o.available===!1){console.log(a.yellow(`
|
|
43
|
+
No usage data yet${o.reason?` (${o.reason})`:""}.
|
|
39
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.
|
|
40
45
|
`));return}console.log(a.bold.cyan(`
|
|
41
46
|
Zibby \u2014 LLM Cost Report
|
|
42
|
-
`));let s=a.gray(` ${"\u2500".repeat(60)}`),n=
|
|
43
|
-
${s}`),console.log(a.white(" By domain:"));for(let r of
|
|
44
|
-
${s}`),console.log(a.white(" By spec:"));for(let r of
|
|
45
|
-
${s}`),console.log(a.white(" Last 10 runs:"));for(let r of
|
|
47
|
+
`));let s=a.gray(` ${"\u2500".repeat(60)}`),n=o.totals;if(console.log(s),console.log(a.white(` Runs with usage data: ${a.cyan(n.runs)}`)),console.log(a.white(` Total input tokens: ${a.cyan(q(n.input))}`)),console.log(a.white(` Total output tokens: ${a.cyan(q(n.output))}`)),console.log(a.white(` Total cache reads: ${a.cyan(q(n.cache_read))} ${a.gray("(billed at ~10% of normal input rate)")}`)),console.log(a.white(` Total cache creation: ${a.cyan(q(n.cache_creation))} ${a.gray("(billed at ~125% of normal input rate)")}`)),o.by_domain.length>0){console.log(`
|
|
48
|
+
${s}`),console.log(a.white(" By domain:"));for(let r of o.by_domain.slice(0,10)){let u=r.runs>0?Math.round((r.input+r.output)/r.runs):0;console.log(` ${a.cyan(r.domain.padEnd(30))} ${a.gray(`${r.runs} runs \xB7 ~${q(u)}/run avg`)}`)}}if(o.by_spec.length>0){console.log(`
|
|
49
|
+
${s}`),console.log(a.white(" By spec:"));for(let r of o.by_spec.slice(0,10)){let u=r.runs>0?Math.round((r.input+r.output)/r.runs):0;console.log(` ${a.cyan(String(r.spec_path).padEnd(40))} ${a.gray(`${r.runs} runs \xB7 ~${q(u)}/run avg`)}`)}}if(o.recent.length>0){console.log(`
|
|
50
|
+
${s}`),console.log(a.white(" Last 10 runs:"));for(let r of o.recent.slice(0,10)){let u=r.passed?a.green("\u2713"):a.red("\u2717"),c=(r.input_tokens||0)+(r.output_tokens||0),i=(r.cache_read_tokens||0)>0?a.gray(` \xB7 cache read ${q(r.cache_read_tokens)}`):"";console.log(` ${u} ${a.gray(r.run_at.slice(0,16))} ${a.cyan(q(c).padStart(8))} ${a.white(r.spec_path||"")}${i}`)}}console.log("")}function q(t){return t==null?"\u2014":t<1e3?String(t):t<1e6?`${(t/1e3).toFixed(1)}K`:`${(t/1e6).toFixed(2)}M`}async function cn(t,e={}){let o=await L();if(!o)return;t||(console.log(a.red(`
|
|
46
51
|
Usage: zibby memory remote add <url> [--name origin]
|
|
47
|
-
`)),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 s=process.cwd(),n=e.name||"origin";if(!
|
|
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 s=process.cwd(),n=e.name||"origin";if(!o.memoryRemoteAdd(s,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 un(){let t=await L();if(!t)return;let e=t.memoryRemoteInfo(process.cwd());if(console.log(""),!e){console.log(a.yellow(` No memory remote configured.
|
|
48
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.
|
|
49
|
-
`));return}console.log(a.bold.cyan(" Memory remote")),console.log(` ${a.cyan(e.name||"origin")}: ${e.url||"(unknown)"}`),console.log("")}async function
|
|
50
|
-
Pulling team memory from remote...`));let e=
|
|
51
|
-
`)):(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
|
|
54
|
+
`));return}console.log(a.bold.cyan(" Memory remote")),console.log(` ${a.cyan(e.name||"origin")}: ${e.url||"(unknown)"}`),console.log("")}async function dn(t="origin"){let e=await L();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 pn(){let t=await L();if(!t)return;console.log(a.cyan(`
|
|
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 gn(t={}){let e=await L();if(!e)return;let{join:o}=await import("path"),{existsSync:s}=await import("fs"),n=t.cwd||process.cwd(),r=t.projectId;if(!r){let S=o(n,".zibby.config.mjs");if(s(S))try{let v=(await import(`file://${S}?t=${Date.now()}`)).default;r=v?.projectId||v?.project?.id}catch{}}r||(console.log(a.red(`
|
|
52
57
|
Could not determine projectId.
|
|
53
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>.
|
|
54
|
-
`)),process.exit(1));let{getApiUrl:u}=await Promise.resolve().then(()=>(
|
|
59
|
+
`)),process.exit(1));let{getApiUrl:u}=await Promise.resolve().then(()=>(Pt(),_t)),{getSessionToken:c}=await Promise.resolve().then(()=>(Pe(),_e)),i=u(),d=c();d||(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.
|
|
55
60
|
`)),process.exit(1)),console.log(a.cyan(`
|
|
56
|
-
Configuring hosted memory-sync...`));let
|
|
57
|
-
Failed: ${
|
|
58
|
-
`)),process.exit(1)}let{writeConfig:
|
|
59
|
-
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:
|
|
60
|
-
Config saved, but initial credential fetch failed: ${
|
|
61
|
-
`))}console.log(""),console.log(a.green(" \u2713 Hosted memory-sync configured.")),console.log(a.gray(` Bucket: ${
|
|
62
|
-
Pushing local memory to team remote...`));let e=
|
|
63
|
-
`))}async function
|
|
61
|
+
Configuring hosted memory-sync...`));let b;try{let S=`${i.replace(/\/+$/,"")}/memory/sync-config?projectId=${encodeURIComponent(r)}`,h=await fetch(S,{headers:{Authorization:`Bearer ${d}`}});if(!h.ok){let v=await h.text().catch(()=>"");throw new Error(`backend returned ${h.status}: ${v||"no body"}`)}b=await h.json()}catch(S){console.log(a.red(`
|
|
62
|
+
Failed: ${S.message}
|
|
63
|
+
`)),process.exit(1)}let{writeConfig:k}=await Promise.resolve().then(()=>(Ne(),Te));k(n,{projectId:r,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:f}=await Promise.resolve().then(()=>(Ne(),Te));try{await f({cwd:n,projectId:r,apiUrl:i,sessionToken:d})}catch(S){console.log(a.yellow(`
|
|
65
|
+
Config saved, but initial credential fetch failed: ${S.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 mn(){let t=await L();if(!t)return;console.log(a.cyan(`
|
|
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 fn(){let t=await L();if(!t)return;let e=process.cwd();if(!t.DoltDB.isAvailable()){console.log(a.red(`
|
|
64
69
|
Dolt is not installed.
|
|
65
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
|
|
66
|
-
`));return}let{created:
|
|
71
|
+
`));return}let{created:o,available:s}=t.initMemory(e);o?console.log(a.green(`
|
|
67
72
|
Memory database initialized at .zibby/memory/
|
|
68
73
|
`)):s&&console.log(a.gray(`
|
|
69
74
|
Memory database already initialized.
|
|
70
|
-
`))}var
|
|
75
|
+
`))}var nn,Mt=H(()=>{nn=`
|
|
71
76
|
Install @zibby/ui-memory and Dolt to enable test memory:
|
|
72
77
|
|
|
73
78
|
npm install @zibby/ui-memory # add the package
|
|
74
79
|
brew install dolt # macOS
|
|
75
80
|
# or: curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash
|
|
76
|
-
`});var
|
|
77
|
-
`,"utf-8")}async function
|
|
78
|
-
`).find(r=>/playwright-official/i.test(r)&&/APPROVAL|🔑/i.test(r));if(
|
|
79
|
-
`,"utf-8"),n}function
|
|
81
|
+
`});var Gt={};G(Gt,{setupCiCommand:()=>Sn,setupPlaywrightMcpCommand:()=>Zt,testWithVideoCommand:()=>In});import{spawn as Me,execSync as Ke}from"child_process";import{join as te,dirname as Le,resolve as Dt}from"path";import{readFileSync as Ut,writeFileSync as Yt,existsSync as le,mkdirSync as Ft}from"fs";import{homedir as Ht}from"os";import{createRequire as yn}from"module";import R from"chalk";function hn(){try{return Le(Be.resolve("@zibby/core/package.json"))}catch{return null}}function Wt(t){try{return Ke(`command -v ${t}`,{stdio:"pipe"}),!0}catch{return!1}}function wn(){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=Le(t),o=JSON.parse(Ut(t,"utf-8")),s=typeof o.bin=="string"?o.bin:o.bin?.["playwright-mcp"];if(s){let r=te(e,s);if(le(r))return r}let n=te(e,"cli.js");if(le(n))return n}catch{}return null}function Kt(t,e,o={}){return new Promise((s,n)=>{let r=Me(t,e,{stdio:"inherit",...o});r.on("close",u=>s(u??1)),r.on("error",n)})}async function bn(t){return Wt("playwright")?await Kt("playwright",["install","ffmpeg"],{cwd:t})===0:await Kt("npx",["--yes","playwright","install","ffmpeg"],{cwd:t})===0}function kn({headed:t=!1,viewport:e=null}){let o=process.execPath,s=Le(o),n=wn(),r=Number(e?.width)||1280,u=Number(e?.height)||720,c=`${r}x${u}`,i=[];i.push(`--viewport-size=${c}`,"--output-dir=test-results"),t||i.push("--headless");let d;n?d={command:o,args:[n,...i],env:{PATH:`${s}:/usr/bin:/bin:/usr/sbin:/sbin`}}:d={command:"npx",args:["-y","@playwright/mcp",...i],env:{PATH:`${s}:/usr/bin:/bin:/usr/sbin:/sbin`}},d.description="Zibby MCP Browser - Playwright MCP with Zibby defaults";let b=te(Ht(),".cursor"),k=te(b,"mcp.json");le(b)||Ft(b,{recursive:!0});let f={mcpServers:{}};if(le(k))try{f=JSON.parse(Ut(k,"utf-8")),(!f.mcpServers||typeof f.mcpServers!="object")&&(f.mcpServers={})}catch{f={mcpServers:{}}}f.mcpServers["playwright-official"]=d,Yt(k,`${JSON.stringify(f,null,2)}
|
|
82
|
+
`,"utf-8")}async function $n(){let t=hn();if(!t)return;let e=te(t,"scripts","patch-cursor-mcp.js");if(le(e))try{await new Promise((o,s)=>{let n=Me(process.execPath,[e],{cwd:process.cwd(),stdio:"ignore"});n.on("close",r=>o(r??0)),n.on("error",s)})}catch{}}function vn(t){return Dt(t).replace(/^\/+/,"").replace(/\//g,"-")}function xn(t){let e=String(t||""),o=e.split(`
|
|
83
|
+
`).find(r=>/playwright-official/i.test(r)&&/APPROVAL|🔑/i.test(r));if(o){let r=o.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 Cn(t,e){let o=vn(t),s=te(Ht(),".cursor","projects",o);Ft(s,{recursive:!0});let n=te(s,"mcp-approvals.json");return Yt(n,`${JSON.stringify([e],null,2)}
|
|
84
|
+
`,"utf-8"),n}function Lt(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):"",s=e.stderr!=null?String(e.stderr):"";return o+s}}function An(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 Zt(t={}){let e=!!t.headed,o=t.viewport||{width:1280,height:720};if(!process.execPath)throw new Error("Node.js runtime not found");let s=await bn(process.cwd());console.log(s?R.gray(" \u2713 ffmpeg installed for Playwright video"):R.yellow(" \u26A0 Could not install ffmpeg (video may be unavailable)")),kn({headed:e,viewport:o}),await $n();let n=Dt(process.cwd());if(Wt("cursor-agent")){Lt(n);let r=An(n);r&&console.log(R.gray(" \u2713 cursor-agent: mcp enable playwright-official"));let u=Lt(n),c=xn(u);if(c)try{let i=Cn(n,c);console.log(R.gray(` \u2713 MCP auto-approval key saved (${i})`))}catch(i){console.log(R.yellow(` \u26A0 Could not write mcp-approvals.json: ${i.message}`))}else r||(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 Sn(t){try{console.log(R.cyan(`
|
|
80
85
|
\u{1F680} Running CI setup...
|
|
81
|
-
`)),await
|
|
86
|
+
`)),await Zt({headed:!1,cloudSync:!0,viewport:{width:1280,height:720}}),console.log(R.green(`
|
|
82
87
|
\u2705 CI/CD setup complete!
|
|
83
|
-
`))}catch(e){console.log(
|
|
88
|
+
`))}catch(e){console.log(R.red(`
|
|
84
89
|
\u274C Error: ${e.message}
|
|
85
|
-
`)),process.exit(1)}}async function
|
|
90
|
+
`)),process.exit(1)}}async function In(t,e){try{let o=["playwright","test",t||"tests/","--project=chromium"];e.headed&&o.push("--headed"),console.log(R.cyan(`
|
|
86
91
|
\u{1F3A5} Running tests with video recording...
|
|
87
|
-
`)),console.log(
|
|
92
|
+
`)),console.log(R.gray("\u2501".repeat(50)));let s=Me("npx",o,{cwd:process.cwd(),stdio:"inherit"});s.on("close",n=>{n===0?console.log(R.green(`
|
|
88
93
|
\u2705 Tests complete!
|
|
89
|
-
`)):(console.log(
|
|
94
|
+
`)):(console.log(R.red(`
|
|
90
95
|
\u274C Tests failed with code ${n}
|
|
91
|
-
`)),process.exit(n))}),s.on("error",n=>{console.log(
|
|
96
|
+
`)),process.exit(n))}),s.on("error",n=>{console.log(R.red(`
|
|
92
97
|
\u274C Error: ${n.message}
|
|
93
|
-
`)),process.exit(1)})}catch(
|
|
94
|
-
\u274C Error: ${
|
|
95
|
-
`)),process.exit(1)}}var
|
|
96
|
-
`));return}console.log(
|
|
97
|
-
To add manually on Windows:`)),console.log(
|
|
98
|
-
`))):(console.log(
|
|
99
|
-
To add manually, run:`)),console.log(
|
|
100
|
-
`)));return}if(
|
|
101
|
-
`));return}let i=process.env.SHELL||"",d="";if(i.includes("zsh"))d=
|
|
102
|
-
`));return}}let
|
|
98
|
+
`)),process.exit(1)})}catch(o){console.log(R.red(`
|
|
99
|
+
\u274C Error: ${o.message}
|
|
100
|
+
`)),process.exit(1)}}var Be,Vt=H(()=>{Be=yn(import.meta.url)});var qt={};G(qt,{generateConfig:()=>ke,initCommand:()=>Tn});import{mkdir as D,writeFile as P,readFile as K}from"fs/promises";import{existsSync as C,readdirSync as we}from"fs";import{join as y,resolve as De,dirname as _n}from"path";import{homedir as Q}from"os";import oe from"inquirer";import l from"chalk";import X from"ora";import{spawn as pe,execSync as be}from"child_process";import{fileURLToPath as Pn}from"url";import{createRequire as En}from"module";async function zn(){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(l.cyan(" Claude credentials \u2014 pick the type you have:")),console.log("");let{kind:s}=await oe.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(s==="skip")return{kind:"skip"};if(s==="oauth"){o||(console.log(""),console.log(l.gray(" How to generate a long-lived OAuth token (cloud-compatible):")),console.log(l.gray(" 1. Install claude (skip if you already have it):")),console.log(l.gray(" npm install -g @anthropic-ai/claude-code")),console.log(l.gray(" 2. Run:")),console.log(l.gray(" claude setup-token")),console.log(l.gray(" \u2192 confirms in your browser \u2192 prints a token starting with sk-ant-oat01-\u2026")),console.log(l.gray(" 3. Paste that token below.")),console.log(""),console.log(l.yellow(" Note: do NOT paste the short-lived token from `claude` browser-login \u2014")),console.log(l.yellow(" it works locally but Anthropic rejects it from non-login IPs (cloud).")),console.log(""));let c=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:i}=await oe.prompt([{type:"password",name:"token",message:c,mask:"*"}]),d=(i||"").trim();return d?{kind:"oauth",token:d}: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:r}=await oe.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 On(){try{let t=process.platform==="win32",e=be("npm config get prefix",{encoding:"utf-8"}).trim(),o=t?e:`${e}/bin`,s=o.replace(/^~/,Q()),n=t?";":":";if(process.env.PATH.split(n).some(k=>{let f=k.replace(/^~/,Q());return f===s||f===o}))return;if(process.env.CI||process.env.ZIBBY_CI||!process.stdin.isTTY){console.log(l.yellow("npm global bin not in PATH")),console.log(l.gray(` Location: ${s}`)),console.log(l.gray(` Add it manually: export PATH="${s}:$PATH"
|
|
101
|
+
`));return}console.log(l.yellow("npm global bin not in PATH")),console.log(l.gray(` Location: ${s}`)),console.log();let{shouldAddPath:c}=await oe.prompt([{type:"confirm",name:"shouldAddPath",message:"Add npm global bin to your shell PATH automatically?",default:!0}]);if(!c){t?(console.log(l.gray(`
|
|
102
|
+
To add manually on Windows:`)),console.log(l.gray(' 1. Search "Environment Variables" in Start menu')),console.log(l.gray(' 2. Edit "Path" in User variables')),console.log(l.gray(` 3. Add: ${s}
|
|
103
|
+
`))):(console.log(l.gray(`
|
|
104
|
+
To add manually, run:`)),console.log(l.gray(` echo 'export PATH="${s}:$PATH"' >> ~/.zshrc`)),console.log(l.gray(` source ~/.zshrc
|
|
105
|
+
`)));return}if(t){console.log(l.yellow("Cannot auto-add PATH on Windows")),console.log(l.gray(" Please add manually:")),console.log(l.gray(' 1. Search "Environment Variables" in Start menu')),console.log(l.gray(' 2. Edit "Path" in User variables')),console.log(l.gray(` 3. Add: ${s}
|
|
106
|
+
`));return}let i=process.env.SHELL||"",d="";if(i.includes("zsh"))d=y(Q(),".zshrc");else if(i.includes("bash"))d=C(y(Q(),".bashrc"))?y(Q(),".bashrc"):y(Q(),".bash_profile");else{console.log(l.yellow(`Unknown shell: ${i}`)),console.log(l.gray(" Please add manually:")),console.log(l.gray(` export PATH="${s}:$PATH"`));return}if(C(d)){let k=await K(d,"utf-8");if(k.includes(s)||k.includes("npm")&&k.includes("global")&&k.includes("bin")){console.log(l.yellow(`PATH entry found in ${d} but not active`)),console.log(l.gray(` Run: source ${d}
|
|
107
|
+
`));return}}let b=`
|
|
103
108
|
# npm global bin (added by zibby)
|
|
104
109
|
export PATH="${s}:$PATH"
|
|
105
|
-
`;await
|
|
106
|
-
Run this to activate in current session:`)),console.log(
|
|
107
|
-
`))}catch{}}async function
|
|
110
|
+
`;await P(d,(C(d)?await K(d,"utf-8"):"")+b),console.log(l.green(`Added to ${d}`)),console.log(l.yellow(`
|
|
111
|
+
Run this to activate in current session:`)),console.log(l.gray(` source ${d}
|
|
112
|
+
`))}catch{}}async function Tn(t,e){let o=e.template==="browser-test-automation";console.log(o?`
|
|
108
113
|
Zibby Test Automation
|
|
109
114
|
`:`
|
|
110
115
|
Zibby Project Init
|
|
111
|
-
`);let s=!e.skipMemory,n=["dolt","mem0"].includes(String(e.memoryBackend||"").toLowerCase())?String(e.memoryBackend).toLowerCase():"dolt";await
|
|
112
|
-
Directory "${
|
|
113
|
-
`)),process.exit(1)),!
|
|
116
|
+
`);let s=!e.skipMemory,n=["dolt","mem0"].includes(String(e.memoryBackend||"").toLowerCase())?String(e.memoryBackend).toLowerCase():"dolt";await On();let r=t?De(process.cwd(),t):process.cwd(),u=t||"zibby-tests",c=!!t;c&&C(r)&&(console.log(l.red(`
|
|
117
|
+
Directory "${t}" already exists!
|
|
118
|
+
`)),process.exit(1)),!c&&C(y(r,".zibby.config.mjs"))&&!e.force&&(console.log(l.yellow(`
|
|
114
119
|
Zibby is already initialized in this directory!
|
|
115
|
-
`)),console.log(
|
|
116
|
-
`)),process.exit(0)),e.force&&!
|
|
120
|
+
`)),console.log(l.white("Config file found: .zibby.config.mjs")),console.log(l.gray(`Use --force or -f to reinitialize
|
|
121
|
+
`)),process.exit(0)),e.force&&!c&&console.log(l.cyan(`
|
|
117
122
|
Reinitializing Zibby configuration...
|
|
118
|
-
`));let i;if(e.agent&&(e.headed||e.headless))console.log(
|
|
119
|
-
`)),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(l.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:v}=await oe.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:v}}let f=me[i.agent],S=!(process.env.CI||process.env.ZIBBY_CI||!process.stdin.isTTY);if(i.agent==="claude"&&!e.agentKey&&S){let v=await zn();v?.kind==="oauth"&&v.token?(i.claudeOauthToken=v.token,i.agentAuth="oauth"):v?.kind==="api"&&v.token&&(i.agentKey=v.token,i.agentAuth="api")}else if(f&&!e.agentKey&&S){let v=fe(),j=process.env[f.envVar]||v.agentKeys?.[f.envVar],_=j?`***${j.slice(-4)}`:null,E=_?`${f.label} found (${_}). Press Enter to keep, or paste a new key:`:`Enter ${f.label} (from ${f.url}, or press Enter to skip):`,{agentKey:O}=await oe.prompt([{type:"password",name:"agentKey",message:E,mask:"*"}]);O&&O.trim()&&(i.agentKey=O.trim(),i.agentAuth="api")}let h=[];if(o&&!e.headed&&!e.headless&&h.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&&h.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:"}),h.length>0){let v=await oe.prompt(h);Object.assign(i,v)}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 b=me[i.agent];i.claudeOauthToken&&(xe("CLAUDE_CODE_OAUTH_TOKEN",i.claudeOauthToken),console.log(l.gray(" Claude OAuth subscription token saved to ~/.zibby/config.json")),console.log(l.gray(" Used by: zibby test / chat / workflow run / workflow start"))),i.agentKey&&(Qe(i.agentKey,i.agent),console.log(l.gray(" Agent API key saved to ~/.zibby/config.json"))),i.mcp="playwright",i.setupMcp=i.agent==="cursor";let k=X("Setting up Zibby...").start();try{if(c&&await D(r,{recursive:!0}),o&&(await D(y(r,"test-specs/examples"),{recursive:!0}),await D(y(r,"tests"),{recursive:!0})),await D(y(r,".zibby/output"),{recursive:!0}),await D(y(r,".zibby/commands"),{recursive:!0}),s&&n==="dolt")try{let{initMemory:g,DoltDB:w}=await import("@zibby/ui-memory");if(w.isAvailable()){let{created:m}=g(r);m&&(k.text="Initialized test memory database (Dolt)...")}else k.text="Dolt not found \u2014 skipping memory database (brew install dolt)"}catch{}let f=e.template,S=f&&f!=="none"&&f!=="false";if(S){k.text=`Scaffolding workflow template: ${f}...`;try{let{writeTemplateFiles:g}=await Promise.resolve().then(()=>(Ae(),Ce));await g(r,f,{enableMemory:s})}catch(g){throw k.fail(`Failed to scaffold template: ${g.message}`),g}}else await D(y(r,".zibby"),{recursive:!0});k.text="Generating configuration files...";let h=ke(i,e,{memoryBackend:n});if(await P(y(r,".zibby.config.mjs"),h),await P(y(r,".env.example"),Nn(i,n)),i.apiKey&&i.apiKey.trim()){let g=y(r,".env"),w=i.apiKey.trim();if(C(g)){let m=await K(g,"utf8");/^ZIBBY_API_KEY=/m.test(m)?m=m.replace(/^ZIBBY_API_KEY=.*/m,`ZIBBY_API_KEY=${w}`):/^#\s*ZIBBY_API_KEY=/m.test(m)?m=m.replace(/^#\s*ZIBBY_API_KEY=.*/m,`ZIBBY_API_KEY=${w}`):m=`${m.trimEnd()}
|
|
120
125
|
|
|
121
126
|
# Zibby Cloud Sync
|
|
122
|
-
ZIBBY_API_KEY=${
|
|
123
|
-
`,await
|
|
127
|
+
ZIBBY_API_KEY=${w}
|
|
128
|
+
`,await P(g,m)}else await P(g,Bn(i,w,n))}if(i.agentKey&&b){let g=y(r,".env"),w=i.agentKey;if(C(g)){let m=await K(g,"utf8"),x=new RegExp(`^${b.envVar}=.*`,"m"),$=new RegExp(`^#\\s*${b.envVar}=.*`,"m");x.test(m)?m=m.replace(x,`${b.envVar}=${w}`):$.test(m)?m=m.replace($,`${b.envVar}=${w}`):m=`${m.trimEnd()}
|
|
124
129
|
|
|
125
130
|
# AI Agent Key
|
|
126
|
-
${
|
|
127
|
-
`,await
|
|
128
|
-
Using mem0 backend requires mem0ai in your project dependencies.`)),console.log(
|
|
129
|
-
`))),!e.skipInstall&&
|
|
131
|
+
${b.envVar}=${w}
|
|
132
|
+
`,await P(g,m)}}if(c){let g=Mn(u,i,{memoryBackend:n});await P(y(r,"package.json"),g)}if(!C(y(r,".gitignore"))){let g=Kn();await P(y(r,".gitignore"),g)}if(o){if(!C(y(r,"playwright.config.js"))){let g=Ln("on");await P(y(r,"playwright.config.js"),g)}if(!C(y(r,"test-specs/examples/example-domain.txt"))){let g=Dn();await P(y(r,"test-specs/examples/example-domain.txt"),g)}}let v=De(Jt,"../../../../examples/.zibby/commands");if(C(v)){let g=we(v).filter(w=>w.toLowerCase().endsWith(".md"));for(let w of g){let m=y(r,".zibby/commands",w);if(e.force||!C(m)){let x=await K(y(v,w),"utf-8");await P(m,x)}}}if(!C(y(r,".zibby/commands/example.md"))){let g=Un();await P(y(r,".zibby/commands/example.md"),g)}let j=De(Jt,"../../templates"),_=y(j,".claude"),E=!1,O=0,W=0,Z=0,ie=null;if(C(_)){await D(y(r,".claude"),{recursive:!0}),await D(y(r,".claude","commands"),{recursive:!0}),await D(y(r,".claude","agents"),{recursive:!0});let g=y(_,"CLAUDE.md"),w=y(r,".claude","CLAUDE.md");if(C(g)&&(e.force||!C(w))){let $=await K(g,"utf-8");await P(w,$),E=!0}let m=y(_,"commands");if(C(m)){let $=we(m).filter(A=>A.toLowerCase().endsWith(".md"));for(let A of $){let F=y(r,".claude","commands",A);if(e.force||!C(F)){let B=await K(y(m,A),"utf-8");await P(F,B),O++}}}let x=y(_,"agents");if(C(x)){let $=we(x).filter(A=>A.toLowerCase().endsWith(".md"));for(let A of $){let F=y(r,".claude","agents",A);if(e.force||!C(F)){let B=await K(y(x,A),"utf-8");await P(F,B),W++}}}}let ve=y(j,".cursor","rules");if(C(ve)){await D(y(r,".cursor","rules"),{recursive:!0});let g=we(ve).filter(w=>w.toLowerCase().endsWith(".mdc"));for(let w of g){let m=y(r,".cursor","rules",w);if(e.force||!C(m)){let x=await K(y(ve,w),"utf-8");await P(m,x),Z++}}}let Ze=y(j,"AGENTS.md");if(C(Ze)){let{upsertManagedBlock:g}=await Promise.resolve().then(()=>(at(),it)),w=y(r,"AGENTS.md"),m=await K(Ze,"utf-8"),x=C(w)?await K(w,"utf-8"):null,{content:$,action:A}=g(x,m);A!=="skipped"&&await P(w,$),ie=A}if(E&&console.log(l.green(" \u2713 Wrote .claude/CLAUDE.md (workflow + apps knowledge)")),O>0&&console.log(l.green(` \u2713 Wrote .claude/commands/ (${O} slash command${O===1?"":"s"})`)),W>0&&console.log(l.green(` \u2713 Wrote .claude/agents/ (${W} subagent definition${W===1?"":"s"})`)),Z>0&&console.log(l.green(` \u2713 Wrote .cursor/rules/ (${Z} Cursor rule${Z===1?"":"s"})`)),ie==="created"?console.log(l.green(" \u2713 Wrote AGENTS.md (Zibby section, managed block)")):ie==="updated"&&console.log(l.green(" \u2713 Updated AGENTS.md (Zibby section, your content preserved)")),c){let g=Yn(u,i);await P(y(r,"README.md"),g)}try{let{validateMemorySyncConfig:g,applyMemorySyncConfig:w}=await Promise.resolve().then(()=>(dt(),ut)),m=y(r,".zibby.config.mjs"),x=null;if(C(m))try{x=(await import(`file://${m}?t=${Date.now()}`)).default?.memorySync}catch{}let $=g(x);if($.ok&&$.kind!=="noop"){let A=await import("@zibby/ui-memory").catch(()=>null),{getSessionToken:F}=await Promise.resolve().then(()=>(Pe(),_e)),B=await w({cwd:r,projectId:i.projectId,block:x,memoryApi:A,getSessionToken:F,hostedSetup:async({cwd:ue,projectId:de})=>{let{memoryRemoteUseHostedCommand:Ge}=await Promise.resolve().then(()=>(Mt(),Bt));await Ge({cwd:ue,projectId:de})},logger:{info:()=>{},warn:()=>{},error:()=>{}}});B.action==="hosted"?console.log(l.green(" \u2713 Hosted memory-sync configured from .zibby.config.mjs")):B.action==="byo"?console.log(l.green(` \u2713 Memory remote configured from .zibby.config.mjs \u2192 ${B.remote}`)):B.action==="pending-login"?(console.log(l.yellow(` \u26A0 memorySync.remote = "hosted" but you're not logged in.`)),console.log(l.gray(" Run `zibby login` then `zibby memory remote use --hosted` to finish."))):B.action==="error"&&console.log(l.yellow(` \u26A0 memorySync setup skipped: ${B.reason}`))}else $.ok||console.log(l.yellow(` \u26A0 memorySync config invalid: ${$.error}`))}catch(g){console.log(l.yellow(` \u26A0 memorySync auto-apply failed: ${g.message}`))}if(k.succeed(c?"Project created!":"Zibby initialized!"),S||(console.log(""),console.log(l.gray(" No workflow scaffolded. Add one when ready:")),console.log(l.gray(" zibby template list # see available")),console.log(l.gray(" zibby workflow new <slug> -t <template> # named, deployable copy")),console.log("")),c&&!e.skipInstall){let g=X("Installing dependencies...").start();await new Promise((w,m)=>{pe("npm",["install"],{cwd:r,stdio:"pipe"}).on("close",$=>{$===0?(g.succeed("Dependencies installed!"),w()):(g.fail("Failed to install dependencies"),m(new Error("npm install failed")))})})}if(!c&&s&&n==="mem0"&&(console.log(l.yellow(`
|
|
133
|
+
Using mem0 backend requires mem0ai in your project dependencies.`)),console.log(l.gray("Run this manually in your project when ready:")),console.log(l.white(` npm install mem0ai
|
|
134
|
+
`))),!e.skipInstall&&o){let g=X("Installing Playwright browsers...").start();await new Promise(w=>{let m=pe("npx",["playwright","install","chromium"],{cwd:r,stdio:"pipe"}),x="";m.stdout.on("data",$=>{x+=$.toString()}),m.stderr.on("data",$=>{x+=$.toString()}),m.on("close",$=>{$===0?(x.includes("already installed")||x.includes("up to date")?g.succeed("Playwright browsers already installed"):g.succeed("Playwright browsers installed!"),w()):(g.warn("Could not verify Playwright browsers"),console.log(l.yellow(`
|
|
130
135
|
If tests fail, run: npx playwright install
|
|
131
|
-
`)),
|
|
132
|
-
`))}}}if(i.agent==="codex"&&!e.skipInstall){let
|
|
133
|
-
`))}}}if(i.agent==="gemini"&&!e.skipInstall){let
|
|
134
|
-
`))}}if(
|
|
135
|
-
`,"utf-8");let
|
|
136
|
-
`))}}}if(i.agent==="cursor"&&i.setupMcp&&
|
|
136
|
+
`)),w())})})}if(i.agent==="cursor"&&!e.skipInstall){let g=X("Checking cursor-agent CLI...").start();try{be("cursor-agent --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),g.succeed("cursor-agent CLI already installed")}catch{g.text="Installing cursor-agent CLI...";try{await new Promise((w,m)=>{pe("bash",["-c","curl https://cursor.com/install -fsS | bash"],{stdio:"pipe"}).on("close",$=>{if($===0){let A=y(Q(),".local","bin");process.env.PATH.includes(A)||(process.env.PATH=`${A}:${process.env.PATH}`),g.succeed("cursor-agent CLI installed!"),w()}else m(new Error("cursor-agent install failed"))})})}catch{g.fail("Could not install cursor-agent CLI"),console.log(l.yellow(` Install manually: curl https://cursor.com/install -fsS | bash
|
|
137
|
+
`))}}}if(i.agent==="codex"&&!e.skipInstall){let g=X("Checking Codex CLI...").start();try{be("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),g.succeed("Codex CLI already installed")}catch{g.text="Installing Codex CLI...";try{await new Promise((w,m)=>{pe("npm",["install","-g","@openai/codex"],{stdio:"pipe"}).on("close",$=>{$===0?(g.succeed("Codex CLI installed!"),w()):m(new Error("npm install -g @openai/codex failed"))})})}catch{g.fail("Could not install Codex CLI"),console.log(l.yellow(` Install manually: npm install -g @openai/codex
|
|
138
|
+
`))}}}if(i.agent==="gemini"&&!e.skipInstall){let g=X("Checking Gemini CLI...").start();try{be("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),g.succeed("Gemini CLI already installed")}catch{g.text="Installing Gemini CLI...";try{await new Promise((w,m)=>{pe("npm",["install","-g","@google/gemini-cli"],{stdio:"pipe"}).on("close",$=>{$===0?(g.succeed("Gemini CLI installed!"),w()):m(new Error("npm install -g @google/gemini-cli failed"))})})}catch{g.fail("Could not install Gemini CLI"),console.log(l.yellow(` Install manually: npm install -g @google/gemini-cli
|
|
139
|
+
`))}}if(o){let w=X("Configuring Gemini MCP servers...").start();try{let m=y(Q(),".gemini"),x=y(m,"settings.json");C(m)||await D(m,{recursive:!0});let $={mcpServers:{}};if(C(x))try{let de=await K(x,"utf-8");$=JSON.parse(de),$.mcpServers||($.mcpServers={})}catch{}let A;try{let{createRequire:de}=await import("module");A=de(import.meta.url).resolve("@zibby/mcp-browser/bin/mcp-browser-zibby.js")}catch{A="@playwright/mcp"}let F=i.browserMode!=="headless",B=A==="@playwright/mcp"?["-y","@playwright/mcp","--isolated","--viewport-size=1280x720","--output-dir","test-results"]:[A,"--isolated","--viewport-size=1280x720","--output-dir=test-results"];F||B.push("--headless"),$.mcpServers["playwright-official"]={command:A==="@playwright/mcp"?"npx":"node",args:B},await P(x,`${JSON.stringify($,null,2)}
|
|
140
|
+
`,"utf-8");let ue="Gemini MCP configured";F?ue+=" (headed mode - visible browser)":ue+=" (headless mode - hidden browser)",w.succeed(ue)}catch(m){w.fail("MCP setup failed"),console.log(l.yellow(" You may need to configure ~/.gemini/settings.json manually")),console.log(l.gray(` Error: ${m.message}
|
|
141
|
+
`))}}}if(i.agent==="cursor"&&i.setupMcp&&o){let g=X("Setting up Playwright MCP...").start();try{let{setupPlaywrightMcpCommand:w}=await Promise.resolve().then(()=>(Vt(),Gt)),m=i.cloudSync||!1,x=i.browserMode!=="headless";await w({headed:x,cloudSync:m,viewport:{width:1280,height:720}});let $="Playwright MCP configured";x?$+=" (headed mode - visible browser)":$+=" (headless mode - hidden browser)",m&&($+=" + Zibby MCP (cloud sync)"),g.succeed($),m&&!(i.apiKey&&i.apiKey.trim())&&console.log(l.gray(`
|
|
137
142
|
Copy .env.example to .env and set ZIBBY_API_KEY to enable uploads
|
|
138
|
-
`))}catch(
|
|
139
|
-
`)),console.log(
|
|
140
|
-
`))}}console.log(
|
|
143
|
+
`))}catch(w){g.fail("MCP setup script failed"),console.log(l.yellow(" Check if MCP is already configured:")),console.log(l.gray(' \u2022 Open Cursor settings \u2192 Check "playwright-official" MCP')),console.log(l.gray(" \u2022 Run: cursor-agent mcp list")),console.log(l.gray(` \u2022 Or run manually: zibby setup-playwright
|
|
144
|
+
`)),console.log(l.gray(` Error: ${w.message}
|
|
145
|
+
`))}}console.log(l.bold.green(`
|
|
141
146
|
All set!
|
|
142
|
-
`)),
|
|
143
|
-
`))),
|
|
144
|
-
`)),console.log(
|
|
145
|
-
`))):(console.log(
|
|
146
|
-
`)),console.log(
|
|
147
|
-
Error: ${
|
|
148
|
-
`)),process.exit(1)}}function
|
|
149
|
-
auth: '${
|
|
147
|
+
`)),c&&(console.log(l.cyan("Get into the project:")),console.log(l.white(` cd ${t}
|
|
148
|
+
`))),o?(console.log(l.cyan("Run a test:")),console.log(l.white(` zibby test test-specs/examples/example-domain.txt
|
|
149
|
+
`)),console.log(l.cyan("Cloud features (optional):")),console.log(l.white(` zibby login ${l.gray("# unlock workflow deploy, hosted memory, etc.")}`)),console.log(""),console.log(l.cyan("Next steps:")),console.log(l.white(` 1. cp .env.example .env ${l.gray("# then add your API keys")}`)),console.log(l.white(` 2. Write test specs in ${l.bold("test-specs/")}`)),console.log(l.white(` 3. Run: ${l.bold("zibby test <spec-file>")}`)),console.log(l.white(` 4. Or chat: ${l.bold("zibby")}
|
|
150
|
+
`))):(console.log(l.cyan("Add a workflow when ready:")),console.log(l.white(` zibby template list ${l.gray("# see available")}`)),console.log(l.white(` zibby workflow new my-pipeline ${l.gray("# blank scaffold")}`)),console.log(l.white(` zibby workflow new my-pip -t <name> ${l.gray("# from a template")}
|
|
151
|
+
`)),console.log(l.cyan("Cloud features (optional):")),console.log(l.white(` zibby login ${l.gray("# unlock workflow deploy, hosted memory, etc.")}`)),console.log(""))}catch(f){k.fail("Failed to create project"),console.error(l.red(`
|
|
152
|
+
Error: ${f.message}
|
|
153
|
+
`)),process.exit(1)}}function ke(t,e={},o={}){let s=["dolt","mem0"].includes(String(o.memoryBackend||"").toLowerCase())?String(o.memoryBackend).toLowerCase():"dolt",n=t.agentAuth==="oauth"||t.agentAuth==="api"?`
|
|
154
|
+
auth: '${t.agentAuth}', // 'oauth' (subscription) or 'api' (pay-per-token); cloud needs 'api'`:"",r={claude:`
|
|
150
155
|
claude: {
|
|
151
156
|
model: 'auto', // Options: 'auto', 'sonnet-4.6', 'opus-4.6', 'sonnet-4.5', 'opus-4.5'
|
|
152
|
-
maxTokens: 4096,${
|
|
157
|
+
maxTokens: 4096,${t.agent==="claude"?n:""}
|
|
153
158
|
},`,cursor:`
|
|
154
159
|
cursor: {
|
|
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'${
|
|
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"?n:""}
|
|
156
161
|
},`,codex:`
|
|
157
162
|
codex: {
|
|
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'${
|
|
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"?n:""}
|
|
159
164
|
},`,gemini:`
|
|
160
165
|
gemini: {
|
|
161
|
-
model: 'gemini-2.5-pro', // Options: 'auto', 'gemini-2.5-pro', 'gemini-2.5-flash'${
|
|
162
|
-
},`},u=
|
|
166
|
+
model: 'gemini-2.5-pro', // Options: 'auto', 'gemini-2.5-pro', 'gemini-2.5-flash'${t.agent==="gemini"?n:""}
|
|
167
|
+
},`},u=t.agent,c=Object.entries(r).filter(([i])=>i!==u).map(([,i])=>i.split(`
|
|
163
168
|
`).map(d=>d.trim()?` // ${d.trimStart()}`:d).join(`
|
|
164
169
|
`)).join(`
|
|
165
170
|
`);return`export default {
|
|
166
171
|
// AI agent settings
|
|
167
172
|
agent: {${r[u]}
|
|
168
|
-
${
|
|
173
|
+
${c}
|
|
169
174
|
strictMode: false,
|
|
170
175
|
},
|
|
171
176
|
|
|
@@ -173,7 +178,7 @@ ${l}
|
|
|
173
178
|
// and workflow config. Runtime strategies attach MCP per run (no global Gemini settings mutation).
|
|
174
179
|
browser: {
|
|
175
180
|
mcp: 'playwright',
|
|
176
|
-
headless: ${
|
|
181
|
+
headless: ${t.browserMode==="headless"},
|
|
177
182
|
},
|
|
178
183
|
|
|
179
184
|
// Chat memory backend adapter (dolt | mem0)
|
|
@@ -211,7 +216,7 @@ ${l}
|
|
|
211
216
|
specs: 'test-specs', // Where your .txt test specs are
|
|
212
217
|
generated: 'tests', // Where generated .spec.js files go
|
|
213
218
|
output: '.zibby/output', // Where workflow execution results are saved (default: .zibby/output)
|
|
214
|
-
workflows: '${
|
|
219
|
+
workflows: '${t.workflowsPath||"workflows"}', // Where custom workflows are stored (visible at project root; .zibby/ is runtime/scratch only)
|
|
215
220
|
// sessionPrefix: 'run', // Optional: prefix for session folders (e.g., run_1772788458045)
|
|
216
221
|
},
|
|
217
222
|
|
|
@@ -246,13 +251,13 @@ ${l}
|
|
|
246
251
|
},
|
|
247
252
|
|
|
248
253
|
// Cloud sync - auto-upload test results & videos (requires ZIBBY_API_KEY in .env)
|
|
249
|
-
cloudSync: ${
|
|
254
|
+
cloudSync: ${t.cloudSync||!1}
|
|
250
255
|
};
|
|
251
|
-
`}function
|
|
256
|
+
`}function Nn(t,e="dolt"){return`# Zibby Test Automation - Environment Variables
|
|
252
257
|
|
|
253
258
|
# AI Provider Keys
|
|
254
259
|
${{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"}[
|
|
260
|
+
# Install: curl https://cursor.com/install -fsS | bash`,codex:"OPENAI_API_KEY=sk-your_key_here",gemini:"GEMINI_API_KEY=your_key_here"}[t.agent]||""}
|
|
256
261
|
|
|
257
262
|
# Zibby Cloud Sync (for uploading test results & videos)
|
|
258
263
|
# Get your API key from: https://zibby.dev/settings/tokens
|
|
@@ -265,10 +270,10 @@ ${{claude:"ANTHROPIC_API_KEY=sk-ant-your_key_here",cursor:`# Cursor Agent uses c
|
|
|
265
270
|
|
|
266
271
|
# Chat memory backend
|
|
267
272
|
ZIBBY_MEMORY_BACKEND=${e}
|
|
268
|
-
`}function
|
|
273
|
+
`}function Bn(t,e,o="dolt"){return`# Zibby Test Automation - Environment Variables
|
|
269
274
|
|
|
270
275
|
# 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"}[
|
|
276
|
+
${{claude:"ANTHROPIC_API_KEY=sk-ant-your_key_here",cursor:"# Cursor Agent uses cursor-agent CLI \u2014 no API key needed",codex:"OPENAI_API_KEY=sk-your_key_here",gemini:"GEMINI_API_KEY=your_key_here"}[t.agent]||""}
|
|
272
277
|
|
|
273
278
|
# Zibby Cloud Sync
|
|
274
279
|
ZIBBY_API_KEY=${e}
|
|
@@ -279,8 +284,8 @@ ZIBBY_API_KEY=${e}
|
|
|
279
284
|
# ZIBBY_MEMORY_COMPACT_EVERY=1500 # Auto-compact every N runs (0 to disable)
|
|
280
285
|
|
|
281
286
|
# Chat memory backend
|
|
282
|
-
ZIBBY_MEMORY_BACKEND=${
|
|
283
|
-
`}function
|
|
287
|
+
ZIBBY_MEMORY_BACKEND=${o}
|
|
288
|
+
`}function Mn(t,e,o={}){let n={"@zibby/cli":"latest","@zibby/core":Rn("../../package.json").dependencies?.["@zibby/core"]||"latest"};return o.memoryBackend==="mem0"&&(n.mem0ai="^2.4.6"),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 Kn(){return`# Dependencies
|
|
284
289
|
node_modules/
|
|
285
290
|
|
|
286
291
|
# Test artifacts
|
|
@@ -308,7 +313,7 @@ Thumbs.db
|
|
|
308
313
|
# Zibby memory (Dolt DB synced separately via dolt remote, not git)
|
|
309
314
|
.zibby/memory/
|
|
310
315
|
.zibby/memory-context.md
|
|
311
|
-
`}function
|
|
316
|
+
`}function Ln(t="off",e=null){return`import { defineConfig} from '@playwright/test';
|
|
312
317
|
|
|
313
318
|
export default defineConfig({
|
|
314
319
|
testDir: './tests',
|
|
@@ -330,7 +335,7 @@ ${e?` outputDir: '${e}',
|
|
|
330
335
|
['list']
|
|
331
336
|
],
|
|
332
337
|
});
|
|
333
|
-
`}function
|
|
338
|
+
`}function Dn(){return`Test Specification: Example Domain Navigation
|
|
334
339
|
==============================================
|
|
335
340
|
|
|
336
341
|
Application: Example Domain
|
|
@@ -367,7 +372,7 @@ Notes:
|
|
|
367
372
|
- Uses a stable, public domain (example.com) maintained by IANA
|
|
368
373
|
- No authentication required
|
|
369
374
|
- Suitable for CI/CD smoke testing
|
|
370
|
-
`}function
|
|
375
|
+
`}function Un(){return`# Example command template
|
|
371
376
|
|
|
372
377
|
Use this command when the user asks for a concise testing task breakdown.
|
|
373
378
|
|
|
@@ -378,7 +383,7 @@ Required output format:
|
|
|
378
383
|
4. Expected result
|
|
379
384
|
|
|
380
385
|
Keep the response actionable and short.
|
|
381
|
-
`}function
|
|
386
|
+
`}function Yn(t,e){return`# ${t}
|
|
382
387
|
|
|
383
388
|
AI-powered test automation with Zibby.
|
|
384
389
|
|
|
@@ -449,7 +454,7 @@ Edit \`.zibby.config.mjs\` to customize:
|
|
|
449
454
|
## Project Structure
|
|
450
455
|
|
|
451
456
|
\`\`\`
|
|
452
|
-
${
|
|
457
|
+
${t}/
|
|
453
458
|
\u251C\u2500\u2500 .zibby/
|
|
454
459
|
\u2502 \u251C\u2500\u2500 graph.mjs # Workflow definition
|
|
455
460
|
\u2502 \u251C\u2500\u2500 nodes/ # Custom nodes
|
|
@@ -467,25 +472,25 @@ ${o}/
|
|
|
467
472
|
|
|
468
473
|
- Documentation: https://docs.zibby.dev
|
|
469
474
|
- Examples: https://github.com/zibby/examples
|
|
470
|
-
`}var
|
|
475
|
+
`}var jn,Jt,Rn,Ue=H(()=>{et();jn=Pn(import.meta.url),Jt=_n(jn),Rn=En(import.meta.url)});import{mkdir as We,writeFile as V,readFile as sr,readdir as ir}from"fs/promises";import{existsSync as ge}from"fs";import{spawn as ar}from"child_process";import{join as z}from"path";import p from"chalk";import oo from"ora";import{input as no}from"@inquirer/prompts";import{existsSync as po}from"fs";import{join as go}from"path";import{pathToFileURL as mo}from"url";async function Ve(t){let e=go(t,".zibby.config.mjs");if(!po(e))throw new Error(".zibby.config.mjs not found");try{let o=await import(mo(e).href);return o.default||o}catch(o){throw new Error(`Failed to load .zibby.config.mjs: ${o.message}`,{cause:o})}}Ue();import{readFileSync as ne,existsSync as Y,mkdirSync as Ye,writeFileSync as re,statSync as Fn,chmodSync as Hn}from"fs";import{join as N,dirname as $e}from"path";import{fileURLToPath as Wn}from"url";import U from"chalk";var ce=["claude","cursor","codex"],Zn=$e(Wn(import.meta.url)),Fe=N(Zn,"..","..","..","templates","zibby-workflow-claude"),Gn="<!-- BEGIN zibby-workflows",Xt="<!-- END zibby-workflows -->";function Vn(t){let e=process.argv[1];if(!e||!Y(e))return null;let o=N(t,".zibby","bin"),s=N(o,"zibby");Ye(o,{recursive:!0});let n=`#!/bin/sh
|
|
471
476
|
# Auto-generated by 'zibby workflow generate'. Re-runs of generate update this path.
|
|
472
477
|
# Lets agents (Claude / Cursor / Codex) and CI scripts call zibby reliably even
|
|
473
478
|
# when the CLI isn't on PATH. Delete this file or .zibby/bin/ to disable.
|
|
474
479
|
exec node ${JSON.stringify(e)} "$@"
|
|
475
|
-
`;
|
|
476
|
-
`;if(!
|
|
480
|
+
`;re(s,n);try{Fn(s)}catch{}try{Hn(s,493)}catch{}return s}function Jn(){let t=N(Fe,"manifest.json");return JSON.parse(ne(t,"utf8"))}function Qt(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(!Y(t))return{write:!0,reason:"new"};if(o)return{write:!0,reason:"force"};let s=ne(t,"utf8"),n=Qt(s),r=Qt(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 Xn(t,e){let o=`${e.trim()}
|
|
481
|
+
`;if(!Y(t))return re(t,o),"created";let s=ne(t,"utf8"),n=s.indexOf(Gn),r=s.indexOf(Xt);if(n!==-1&&r!==-1&&r>n){let c=s.slice(0,n),i=s.slice(r+Xt.length),d=c+o.trim()+i;return d===s?"unchanged":(re(t,d),"updated")}let u=s.endsWith(`
|
|
477
482
|
`)?`
|
|
478
483
|
`:`
|
|
479
484
|
|
|
480
|
-
`;return
|
|
485
|
+
`;return re(t,s+u+o),"appended"}function Qn(t,e,o,s){let n=o.agents[t];if(!n)return[];let r=[],u=c=>N(Fe,c.split("/").map(i=>i.startsWith(".")?i.slice(1):i).join("/"));for(let c of n.files||[]){let i=u(c);if(!Y(i))continue;let d=ne(i,"utf8"),b=N(e,c),k=qn(b,d,s);k.write?(Ye($e(b),{recursive:!0}),re(b,d),r.push({path:c,action:"write",detail:k.reason})):r.push({path:c,action:"skip",detail:k.reason})}for(let c of n.writeOnceFiles||[]){let i=u(c);if(!Y(i))continue;let d=N(e,c);if(Y(d)){r.push({path:c,action:"skip",detail:"write-once: already exists, leaving alone"});continue}Ye($e(d),{recursive:!0}),re(d,ne(i,"utf8")),r.push({path:c,action:"write",detail:"write-once: created"})}if(n.rootBlock){let c=N(Fe,n.rootBlock.source),i=ne(c,"utf8"),d=N(e,n.rootBlock.target),b=Xn(d,i);r.push({path:n.rootBlock.target,action:b})}return r}function er(t){let e=t;for(let o=0;o<6;o++){if(Y(N(e,".git"))||Y(N(e,".zibby.config.mjs"))||Y(N(e,"package.json")))return e;let s=$e(e);if(s===e)break;e=s}return t}async function tr(t){let e=N(t,".zibby.config.mjs");if(!Y(e))return null;try{return((await import(`file://${e}?t=${Date.now()}`)).default||{}).agentHelpers||null}catch(o){return console.log(U.gray(` (couldn't parse .zibby.config.mjs agentHelpers section: ${o.message})`)),null}}function or(t,e){let o=N(t,".zibby.config.mjs");if(!Y(o)){console.log(U.yellow(" \u26A0\uFE0F .zibby.config.mjs not found; agentHelpers state not persisted"));return}let s=ne(o,"utf8"),n=` agentHelpers: {
|
|
481
486
|
templateVersion: ${e.templateVersion},
|
|
482
487
|
agents: ${JSON.stringify(e.agents)},
|
|
483
488
|
updatedAt: '${new Date().toISOString()}',
|
|
484
489
|
},
|
|
485
490
|
`,r=/\s*agentHelpers\s*:\s*\{[^}]*\}\s*,?\n?/m,u;if(r.test(s))u=s.replace(r,`
|
|
486
|
-
${n}`);else{let
|
|
487
|
-
`:"")+n+s.slice(
|
|
488
|
-
* ${
|
|
491
|
+
${n}`);else{let c=s.lastIndexOf("}");if(c===-1)return;let i=s.slice(0,c),d=i.replace(/\s+$/,"").slice(-1);u=i+(d&&d!==","&&d!=="{"?`,
|
|
492
|
+
`:"")+n+s.slice(c)}re(o,u)}function nr(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 rr({agentHelpersFlag:t,noAgentHelpers:e,existingConfig:o,legacyAgent:s}={}){if(e===!0)return{install:!1,reason:"explicit-no"};if(t!==void 0&&t!==!1){let n=nr(t);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:[...ce]};if(!ce.includes(s))throw new Error(`unknown agent "${s}" \u2014 supported: ${ce.join(", ")}`);return{install:!0,agents:[s]}}if(o&&Array.isArray(o.agents)&&o.agents.length>0){let n=o.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 eo(t={}){let{forcedAgents:e,force:o=!1,silent:s=!1}=t,n=t.projectRoot||er(process.cwd()),r=Jn(),u=await tr(n),c;if(e&&e.length>0?e.length===1&&e[0]==="none"?c={install:!1,reason:"explicit-no"}:c={install:!0,agents:e}:c=rr({agentHelpersFlag:t.agentHelpersFlag,noAgentHelpers:t.noAgentHelpers===!0,existingConfig:u,legacyAgent:t.legacyAgent}),!c.install)return c.reason==="explicit-no"?(t.noAgentHelpers===!0||t.legacyAgent==="none"||e&&e.length===1&&e[0],{action:"skipped-explicit-no"}):{action:"skipped-no-config"};let i=c.agents,d=Vn(n),b=[];for(let k of i){if(!r.agents[k])continue;Qn(k,n,r,o).forEach(S=>b.push({...S,agent:k}))}if(or(n,{templateVersion:r.templateVersion,agents:i}),!s){c.fromConfig&&console.log(U.gray(` agent helpers: ${i.join(", ")} (from .zibby.config.mjs)`));let k=b.filter(h=>["write","created","updated","appended"].includes(h.action)),f=b.filter(h=>h.action==="skip"),S=b.filter(h=>h.action==="unchanged");if(k.length>0){console.log(U.green(` \u2713 Wrote ${k.length} agent helper file(s):`));for(let h of k)console.log(U.gray(` ${h.path} (${h.detail||h.action})`))}if(f.length>0){console.log(U.yellow(` \u26A0\uFE0F Skipped ${f.length} (use --force-agents to overwrite):`));for(let h of f)console.log(U.gray(` ${h.path} \u2014 ${h.detail}`))}k.length===0&&f.length===0&&S.length>0&&console.log(U.gray(` Agent helpers up to date (template v${r.templateVersion}).`)),c.fromConfig||console.log(U.gray(` agentHelpers: { agents: [${i.map(h=>`"${h}"`).join(", ")}] } saved to .zibby.config.mjs`)),d&&console.log(U.gray(` CLI shim: ${d} (agents fall back to ./.zibby/bin/zibby if zibby isn't on PATH)`)),i.includes("claude")&&console.log(U.gray(" \u2192 Run `claude` and try /zibby-add-node"))}return{action:c.fromConfig?"installed-from-config":"installed",agents:i}}var se=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/;function to(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(se.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:se.test(e)?e:null}}function He(t,e){let o=e instanceof Set?e:new Set(e||[]);if(!o.has(t))return t;let s=t.match(/^(.+)-(\d+)$/),n=s?s[1]:t;for(let r=2;r<=99;r+=1){let u=`${n}-${r}`;if(se.test(u)&&!o.has(u))return u}return null}function lr(t){return new Promise(e=>{let o=ar("npm",["install","--no-audit","--no-fund"],{cwd:t,stdio:"pipe",shell:!1}),s="";o.stderr.on("data",n=>{s+=n.toString()}),o.on("error",()=>e({ok:!1,stderr:"npm not found on PATH"})),o.on("close",n=>e({ok:n===0,stderr:s}))})}var cr=se;async function ur(t){try{let e=await import(`@zibby/workflow-templates/${t}/workflow.json`,{with:{type:"json"}}),o=e?.default||e,s=o?.defaultSlug||o?.name;return typeof s=="string"&&se.test(s)?s:null}catch{return null}}var ro=["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"],so=["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 io(){let t=ro[Math.floor(Math.random()*ro.length)],e=so[Math.floor(Math.random()*so.length)];return`${t}-${e}`}function dr(t){return`${t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}Workflow`}function co(t){return`${t.split("-").map((o,s)=>s===0?o:o.charAt(0).toUpperCase()+o.slice(1)).join("")}StateSchema`}function pr(t,e){let o=co(e);return`/**
|
|
493
|
+
* ${t}
|
|
489
494
|
*
|
|
490
495
|
* buildGraph() \u2014 define nodes, edges, conditional routing
|
|
491
496
|
* onComplete(result) \u2014 post-processing after the graph finishes
|
|
@@ -498,12 +503,12 @@ ${n}`);else{let l=s.lastIndexOf("}");if(l===-1)return;let i=s.slice(0,l),d=i.rep
|
|
|
498
503
|
|
|
499
504
|
import { WorkflowAgent, WorkflowGraph } from '@zibby/core';
|
|
500
505
|
import { exampleNode } from './nodes/index.mjs';
|
|
501
|
-
import { ${
|
|
506
|
+
import { ${o} } from './state.js';
|
|
502
507
|
|
|
503
|
-
export class ${
|
|
508
|
+
export class ${t} extends WorkflowAgent {
|
|
504
509
|
buildGraph() {
|
|
505
510
|
const graph = new WorkflowGraph();
|
|
506
|
-
graph.setStateSchema(${
|
|
511
|
+
graph.setStateSchema(${o});
|
|
507
512
|
|
|
508
513
|
graph.addNode('example', exampleNode);
|
|
509
514
|
|
|
@@ -517,7 +522,7 @@ export class ${o} extends WorkflowAgent {
|
|
|
517
522
|
console.log(\`[${e}] workflow complete \u2014 success: \${result.success !== false}\`);
|
|
518
523
|
}
|
|
519
524
|
}
|
|
520
|
-
`}function
|
|
525
|
+
`}function gr(t){return`/**
|
|
521
526
|
* Input state schema for this workflow.
|
|
522
527
|
*
|
|
523
528
|
* Declares the user-input fields callers can pass via:
|
|
@@ -541,7 +546,7 @@ export class ${o} extends WorkflowAgent {
|
|
|
541
546
|
|
|
542
547
|
import { z } from 'zod';
|
|
543
548
|
|
|
544
|
-
export const ${
|
|
549
|
+
export const ${co(t)} = z.object({
|
|
545
550
|
// Add user-input fields here. Examples:
|
|
546
551
|
//
|
|
547
552
|
// url: z.string().url().describe('Page to test'),
|
|
@@ -550,8 +555,8 @@ export const ${Qo(o)} = z.object({
|
|
|
550
555
|
//
|
|
551
556
|
// Then read them in any node via state.url / state.count / state.tags.
|
|
552
557
|
});
|
|
553
|
-
`}function
|
|
554
|
-
`}function
|
|
558
|
+
`}function mr(){return`export { exampleNode } from './example.mjs';
|
|
559
|
+
`}function fr(){return`import { z } from '@zibby/core';
|
|
555
560
|
|
|
556
561
|
const ExampleOutputSchema = z.object({
|
|
557
562
|
summary: z.string().describe('A short summary of the result'),
|
|
@@ -578,29 +583,29 @@ Analyze the input and return a summary with a status.\`,
|
|
|
578
583
|
|
|
579
584
|
outputSchema: ExampleOutputSchema,
|
|
580
585
|
};
|
|
581
|
-
`}function
|
|
582
|
-
`}var
|
|
583
|
-
`))}else console.log(
|
|
584
|
-
`))}function
|
|
585
|
-
`}async function
|
|
586
|
+
`}function ao(t,e){return`${JSON.stringify({name:t,description:`${e} workflow`,entryClass:e,triggers:{api:!0}},null,2)}
|
|
587
|
+
`}var yr=new Set(["cwd","sessionPath","outputPath","context","input"]);async function hr(t){try{let e=await sr(z(t,"graph.mjs"),"utf-8"),o=new Set,s=/addNode\(\s*['"`]([A-Za-z_][\w-]*)['"`]/g,n;for(;(n=s.exec(e))!==null;)o.add(n[1]);return o}catch{return new Set}}async function wr(t){try{let e=await import(`@zibby/workflow-templates/${t}/state.js`),o=c=>{if(!c||typeof c!="object")return!1;try{let i=c.shape;return i&&typeof i=="object"&&Object.keys(i).length>0}catch{return!1}},s=null,n=null,r=null;for(let[c,i]of Object.entries(e))o(i)&&(r||(r=i),!s&&/InputSchema$/.test(c)&&(s=i),!n&&/StateSchema$/.test(c)&&(n=i));let u=s||n||r;return u?{schema:u,shape:u.shape}:null}catch{return null}}function br(t,e){try{let o=[],s=[];for(let[n,r]of Object.entries(t)){if(yr.has(n)||e.has(n))continue;let u=!1;try{u=r?.isOptional?.()===!0}catch{}u?s.push(n):o.push(n)}return{required:o,optional:s}}catch{return null}}async function kr(t,e,o){let s=null;if(e)try{let n=await wr(e);if(n){let r=await hr(o);s=br(n.shape,r)}}catch{s=null}if(console.log(p.white(" Pass inputs:")),s&&s.required.length+s.optional.length>0){let{required:n,optional:r}=s,u=n[0]||r[0],c=`<${u}>`;console.log(p.gray(` ${p.white(`zibby workflow run ${t} -p ${u}="${c}"`)}`));let i=[...n.slice(0,3),...r.slice(0,1)],d={};for(let f of i)f==="model"?d[f]="opus-4.6":d[f]=`<${f}>`;console.log(p.gray(` ${p.white(`zibby workflow run ${t} --input '${JSON.stringify(d)}'`)}`)),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=i,k=b.length>0?`${b.map(f=>p.white(`state.${f}`)).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
|
+
`))}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 lo(t){let e={"@zibby/core":"^0.3.0",...t};return`${JSON.stringify({type:"module",dependencies:e},null,2)}
|
|
590
|
+
`}async function Cs(t,e={}){if(!e.skipInitCheck){let{homedir:h}=await import("os"),v=process.env.ZIBBY_CONFIG_DIR?z(process.env.ZIBBY_CONFIG_DIR,"config.json"):z(h(),".zibby","config.json");if(!ge(v)){console.log(p.gray(`
|
|
586
591
|
Looks like first run on this machine \u2014 let's do a quick setup so the
|
|
587
592
|
scaffolded workflow can actually run. (Skip with --skip-init-check.)
|
|
588
|
-
`));let{initCommand:
|
|
589
|
-
Init failed: ${
|
|
590
|
-
`)),console.log(
|
|
591
|
-
No name provided \u2014 generated: ${
|
|
592
|
-
Invalid workflow name: "${
|
|
593
|
-
`)),process.exit(1));let r=process.cwd(),u=
|
|
594
|
-
Common picks: ${
|
|
595
|
-
`));let
|
|
596
|
-
Workflow already exists: ${i}/${n}/`)),console.log(
|
|
597
|
-
`)),process.exit(1));let
|
|
598
|
-
Created:`)),console.log(
|
|
599
|
-
`)[0]||"unknown error"})`),console.log(
|
|
600
|
-
${
|
|
601
|
-
`)),process.exit(1)),console.log(
|
|
602
|
-
Next steps:`));let
|
|
603
|
-
`)),await
|
|
604
|
-
`)))}catch(h){
|
|
593
|
+
`));let{initCommand:j}=await Promise.resolve().then(()=>(Ue(),qt));try{await j(void 0,{...e,template:void 0})}catch(_){console.log(p.red(`
|
|
594
|
+
Init failed: ${_.message}
|
|
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 s(){let h=new Set;for(let v of["workflows",".zibby/workflows"])try{let j=await ir(z(process.cwd(),v),{withFileTypes:!0});for(let _ of j)_.isDirectory()&&se.test(_.name)&&h.add(_.name)}catch{}return h}let n;if(t)n=t.toLowerCase();else if(o&&process.stdin.isTTY&&!e.skipInitCheck){let h=await s(),v=await ur(o),j=v?He(v,h)||v:io(),E=(await no({message:`Name this workflow ${p.gray(`[Enter for ${j}]`)}`,validate:O=>{let W=(O||"").trim();if(W==="")return!0;let Z=to(W);if(!Z.valid)return Z.reason+(Z.suggestion?` \u2014 try "${Z.suggestion}"`:"");if(h.has(W)){let ie=He(W,h);return ie?`Already exists locally \u2014 try "${ie}"`:"Already exists locally \u2014 pick a different name"}return!0}})||"").trim();n=E===""?j:E.toLowerCase()}else n=io(),console.log(p.gray(`
|
|
596
|
+
No name provided \u2014 generated: ${p.white(n)}`));cr.test(n)||(console.log(p.red(`
|
|
597
|
+
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 r=process.cwd(),u=z(r,".zibby.config.mjs"),c=ge(u),i="workflows";if(c)try{let h=await Ve(r);h?.paths?.workflows&&(i=h.paths.workflows)}catch(h){console.log(p.yellow(` \u26A0\uFE0F Could not load .zibby.config.mjs: ${h.message}`)),console.log(p.gray(` Using default path: ${i}`))}else if(process.stdin.isTTY){console.log(p.gray(`
|
|
599
|
+
Common picks: ${p.white("workflows")} (visible at project root, default) \xB7 ${p.white(".zibby/workflows")} (hidden under runtime dir)
|
|
600
|
+
`));let v=(await no({message:`Where to save workflows? ${p.gray("[Enter for workflows]")}`})).trim();i=v===""?"workflows":v}else console.log(p.gray(` Using default workflows path: ${i} (run interactively to customize)`));let d=z(r,i,n),b=z(d,"nodes");ge(d)&&(console.log(p.red(`
|
|
601
|
+
Workflow already exists: ${i}/${n}/`)),console.log(p.gray(` Choose a different name or delete the existing folder.
|
|
602
|
+
`)),process.exit(1));let k=dr(n),f=o,S=oo(f?` Scaffolding workflow "${n}" from template ${p.cyan(f)}...`:` Scaffolding workflow "${n}"...`).start();try{if(await We(z(r,i),{recursive:!0}),f){let{writeTemplateFilesToDir:E}=await Promise.resolve().then(()=>(Ae(),Ce));await We(d,{recursive:!0});let{template:O}=await E(d,f);ge(z(d,"workflow.json"))||await V(z(d,"workflow.json"),ao(n,k)),ge(z(d,"package.json"))||await V(z(d,"package.json"),lo(O?.deps||{}))}else await We(b,{recursive:!0}),await Promise.all([V(z(d,"graph.mjs"),pr(k,n)),V(z(d,"state.js"),gr(n)),V(z(b,"index.mjs"),mr()),V(z(b,"example.mjs"),fr()),V(z(d,"workflow.json"),ao(n,k)),V(z(d,"package.json"),lo({zod:"^3.23.0"}))]);let h=!1;if(!c){let E=ke({agent:"claude",browserMode:"headless",workflowsPath:i},{},{memoryBackend:"dolt"});await V(u,E),h=!0}S.succeed(f?` Scaffolded ${p.bold(n)} from template ${p.cyan(f)}`:` Scaffolded ${p.bold(n)}`),console.log(p.green(`
|
|
603
|
+
Created:`)),console.log(p.white(` ${i}/${n}/`)),f?(console.log(p.gray(` graph.mjs (from template ${f})`)),console.log(p.gray(` nodes/ (from template ${f})`)),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)"))),h&&console.log(p.white(" .zibby.config.mjs project config (agent: claude \u2014 edit to switch)"));let v=!1;if(e.skipInstall)console.log(p.gray(` Skipped npm install (--skip-install). Run manually: cd ${i}/${n} && npm install`));else{let E=oo({text:` Installing dependencies in ${i}/${n}/...`,prefixText:""}).start(),O=await lr(d);O.ok?(E.succeed(` Installed dependencies in ${i}/${n}/`),v=!0):(E.warn(` Could not install dependencies (${O.stderr.trim().split(`
|
|
604
|
+
`)[0]||"unknown error"})`),console.log(p.gray(` Run manually: cd ${i}/${n} && npm install`)))}let j={action:"skipped-no-config"};try{j=await eo({projectRoot:r,agentHelpersFlag:e.agentHelpers,noAgentHelpers:e.agentHelpers===!1,legacyAgent:e.agent,force:e.forceClaude===!0||e.forceAgents===!0})||j}catch(E){/^unknown agent /.test(E.message)&&(console.log(p.red(`
|
|
605
|
+
${E.message}
|
|
606
|
+
`)),process.exit(1)),console.log(p.yellow(` \u26A0\uFE0F Agent helpers setup failed: ${E.message}`)),console.log(p.gray(" Run `zibby agents add` later to retry."))}console.log(p.white(`
|
|
607
|
+
Next steps:`));let _=1;!v&&e.skipInstall!==!0&&console.log(p.cyan(` ${_++}. Install deps: cd ${i}/${n} && npm install`)),console.log(p.cyan(` ${_++}. Edit nodes in ${i}/${n}/nodes/`)),console.log(p.cyan(` ${_++}. Wire them in graph.mjs`)),console.log(p.cyan(` ${_++}. Run locally: zibby workflow run ${n}`)),console.log(p.cyan(` ${_++}. Deploy to cloud: zibby workflow deploy ${n}
|
|
608
|
+
`)),await kr(n,f,d),j.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)
|
|
609
|
+
`)))}catch(h){S.fail(" Scaffold failed"),console.log(p.red(`
|
|
605
610
|
${h.message}
|
|
606
|
-
`)),process.exit(1)}}export{
|
|
611
|
+
`)),process.exit(1)}}export{Cs as generateWorkflowCommand};
|