@zibby/cli 0.2.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +117 -16
- package/dist/bin/zibby.js +3 -3
- package/dist/commands/chat-agents.js +1 -1
- package/dist/commands/chat.js +62 -62
- package/dist/commands/credentials-api.js +1 -1
- package/dist/commands/credentials-file.js +1 -1
- package/dist/commands/creds.js +1 -1
- package/dist/commands/init.js +180 -82
- package/dist/commands/memory.js +48 -20
- package/dist/commands/run.js +52 -55
- package/dist/commands/template.js +9 -0
- package/dist/commands/uninstall.js +15 -14
- package/dist/commands/workflows/agent-helpers.js +7 -7
- package/dist/commands/workflows/generate.js +54 -32
- package/dist/commands/workflows/run-local.js +19 -19
- package/dist/commands/workflows/run.js +5 -5
- package/dist/commands/workflows/start.js +12 -12
- package/dist/package.json +2 -2
- package/dist/templates/zibby-workflow-claude/agents-md-block.md +65 -5
- package/dist/templates/zibby-workflow-claude/claude/agents/zibby-test-author.md +16 -1
- package/dist/templates/zibby-workflow-claude/claude/agents/zibby-workflow-builder.md +22 -2
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-add-node.md +1 -1
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-debug.md +1 -1
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-delete.md +1 -1
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-deploy.md +24 -14
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-list.md +2 -2
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-memory-cost.md +39 -0
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-memory-pull.md +47 -0
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-memory-remote-use-hosted.md +61 -0
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-memory-stats.md +38 -0
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-static-ip.md +8 -6
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-tail.md +1 -1
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-test-debug.md +2 -2
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-test-generate.md +1 -1
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-test-run.md +3 -2
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-test-write.md +1 -1
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-trigger.md +10 -6
- package/dist/templates/zibby-workflow-claude/cursor/rules/zibby-workflows.mdc +76 -13
- package/dist/templates/zibby-workflow-claude/manifest.json +5 -1
- package/dist/utils/agent-credentials.js +4 -3
- package/dist/utils/apply-memory-sync-config.js +1 -0
- package/dist/utils/credentials-loader.js +1 -1
- package/dist/utils/hosted-memory-sync.js +1 -0
- package/package.json +2 -2
package/dist/commands/memory.js
CHANGED
|
@@ -1,39 +1,67 @@
|
|
|
1
|
-
import o from"chalk";var
|
|
2
|
-
Install @zibby/memory and Dolt to enable test memory:
|
|
1
|
+
var lo=Object.defineProperty;var _=(e,n)=>()=>(e&&(n=e(e=0)),n);var I=(e,n)=>{for(var t in n)lo(e,t,{get:n[t],enumerable:!0})};var P={};I(P,{ENVIRONMENTS:()=>a,getAccountApiUrl:()=>ao,getApiUrl:()=>io,getCurrentEnvironment:()=>uo,getFrontendUrl:()=>go});function io(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let n=process.env.ZIBBY_ENV||"prod";a[n]?e=a[n].apiUrl:e=a.prod.apiUrl}try{let n=new URL(e);return n.protocol!=="http:"&&n.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${n.protocol} (only http/https allowed)`),a.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),a.prod.apiUrl}}function ao(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let e=process.env.ZIBBY_ENV||"prod";return(a[e]||a.prod).accountApiUrl}function uo(){let e=process.env.ZIBBY_ENV||"prod";return a[e]||a.prod}function go(){let e;if(process.env.ZIBBY_FRONTEND_URL)e=process.env.ZIBBY_FRONTEND_URL;else{let n=process.env.ZIBBY_ENV||"prod";a[n]?e=a[n].frontendUrl:e=a.prod.frontendUrl}try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${n.protocol} (only http/https allowed)`),a.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let c=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],s=n.hostname;if(!c.some(l=>s===l||s.endsWith(`.${l}`))&&!s.includes("localhost")&&s!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${s}`),"https://studio.zibby.dev"}return e}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${e}`),a.local.frontendUrl}}var a,E=_(()=>{a={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}}});var J={};I(J,{clearSession:()=>Y,default:()=>bo,getMem0ProxyUrl:()=>W,getProjects:()=>G,getProxyUrl:()=>Z,getSessionToken:()=>S,getUserInfo:()=>j,isLoggedIn:()=>F,loadConfig:()=>d,saveConfig:()=>f,saveMem0ProxyUrl:()=>V,saveProjects:()=>H,saveProxyUrl:()=>K,saveSessionToken:()=>O,saveUserInfo:()=>M});import{existsSync as N,mkdirSync as mo,readFileSync as yo,writeFileSync as po}from"fs";import{homedir as T}from"os";import{join as x}from"path";function D(){return process.env.ZIBBY_CONFIG_DIR||x(T(),".zibby")}function B(){return x(D(),"config.json")}function ho(){let e=D();N(e)||mo(e,{recursive:!0})}function d(){try{let e=B();if(N(e)){let n=yo(e,"utf-8");return JSON.parse(n)}}catch{}return{}}function f(e){ho(),po(B(),JSON.stringify(e,null,2))}function S(){return d().sessionToken||null}function O(e){let n=d();n.sessionToken=e,f(n)}function j(){return d().user||null}function M(e){let n=d();n.user=e,f(n)}function F(){return S()!==null}function Y(){let e=d();delete e.sessionToken,delete e.user,delete e.mem0ProxyUrl,f(e)}function Z(){return d().proxyUrl||null}function K(e){let n=d();n.proxyUrl=e,f(n)}function W(){return d().mem0ProxyUrl||null}function V(e){let n=d();n.mem0ProxyUrl=e,f(n)}function G(){return d().projects||[]}function H(e){let n=d();n.projects=e,f(n)}var L,fo,bo,q=_(()=>{L=x(T(),".zibby"),fo=x(L,"config.json");bo={loadConfig:d,saveConfig:f,getSessionToken:S,saveSessionToken:O,getUserInfo:j,saveUserInfo:M,isLoggedIn:F,clearSession:Y,getProxyUrl:Z,saveProxyUrl:K,getMem0ProxyUrl:W,saveMem0ProxyUrl:V,getProjects:G,saveProjects:H,CONFIG_DIR:L,CONFIG_FILE:fo}});var A={};I(A,{__testing:()=>Uo,buildDoltEnv:()=>vo,clearConfig:()=>So,getActiveCredentials:()=>ro,isHosted:()=>_o,readConfig:()=>C,refreshCredentials:()=>to,writeConfig:()=>Io});import{readFileSync as Q,writeFileSync as U,existsSync as R,mkdirSync as X,chmodSync as wo}from"fs";import{join as v}from"path";function b(e){let n=v(e,".zibby");return{dir:n,config:v(n,$o),creds:v(n,xo)}}function C(e){let{config:n}=b(e);if(!R(n))return null;try{let t=JSON.parse(Q(n,"utf-8"));return t.mode!=="hosted"?null:t}catch{return null}}function _o(e){return!!C(e)}function Io(e,n){let{dir:t,config:c}=b(e);X(t,{recursive:!0}),U(c,JSON.stringify({mode:"hosted",projectId:n.projectId,bucket:n.bucket,prefix:n.prefix,doltUrl:n.doltUrl,configuredAt:new Date().toISOString()},null,2),"utf-8")}function So(e){let{config:n,creds:t}=b(e);for(let c of[n,t])if(R(c))try{U(c,"")}catch{}}function z(e){let{creds:n}=b(e);if(!R(n))return null;try{let t=JSON.parse(Q(n,"utf-8"));return!t?.accessKeyId||!t?.secretAccessKey||!t?.sessionToken?null:t}catch{return null}}function eo(e,n){let{dir:t,creds:c}=b(e);X(t,{recursive:!0}),U(c,JSON.stringify(n,null,2),"utf-8");try{wo(c,384)}catch{}}function no(e){return e?.expiration?new Date(e.expiration).getTime()-Date.now()<oo:!0}async function to({cwd:e,projectId:n,apiUrl:t,sessionToken:c,fetch:s=globalThis.fetch}){if(!n)throw new Error("refreshCredentials: projectId required");if(!t)throw new Error("refreshCredentials: apiUrl required");if(!c)throw new Error("refreshCredentials: sessionToken required (run `zibby login`)");let r=`${String(t).replace(/\/+$/,"")}/memory/sync-credentials`,l=await s(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`},body:JSON.stringify({projectId:n})});if(!l.ok){let y=await l.text().catch(()=>"");throw new Error(`memory-sync credentials request failed (${l.status}): ${y||"no body"}`)}let i=await l.json();if(!i?.accessKeyId||!i?.secretAccessKey||!i?.sessionToken)throw new Error("memory-sync credentials response missing required fields");return eo(e,{accessKeyId:i.accessKeyId,secretAccessKey:i.secretAccessKey,sessionToken:i.sessionToken,expiration:i.expiration||null,refreshedAt:new Date().toISOString()}),z(e)}async function ro({cwd:e,apiUrl:n,sessionToken:t,fetch:c}){let s=C(e);if(!s)return null;let r=z(e);return(!r||no(r))&&(r=await to({cwd:e,projectId:s.projectId,apiUrl:n,sessionToken:t,fetch:c})),r}async function vo({cwd:e,apiUrl:n,sessionToken:t,fetch:c}){let s=await ro({cwd:e,apiUrl:n,sessionToken:t,fetch:c});return s?{AWS_ACCESS_KEY_ID:s.accessKeyId,AWS_SECRET_ACCESS_KEY:s.secretAccessKey,AWS_SESSION_TOKEN:s.sessionToken,AWS_REGION:process.env.AWS_REGION||"ap-southeast-2"}:null}var $o,xo,oo,Uo,k=_(()=>{$o="memory-sync.json",xo="memory-sync-creds.json",oo=120*1e3;Uo={paths:b,readCreds:z,writeCreds:eo,isExpiringSoon:no,REFRESH_HEADROOM_MS:oo}});import o from"chalk";var Ro=`
|
|
2
|
+
Install @zibby/ui-memory and Dolt to enable test memory:
|
|
3
3
|
|
|
4
|
-
npm install @zibby/memory # add the package
|
|
4
|
+
npm install @zibby/ui-memory # add the package
|
|
5
5
|
brew install dolt # macOS
|
|
6
6
|
# or: curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash
|
|
7
|
-
`;async function
|
|
8
|
-
@zibby/memory is not installed.
|
|
9
|
-
`)),console.log(o.white(
|
|
7
|
+
`;async function m(){try{return await import("@zibby/ui-memory")}catch{return console.log(o.yellow(`
|
|
8
|
+
@zibby/ui-memory is not installed.
|
|
9
|
+
`)),console.log(o.white(Ro)),null}}async function To(){let e=await m();if(!e)return;let n=process.cwd(),t=e.getStats(n);if(!t.available){console.log(o.red(`
|
|
10
10
|
Dolt is not installed.
|
|
11
11
|
`)),console.log(o.white(" Install Dolt to enable test memory:")),console.log(o.gray(" brew install dolt # macOS")),console.log(o.gray(` curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash # Linux
|
|
12
|
-
`));return}if(!
|
|
12
|
+
`));return}if(!t.initialized){console.log(o.yellow(`
|
|
13
13
|
Memory database not initialized.
|
|
14
14
|
`)),console.log(o.white(" Run `zibby init` or `zibby memory init` to set it up.\n"));return}console.log(o.bold.cyan(`
|
|
15
15
|
Zibby Test Memory
|
|
16
|
-
`)),console.log(o.gray(` Dolt: ${
|
|
17
|
-
${
|
|
18
|
-
${
|
|
19
|
-
${
|
|
20
|
-
`).filter(
|
|
16
|
+
`)),console.log(o.gray(` Dolt: ${t.doltVersion}`));let c=o.gray(` ${"\u2500".repeat(40)}`);console.log(c);let s=t.counts;if(console.log(o.white(` Test runs: ${o.cyan(s.runs)} (${o.green(`${s.passed} passed`)}, ${s.failed>0?o.red(`${s.failed} failed`):o.gray(`${s.failed} failed`)})`)),console.log(o.white(` Selectors: ${o.cyan(s.selectors)} tracked`)),console.log(o.white(` Pages: ${o.cyan(s.pages)} discovered`)),console.log(o.white(` Transitions: ${o.cyan(s.transitions)} mapped`)),console.log(o.white(` Insights: ${o.cyan(s.insights||0)} saved`)),t.recentRuns.length>0){console.log(`
|
|
17
|
+
${c}`),console.log(o.white(" Recent runs:"));for(let r of t.recentRuns){let l=r.passed?o.green("\u2713"):o.red("\u2717"),i=r.duration_ms?o.gray(`${(r.duration_ms/1e3).toFixed(1)}s`):"";console.log(` ${l} ${o.white(r.spec_path)} ${i}`)}}if(t.topSelectors.length>0){console.log(`
|
|
18
|
+
${c}`),console.log(o.white(" Top selectors:"));for(let r of t.topSelectors){let l=r.success_count+r.failure_count,i=Math.round(r.success_count/l*100);console.log(` ${o.cyan(r.stable_id||"?")} \u2192 ${r.element_desc} (${i}%, ${l} uses)`)}}if(t.log){console.log(`
|
|
19
|
+
${c}`),console.log(o.white(" Recent commits:"));let r=t.log.split(`
|
|
20
|
+
`).filter(l=>l.startsWith("commit")||l.trim().startsWith("run ")).slice(0,10);for(let l of r)console.log(o.gray(` ${l.trim()}`))}console.log("")}async function Do(e){let n=await m();if(!n)return;let t=process.cwd();if(!e.force){console.log(o.yellow(`
|
|
21
21
|
This will permanently delete the memory database.
|
|
22
22
|
`)),console.log(o.white(` Run with --force to confirm: zibby memory reset --force
|
|
23
|
-
`));return}let
|
|
23
|
+
`));return}let c=n.resetMemory(t);console.log(c?o.green(`
|
|
24
24
|
Memory database reset.
|
|
25
25
|
`):o.gray(`
|
|
26
26
|
No memory database found.
|
|
27
|
-
`))}async function
|
|
27
|
+
`))}async function Bo(e){let n=await m();if(!n)return;let t=process.cwd(),c=n.getStats(t);if(!c.initialized){console.log(o.yellow(`
|
|
28
28
|
Memory database not initialized.
|
|
29
|
-
`));return}let
|
|
30
|
-
Compacting memory (keep last ${
|
|
29
|
+
`));return}let s=e.maxRuns||50,r=e.maxAge||90;console.log(o.white(`
|
|
30
|
+
Compacting memory (keep last ${s} runs/spec, prune data older than ${r}d)...`));let l=c.counts;if(n.compactMemory(t,{maxRuns:s,maxAgeDays:r}).pruned){let y=n.getStats(t).counts,u=g=>l[g]-y[g];console.log(o.green(" Done.")),u("runs")>0&&console.log(o.gray(` Pruned ${u("runs")} old runs`)),u("selectors")>0&&console.log(o.gray(` Pruned ${u("selectors")} stale selectors`)),u("insights")>0&&console.log(o.gray(` Pruned ${u("insights")} old insights`)),u("transitions")>0&&console.log(o.gray(` Pruned ${u("transitions")} stale transitions`)),console.log(o.gray(` Dolt GC completed
|
|
31
31
|
`))}else console.log(o.gray(` Nothing to compact.
|
|
32
|
-
`))}async function
|
|
32
|
+
`))}async function Lo(){let e=await m();if(!e)return;let n=process.cwd(),t=e.getCostStats(n);if(!t){console.log(o.yellow(`
|
|
33
|
+
Memory database not initialized.
|
|
34
|
+
`)),console.log(o.white(" Run `zibby memory init` first.\n"));return}if(t.available===!1){console.log(o.yellow(`
|
|
35
|
+
No usage data yet${t.reason?` (${t.reason})`:""}.
|
|
36
|
+
`)),console.log(o.gray(" Run `zibby test <spec>` once to populate. Token counts come from")),console.log(o.gray(` the LLM SDK and are written to .zibby/output/sessions/<id>/execute_live/usage.json.
|
|
37
|
+
`));return}console.log(o.bold.cyan(`
|
|
38
|
+
Zibby \u2014 LLM Cost Report
|
|
39
|
+
`));let c=o.gray(` ${"\u2500".repeat(60)}`),s=t.totals;if(console.log(c),console.log(o.white(` Runs with usage data: ${o.cyan(s.runs)}`)),console.log(o.white(` Total input tokens: ${o.cyan(h(s.input))}`)),console.log(o.white(` Total output tokens: ${o.cyan(h(s.output))}`)),console.log(o.white(` Total cache reads: ${o.cyan(h(s.cache_read))} ${o.gray("(billed at ~10% of normal input rate)")}`)),console.log(o.white(` Total cache creation: ${o.cyan(h(s.cache_creation))} ${o.gray("(billed at ~125% of normal input rate)")}`)),t.by_domain.length>0){console.log(`
|
|
40
|
+
${c}`),console.log(o.white(" By domain:"));for(let r of t.by_domain.slice(0,10)){let l=r.runs>0?Math.round((r.input+r.output)/r.runs):0;console.log(` ${o.cyan(r.domain.padEnd(30))} ${o.gray(`${r.runs} runs \xB7 ~${h(l)}/run avg`)}`)}}if(t.by_spec.length>0){console.log(`
|
|
41
|
+
${c}`),console.log(o.white(" By spec:"));for(let r of t.by_spec.slice(0,10)){let l=r.runs>0?Math.round((r.input+r.output)/r.runs):0;console.log(` ${o.cyan(String(r.spec_path).padEnd(40))} ${o.gray(`${r.runs} runs \xB7 ~${h(l)}/run avg`)}`)}}if(t.recent.length>0){console.log(`
|
|
42
|
+
${c}`),console.log(o.white(" Last 10 runs:"));for(let r of t.recent.slice(0,10)){let l=r.passed?o.green("\u2713"):o.red("\u2717"),i=(r.input_tokens||0)+(r.output_tokens||0),y=(r.cache_read_tokens||0)>0?o.gray(` \xB7 cache read ${h(r.cache_read_tokens)}`):"";console.log(` ${l} ${o.gray(r.run_at.slice(0,16))} ${o.cyan(h(i).padStart(8))} ${o.white(r.spec_path||"")}${y}`)}}console.log("")}function h(e){return e==null?"\u2014":e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}K`:`${(e/1e6).toFixed(2)}M`}async function Oo(e,n={}){let t=await m();if(!t)return;e||(console.log(o.red(`
|
|
43
|
+
Usage: zibby memory remote add <url> [--name origin]
|
|
44
|
+
`)),console.log(o.gray(" Supported: aws:// gs:// https:// file:///")),console.log(o.gray(" Example: zibby memory remote add aws://team-bucket/zibby/shop-prod")),console.log(""),process.exit(1));let c=process.cwd(),s=n.name||"origin";if(!t.memoryRemoteAdd(c,e,s)){console.log(o.red("\n Failed to add remote. Is the memory DB initialized? Run `zibby memory init` first.\n"));return}console.log(""),console.log(o.green(` \u2713 Added remote ${o.bold(s)} \u2192 ${e}`)),console.log(o.gray(" Next step: zibby memory pull (or just run any test \u2014 middleware auto-pulls/pushes)")),console.log("")}async function jo(){let e=await m();if(!e)return;let n=e.memoryRemoteInfo(process.cwd());if(console.log(""),!n){console.log(o.yellow(` No memory remote configured.
|
|
45
|
+
`)),console.log(o.gray(" Set one with: zibby memory remote add <url>")),console.log(o.gray(` Without a remote, memory is local-only \u2014 team members won't see each other's learnings.
|
|
46
|
+
`));return}console.log(o.bold.cyan(" Memory remote")),console.log(` ${o.cyan(n.name||"origin")}: ${n.url||"(unknown)"}`),console.log("")}async function Mo(e="origin"){let n=await m();if(!n)return;let t=n.memoryRemoteRemove(process.cwd(),e);console.log(""),t?(console.log(o.green(` \u2713 Removed remote ${e}.`)),console.log(o.gray(" Memory is now local-only."))):console.log(o.gray(` No remote named ${e} to remove.`)),console.log("")}async function Fo(){let e=await m();if(!e)return;console.log(o.cyan(`
|
|
47
|
+
Pulling team memory from remote...`));let n=e.memorySyncPull(process.cwd());n.pulled?console.log(o.green(` \u2713 Pulled latest. Local memory now reflects the team's shared knowledge.
|
|
48
|
+
`)):(console.log(o.yellow(` \u26A0 Pull skipped \u2014 ${n.error||"unknown reason"}.`)),console.log(o.gray(" Did you run `zibby memory remote add <url>` first?\n")))}async function Yo(e={}){let n=await m();if(!n)return;let{join:t}=await import("path"),{existsSync:c}=await import("fs"),s=e.cwd||process.cwd(),r=e.projectId;if(!r){let p=t(s,".zibby.config.mjs");if(c(p))try{let $=(await import(`file://${p}?t=${Date.now()}`)).default;r=$?.projectId||$?.project?.id}catch{}}r||(console.log(o.red(`
|
|
49
|
+
Could not determine projectId.
|
|
50
|
+
`)),console.log(o.gray(" Either run this from a project dir with `.zibby.config.mjs`")),console.log(o.gray(` containing { projectId: "..." }, or pass --project-id <id>.
|
|
51
|
+
`)),process.exit(1));let{getApiUrl:l}=await Promise.resolve().then(()=>(E(),P)),{getSessionToken:i}=await Promise.resolve().then(()=>(q(),J)),y=l(),u=i();u||(console.log(o.red("\n Not logged in. Run `zibby login` first.\n")),console.log(o.gray(" Hosted memory-sync is for signed-in users only \u2014")),console.log(o.gray(` the backend needs your identity to scope per-tenant credentials.
|
|
52
|
+
`)),process.exit(1)),console.log(o.cyan(`
|
|
53
|
+
Configuring hosted memory-sync...`));let g;try{let p=`${y.replace(/\/+$/,"")}/memory/sync-config?projectId=${encodeURIComponent(r)}`,w=await fetch(p,{headers:{Authorization:`Bearer ${u}`}});if(!w.ok){let $=await w.text().catch(()=>"");throw new Error(`backend returned ${w.status}: ${$||"no body"}`)}g=await w.json()}catch(p){console.log(o.red(`
|
|
54
|
+
Failed: ${p.message}
|
|
55
|
+
`)),process.exit(1)}let{writeConfig:so}=await Promise.resolve().then(()=>(k(),A));so(s,{projectId:r,bucket:g.bucket,prefix:g.prefix,doltUrl:g.doltUrl}),n.memoryRemoteAdd(s,g.doltUrl)||(console.log(o.yellow(`
|
|
56
|
+
Saved hosted-sync config, but failed to register Dolt remote.`)),console.log(o.gray(" Try `zibby memory init` first (the local Dolt DB must exist).\n")),process.exit(1));let{refreshCredentials:co}=await Promise.resolve().then(()=>(k(),A));try{await co({cwd:s,projectId:r,apiUrl:y,sessionToken:u})}catch(p){console.log(o.yellow(`
|
|
57
|
+
Config saved, but initial credential fetch failed: ${p.message}`)),console.log(o.gray(` Will retry on first push/pull.
|
|
58
|
+
`))}console.log(""),console.log(o.green(" \u2713 Hosted memory-sync configured.")),console.log(o.gray(` Bucket: ${g.bucket}`)),console.log(o.gray(` Prefix: ${g.prefix} \u2190 your tenant slot`)),console.log(o.gray(` Dolt: ${g.doltUrl}`)),console.log(""),console.log(o.gray(" Every test run will auto-pull/push. Creds refresh automatically.")),console.log(o.gray(" To revert to local-only: zibby memory remote remove origin")),console.log("")}async function Zo(){let e=await m();if(!e)return;console.log(o.cyan(`
|
|
59
|
+
Pushing local memory to team remote...`));let n=e.memorySyncPush(process.cwd());n.pushed?console.log(o.green(" \u2713 Pushed. Team can now `zibby memory pull` to see your run's learnings.\n")):console.log(o.yellow(` \u26A0 Push skipped \u2014 ${n.error||"unknown reason"}.
|
|
60
|
+
`))}async function Ko(){let e=await m();if(!e)return;let n=process.cwd();if(!e.DoltDB.isAvailable()){console.log(o.red(`
|
|
33
61
|
Dolt is not installed.
|
|
34
62
|
`)),console.log(o.white(" Install Dolt:")),console.log(o.gray(" brew install dolt # macOS")),console.log(o.gray(` curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash # Linux
|
|
35
|
-
`));return}let{created:
|
|
63
|
+
`));return}let{created:t,available:c}=e.initMemory(n);t?console.log(o.green(`
|
|
36
64
|
Memory database initialized at .zibby/memory/
|
|
37
|
-
`)):
|
|
65
|
+
`)):c&&console.log(o.gray(`
|
|
38
66
|
Memory database already initialized.
|
|
39
|
-
`))}export{
|
|
67
|
+
`))}export{Bo as memoryCompactCommand,Lo as memoryCostCommand,Ko as memoryInitCommand,Fo as memoryPullCommand,Zo as memoryPushCommand,Oo as memoryRemoteAddCommand,jo as memoryRemoteInfoCommand,Mo as memoryRemoteRemoveCommand,Yo as memoryRemoteUseHostedCommand,Do as memoryResetCommand,To as memoryStatsCommand};
|
package/dist/commands/run.js
CHANGED
|
@@ -1,78 +1,75 @@
|
|
|
1
|
-
var
|
|
2
|
-
`,"utf8")}function
|
|
3
|
-
`,"utf8")}import{readFileSync as
|
|
1
|
+
var De=Object.defineProperty;var je=(t,o)=>()=>(t&&(o=t(t=0)),o);var Ye=(t,o)=>{for(var s in o)De(t,s,{get:o[s],enumerable:!0})};var xe={};Ye(xe,{_resetLoaderCacheForTests:()=>lo,loadCredentialsIntoEnv:()=>co});import Pe from"node:fs";import to from"node:path";import no from"node:os";async function Ee(){if(!(process.env.__ZIBBY_CLAUDE_PLAN||process.platform!=="darwin"||!(process.env.CLAUDE_CODE_OAUTH_TOKEN||process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL||process.env.ANTHROPIC_AUTH_TOKEN)))try{let{execSync:o}=await import("node:child_process"),s=o('security find-generic-password -s "Claude Code-credentials" -w',{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(s){let i=JSON.parse(s)?.claudeAiOauth?.subscriptionType;i&&(process.env.__ZIBBY_CLAUDE_PLAN=i)}}catch{}}function io(t){try{if(!Pe.existsSync(t))return{};let o=Pe.readFileSync(t,"utf-8"),s=JSON.parse(o);return s&&s.agentKeys&&typeof s.agentKeys=="object"?s.agentKeys:{}}catch{return{}}}async function co(t={}){let{verbose:o=!1,force:s=!1,configPath:l}=t;if(q&&!s)return G;if(!!(process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL||process.env.ANTHROPIC_API_KEY_POOL||process.env.CLAUDE_CODE_OAUTH_TOKEN||process.env.ANTHROPIC_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN))return await Ee(),q=!0,G={oauthCount:0,apiCount:0,source:"cloud-env"},o&&console.log("[credentials-loader] env vars already set \u2014 skipping local discovery"),G;let a=l||to.join(no.homedir(),".zibby","config.json"),n=io(a),y="none",d=0,m=0;for(let h of so)n[h]&&!process.env[h]&&(process.env[h]=String(n[h]).trim(),y="config.json",h.endsWith("_POOL")?d+=String(n[h]).split(",").filter(D=>D.trim()).length:d+=1);for(let h of ro)n[h]&&!process.env[h]&&(process.env[h]=String(n[h]).trim(),y="config.json",h.endsWith("_POOL")?m+=String(n[h]).split(",").filter(D=>D.trim()).length:m+=1);return await Ee(),q=!0,G={oauthCount:d,apiCount:m,source:y},o&&d+m>0&&console.log(`[credentials-loader] loaded ${d} OAuth + ${m} API from ${y} (~/.zibby/config.json)`),G}function lo(){q=!1,G=null}var q,G,so,ro,be=je(()=>{q=!1,G=null,so=["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN_POOL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_AUTH_TOKEN_POOL"],ro=["ANTHROPIC_API_KEY","ANTHROPIC_API_KEY_POOL"]});import{runTest as ao,logger as U,DEFAULT_OUTPUT_BASE as uo,SESSIONS_DIR as po}from"@zibby/core";import{zibbyScratchSpecsDir as ae}from"@zibby/core/constants/zibby-scratch.js";import{createCliRunIndexPipelineProgressAppender as fo,postCliInterruptedRunIndex as Oe}from"@zibby/core/utils/run-index-post-cli.js";import{createWriteStream as Ke,mkdirSync as Fe}from"fs";import{join as pe,isAbsolute as ze}from"path";var Ge="studio-cli.log";function He(t,o){if(!t||typeof t!="string")return null;let s=t.trim();return s?ze(s)?s:pe(o,s):null}function Ze(t){if(!t)return()=>{};Fe(t,{recursive:!0});let o=pe(t,Ge),s=Ke(o,{flags:"a"}),l=process.stdout.write.bind(process.stdout),i=process.stderr.write.bind(process.stderr),a=n=>function(d,m,h){typeof m=="function"&&(h=m,m=void 0);try{Buffer.isBuffer(d)?s.write(d):s.write(String(d),m||"utf8")}catch{}return n(d,m,h)};return process.stdout.write=a(l),process.stderr.write=a(i),()=>{process.stdout.write=l,process.stderr.write=i;try{s.end()}catch{}}}function oe(t,o,s){let l=null;function i(a){if(!l&&a?.sessionPath){let n=He(a.sessionPath,o);n&&(l=Ze(n))}typeof t=="function"&&t(a)}return i.dispose=()=>{typeof l=="function"&&(l(),l=null)},i}import{existsSync as fe,mkdirSync as Me,readFileSync as Ve,readdirSync as Lo,unlinkSync as We,writeFileSync as ge}from"fs";import{join as he}from"path";import{execSync as Yo}from"child_process";import{DEFAULT_OUTPUT_BASE as Je}from"@zibby/core";function ye(t){return t?.paths?.output||Je}function te(t,o,s){return he(t,o,`.zibby-chat-run-pids-${s}.json`)}function me(t,o,s){let l=te(t,o,s);if(!fe(l))return[];try{let i=JSON.parse(Ve(l,"utf8"));return(Array.isArray(i?.pids)?i.pids:[]).map(n=>Number(n)).filter(n=>Number.isFinite(n)&&n>0)}catch{return[]}}function Ie(t,o,s,l={}){let i=Number(o),a=Number(s);if(!Number.isFinite(i)||i<=0||!Number.isFinite(a)||a<=0)return;let n=ye(l),y=he(t,n);Me(y,{recursive:!0});let d=me(t,n,i);d.includes(a)||d.push(a),ge(te(t,n,i),`${JSON.stringify({v:1,pids:d})}
|
|
2
|
+
`,"utf8")}function _e(t,o,s,l={}){let i=Number(o),a=Number(s);if(!Number.isFinite(i)||i<=0||!Number.isFinite(a)||a<=0)return;let n=ye(l),y=te(t,n,i);if(!fe(y))return;let d=me(t,n,i).filter(m=>m!==a);if(d.length===0)try{We(y)}catch{}else ge(y,`${JSON.stringify({v:1,pids:d})}
|
|
3
|
+
`,"utf8")}import{readFileSync as O,existsSync as w,statSync as Te,mkdirSync as Ue,writeFileSync as Se,appendFileSync as go,rmSync as $e}from"fs";import{resolve as B,join as $,dirname as ho,isAbsolute as Ne}from"path";import{fileURLToPath as yo}from"url";import{glob as X}from"glob";import e from"chalk";import Be from"ora";import mo from"dotenv";import Io from"open";var b={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"}};function W(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";b[o]?t=b[o].apiUrl:t=b.prod.apiUrl}try{let o=new URL(t);return o.protocol!=="http:"&&o.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${o.protocol} (only http/https allowed)`),b.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),b.prod.apiUrl}}function we(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let t=process.env.ZIBBY_ENV||"prod";return(b[t]||b.prod).accountApiUrl}function ne(){let t=process.env.ZIBBY_ENV||"prod";return b[t]||b.prod}function se(){let t;if(process.env.ZIBBY_FRONTEND_URL)t=process.env.ZIBBY_FRONTEND_URL;else{let o=process.env.ZIBBY_ENV||"prod";b[o]?t=b[o].frontendUrl:t=b.prod.frontendUrl}try{let o=new URL(t);if(o.protocol!=="http:"&&o.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${o.protocol} (only http/https allowed)`),b.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let l=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],i=o.hostname;if(!l.some(n=>i===n||i.endsWith(`.${n}`))&&!i.includes("localhost")&&i!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${i}`),"https://studio.zibby.dev"}return t}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${t}`),b.local.frontendUrl}}import{existsSync as qe,mkdirSync as Ho,readFileSync as Xe,writeFileSync as Zo}from"fs";import{homedir as ve}from"os";import{join as J}from"path";function Qe(){return process.env.ZIBBY_CONFIG_DIR||J(ve(),".zibby")}function eo(){return J(Qe(),"config.json")}var oo=J(ve(),".zibby"),Wo=J(oo,"config.json");function Ae(){try{let t=eo();if(qe(t)){let o=Xe(t,"utf-8");return JSON.parse(o)}}catch{}return{}}function re(){return Ae().sessionToken||null}function ie(){return Ae().user||null}var _o=yo(import.meta.url),wo=ho(_o),vo=JSON.parse(O($(wo,"../../package.json"),"utf-8"));function Ao(t){let o=s=>s?typeof s.message=="string"&&s.message.includes("Interrupted by user")?!0:Array.isArray(s.errors)?s.errors.some(o):s.cause?o(s.cause):!1:!1;return o(t)}function Ce(t,o){if(t==null)return null;let s=String(t).trim();return s?Ne(s)?s:B(o,s):null}function Po(t,o){try{if(!t||!w(t))return;let s=$(t,"studio-cli.log"),l=`
|
|
4
4
|
[CLI_FATAL] ${new Date().toISOString()}
|
|
5
5
|
Error: ${String(o?.message||o)}
|
|
6
6
|
${o?.stack?`${String(o.stack)}
|
|
7
|
-
`:""}`;
|
|
7
|
+
`:""}`;go(s,l,"utf8")}catch{}}process.env.DOTENV_CONFIG_QUIET="true";var Eo=process.env.NODE_ENV||"development",xo=[B(process.cwd(),".env.local"),B(process.cwd(),`.env.${Eo}`),B(process.cwd(),".env")];xo.forEach(t=>{w(t)&&mo.config({path:t,override:!1})});function bo(t,o){let s=o?.paths?.specs||"test-specs",l=o?.paths?.generated||"tests";return t.replace(s,l).replace(/\.txt$/,".spec.js")}async function Oo(t,o){let s=se(),l=/^[0-9A-HJKMNP-TV-Z]{26}$/,i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(!l.test(t)&&!i.test(t))return console.log(e.red(`
|
|
8
8
|
\u274C Invalid execution ID format (security check)
|
|
9
|
-
`)),!1;if(!
|
|
9
|
+
`)),!1;if(!i.test(o))return console.log(e.red(`
|
|
10
10
|
\u274C Invalid project ID format (security check)
|
|
11
|
-
`)),!1;let
|
|
11
|
+
`)),!1;let a=new URL(s);if(!s.includes("localhost")&&!s.includes("127.0.0.1")&&a.protocol!=="https:")return console.log(e.red(`
|
|
12
12
|
\u274C Frontend URL must use HTTPS in production
|
|
13
|
-
`)),!1;let
|
|
14
|
-
Opening test results in browser...`)),console.log(e.gray(` ${
|
|
15
|
-
`)),await
|
|
16
|
-
`)),!1}}function ce(t,o){let s=o?.paths?.specs||"test-specs",
|
|
17
|
-
${
|
|
13
|
+
`)),!1;let y=`${s}/projects/${o}/runs/${t}`;try{return console.log(e.cyan(`
|
|
14
|
+
Opening test results in browser...`)),console.log(e.gray(` ${y}
|
|
15
|
+
`)),await Io(y),!0}catch{return console.log(e.yellow("Could not open browser automatically")),console.log(e.gray(` Please open manually: ${y}
|
|
16
|
+
`)),!1}}function ce(t,o){let s=o?.paths?.specs||"test-specs",l=o?.paths?.generated||"tests";return t.replace(l,s).replace(/\.spec\.js$/,".txt")}async function To({apiKey:t,specPath:o,fullSpecPath:s,collectionIdOrName:l,folder:i,agent:a,config:n,result:y,shouldOpen:d}){let m=W(),h=ne(),D=process.env.ZIBBY_USER_TOKEN||re(),k=ie();console.log(k?e.gray(`Authenticated: ${k.email} (${k.name||"User"})`):e.gray("Authenticated: Using Personal Access Token"));let v=Be(`Uploading to ${h.name}...`).start();try{let f=process.cwd(),T=null;if(y?.state?.sessionPath){let c=y.state.sessionPath;T=c.startsWith(f)?c.slice(f.length+1):c}if(!T){let g=`${n.paths?.output||uo}/${po}/*`,N=X.sync(g,{cwd:f}).filter(C=>Te($(f,C)).isDirectory()&&!/session_/.test(C)).map(C=>({path:C,stat:Te($(f,C))})).sort((C,de)=>de.stat.mtimeMs-C.stat.mtimeMs);if(N.length===0){v.warn("No session folder found, skipping upload");return}T=N[0].path}let S=X.sync(`${T}/execute_live/videos/*.webm`,{cwd:f});S.length===0&&(S=X.sync(`${T}/execute_live/*.webm`,{cwd:f})),S.length===0&&(S=X.sync(`${T}/*.webm`,{cwd:f}));let L=$(f,T,"execute_live","events.json"),K=$(f,T,"execute_live","result.json"),Y=$(f,T,"title.txt"),M=bo(o,n),r=$(f,M),u=w(r);if(S.length===0){v.warn("No video file found in session folder, skipping upload");return}let I=$(f,S[0]),E=w(Y)?O(Y,"utf-8").trim():null;U.debug(`Video exists: ${w(I)}`),U.debug(`Events exists: ${w(L)}`);let A=null,j=null;if(l){v.text="Resolving collection...";let c=we(),g=await fetch(`${c}/collections/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({collectionIdOrName:l})});if(!g.ok){let C=await g.json().catch(()=>({}));throw new Error(C.error||"Failed to resolve collection")}let N=await g.json();A=N.collectionId,j=N.collectionName,N.isNew&&(v.text=`Created new collection: ${j}`)}v.text="Preparing upload...";let _={video:w(I)?O(I).length:0,events:w(L)?O(L).length:0,instructions:(()=>{let c=ce(o,n),g=$(f,c);return w(g)?O(g).length:0})(),result:w(K)?O(K).length:0},x=_.video+_.events+_.instructions+_.result,V=(x/1024/1024).toFixed(2);if(_.video>50*1024*1024)throw new Error(`Video file too large: ${(_.video/1024/1024).toFixed(2)}MB (max: 50MB)`);if(x>60*1024*1024)throw new Error(`Total upload size too large: ${V}MB (max: 60MB)`);v.text=`Getting upload URLs... (${V}MB)`;let p={"Content-Type":"application/json",Authorization:`Bearer ${t}`};D&&(p["X-User-Token"]=D);let P=typeof a=="object"?a.provider:a||"cursor",H=typeof a=="object"&&a[P]?.model||null,Re=H==="auto"?null:H,Z=await fetch(`${m}/executions/upload`,{method:"POST",headers:p,body:JSON.stringify({collectionId:A||null,specPath:o,specContent:(()=>{let c=ce(o,n),g=$(f,c);return w(g)?O(g,"utf-8"):w(s)?O(s,"utf-8"):""})(),title:E||null,agentType:P,model:Re,metadata:{agent:a||"cursor",timestamp:new Date().toISOString(),folder:i||null,collectionName:j||null},fileSizes:_})});if(!Z.ok){let c=await Z.json();if(Z.status===413)throw c.details&&Array.isArray(c.details)?new Error(`File size limit exceeded:
|
|
17
|
+
${c.details.map(g=>` \u2022 ${g}`).join(`
|
|
18
18
|
`)}
|
|
19
19
|
|
|
20
|
-
Compress your files or reduce recording quality.`):new Error(
|
|
21
|
-
Plan: ${
|
|
22
|
-
Upgrade at: https://studio.zibby.dev/billing`);if(
|
|
23
|
-
Current usage: ${
|
|
24
|
-
This upload: ${
|
|
25
|
-
Plan: ${
|
|
26
|
-
Upgrade at: https://studio.zibby.dev/billing`)}}throw new Error(
|
|
27
|
-
${"\u2501".repeat(50)}`)),console.log(e.white(`Execution ID: ${e.cyan(
|
|
28
|
-
`)),{success:!0,executionId:
|
|
29
|
-
`)),{success:!1}}}async function
|
|
20
|
+
Compress your files or reduce recording quality.`):new Error(c.error||"Upload files too large");if(Z.status===429){if(c.quotaInfo)throw new Error(`Video verification quota exceeded (${c.quotaInfo.used}/${c.quotaInfo.limit}).
|
|
21
|
+
Plan: ${c.quotaInfo.planId}. Resets: ${new Date(c.quotaInfo.periodEnd).toLocaleDateString()}
|
|
22
|
+
Upgrade at: https://studio.zibby.dev/billing`);if(c.storageInfo){let g=(c.storageInfo.used/1073741824).toFixed(2),N=(c.storageInfo.limit/(1024*1024*1024)).toFixed(2),C=(c.storageInfo.uploadSize/(1024*1024)).toFixed(2);throw new Error(`Storage quota would be exceeded.
|
|
23
|
+
Current usage: ${g}GB / ${N}GB
|
|
24
|
+
This upload: ${C}MB
|
|
25
|
+
Plan: ${c.storageInfo.planId}
|
|
26
|
+
Upgrade at: https://studio.zibby.dev/billing`)}}throw new Error(c.error||"Failed to initiate upload")}let{executionId:F,uploadUrls:R,isOrphan:ke,projectId:Q}=await Z.json();v.text=`Uploading video... (${F})`;let ee=O(I);U.debug(`Video buffer size: ${ee.length} bytes`),U.debug("Upload URL received (redacted)");let z=await fetch(R.video,{method:"PUT",body:ee,headers:{"Content-Type":"video/webm","Content-Length":ee.length.toString()}});if(U.debug(`Video upload status: ${z.status} ${z.statusText}`),!z.ok){let c=await z.text();throw new Error(`Failed to upload video: ${z.status} ${z.statusText} - ${c}`)}if(U.info("Video uploaded successfully"),w(L)&&R.events){v.text="Uploading events...";let c=O(L),g=await fetch(R.events,{method:"PUT",body:c,headers:{"Content-Type":"application/json","Content-Length":c.length.toString()}});if(U.debug(`Events upload status: ${g.status} ${g.statusText}`),!g.ok)throw new Error("Failed to upload events");U.info("Events uploaded successfully")}else U.debug(`Skipping events upload - exists: ${w(L)}, hasUrl: ${!!R.events}`);if(u&&R.generatedTest){v.text="Uploading generated test...";let c=O(r);if(!(await fetch(R.generatedTest,{method:"PUT",body:c,headers:{"Content-Type":"application/javascript","Content-Length":c.length.toString()}})).ok)throw new Error("Failed to upload generated test")}if(R.testInstructions){let c=ce(o,n),g=$(f,c);if(w(g)){v.text="Uploading test instructions...";let N=O(g);(await fetch(R.testInstructions,{method:"PUT",body:N,headers:{"Content-Type":"text/plain","Content-Length":N.length.toString()}})).ok?U.debug("Test instructions uploaded successfully"):U.warn("Failed to upload test instructions (non-blocking)")}else console.log(`\u2139\uFE0F No source test instructions found at ${c}`)}if(R.result&&w(K)){v.text="Uploading test results...";let c=O(K);(await fetch(R.result,{method:"PUT",body:c,headers:{"Content-Type":"application/json","Content-Length":c.length.toString()}})).ok?U.debug("result.json uploaded successfully"):U.warn("Failed to upload result.json (non-blocking)")}if(v.text="Confirming upload...",!(await fetch(`${m}/executions/${F}/confirm`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({status:"completed",metadata:{uploadedAt:new Date().toISOString()},fileSizes:_})})).ok)throw new Error("Failed to confirm upload");v.succeed("Uploaded to Zibby Cloud!"),console.log(e.gray(`
|
|
27
|
+
${"\u2501".repeat(50)}`)),console.log(e.white(`Execution ID: ${e.cyan(F)}`));let ue=se();console.log(ke?e.white(`Location: ${e.yellow("History tab")}`):e.white(`Collection: ${e.cyan(A)}`));let Le=Q?`${ue}/projects/${Q}/runs/${F}`:`${ue}/history?execution=${F}`;return console.log(e.white(`View execution: ${e.cyan(Le)}`)),console.log(e.gray(`${"\u2501".repeat(50)}
|
|
28
|
+
`)),{success:!0,executionId:F,projectId:Q||null}}catch(f){return v.fail("Upload failed"),console.log(e.red(` ${f.message}`)),process.env.DEBUG&&console.log(e.gray(` Stack: ${f.stack}`)),console.log(e.gray(` Continuing without upload...
|
|
29
|
+
`)),{success:!1}}}async function Uo(t,o,s){let l=W(),i=o.join(","),a=await fetch(`${l}/executions/${t}/test-cases?ids=${i}`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch test cases: ${a.status} ${a.statusText}`);return(await a.json()).testCases||[]}async function So(t,o){let s=ne();console.log(e.bold.cyan(`
|
|
30
30
|
Zibby Test Automation
|
|
31
|
-
`)),console.log(e.gray(`@zibby/cli v${
|
|
31
|
+
`)),console.log(e.gray(`@zibby/cli v${vo.version} | Node.js ${process.version}`)),console.log(e.gray("\u2501".repeat(50)));try{let{loadCredentialsIntoEnv:r}=await Promise.resolve().then(()=>(be(),xe));await r({verbose:!!process.env.ZIBBY_DEBUG})}catch{}if(o.sources){o.execution||(console.log(e.red(`
|
|
32
32
|
\u274C --execution <id> is required when using --sources
|
|
33
|
-
`)),process.exit(1));let
|
|
33
|
+
`)),process.exit(1));let r=o.project||process.env.ZIBBY_API_KEY;r||(console.log(e.red(`
|
|
34
34
|
\u274C --project <id> or ZIBBY_API_KEY required when using --sources
|
|
35
|
-
`)),process.exit(1));let
|
|
35
|
+
`)),process.exit(1));let u=o.sources.split(",").map(A=>A.trim());console.log(e.white(`Fetching ${u.length} test case(s) from execution ${e.cyan(o.execution)}...`));let I=await Uo(o.execution,u,r);I.length===0&&(console.log(e.red(`
|
|
36
36
|
No test cases found for the given IDs
|
|
37
|
-
`)),process.exit(1)),console.log(e.green(`\u2713 Fetched ${I.length} test case(s)`));let E=ae(process.cwd());
|
|
37
|
+
`)),process.exit(1)),console.log(e.green(`\u2713 Fetched ${I.length} test case(s)`));let E=ae(process.cwd());Ue(E,{recursive:!0});for(let A of I){let j=`# ${A.title}
|
|
38
38
|
|
|
39
|
-
${
|
|
40
|
-
Running: ${e.cyan(
|
|
39
|
+
${A.content}`,_=B(E,`${A.id}.txt`);Se(_,j,"utf-8"),console.log(e.gray("\u2501".repeat(50))),console.log(e.white(`
|
|
40
|
+
Running: ${e.cyan(A.title)} (${A.id})`));let x={...o,sources:void 0,execution:void 0};x.sync=!0,await So(_,x)}$e(E,{recursive:!0,force:!0});return}!t&&!o.sources&&(console.log(e.red(`
|
|
41
41
|
\u274C Missing test spec path
|
|
42
42
|
`)),console.log(e.white("Usage:")),console.log(e.gray(" zibby test test-specs/login.txt Run a spec file")),console.log(e.gray(` zibby test "login and check dashboard" Run inline spec
|
|
43
|
-
`)),process.exit(1));let
|
|
43
|
+
`)),process.exit(1));let l=t&&!t.endsWith(".txt")&&!w(B(process.cwd(),t))&&t.includes(" ");if(l){let r=ae(process.cwd());Ue(r,{recursive:!0});let u=B(r,`inline-${Date.now()}.txt`);Se(u,t,"utf-8"),t=u}let i=B(process.cwd(),t);w(i)||(console.log(e.red(`
|
|
44
44
|
\u274C Test spec not found: ${t}
|
|
45
|
-
`)),process.exit(1));let
|
|
45
|
+
`)),process.exit(1));let a=O(i,"utf-8"),n={headless:o.headless||!1,playwrightArtifacts:!0},y=B(process.cwd(),o.config);if(w(y))try{let r=await import(y),u=I=>I?.provider?I.provider:I?.gemini?"gemini":I?.codex?"codex":I?.claude?"claude":I?.cursor?"cursor":null;n={...n,...r.default,agent:r.default?.agent?{...r.default.agent,provider:o.agent||u(r.default.agent)}:{provider:o.agent||"cursor"},mcp:r.default?.browser?.mcp||"playwright",headless:o.headless!==void 0?o.headless:r.default?.browser?.headless,paths:r.default?.paths||{specs:"test-specs",generated:"tests"},cloudSync:r.default?.cloudSync||!1}}catch{console.log(e.yellow(`\u26A0\uFE0F Could not load config from ${o.config}`)),n.agent={provider:o.agent||"cursor"},n.cloudSync=!1}else n.agent={provider:o.agent||"cursor"},n.cloudSync=!1;let d=process.env.ZIBBY_API_KEY,m=o.sync||n.cloudSync===!0&&o.sync!==!1;if(o.project&&o.project.startsWith("zby_")&&(d=o.project,console.log(e.gray("Using --project as API token (overriding .env)"))),m&&!d&&(console.log(e.red(`
|
|
46
46
|
\u274C Error: Cloud sync is enabled but ZIBBY_API_KEY not set
|
|
47
47
|
`)),console.log(e.white("Cloud sync is enabled in .zibby.config.js")),console.log(e.white(`You need to set ZIBBY_API_KEY in .env file
|
|
48
48
|
`)),console.log(e.white("Option 1: Add to .env file:")),console.log(e.gray(` ZIBBY_API_KEY=zby_your_key_here
|
|
49
49
|
`)),console.log(e.white("Option 2: Disable cloud sync:")),console.log(e.gray(` Edit .zibby.config.js \u2192 cloudSync: false
|
|
50
50
|
`)),console.log(e.white(`Get your API key from: https://zibby.dev/dashboard
|
|
51
|
-
`)),process.exit(1)),
|
|
51
|
+
`)),process.exit(1)),m&&d){let r=process.env.ZIBBY_USER_TOKEN,u;r?console.log(e.gray("Using Personal Access Token from ZIBBY_USER_TOKEN")):(r=re(),u=ie(),(!r||!u)&&(console.log(e.red(`
|
|
52
52
|
\u274C Error: User authentication required for uploads
|
|
53
53
|
`)),console.log(e.gray(`Choose one of these options:
|
|
54
54
|
`)),console.log(e.cyan(" Option 1 (Local Development):")),console.log(e.gray(` zibby login
|
|
55
55
|
`)),console.log(e.cyan(" Option 2 (CI/CD):")),console.log(e.gray(" 1. Generate a Personal Access Token at:")),console.log(e.gray(" https://zibby.dev/settings/tokens")),console.log(e.gray(" 2. Set environment variable:")),console.log(e.gray(` export ZIBBY_USER_TOKEN=zby_pat_xxxxx
|
|
56
|
-
`)),process.exit(1)),
|
|
56
|
+
`)),process.exit(1)),u&&console.log(e.gray(`Authenticated: ${u.email} (${u.name||"User"})`)))}if(m&&d){let r=W();try{d.startsWith("zby_")||(console.log(e.red(`
|
|
57
57
|
\u274C Invalid API token format
|
|
58
58
|
`)),console.log(e.white('This CLI requires a project API token (starts with "zby_").')),console.log(e.gray(` Format: zby_***
|
|
59
59
|
`)),console.log(e.white(`Get your project API token from settings:
|
|
60
60
|
`)),console.log(e.gray(" Local: http://localhost:3001/settings")),console.log(e.gray(` Prod: https://studio.zibby.dev/settings
|
|
61
|
-
`)),process.exit(1));let
|
|
61
|
+
`)),process.exit(1));let u=await fetch(`${r}/projects`,{headers:{Authorization:`Bearer ${d}`}});u.ok||(console.log(e.red(`
|
|
62
62
|
\u274C Unauthorized: Invalid project API token
|
|
63
63
|
`)),console.log(e.white("Your project API token is invalid or does not have access.")),console.log(e.gray(` Token format: zby_***
|
|
64
64
|
`)),console.log(e.white(`Get your project API token from settings:
|
|
65
65
|
`)),console.log(e.gray(" Local: http://localhost:3001/settings")),console.log(e.gray(` Prod: https://studio.zibby.dev/settings
|
|
66
|
-
`)),process.exit(1));let E=(await
|
|
66
|
+
`)),process.exit(1));let E=(await u.json()).projects||[];(!E||E.length===0)&&(console.log(e.red(`
|
|
67
67
|
\u274C No projects found for this token
|
|
68
|
-
`)),process.exit(1));let
|
|
69
|
-
\u274C Failed to validate API credentials: ${
|
|
70
|
-
`)),process.exit(1)}}let
|
|
71
|
-
|
|
72
|
-
`)),console.log(e.white("
|
|
73
|
-
`)),console.log(e.white("Or add to .env file:")),console.log(e.gray(` ANTHROPIC_API_KEY=sk-ant-...
|
|
74
|
-
`)),console.log(e.white(`Get your API key from: https://console.anthropic.com/
|
|
75
|
-
`)),process.exit(1)),A==="codex"){try{let{execSync:i}=await import("child_process");i("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"})}catch{console.log(e.red(`
|
|
68
|
+
`)),process.exit(1));let A=E[0];console.log(e.green(`\u2713 Authorized for project: ${A.name} (${A.projectId})`))}catch(u){console.log(e.red(`
|
|
69
|
+
\u274C Failed to validate API credentials: ${u.message}
|
|
70
|
+
`)),process.exit(1)}}let h=typeof n.agent=="object"?n.agent.provider:n.agent;if(h==="claude"){let r=!!process.env.ANTHROPIC_API_KEY||!!process.env.ANTHROPIC_API_KEY_POOL,u=!!process.env.CLAUDE_CODE_OAUTH_TOKEN||!!process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,I=!!process.env.ANTHROPIC_AUTH_TOKEN||!!process.env.ANTHROPIC_AUTH_TOKEN_POOL;r||u||I||(console.log(e.red(`
|
|
71
|
+
Error: no Claude credentials found
|
|
72
|
+
`)),console.log(e.white("Run `zibby init` to set up credentials interactively.")),console.log(e.gray(" Pick Claude \u2192 Subscription (OAuth) or API key.")),console.log(""),console.log(e.gray("Or export ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN in your shell.")),console.log(""),process.exit(1))}if(h==="codex"){try{let{execSync:r}=await import("child_process");r("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"})}catch{console.log(e.red(`
|
|
76
73
|
\u274C Error: Codex CLI not installed
|
|
77
74
|
`)),console.log(e.white("Install the Codex CLI:")),console.log(e.gray(` npm install -g @openai/codex
|
|
78
75
|
`)),console.log(e.white("Then verify:")),console.log(e.gray(` codex --version
|
|
@@ -81,7 +78,7 @@ Running: ${e.cyan(x.title)} (${x.id})`));let b={...o,sources:void 0,execution:vo
|
|
|
81
78
|
`)),console.log(e.white("Set your API key:")),console.log(e.gray(` export OPENAI_API_KEY="sk-..."
|
|
82
79
|
`)),console.log(e.white("Or add to .env file:")),console.log(e.gray(` OPENAI_API_KEY=sk-...
|
|
83
80
|
`)),console.log(e.white(`Get your API key from: https://platform.openai.com/api-keys
|
|
84
|
-
`)),process.exit(1))}if(
|
|
81
|
+
`)),process.exit(1))}if(h==="gemini"){if(process.env.GEMINI_API_KEY&&process.env.GOOGLE_API_KEY){let r=String(process.env.GEMINI_API_KEY).trim(),u=String(process.env.GOOGLE_API_KEY).trim();r&&u&&r!==u&&(process.env.GOOGLE_API_KEY=r,console.log(e.yellow("\u26A0\uFE0F Both GOOGLE_API_KEY and GEMINI_API_KEY are set; forcing GOOGLE_API_KEY to GEMINI_API_KEY for this run.")))}try{let{execSync:r}=await import("child_process");r("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"})}catch{console.log(e.red(`
|
|
85
82
|
\u274C Error: Gemini CLI not installed
|
|
86
83
|
`)),console.log(e.white("Install the Gemini CLI:")),console.log(e.gray(` npm install -g @google/gemini-cli
|
|
87
84
|
`)),console.log(e.white("Then verify:")),console.log(e.gray(` gemini --version
|
|
@@ -90,25 +87,25 @@ Running: ${e.cyan(x.title)} (${x.id})`));let b={...o,sources:void 0,execution:vo
|
|
|
90
87
|
`)),console.log(e.white("Set your API key:")),console.log(e.gray(` export GEMINI_API_KEY="your_key_here"
|
|
91
88
|
`)),console.log(e.white("Or add to .env file:")),console.log(e.gray(` GEMINI_API_KEY=your_key_here
|
|
92
89
|
`)),console.log(e.white(`Get your API key from: https://aistudio.google.com/app/apikey
|
|
93
|
-
`)),process.exit(1))}if(
|
|
90
|
+
`)),process.exit(1))}if(h==="cursor"){let{checkCursorAgentInstalled:r,getCursorAgentInstallInstructions:u}=await import("@zibby/core");await r()||(console.log(e.red(u())),process.exit(1));let E=process.env.CI||process.env.GITLAB_CI||process.env.CIRCLECI||process.env.GITHUB_ACTIONS;process.env.CURSOR_API_KEY||(E?(console.log(e.red(`
|
|
94
91
|
\u274C Error: CURSOR_API_KEY not set
|
|
95
92
|
`)),console.log(e.white("In CI/CD, you must provide your Cursor API key:")),console.log(e.gray(` export CURSOR_API_KEY="your-cursor-token-here"
|
|
96
93
|
`)),console.log(e.white(`Get your API key from: https://cursor.com/settings
|
|
97
94
|
`)),console.log(e.white(`Add it to your CI/CD environment variables.
|
|
98
95
|
`)),process.exit(1)):console.log(e.yellow(`\u26A0\uFE0F CURSOR_API_KEY not set (using locally stored Cursor credentials)
|
|
99
|
-
`)))}console.log(e.white(`Test Spec: ${e.cyan(t)}`));let
|
|
100
|
-
${"\u2501".repeat(50)}`)),V&&
|
|
101
|
-
`)),console.log(e.cyan("Next steps:")),console.log(e.white(` 1. Review generated test: ${
|
|
102
|
-
`));else{let
|
|
103
|
-
Execution Summary:`)),console.log(e.white(` Steps: ${
|
|
104
|
-
\u{1F4DD} ${
|
|
105
|
-
\u26A0\uFE0F ${
|
|
96
|
+
`)))}console.log(e.white(`Test Spec: ${e.cyan(t)}`));let D=typeof n.agent=="object"?n.agent.provider:n.agent;console.log(e.white(`Agent: ${e.cyan(D)}`)),console.log(e.white(`Browser: ${e.cyan(n.mcp||"playwright")} ${n.headless?e.gray("(headless)"):e.gray("(headed)")}`)),n.cloudSync&&console.log(e.white(`Cloud Sync: ${e.green("enabled")}`)),o.autoApprove&&console.log(e.white(`Auto-approve: ${e.yellow("enabled (CI/CD mode)")}`)),o.collection?console.log(e.white(`Collection: ${e.cyan(o.collection)}${o.folder?` / ${o.folder}`:""}`)):console.log(e.gray("Mode: Orphan execution (History tab)"));let k;if(o.sessionPath!=null&&String(o.sessionPath).trim()!==""){let r=String(o.sessionPath).trim();k=Ne(r)?B(r):B(process.cwd(),r),console.log(e.white(`Session path: ${e.cyan(k)}`))}console.log(e.gray("\u2501".repeat(50)));let v=Be({text:"Initializing...",stream:process.stdout}).start(),f=()=>{try{Oe({cwd:process.cwd(),config:n})}catch{}},T=process.env.ZIBBY_CHAT_OWNER_PID,S=T!=null&&String(T).trim()!==""?Number(T):null,L=S!=null&&Number.isFinite(S)&&S>0,K=()=>{if(L)try{_e(process.cwd(),S,process.pid,n)}catch{}},Y=null,M=Ce(k,process.cwd());try{v.stop();let{waitUntilRunCapacity:r}=await import("@zibby/core/utils/run-capacity-coordinator.js"),{basename:u}=await import("path");await r({cwd:process.cwd(),config:n,meta:{source:process.env.ZIBBY_RUN_SOURCE||"cli",specHint:t?u(t):"",studioTestCaseId:process.env.ZIBBY_STUDIO_TEST_CASE_ID||null},log:p=>console.log(e.gray(p))});let I=await import("@zibby/core/templates/browser-test-automation/graph.mjs").catch(()=>null);if(L)try{Ie(process.cwd(),S,process.pid,n)}catch{}process.on("SIGINT",f),process.on("SIGTERM",f);let E=process.cwd(),A={},j=p=>{let P=Ce(p?.sessionPath,E);P&&(M=P)};if(typeof n.onPipelineProgress=="function"){let p=oe(n.onPipelineProgress,E,n);Y=()=>p.dispose(),A.onPipelineProgress=P=>{j(P),p({...P,specPath:t,taskDescription:a})}}else if(n.runIndex?.pipelineProgress!==!1){let p=fo({cwd:E,config:n}),P=oe(p,E,n);Y=()=>P.dispose(),A.onPipelineProgress=H=>{j(H),P({...H,specPath:t,taskDescription:a})}}let _=await ao(i,{...n,...A,specPath:t,apiKey:process.env.ANTHROPIC_API_KEY,autoApprove:o.autoApprove,force:o.autoApprove,singleNode:o.node,sessionId:o.session,...k?{sessionPath:k}:{},workflow:o.workflow,contextConfig:n.context,fallbackAgentModule:I}),x=_.outputPath||null;x&&(x=x.replace(/\/+/g,"/"),x.includes(process.cwd())&&(x=x.replace(`${process.cwd()}/`,"")));let V=_.state?.generate_script?.scriptPath||_.state?.verify_script?.success;if(console.log(e.gray(`
|
|
97
|
+
${"\u2501".repeat(50)}`)),V&&x)console.log(e.green("\u2713 Test execution completed")),console.log(e.white(`Generated test: ${e.cyan(x)}`)),_.toolCount!==void 0&&console.log(e.white(`Tools used: ${e.cyan(_.toolCount)}`)),console.log(e.gray(`${"\u2501".repeat(50)}
|
|
98
|
+
`)),console.log(e.cyan("Next steps:")),console.log(e.white(` 1. Review generated test: ${x}`)),console.log(e.white(` 2. Run with Playwright: npx playwright test ${x}`)),console.log(e.white(` 3. View report: npx playwright show-report
|
|
99
|
+
`));else{let p=_.state?.execute_live;p?p.steps?.length>0||p.actions?.length>0?(console.log(e.white(`
|
|
100
|
+
Execution Summary:`)),console.log(e.white(` Steps: ${p.steps?.length||0}`)),console.log(e.white(` Actions: ${p.actions?.length||0}`)),p.finalUrl&&console.log(e.white(` Final URL: ${p.finalUrl}`)),p.notes&&console.log(e.white(`
|
|
101
|
+
\u{1F4DD} ${p.notes}`))):(console.log(e.red("\u2716 Workflow did not complete")),console.log(e.yellow(`
|
|
102
|
+
\u26A0\uFE0F ${p.notes||"Test execution failed"}`))):console.log(e.red("\u2716 Workflow did not complete")),console.log(e.gray(`${"\u2501".repeat(50)}
|
|
106
103
|
`))}if(o.node)console.log(e.gray(`
|
|
107
104
|
Note: Upload skipped for single node execution`)),console.log(e.gray(` Run full workflow to upload all artifacts
|
|
108
|
-
`));else if(
|
|
105
|
+
`));else if(m){let p=o.project||process.env.ZIBBY_API_KEY;if(!p)console.log(e.yellow(`
|
|
109
106
|
Cloud sync enabled but no API key provided`)),console.log(e.gray(" Option 1: Use --project flag: --project zby_xxx")),console.log(e.gray(` Option 2: Add to .env: ZIBBY_API_KEY=zby_xxx
|
|
110
|
-
`));else{let P=await
|
|
107
|
+
`));else{let P=await To({apiKey:p,specPath:t,fullSpecPath:i,projectId:null,collectionIdOrName:o.collection||null,folder:o.folder,agent:n.agent,config:n,result:_,shouldOpen:o.open});o.open&&P?.success&&P.executionId&&P.projectId&&await Oo(P.executionId,P.projectId)}}}catch(r){if(v.isSpinning&&v.stop(),console.log(e.red(`
|
|
111
108
|
\u2716 Test failed
|
|
112
|
-
`)),
|
|
113
|
-
`));try{
|
|
114
|
-
`)),
|
|
109
|
+
`)),Ao(r)){console.log(e.yellow(`Test execution was interrupted
|
|
110
|
+
`));try{Oe({cwd:process.cwd(),config:n})}catch{}le(l),process.exit(130)}Po(M,r),console.log(e.red(`Error: ${r.message}
|
|
111
|
+
`)),r.stack&&console.log(e.gray(r.stack)),le(l),process.exit(1)}finally{typeof Y=="function"&&Y(),K(),process.off("SIGINT",f),process.off("SIGTERM",f)}le(l)}function le(t){if(t)try{$e(ae(process.cwd()),{recursive:!0,force:!0})}catch{}}export{So as runCommand};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{mkdir as S,writeFile as m,readFile as p}from"fs/promises";import{existsSync as f,readdirSync as z}from"fs";import{join as o}from"path";import e from"chalk";async function $(l,s,t={}){let n=t.enableMemory!==!1,{TemplateFactory:i}=await import("@zibby/core/templates"),{graphPath:c,nodesPath:y,readmePath:j,resultHandlerPath:b,template:u}=i.getTemplateFiles(s),a=o(l,".zibby");f(a)||await S(a,{recursive:!0});let r=[];await m(o(a,"graph.mjs"),await p(c,"utf-8")),r.push("graph.mjs"),b&&(await m(o(a,"result-handler.mjs"),await p(b,"utf-8")),r.push("result-handler.mjs")),await m(o(a,"README.md"),await p(j,"utf-8")),r.push("README.md");let h=o(a,"nodes");await S(h,{recursive:!0});for(let g of z(y)){let d=await p(o(y,g),"utf-8");!n&&g==="execute-live.mjs"&&(d=d.replace("skills: [SKILLS.BROWSER, SKILLS.MEMORY],","skills: [SKILLS.BROWSER],")),await m(o(h,g),d),r.push(`nodes/${g}`)}let w=o(u.path,"chat.mjs");return f(w)&&(await m(o(a,"chat.mjs"),await p(w,"utf-8")),r.push("chat.mjs")),{template:u,copied:r}}async function E(){let{TemplateFactory:l}=await import("@zibby/core/templates"),s=l.listTemplates();console.log(""),console.log(e.bold.cyan(" Available templates")),console.log("");for(let t of s){if(console.log(` ${e.cyan(t.name)}`),console.log(` ${e.white(t.displayName)}`),t.description&&console.log(` ${e.gray(t.description)}`),t.features&&t.features.length)for(let n of t.features)console.log(e.gray(` \u2022 ${n}`));console.log("")}console.log(e.gray(" Use: zibby template add <name> (or pass -t <name> to zibby init)")),console.log("")}async function L(l,s={}){l||(console.log(e.red(`
|
|
2
|
+
Missing template name.
|
|
3
|
+
`)),console.log(e.gray(" Usage: zibby template add <name>")),console.log(e.gray(` See available templates: zibby template list
|
|
4
|
+
`)),process.exit(1));let t=s.cwd||process.cwd(),n=o(t,".zibby");f(n)||(console.log(e.yellow(`
|
|
5
|
+
No .zibby/ directory in ${t}.
|
|
6
|
+
`)),console.log(e.gray(" Run `zibby init` first to bootstrap the project.\n")),process.exit(1));let i;try{i=await $(t,l,{enableMemory:s.enableMemory!==!1})}catch(c){console.log(e.red(`
|
|
7
|
+
${c.message}
|
|
8
|
+
`)),console.log(e.gray(` See available templates: zibby template list
|
|
9
|
+
`)),process.exit(1)}console.log(""),console.log(e.green(` \u2713 Added template ${e.bold(i.template.name)}`)),console.log(e.gray(` ${i.copied.length} files written to ${n}/`));for(let c of i.copied)console.log(e.gray(` \u2022 ${c}`));console.log(""),console.log(e.gray(" Re-running `zibby template add <name>` overwrites existing files \u2014")),console.log(e.gray(" use this to refresh after `npm update @zibby/core`.")),console.log("")}export{L as templateAddCommand,E as templateListCommand,$ as writeTemplateFiles};
|
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
import{spawnSync as
|
|
1
|
+
import{spawnSync as _}from"child_process";import{existsSync as i,readFileSync as R,writeFileSync as $,readdirSync as h,cpSync as A,rmSync as j,mkdirSync as Z,statSync as k}from"fs";import{join as r}from"path";import{homedir as b}from"os";import o from"chalk";function J(e){if(!i(e))return 0;let n=0;try{let c=[e];for(;c.length;){let l=c.pop(),y=k(l);if(y.isDirectory())for(let a of h(l))c.push(r(l,a));else n+=y.size}}catch{}return n}function L(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`}var v=r(b(),".zibby-cleanup-backups",new Date().toISOString().replace(/[:.]/g,"-").slice(0,19));function S(e){Z(v,{recursive:!0});try{A(e,r(v,e.replace(/\//g,"_")),{recursive:!0})}catch{}try{let n=r(v,e.replace(/\//g,"_"));i(n)&&I(n)}catch{}}function I(e){if(i(e))try{if(!k(e).isDirectory())return;let c=[e];for(;c.length;){let l=c.pop();for(let y of h(l)){let a=r(l,y);k(a).isDirectory()?c.push(a):y==="memory-sync-creds.json"&&$(a,`{ "_scrubbed": "removed by zibby uninstall \u2014 original file contained AWS temp creds" }
|
|
2
|
+
`,"utf-8")}}}catch{}}function B(e,n){i(e)&&(S(e),j(e,{recursive:!0,force:!0}),console.log(o.gray(` \u2713 Removed ${n||e}`)))}async function K(e={}){let n=e.dryRun||!1,c=process.cwd();if(console.log(o.cyan(`
|
|
2
3
|
\u{1F9F9} Zibby Uninstall
|
|
3
|
-
`)),
|
|
4
|
-
`)),console.log(o.white("Global CLI:")),
|
|
5
|
-
Global config (~/.zibby):`)),i(
|
|
6
|
-
Cursor MCP config:`)),i(
|
|
7
|
-
`),console.log(o.gray(" \u2713 Removed playwright-official from ~/.cursor/mcp.json"))):console.log(o.gray(" (no playwright-official entry)"))}catch{console.log(o.yellow(" \u26A0 Could not parse ~/.cursor/mcp.json"))}else console.log(o.gray(" (not found)"));let
|
|
8
|
-
Cursor MCP approvals:`)),i(
|
|
9
|
-
Zibby Studio:`));let
|
|
10
|
-
Current project (${
|
|
11
|
-
`),console.log(o.gray(" \u2713 Stripped @zibby/* from package.json"))))}catch{}}if(
|
|
12
|
-
npx cache (--deep):`)),i(
|
|
13
|
-
`);/zibby/i.test(
|
|
14
|
-
\u2705 Uninstall complete.`)),
|
|
15
|
-
`))}export{
|
|
4
|
+
`)),n&&console.log(o.yellow(` (dry-run mode \u2014 nothing will be deleted)
|
|
5
|
+
`)),console.log(o.white("Global CLI:")),n)console.log(o.gray(" [dry-run] npm uninstall -g @zibby/cli"));else try{_("npm",["uninstall","-g","@zibby/cli"],{stdio:"pipe",timeout:3e4}),console.log(o.gray(" \u2713 npm uninstall -g @zibby/cli"))}catch{console.log(o.yellow(" \u26A0 Could not uninstall global CLI"))}let l=r(b(),".zibby");console.log(o.white(`
|
|
6
|
+
Global config (~/.zibby):`)),i(l)?n?console.log(o.gray(` [dry-run] rm -rf ${l}`)):B(l,"~/.zibby"):console.log(o.gray(" (not found)"));let y=r(b(),".cursor","mcp.json");if(console.log(o.white(`
|
|
7
|
+
Cursor MCP config:`)),i(y))try{let s=JSON.parse(R(y,"utf-8"));s.mcpServers?.["playwright-official"]?n?console.log(o.gray(" [dry-run] Remove playwright-official from ~/.cursor/mcp.json")):(S(y),delete s.mcpServers["playwright-official"],$(y,`${JSON.stringify(s,null,2)}
|
|
8
|
+
`),console.log(o.gray(" \u2713 Removed playwright-official from ~/.cursor/mcp.json"))):console.log(o.gray(" (no playwright-official entry)"))}catch{console.log(o.yellow(" \u26A0 Could not parse ~/.cursor/mcp.json"))}else console.log(o.gray(" (not found)"));let a=r(b(),".cursor","projects");if(console.log(o.white(`
|
|
9
|
+
Cursor MCP approvals:`)),i(a)){let s=0;for(let u of h(a)){let m=r(a,u,"mcp-approvals.json");i(m)&&(n?console.log(o.gray(` [dry-run] rm ${m}`)):B(m,`${u}/mcp-approvals.json`),s++)}s===0&&console.log(o.gray(" (none found)"))}else console.log(o.gray(" (not found)"));let x="/Applications/Zibby Studio.app",O=r(b(),"Library","Application Support","@zibby");console.log(o.white(`
|
|
10
|
+
Zibby Studio:`));let C=!1;for(let s of[x,O])i(s)&&(C=!0,n?console.log(o.gray(` [dry-run] rm -rf "${s}"`)):(j(s,{recursive:!0,force:!0}),console.log(o.gray(` \u2713 Removed ${s}`))));if(C||console.log(o.gray(" (not found)")),i(r(c,".zibby"))||i(r(c,".zibby.config.mjs"))){console.log(o.white(`
|
|
11
|
+
Current project (${c}):`));let s=r(c,".zibby","memory"),u=r(c,".zibby","memory-sync.json"),m=r(c,".zibby","memory-sync-creds.json"),p=r(c,".zibby","memory-context.md"),w=[[s,"memory database (.zibby/memory/)",!0],[u,"memory-sync config (.zibby/memory-sync.json)",!1],[m,"memory-sync creds (.zibby/memory-sync-creds.json \u2014 sensitive, sanitized in backup)",!1],[p,"memory context cache (.zibby/memory-context.md)",!1]],D=!1;for(let[t,f,g]of w){if(!i(t))continue;D=!0;let d=g?`, ${L(J(t))}`:"";console.log(n?o.gray(` [dry-run] ${f}${d}`):o.gray(` \u2713 ${f}${d}`))}D||console.log(o.gray(" (no memory artifacts in this project)"));let F=[".zibby",".zibby.config.mjs",".env.example","node_modules","package-lock.json","test-results","playwright-report"];for(let t of F){let f=r(c,t);i(f)&&(n?console.log(o.gray(` [dry-run] rm -rf ${t}`)):([".zibby",".zibby.config.mjs",".env.example"].includes(t)&&S(f),j(f,{recursive:!0,force:!0}),console.log(o.gray(` \u2713 Removed ${t}`))))}let z=r(c,"package.json");if(i(z))try{let t=JSON.parse(R(z,"utf-8")),f=!1;for(let g of["dependencies","devDependencies","peerDependencies"])if(t[g]){for(let d of Object.keys(t[g]))d.startsWith("@zibby/")&&(delete t[g][d],f=!0);t[g]&&Object.keys(t[g]).length===0&&delete t[g]}f&&(n?console.log(o.gray(" [dry-run] Strip @zibby/* from package.json")):(S(z),$(z,`${JSON.stringify(t,null,2)}
|
|
12
|
+
`),console.log(o.gray(" \u2713 Stripped @zibby/* from package.json"))))}catch{}}if(e.deep){let s=r(b(),".npm","_npx");if(console.log(o.white(`
|
|
13
|
+
npx cache (--deep):`)),i(s)){let u=0;for(let m of h(s)){let p=r(s,m);try{let w=h(p,{recursive:!0}).join(`
|
|
14
|
+
`);/zibby/i.test(w)&&(n?console.log(o.gray(` [dry-run] rm -rf ${p}`)):(j(p,{recursive:!0,force:!0}),console.log(o.gray(` \u2713 Removed ${p}`))),u++)}catch{}}u===0&&console.log(o.gray(" (no zibby-related npx cache found)"))}else console.log(o.gray(" (no ~/.npm/_npx)"))}console.log(o.green(`
|
|
15
|
+
\u2705 Uninstall complete.`)),n||console.log(o.gray(` Backups: ${v}`)),console.log(o.gray(` To reinstall: npm i -g @zibby/cli && zibby init
|
|
16
|
+
`))}export{K as uninstallCommand};
|