@zibby/cli 0.4.1 → 0.4.3
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/commands/init.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var wo=Object.defineProperty;var
|
|
1
|
+
var wo=Object.defineProperty;var j=(e,o)=>()=>(e&&(o=e(e=0)),o);var D=(e,o)=>{for(var t in o)wo(e,t,{get:o[t],enumerable:!0})};var Pe={};D(Pe,{templateAddCommand:()=>Co,templateListCommand:()=>Po,writeTemplateFiles:()=>Ae});import{mkdir as Ie,writeFile as q,readFile as J}from"fs/promises";import{existsSync as ne,readdirSync as Ao}from"fs";import{join as O}from"path";import k from"chalk";async function Ae(e,o,t={}){let a=t.enableMemory!==!1,{TemplateFactory:i}=await import("@zibby/core/templates"),{graphPath:s,nodesPath:p,readmePath:u,resultHandlerPath:l,template:y}=i.getTemplateFiles(o),h=O(e,".zibby");ne(h)||await Ie(h,{recursive:!0});let v=[];await q(O(h,"graph.mjs"),await J(s,"utf-8")),v.push("graph.mjs"),l&&(await q(O(h,"result-handler.mjs"),await J(l,"utf-8")),v.push("result-handler.mjs")),await q(O(h,"README.md"),await J(u,"utf-8")),v.push("README.md");let w=O(h,"nodes");await Ie(w,{recursive:!0});for(let A of Ao(p)){let x=await J(O(p,A),"utf-8");!a&&A==="execute-live.mjs"&&(x=x.replace("skills: [SKILLS.BROWSER, SKILLS.MEMORY],","skills: [SKILLS.BROWSER],")),await q(O(w,A),x),v.push(`nodes/${A}`)}let I=O(y.path,"chat.mjs");return ne(I)&&(await q(O(h,"chat.mjs"),await J(I,"utf-8")),v.push("chat.mjs")),{template:y,copied:v}}async function Po(){let{TemplateFactory:e}=await import("@zibby/core/templates"),o=e.listTemplates();console.log(""),console.log(k.bold.cyan(" Available templates")),console.log("");for(let t of o){if(console.log(` ${k.cyan(t.name)}`),console.log(` ${k.white(t.displayName)}`),t.description&&console.log(` ${k.gray(t.description)}`),t.features&&t.features.length)for(let a of t.features)console.log(k.gray(` \u2022 ${a}`));console.log("")}console.log(k.gray(" Use: zibby template add <name> (or pass -t <name> to zibby init)")),console.log("")}async function Co(e,o={}){e||(console.log(k.red(`
|
|
2
2
|
Missing template name.
|
|
3
3
|
`)),console.log(k.gray(" Usage: zibby template add <name>")),console.log(k.gray(` See available templates: zibby template list
|
|
4
4
|
`)),process.exit(1));let t=o.cwd||process.cwd(),a=O(t,".zibby");ne(a)||(console.log(k.yellow(`
|
|
5
5
|
No .zibby/ directory in ${t}.
|
|
6
|
-
`)),console.log(k.gray(" Run `zibby init` first to bootstrap the project.\n")),process.exit(1));let
|
|
6
|
+
`)),console.log(k.gray(" Run `zibby init` first to bootstrap the project.\n")),process.exit(1));let i;try{i=await Ae(t,e,{enableMemory:o.enableMemory!==!1})}catch(s){console.log(k.red(`
|
|
7
7
|
${s.message}
|
|
8
8
|
`)),console.log(k.gray(` See available templates: zibby template list
|
|
9
|
-
`)),process.exit(1)}console.log(""),console.log(k.green(` \u2713 Added template ${k.bold(
|
|
9
|
+
`)),process.exit(1)}console.log(""),console.log(k.green(` \u2713 Added template ${k.bold(i.template.name)}`)),console.log(k.gray(` ${i.copied.length} files written to ${a}/`));for(let s of i.copied)console.log(k.gray(` \u2022 ${s}`));console.log(""),console.log(k.gray(" Re-running `zibby template add <name>` overwrites existing files \u2014")),console.log(k.gray(" use this to refresh after `npm update @zibby/core`.")),console.log("")}var Ce=j(()=>{});var Se={};D(Se,{applyMemorySyncConfig:()=>So,validateMemorySyncConfig:()=>$e});function $e(e){if(!e||typeof e!="object")return{ok:!0,kind:"noop"};let o=e.remote;return _o.includes(o)?{ok:!0,kind:"noop"}:typeof o!="string"?{ok:!1,error:`memorySync.remote must be null or a string, got ${typeof o}`}:o===$o?{ok:!0,kind:"hosted"}:_e.some(t=>o.startsWith(t))?{ok:!0,kind:"byo",remote:o}:{ok:!1,error:`memorySync.remote = ${JSON.stringify(o)} is not recognized. Use null, 'hosted', or a URL beginning with one of: ${_e.join(" / ")}.`}}async function So({cwd:e,projectId:o,block:t,memoryApi:a,hostedSetup:i,getSessionToken:s,logger:p=console}){let u=$e(t);if(!u.ok)return p.warn?.(`[memory-sync] config invalid: ${u.error}`),{action:"error",reason:u.error};if(u.kind==="noop")return{action:"skipped",reason:"memorySync.remote not set"};if(u.kind==="byo")return a?.memoryRemoteAdd?a.memoryRemoteAdd(e,u.remote)?{action:"byo",remote:u.remote}:{action:"error",reason:"memoryRemoteAdd returned false (memory DB not initialized?)"}:{action:"error",reason:"@zibby/ui-memory not loaded"};if(u.kind==="hosted"){if(typeof s=="function"&&!s())return{action:"pending-login",reason:'memorySync.remote = "hosted" but the user is not logged in. Run `zibby login` then `zibby memory remote use --hosted`.'};if(typeof i!="function")return{action:"error",reason:"hostedSetup function not provided"};try{return await i({cwd:e,projectId:o}),{action:"hosted"}}catch(l){return{action:"error",reason:`hosted setup failed: ${l.message}`}}}return{action:"error",reason:`unhandled kind: ${u.kind}`}}var _o,$o,_e,Ee=j(()=>{_o=[null,void 0,"","none","off",!1],$o="hosted",_e=["aws://","gs://","https://","http://","file://"]});var re={};D(re,{clearSession:()=>De,default:()=>Ko,getMem0ProxyUrl:()=>Ye,getProjects:()=>He,getProxyUrl:()=>Le,getSessionToken:()=>se,getUserInfo:()=>Be,isLoggedIn:()=>je,loadConfig:()=>S,saveConfig:()=>K,saveMem0ProxyUrl:()=>Ze,saveProjects:()=>Fe,saveProxyUrl:()=>Ue,saveSessionToken:()=>Me,saveUserInfo:()=>Ne});import{existsSync as ze,mkdirSync as Eo,readFileSync as zo,writeFileSync as Ro}from"fs";import{homedir as Re}from"os";import{join as ee}from"path";function Oe(){return process.env.ZIBBY_CONFIG_DIR||ee(Re(),".zibby")}function Te(){return ee(Oe(),"config.json")}function To(){let e=Oe();ze(e)||Eo(e,{recursive:!0})}function S(){try{let e=Te();if(ze(e)){let o=zo(e,"utf-8");return JSON.parse(o)}}catch{}return{}}function K(e){To(),Ro(Te(),JSON.stringify(e,null,2))}function se(){return S().sessionToken||null}function Me(e){let o=S();o.sessionToken=e,K(o)}function Be(){return S().user||null}function Ne(e){let o=S();o.user=e,K(o)}function je(){return se()!==null}function De(){let e=S();delete e.sessionToken,delete e.user,delete e.mem0ProxyUrl,K(e)}function Le(){return S().proxyUrl||null}function Ue(e){let o=S();o.proxyUrl=e,K(o)}function Ye(){return S().mem0ProxyUrl||null}function Ze(e){let o=S();o.mem0ProxyUrl=e,K(o)}function He(){return S().projects||[]}function Fe(e){let o=S();o.projects=e,K(o)}var Ke,Oo,Ko,ie=j(()=>{Ke=ee(Re(),".zibby"),Oo=ee(Ke,"config.json");Ko={loadConfig:S,saveConfig:K,getSessionToken:se,saveSessionToken:Me,getUserInfo:Be,saveUserInfo:Ne,isLoggedIn:je,clearSession:De,getProxyUrl:Le,saveProxyUrl:Ue,getMem0ProxyUrl:Ye,saveMem0ProxyUrl:Ze,getProjects:He,saveProjects:Fe,CONFIG_DIR:Ke,CONFIG_FILE:Oo}});var Ge={};D(Ge,{ENVIRONMENTS:()=>_,getAccountApiUrl:()=>Bo,getApiUrl:()=>Mo,getCurrentEnvironment:()=>No,getFrontendUrl:()=>jo});function Mo(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";_[o]?e=_[o].apiUrl:e=_.prod.apiUrl}try{let o=new URL(e);return o.protocol!=="http:"&&o.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${o.protocol} (only http/https allowed)`),_.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),_.prod.apiUrl}}function Bo(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let e=process.env.ZIBBY_ENV||"prod";return(_[e]||_.prod).accountApiUrl}function No(){let e=process.env.ZIBBY_ENV||"prod";return _[e]||_.prod}function jo(){let e;if(process.env.ZIBBY_FRONTEND_URL)e=process.env.ZIBBY_FRONTEND_URL;else{let o=process.env.ZIBBY_ENV||"prod";_[o]?e=_[o].frontendUrl:e=_.prod.frontendUrl}try{let o=new URL(e);if(o.protocol!=="http:"&&o.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${o.protocol} (only http/https allowed)`),_.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let a=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],i=o.hostname;if(!a.some(p=>i===p||i.endsWith(`.${p}`))&&!i.includes("localhost")&&i!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${i}`),"https://studio.zibby.dev"}return e}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${e}`),_.local.frontendUrl}}var _,Ve=j(()=>{_={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}}});var pe={};D(pe,{__testing:()=>Go,buildDoltEnv:()=>Fo,clearConfig:()=>Ho,getActiveCredentials:()=>oo,isHosted:()=>Yo,readConfig:()=>de,refreshCredentials:()=>eo,writeConfig:()=>Zo});import{readFileSync as We,writeFileSync as le,existsSync as ce,mkdirSync as qe,chmodSync as Do}from"fs";import{join as ae}from"path";function H(e){let o=ae(e,".zibby");return{dir:o,config:ae(o,Lo),creds:ae(o,Uo)}}function de(e){let{config:o}=H(e);if(!ce(o))return null;try{let t=JSON.parse(We(o,"utf-8"));return t.mode!=="hosted"?null:t}catch{return null}}function Yo(e){return!!de(e)}function Zo(e,o){let{dir:t,config:a}=H(e);qe(t,{recursive:!0}),le(a,JSON.stringify({mode:"hosted",projectId:o.projectId,bucket:o.bucket,prefix:o.prefix,doltUrl:o.doltUrl,configuredAt:new Date().toISOString()},null,2),"utf-8")}function Ho(e){let{config:o,creds:t}=H(e);for(let a of[o,t])if(ce(a))try{le(a,"")}catch{}}function ue(e){let{creds:o}=H(e);if(!ce(o))return null;try{let t=JSON.parse(We(o,"utf-8"));return!t?.accessKeyId||!t?.secretAccessKey||!t?.sessionToken?null:t}catch{return null}}function Xe(e,o){let{dir:t,creds:a}=H(e);qe(t,{recursive:!0}),le(a,JSON.stringify(o,null,2),"utf-8");try{Do(a,384)}catch{}}function Qe(e){return e?.expiration?new Date(e.expiration).getTime()-Date.now()<Je:!0}async function eo({cwd:e,projectId:o,apiUrl:t,sessionToken:a,fetch:i=globalThis.fetch}){if(!o)throw new Error("refreshCredentials: projectId required");if(!t)throw new Error("refreshCredentials: apiUrl required");if(!a)throw new Error("refreshCredentials: sessionToken required (run `zibby login`)");let s=`${String(t).replace(/\/+$/,"")}/memory/sync-credentials`,p=await i(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({projectId:o})});if(!p.ok){let l=await p.text().catch(()=>"");throw new Error(`memory-sync credentials request failed (${p.status}): ${l||"no body"}`)}let u=await p.json();if(!u?.accessKeyId||!u?.secretAccessKey||!u?.sessionToken)throw new Error("memory-sync credentials response missing required fields");return Xe(e,{accessKeyId:u.accessKeyId,secretAccessKey:u.secretAccessKey,sessionToken:u.sessionToken,expiration:u.expiration||null,refreshedAt:new Date().toISOString()}),ue(e)}async function oo({cwd:e,apiUrl:o,sessionToken:t,fetch:a}){let i=de(e);if(!i)return null;let s=ue(e);return(!s||Qe(s))&&(s=await eo({cwd:e,projectId:i.projectId,apiUrl:o,sessionToken:t,fetch:a})),s}async function Fo({cwd:e,apiUrl:o,sessionToken:t,fetch:a}){let i=await oo({cwd:e,apiUrl:o,sessionToken:t,fetch:a});return i?{AWS_ACCESS_KEY_ID:i.accessKeyId,AWS_SECRET_ACCESS_KEY:i.secretAccessKey,AWS_SESSION_TOKEN:i.sessionToken,AWS_REGION:process.env.AWS_REGION||"ap-southeast-2"}:null}var Lo,Uo,Je,Go,ge=j(()=>{Lo="memory-sync.json",Uo="memory-sync-creds.json",Je=120*1e3;Go={paths:H,readCreds:ue,writeCreds:Xe,isExpiringSoon:Qe,REFRESH_HEADROOM_MS:Je}});var to={};D(to,{memoryCompactCommand:()=>Jo,memoryCostCommand:()=>Xo,memoryInitCommand:()=>rt,memoryPullCommand:()=>tt,memoryPushCommand:()=>st,memoryRemoteAddCommand:()=>Qo,memoryRemoteInfoCommand:()=>et,memoryRemoteRemoveCommand:()=>ot,memoryRemoteUseHostedCommand:()=>nt,memoryResetCommand:()=>qo,memoryStatsCommand:()=>Wo});import n from"chalk";async function z(){try{return await import("@zibby/ui-memory")}catch{return console.log(n.yellow(`
|
|
10
10
|
@zibby/ui-memory is not installed.
|
|
11
11
|
`)),console.log(n.white(Vo)),null}}async function Wo(){let e=await z();if(!e)return;let o=process.cwd(),t=e.getStats(o);if(!t.available){console.log(n.red(`
|
|
12
12
|
Dolt is not installed.
|
|
@@ -15,7 +15,7 @@ var wo=Object.defineProperty;var N=(e,o)=>()=>(e&&(o=e(e=0)),o);var D=(e,o)=>{fo
|
|
|
15
15
|
Memory database not initialized.
|
|
16
16
|
`)),console.log(n.white(" Run `zibby init` or `zibby memory init` to set it up.\n"));return}console.log(n.bold.cyan(`
|
|
17
17
|
Zibby Test Memory
|
|
18
|
-
`)),console.log(n.gray(` Dolt: ${t.doltVersion}`));let a=n.gray(` ${"\u2500".repeat(40)}`);console.log(a);let
|
|
18
|
+
`)),console.log(n.gray(` Dolt: ${t.doltVersion}`));let a=n.gray(` ${"\u2500".repeat(40)}`);console.log(a);let i=t.counts;if(console.log(n.white(` Test runs: ${n.cyan(i.runs)} (${n.green(`${i.passed} passed`)}, ${i.failed>0?n.red(`${i.failed} failed`):n.gray(`${i.failed} failed`)})`)),console.log(n.white(` Selectors: ${n.cyan(i.selectors)} tracked`)),console.log(n.white(` Pages: ${n.cyan(i.pages)} discovered`)),console.log(n.white(` Transitions: ${n.cyan(i.transitions)} mapped`)),console.log(n.white(` Insights: ${n.cyan(i.insights||0)} saved`)),t.recentRuns.length>0){console.log(`
|
|
19
19
|
${a}`),console.log(n.white(" Recent runs:"));for(let s of t.recentRuns){let p=s.passed?n.green("\u2713"):n.red("\u2717"),u=s.duration_ms?n.gray(`${(s.duration_ms/1e3).toFixed(1)}s`):"";console.log(` ${p} ${n.white(s.spec_path)} ${u}`)}}if(t.topSelectors.length>0){console.log(`
|
|
20
20
|
${a}`),console.log(n.white(" Top selectors:"));for(let s of t.topSelectors){let p=s.success_count+s.failure_count,u=Math.round(s.success_count/p*100);console.log(` ${n.cyan(s.stable_id||"?")} \u2192 ${s.element_desc} (${u}%, ${p} uses)`)}}if(t.log){console.log(`
|
|
21
21
|
${a}`),console.log(n.white(" Recent commits:"));let s=t.log.split(`
|
|
@@ -28,8 +28,8 @@ ${a}`),console.log(n.white(" Recent commits:"));let s=t.log.split(`
|
|
|
28
28
|
No memory database found.
|
|
29
29
|
`))}async function Jo(e){let o=await z();if(!o)return;let t=process.cwd(),a=o.getStats(t);if(!a.initialized){console.log(n.yellow(`
|
|
30
30
|
Memory database not initialized.
|
|
31
|
-
`));return}let
|
|
32
|
-
Compacting memory (keep last ${
|
|
31
|
+
`));return}let i=e.maxRuns||50,s=e.maxAge||90;console.log(n.white(`
|
|
32
|
+
Compacting memory (keep last ${i} runs/spec, prune data older than ${s}d)...`));let p=a.counts;if(o.compactMemory(t,{maxRuns:i,maxAgeDays:s}).pruned){let l=o.getStats(t).counts,y=h=>p[h]-l[h];console.log(n.green(" Done.")),y("runs")>0&&console.log(n.gray(` Pruned ${y("runs")} old runs`)),y("selectors")>0&&console.log(n.gray(` Pruned ${y("selectors")} stale selectors`)),y("insights")>0&&console.log(n.gray(` Pruned ${y("insights")} old insights`)),y("transitions")>0&&console.log(n.gray(` Pruned ${y("transitions")} stale transitions`)),console.log(n.gray(` Dolt GC completed
|
|
33
33
|
`))}else console.log(n.gray(` Nothing to compact.
|
|
34
34
|
`))}async function Xo(){let e=await z();if(!e)return;let o=process.cwd(),t=e.getCostStats(o);if(!t){console.log(n.yellow(`
|
|
35
35
|
Memory database not initialized.
|
|
@@ -38,25 +38,25 @@ ${a}`),console.log(n.white(" Recent commits:"));let s=t.log.split(`
|
|
|
38
38
|
`)),console.log(n.gray(" Run `zibby test <spec>` once to populate. Token counts come from")),console.log(n.gray(` the LLM SDK and are written to .zibby/output/sessions/<id>/execute_live/usage.json.
|
|
39
39
|
`));return}console.log(n.bold.cyan(`
|
|
40
40
|
Zibby \u2014 LLM Cost Report
|
|
41
|
-
`));let a=n.gray(` ${"\u2500".repeat(60)}`),
|
|
42
|
-
${a}`),console.log(n.white(" By domain:"));for(let s of t.by_domain.slice(0,10)){let p=s.runs>0?Math.round((s.input+s.output)/s.runs):0;console.log(` ${n.cyan(s.domain.padEnd(30))} ${n.gray(`${s.runs} runs \xB7 ~${
|
|
43
|
-
${a}`),console.log(n.white(" By spec:"));for(let s of t.by_spec.slice(0,10)){let p=s.runs>0?Math.round((s.input+s.output)/s.runs):0;console.log(` ${n.cyan(String(s.spec_path).padEnd(40))} ${n.gray(`${s.runs} runs \xB7 ~${
|
|
44
|
-
${a}`),console.log(n.white(" Last 10 runs:"));for(let s of t.recent.slice(0,10)){let p=s.passed?n.green("\u2713"):n.red("\u2717"),u=(s.input_tokens||0)+(s.output_tokens||0),l=(s.cache_read_tokens||0)>0?n.gray(` \xB7 cache read ${
|
|
41
|
+
`));let a=n.gray(` ${"\u2500".repeat(60)}`),i=t.totals;if(console.log(a),console.log(n.white(` Runs with usage data: ${n.cyan(i.runs)}`)),console.log(n.white(` Total input tokens: ${n.cyan(M(i.input))}`)),console.log(n.white(` Total output tokens: ${n.cyan(M(i.output))}`)),console.log(n.white(` Total cache reads: ${n.cyan(M(i.cache_read))} ${n.gray("(billed at ~10% of normal input rate)")}`)),console.log(n.white(` Total cache creation: ${n.cyan(M(i.cache_creation))} ${n.gray("(billed at ~125% of normal input rate)")}`)),t.by_domain.length>0){console.log(`
|
|
42
|
+
${a}`),console.log(n.white(" By domain:"));for(let s of t.by_domain.slice(0,10)){let p=s.runs>0?Math.round((s.input+s.output)/s.runs):0;console.log(` ${n.cyan(s.domain.padEnd(30))} ${n.gray(`${s.runs} runs \xB7 ~${M(p)}/run avg`)}`)}}if(t.by_spec.length>0){console.log(`
|
|
43
|
+
${a}`),console.log(n.white(" By spec:"));for(let s of t.by_spec.slice(0,10)){let p=s.runs>0?Math.round((s.input+s.output)/s.runs):0;console.log(` ${n.cyan(String(s.spec_path).padEnd(40))} ${n.gray(`${s.runs} runs \xB7 ~${M(p)}/run avg`)}`)}}if(t.recent.length>0){console.log(`
|
|
44
|
+
${a}`),console.log(n.white(" Last 10 runs:"));for(let s of t.recent.slice(0,10)){let p=s.passed?n.green("\u2713"):n.red("\u2717"),u=(s.input_tokens||0)+(s.output_tokens||0),l=(s.cache_read_tokens||0)>0?n.gray(` \xB7 cache read ${M(s.cache_read_tokens)}`):"";console.log(` ${p} ${n.gray(s.run_at.slice(0,16))} ${n.cyan(M(u).padStart(8))} ${n.white(s.spec_path||"")}${l}`)}}console.log("")}function M(e){return e==null?"\u2014":e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}K`:`${(e/1e6).toFixed(2)}M`}async function Qo(e,o={}){let t=await z();if(!t)return;e||(console.log(n.red(`
|
|
45
45
|
Usage: zibby memory remote add <url> [--name origin]
|
|
46
|
-
`)),console.log(n.gray(" Supported: aws:// gs:// https:// file:///")),console.log(n.gray(" Example: zibby memory remote add aws://team-bucket/zibby/shop-prod")),console.log(""),process.exit(1));let a=process.cwd(),
|
|
46
|
+
`)),console.log(n.gray(" Supported: aws:// gs:// https:// file:///")),console.log(n.gray(" Example: zibby memory remote add aws://team-bucket/zibby/shop-prod")),console.log(""),process.exit(1));let a=process.cwd(),i=o.name||"origin";if(!t.memoryRemoteAdd(a,e,i)){console.log(n.red("\n Failed to add remote. Is the memory DB initialized? Run `zibby memory init` first.\n"));return}console.log(""),console.log(n.green(` \u2713 Added remote ${n.bold(i)} \u2192 ${e}`)),console.log(n.gray(" Next step: zibby memory pull (or just run any test \u2014 middleware auto-pulls/pushes)")),console.log("")}async function et(){let e=await z();if(!e)return;let o=e.memoryRemoteInfo(process.cwd());if(console.log(""),!o){console.log(n.yellow(` No memory remote configured.
|
|
47
47
|
`)),console.log(n.gray(" Set one with: zibby memory remote add <url>")),console.log(n.gray(` Without a remote, memory is local-only \u2014 team members won't see each other's learnings.
|
|
48
48
|
`));return}console.log(n.bold.cyan(" Memory remote")),console.log(` ${n.cyan(o.name||"origin")}: ${o.url||"(unknown)"}`),console.log("")}async function ot(e="origin"){let o=await z();if(!o)return;let t=o.memoryRemoteRemove(process.cwd(),e);console.log(""),t?(console.log(n.green(` \u2713 Removed remote ${e}.`)),console.log(n.gray(" Memory is now local-only."))):console.log(n.gray(` No remote named ${e} to remove.`)),console.log("")}async function tt(){let e=await z();if(!e)return;console.log(n.cyan(`
|
|
49
49
|
Pulling team memory from remote...`));let o=e.memorySyncPull(process.cwd());o.pulled?console.log(n.green(` \u2713 Pulled latest. Local memory now reflects the team's shared knowledge.
|
|
50
|
-
`)):(console.log(n.yellow(` \u26A0 Pull skipped \u2014 ${o.error||"unknown reason"}.`)),console.log(n.gray(" Did you run `zibby memory remote add <url>` first?\n")))}async function nt(e={}){let o=await z();if(!o)return;let{join:t}=await import("path"),{existsSync:a}=await import("fs"),
|
|
50
|
+
`)):(console.log(n.yellow(` \u26A0 Pull skipped \u2014 ${o.error||"unknown reason"}.`)),console.log(n.gray(" Did you run `zibby memory remote add <url>` first?\n")))}async function nt(e={}){let o=await z();if(!o)return;let{join:t}=await import("path"),{existsSync:a}=await import("fs"),i=e.cwd||process.cwd(),s=e.projectId;if(!s){let I=t(i,".zibby.config.mjs");if(a(I))try{let x=(await import(`file://${I}?t=${Date.now()}`)).default;s=x?.projectId||x?.project?.id}catch{}}s||(console.log(n.red(`
|
|
51
51
|
Could not determine projectId.
|
|
52
52
|
`)),console.log(n.gray(" Either run this from a project dir with `.zibby.config.mjs`")),console.log(n.gray(` containing { projectId: "..." }, or pass --project-id <id>.
|
|
53
53
|
`)),process.exit(1));let{getApiUrl:p}=await Promise.resolve().then(()=>(Ve(),Ge)),{getSessionToken:u}=await Promise.resolve().then(()=>(ie(),re)),l=p(),y=u();y||(console.log(n.red("\n Not logged in. Run `zibby login` first.\n")),console.log(n.gray(" Hosted memory-sync is for signed-in users only \u2014")),console.log(n.gray(` the backend needs your identity to scope per-tenant credentials.
|
|
54
54
|
`)),process.exit(1)),console.log(n.cyan(`
|
|
55
|
-
Configuring hosted memory-sync...`));let h;try{let
|
|
56
|
-
Failed: ${
|
|
57
|
-
`)),process.exit(1)}let{writeConfig:v}=await Promise.resolve().then(()=>(ge(),pe));v(
|
|
58
|
-
Saved hosted-sync config, but failed to register Dolt remote.`)),console.log(n.gray(" Try `zibby memory init` first (the local Dolt DB must exist).\n")),process.exit(1));let{refreshCredentials:w}=await Promise.resolve().then(()=>(ge(),pe));try{await w({cwd:
|
|
59
|
-
Config saved, but initial credential fetch failed: ${
|
|
55
|
+
Configuring hosted memory-sync...`));let h;try{let I=`${l.replace(/\/+$/,"")}/memory/sync-config?projectId=${encodeURIComponent(s)}`,A=await fetch(I,{headers:{Authorization:`Bearer ${y}`}});if(!A.ok){let x=await A.text().catch(()=>"");throw new Error(`backend returned ${A.status}: ${x||"no body"}`)}h=await A.json()}catch(I){console.log(n.red(`
|
|
56
|
+
Failed: ${I.message}
|
|
57
|
+
`)),process.exit(1)}let{writeConfig:v}=await Promise.resolve().then(()=>(ge(),pe));v(i,{projectId:s,bucket:h.bucket,prefix:h.prefix,doltUrl:h.doltUrl}),o.memoryRemoteAdd(i,h.doltUrl)||(console.log(n.yellow(`
|
|
58
|
+
Saved hosted-sync config, but failed to register Dolt remote.`)),console.log(n.gray(" Try `zibby memory init` first (the local Dolt DB must exist).\n")),process.exit(1));let{refreshCredentials:w}=await Promise.resolve().then(()=>(ge(),pe));try{await w({cwd:i,projectId:s,apiUrl:l,sessionToken:y})}catch(I){console.log(n.yellow(`
|
|
59
|
+
Config saved, but initial credential fetch failed: ${I.message}`)),console.log(n.gray(` Will retry on first push/pull.
|
|
60
60
|
`))}console.log(""),console.log(n.green(" \u2713 Hosted memory-sync configured.")),console.log(n.gray(` Bucket: ${h.bucket}`)),console.log(n.gray(` Prefix: ${h.prefix} \u2190 your tenant slot`)),console.log(n.gray(` Dolt: ${h.doltUrl}`)),console.log(""),console.log(n.gray(" Every test run will auto-pull/push. Creds refresh automatically.")),console.log(n.gray(" To revert to local-only: zibby memory remote remove origin")),console.log("")}async function st(){let e=await z();if(!e)return;console.log(n.cyan(`
|
|
61
61
|
Pushing local memory to team remote...`));let o=e.memorySyncPush(process.cwd());o.pushed?console.log(n.green(" \u2713 Pushed. Team can now `zibby memory pull` to see your run's learnings.\n")):console.log(n.yellow(` \u26A0 Push skipped \u2014 ${o.error||"unknown reason"}.
|
|
62
62
|
`))}async function rt(){let e=await z();if(!e)return;let o=process.cwd();if(!e.DoltDB.isAvailable()){console.log(n.red(`
|
|
@@ -66,104 +66,104 @@ ${a}`),console.log(n.white(" Last 10 runs:"));for(let s of t.recent.slice(0,10)
|
|
|
66
66
|
Memory database initialized at .zibby/memory/
|
|
67
67
|
`)):a&&console.log(n.gray(`
|
|
68
68
|
Memory database already initialized.
|
|
69
|
-
`))}var Vo,no=
|
|
69
|
+
`))}var Vo,no=j(()=>{Vo=`
|
|
70
70
|
Install @zibby/ui-memory and Dolt to enable test memory:
|
|
71
71
|
|
|
72
72
|
npm install @zibby/ui-memory # add the package
|
|
73
73
|
brew install dolt # macOS
|
|
74
74
|
# or: curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash
|
|
75
|
-
`});var mo={};D(mo,{setupCiCommand:()=>ft,setupPlaywrightMcpCommand:()=>go,testWithVideoCommand:()=>ht});import{spawn as ye,execSync as fe}from"child_process";import{join as L,dirname as he,resolve as io}from"path";import{readFileSync as ao,writeFileSync as lo,existsSync as F,mkdirSync as co}from"fs";import{homedir as uo}from"os";import{createRequire as it}from"module";import
|
|
76
|
-
`,"utf-8")}async function ut(){let e=at();if(!e)return;let o=L(e,"scripts","patch-cursor-mcp.js");if(F(o))try{await new Promise((t,a)=>{let
|
|
77
|
-
`).find(s=>/playwright-official/i.test(s)&&/APPROVAL|🔑/i.test(s));if(t){let s=t.match(/=>\s*(\S+)/);if(s)return s[1]}let a=o.match(/playwright-official[^=]*=>\s*(\S+)/);if(a)return a[1];let
|
|
78
|
-
`,"utf-8"),
|
|
75
|
+
`});var mo={};D(mo,{setupCiCommand:()=>ft,setupPlaywrightMcpCommand:()=>go,testWithVideoCommand:()=>ht});import{spawn as ye,execSync as fe}from"child_process";import{join as L,dirname as he,resolve as io}from"path";import{readFileSync as ao,writeFileSync as lo,existsSync as F,mkdirSync as co}from"fs";import{homedir as uo}from"os";import{createRequire as it}from"module";import P from"chalk";function at(){try{return he(me.resolve("@zibby/core/package.json"))}catch{return null}}function po(e){try{return fe(`command -v ${e}`,{stdio:"pipe"}),!0}catch{return!1}}function lt(){try{let e=me.resolve("@zibby/mcp-browser/bin/mcp-browser-zibby.js");if(F(e))return e}catch{}try{let e=me.resolve("@playwright/mcp/package.json"),o=he(e),t=JSON.parse(ao(e,"utf-8")),a=typeof t.bin=="string"?t.bin:t.bin?.["playwright-mcp"];if(a){let s=L(o,a);if(F(s))return s}let i=L(o,"cli.js");if(F(i))return i}catch{}return null}function so(e,o,t={}){return new Promise((a,i)=>{let s=ye(e,o,{stdio:"inherit",...t});s.on("close",p=>a(p??1)),s.on("error",i)})}async function ct(e){return po("playwright")?await so("playwright",["install","ffmpeg"],{cwd:e})===0:await so("npx",["--yes","playwright","install","ffmpeg"],{cwd:e})===0}function dt({headed:e=!1,viewport:o=null}){let t=process.execPath,a=he(t),i=lt(),s=Number(o?.width)||1280,p=Number(o?.height)||720,u=`${s}x${p}`,l=[];l.push(`--viewport-size=${u}`,"--output-dir=test-results"),e||l.push("--headless");let y;i?y={command:t,args:[i,...l],env:{PATH:`${a}:/usr/bin:/bin:/usr/sbin:/sbin`}}:y={command:"npx",args:["-y","@playwright/mcp",...l],env:{PATH:`${a}:/usr/bin:/bin:/usr/sbin:/sbin`}},y.description="Zibby MCP Browser - Playwright MCP with Zibby defaults";let h=L(uo(),".cursor"),v=L(h,"mcp.json");F(h)||co(h,{recursive:!0});let w={mcpServers:{}};if(F(v))try{w=JSON.parse(ao(v,"utf-8")),(!w.mcpServers||typeof w.mcpServers!="object")&&(w.mcpServers={})}catch{w={mcpServers:{}}}w.mcpServers["playwright-official"]=y,lo(v,`${JSON.stringify(w,null,2)}
|
|
76
|
+
`,"utf-8")}async function ut(){let e=at();if(!e)return;let o=L(e,"scripts","patch-cursor-mcp.js");if(F(o))try{await new Promise((t,a)=>{let i=ye(process.execPath,[o],{cwd:process.cwd(),stdio:"ignore"});i.on("close",s=>t(s??0)),i.on("error",a)})}catch{}}function pt(e){return io(e).replace(/^\/+/,"").replace(/\//g,"-")}function gt(e){let o=String(e||""),t=o.split(`
|
|
77
|
+
`).find(s=>/playwright-official/i.test(s)&&/APPROVAL|🔑/i.test(s));if(t){let s=t.match(/=>\s*(\S+)/);if(s)return s[1]}let a=o.match(/playwright-official[^=]*=>\s*(\S+)/);if(a)return a[1];let i=o.match(/playwright-official-[a-f0-9]+/i);return i?i[0]:null}function mt(e,o){let t=pt(e),a=L(uo(),".cursor","projects",t);co(a,{recursive:!0});let i=L(a,"mcp-approvals.json");return lo(i,`${JSON.stringify([o],null,2)}
|
|
78
|
+
`,"utf-8"),i}function ro(e){try{return fe("cursor-agent mcp list",{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:process.env,maxBuffer:2*1024*1024})}catch(o){let t=o.stdout!=null?String(o.stdout):"",a=o.stderr!=null?String(o.stderr):"";return t+a}}function yt(e){try{return fe("cursor-agent mcp enable playwright-official",{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:process.env,maxBuffer:1024*1024}),!0}catch{return!1}}async function go(e={}){let o=!!e.headed,t=e.viewport||{width:1280,height:720};if(!process.execPath)throw new Error("Node.js runtime not found");let a=await ct(process.cwd());console.log(a?P.gray(" \u2713 ffmpeg installed for Playwright video"):P.yellow(" \u26A0 Could not install ffmpeg (video may be unavailable)")),dt({headed:o,viewport:t}),await ut();let i=io(process.cwd());if(po("cursor-agent")){ro(i);let s=yt(i);s&&console.log(P.gray(" \u2713 cursor-agent: mcp enable playwright-official"));let p=ro(i),u=gt(p);if(u)try{let l=mt(i,u);console.log(P.gray(` \u2713 MCP auto-approval key saved (${l})`))}catch(l){console.log(P.yellow(` \u26A0 Could not write mcp-approvals.json: ${l.message}`))}else s||(console.log(P.yellow(" \u26A0 Could not auto-approve MCP (mcp enable failed and no approval key in cursor-agent output)")),console.log(P.gray(" Try: cursor-agent mcp enable playwright-official")))}else console.log(P.yellow(" \u26A0 cursor-agent not found; install it to use Cursor MCP tools"))}async function ft(e){try{console.log(P.cyan(`
|
|
79
79
|
\u{1F680} Running CI setup...
|
|
80
|
-
`)),await go({headed:!1,cloudSync:!0,viewport:{width:1280,height:720}}),console.log(
|
|
80
|
+
`)),await go({headed:!1,cloudSync:!0,viewport:{width:1280,height:720}}),console.log(P.green(`
|
|
81
81
|
\u2705 CI/CD setup complete!
|
|
82
|
-
`))}catch(o){console.log(
|
|
82
|
+
`))}catch(o){console.log(P.red(`
|
|
83
83
|
\u274C Error: ${o.message}
|
|
84
|
-
`)),process.exit(1)}}async function ht(e,o){try{let t=["playwright","test",e||"tests/","--project=chromium"];o.headed&&t.push("--headed"),console.log(
|
|
84
|
+
`)),process.exit(1)}}async function ht(e,o){try{let t=["playwright","test",e||"tests/","--project=chromium"];o.headed&&t.push("--headed"),console.log(P.cyan(`
|
|
85
85
|
\u{1F3A5} Running tests with video recording...
|
|
86
|
-
`)),console.log(
|
|
86
|
+
`)),console.log(P.gray("\u2501".repeat(50)));let a=ye("npx",t,{cwd:process.cwd(),stdio:"inherit"});a.on("close",i=>{i===0?console.log(P.green(`
|
|
87
87
|
\u2705 Tests complete!
|
|
88
|
-
`)):(console.log(
|
|
89
|
-
\u274C Tests failed with code ${
|
|
90
|
-
`)),process.exit(
|
|
91
|
-
\u274C Error: ${
|
|
92
|
-
`)),process.exit(1)})}catch(t){console.log(
|
|
88
|
+
`)):(console.log(P.red(`
|
|
89
|
+
\u274C Tests failed with code ${i}
|
|
90
|
+
`)),process.exit(i))}),a.on("error",i=>{console.log(P.red(`
|
|
91
|
+
\u274C Error: ${i.message}
|
|
92
|
+
`)),process.exit(1)})}catch(t){console.log(P.red(`
|
|
93
93
|
\u274C Error: ${t.message}
|
|
94
|
-
`)),process.exit(1)}}var me,yo=
|
|
95
|
-
`,"utf-8")}
|
|
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(e){console.log(
|
|
101
|
-
`));return}let l=process.env.SHELL||"",y="";if(l.includes("zsh"))y=b(
|
|
94
|
+
`)),process.exit(1)}}var me,yo=j(()=>{me=it(import.meta.url)});import{mkdir as U,writeFile as $,readFile as V}from"fs/promises";import{existsSync as C,readdirSync as bt}from"fs";import{join as b,resolve as fo,dirname as wt}from"path";import{homedir as B}from"os";import Y from"inquirer";import r from"chalk";import T from"ora";import{spawn as G,execSync as oe}from"child_process";import{fileURLToPath as vt}from"url";import{createRequire as ho}from"module";import{existsSync as vo,readFileSync as xo,writeFileSync as ko,mkdirSync as Io}from"fs";import{join as we}from"path";import{homedir as ve}from"os";var X={cursor:{envVar:"CURSOR_API_KEY",label:"Cursor API Key",url:"https://cursor.com/settings"},claude:{envVar:"ANTHROPIC_API_KEY",label:"Anthropic API Key",url:"https://console.anthropic.com/settings/keys"},codex:{envVar:"OPENAI_API_KEY",label:"OpenAI API Key",url:"https://platform.openai.com/api-keys"},gemini:{envVar:"GEMINI_API_KEY",label:"Gemini API Key",url:"https://aistudio.google.com/app/apikey"}};function xe(){return we(ve(),".zibby","config.json")}function Q(){try{let e=xe();return vo(e)?JSON.parse(xo(e,"utf-8")):{}}catch{return{}}}function ke(e,o){let t=o?X[o]:null;t&&te(t.envVar,e)}function te(e,o){if(!e||typeof e!="string"||!o||typeof o!="string")return;let t=we(ve(),".zibby");Io(t,{recursive:!0});let a=xe(),i=Q();(!i.agentKeys||typeof i.agentKeys!="object")&&(i.agentKeys={}),i.agentKeys[e]=String(o).trim(),delete i.agentApiKey,ko(a,`${JSON.stringify(i,null,2)}
|
|
95
|
+
`,"utf-8")}async function xt(){let e=process.env.ANTHROPIC_API_KEY||Q().agentKeys?.ANTHROPIC_API_KEY;console.log(""),console.log(r.cyan(" Claude credentials \u2014 pick the type you have:")),console.log("");let{kind:o}=await Y.prompt([{type:"select",name:"kind",message:"Which Claude credential do you want to use?",choices:[{name:"OAuth token (long-lived) \u2014 uses your Claude Pro / Max subscription, works in cloud",value:"oauth"},{name:e?`API key \u2014 found one (***${e.slice(-4)}), pay-per-token billing`:"API key \u2014 pay-per-token billing via console.anthropic.com",value:"api"}],default:e?"api":"oauth"}]);if(o==="skip")return{kind:"skip"};if(o==="oauth"){console.log(""),console.log(r.gray(" How to generate a long-lived OAuth token (cloud-compatible):")),console.log(r.gray(" 1. Install claude (skip if you already have it):")),console.log(r.gray(" npm install -g @anthropic-ai/claude-code")),console.log(r.gray(" 2. Run:")),console.log(r.gray(" claude setup-token")),console.log(r.gray(" \u2192 confirms in your browser \u2192 prints a token starting with sk-ant-oat01-\u2026")),console.log(r.gray(" 3. Paste that token below.")),console.log(""),console.log(r.yellow(" Note: do NOT paste the short-lived token from `claude` browser-login \u2014")),console.log(r.yellow(" it works locally but Anthropic rejects it from non-login IPs (cloud).")),console.log("");let{token:a}=await Y.prompt([{type:"password",name:"token",message:"Paste OAuth token from `claude setup-token` (or press Enter to skip):",mask:"*"}]);return a&&a.trim()?{kind:"oauth",token:a.trim()}:{kind:"skip"}}if(e)return{kind:"api",token:e};let{token:t}=await Y.prompt([{type:"password",name:"token",message:"Paste Anthropic API key (from https://console.anthropic.com/settings/keys, or press Enter to skip):",mask:"*"}]);return t&&t.trim()?{kind:"api",token:t.trim()}:{kind:"skip"}}var kt=vt(import.meta.url),It=wt(kt),bo=ho(import.meta.url);async function At(){try{let e=process.platform==="win32",o=oe("npm config get prefix",{encoding:"utf-8"}).trim(),t=e?o:`${o}/bin`,a=t.replace(/^~/,B()),i=e?";":":";if(process.env.PATH.split(i).some(v=>{let w=v.replace(/^~/,B());return w===a||w===t}))return;if(process.env.CI||process.env.ZIBBY_CI||!process.stdin.isTTY){console.log(r.yellow("npm global bin not in PATH")),console.log(r.gray(` Location: ${a}`)),console.log(r.gray(` Add it manually: export PATH="${a}:$PATH"
|
|
96
|
+
`));return}console.log(r.yellow("npm global bin not in PATH")),console.log(r.gray(` Location: ${a}`)),console.log();let{shouldAddPath:u}=await Y.prompt([{type:"confirm",name:"shouldAddPath",message:"Add npm global bin to your shell PATH automatically?",default:!0}]);if(!u){e?(console.log(r.gray(`
|
|
97
|
+
To add manually on Windows:`)),console.log(r.gray(' 1. Search "Environment Variables" in Start menu')),console.log(r.gray(' 2. Edit "Path" in User variables')),console.log(r.gray(` 3. Add: ${a}
|
|
98
|
+
`))):(console.log(r.gray(`
|
|
99
|
+
To add manually, run:`)),console.log(r.gray(` echo 'export PATH="${a}:$PATH"' >> ~/.zshrc`)),console.log(r.gray(` source ~/.zshrc
|
|
100
|
+
`)));return}if(e){console.log(r.yellow("Cannot auto-add PATH on Windows")),console.log(r.gray(" Please add manually:")),console.log(r.gray(' 1. Search "Environment Variables" in Start menu')),console.log(r.gray(' 2. Edit "Path" in User variables')),console.log(r.gray(` 3. Add: ${a}
|
|
101
|
+
`));return}let l=process.env.SHELL||"",y="";if(l.includes("zsh"))y=b(B(),".zshrc");else if(l.includes("bash"))y=C(b(B(),".bashrc"))?b(B(),".bashrc"):b(B(),".bash_profile");else{console.log(r.yellow(`Unknown shell: ${l}`)),console.log(r.gray(" Please add manually:")),console.log(r.gray(` export PATH="${a}:$PATH"`));return}if(C(y)){let v=await V(y,"utf-8");if(v.includes(a)||v.includes("npm")&&v.includes("global")&&v.includes("bin")){console.log(r.yellow(`PATH entry found in ${y} but not active`)),console.log(r.gray(` Run: source ${y}
|
|
102
102
|
`));return}}let h=`
|
|
103
103
|
# npm global bin (added by zibby)
|
|
104
104
|
export PATH="${a}:$PATH"
|
|
105
|
-
`;await $(y,(
|
|
106
|
-
Run this to activate in current session:`)),console.log(
|
|
107
|
-
`))}catch{}}async function
|
|
105
|
+
`;await $(y,(C(y)?await V(y,"utf-8"):"")+h),console.log(r.green(`Added to ${y}`)),console.log(r.yellow(`
|
|
106
|
+
Run this to activate in current session:`)),console.log(r.gray(` source ${y}
|
|
107
|
+
`))}catch{}}async function gn(e,o){let t=o.template==="browser-test-automation";console.log(t?`
|
|
108
108
|
Zibby Test Automation
|
|
109
109
|
`:`
|
|
110
110
|
Zibby Project Init
|
|
111
|
-
`);let a=!o.skipMemory,
|
|
111
|
+
`);let a=!o.skipMemory,i=["dolt","mem0"].includes(String(o.memoryBackend||"").toLowerCase())?String(o.memoryBackend).toLowerCase():"dolt";await At();let s=e?fo(process.cwd(),e):process.cwd(),p=e||"zibby-tests",u=!!e;u&&C(s)&&(console.log(r.red(`
|
|
112
112
|
Directory "${e}" already exists!
|
|
113
|
-
`)),process.exit(1)),!u&&
|
|
113
|
+
`)),process.exit(1)),!u&&C(b(s,".zibby.config.mjs"))&&!o.force&&(console.log(r.yellow(`
|
|
114
114
|
Zibby is already initialized in this directory!
|
|
115
|
-
`)),console.log(
|
|
116
|
-
`)),process.exit(0)),o.force&&!u&&console.log(
|
|
115
|
+
`)),console.log(r.white("Config file found: .zibby.config.mjs")),console.log(r.gray(`Use --force or -f to reinitialize
|
|
116
|
+
`)),process.exit(0)),o.force&&!u&&console.log(r.cyan(`
|
|
117
117
|
Reinitializing Zibby configuration...
|
|
118
|
-
`));let l;if(o.agent&&(o.headed||o.headless))console.log(
|
|
119
|
-
`)),l={agent:o.agent,browserMode:o.headless?"headless":"headed",apiKey:o.apiKey||null,cloudSync:!!(o.cloudSync||o.apiKey)};else{if(o.agent)l={agent:o.agent};else{let{agent:x}=await Y.prompt([{type:"select",name:"agent",message:"Which AI agent do you prefer?",choices:[{name:"Claude (Anthropic)",value:"claude"},{name:"Cursor",value:"cursor"},{name:"Codex (OpenAI)",value:"codex"},{name:"Gemini (Google)",value:"gemini"}],default:"claude"}]);l={agent:x}}let w=
|
|
118
|
+
`));let l;if(o.agent&&(o.headed||o.headless))console.log(r.cyan(`Setting up with provided options...
|
|
119
|
+
`)),l={agent:o.agent,browserMode:o.headless?"headless":"headed",apiKey:o.apiKey||null,cloudSync:!!(o.cloudSync||o.apiKey)};else{if(o.agent)l={agent:o.agent};else{let{agent:x}=await Y.prompt([{type:"select",name:"agent",message:"Which AI agent do you prefer?",choices:[{name:"Claude (Anthropic)",value:"claude"},{name:"Cursor",value:"cursor"},{name:"Codex (OpenAI)",value:"codex"},{name:"Gemini (Google)",value:"gemini"}],default:"claude"}]);l={agent:x}}let w=X[l.agent],I=!(process.env.CI||process.env.ZIBBY_CI||!process.stdin.isTTY);if(l.agent==="claude"&&!o.agentKey&&I){let x=await xt();x?.kind==="oauth"&&x.token?(l.claudeOauthToken=x.token,l.agentAuth="oauth"):x?.kind==="api"&&x.token&&(l.agentKey=x.token,l.agentAuth="api")}else if(w&&!o.agentKey&&I){let x=Q(),c=process.env[w.envVar]||x.agentKeys?.[w.envVar],g=c?`***${c.slice(-4)}`:null,d=g?`${w.label} found (${g}). Press Enter to keep, or paste a new key:`:`Enter ${w.label} (from ${w.url}, or press Enter to skip):`,{agentKey:f}=await Y.prompt([{type:"password",name:"agentKey",message:d,mask:"*"}]);f&&f.trim()&&(l.agentKey=f.trim(),l.agentAuth="api")}let A=[];if(t&&!o.headed&&!o.headless&&A.push({type:"select",name:"browserMode",message:"Browser mode during live AI execution?",choices:[{name:"Headed - Visible browser (recommended for development)",value:"headed"},{name:"Headless - Hidden browser (for CI/CD)",value:"headless"}],default:"headed"}),t&&!o.apiKey&&A.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:"}),A.length>0){let x=await Y.prompt(A);Object.assign(l,x)}l.browserMode=o.headless?"headless":o.headed?"headed":l.browserMode,l.apiKey=o.apiKey||l.apiKey,l.cloudSync=!!(o.cloudSync||o.apiKey||l.apiKey&&l.apiKey.trim())}o.agentKey&&(l.agentKey=o.agentKey),o.agentOauthToken&&l.agent==="claude"&&(l.claudeOauthToken=o.agentOauthToken);let h=X[l.agent];l.claudeOauthToken&&(te("CLAUDE_CODE_OAUTH_TOKEN",l.claudeOauthToken),console.log(r.gray(" Claude OAuth subscription token saved to ~/.zibby/config.json")),console.log(r.gray(" Used by: zibby test / chat / workflow run / workflow start"))),l.agentKey&&(ke(l.agentKey,l.agent),console.log(r.gray(" Agent API key saved to ~/.zibby/config.json"))),l.mcp="playwright",l.setupMcp=l.agent==="cursor";let v=T("Setting up Zibby...").start();try{if(u&&await U(s,{recursive:!0}),t&&(await U(b(s,"test-specs/examples"),{recursive:!0}),await U(b(s,"tests"),{recursive:!0})),await U(b(s,".zibby/output"),{recursive:!0}),await U(b(s,".zibby/commands"),{recursive:!0}),a&&i==="dolt")try{let{initMemory:c,DoltDB:g}=await import("@zibby/ui-memory");if(g.isAvailable()){let{created:d}=c(s);d&&(v.text="Initialized test memory database (Dolt)...")}else v.text="Dolt not found \u2014 skipping memory database (brew install dolt)"}catch{}let w=o.template,I=w&&w!=="none"&&w!=="false";if(I){v.text=`Scaffolding workflow template: ${w}...`;try{let{writeTemplateFiles:c}=await Promise.resolve().then(()=>(Ce(),Pe));await c(s,w,{enableMemory:a})}catch(c){throw v.fail(`Failed to scaffold template: ${c.message}`),c}}else await U(b(s,".zibby"),{recursive:!0});v.text="Generating configuration files...";let A=Pt(l,o,{memoryBackend:i});if(await $(b(s,".zibby.config.mjs"),A),await $(b(s,".env.example"),Ct(l,i)),l.apiKey&&l.apiKey.trim()){let c=b(s,".env"),g=l.apiKey.trim();if(C(c)){let d=await V(c,"utf8");/^ZIBBY_API_KEY=/m.test(d)?d=d.replace(/^ZIBBY_API_KEY=.*/m,`ZIBBY_API_KEY=${g}`):/^#\s*ZIBBY_API_KEY=/m.test(d)?d=d.replace(/^#\s*ZIBBY_API_KEY=.*/m,`ZIBBY_API_KEY=${g}`):d=`${d.trimEnd()}
|
|
120
120
|
|
|
121
121
|
# Zibby Cloud Sync
|
|
122
122
|
ZIBBY_API_KEY=${g}
|
|
123
|
-
`,await $(c,d)}else await $(c,
|
|
123
|
+
`,await $(c,d)}else await $(c,_t(l,g,i))}if(l.agentKey&&h){let c=b(s,".env"),g=l.agentKey;if(C(c)){let d=await V(c,"utf8"),f=new RegExp(`^${h.envVar}=.*`,"m"),m=new RegExp(`^#\\s*${h.envVar}=.*`,"m");f.test(d)?d=d.replace(f,`${h.envVar}=${g}`):m.test(d)?d=d.replace(m,`${h.envVar}=${g}`):d=`${d.trimEnd()}
|
|
124
124
|
|
|
125
125
|
# AI Agent Key
|
|
126
126
|
${h.envVar}=${g}
|
|
127
|
-
`,await $(c,d)}}if(u){let c
|
|
128
|
-
Missing required Zibby dependencies in this project:`)),console.log(
|
|
129
|
-
`));else{let m=T(`Installing ${f.join(", ")}...`).start();await new Promise(Z=>{G("npm",["install","--save-dev",...f],{cwd:s,stdio:"pipe"}).on("close",
|
|
130
|
-
`)))}}}if(!u&&a&&
|
|
131
|
-
Using mem0 backend requires mem0ai in your project dependencies.`)),console.log(
|
|
132
|
-
`))),!o.skipInstall&&t){let c=T("Installing Playwright browsers...").start();await new Promise(g=>{let d=G("npx",["playwright","install","chromium"],{cwd:s,stdio:"pipe"}),f="";d.stdout.on("data",m=>{f+=m.toString()}),d.stderr.on("data",m=>{f+=m.toString()}),d.on("close",m=>{m===0?(f.includes("already installed")||f.includes("up to date")?c.succeed("Playwright browsers already installed"):c.succeed("Playwright browsers installed!"),g()):(c.warn("Could not verify Playwright browsers"),console.log(
|
|
127
|
+
`,await $(c,d)}}if(u){let c=$t(p,l,{memoryBackend:i});await $(b(s,"package.json"),c)}if(!C(b(s,".gitignore"))){let c=St();await $(b(s,".gitignore"),c)}if(t){if(!C(b(s,"playwright.config.js"))){let c=Et("on");await $(b(s,"playwright.config.js"),c)}if(!C(b(s,"test-specs/examples/example-domain.txt"))){let c=zt();await $(b(s,"test-specs/examples/example-domain.txt"),c)}}let x=fo(It,"../../../../examples/.zibby/commands");if(C(x)){let c=bt(x).filter(g=>g.toLowerCase().endsWith(".md"));for(let g of c){let d=b(s,".zibby/commands",g);if(o.force||!C(d)){let f=await V(b(x,g),"utf-8");await $(d,f)}}}if(!C(b(s,".zibby/commands/example.md"))){let c=Rt();await $(b(s,".zibby/commands/example.md"),c)}if(u){let c=Ot(p,l);await $(b(s,"README.md"),c)}try{let{validateMemorySyncConfig:c,applyMemorySyncConfig:g}=await Promise.resolve().then(()=>(Ee(),Se)),d=b(s,".zibby.config.mjs"),f=null;if(C(d))try{f=(await import(`file://${d}?t=${Date.now()}`)).default?.memorySync}catch{}let m=c(f);if(m.ok&&m.kind!=="noop"){let E=await import("@zibby/ui-memory").catch(()=>null),{getSessionToken:Z}=await Promise.resolve().then(()=>(ie(),re)),R=await g({cwd:s,projectId:l.projectId,block:f,memoryApi:E,getSessionToken:Z,hostedSetup:async({cwd:N,projectId:W})=>{let{memoryRemoteUseHostedCommand:be}=await Promise.resolve().then(()=>(no(),to));await be({cwd:N,projectId:W})},logger:{info:()=>{},warn:()=>{},error:()=>{}}});R.action==="hosted"?console.log(r.green(" \u2713 Hosted memory-sync configured from .zibby.config.mjs")):R.action==="byo"?console.log(r.green(` \u2713 Memory remote configured from .zibby.config.mjs \u2192 ${R.remote}`)):R.action==="pending-login"?(console.log(r.yellow(` \u26A0 memorySync.remote = "hosted" but you're not logged in.`)),console.log(r.gray(" Run `zibby login` then `zibby memory remote use --hosted` to finish."))):R.action==="error"&&console.log(r.yellow(` \u26A0 memorySync setup skipped: ${R.reason}`))}else m.ok||console.log(r.yellow(` \u26A0 memorySync config invalid: ${m.error}`))}catch(c){console.log(r.yellow(` \u26A0 memorySync auto-apply failed: ${c.message}`))}if(v.succeed(u?"Project created!":"Zibby initialized!"),I||(console.log(""),console.log(r.gray(" No workflow template installed. Add one when ready:")),console.log(r.gray(" zibby template list # see available")),console.log(r.gray(" zibby template add browser-test-automation # for `zibby test`")),console.log(r.gray(" Or pass `-t <name>` to a future `zibby init` to do both at once.")),console.log("")),u&&!o.skipInstall){let c=T("Installing dependencies...").start();await new Promise((g,d)=>{G("npm",["install"],{cwd:s,stdio:"pipe"}).on("close",m=>{m===0?(c.succeed("Dependencies installed!"),g()):(c.fail("Failed to install dependencies"),d(new Error("npm install failed")))})})}else if(!u){let c=["@zibby/cli","@zibby/core"],g=[];for(let d of c)try{ho(b(s,"package.json")).resolve(`${d}/package.json`)}catch{g.push(d)}if(g.length>0){let d=bo("../../package.json"),f=g.map(m=>m==="@zibby/cli"?`${m}@latest`:m==="@zibby/core"?`${m}@${d.dependencies?.["@zibby/core"]||"latest"}`:m);if(o.skipInstall)console.log(r.yellow(`
|
|
128
|
+
Missing required Zibby dependencies in this project:`)),console.log(r.white(` ${g.join(", ")}`)),console.log(r.gray("Install them manually to avoid runtime errors:")),console.log(r.white(` npm install --save-dev ${f.join(" ")}
|
|
129
|
+
`));else{let m=T(`Installing ${f.join(", ")}...`).start();await new Promise(Z=>{G("npm",["install","--save-dev",...f],{cwd:s,stdio:"pipe"}).on("close",N=>Z(N??1))})===0?m.succeed("Installed missing Zibby dependencies"):(m.warn("Could not auto-install Zibby dependencies"),console.log(r.gray("Run this manually:")),console.log(r.white(` npm install --save-dev ${f.join(" ")}
|
|
130
|
+
`)))}}}if(!u&&a&&i==="mem0"&&(console.log(r.yellow(`
|
|
131
|
+
Using mem0 backend requires mem0ai in your project dependencies.`)),console.log(r.gray("Run this manually in your project when ready:")),console.log(r.white(` npm install mem0ai
|
|
132
|
+
`))),!o.skipInstall&&t){let c=T("Installing Playwright browsers...").start();await new Promise(g=>{let d=G("npx",["playwright","install","chromium"],{cwd:s,stdio:"pipe"}),f="";d.stdout.on("data",m=>{f+=m.toString()}),d.stderr.on("data",m=>{f+=m.toString()}),d.on("close",m=>{m===0?(f.includes("already installed")||f.includes("up to date")?c.succeed("Playwright browsers already installed"):c.succeed("Playwright browsers installed!"),g()):(c.warn("Could not verify Playwright browsers"),console.log(r.yellow(`
|
|
133
133
|
If tests fail, run: npx playwright install
|
|
134
|
-
`)),g())})})}if(l.agent==="cursor"&&!o.skipInstall){let c=T("Checking cursor-agent CLI...").start();try{
|
|
135
|
-
`))}}}if(l.agent==="codex"&&!o.skipInstall){let c=T("Checking Codex CLI...").start();try{
|
|
136
|
-
`))}}}if(l.agent==="gemini"&&!o.skipInstall){let c=T("Checking Gemini CLI...").start();try{
|
|
137
|
-
`))}}if(t){let g=T("Configuring Gemini MCP servers...").start();try{let d=b(
|
|
138
|
-
`,"utf-8");let
|
|
139
|
-
`))}}}if(l.agent==="cursor"&&l.setupMcp&&t){let c=T("Setting up Playwright MCP...").start();try{let{setupPlaywrightMcpCommand:g}=await Promise.resolve().then(()=>(yo(),mo)),d=l.cloudSync||!1,f=l.browserMode!=="headless";await g({headed:f,cloudSync:d,viewport:{width:1280,height:720}});let m="Playwright MCP configured";f?m+=" (headed mode - visible browser)":m+=" (headless mode - hidden browser)",d&&(m+=" + Zibby MCP (cloud sync)"),c.succeed(m),d&&!(l.apiKey&&l.apiKey.trim())&&console.log(
|
|
134
|
+
`)),g())})})}if(l.agent==="cursor"&&!o.skipInstall){let c=T("Checking cursor-agent CLI...").start();try{oe("cursor-agent --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),c.succeed("cursor-agent CLI already installed")}catch{c.text="Installing cursor-agent CLI...";try{await new Promise((g,d)=>{G("bash",["-c","curl https://cursor.com/install -fsS | bash"],{stdio:"pipe"}).on("close",m=>{if(m===0){let E=b(B(),".local","bin");process.env.PATH.includes(E)||(process.env.PATH=`${E}:${process.env.PATH}`),c.succeed("cursor-agent CLI installed!"),g()}else d(new Error("cursor-agent install failed"))})})}catch{c.fail("Could not install cursor-agent CLI"),console.log(r.yellow(` Install manually: curl https://cursor.com/install -fsS | bash
|
|
135
|
+
`))}}}if(l.agent==="codex"&&!o.skipInstall){let c=T("Checking Codex CLI...").start();try{oe("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),c.succeed("Codex CLI already installed")}catch{c.text="Installing Codex CLI...";try{await new Promise((g,d)=>{G("npm",["install","-g","@openai/codex"],{stdio:"pipe"}).on("close",m=>{m===0?(c.succeed("Codex CLI installed!"),g()):d(new Error("npm install -g @openai/codex failed"))})})}catch{c.fail("Could not install Codex CLI"),console.log(r.yellow(` Install manually: npm install -g @openai/codex
|
|
136
|
+
`))}}}if(l.agent==="gemini"&&!o.skipInstall){let c=T("Checking Gemini CLI...").start();try{oe("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),c.succeed("Gemini CLI already installed")}catch{c.text="Installing Gemini CLI...";try{await new Promise((g,d)=>{G("npm",["install","-g","@google/gemini-cli"],{stdio:"pipe"}).on("close",m=>{m===0?(c.succeed("Gemini CLI installed!"),g()):d(new Error("npm install -g @google/gemini-cli failed"))})})}catch{c.fail("Could not install Gemini CLI"),console.log(r.yellow(` Install manually: npm install -g @google/gemini-cli
|
|
137
|
+
`))}}if(t){let g=T("Configuring Gemini MCP servers...").start();try{let d=b(B(),".gemini"),f=b(d,"settings.json");C(d)||await U(d,{recursive:!0});let m={mcpServers:{}};if(C(f))try{let W=await V(f,"utf-8");m=JSON.parse(W),m.mcpServers||(m.mcpServers={})}catch{}let E;try{let{createRequire:W}=await import("module");E=W(import.meta.url).resolve("@zibby/mcp-browser/bin/mcp-browser-zibby.js")}catch{E="@playwright/mcp"}let Z=l.browserMode!=="headless",R=E==="@playwright/mcp"?["-y","@playwright/mcp","--isolated","--viewport-size=1280x720","--output-dir","test-results"]:[E,"--isolated","--viewport-size=1280x720","--output-dir=test-results"];Z||R.push("--headless"),m.mcpServers["playwright-official"]={command:E==="@playwright/mcp"?"npx":"node",args:R},await $(f,`${JSON.stringify(m,null,2)}
|
|
138
|
+
`,"utf-8");let N="Gemini MCP configured";Z?N+=" (headed mode - visible browser)":N+=" (headless mode - hidden browser)",g.succeed(N)}catch(d){g.fail("MCP setup failed"),console.log(r.yellow(" You may need to configure ~/.gemini/settings.json manually")),console.log(r.gray(` Error: ${d.message}
|
|
139
|
+
`))}}}if(l.agent==="cursor"&&l.setupMcp&&t){let c=T("Setting up Playwright MCP...").start();try{let{setupPlaywrightMcpCommand:g}=await Promise.resolve().then(()=>(yo(),mo)),d=l.cloudSync||!1,f=l.browserMode!=="headless";await g({headed:f,cloudSync:d,viewport:{width:1280,height:720}});let m="Playwright MCP configured";f?m+=" (headed mode - visible browser)":m+=" (headless mode - hidden browser)",d&&(m+=" + Zibby MCP (cloud sync)"),c.succeed(m),d&&!(l.apiKey&&l.apiKey.trim())&&console.log(r.gray(`
|
|
140
140
|
Copy .env.example to .env and set ZIBBY_API_KEY to enable uploads
|
|
141
|
-
`))}catch(g){c.fail("MCP setup script failed"),console.log(
|
|
142
|
-
`)),console.log(
|
|
143
|
-
`))}}console.log(
|
|
141
|
+
`))}catch(g){c.fail("MCP setup script failed"),console.log(r.yellow(" Check if MCP is already configured:")),console.log(r.gray(' \u2022 Open Cursor settings \u2192 Check "playwright-official" MCP')),console.log(r.gray(" \u2022 Run: cursor-agent mcp list")),console.log(r.gray(` \u2022 Or run manually: zibby setup-playwright
|
|
142
|
+
`)),console.log(r.gray(` Error: ${g.message}
|
|
143
|
+
`))}}console.log(r.bold.green(`
|
|
144
144
|
All set!
|
|
145
|
-
`)),u&&(console.log(
|
|
146
|
-
`))),t?(console.log(
|
|
147
|
-
`)),console.log(
|
|
148
|
-
`))):(console.log(
|
|
149
|
-
`)),console.log(
|
|
150
|
-
`)),console.log(
|
|
151
|
-
`)))}catch(w){v.fail("Failed to create project"),console.error(
|
|
145
|
+
`)),u&&(console.log(r.cyan("Get into the project:")),console.log(r.white(` cd ${e}
|
|
146
|
+
`))),t?(console.log(r.cyan("Run a test:")),console.log(r.white(` zibby test test-specs/examples/example-domain.txt
|
|
147
|
+
`)),console.log(r.cyan("Cloud features (optional):")),console.log(r.white(` zibby login ${r.gray("# unlock workflow deploy, hosted memory, etc.")}`)),console.log(""),console.log(r.cyan("Next steps:")),console.log(r.white(` 1. cp .env.example .env ${r.gray("# then add your API keys")}`)),console.log(r.white(` 2. Write test specs in ${r.bold("test-specs/")}`)),console.log(r.white(` 3. Run: ${r.bold("zibby test <spec-file>")}`)),console.log(r.white(` 4. Or chat: ${r.bold("zibby")}
|
|
148
|
+
`))):(console.log(r.cyan("Start the Zibby chat agent:")),console.log(r.white(` zibby
|
|
149
|
+
`)),console.log(r.cyan("Add a workflow when ready:")),console.log(r.white(` zibby template list ${r.gray("# see available")}`)),console.log(r.white(` zibby template add browser-test-automation ${r.gray("# scaffold for `zibby test`")}`)),console.log(r.white(` zibby workflow new my-pipeline ${r.gray("# or write your own")}
|
|
150
|
+
`)),console.log(r.cyan("Cloud features (optional):")),console.log(r.white(` zibby login ${r.gray("# unlock workflow deploy, hosted memory, etc.")}`)),console.log(""),console.log(r.cyan("Next steps:")),console.log(r.white(` 1. cp .env.example .env ${r.gray("# then add your API keys")}`)),console.log(r.white(` 2. Run ${r.bold("zibby")} to chat, or scaffold a workflow above
|
|
151
|
+
`)))}catch(w){v.fail("Failed to create project"),console.error(r.red(`
|
|
152
152
|
Error: ${w.message}
|
|
153
|
-
`)),process.exit(1)}}function
|
|
153
|
+
`)),process.exit(1)}}function Pt(e,o={},t={}){let a=["dolt","mem0"].includes(String(t.memoryBackend||"").toLowerCase())?String(t.memoryBackend).toLowerCase():"dolt",i=e.agentAuth==="oauth"||e.agentAuth==="api"?`
|
|
154
154
|
auth: '${e.agentAuth}', // 'oauth' (subscription) or 'api' (pay-per-token); cloud needs 'api'`:"",s={claude:`
|
|
155
155
|
claude: {
|
|
156
156
|
model: 'auto', // Options: 'auto', 'sonnet-4.6', 'opus-4.6', 'sonnet-4.5', 'opus-4.5'
|
|
157
|
-
maxTokens: 4096,${e.agent==="claude"?
|
|
157
|
+
maxTokens: 4096,${e.agent==="claude"?i:""}
|
|
158
158
|
},`,cursor:`
|
|
159
159
|
cursor: {
|
|
160
|
-
model: 'auto', // Options: 'auto', 'opus-4.5', 'opus-4.5-thinking', 'sonnet-4.5', 'sonnet-4.5-thinking', 'composer-1', 'gpt-5.2-codex', 'gpt-5.2', 'gpt-5.3', 'gpt-5.4', 'gemini-3-pro', 'gemini-3-flash'${e.agent==="cursor"?
|
|
160
|
+
model: 'auto', // Options: 'auto', 'opus-4.5', 'opus-4.5-thinking', 'sonnet-4.5', 'sonnet-4.5-thinking', 'composer-1', 'gpt-5.2-codex', 'gpt-5.2', 'gpt-5.3', 'gpt-5.4', 'gemini-3-pro', 'gemini-3-flash'${e.agent==="cursor"?i:""}
|
|
161
161
|
},`,codex:`
|
|
162
162
|
codex: {
|
|
163
|
-
model: 'gpt-5.2-codex', // Options: 'auto', 'o4-mini', 'o3', 'codex-mini', 'gpt-4o', 'gpt-5.2-codex', 'gpt-5.2', 'gpt-5.3', 'gpt-5.4'${e.agent==="codex"?
|
|
163
|
+
model: 'gpt-5.2-codex', // Options: 'auto', 'o4-mini', 'o3', 'codex-mini', 'gpt-4o', 'gpt-5.2-codex', 'gpt-5.2', 'gpt-5.3', 'gpt-5.4'${e.agent==="codex"?i:""}
|
|
164
164
|
},`,gemini:`
|
|
165
165
|
gemini: {
|
|
166
|
-
model: 'gemini-2.5-pro', // Options: 'auto', 'gemini-2.5-pro', 'gemini-2.5-flash'${e.agent==="gemini"?
|
|
166
|
+
model: 'gemini-2.5-pro', // Options: 'auto', 'gemini-2.5-pro', 'gemini-2.5-flash'${e.agent==="gemini"?i:""}
|
|
167
167
|
},`},p=e.agent,u=Object.entries(s).filter(([l])=>l!==p).map(([,l])=>l.split(`
|
|
168
168
|
`).map(y=>y.trim()?` // ${y.trimStart()}`:y).join(`
|
|
169
169
|
`)).join(`
|
|
@@ -253,7 +253,7 @@ ${u}
|
|
|
253
253
|
// Cloud sync - auto-upload test results & videos (requires ZIBBY_API_KEY in .env)
|
|
254
254
|
cloudSync: ${e.cloudSync||!1}
|
|
255
255
|
};
|
|
256
|
-
`}function
|
|
256
|
+
`}function Ct(e,o="dolt"){return`# Zibby Test Automation - Environment Variables
|
|
257
257
|
|
|
258
258
|
# AI Provider Keys
|
|
259
259
|
${{claude:"ANTHROPIC_API_KEY=sk-ant-your_key_here",cursor:`# Cursor Agent uses cursor-agent CLI \u2014 no API key needed
|
|
@@ -270,7 +270,7 @@ ${{claude:"ANTHROPIC_API_KEY=sk-ant-your_key_here",cursor:`# Cursor Agent uses c
|
|
|
270
270
|
|
|
271
271
|
# Chat memory backend
|
|
272
272
|
ZIBBY_MEMORY_BACKEND=${o}
|
|
273
|
-
`}function
|
|
273
|
+
`}function _t(e,o,t="dolt"){return`# Zibby Test Automation - Environment Variables
|
|
274
274
|
|
|
275
275
|
# AI Provider Keys
|
|
276
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"}[e.agent]||""}
|
|
@@ -285,7 +285,7 @@ ZIBBY_API_KEY=${o}
|
|
|
285
285
|
|
|
286
286
|
# Chat memory backend
|
|
287
287
|
ZIBBY_MEMORY_BACKEND=${t}
|
|
288
|
-
`}function
|
|
288
|
+
`}function $t(e,o,t={}){let i={"@zibby/cli":"latest","@zibby/core":bo("../../package.json").dependencies?.["@zibby/core"]||"latest"};return t.memoryBackend==="mem0"&&(i.mem0ai="^2.4.6"),JSON.stringify({name:e,version:"1.0.0",type:"module",private:!0,scripts:{"test:spec":"zibby run",test:"playwright test","test:headed":"playwright test --headed"},dependencies:i,devDependencies:{"@playwright/test":"^1.49.0",dotenv:"^17.2.3"}},null,2)}function St(){return`# Dependencies
|
|
289
289
|
node_modules/
|
|
290
290
|
|
|
291
291
|
# Test artifacts
|
|
@@ -313,7 +313,7 @@ Thumbs.db
|
|
|
313
313
|
# Zibby memory (Dolt DB synced separately via dolt remote, not git)
|
|
314
314
|
.zibby/memory/
|
|
315
315
|
.zibby/memory-context.md
|
|
316
|
-
`}function
|
|
316
|
+
`}function Et(e="off",o=null){return`import { defineConfig} from '@playwright/test';
|
|
317
317
|
|
|
318
318
|
export default defineConfig({
|
|
319
319
|
testDir: './tests',
|
|
@@ -335,7 +335,7 @@ ${o?` outputDir: '${o}',
|
|
|
335
335
|
['list']
|
|
336
336
|
],
|
|
337
337
|
});
|
|
338
|
-
`}function
|
|
338
|
+
`}function zt(){return`Test Specification: Example Domain Navigation
|
|
339
339
|
==============================================
|
|
340
340
|
|
|
341
341
|
Application: Example Domain
|
|
@@ -372,7 +372,7 @@ Notes:
|
|
|
372
372
|
- Uses a stable, public domain (example.com) maintained by IANA
|
|
373
373
|
- No authentication required
|
|
374
374
|
- Suitable for CI/CD smoke testing
|
|
375
|
-
`}function
|
|
375
|
+
`}function Rt(){return`# Example command template
|
|
376
376
|
|
|
377
377
|
Use this command when the user asks for a concise testing task breakdown.
|
|
378
378
|
|
|
@@ -383,7 +383,7 @@ Required output format:
|
|
|
383
383
|
4. Expected result
|
|
384
384
|
|
|
385
385
|
Keep the response actionable and short.
|
|
386
|
-
`}function
|
|
386
|
+
`}function Ot(e,o){return`# ${e}
|
|
387
387
|
|
|
388
388
|
AI-powered test automation with Zibby.
|
|
389
389
|
|
|
@@ -472,4 +472,4 @@ ${e}/
|
|
|
472
472
|
|
|
473
473
|
- Documentation: https://docs.zibby.dev
|
|
474
474
|
- Examples: https://github.com/zibby/examples
|
|
475
|
-
`}export{
|
|
475
|
+
`}export{Pt as generateConfig,gn as initCommand};
|
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
1
|
+
import i from"chalk";import B from"inquirer";import{execSync as M}from"node:child_process";import{existsSync as T,readFileSync as C,writeFileSync as W,chmodSync as q,unlinkSync as Q}from"node:fs";import{homedir as Z,tmpdir as X}from"node:os";import{join as h}from"node:path";import{randomBytes as ee}from"node:crypto";import{existsSync as R,readFileSync as j,writeFileSync as pe,mkdirSync as ye}from"fs";import{join as D}from"path";import{homedir as G}from"os";var m={cursor:{envVar:"CURSOR_API_KEY",label:"Cursor API Key",url:"https://cursor.com/settings"},claude:{envVar:"ANTHROPIC_API_KEY",label:"Anthropic API Key",url:"https://console.anthropic.com/settings/keys"},codex:{envVar:"OPENAI_API_KEY",label:"OpenAI API Key",url:"https://platform.openai.com/api-keys"},gemini:{envVar:"GEMINI_API_KEY",label:"Gemini API Key",url:"https://aistudio.google.com/app/apikey"}};function H(){return D(G(),".zibby","config.json")}function O(){try{let e=H();return R(e)?JSON.parse(j(e,"utf-8")):{}}catch{return{}}}import{readFileSync as V,existsSync as z}from"fs";import F from"dotenv";var K=/^[A-Z_][A-Z0-9_]*$/;function J(e){return typeof e=="string"&&K.test(e)}function w(e){if(!Array.isArray(e)||e.length===0)return{};let t={};for(let n of e){if(!z(n))throw new Error(`--env file not found: ${n}`);let r=F.parse(V(n,"utf-8"));for(let[o,s]of Object.entries(r)){if(!J(o))throw new Error(`Invalid env var name "${o}" in ${n} \u2014 must match ${K} (uppercase letters, digits, underscores; can't start with a digit)`);t[o]=s}}return t}function b(e,t,n){let r=String(e).replace(/\/+$/,"");return n?`${r}/workflows/${t}/env/${encodeURIComponent(n)}`:`${r}/workflows/${t}/env`}var te={claude:["ANTHROPIC_API_KEY","CLAUDE_CODE_OAUTH_TOKEN"],cursor:["CURSOR_API_KEY"],codex:["OPENAI_API_KEY"],gemini:["GOOGLE_API_KEY"]};function re(){if(process.platform==="darwin")try{let e=M('security find-generic-password -s "Claude Code-credentials" -w',{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e){let t=JSON.parse(e);if(t?.claudeAiOauth?.accessToken)return t.claudeAiOauth}}catch{}try{let e=h(Z(),".claude",".credentials.json");return T(e)&&JSON.parse(C(e,"utf-8"))?.claudeAiOauth||null}catch{return null}}var ne={claude:[{localVar:"ANTHROPIC_API_KEY",uploadAs:"ANTHROPIC_API_KEY",kind:"api"},{localVar:"CLAUDE_CODE_OAUTH_TOKEN",uploadAs:"CLAUDE_CODE_OAUTH_TOKEN",kind:"oauth"}],cursor:[{localVar:"CURSOR_API_KEY",uploadAs:"CURSOR_API_KEY",kind:"api"}],codex:[{localVar:"OPENAI_API_KEY",uploadAs:"OPENAI_API_KEY",kind:"api"}],gemini:[{localVar:"GEMINI_API_KEY",uploadAs:"GOOGLE_API_KEY",kind:"api"},{localVar:"GOOGLE_API_KEY",uploadAs:"GOOGLE_API_KEY",kind:"api"}]};function oe(e){let t=N(e);if(!t)return null;let n=e?.agent;if(!n||typeof n!="object")return null;let r=n[t];if(r&&typeof r=="object"&&typeof r.auth=="string"){let o=r.auth.toLowerCase();if(o==="oauth"||o==="api")return o}return null}function N(e){if(!e||typeof e!="object")return null;let t=e.agent;if(!t)return null;if(typeof t=="string")return m[t]?t:null;if(typeof t=="object"){if(typeof t.provider=="string"&&m[t.provider])return t.provider;for(let n of Object.keys(t))if(m[n])return n}return null}function se(e){if(!e)return null;let t=h(e,".zibby-deploy.json");if(!T(t))return null;try{let n=JSON.parse(C(t,"utf-8"));if(typeof n?.uuid=="string"&&n.uuid)return n.uuid}catch{}return null}function ie(e,t,n){let o=(ne[e]||[]).slice().sort((s,a)=>n&&s.kind===n&&a.kind!==n?-1:n&&a.kind===n&&s.kind!==n?1:0);for(let s of o){let a=t?.[s.localVar];if(typeof a=="string"&&a.trim())return{...s,value:a.trim()}}return null}function ae(e,t,{readConfig:n=O}={}){let r=n()||{},o=r.agentKeys&&typeof r.agentKeys=="object"?r.agentKeys:{};return ie(e,o,t)}async function ce({apiUrl:e,sessionToken:t,uuid:n,fetchImpl:r}){let o=await r(b(e,n),{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});if(!o.ok)throw new Error(`GET /workflows/${n}/env \u2192 HTTP ${o.status}`);let s=await o.json();return Array.isArray(s?.keys)?s.keys:[]}function ue(e,t){if(!e?.length)return!1;try{let n=w(e);return t.some(r=>Object.prototype.hasOwnProperty.call(n,r)&&typeof n[r]=="string"&&n[r].trim().length>0)}catch{return!1}}async function le({workflowAgent:e,workflowUuid:t,authChoice:n,envFiles:r=[],sessionToken:o,apiUrl:s,fetchImpl:a=globalThis.fetch,readConfig:y=O}){if(!e)return{status:"error",detail:"workflowAgent unresolved (no agent in .zibby.config.mjs)"};let c=te[e];if(!c)return{status:"error",detail:`unknown agent: ${e}`};if(!o||!s)return{status:"error",detail:"missing sessionToken or apiUrl"};if(t)try{let d=await ce({apiUrl:s,sessionToken:o,uuid:t,fetchImpl:a}),A=c.find(f=>d.includes(f));if(A)return{status:"ok-already-set",acceptedVars:c,matchedVar:A}}catch(d){if(!/HTTP 404/.test(d.message))return{status:"error",detail:d.message}}if(ue(r,c))return{status:"ok-via-env-flag",acceptedVars:c};let u=ae(e,n,{readConfig:y});return u?{status:"mismatch-can-upload",acceptedVars:c,candidate:u}:{status:"mismatch-no-local",acceptedVars:c}}function Ce({uploadAs:e,value:t}){return $({[e]:t})}function $(e){let t=h(X(),`zibby-creds-${ee(8).toString("hex")}.env`),n=Object.entries(e).map(([o,s])=>{let a=String(s);return/[\s"'={}[\]:,]/.test(a)?`${o}='${a.replace(/'/g,"'\\''")}'`:`${o}=${a}`});W(t,`${n.join(`
|
|
2
|
+
`)}
|
|
3
|
+
`,"utf-8");try{q(t,384)}catch{}let r=()=>{try{Q(t)}catch{}};return process.on("exit",r),process.on("SIGINT",()=>{r(),process.exit(130)}),t}function fe({workflowAgent:e,acceptedVars:t,projectId:n,log:r}){r(i.red(` \u2716 No local ${e} credentials found to upload.`)),r(i.red(` Cloud Fargate needs ${t.join(" or ")} in this workflow's env.`)),r(""),r(i.yellow(" Pick one:")),e==="claude"?(r(i.yellow(" A. Set up Claude OAuth (no API costs):")),r(i.gray(" 1. claude (the CLI from @anthropic-ai/claude-code) \u2192 log in, quit")),r(i.gray(" 2. zibby init -f # picks up the token")),r(i.gray(" 3. zibby workflow deploy <name> # we'll upload it")),r(i.yellow(" B. Buy a Claude API key (pay-per-token):")),r(i.gray(" https://console.anthropic.com/settings/keys")),r(i.gray(" zibby workflow env set <uuid> ANTHROPIC_API_KEY=sk-ant-..."))):(r(i.yellow(` A. Get an API key for ${e}:`)),r(i.gray(` zibby workflow env set <uuid> ${t[0]}=<your-key>`))),r(i.yellow(" C. Skip this gate (deploy WILL fail at trigger time):")),r(i.gray(" zibby workflow deploy <name> --no-creds-check")),r(i.gray(" (or set the project-level key at")),r(i.gray(` https://studio.zibby.dev/projects/${n}/settings)`)),r("")}async function Ne({userConfig:e,workflowDir:t,projectId:n,sessionToken:r,apiUrl:o,deployOptions:s,fetchImpl:a,readConfig:y,prompt:c,log:u=console.log,writeTempBag:d=$,readFullBlob:A=re}){let f=N(e);if(!f)return{proceed:!0};let x=oe(e),S=se(t),Y=Array.isArray(s?.env)?s.env:[],E=await le({workflowAgent:f,workflowUuid:S,authChoice:x,envFiles:Y,sessionToken:r,apiUrl:o,fetchImpl:a,readConfig:y});switch(E.status){case"ok-already-set":return{proceed:!0};case"ok-via-env-flag":return{proceed:!0};case"mismatch-can-upload":{let{candidate:l}=E,U=c||(async({message:p})=>{let{proceed:P}=await B.prompt([{type:"confirm",name:"proceed",message:p,default:!0}]);return P}),k=l.kind==="oauth"?"OAuth token":"API key",L=`Cloud workflow has no ${f} credentials. Upload your local ${k} (${l.uploadAs})?`,g;try{g=await U({message:L})}catch{g=!1}if(!g)return u(i.yellow(` \u26A0 Deploying without ${l.uploadAs} on the workflow.`)),u(i.yellow(" Trigger will fail until you set it manually:")),u(i.gray(` zibby workflow env set <uuid> ${l.uploadAs}=<your-token>`)),{proceed:!0};let _,v="";if(f==="claude"&&l.kind==="oauth"){let p=A();p&&p.accessToken?(_={CLAUDE_CODE_CREDENTIALS_JSON:JSON.stringify({claudeAiOauth:p}),CLAUDE_CODE_OAUTH_TOKEN:p.accessToken},v=" (full Keychain blob \u2014 accessToken + refreshToken + expiresAt + scopes)"):_={CLAUDE_CODE_OAUTH_TOKEN:l.value}}else _={[l.uploadAs]:l.value};let I=d(_);return s&&(Array.isArray(s.env)||(s.env=[]),s.env.push(I)),u(i.green(` \u2713 Will upload ${k}${v} to workflow env after deploy.`)),{proceed:!0,addedEnvFile:I}}case"mismatch-no-local":return fe({workflowAgent:f,acceptedVars:E.acceptedVars,projectId:n,log:u}),{proceed:!1};default:return u(i.gray(` (skipped cloud-creds sanity check: ${E.detail||"unknown error"})`)),{proceed:!0}}}export{ie as pickLocalUpload,se as readDeployedUuid,re as readFullClaudeOauthBlob,ae as readLocalUpload,oe as resolveAgentAuthChoice,le as resolveCheckResult,N as resolveWorkflowAgent,Ne as runCloudCredsCheck,$ as writeTempEnvBag,Ce as writeTempEnvFile};
|
|
@@ -1,58 +1,59 @@
|
|
|
1
|
-
var
|
|
1
|
+
var mo=Object.defineProperty;var O=(e,o)=>()=>(e&&(o=e(e=0)),o);var Ee=(e,o)=>{for(var t in o)mo(e,t,{get:o[t],enumerable:!0})};function C(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";F[o]?e=F[o].apiUrl:e=F.prod.apiUrl}try{let o=new URL(e);return o.protocol!=="http:"&&o.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${o.protocol} (only http/https allowed)`),F.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),F.prod.apiUrl}}var F,Z=O(()=>{F={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}}});import{existsSync as Pe,mkdirSync as Eo,readFileSync as xo,writeFileSync as Io}from"fs";import{homedir as Ue}from"os";import{join as W}from"path";function Se(){return process.env.ZIBBY_CONFIG_DIR||W(Ue(),".zibby")}function Oe(){return W(Se(),"config.json")}function jo(){let e=Se();Pe(e)||Eo(e,{recursive:!0})}function B(){try{let e=Oe();if(Pe(e)){let o=xo(e,"utf-8");return JSON.parse(o)}}catch{}return{}}function G(e){jo(),Io(Oe(),JSON.stringify(e,null,2))}function Ce(){return B().sessionToken||null}function Ne(e){let o=B();o.sessionToken=e,G(o)}function Le(){return B().user||null}function Be(e){let o=B();o.user=e,G(o)}function Ke(e){let o=B();o.proxyUrl=e,G(o)}function ze(e){let o=B();o.mem0ProxyUrl=e,G(o)}function De(e){let o=B();o.projects=e,G(o)}var _o,_t,Re=O(()=>{_o=W(Ue(),".zibby"),_t=W(_o,"config.json")});import{existsSync as Pt,mkdirSync as Ut,readFileSync as St,writeFileSync as Ot,unlinkSync as Ct}from"fs";import{resolve as Lt}from"path";import{homedir as Kt}from"os";var Ye=O(()=>{});import h from"chalk";import le from"ora";import{spawn as To}from"child_process";function Po(e){let o=process.platform;try{let t,n;return o==="darwin"?(t="open",n=[e]):o==="win32"?(t="cmd",n=["/c","start","",e]):(t="xdg-open",n=[e]),To(t,n,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function Uo(){let e=Ce(),o=Le();return e&&o?{loggedIn:!0,user:o,token:e}:{loggedIn:!1}}async function Ge(){try{console.log(h.cyan(`
|
|
2
2
|
\u{1F510} Initiating login...
|
|
3
|
-
`));let e=
|
|
4
|
-
`));let{createInterface:o}=await import("readline"),t=o({input:process.stdin,output:process.stdout});return new Promise((n,r)=>{let i=()=>{t.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},s=()=>{console.log(
|
|
3
|
+
`));let e=Uo();if(e.loggedIn){console.log(h.green("\u2705 Already logged in!")),console.log(h.gray(`User: ${e.user.email}`)),console.log(h.gray(`Name: ${e.user.name}
|
|
4
|
+
`));let{createInterface:o}=await import("readline"),t=o({input:process.stdin,output:process.stdout});return new Promise((n,r)=>{let i=()=>{t.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},s=()=>{console.log(h.yellow(`
|
|
5
5
|
|
|
6
6
|
\u26A0\uFE0F Login cancelled
|
|
7
|
-
`)),i(),process.exit(0)};process.on("SIGINT",s),t.question(
|
|
8
|
-
`));let f=await
|
|
9
|
-
`)),n({success:!0,...e})}catch(f){r(f)}})})}return await
|
|
10
|
-
\u274C Login failed:`,e.message)),{success:!1,error:e.message}}}async function
|
|
7
|
+
`)),i(),process.exit(0)};process.on("SIGINT",s),t.question(h.yellow("Continue with this session? (Y/n): "),async c=>{process.removeListener("SIGINT",s),i();try{if(c.toLowerCase()==="n"||c.toLowerCase()==="no"){console.log(h.gray(`Starting new login...
|
|
8
|
+
`));let f=await Fe();n(f)}else console.log(h.green(`Using existing session.
|
|
9
|
+
`)),n({success:!0,...e})}catch(f){r(f)}})})}return await Fe()}catch(e){return console.error(h.red(`
|
|
10
|
+
\u274C Login failed:`,e.message)),{success:!1,error:e.message}}}async function So(e){let o=C();try{let t=await fetch(`${o}/projects`,{headers:{Authorization:`Bearer ${e}`}});if(t.ok){let r=((await t.json()).projects||[]).map(i=>({name:i.name,projectId:i.projectId,apiToken:i.apiToken}));return De(r),r}}catch(t){console.log(h.gray(`\u26A0\uFE0F Could not fetch projects: ${t.message}`))}return[]}async function Fe(){let e=C(),o=le("Requesting login code...").start(),t=await fetch(`${e}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){o.fail("Failed to request login code");let u=await t.json();throw new Error(u.error||"Failed to initiate login")}let{deviceCode:n,userCode:r,verificationUrl:i,expiresIn:s,interval:c}=await t.json();o.succeed("Login code generated"),console.log(""),console.log(h.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")),console.log(h.cyan("\u2551")+h.white.bold(" Complete login in your browser ")+h.cyan("\u2551")),console.log(h.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")),console.log(""),console.log(h.white("Opening browser to login page...")),console.log(h.gray(`Code expires in ${Math.floor(s/60)} minutes`)),console.log(""),await Po(i)||(console.log(h.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(h.white("Please open this URL manually: ")+h.blue(i)),console.log(""));let a=le("Waiting for authorization...").start(),g=(c||3)*1e3,x=Math.floor(s/(c||3)),d=0,_=!1,v=()=>{_=!0,a.stop(),console.log(h.yellow(`
|
|
11
11
|
|
|
12
12
|
\u26A0\uFE0F Login cancelled
|
|
13
|
-
`)),process.exit(0)};process.on("SIGINT",v);try{for(;
|
|
14
|
-
`)),{success:!0,loggedIn:!0,user:l.user,token:l.token}}if(l.status==="denied")throw a.fail("Authorization denied"),new Error("User denied authorization")}throw a.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",v)}}function
|
|
15
|
-
Not authenticated.`),console.log(` Run ${
|
|
16
|
-
`)}async function
|
|
17
|
-
Not logged in.`));let n;try{n=await
|
|
18
|
-
`)}var
|
|
19
|
-
|
|
13
|
+
`)),process.exit(0)};process.on("SIGINT",v);try{for(;d<x&&!_;){await Oo(g),d++;let u=await fetch(`${e}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:n})});if(u.status===202)continue;if(!u.ok){a.fail("Authorization failed");let y=await u.json();throw new Error(y.error||"Authorization failed")}let l=await u.json();if(l.status==="authorized"){a.succeed(h.white("Authorization successful!")),Ne(l.token),Be(l.user),l.proxyUrl&&Ke(l.proxyUrl),l.mem0ProxyUrl&&ze(l.mem0ProxyUrl),console.log(""),console.log(h.gray(`User: ${l.user.email}`));let y=le("Fetching projects...").start(),L=await So(l.token);return y.succeed(`Fetched ${L.length} project${L.length!==1?"s":""}`),console.log(h.gray(`Session saved to: ~/.zibby/config.json
|
|
14
|
+
`)),{success:!0,loggedIn:!0,user:l.user,token:l.token}}if(l.status==="denied")throw a.fail("Authorization denied"),new Error("User denied authorization")}throw a.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",v)}}function Oo(e){return new Promise(o=>setTimeout(o,e))}var Me=O(()=>{Z();Re();Ye()});import{existsSync as Co,readFileSync as No}from"fs";import{join as Lo}from"path";import fe from"chalk";import{confirm as Bo}from"@inquirer/prompts";function Ve(){try{let e=process.env.HOME||process.env.USERPROFILE;if(!e)return null;let o=Lo(e,".zibby","config.json");return Co(o)&&JSON.parse(No(o,"utf-8")).sessionToken||null}catch{return null}}function ue(){console.log(`
|
|
15
|
+
Not authenticated.`),console.log(` Run ${fe.cyan("zibby login")} or set ${fe.cyan("ZIBBY_API_KEY")} in your environment.
|
|
16
|
+
`)}async function q(e={}){let o=e.apiKey||process.env.ZIBBY_API_KEY||null,t=Ve();if(t||o)return{sessionToken:t,apiKey:o};if(!process.stdin.isTTY){if(e.optional)return{sessionToken:null,apiKey:null};ue(),process.exit(1)}console.log(fe.yellow(`
|
|
17
|
+
Not logged in.`));let n;try{n=await Bo({message:"Open browser to log in now?",default:!0})}catch{n=!1}if(!n){if(e.optional)return{sessionToken:null,apiKey:null};ue(),process.exit(1)}if(await Ge(),t=Ve(),!t){if(e.optional)return{sessionToken:null,apiKey:null};ue(),process.exit(1)}return{sessionToken:t,apiKey:null}}var pe=O(()=>{Me()});import{existsSync as Ko,readFileSync as zo,writeFileSync as tn,mkdirSync as nn}from"fs";import{join as Do}from"path";import{homedir as Ro}from"os";function Yo(){return Do(Ro(),".zibby","config.json")}function de(){try{let e=Yo();return Ko(e)?JSON.parse(zo(e,"utf-8")):{}}catch{return{}}}var Q,He=O(()=>{Q={cursor:{envVar:"CURSOR_API_KEY",label:"Cursor API Key",url:"https://cursor.com/settings"},claude:{envVar:"ANTHROPIC_API_KEY",label:"Anthropic API Key",url:"https://console.anthropic.com/settings/keys"},codex:{envVar:"OPENAI_API_KEY",label:"OpenAI API Key",url:"https://platform.openai.com/api-keys"},gemini:{envVar:"GEMINI_API_KEY",label:"Gemini API Key",url:"https://aistudio.google.com/app/apikey"}}});import{readFileSync as Fo,existsSync as Go}from"fs";import Mo from"dotenv";function X(e){return typeof e=="string"&&ge.test(e)}function Je(e){if(typeof e!="string"||e.length===0)throw new Error("Expected KEY=value, got empty argument");let o=e.indexOf("=");if(o<=0)throw new Error(`Expected KEY=value, got "${e}" \u2014 missing '=' or empty key`);let t=e.slice(0,o),n=e.slice(o+1);if(!X(t))throw new Error(`Invalid env var name "${t}" \u2014 must match ${ge} (uppercase letters, digits, underscores; can't start with a digit)`);return{key:t,value:n}}function M(e){if(!Array.isArray(e)||e.length===0)return{};let o={};for(let t of e){if(!Go(t))throw new Error(`--env file not found: ${t}`);let n=Mo.parse(Fo(t,"utf-8"));for(let[r,i]of Object.entries(n)){if(!X(r))throw new Error(`Invalid env var name "${r}" in ${t} \u2014 must match ${ge} (uppercase letters, digits, underscores; can't start with a digit)`);o[r]=i}}return o}function N(e,o,t){let n=String(e).replace(/\/+$/,"");return t?`${n}/workflows/${o}/env/${encodeURIComponent(t)}`:`${n}/workflows/${o}/env`}function ye(e){return!Array.isArray(e)||e.length===0?"No env vars set on this workflow.":[...e].sort().map(t=>` ${t}`).join(`
|
|
18
|
+
`)}var ge,he=O(()=>{ge=/^[A-Z_][A-Z0-9_]*$/});var no={};Ee(no,{pickLocalUpload:()=>eo,readDeployedUuid:()=>Xe,readFullClaudeOauthBlob:()=>qe,readLocalUpload:()=>oo,resolveAgentAuthChoice:()=>Qe,resolveCheckResult:()=>to,resolveWorkflowAgent:()=>we,runCloudCredsCheck:()=>it,writeTempEnvBag:()=>ke,writeTempEnvFile:()=>rt});import m from"chalk";import Vo from"inquirer";import{execSync as Ho}from"node:child_process";import{existsSync as Ze,readFileSync as We,writeFileSync as Jo,chmodSync as Zo,unlinkSync as Wo}from"node:fs";import{homedir as qo,tmpdir as Qo}from"node:os";import{join as me}from"node:path";import{randomBytes as Xo}from"node:crypto";function qe(){if(process.platform==="darwin")try{let e=Ho('security find-generic-password -s "Claude Code-credentials" -w',{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e){let o=JSON.parse(e);if(o?.claudeAiOauth?.accessToken)return o.claudeAiOauth}}catch{}try{let e=me(qo(),".claude",".credentials.json");return Ze(e)&&JSON.parse(We(e,"utf-8"))?.claudeAiOauth||null}catch{return null}}function Qe(e){let o=we(e);if(!o)return null;let t=e?.agent;if(!t||typeof t!="object")return null;let n=t[o];if(n&&typeof n=="object"&&typeof n.auth=="string"){let r=n.auth.toLowerCase();if(r==="oauth"||r==="api")return r}return null}function we(e){if(!e||typeof e!="object")return null;let o=e.agent;if(!o)return null;if(typeof o=="string")return Q[o]?o:null;if(typeof o=="object"){if(typeof o.provider=="string"&&Q[o.provider])return o.provider;for(let t of Object.keys(o))if(Q[t])return t}return null}function Xe(e){if(!e)return null;let o=me(e,".zibby-deploy.json");if(!Ze(o))return null;try{let t=JSON.parse(We(o,"utf-8"));if(typeof t?.uuid=="string"&&t.uuid)return t.uuid}catch{}return null}function eo(e,o,t){let r=(ot[e]||[]).slice().sort((i,s)=>t&&i.kind===t&&s.kind!==t?-1:t&&s.kind===t&&i.kind!==t?1:0);for(let i of r){let s=o?.[i.localVar];if(typeof s=="string"&&s.trim())return{...i,value:s.trim()}}return null}function oo(e,o,{readConfig:t=de}={}){let n=t()||{},r=n.agentKeys&&typeof n.agentKeys=="object"?n.agentKeys:{};return eo(e,r,o)}async function tt({apiUrl:e,sessionToken:o,uuid:t,fetchImpl:n}){let r=await n(N(e,t),{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}});if(!r.ok)throw new Error(`GET /workflows/${t}/env \u2192 HTTP ${r.status}`);let i=await r.json();return Array.isArray(i?.keys)?i.keys:[]}function nt(e,o){if(!e?.length)return!1;try{let t=M(e);return o.some(n=>Object.prototype.hasOwnProperty.call(t,n)&&typeof t[n]=="string"&&t[n].trim().length>0)}catch{return!1}}async function to({workflowAgent:e,workflowUuid:o,authChoice:t,envFiles:n=[],sessionToken:r,apiUrl:i,fetchImpl:s=globalThis.fetch,readConfig:c=de}){if(!e)return{status:"error",detail:"workflowAgent unresolved (no agent in .zibby.config.mjs)"};let f=et[e];if(!f)return{status:"error",detail:`unknown agent: ${e}`};if(!r||!i)return{status:"error",detail:"missing sessionToken or apiUrl"};if(o)try{let g=await tt({apiUrl:i,sessionToken:r,uuid:o,fetchImpl:s}),x=f.find(d=>g.includes(d));if(x)return{status:"ok-already-set",acceptedVars:f,matchedVar:x}}catch(g){if(!/HTTP 404/.test(g.message))return{status:"error",detail:g.message}}if(nt(n,f))return{status:"ok-via-env-flag",acceptedVars:f};let a=oo(e,t,{readConfig:c});return a?{status:"mismatch-can-upload",acceptedVars:f,candidate:a}:{status:"mismatch-no-local",acceptedVars:f}}function rt({uploadAs:e,value:o}){return ke({[e]:o})}function ke(e){let o=me(Qo(),`zibby-creds-${Xo(8).toString("hex")}.env`),t=Object.entries(e).map(([r,i])=>{let s=String(i);return/[\s"'={}[\]:,]/.test(s)?`${r}='${s.replace(/'/g,"'\\''")}'`:`${r}=${s}`});Jo(o,`${t.join(`
|
|
19
|
+
`)}
|
|
20
|
+
`,"utf-8");try{Zo(o,384)}catch{}let n=()=>{try{Wo(o)}catch{}};return process.on("exit",n),process.on("SIGINT",()=>{n(),process.exit(130)}),o}function st({workflowAgent:e,acceptedVars:o,projectId:t,log:n}){n(m.red(` \u2716 No local ${e} credentials found to upload.`)),n(m.red(` Cloud Fargate needs ${o.join(" or ")} in this workflow's env.`)),n(""),n(m.yellow(" Pick one:")),e==="claude"?(n(m.yellow(" A. Set up Claude OAuth (no API costs):")),n(m.gray(" 1. claude (the CLI from @anthropic-ai/claude-code) \u2192 log in, quit")),n(m.gray(" 2. zibby init -f # picks up the token")),n(m.gray(" 3. zibby workflow deploy <name> # we'll upload it")),n(m.yellow(" B. Buy a Claude API key (pay-per-token):")),n(m.gray(" https://console.anthropic.com/settings/keys")),n(m.gray(" zibby workflow env set <uuid> ANTHROPIC_API_KEY=sk-ant-..."))):(n(m.yellow(` A. Get an API key for ${e}:`)),n(m.gray(` zibby workflow env set <uuid> ${o[0]}=<your-key>`))),n(m.yellow(" C. Skip this gate (deploy WILL fail at trigger time):")),n(m.gray(" zibby workflow deploy <name> --no-creds-check")),n(m.gray(" (or set the project-level key at")),n(m.gray(` https://studio.zibby.dev/projects/${t}/settings)`)),n("")}async function it({userConfig:e,workflowDir:o,projectId:t,sessionToken:n,apiUrl:r,deployOptions:i,fetchImpl:s,readConfig:c,prompt:f,log:a=console.log,writeTempBag:g=ke,readFullBlob:x=qe}){let d=we(e);if(!d)return{proceed:!0};let _=Qe(e),v=Xe(o),u=Array.isArray(i?.env)?i.env:[],l=await to({workflowAgent:d,workflowUuid:v,authChoice:_,envFiles:u,sessionToken:n,apiUrl:r,fetchImpl:s,readConfig:c});switch(l.status){case"ok-already-set":return{proceed:!0};case"ok-via-env-flag":return{proceed:!0};case"mismatch-can-upload":{let{candidate:y}=l,L=f||(async({message:U})=>{let{proceed:R}=await Vo.prompt([{type:"confirm",name:"proceed",message:U,default:!0}]);return R}),T=y.kind==="oauth"?"OAuth token":"API key",P=`Cloud workflow has no ${d} credentials. Upload your local ${T} (${y.uploadAs})?`,E;try{E=await L({message:P})}catch{E=!1}if(!E)return a(m.yellow(` \u26A0 Deploying without ${y.uploadAs} on the workflow.`)),a(m.yellow(" Trigger will fail until you set it manually:")),a(m.gray(` zibby workflow env set <uuid> ${y.uploadAs}=<your-token>`)),{proceed:!0};let b,D="";if(d==="claude"&&y.kind==="oauth"){let U=x();U&&U.accessToken?(b={CLAUDE_CODE_CREDENTIALS_JSON:JSON.stringify({claudeAiOauth:U}),CLAUDE_CODE_OAUTH_TOKEN:U.accessToken},D=" (full Keychain blob \u2014 accessToken + refreshToken + expiresAt + scopes)"):b={CLAUDE_CODE_OAUTH_TOKEN:y.value}}else b={[y.uploadAs]:y.value};let K=g(b);return i&&(Array.isArray(i.env)||(i.env=[]),i.env.push(K)),a(m.green(` \u2713 Will upload ${T}${D} to workflow env after deploy.`)),{proceed:!0,addedEnvFile:K}}case"mismatch-no-local":return st({workflowAgent:d,acceptedVars:l.acceptedVars,projectId:t,log:a}),{proceed:!1};default:return a(m.gray(` (skipped cloud-creds sanity check: ${l.detail||"unknown error"})`)),{proceed:!0}}}var et,ot,ro=O(()=>{He();he();et={claude:["ANTHROPIC_API_KEY","CLAUDE_CODE_OAUTH_TOKEN"],cursor:["CURSOR_API_KEY"],codex:["OPENAI_API_KEY"],gemini:["GOOGLE_API_KEY"]};ot={claude:[{localVar:"ANTHROPIC_API_KEY",uploadAs:"ANTHROPIC_API_KEY",kind:"api"},{localVar:"CLAUDE_CODE_OAUTH_TOKEN",uploadAs:"CLAUDE_CODE_OAUTH_TOKEN",kind:"oauth"}],cursor:[{localVar:"CURSOR_API_KEY",uploadAs:"CURSOR_API_KEY",kind:"api"}],codex:[{localVar:"OPENAI_API_KEY",uploadAs:"OPENAI_API_KEY",kind:"api"}],gemini:[{localVar:"GEMINI_API_KEY",uploadAs:"GOOGLE_API_KEY",kind:"api"},{localVar:"GOOGLE_API_KEY",uploadAs:"GOOGLE_API_KEY",kind:"api"}]}});var so={};Ee(so,{listEnvCommand:()=>ct,pushEnvCommand:()=>ut,setEnvCommand:()=>at,syncEnvFromFiles:()=>ft,unsetEnvCommand:()=>lt});import k from"chalk";import ee from"ora";async function oe(e){let{sessionToken:o,apiKey:t}=await q({apiKey:e.apiKey}),n=o||t;return n||(console.log(k.red("\n Not authenticated \u2014 run `zibby login` or pass --api-key.\n")),process.exit(1)),{authToken:n,apiUrl:C()}}async function te(e,o,t,n,r){let i={method:e,headers:{Authorization:`Bearer ${t}`,...n?{"Content-Type":"application/json"}:{}},...n?{body:JSON.stringify(n)}:{}},s;try{s=await fetch(o,i)}catch(f){r&&r.fail(`Network error: ${f.message}`),process.exit(1)}let c;try{c=await s.json()}catch{c={}}return s.ok||(r?r.fail(c.error||c.message||`HTTP ${s.status}`):console.log(k.red(`
|
|
20
21
|
${c.error||c.message||`HTTP ${s.status}`}
|
|
21
|
-
`)),process.exit(1)),c}async function
|
|
22
|
-
Workflow UUID is required`)),console.log(
|
|
23
|
-
`)),process.exit(1));let{authToken:t,apiUrl:n}=await
|
|
24
|
-
Last updated: ${i.envUpdatedAt}`)),console.log("")}async function
|
|
25
|
-
Both UUID and KEY=value are required`)),console.log(
|
|
26
|
-
`)),process.exit(1));let n,r;try{({key:n,value:r}=
|
|
27
|
-
${
|
|
28
|
-
`)),process.exit(1)}let{authToken:i,apiUrl:s}=await
|
|
29
|
-
Both UUID and KEY are required`)),console.log(
|
|
30
|
-
`)),process.exit(1)),
|
|
22
|
+
`)),process.exit(1)),c}async function ct(e,o={}){e||(console.log(k.red(`
|
|
23
|
+
Workflow UUID is required`)),console.log(k.gray(` Usage: zibby workflow env list <uuid>
|
|
24
|
+
`)),process.exit(1));let{authToken:t,apiUrl:n}=await oe(o),r=ee(`Fetching env keys for ${e}...`).start(),i=await te("GET",N(n,e),t,null,r),s=i.keys||[];r.succeed(`${s.length} env var${s.length===1?"":"s"} on workflow ${e}`),console.log(""),console.log(ye(s)),i.envUpdatedAt&&console.log(k.gray(`
|
|
25
|
+
Last updated: ${i.envUpdatedAt}`)),console.log("")}async function at(e,o,t={}){(!e||!o)&&(console.log(k.red(`
|
|
26
|
+
Both UUID and KEY=value are required`)),console.log(k.gray(` Usage: zibby workflow env set <uuid> KEY=value
|
|
27
|
+
`)),process.exit(1));let n,r;try{({key:n,value:r}=Je(o))}catch(g){console.log(k.red(`
|
|
28
|
+
${g.message}
|
|
29
|
+
`)),process.exit(1)}let{authToken:i,apiUrl:s}=await oe(t),c=ee(`Setting ${n} on workflow ${e}...`).start(),a=((await te("PATCH",N(s,e,n),i,{value:r},c)).keys||[]).length;c.succeed(`Set ${k.cyan(n)} (workflow now has ${a} env var${a===1?"":"s"})`)}async function lt(e,o,t={}){(!e||!o)&&(console.log(k.red(`
|
|
30
|
+
Both UUID and KEY are required`)),console.log(k.gray(` Usage: zibby workflow env unset <uuid> KEY
|
|
31
|
+
`)),process.exit(1)),X(o)||(console.log(k.red(`
|
|
31
32
|
Invalid env var name "${o}"
|
|
32
|
-
`)),process.exit(1));let{authToken:n,apiUrl:r}=await
|
|
33
|
-
Workflow UUID is required`)),console.log(
|
|
34
|
-
`)),process.exit(1));let t=Array.isArray(o.file)?o.file:o.file?[o.file]:[];t.length===0&&(console.log(
|
|
35
|
-
At least one --file is required`)),console.log(
|
|
36
|
-
`)),process.exit(1));let n;try{n=
|
|
33
|
+
`)),process.exit(1));let{authToken:n,apiUrl:r}=await oe(t),i=ee(`Unsetting ${o} on workflow ${e}...`).start(),s=await te("DELETE",N(r,e,o),n,null,i),c=(s.keys||[]).length;s.removed?i.succeed(`Unset ${k.cyan(o)} (workflow now has ${c} env var${c===1?"":"s"})`):i.warn(`Key ${k.cyan(o)} was not set on workflow ${e} \u2014 nothing to do`)}async function ut(e,o={}){e||(console.log(k.red(`
|
|
34
|
+
Workflow UUID is required`)),console.log(k.gray(` Usage: zibby workflow env push <uuid> --file .env [--file .env.prod]
|
|
35
|
+
`)),process.exit(1));let t=Array.isArray(o.file)?o.file:o.file?[o.file]:[];t.length===0&&(console.log(k.red(`
|
|
36
|
+
At least one --file is required`)),console.log(k.gray(` Usage: zibby workflow env push <uuid> --file .env
|
|
37
|
+
`)),process.exit(1));let n;try{n=M(t)}catch(f){console.log(k.red(`
|
|
37
38
|
${f.message}
|
|
38
|
-
`)),process.exit(1)}let r=Object.keys(n);r.length===0&&(console.log(
|
|
39
|
+
`)),process.exit(1)}let r=Object.keys(n);r.length===0&&(console.log(k.yellow(`
|
|
39
40
|
No env vars found in ${t.join(", ")} \u2014 nothing to push.
|
|
40
|
-
`)),process.exit(0));let{authToken:i,apiUrl:s}=await
|
|
41
|
-
`);continue}
|
|
42
|
-
`)}if(i.text=
|
|
41
|
+
`)),process.exit(0));let{authToken:i,apiUrl:s}=await oe(o),c=ee(`Pushing ${r.length} env var${r.length===1?"":"s"} to ${e}...`).start();await te("PUT",N(s,e),i,{env:n},c),c.succeed(`Pushed ${r.length} env var${r.length===1?"":"s"} from ${t.join(", ")}`),console.log(""),console.log(ye(r)),console.log("")}async function ft({uuid:e,files:o,authToken:t,apiUrl:n,spinner:r}){let i=M(o),s=Object.keys(i);if(s.length===0)return{count:0,files:o};let c=N(n,e),f={method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({env:i})},a=await fetch(c,f);if(!a.ok){let g=await a.json().catch(()=>({}));throw new Error(`Env push failed: ${g.error||g.message||`HTTP ${a.status}`}`)}return r&&(r.text=`Synced ${s.length} env var${s.length===1?"":"s"} to workflow`),{count:s.length,files:o}}var io=O(()=>{pe();Z();he()});import{existsSync as j,readFileSync as ve,writeFileSync as pt}from"fs";import{join as A}from"path";import $ from"chalk";import ne from"ora";import dt from"dotenv";import{select as co}from"@inquirer/prompts";import{existsSync as wo}from"fs";import{join as ko}from"path";import{pathToFileURL as vo}from"url";async function xe(e){let o=ko(e,".zibby.config.mjs");if(!wo(o))throw new Error(".zibby.config.mjs not found");try{let t=await import(vo(o).href);return t.default||t}catch(t){throw new Error(`Failed to load .zibby.config.mjs: ${t.message}`,{cause:t})}}Z();function Ie(e,o){return e?.uuid||e?.workflowUuid||o?.uuid||null}var bo=4;function ae({elapsedMs:e,phase:o,step:t}){let r=` \u2014 ${Math.max(0,Math.floor(e/1e3))}s`;return t?`Building bundle on Zibby Cloud... [${t.n}/${bo}] ${t.label}${r}`:o?`Building bundle on Zibby Cloud... (${o.toLowerCase()})${r}`:`Building bundle on Zibby Cloud...${r}`}var Ao=/\[(\d+)\/\d+\]\s+(.+?)\s*\.{0,3}\s*$/;function _e(e){if(!e)return null;let o=Ao.exec(e);if(!o)return null;let t=parseInt(o[1],10);return!Number.isInteger(t)||t<1?null:{n:t,label:o[2].trim()}}function je(){let e=!1;return function(t){if(!t)return!0;let n=t.replace(/\s+$/,"");if(e)return/^\s*"\s*$/.test(n)&&(e=!1),!0;if(!$o(t))return!1;let r=n.replace(/^\[Container\]\s+\d{4}\/\d{2}\/\d{2}\s+\d{2}:\d{2}:\d{2}\.\d+\s*/,"");return r.startsWith("Running command ")&&(r.match(/"/g)||[]).length%2===1&&(e=!0),!0}}function $o(e){if(!e)return!0;let t=e.trim().replace(/^\[Container\]\s+\d{4}\/\d{2}\/\d{2}\s+\d{2}:\d{2}:\d{2}\.\d+\s*/,"");return!!(/^Phase complete:/.test(t)||/^Phase context status code:/.test(t)||/^Entering phase /.test(t)||/^Running command /.test(t)||/^Phase is /.test(t)||/^Waiting for /.test(t)||/^Registering with agent$/.test(t)||/^Running on CodeBuild /.test(t)||/^Phases found in YAML:/.test(t)||/^CODEBUILD_SRC_DIR=/.test(t)||/^YAML location is /.test(t)||/^Processing environment variables$/.test(t)||/^Moving to directory /.test(t)||/^Cache is not defined /.test(t)||/^Skip cache due to:/.test(t)||/^\s*INSTALL: \d+ commands?$/.test(t)||/^\s*BUILD: \d+ commands?$/.test(t)||/^Set report auto-discover timeout/.test(t)||/^Expanding /.test(t)||/^Assembling file list$/.test(t)||/^No matching auto-discover/.test(t)||/^Report auto-discover/.test(t)||t==="")}function Te({uuid:e,name:o,projectId:t,result:n,existingManifest:r=null,now:i=()=>new Date().toISOString()}){let s=n?.version??(r?.version??0)+1;return{uuid:e,name:o,projectId:t,version:s,deployedAt:i()}}pe();dt.config();async function gt({apiUrl:e,projectId:o,workflowName:t,buildId:n,authToken:r,spinner:i,verbose:s}){let c=Date.now(),f,a=null,g=null,x=je(),d=setInterval(()=>{i.text=ae({elapsedMs:Date.now()-c,phase:a,step:g})},1e3);try{for(;;){let _=new URL(`${e}/projects/${o}/workflows/${t}/build/${n}`);f&&_.searchParams.set("logsToken",f);let v;try{let u=await fetch(_,{headers:{Authorization:`Bearer ${r}`}});if(!u.ok)throw new Error(`HTTP ${u.status}`);v=await u.json()}catch{await new Promise(l=>setTimeout(l,2e3));continue}v.phase&&v.phase!==a&&(a=v.phase),v.nextLogsToken&&v.nextLogsToken!==f&&(f=v.nextLogsToken);for(let u of v.logEvents||[]){let l=String(u.m||"").trimEnd();if(!l)continue;let y=_e(l);if(y&&(g=y),s){process.stdout.write(` ${l}
|
|
42
|
+
`);continue}x(l)||y||process.stdout.write(` ${l}
|
|
43
|
+
`)}if(i.text=ae({elapsedMs:Date.now()-c,phase:a,step:g}),v.done){let u=(Date.now()-c)/1e3;return{status:v.status,elapsedSec:u,lastPhase:a}}await new Promise(u=>setTimeout(u,2e3))}}finally{clearInterval(d)}}async function yt(e,o){let t=C(),n=ne("Fetching projects...").start();try{let r=o||e,i=await fetch(`${t}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`}});i.ok||(n.fail("Failed to fetch projects"),process.exit(1));let s=await i.json();Array.isArray(s)||(s.projects&&Array.isArray(s.projects)?s=s.projects:s.data&&Array.isArray(s.data)?s=s.data:(n.fail("Unexpected response format"),process.exit(1))),(!s||s.length===0)&&(n.fail("No projects found"),process.exit(1)),n.succeed(`Found ${s.length} project${s.length===1?"":"s"}`),console.log("");let c=s.map(a=>{let g=a.projectId||a.id||a._id||"unknown";return{name:`${a.name||a.projectName||"Unnamed"} (${g})`,value:g}});return await co({message:"Select a project to deploy to:",choices:c})}catch(r){n.fail(`Error: ${r.message}`),process.exit(1)}}async function Nn(e,o={}){let t=process.cwd(),n=".zibby/workflows",r=null;try{r=await xe(t),n=r?.paths?.workflows||".zibby/workflows"}catch{}if(e){let u=A(t,n,e);j(u)||(console.log(`
|
|
43
44
|
Error: Workflow not found: ${n}/${e}/`),console.log(" Run `zibby workflow list` to see local workflows,"),console.log(` or scaffold a new one: zibby workflow new ${e}
|
|
44
45
|
`),process.exit(1))}else{let u=A(t,n);j(u)||(console.log(`
|
|
45
46
|
Error: No workflows found in ${n}/`),console.log(` Create one with: zibby workflow new <name>
|
|
46
|
-
`),process.exit(1));let{readdir:l,stat:
|
|
47
|
+
`),process.exit(1));let{readdir:l,stat:y}=await import("fs/promises"),L=await l(u),T=[];for(let P of L){let E=A(u,P);if(!(await y(E)).isDirectory())continue;(j(A(E,"graph.mjs"))||j(A(E,"graph.js")))&&T.push(P)}T.length===0&&(console.log(`
|
|
47
48
|
Error: No workflows found in ${n}/`),console.log(` Create one with: zibby workflow new <name>
|
|
48
|
-
`),process.exit(1)),console.log(""),e=await
|
|
49
|
-
Error: graph.mjs not found in ${n}/${e}/`),process.exit(1)),o.credsCheck!==!1)try{let{runCloudCredsCheck:u}=await Promise.resolve().then(()=>(
|
|
49
|
+
`),process.exit(1)),console.log(""),e=await co({message:"Select a workflow to deploy:",choices:T.map(P=>({name:P,value:P}))})}let{sessionToken:i,apiKey:s}=await q({apiKey:o.apiKey}),c=o.project||process.env.ZIBBY_PROJECT_ID;c||(console.log(""),c=await yt(s,i));let f=i||s,a=A(t,n,e),g=A(a,"graph.mjs"),x=A(a,"workflow.json");if(j(g)||(console.log(`
|
|
50
|
+
Error: graph.mjs not found in ${n}/${e}/`),process.exit(1)),o.credsCheck!==!1)try{let{runCloudCredsCheck:u}=await Promise.resolve().then(()=>(ro(),no));(await u({userConfig:r,workflowDir:a,projectId:c,sessionToken:f,apiUrl:C(),deployOptions:o})).proceed||(console.log(""),process.exit(1))}catch(u){console.log($.gray(` (creds-check skipped: ${u.message})`))}console.log(`
|
|
50
51
|
Deploying Workflow
|
|
51
|
-
`),console.log(" ".padEnd(60,"-")),console.log(` Workflow: ${e}`),console.log(` Project: ${c}`),console.log(" ".padEnd(60,"-")),console.log("");let
|
|
52
|
-
`),process.exit(1)}let
|
|
53
|
-
`),process.exit(1)}
|
|
54
|
-
`),process.exit(1)}let
|
|
55
|
-
`,"utf-8")}catch(
|
|
56
|
-
`)}}catch(
|
|
57
|
-
`))}}console.log(""),
|
|
58
|
-
`),process.exit(1)}}export{
|
|
52
|
+
`),console.log(" ".padEnd(60,"-")),console.log(` Workflow: ${e}`),console.log(` Project: ${c}`),console.log(" ".padEnd(60,"-")),console.log("");let d=ne("Validating workflow...").start(),_=ve(g,"utf-8");if(_.includes("@zibby/core")||_.includes("@zibby/skills")){let u=A(a,"package.json");j(u)||(d.fail("Missing package.json"),console.log(""),console.log($.red(" \u2717 graph.mjs imports @zibby packages but no package.json found")),console.log(""),console.log($.yellow(" Create package.json with:")),console.log(""),console.log($.gray(" {")),console.log($.gray(' "type": "module",')),console.log($.gray(' "dependencies": {')),console.log($.gray(' "@zibby/core": "workspace:*"')),console.log($.gray(" }")),console.log($.gray(" }")),console.log(""),process.exit(1));let l=JSON.parse(ve(u,"utf-8"));!{...l.dependencies,...l.devDependencies}["@zibby/core"]&&_.includes("@zibby/core")&&(d.fail("Missing @zibby/core dependency"),console.log(""),console.log($.red(" \u2717 graph.mjs imports @zibby/core but it's not in package.json")),console.log(""),console.log($.yellow(" Add to package.json dependencies:")),console.log($.gray(' "@zibby/core": "workspace:*"')),console.log(""),process.exit(1))}d.text="Loading workflow graph...";try{let{pathToFileURL:u}=await import("url"),l=await import(u(g).href),y;if(l.default)if(typeof l.default=="function"){let p=l.default.prototype;p&&p.buildGraph?y=new l.default:y=l.default()}else d.fail("graph.mjs must export a class or factory function"),process.exit(1);else{let p=Object.values(l).find(w=>w.prototype&&w.prototype.buildGraph);p?y=new p:(d.fail("graph.mjs must export a WorkflowAgent class or factory function"),process.exit(1))}let T=y.buildGraph().serialize(),{readdir:P,readFile:E}=await import("fs/promises"),b={};d.text="Packaging workflow sources...";let D=await E(g,"utf-8");if(b["graph.mjs"]=D,j(x)){let p=await E(x,"utf-8");b["workflow.json"]=p}let K=A(a,"nodes");if(j(K)){let p=await P(K);for(let w of p)if(w.endsWith(".mjs")||w.endsWith(".js")){let I=A(K,w),ce=await E(I,"utf-8");b[`nodes/${w}`]=ce}}let U=A(a,"package.json");if(j(U)){let p=await E(U,"utf-8");b["package.json"]=p,d.text="Including package.json for dependencies..."}let R=A(a,"package-lock.json");if(j(R)){let p=await E(R,"utf-8");b["package-lock.json"]=p}r&&typeof r=="object"&&(b["zibby.config.json"]=JSON.stringify(r,null,2)),d.text=`Uploading to cloud (${T.nodes.size||Object.keys(T.nodes||{}).length} nodes, ${Object.keys(b).length} files)...`;let Y=C(),be=JSON.stringify({format:1,sources:b}),Ae=Buffer.byteLength(be,"utf8"),V=await fetch(`${Y}/projects/${c}/workflows/${e}/sources/presign`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f}`},body:JSON.stringify({contentLength:Ae})});if(!V.ok){let p=await V.json().catch(()=>({}));d.fail("Deploy failed (presign)"),console.log(` Error: ${p.error||p.message||V.statusText}
|
|
53
|
+
`),process.exit(1)}let ao=await V.json(),{uploadUrl:lo,key:uo,headers:fo}=ao,re=await fetch(lo,{method:"PUT",headers:{...fo||{},"Content-Length":String(Ae)},body:be});if(!re.ok){let p=await re.text().catch(()=>"");d.fail("Deploy failed (S3 upload)"),console.log(` S3 PUT failed: ${re.status} ${p.slice(0,200)}
|
|
54
|
+
`),process.exit(1)}d.text="Saving workflow definition...";let H=await fetch(`${Y}/projects/${c}/workflows/${e}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f}`},body:JSON.stringify({graph:T,sourcesStagingKey:uo,isDefault:!1})});if(!H.ok){let p=await H.json().catch(()=>({}));d.fail("Deploy failed"),console.log(` Error: ${p.message||p.error||H.statusText}
|
|
55
|
+
`),process.exit(1)}let se=await H.json(),J=A(a,".zibby-deploy.json"),ie=j(J)?(()=>{try{return JSON.parse(ve(J,"utf-8"))}catch{return null}})():null,S=Ie(se,ie);if(S){let p=Te({uuid:S,name:e,projectId:c,result:se,existingManifest:ie});try{pt(J,`${JSON.stringify(p,null,2)}
|
|
56
|
+
`,"utf-8")}catch(w){console.log(` Warning: failed to write ${J}: ${w.message}`)}}let po=ie?"Updated":"Deployed";if(d.succeed(`${po} ${e} (v${se.version||1})`),!(o.noWait===!0||process.env.ZIBBY_DEPLOY_NO_BUNDLE==="1")){console.log("");let p=ne("Building bundle on Zibby Cloud...").start();try{let w=await fetch(`${Y}/projects/${c}/workflows/${e}/build`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f}`}});if(w.ok){let I=await w.json(),{buildId:ce}=I,go=o.verbose===!0||process.env.ZIBBY_DEPLOY_VERBOSE==="1",{status:$e,elapsedSec:yo,lastPhase:ho}=await gt({apiUrl:Y,projectId:c,workflowName:e,buildId:ce,authToken:f,spinner:p,verbose:go});$e==="SUCCEEDED"?p.succeed(`Bundle ready (${yo.toFixed(1)}s) \u2014 runtime npm install eliminated`):p.warn(`Bundle build ${$e} at phase ${ho||"unknown"} \u2014 workflow will fall back to runtime install`)}else{let I=await w.json().catch(()=>({}));p.warn(`Bundle build skipped: ${I.error||I.message||w.statusText}`),console.log(` Workflow will use slower runtime install path until next deploy.
|
|
57
|
+
`)}}catch(w){p.warn(`Bundle build error: ${w.message}`)}}let z=Array.isArray(o.env)?o.env:o.env?[o.env]:[];if(z.length>0)if(!S)console.log($.yellow(" Skipping --env sync: deploy did not return a workflow UUID."));else{console.log("");let p=ne(`Syncing env from ${z.join(", ")}...`).start();try{let{syncEnvFromFiles:w}=await Promise.resolve().then(()=>(io(),so)),{count:I}=await w({uuid:S,files:z,authToken:f,apiUrl:Y,spinner:p});I===0?p.warn(`No env vars found in ${z.join(", ")} \u2014 workflow env unchanged.`):p.succeed(`Synced ${I} env var${I===1?"":"s"} from ${z.join(", ")}`)}catch(w){p.fail(`Env sync failed: ${w.message}`),console.log($.gray(` Re-run after fixing: zibby workflow env push ${S} ${z.map(I=>`--file ${I}`).join(" ")}
|
|
58
|
+
`))}}console.log(""),S&&console.log(` UUID: ${S}`),console.log(""),console.log(" Next steps:"),console.log(` zibby workflow run ${e} Run locally`),S&&console.log(` zibby workflow trigger ${S} Run in cloud`),console.log(" zibby workflow list View all workflows"),console.log("")}catch(u){d.fail("Deploy failed"),console.log(` Error: ${u.message}
|
|
59
|
+
`),process.exit(1)}}export{Nn as deployWorkflowCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{mkdir as j,writeFile as C}from"fs/promises";import{existsSync as
|
|
1
|
+
import{mkdir as j,writeFile as C}from"fs/promises";import{existsSync as T}from"fs";import{spawn as ae}from"child_process";import{join as b}from"path";import i from"chalk";import R from"ora";import{input as le}from"@inquirer/prompts";import{existsSync as B}from"fs";import{join as Y}from"path";import{pathToFileURL as H}from"url";async function _(t){let e=Y(t,".zibby.config.mjs");if(!B(e))throw new Error(".zibby.config.mjs not found");try{let o=await import(H(e).href);return o.default||o}catch(o){throw new Error(`Failed to load .zibby.config.mjs: ${o.message}`,{cause:o})}}import{mkdir as Me,writeFile as Ne,readFile as Be}from"fs/promises";import{existsSync as He,readdirSync as Le}from"fs";import{join as Ge,resolve as Ze,dirname as L}from"path";import{homedir as We}from"os";import Fe from"inquirer";import Je from"chalk";import Qe from"ora";import{spawn as tt,execSync as ot}from"child_process";import{fileURLToPath as D}from"url";import{createRequire as G}from"module";import{existsSync as ve,readFileSync as Ce,writeFileSync as Ie,mkdirSync as Pe}from"fs";import{join as Ee}from"path";import{homedir as ze}from"os";var Z=D(import.meta.url),rt=L(Z),at=G(import.meta.url);function z(t,e={},o={}){let s=["dolt","mem0"].includes(String(o.memoryBackend||"").toLowerCase())?String(o.memoryBackend).toLowerCase():"dolt",n=t.agentAuth==="oauth"||t.agentAuth==="api"?`
|
|
2
2
|
auth: '${t.agentAuth}', // 'oauth' (subscription) or 'api' (pay-per-token); cloud needs 'api'`:"",a={claude:`
|
|
3
3
|
claude: {
|
|
4
4
|
model: 'auto', // Options: 'auto', 'sonnet-4.6', 'opus-4.6', 'sonnet-4.5', 'opus-4.5'
|
|
@@ -101,24 +101,24 @@ ${r}
|
|
|
101
101
|
// Cloud sync - auto-upload test results & videos (requires ZIBBY_API_KEY in .env)
|
|
102
102
|
cloudSync: ${t.cloudSync||!1}
|
|
103
103
|
};
|
|
104
|
-
`}import{readFileSync as x,existsSync as h,mkdirSync as P,writeFileSync as A,statSync as U,chmodSync as W}from"fs";import{join as m,dirname as I}from"path";import{fileURLToPath as V}from"url";import y from"chalk";var v=["claude","cursor","codex"],F=I(V(import.meta.url)),$=m(F,"..","..","..","templates","zibby-workflow-claude"),q="<!-- BEGIN zibby-workflows",
|
|
104
|
+
`}import{readFileSync as x,existsSync as h,mkdirSync as P,writeFileSync as A,statSync as U,chmodSync as W}from"fs";import{join as m,dirname as I}from"path";import{fileURLToPath as V}from"url";import y from"chalk";var v=["claude","cursor","codex"],F=I(V(import.meta.url)),$=m(F,"..","..","..","templates","zibby-workflow-claude"),q="<!-- BEGIN zibby-workflows",S="<!-- END zibby-workflows -->";function J(t){let e=process.argv[1];if(!e||!h(e))return null;let o=m(t,".zibby","bin"),s=m(o,"zibby");P(o,{recursive:!0});let n=`#!/bin/sh
|
|
105
105
|
# Auto-generated by 'zibby workflow generate'. Re-runs of generate update this path.
|
|
106
106
|
# Lets agents (Claude / Cursor / Codex) and CI scripts call zibby reliably even
|
|
107
107
|
# when the CLI isn't on PATH. Delete this file or .zibby/bin/ to disable.
|
|
108
108
|
exec node ${JSON.stringify(e)} "$@"
|
|
109
109
|
`;A(s,n);try{U(s)}catch{}try{W(s,493)}catch{}return s}function X(){let t=m($,"manifest.json");return JSON.parse(x(t,"utf8"))}function O(t){let e=t.match(/<!--\s*(?:BEGIN zibby-workflows\s+)?zibby-template-version:\s*(\d+)\s*-->/);return e?parseInt(e[1],10):null}function Q(t,e,o){if(!h(t))return{write:!0,reason:"new"};if(o)return{write:!0,reason:"force"};let s=x(t,"utf8"),n=O(s),a=O(e);return n==null?{write:!1,reason:"user-edited (no version marker)"}:a==null?{write:!1,reason:"shipped file has no version (skipping for safety)"}:n>a?{write:!1,reason:`current version ${n} > shipped ${a}`}:{write:!0,reason:n===a?"same version, refresh":`upgrade ${n} \u2192 ${a}`}}function ee(t,e){let o=`${e.trim()}
|
|
110
|
-
`;if(!h(t))return A(t,o),"created";let s=x(t,"utf8"),n=s.indexOf(q),a=s.indexOf(
|
|
110
|
+
`;if(!h(t))return A(t,o),"created";let s=x(t,"utf8"),n=s.indexOf(q),a=s.indexOf(S);if(n!==-1&&a!==-1&&a>n){let r=s.slice(0,n),l=s.slice(a+S.length),d=r+o.trim()+l;return d===s?"unchanged":(A(t,d),"updated")}let c=s.endsWith(`
|
|
111
111
|
`)?`
|
|
112
112
|
`:`
|
|
113
113
|
|
|
114
|
-
`;return A(t,s+c+o),"appended"}function te(t,e,o,s){let n=o.agents[t];if(!n)return[];let a=[],c=r=>m($,r.split("/").map(l=>l.startsWith(".")?l.slice(1):l).join("/"));for(let r of n.files||[]){let l=c(r);if(!h(l))continue;let d=x(l,"utf8"),p=m(e,r),
|
|
114
|
+
`;return A(t,s+c+o),"appended"}function te(t,e,o,s){let n=o.agents[t];if(!n)return[];let a=[],c=r=>m($,r.split("/").map(l=>l.startsWith(".")?l.slice(1):l).join("/"));for(let r of n.files||[]){let l=c(r);if(!h(l))continue;let d=x(l,"utf8"),p=m(e,r),g=Q(p,d,s);g.write?(P(I(p),{recursive:!0}),A(p,d),a.push({path:r,action:"write",detail:g.reason})):a.push({path:r,action:"skip",detail:g.reason})}for(let r of n.writeOnceFiles||[]){let l=c(r);if(!h(l))continue;let d=m(e,r);if(h(d)){a.push({path:r,action:"skip",detail:"write-once: already exists, leaving alone"});continue}P(I(d),{recursive:!0}),A(d,x(l,"utf8")),a.push({path:r,action:"write",detail:"write-once: created"})}if(n.rootBlock){let r=m($,n.rootBlock.source),l=x(r,"utf8"),d=m(e,n.rootBlock.target),p=ee(d,l);a.push({path:n.rootBlock.target,action:p})}return a}function oe(t){let e=t;for(let o=0;o<6;o++){if(h(m(e,".git"))||h(m(e,".zibby.config.mjs"))||h(m(e,"package.json")))return e;let s=I(e);if(s===e)break;e=s}return t}async function ne(t){let e=m(t,".zibby.config.mjs");if(!h(e))return null;try{return((await import(`file://${e}?t=${Date.now()}`)).default||{}).agentHelpers||null}catch(o){return console.log(y.gray(` (couldn't parse .zibby.config.mjs agentHelpers section: ${o.message})`)),null}}function se(t,e){let o=m(t,".zibby.config.mjs");if(!h(o)){console.log(y.yellow(" \u26A0\uFE0F .zibby.config.mjs not found; agentHelpers state not persisted"));return}let s=x(o,"utf8"),n=` agentHelpers: {
|
|
115
115
|
templateVersion: ${e.templateVersion},
|
|
116
116
|
agents: ${JSON.stringify(e.agents)},
|
|
117
117
|
updatedAt: '${new Date().toISOString()}',
|
|
118
118
|
},
|
|
119
119
|
`,a=/\s*agentHelpers\s*:\s*\{[^}]*\}\s*,?\n?/m,c;if(a.test(s))c=s.replace(a,`
|
|
120
120
|
${n}`);else{let r=s.lastIndexOf("}");if(r===-1)return;let l=s.slice(0,r),d=l.replace(/\s+$/,"").slice(-1);c=l+(d&&d!==","&&d!=="{"?`,
|
|
121
|
-
`:"")+n+s.slice(r)}A(o,c)}function ie(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[...v];if(e.length===1&&e[0]==="none")return["none"];for(let o of e)if(!v.includes(o))throw new Error(`unknown agent "${o}" \u2014 supported: ${v.join(", ")}`);return Array.from(new Set(e))}function re({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=ie(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:[...v]};if(!v.includes(s))throw new Error(`unknown agent "${s}" \u2014 supported: ${v.join(", ")}`);return{install:!0,agents:[s]}}if(o&&Array.isArray(o.agents)&&o.agents.length>0){let n=o.agents.filter(a=>a!=="none");return n.length>0?{install:!0,agents:n,fromConfig:!0}:{install:!1,reason:"explicit-no"}}return{install:!1,reason:"no-config"}}async function
|
|
121
|
+
`:"")+n+s.slice(r)}A(o,c)}function ie(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[...v];if(e.length===1&&e[0]==="none")return["none"];for(let o of e)if(!v.includes(o))throw new Error(`unknown agent "${o}" \u2014 supported: ${v.join(", ")}`);return Array.from(new Set(e))}function re({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=ie(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:[...v]};if(!v.includes(s))throw new Error(`unknown agent "${s}" \u2014 supported: ${v.join(", ")}`);return{install:!0,agents:[s]}}if(o&&Array.isArray(o.agents)&&o.agents.length>0){let n=o.agents.filter(a=>a!=="none");return n.length>0?{install:!0,agents:n,fromConfig:!0}:{install:!1,reason:"explicit-no"}}return{install:!1,reason:"no-config"}}async function K(t={}){let{forcedAgents:e,force:o=!1,silent:s=!1}=t,n=t.projectRoot||oe(process.cwd()),a=X(),c=await ne(n),r;if(e&&e.length>0?e.length===1&&e[0]==="none"?r={install:!1,reason:"explicit-no"}:r={install:!0,agents:e}:r=re({agentHelpersFlag:t.agentHelpersFlag,noAgentHelpers:t.noAgentHelpers===!0,existingConfig:c,legacyAgent:t.legacyAgent}),!r.install)return r.reason==="explicit-no"?(t.noAgentHelpers===!0||t.legacyAgent==="none"||e&&e.length===1&&e[0],{action:"skipped-explicit-no"}):{action:"skipped-no-config"};let l=r.agents,d=J(n),p=[];for(let g of l){if(!a.agents[g])continue;te(g,n,a,o).forEach(k=>p.push({...k,agent:g}))}if(se(n,{templateVersion:a.templateVersion,agents:l}),!s){r.fromConfig&&console.log(y.gray(` agent helpers: ${l.join(", ")} (from .zibby.config.mjs)`));let g=p.filter(u=>["write","created","updated","appended"].includes(u.action)),f=p.filter(u=>u.action==="skip"),k=p.filter(u=>u.action==="unchanged");if(g.length>0){console.log(y.green(` \u2713 Wrote ${g.length} agent helper file(s):`));for(let u of g)console.log(y.gray(` ${u.path} (${u.detail||u.action})`))}if(f.length>0){console.log(y.yellow(` \u26A0\uFE0F Skipped ${f.length} (use --force-agents to overwrite):`));for(let u of f)console.log(y.gray(` ${u.path} \u2014 ${u.detail}`))}g.length===0&&f.length===0&&k.length>0&&console.log(y.gray(` Agent helpers up to date (template v${a.templateVersion}).`)),r.fromConfig||console.log(y.gray(` agentHelpers: { agents: [${l.map(u=>`"${u}"`).join(", ")}] } saved to .zibby.config.mjs`)),d&&console.log(y.gray(` CLI shim: ${d} (agents fall back to ./.zibby/bin/zibby if zibby isn't on PATH)`)),l.includes("claude")&&console.log(y.gray(" \u2192 Run `claude` and try /zibby-add-node"))}return{action:r.fromConfig?"installed-from-config":"installed",agents:l}}function ce(t){return new Promise(e=>{let o=ae("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 de=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/,M=["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"],N=["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 ge(){let t=M[Math.floor(Math.random()*M.length)],e=N[Math.floor(Math.random()*N.length)];return`${t}-${e}`}function ue(t){return`${t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}Workflow`}function pe(t,e){return`/**
|
|
122
122
|
* ${t}
|
|
123
123
|
*
|
|
124
124
|
* buildGraph() \u2014 define nodes, edges, conditional routing
|
|
@@ -166,20 +166,20 @@ Analyze the input and return a summary with a status.\`,
|
|
|
166
166
|
};
|
|
167
167
|
`}function ye(t,e){return`${JSON.stringify({name:t,description:`${e} workflow`,entryClass:e,triggers:{api:!0}},null,2)}
|
|
168
168
|
`}function he(){return`${JSON.stringify({type:"module",dependencies:{"@zibby/core":"^0.3.0"}},null,2)}
|
|
169
|
-
`}async function
|
|
169
|
+
`}async function Ct(t,e={}){let o;t?o=t.toLowerCase():(o=ge(),console.log(i.gray(`
|
|
170
170
|
No name provided \u2014 generated: ${i.white(o)}`))),de.test(o)||(console.log(i.red(`
|
|
171
171
|
Invalid workflow name: "${t}"`)),console.log(i.gray(" Must be lowercase, start with a letter, use only a-z, 0-9, hyphens")),console.log(i.gray(" Length: 2\u201364 characters")),console.log(i.gray(` Example: ticket-triage, pr-review, deploy-checker
|
|
172
|
-
`)),process.exit(1));let s=process.cwd(),n=b(s,".zibby.config.mjs"),a=
|
|
172
|
+
`)),process.exit(1));let s=process.cwd(),n=b(s,".zibby.config.mjs"),a=T(n),c=".zibby/workflows";if(a)try{let g=await _(s);g?.paths?.workflows&&(c=g.paths.workflows)}catch(g){console.log(i.yellow(` \u26A0\uFE0F Could not load .zibby.config.mjs: ${g.message}`)),console.log(i.gray(` Using default path: ${c}`))}else if(process.stdin.isTTY){console.log(i.gray(`
|
|
173
173
|
Common picks: ${i.white(".zibby/workflows")} (hidden, default) \xB7 ${i.white("workflows")} (visible at project root)
|
|
174
|
-
`));let f=(await le({message:`Where to save workflows? ${i.gray("[Enter for .zibby/workflows]")}`})).trim();c=f===""?".zibby/workflows":f}else console.log(i.gray(` Using default workflows path: ${c} (run interactively to customize)`));let r=b(s,c,o),l=b(r,"nodes");
|
|
174
|
+
`));let f=(await le({message:`Where to save workflows? ${i.gray("[Enter for .zibby/workflows]")}`})).trim();c=f===""?".zibby/workflows":f}else console.log(i.gray(` Using default workflows path: ${c} (run interactively to customize)`));let r=b(s,c,o),l=b(r,"nodes");T(r)&&(console.log(i.red(`
|
|
175
175
|
Workflow already exists: ${c}/${o}/`)),console.log(i.gray(` Choose a different name or delete the existing folder.
|
|
176
|
-
`)),process.exit(1));let d=
|
|
177
|
-
Created:`)),console.log(i.white(` ${c}/${o}/`)),console.log(i.gray(` graph.mjs ${d} (entry)`)),console.log(i.gray(" nodes/index.mjs barrel export")),console.log(i.gray(" nodes/example.mjs starter node (prompt + schema)")),console.log(i.gray(" workflow.json manifest")),console.log(i.gray(" package.json dependencies (@zibby/core)")),
|
|
178
|
-
`)[0]||"unknown error"})`),console.log(i.gray(` Run manually: cd ${c}/${o} && npm install`)))}let k={action:"skipped-no-config"};try{k=await
|
|
176
|
+
`)),process.exit(1));let d=ue(o),p=R(` Scaffolding workflow "${o}"...`).start();try{await j(b(s,c),{recursive:!0}),await j(l,{recursive:!0}),await Promise.all([C(b(r,"graph.mjs"),pe(d,o)),C(b(l,"index.mjs"),me()),C(b(l,"example.mjs"),fe()),C(b(r,"workflow.json"),ye(o,d)),C(b(r,"package.json"),he())]);let g=!1;if(!a){let w=z({agent:"claude",browserMode:"headless",workflowsPath:c},{},{memoryBackend:"dolt"});await C(n,w),g=!0}p.succeed(` Scaffolded ${i.bold(o)}`),console.log(i.green(`
|
|
177
|
+
Created:`)),console.log(i.white(` ${c}/${o}/`)),console.log(i.gray(` graph.mjs ${d} (entry)`)),console.log(i.gray(" nodes/index.mjs barrel export")),console.log(i.gray(" nodes/example.mjs starter node (prompt + schema)")),console.log(i.gray(" workflow.json manifest")),console.log(i.gray(" package.json dependencies (@zibby/core)")),g&&console.log(i.white(" .zibby.config.mjs project config (agent: claude \u2014 edit to switch)"));let f=!1;if(e.skipInstall)console.log(i.gray(` Skipped npm install (--skip-install). Run manually: cd ${c}/${o} && npm install`));else{let w=R({text:` Installing dependencies in ${c}/${o}/...`,prefixText:""}).start(),E=await ce(r);E.ok?(w.succeed(` Installed dependencies in ${c}/${o}/`),f=!0):(w.warn(` Could not install dependencies (${E.stderr.trim().split(`
|
|
178
|
+
`)[0]||"unknown error"})`),console.log(i.gray(` Run manually: cd ${c}/${o} && npm install`)))}let k={action:"skipped-no-config"};try{k=await K({projectRoot:s,agentHelpersFlag:e.agentHelpers,noAgentHelpers:e.agentHelpers===!1,legacyAgent:e.agent,force:e.forceClaude===!0||e.forceAgents===!0})||k}catch(w){/^unknown agent /.test(w.message)&&(console.log(i.red(`
|
|
179
179
|
${w.message}
|
|
180
180
|
`)),process.exit(1)),console.log(i.yellow(` \u26A0\uFE0F Agent helpers setup failed: ${w.message}`)),console.log(i.gray(" Run `zibby agents add` later to retry."))}console.log(i.white(`
|
|
181
|
-
Next steps:`));let
|
|
181
|
+
Next steps:`));let u=1;!f&&e.skipInstall!==!0&&console.log(i.cyan(` ${u++}. Install deps: cd ${c}/${o} && npm install`)),console.log(i.cyan(` ${u++}. Edit nodes in ${c}/${o}/nodes/`)),console.log(i.cyan(` ${u++}. Wire them in graph.mjs`)),console.log(i.cyan(` ${u++}. Run locally: zibby workflow run ${o}`)),console.log(i.cyan(` ${u++}. Deploy to cloud: zibby workflow deploy ${o}
|
|
182
182
|
`)),k.action==="skipped-no-config"&&(console.log(i.gray(" Tip: Using Claude Code or Cursor? Set up slash commands + agent context:")),console.log(i.gray(" zibby workflow new <name> --agent-helpers claude")),console.log(i.gray(` (commits agentHelpers to .zibby.config.mjs \u2014 auto-applies to future workflows)
|
|
183
|
-
`)))}catch(
|
|
184
|
-
${
|
|
185
|
-
`)),process.exit(1)}}export{
|
|
183
|
+
`)))}catch(g){p.fail(" Scaffold failed"),console.log(i.red(`
|
|
184
|
+
${g.message}
|
|
185
|
+
`)),process.exit(1)}}export{Ct as generateWorkflowCommand};
|
package/dist/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zibby/cli",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.3",
|
|
4
4
|
"description": "Zibby CLI - Test automation generator and runner",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"dependencies": {
|
|
35
35
|
"@aws-sdk/client-sqs": "^3.1038.0",
|
|
36
36
|
"@zibby/agent-workflow": "^0.3.2",
|
|
37
|
-
"@zibby/core": "^0.3.
|
|
37
|
+
"@zibby/core": "^0.3.5",
|
|
38
38
|
"@zibby/ui-memory": "^1.0.0",
|
|
39
39
|
"@zibby/skills": "^0.1.11",
|
|
40
40
|
"adm-zip": "^0.5.17",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zibby/cli",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.3",
|
|
4
4
|
"description": "Zibby CLI - Test automation generator and runner",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"dependencies": {
|
|
35
35
|
"@aws-sdk/client-sqs": "^3.1038.0",
|
|
36
36
|
"@zibby/agent-workflow": "^0.3.2",
|
|
37
|
-
"@zibby/core": "^0.3.
|
|
37
|
+
"@zibby/core": "^0.3.5",
|
|
38
38
|
"@zibby/ui-memory": "^1.0.0",
|
|
39
39
|
"@zibby/skills": "^0.1.11",
|
|
40
40
|
"adm-zip": "^0.5.17",
|