@zibby/cli 0.4.11 → 0.4.12

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.
@@ -1 +1 @@
1
- import t from"chalk";function y(o,e=""){return`${String(o).replace(/\/+$/,"")}/agents/credentials${e}`}function h(){let o=new Error("Session expired \u2014 run zibby login");return o.code="AUTH_EXPIRED",o}async function m({apiUrl:o,sessionToken:e}){if(!e)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let r=await fetch(y(o),{headers:{Authorization:`Bearer ${e}`}});if(r.status===401)throw h();if(r.status===404)return{credentials:[],by_type:{oauth:[],api:[]},total:0};if(!r.ok){let c=new Error(`List credentials failed (${r.status})`);throw c.status=r.status,c}return r.json()}async function O({apiUrl:o,sessionToken:e,type:r,token:c,source:s="~/.zibby/config.json"}){if(!e)throw new Error("No session token \u2014 run zibby login first");let n=await fetch(y(o),{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({type:r,token:c,source:s})});if(n.status===401)throw h();if(!n.ok){let i=`Add credential failed (${n.status})`;try{let d=await n.json();d?.error&&(i=`${i}: ${d.error}`)}catch{}let l=new Error(i);throw l.status=n.status,l}return n.json()}async function _({apiUrl:o,sessionToken:e,type:r,index:c}){if(!e)throw new Error("No session token \u2014 run zibby login first");let s=await fetch(y(o,`/${encodeURIComponent(r)}/${encodeURIComponent(c)}`),{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(s.status===401)throw h();if(!s.ok){let n=new Error(`Delete credential failed (${s.status})`);throw n.status=s.status,n}return s.json()}async function U({apiUrl:o,sessionToken:e,credentials:r}){let c=0,s=0,n=[];for(let i of r)try{let l=await O({apiUrl:o,sessionToken:e,type:i.type,token:i.token,source:i.source_var||i.source||"local"});l.deduped?s+=1:l.added&&(c+=1)}catch(l){n.push({masked:i.token?`***${i.token.slice(-4)}`:"***",error:l.message})}return{added:c,deduped:s,errors:n}}import $ from"node:fs/promises";import C from"node:path";import A from"node:os";var p=C.join(A.homedir(),".zibby","config.json"),v={CLAUDE_CODE_OAUTH_TOKEN:"oauth",CLAUDE_CODE_OAUTH_TOKEN_POOL:"oauth",ANTHROPIC_AUTH_TOKEN:"oauth",ANTHROPIC_API_KEY:"api",ANTHROPIC_API_KEY_POOL:"api"};function k(o){if(!o)return[];let e;try{e=JSON.parse(o)}catch{return[]}let r=e?.agentKeys;if(!r||typeof r!="object")return[];let c=[],s=new Set;for(let[n,i]of Object.entries(v)){let l=r[n];if(!l||typeof l!="string")continue;let d=n.endsWith("_POOL")?l.split(",").map(a=>a.trim()).filter(Boolean):[l.trim()];for(let a of d)a.length<8||s.has(a)||(s.add(a),c.push({type:i,token:a,source_var:n}))}return c}async function N(o=p){let e;try{e=await $.readFile(o,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}return k(e)}async function w({filepath:o,env:e=process.env}={}){let r=await N(o),c=new Set(r.map(n=>n.token)),s=[];for(let[n,i]of Object.entries(v)){let l=e[n];if(!l)continue;let d=n.endsWith("_POOL")?l.split(",").map(a=>a.trim()).filter(Boolean):[l];for(let a of d)a.length<8||c.has(a)||(c.add(a),s.push({type:i,token:a,source_var:n,source:"process.env"}))}return{config:r.map(n=>({...n,source:"config.json"})),env:s,all:[...r.map(n=>({...n,source:"config.json"})),...s]}}var u={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 f(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";u[e]?o=u[e].apiUrl:o=u.prod.apiUrl}try{let e=new URL(o);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),u.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),u.prod.apiUrl}}import{existsSync as E,mkdirSync as G,readFileSync as P,writeFileSync as J}from"fs";import{homedir as x}from"os";import{join as g}from"path";function R(){return process.env.ZIBBY_CONFIG_DIR||g(x(),".zibby")}function T(){return g(R(),"config.json")}var B=g(x(),".zibby"),X=g(B,"config.json");function z(){try{let o=T();if(E(o)){let e=P(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function I(){return z().sessionToken||null}function b(){let o=I();return o||(console.log(t.red("Not logged in. Run `zibby login` first.")),process.exit(1)),o}async function L(){let o=b(),e=f();console.log(""),console.log(t.cyan(" Stored credentials in your Zibby workspace")),console.log(t.gray(` Source file: ${p}`)),console.log("");let r;try{r=await m({apiUrl:e,sessionToken:o})}catch(s){console.log(t.red(` Failed: ${s.message}`)),process.exit(1)}let{by_type:c}=r;for(let s of["oauth","api"]){let n=c[s]||[];if(console.log(t.bold(` ${s} pool (${n.length} ${n.length===1?"token":"tokens"}):`)),n.length===0)console.log(t.gray(" (none)"));else for(let i of n){let l=i.uploaded_at?new Date(i.uploaded_at).toISOString().slice(0,10):"?",d=i.uploaded_by||"?";console.log(` [${i.index}] ${t.cyan(i.masked)} `+t.gray(`uploaded ${l} by ${d} source: ${i.source||"unknown"}`))}console.log("")}r.total===0&&(console.log(t.gray(" No credentials yet. Run `zibby init` to set them up \u2014 Claude has")),console.log(t.gray(" both OAuth subscription and API key options. Then re-run sync.")),console.log("")),console.log(t.gray(" Same file, same credentials, used by every zibby command:")),console.log(t.gray(" zibby test (test automation)")),console.log(t.gray(" zibby chat (interactive chat + cloud Claude Code sandbox)")),console.log(t.gray(" zibby workflow run (local execution)")),console.log(t.gray(" zibby workflow start (local dev server)")),console.log("")}async function S(){let o=b(),e=f();console.log(""),console.log(t.cyan(" Scanning your local credentials...")),console.log(t.gray(` ${p}`));let r=await w(),c=r.all.length;if(c===0){console.log(""),console.log(t.yellow(" No credentials found in ~/.zibby/config.json.")),console.log(""),console.log(t.white(" Run `zibby init` first to choose API key or OAuth subscription.")),console.log(t.gray(" Or export tokens in your shell \u2014 Zibby reads process.env too.")),console.log("");return}console.log(t.green(` \u2713 Found ${c} ${c===1?"credential":"credentials"}:`));for(let n of r.all)console.log(t.gray(` ${n.type} ***${n.token.slice(-4)} source: ${n.source_var} (${n.source})`));console.log(""),console.log(t.cyan(" Uploading to Zibby (KMS-encrypted)..."));let s=await U({apiUrl:e,sessionToken:o,credentials:r.all});if(console.log(""),console.log(t.green(` \u2713 ${s.added} new, ${s.deduped} already present`)),s.errors.length>0){console.log(t.red(` \u2717 ${s.errors.length} failed:`));for(let n of s.errors)console.log(t.red(` ${n.masked}: ${n.error}`))}console.log("")}async function D(o,e){let r=b(),c=f();(!o||!e)&&(console.log(t.red("Usage: zibby creds remove <type> <index>")),console.log(t.gray(" e.g. zibby creds remove oauth 0")),process.exit(1)),console.log(""),console.log(t.cyan(` Removing ${o} credential at index ${e}...`));try{await _({apiUrl:c,sessionToken:r,type:o,index:e})}catch(s){console.log(t.red(` Failed: ${s.message}`)),process.exit(1)}console.log(t.green(" \u2713 Removed.")),console.log(""),console.log(t.gray(" Note: this only deletes Zibby's encrypted copy. To revoke")),console.log(t.gray(" the actual token, do that on the upstream provider where")),console.log(t.gray(" it was issued.")),console.log("")}async function ro(o,...e){switch(o){case"list":return L();case"sync":return S();case"remove":return D(e[0],e[1]);default:console.log(t.red(`Unknown subcommand: ${o}`)),console.log(t.gray(" zibby creds list")),console.log(t.gray(" zibby creds sync")),console.log(t.gray(" zibby creds remove <type> <index>")),process.exit(1)}}export{ro as credsCmd,L as listCmd,D as removeCmd,S as syncCmd};
1
+ import t from"chalk";function y(o,e=""){return`${String(o).replace(/\/+$/,"")}/agents/credentials${e}`}function h(){let o=new Error("Session expired \u2014 run zibby login");return o.code="AUTH_EXPIRED",o}async function m({apiUrl:o,sessionToken:e}){if(!e)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let r=await fetch(y(o),{headers:{Authorization:`Bearer ${e}`}});if(r.status===401)throw h();if(r.status===404)return{credentials:[],by_type:{oauth:[],api:[]},total:0};if(!r.ok){let c=new Error(`List credentials failed (${r.status})`);throw c.status=r.status,c}return r.json()}async function $({apiUrl:o,sessionToken:e,type:r,token:c,source:s="~/.zibby/config.json"}){if(!e)throw new Error("No session token \u2014 run zibby login first");let n=await fetch(y(o),{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({type:r,token:c,source:s})});if(n.status===401)throw h();if(!n.ok){let i=`Add credential failed (${n.status})`;try{let d=await n.json();d?.error&&(i=`${i}: ${d.error}`)}catch{}let l=new Error(i);throw l.status=n.status,l}return n.json()}async function _({apiUrl:o,sessionToken:e,type:r,index:c}){if(!e)throw new Error("No session token \u2014 run zibby login first");let s=await fetch(y(o,`/${encodeURIComponent(r)}/${encodeURIComponent(c)}`),{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(s.status===401)throw h();if(!s.ok){let n=new Error(`Delete credential failed (${s.status})`);throw n.status=s.status,n}return s.json()}async function U({apiUrl:o,sessionToken:e,credentials:r}){let c=0,s=0,n=[];for(let i of r)try{let l=await $({apiUrl:o,sessionToken:e,type:i.type,token:i.token,source:i.source_var||i.source||"local"});l.deduped?s+=1:l.added&&(c+=1)}catch(l){n.push({masked:i.token?`***${i.token.slice(-4)}`:"***",error:l.message})}return{added:c,deduped:s,errors:n}}import O from"node:fs/promises";import C from"node:path";import A from"node:os";var p=C.join(A.homedir(),".zibby","config.json"),v={CLAUDE_CODE_OAUTH_TOKEN:"oauth",CLAUDE_CODE_OAUTH_TOKEN_POOL:"oauth",ANTHROPIC_AUTH_TOKEN:"oauth",ANTHROPIC_API_KEY:"api",ANTHROPIC_API_KEY_POOL:"api"};function k(o){if(!o)return[];let e;try{e=JSON.parse(o)}catch{return[]}let r=e?.agentKeys;if(!r||typeof r!="object")return[];let c=[],s=new Set;for(let[n,i]of Object.entries(v)){let l=r[n];if(!l||typeof l!="string")continue;let d=n.endsWith("_POOL")?l.split(",").map(a=>a.trim()).filter(Boolean):[l.trim()];for(let a of d)a.length<8||s.has(a)||(s.add(a),c.push({type:i,token:a,source_var:n}))}return c}async function N(o=p){let e;try{e=await O.readFile(o,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}return k(e)}async function w({filepath:o,env:e=process.env}={}){let r=await N(o),c=new Set(r.map(n=>n.token)),s=[];for(let[n,i]of Object.entries(v)){let l=e[n];if(!l)continue;let d=n.endsWith("_POOL")?l.split(",").map(a=>a.trim()).filter(Boolean):[l];for(let a of d)a.length<8||c.has(a)||(c.add(a),s.push({type:i,token:a,source_var:n,source:"process.env"}))}return{config:r.map(n=>({...n,source:"config.json"})),env:s,all:[...r.map(n=>({...n,source:"config.json"})),...s]}}var u={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 f(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";u[e]?o=u[e].apiUrl:o=u.prod.apiUrl}try{let e=new URL(o);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),u.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),u.prod.apiUrl}}import{existsSync as E,mkdirSync as G,readFileSync as P,writeFileSync as J}from"fs";import{homedir as x}from"os";import{join as g}from"path";function R(){return process.env.ZIBBY_CONFIG_DIR||g(x(),".zibby")}function T(){return g(R(),"config.json")}var B=g(x(),".zibby"),X=g(B,"config.json");function z(){try{let o=T();if(E(o)){let e=P(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function I(){return z().sessionToken||null}function b(){let o=I();return o||(console.log(t.red("Not logged in. Run `zibby login` first.")),process.exit(1)),o}async function L(){let o=b(),e=f();console.log(""),console.log(t.cyan(" Stored credentials in your Zibby workspace")),console.log(t.gray(` Source file: ${p}`)),console.log("");let r;try{r=await m({apiUrl:e,sessionToken:o})}catch(s){console.log(t.red(` Failed: ${s.message}`)),process.exit(1)}let{by_type:c}=r;for(let s of["oauth","api"]){let n=c[s]||[];if(console.log(t.bold(` ${s} pool (${n.length} ${n.length===1?"token":"tokens"}):`)),n.length===0)console.log(t.gray(" (none)"));else for(let i of n){let l=i.uploaded_at?new Date(i.uploaded_at).toISOString().slice(0,10):"?",d=i.uploaded_by||"?";console.log(` [${i.index}] ${t.cyan(i.masked)} ${t.gray(`uploaded ${l} by ${d} source: ${i.source||"unknown"}`)}`)}console.log("")}r.total===0&&(console.log(t.gray(" No credentials yet. Run `zibby init` to set them up \u2014 Claude has")),console.log(t.gray(" both OAuth subscription and API key options. Then re-run sync.")),console.log("")),console.log(t.gray(" Same file, same credentials, used by every zibby command:")),console.log(t.gray(" zibby test (test automation)")),console.log(t.gray(" zibby chat (interactive chat + cloud Claude Code sandbox)")),console.log(t.gray(" zibby workflow run (local execution)")),console.log(t.gray(" zibby workflow start (local dev server)")),console.log("")}async function S(){let o=b(),e=f();console.log(""),console.log(t.cyan(" Scanning your local credentials...")),console.log(t.gray(` ${p}`));let r=await w(),c=r.all.length;if(c===0){console.log(""),console.log(t.yellow(" No credentials found in ~/.zibby/config.json.")),console.log(""),console.log(t.white(" Run `zibby init` first to choose API key or OAuth subscription.")),console.log(t.gray(" Or export tokens in your shell \u2014 Zibby reads process.env too.")),console.log("");return}console.log(t.green(` \u2713 Found ${c} ${c===1?"credential":"credentials"}:`));for(let n of r.all)console.log(t.gray(` ${n.type} ***${n.token.slice(-4)} source: ${n.source_var} (${n.source})`));console.log(""),console.log(t.cyan(" Uploading to Zibby (KMS-encrypted)..."));let s=await U({apiUrl:e,sessionToken:o,credentials:r.all});if(console.log(""),console.log(t.green(` \u2713 ${s.added} new, ${s.deduped} already present`)),s.errors.length>0){console.log(t.red(` \u2717 ${s.errors.length} failed:`));for(let n of s.errors)console.log(t.red(` ${n.masked}: ${n.error}`))}console.log("")}async function D(o,e){let r=b(),c=f();(!o||!e)&&(console.log(t.red("Usage: zibby creds remove <type> <index>")),console.log(t.gray(" e.g. zibby creds remove oauth 0")),process.exit(1)),console.log(""),console.log(t.cyan(` Removing ${o} credential at index ${e}...`));try{await _({apiUrl:c,sessionToken:r,type:o,index:e})}catch(s){console.log(t.red(` Failed: ${s.message}`)),process.exit(1)}console.log(t.green(" \u2713 Removed.")),console.log(""),console.log(t.gray(" Note: this only deletes Zibby's encrypted copy. To revoke")),console.log(t.gray(" the actual token, do that on the upstream provider where")),console.log(t.gray(" it was issued.")),console.log("")}async function ro(o,...e){switch(o){case"list":return L();case"sync":return S();case"remove":return D(e[0],e[1]);default:console.log(t.red(`Unknown subcommand: ${o}`)),console.log(t.gray(" zibby creds list")),console.log(t.gray(" zibby creds sync")),console.log(t.gray(" zibby creds remove <type> <index>")),process.exit(1)}}export{ro as credsCmd,L as listCmd,D as removeCmd,S as syncCmd};
@@ -72,7 +72,7 @@ ${i}`),console.log(r.white(" Last 10 runs:"));for(let n of t.recent.slice(0,10)
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 yo={};N(yo,{setupCiCommand:()=>$t,setupPlaywrightMcpCommand:()=>go,testWithVideoCommand:()=>St});import{spawn as me,execSync as ge}from"child_process";import{join as L,dirname as ye,resolve as ao}from"path";import{readFileSync as lo,writeFileSync as co,existsSync as Z,mkdirSync as uo}from"fs";import{homedir as po}from"os";import{createRequire as bt}from"module";import _ from"chalk";function wt(){try{return ye(pe.resolve("@zibby/core/package.json"))}catch{return null}}function mo(e){try{return ge(`command -v ${e}`,{stdio:"pipe"}),!0}catch{return!1}}function vt(){try{let e=pe.resolve("@zibby/mcp-browser/bin/mcp-browser-zibby.js");if(Z(e))return e}catch{}try{let e=pe.resolve("@playwright/mcp/package.json"),o=ye(e),t=JSON.parse(lo(e,"utf-8")),i=typeof t.bin=="string"?t.bin:t.bin?.["playwright-mcp"];if(i){let n=L(o,i);if(Z(n))return n}let s=L(o,"cli.js");if(Z(s))return s}catch{}return null}function so(e,o,t={}){return new Promise((i,s)=>{let n=me(e,o,{stdio:"inherit",...t});n.on("close",u=>i(u??1)),n.on("error",s)})}async function kt(e){return mo("playwright")?await so("playwright",["install","ffmpeg"],{cwd:e})===0:await so("npx",["--yes","playwright","install","ffmpeg"],{cwd:e})===0}function xt({headed:e=!1,viewport:o=null}){let t=process.execPath,i=ye(t),s=vt(),n=Number(o?.width)||1280,u=Number(o?.height)||720,d=`${n}x${u}`,l=[];l.push(`--viewport-size=${d}`,"--output-dir=test-results"),e||l.push("--headless");let m;s?m={command:t,args:[s,...l],env:{PATH:`${i}:/usr/bin:/bin:/usr/sbin:/sbin`}}:m={command:"npx",args:["-y","@playwright/mcp",...l],env:{PATH:`${i}:/usr/bin:/bin:/usr/sbin:/sbin`}},m.description="Zibby MCP Browser - Playwright MCP with Zibby defaults";let w=L(po(),".cursor"),v=L(w,"mcp.json");Z(w)||uo(w,{recursive:!0});let h={mcpServers:{}};if(Z(v))try{h=JSON.parse(lo(v,"utf-8")),(!h.mcpServers||typeof h.mcpServers!="object")&&(h.mcpServers={})}catch{h={mcpServers:{}}}h.mcpServers["playwright-official"]=m,co(v,`${JSON.stringify(h,null,2)}
75
+ `});var yo={};N(yo,{setupCiCommand:()=>$t,setupPlaywrightMcpCommand:()=>go,testWithVideoCommand:()=>St});import{spawn as me,execSync as ge}from"child_process";import{join as L,dirname as ye,resolve as ao}from"path";import{readFileSync as lo,writeFileSync as co,existsSync as Z,mkdirSync as uo}from"fs";import{homedir as po}from"os";import{createRequire as bt}from"module";import _ from"chalk";function wt(){try{return ye(pe.resolve("@zibby/core/package.json"))}catch{return null}}function mo(e){try{return ge(`command -v ${e}`,{stdio:"pipe"}),!0}catch{return!1}}function vt(){try{let e=pe.resolve("@zibby/mcp-browser/dist/bin/mcp-browser-zibby.js");if(Z(e))return e}catch{}try{let e=pe.resolve("@playwright/mcp/package.json"),o=ye(e),t=JSON.parse(lo(e,"utf-8")),i=typeof t.bin=="string"?t.bin:t.bin?.["playwright-mcp"];if(i){let n=L(o,i);if(Z(n))return n}let s=L(o,"cli.js");if(Z(s))return s}catch{}return null}function so(e,o,t={}){return new Promise((i,s)=>{let n=me(e,o,{stdio:"inherit",...t});n.on("close",u=>i(u??1)),n.on("error",s)})}async function kt(e){return mo("playwright")?await so("playwright",["install","ffmpeg"],{cwd:e})===0:await so("npx",["--yes","playwright","install","ffmpeg"],{cwd:e})===0}function xt({headed:e=!1,viewport:o=null}){let t=process.execPath,i=ye(t),s=vt(),n=Number(o?.width)||1280,u=Number(o?.height)||720,d=`${n}x${u}`,l=[];l.push(`--viewport-size=${d}`,"--output-dir=test-results"),e||l.push("--headless");let m;s?m={command:t,args:[s,...l],env:{PATH:`${i}:/usr/bin:/bin:/usr/sbin:/sbin`}}:m={command:"npx",args:["-y","@playwright/mcp",...l],env:{PATH:`${i}:/usr/bin:/bin:/usr/sbin:/sbin`}},m.description="Zibby MCP Browser - Playwright MCP with Zibby defaults";let w=L(po(),".cursor"),v=L(w,"mcp.json");Z(w)||uo(w,{recursive:!0});let h={mcpServers:{}};if(Z(v))try{h=JSON.parse(lo(v,"utf-8")),(!h.mcpServers||typeof h.mcpServers!="object")&&(h.mcpServers={})}catch{h={mcpServers:{}}}h.mcpServers["playwright-official"]=m,co(v,`${JSON.stringify(h,null,2)}
76
76
  `,"utf-8")}async function _t(){let e=wt();if(!e)return;let o=L(e,"scripts","patch-cursor-mcp.js");if(Z(o))try{await new Promise((t,i)=>{let s=me(process.execPath,[o],{cwd:process.cwd(),stdio:"ignore"});s.on("close",n=>t(n??0)),s.on("error",i)})}catch{}}function It(e){return ao(e).replace(/^\/+/,"").replace(/\//g,"-")}function At(e){let o=String(e||""),t=o.split(`
77
77
  `).find(n=>/playwright-official/i.test(n)&&/APPROVAL|🔑/i.test(n));if(t){let n=t.match(/=>\s*(\S+)/);if(n)return n[1]}let i=o.match(/playwright-official[^=]*=>\s*(\S+)/);if(i)return i[1];let s=o.match(/playwright-official-[a-f0-9]+/i);return s?s[0]:null}function Pt(e,o){let t=It(e),i=L(po(),".cursor","projects",t);uo(i,{recursive:!0});let s=L(i,"mcp-approvals.json");return co(s,`${JSON.stringify([o],null,2)}
78
78
  `,"utf-8"),s}function io(e){try{return ge("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):"",i=o.stderr!=null?String(o.stderr):"";return t+i}}function Ct(e){try{return ge("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 i=await kt(process.cwd());console.log(i?_.gray(" \u2713 ffmpeg installed for Playwright video"):_.yellow(" \u26A0 Could not install ffmpeg (video may be unavailable)")),xt({headed:o,viewport:t}),await _t();let s=ao(process.cwd());if(mo("cursor-agent")){io(s);let n=Ct(s);n&&console.log(_.gray(" \u2713 cursor-agent: mcp enable playwright-official"));let u=io(s),d=At(u);if(d)try{let l=Pt(s,d);console.log(_.gray(` \u2713 MCP auto-approval key saved (${l})`))}catch(l){console.log(_.yellow(` \u26A0 Could not write mcp-approvals.json: ${l.message}`))}else n||(console.log(_.yellow(" \u26A0 Could not auto-approve MCP (mcp enable failed and no approval key in cursor-agent output)")),console.log(_.gray(" Try: cursor-agent mcp enable playwright-official")))}else console.log(_.yellow(" \u26A0 cursor-agent not found; install it to use Cursor MCP tools"))}async function $t(e){try{console.log(_.cyan(`
@@ -1,4 +1,4 @@
1
- import{spawn as y,execSync as w}from"child_process";import{join as l,dirname as v,resolve as C}from"path";import{readFileSync as S,writeFileSync as x,existsSync as p,mkdirSync as j}from"fs";import{homedir as $}from"os";import{createRequire as M}from"module";import c from"chalk";var m=M(import.meta.url);function A(){try{return v(m.resolve("@zibby/core/package.json"))}catch{return null}}function k(e){try{return w(`command -v ${e}`,{stdio:"pipe"}),!0}catch{return!1}}function B(){try{let e=m.resolve("@zibby/mcp-browser/bin/mcp-browser-zibby.js");if(p(e))return e}catch{}try{let e=m.resolve("@playwright/mcp/package.json"),r=v(e),o=JSON.parse(S(e,"utf-8")),n=typeof o.bin=="string"?o.bin:o.bin?.["playwright-mcp"];if(n){let s=l(r,n);if(p(s))return s}let t=l(r,"cli.js");if(p(t))return t}catch{}return null}function b(e,r,o={}){return new Promise((n,t)=>{let s=y(e,r,{stdio:"inherit",...o});s.on("close",u=>n(u??1)),s.on("error",t)})}async function E(e){return k("playwright")?await b("playwright",["install","ffmpeg"],{cwd:e})===0:await b("npx",["--yes","playwright","install","ffmpeg"],{cwd:e})===0}function N({headed:e=!1,viewport:r=null}){let o=process.execPath,n=v(o),t=B(),s=Number(r?.width)||1280,u=Number(r?.height)||720,f=`${s}x${u}`,i=[];i.push(`--viewport-size=${f}`,"--output-dir=test-results"),e||i.push("--headless");let g;t?g={command:o,args:[t,...i],env:{PATH:`${n}:/usr/bin:/bin:/usr/sbin:/sbin`}}:g={command:"npx",args:["-y","@playwright/mcp",...i],env:{PATH:`${n}:/usr/bin:/bin:/usr/sbin:/sbin`}},g.description="Zibby MCP Browser - Playwright MCP with Zibby defaults";let d=l($(),".cursor"),h=l(d,"mcp.json");p(d)||j(d,{recursive:!0});let a={mcpServers:{}};if(p(h))try{a=JSON.parse(S(h,"utf-8")),(!a.mcpServers||typeof a.mcpServers!="object")&&(a.mcpServers={})}catch{a={mcpServers:{}}}a.mcpServers["playwright-official"]=g,x(h,`${JSON.stringify(a,null,2)}
1
+ import{spawn as y,execSync as w}from"child_process";import{join as l,dirname as v,resolve as C}from"path";import{readFileSync as S,writeFileSync as x,existsSync as p,mkdirSync as j}from"fs";import{homedir as $}from"os";import{createRequire as M}from"module";import c from"chalk";var m=M(import.meta.url);function A(){try{return v(m.resolve("@zibby/core/package.json"))}catch{return null}}function k(e){try{return w(`command -v ${e}`,{stdio:"pipe"}),!0}catch{return!1}}function B(){try{let e=m.resolve("@zibby/mcp-browser/dist/bin/mcp-browser-zibby.js");if(p(e))return e}catch{}try{let e=m.resolve("@playwright/mcp/package.json"),r=v(e),o=JSON.parse(S(e,"utf-8")),n=typeof o.bin=="string"?o.bin:o.bin?.["playwright-mcp"];if(n){let s=l(r,n);if(p(s))return s}let t=l(r,"cli.js");if(p(t))return t}catch{}return null}function b(e,r,o={}){return new Promise((n,t)=>{let s=y(e,r,{stdio:"inherit",...o});s.on("close",u=>n(u??1)),s.on("error",t)})}async function E(e){return k("playwright")?await b("playwright",["install","ffmpeg"],{cwd:e})===0:await b("npx",["--yes","playwright","install","ffmpeg"],{cwd:e})===0}function N({headed:e=!1,viewport:r=null}){let o=process.execPath,n=v(o),t=B(),s=Number(r?.width)||1280,u=Number(r?.height)||720,f=`${s}x${u}`,i=[];i.push(`--viewport-size=${f}`,"--output-dir=test-results"),e||i.push("--headless");let g;t?g={command:o,args:[t,...i],env:{PATH:`${n}:/usr/bin:/bin:/usr/sbin:/sbin`}}:g={command:"npx",args:["-y","@playwright/mcp",...i],env:{PATH:`${n}:/usr/bin:/bin:/usr/sbin:/sbin`}},g.description="Zibby MCP Browser - Playwright MCP with Zibby defaults";let d=l($(),".cursor"),h=l(d,"mcp.json");p(d)||j(d,{recursive:!0});let a={mcpServers:{}};if(p(h))try{a=JSON.parse(S(h,"utf-8")),(!a.mcpServers||typeof a.mcpServers!="object")&&(a.mcpServers={})}catch{a={mcpServers:{}}}a.mcpServers["playwright-official"]=g,x(h,`${JSON.stringify(a,null,2)}
2
2
  `,"utf-8")}async function O(){let e=A();if(!e)return;let r=l(e,"scripts","patch-cursor-mcp.js");if(p(r))try{await new Promise((o,n)=>{let t=y(process.execPath,[r],{cwd:process.cwd(),stdio:"ignore"});t.on("close",s=>o(s??0)),t.on("error",n)})}catch{}}function R(e){return C(e).replace(/^\/+/,"").replace(/\//g,"-")}function z(e){let r=String(e||""),o=r.split(`
3
3
  `).find(s=>/playwright-official/i.test(s)&&/APPROVAL|🔑/i.test(s));if(o){let s=o.match(/=>\s*(\S+)/);if(s)return s[1]}let n=r.match(/playwright-official[^=]*=>\s*(\S+)/);if(n)return n[1];let t=r.match(/playwright-official-[a-f0-9]+/i);return t?t[0]:null}function J(e,r){let o=R(e),n=l($(),".cursor","projects",o);j(n,{recursive:!0});let t=l(n,"mcp-approvals.json");return x(t,`${JSON.stringify([r],null,2)}
4
4
  `,"utf-8"),t}function P(e){try{return w("cursor-agent mcp list",{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:process.env,maxBuffer:2*1024*1024})}catch(r){let o=r.stdout!=null?String(r.stdout):"",n=r.stderr!=null?String(r.stderr):"";return o+n}}function T(e){try{return w("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 D(e={}){let r=!!e.headed,o=e.viewport||{width:1280,height:720};if(!process.execPath)throw new Error("Node.js runtime not found");let n=await E(process.cwd());console.log(n?c.gray(" \u2713 ffmpeg installed for Playwright video"):c.yellow(" \u26A0 Could not install ffmpeg (video may be unavailable)")),N({headed:r,viewport:o}),await O();let t=C(process.cwd());if(k("cursor-agent")){P(t);let s=T(t);s&&console.log(c.gray(" \u2713 cursor-agent: mcp enable playwright-official"));let u=P(t),f=z(u);if(f)try{let i=J(t,f);console.log(c.gray(` \u2713 MCP auto-approval key saved (${i})`))}catch(i){console.log(c.yellow(` \u26A0 Could not write mcp-approvals.json: ${i.message}`))}else s||(console.log(c.yellow(" \u26A0 Could not auto-approve MCP (mcp enable failed and no approval key in cursor-agent output)")),console.log(c.gray(" Try: cursor-agent mcp enable playwright-official")))}else console.log(c.yellow(" \u26A0 cursor-agent not found; install it to use Cursor MCP tools"))}async function K(e){try{console.log(c.cyan(`
@@ -1,61 +1,61 @@
1
- var wo=Object.defineProperty;var N=(e,o)=>()=>(e&&(o=e(e=0)),o);var Ee=(e,o)=>{for(var t in o)wo(e,t,{get:o[t],enumerable:!0})};function j(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";H[o]?e=H[o].apiUrl:e=H.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)`),H.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),H.prod.apiUrl}}var H,Z=N(()=>{H={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 Po,readFileSync as Oo,writeFileSync as Co}from"fs";import{homedir as Oe}from"os";import{join as W}from"path";function Ce(){return process.env.ZIBBY_CONFIG_DIR||W(Oe(),".zibby")}function Ne(){return W(Ce(),"config.json")}function Lo(){let e=Ce();Pe(e)||Po(e,{recursive:!0})}function B(){try{let e=Ne();if(Pe(e)){let o=Oo(e,"utf-8");return JSON.parse(o)}}catch{}return{}}function M(e){Lo(),Co(Ne(),JSON.stringify(e,null,2))}function Le(){return B().sessionToken||null}function Be(e){let o=B();o.sessionToken=e,M(o)}function Ke(){return B().user||null}function Re(e){let o=B();o.user=e,M(o)}function ze(e){let o=B();o.proxyUrl=e,M(o)}function De(e){let o=B();o.mem0ProxyUrl=e,M(o)}function Ye(e){let o=B();o.projects=e,M(o)}var No,Kt,Fe=N(()=>{No=W(Oe(),".zibby"),Kt=W(No,"config.json")});import{existsSync as Dt,mkdirSync as Yt,readFileSync as Ft,writeFileSync as Gt,unlinkSync as Ht}from"fs";import{resolve as Vt}from"path";import{homedir as Zt}from"os";var Ge=N(()=>{});import g from"chalk";import ue from"ora";import{spawn as Bo}from"child_process";function Ko(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]),Bo(t,n,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function Ro(){let e=Le(),o=Ke();return e&&o?{loggedIn:!0,user:o,token:e}:{loggedIn:!1}}async function Me(){try{console.log(g.cyan(`
1
+ var mo=Object.defineProperty;var j=(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 S(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";G[o]?e=G[o].apiUrl:e=G.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)`),G.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),G.prod.apiUrl}}var G,Z=j(()=>{G={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 jo,readFileSync as Po,writeFileSync as Oo}from"fs";import{homedir as Oe}from"os";import{join as W}from"path";function Ce(){return process.env.ZIBBY_CONFIG_DIR||W(Oe(),".zibby")}function Ne(){return W(Ce(),"config.json")}function No(){let e=Ce();Pe(e)||jo(e,{recursive:!0})}function K(){try{let e=Ne();if(Pe(e)){let o=Po(e,"utf-8");return JSON.parse(o)}}catch{}return{}}function H(e){No(),Oo(Ne(),JSON.stringify(e,null,2))}function Le(){return K().sessionToken||null}function Be(e){let o=K();o.sessionToken=e,H(o)}function Ke(){return K().user||null}function Re(e){let o=K();o.user=e,H(o)}function ze(e){let o=K();o.proxyUrl=e,H(o)}function De(e){let o=K();o.mem0ProxyUrl=e,H(o)}function Ye(e){let o=K();o.projects=e,H(o)}var Co,Bt,Fe=j(()=>{Co=W(Oe(),".zibby"),Bt=W(Co,"config.json")});import{existsSync as zt,mkdirSync as Dt,readFileSync as Yt,writeFileSync as Ft,unlinkSync as Gt}from"fs";import{resolve as Mt}from"path";import{homedir as Jt}from"os";var Ge=j(()=>{});import h from"chalk";import ue from"ora";import{spawn as Lo}from"child_process";function Bo(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]),Lo(t,n,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function Ko(){let e=Le(),o=Ke();return e&&o?{loggedIn:!0,user:o,token:e}:{loggedIn:!1}}async function Me(){try{console.log(h.cyan(`
2
2
  \u{1F510} Initiating login...
3
- `));let e=Ro();if(e.loggedIn){console.log(g.green("\u2705 Already logged in!")),console.log(g.gray(`User: ${e.user.email}`)),console.log(g.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(g.yellow(`
3
+ `));let e=Ko();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(g.yellow("Continue with this session? (Y/n): "),async c=>{process.removeListener("SIGINT",s),i();try{if(c.toLowerCase()==="n"||c.toLowerCase()==="no"){console.log(g.gray(`Starting new login...
8
- `));let u=await He();n(u)}else console.log(g.green(`Using existing session.
9
- `)),n({success:!0,...e})}catch(u){r(u)}})})}return await He()}catch(e){return console.error(g.red(`
10
- \u274C Login failed:`,e.message)),{success:!1,error:e.message}}}async function zo(e){let o=j();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 Ye(r),r}}catch(t){console.log(g.gray(`\u26A0\uFE0F Could not fetch projects: ${t.message}`))}return[]}async function He(){let e=j(),o=ue("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 k=await t.json();throw new Error(k.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(g.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(g.cyan("\u2551")+g.white.bold(" Complete login in your browser ")+g.cyan("\u2551")),console.log(g.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(g.white("Opening browser to login page...")),console.log(g.gray(`Code expires in ${Math.floor(s/60)} minutes`)),console.log(""),await Ko(i)||(console.log(g.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(g.white("Please open this URL manually: ")+g.blue(i)),console.log(""));let l=ue("Waiting for authorization...").start(),d=(c||3)*1e3,x=Math.floor(s/(c||3)),b=0,h=!1,$=()=>{h=!0,l.stop(),console.log(g.yellow(`
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 l=await He();n(l)}else console.log(h.green(`Using existing session.
9
+ `)),n({success:!0,...e})}catch(l){r(l)}})})}return await He()}catch(e){return console.error(h.red(`
10
+ \u274C Login failed:`,e.message)),{success:!1,error:e.message}}}async function Ro(e){let o=S();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 Ye(r),r}}catch(t){console.log(h.gray(`\u26A0\uFE0F Could not fetch projects: ${t.message}`))}return[]}async function He(){let e=S(),o=ue("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 Bo(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=ue("Waiting for authorization...").start(),g=(c||3)*1e3,b=Math.floor(s/(c||3)),y=0,_=!1,$=()=>{_=!0,a.stop(),console.log(h.yellow(`
11
11
 
12
12
  \u26A0\uFE0F Login cancelled
13
- `)),process.exit(0)};process.on("SIGINT",$);try{for(;b<x&&!h;){await Do(d),b++;let k=await fetch(`${e}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:n})});if(k.status===202)continue;if(!k.ok){l.fail("Authorization failed");let f=await k.json();throw new Error(f.error||"Authorization failed")}let a=await k.json();if(a.status==="authorized"){l.succeed(g.white("Authorization successful!")),Be(a.token),Re(a.user),a.proxyUrl&&ze(a.proxyUrl),a.mem0ProxyUrl&&De(a.mem0ProxyUrl),console.log(""),console.log(g.gray(`User: ${a.user.email}`));let f=ue("Fetching projects...").start(),A=await zo(a.token);return f.succeed(`Fetched ${A.length} project${A.length!==1?"s":""}`),console.log(g.gray(`Session saved to: ~/.zibby/config.json
14
- `)),{success:!0,loggedIn:!0,user:a.user,token:a.token}}if(a.status==="denied")throw l.fail("Authorization denied"),new Error("User denied authorization")}throw l.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",$)}}function Do(e){return new Promise(o=>setTimeout(o,e))}var Ve=N(()=>{Z();Fe();Ge()});import{existsSync as Yo,readFileSync as Fo}from"fs";import{join as Go}from"path";import pe from"chalk";import{confirm as Ho}from"@inquirer/prompts";function Je(){try{let e=process.env.HOME||process.env.USERPROFILE;if(!e)return null;let o=Go(e,".zibby","config.json");return Yo(o)&&JSON.parse(Fo(o,"utf-8")).sessionToken||null}catch{return null}}function fe(){console.log(`
13
+ `)),process.exit(0)};process.on("SIGINT",$);try{for(;y<b&&!_;){await zo(g),y++;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 p=await u.json();throw new Error(p.error||"Authorization failed")}let f=await u.json();if(f.status==="authorized"){a.succeed(h.white("Authorization successful!")),Be(f.token),Re(f.user),f.proxyUrl&&ze(f.proxyUrl),f.mem0ProxyUrl&&De(f.mem0ProxyUrl),console.log(""),console.log(h.gray(`User: ${f.user.email}`));let p=ue("Fetching projects...").start(),B=await Ro(f.token);return p.succeed(`Fetched ${B.length} project${B.length!==1?"s":""}`),console.log(h.gray(`Session saved to: ~/.zibby/config.json
14
+ `)),{success:!0,loggedIn:!0,user:f.user,token:f.token}}if(f.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",$)}}function zo(e){return new Promise(o=>setTimeout(o,e))}var Ve=j(()=>{Z();Fe();Ge()});import{existsSync as Do,readFileSync as Yo}from"fs";import{join as Fo}from"path";import pe from"chalk";import{confirm as Go}from"@inquirer/prompts";function Je(){try{let e=process.env.HOME||process.env.USERPROFILE;if(!e)return null;let o=Fo(e,".zibby","config.json");return Do(o)&&JSON.parse(Yo(o,"utf-8")).sessionToken||null}catch{return null}}function fe(){console.log(`
15
15
  Not authenticated.`),console.log(` Run ${pe.cyan("zibby login")} or set ${pe.cyan("ZIBBY_API_KEY")} in your environment.
16
16
  `)}async function q(e={}){let o=e.apiKey||process.env.ZIBBY_API_KEY||null,t=Je();if(t||o)return{sessionToken:t,apiKey:o};if(!process.stdin.isTTY){if(e.optional)return{sessionToken:null,apiKey:null};fe(),process.exit(1)}console.log(pe.yellow(`
17
- Not logged in.`));let n;try{n=await Ho({message:"Open browser to log in now?",default:!0})}catch{n=!1}if(!n){if(e.optional)return{sessionToken:null,apiKey:null};fe(),process.exit(1)}if(await Me(),t=Je(),!t){if(e.optional)return{sessionToken:null,apiKey:null};fe(),process.exit(1)}return{sessionToken:t,apiKey:null}}var de=N(()=>{Ve()});import{existsSync as Mo,readFileSync as Vo,writeFileSync as gn,mkdirSync as yn}from"fs";import{join as Jo}from"path";import{homedir as Zo}from"os";function Wo(){return Jo(Zo(),".zibby","config.json")}function ge(){try{let e=Wo();return Mo(e)?JSON.parse(Vo(e,"utf-8")):{}}catch{return{}}}var Q,Ze=N(()=>{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 qo,existsSync as Qo}from"fs";import Xo from"dotenv";function X(e){return typeof e=="string"&&ye.test(e)}function We(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 ${ye} (uppercase letters, digits, underscores; can't start with a digit)`);return{key:t,value:n}}function V(e){if(!Array.isArray(e)||e.length===0)return{};let o={};for(let t of e){if(!Qo(t))throw new Error(`--env file not found: ${t}`);let n=Xo.parse(qo(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 ${ye} (uppercase letters, digits, underscores; can't start with a digit)`);o[r]=i}}return o}function L(e,o,t){let n=String(e).replace(/\/+$/,"");return t?`${n}/workflows/${o}/env/${encodeURIComponent(t)}`:`${n}/workflows/${o}/env`}function he(e){return!Array.isArray(e)||e.length===0?"No env vars set on this workflow.":[...e].sort().map(t=>` ${t}`).join(`
18
- `)}var ye,me=N(()=>{ye=/^[A-Z_][A-Z0-9_]*$/});var so={};Ee(so,{pickLocalUpload:()=>to,readDeployedUuid:()=>oo,readFullClaudeOauthBlob:()=>Xe,readLocalUpload:()=>no,resolveAgentAuthChoice:()=>eo,resolveCheckResult:()=>ro,resolveWorkflowAgent:()=>ke,runCloudCredsCheck:()=>gt,writeTempEnvBag:()=>ve,writeTempEnvFile:()=>pt});import m from"chalk";import et from"inquirer";import{execSync as ot}from"node:child_process";import{existsSync as qe,readFileSync as Qe,writeFileSync as tt,chmodSync as nt,unlinkSync as rt}from"node:fs";import{homedir as st,tmpdir as it}from"node:os";import{join as we}from"node:path";import{randomBytes as ct}from"node:crypto";function Xe(){if(process.platform==="darwin")try{let e=ot('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=we(st(),".claude",".credentials.json");return qe(e)&&JSON.parse(Qe(e,"utf-8"))?.claudeAiOauth||null}catch{return null}}function eo(e){let o=ke(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 ke(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 oo(e){if(!e)return null;let o=we(e,".zibby-deploy.json");if(!qe(o))return null;try{let t=JSON.parse(Qe(o,"utf-8"));if(typeof t?.uuid=="string"&&t.uuid)return t.uuid}catch{}return null}function to(e,o,t){let r=(lt[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 no(e,o,{readConfig:t=ge}={}){let n=t()||{},r=n.agentKeys&&typeof n.agentKeys=="object"?n.agentKeys:{};return to(e,r,o)}async function ut({apiUrl:e,sessionToken:o,uuid:t,fetchImpl:n}){let r=await n(L(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 ft(e,o){if(!e?.length)return!1;try{let t=V(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 ro({workflowAgent:e,workflowUuid:o,authChoice:t,envFiles:n=[],sessionToken:r,apiUrl:i,fetchImpl:s=globalThis.fetch,readConfig:c=ge}){if(!e)return{status:"error",detail:"workflowAgent unresolved (no agent in .zibby.config.mjs)"};let u=at[e];if(!u)return{status:"error",detail:`unknown agent: ${e}`};if(!r||!i)return{status:"error",detail:"missing sessionToken or apiUrl"};if(o)try{let d=await ut({apiUrl:i,sessionToken:r,uuid:o,fetchImpl:s}),x=u.find(b=>d.includes(b));if(x)return{status:"ok-already-set",acceptedVars:u,matchedVar:x}}catch(d){if(!/HTTP 404/.test(d.message))return{status:"error",detail:d.message}}if(ft(n,u))return{status:"ok-via-env-flag",acceptedVars:u};let l=no(e,t,{readConfig:c});return l?{status:"mismatch-can-upload",acceptedVars:u,candidate:l}:{status:"mismatch-no-local",acceptedVars:u}}function pt({uploadAs:e,value:o}){return ve({[e]:o})}function ve(e){let o=we(it(),`zibby-creds-${ct(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}`});tt(o,`${t.join(`
17
+ Not logged in.`));let n;try{n=await Go({message:"Open browser to log in now?",default:!0})}catch{n=!1}if(!n){if(e.optional)return{sessionToken:null,apiKey:null};fe(),process.exit(1)}if(await Me(),t=Je(),!t){if(e.optional)return{sessionToken:null,apiKey:null};fe(),process.exit(1)}return{sessionToken:t,apiKey:null}}var de=j(()=>{Ve()});import{existsSync as Ho,readFileSync as Mo,writeFileSync as dn,mkdirSync as gn}from"fs";import{join as Vo}from"path";import{homedir as Jo}from"os";function Zo(){return Vo(Jo(),".zibby","config.json")}function ge(){try{let e=Zo();return Ho(e)?JSON.parse(Mo(e,"utf-8")):{}}catch{return{}}}var Q,Ze=j(()=>{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 Wo,existsSync as qo}from"fs";import Qo from"dotenv";function X(e){return typeof e=="string"&&ye.test(e)}function We(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 ${ye} (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(!qo(t))throw new Error(`--env file not found: ${t}`);let n=Qo.parse(Wo(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 ${ye} (uppercase letters, digits, underscores; can't start with a digit)`);o[r]=i}}return o}function L(e,o,t){let n=String(e).replace(/\/+$/,"");return t?`${n}/workflows/${o}/env/${encodeURIComponent(t)}`:`${n}/workflows/${o}/env`}function he(e){return!Array.isArray(e)||e.length===0?"No env vars set on this workflow.":[...e].sort().map(t=>` ${t}`).join(`
18
+ `)}var ye,me=j(()=>{ye=/^[A-Z_][A-Z0-9_]*$/});var so={};Ee(so,{pickLocalUpload:()=>to,readDeployedUuid:()=>oo,readFullClaudeOauthBlob:()=>Xe,readLocalUpload:()=>no,resolveAgentAuthChoice:()=>eo,resolveCheckResult:()=>ro,resolveWorkflowAgent:()=>ke,runCloudCredsCheck:()=>dt,writeTempEnvBag:()=>ve,writeTempEnvFile:()=>ft});import w from"chalk";import Xo from"inquirer";import{execSync as et}from"node:child_process";import{existsSync as qe,readFileSync as Qe,writeFileSync as ot,chmodSync as tt,unlinkSync as nt}from"node:fs";import{homedir as rt,tmpdir as st}from"node:os";import{join as we}from"node:path";import{randomBytes as it}from"node:crypto";function Xe(){if(process.platform==="darwin")try{let e=et('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=we(rt(),".claude",".credentials.json");return qe(e)&&JSON.parse(Qe(e,"utf-8"))?.claudeAiOauth||null}catch{return null}}function eo(e){let o=ke(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 ke(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 oo(e){if(!e)return null;let o=we(e,".zibby-deploy.json");if(!qe(o))return null;try{let t=JSON.parse(Qe(o,"utf-8"));if(typeof t?.uuid=="string"&&t.uuid)return t.uuid}catch{}return null}function to(e,o,t){let r=(at[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 no(e,o,{readConfig:t=ge}={}){let n=t()||{},r=n.agentKeys&&typeof n.agentKeys=="object"?n.agentKeys:{};return to(e,r,o)}async function lt({apiUrl:e,sessionToken:o,uuid:t,fetchImpl:n}){let r=await n(L(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 ut(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 ro({workflowAgent:e,workflowUuid:o,authChoice:t,envFiles:n=[],sessionToken:r,apiUrl:i,fetchImpl:s=globalThis.fetch,readConfig:c=ge}){if(!e)return{status:"error",detail:"workflowAgent unresolved (no agent in .zibby.config.mjs)"};let l=ct[e];if(!l)return{status:"error",detail:`unknown agent: ${e}`};if(!r||!i)return{status:"error",detail:"missing sessionToken or apiUrl"};if(o)try{let g=await lt({apiUrl:i,sessionToken:r,uuid:o,fetchImpl:s}),b=l.find(y=>g.includes(y));if(b)return{status:"ok-already-set",acceptedVars:l,matchedVar:b}}catch(g){if(!/HTTP 404/.test(g.message))return{status:"error",detail:g.message}}if(ut(n,l))return{status:"ok-via-env-flag",acceptedVars:l};let a=no(e,t,{readConfig:c});return a?{status:"mismatch-can-upload",acceptedVars:l,candidate:a}:{status:"mismatch-no-local",acceptedVars:l}}function ft({uploadAs:e,value:o}){return ve({[e]:o})}function ve(e){let o=we(st(),`zibby-creds-${it(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}`});ot(o,`${t.join(`
19
19
  `)}
20
- `,"utf-8");try{nt(o,384)}catch{}let n=()=>{try{rt(o)}catch{}};return process.on("exit",n),process.on("SIGINT",()=>{n(),process.exit(130)}),o}function dt({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 gt({userConfig:e,workflowDir:o,projectId:t,sessionToken:n,apiUrl:r,deployOptions:i,fetchImpl:s,readConfig:c,prompt:u,log:l=console.log,writeTempBag:d=ve,readFullBlob:x=Xe}){let b=ke(e);if(!b)return{proceed:!0};let h=eo(e),$=oo(o),k=Array.isArray(i?.env)?i.env:[],a=await ro({workflowAgent:b,workflowUuid:$,authChoice:h,envFiles:k,sessionToken:n,apiUrl:r,fetchImpl:s,readConfig:c});switch(a.status){case"ok-already-set":return{proceed:!0};case"ok-via-env-flag":return{proceed:!0};case"mismatch-can-upload":{let{candidate:f}=a,A=u||(async({message:D})=>{let{proceed:S}=await et.prompt([{type:"confirm",name:"proceed",message:D,default:!0}]);return S}),R=typeof f.value=="string"?f.value:"",T=R.length>=4?`***${R.slice(-4)}`:"***",I;f.kind==="oauth"?I=R.startsWith("sk-ant-oat01-")?`OAuth token ${T} \xB7 long-lived setup-token`:`OAuth token ${T} \xB7 Keychain (short-lived, ~30d)`:I=`API key ${T}`;let _=`Cloud workflow has no ${b} credentials. Upload saved ${I}?`,z;try{z=await A({message:_})}catch{z=!1}if(!z)return l(m.yellow(` \u26A0 Deploying without ${f.uploadAs} on the workflow.`)),l(m.yellow(" Trigger will fail until you set it manually:")),l(m.gray(` zibby workflow env set <uuid> ${f.uploadAs}=<your-token>`)),{proceed:!0};let U,O="";if(b==="claude"&&f.kind==="oauth")if(typeof f.value=="string"&&f.value.startsWith("sk-ant-oat01-"))U={CLAUDE_CODE_OAUTH_TOKEN:f.value},O=` (long-lived setup-token \u2026${f.value.slice(-4)} \u2014 no expiry)`;else{let S=x();S&&S.accessToken?(U={CLAUDE_CODE_CREDENTIALS_JSON:JSON.stringify({claudeAiOauth:S}),CLAUDE_CODE_OAUTH_TOKEN:S.accessToken},O=" (Keychain blob \u2014 short-lived, expires ~30 days; run `claude setup-token` for a long-lived token to avoid this)"):U={CLAUDE_CODE_OAUTH_TOKEN:f.value}}else U={[f.uploadAs]:f.value};let G=d(U);return i&&(Array.isArray(i.env)||(i.env=[]),i.env.push(G)),l(m.green(` \u2713 Will upload ${I}${O} to workflow env after deploy.`)),{proceed:!0,addedEnvFile:G}}case"mismatch-no-local":return dt({workflowAgent:b,acceptedVars:a.acceptedVars,projectId:t,log:l}),{proceed:!1};default:return l(m.gray(` (skipped cloud-creds sanity check: ${a.detail||"unknown error"})`)),{proceed:!0}}}var at,lt,io=N(()=>{Ze();me();at={claude:["ANTHROPIC_API_KEY","CLAUDE_CODE_OAUTH_TOKEN"],cursor:["CURSOR_API_KEY"],codex:["OPENAI_API_KEY"],gemini:["GOOGLE_API_KEY"]};lt={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 co={};Ee(co,{listEnvCommand:()=>yt,pushEnvCommand:()=>wt,setEnvCommand:()=>ht,syncEnvFromFiles:()=>kt,unsetEnvCommand:()=>mt});import v 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(v.red("\n Not authenticated \u2014 run `zibby login` or pass --api-key.\n")),process.exit(1)),{authToken:n,apiUrl:j()}}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(u){r&&r.fail(`Network error: ${u.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(v.red(`
20
+ `,"utf-8");try{tt(o,384)}catch{}let n=()=>{try{nt(o)}catch{}};return process.on("exit",n),process.on("SIGINT",()=>{n(),process.exit(130)}),o}function pt({workflowAgent:e,acceptedVars:o,projectId:t,log:n}){n(w.red(` \u2716 No local ${e} credentials found to upload.`)),n(w.red(` Cloud Fargate needs ${o.join(" or ")} in this workflow's env.`)),n(""),n(w.yellow(" Pick one:")),e==="claude"?(n(w.yellow(" A. Set up Claude OAuth (no API costs):")),n(w.gray(" 1. claude (the CLI from @anthropic-ai/claude-code) \u2192 log in, quit")),n(w.gray(" 2. zibby init -f # picks up the token")),n(w.gray(" 3. zibby workflow deploy <name> # we'll upload it")),n(w.yellow(" B. Buy a Claude API key (pay-per-token):")),n(w.gray(" https://console.anthropic.com/settings/keys")),n(w.gray(" zibby workflow env set <uuid> ANTHROPIC_API_KEY=sk-ant-..."))):(n(w.yellow(` A. Get an API key for ${e}:`)),n(w.gray(` zibby workflow env set <uuid> ${o[0]}=<your-key>`))),n(w.yellow(" C. Skip this gate (deploy WILL fail at trigger time):")),n(w.gray(" zibby workflow deploy <name> --no-creds-check")),n(w.gray(" (or set the project-level key at")),n(w.gray(` https://studio.zibby.dev/projects/${t}/settings)`)),n("")}async function dt({userConfig:e,workflowDir:o,projectId:t,sessionToken:n,apiUrl:r,deployOptions:i,fetchImpl:s,readConfig:c,prompt:l,log:a=console.log,writeTempBag:g=ve,readFullBlob:b=Xe}){let y=ke(e);if(!y)return{proceed:!0};let _=eo(e),$=oo(o),u=Array.isArray(i?.env)?i.env:[],f=await ro({workflowAgent:y,workflowUuid:$,authChoice:_,envFiles:u,sessionToken:n,apiUrl:r,fetchImpl:s,readConfig:c});switch(f.status){case"ok-already-set":return{proceed:!0};case"ok-via-env-flag":return{proceed:!0};case"mismatch-can-upload":{let{candidate:p}=f,B=l||(async({message:C})=>{let{proceed:N}=await Xo.prompt([{type:"confirm",name:"proceed",message:C,default:!0}]);return N}),x=typeof p.value=="string"?p.value:"",I=x.length>=4?`***${x.slice(-4)}`:"***",A;p.kind==="oauth"?A=x.startsWith("sk-ant-oat01-")?`OAuth token ${I} \xB7 long-lived setup-token`:`OAuth token ${I} \xB7 Keychain (short-lived, ~30d)`:A=`API key ${I}`;let V=`Cloud workflow has no ${y} credentials. Upload saved ${A}?`,O;try{O=await B({message:V})}catch{O=!1}if(!O)return a(w.yellow(` \u26A0 Deploying without ${p.uploadAs} on the workflow.`)),a(w.yellow(" Trigger will fail until you set it manually:")),a(w.gray(` zibby workflow env set <uuid> ${p.uploadAs}=<your-token>`)),{proceed:!0};let T,z="";if(y==="claude"&&p.kind==="oauth")if(typeof p.value=="string"&&p.value.startsWith("sk-ant-oat01-"))T={CLAUDE_CODE_OAUTH_TOKEN:p.value},z=` (long-lived setup-token \u2026${p.value.slice(-4)} \u2014 no expiry)`;else{let N=b();N&&N.accessToken?(T={CLAUDE_CODE_CREDENTIALS_JSON:JSON.stringify({claudeAiOauth:N}),CLAUDE_CODE_OAUTH_TOKEN:N.accessToken},z=" (Keychain blob \u2014 short-lived, expires ~30 days; run `claude setup-token` for a long-lived token to avoid this)"):T={CLAUDE_CODE_OAUTH_TOKEN:p.value}}else T={[p.uploadAs]:p.value};let F=g(T);return i&&(Array.isArray(i.env)||(i.env=[]),i.env.push(F)),a(w.green(` \u2713 Will upload ${A}${z} to workflow env after deploy.`)),{proceed:!0,addedEnvFile:F}}case"mismatch-no-local":return pt({workflowAgent:y,acceptedVars:f.acceptedVars,projectId:t,log:a}),{proceed:!1};default:return a(w.gray(` (skipped cloud-creds sanity check: ${f.detail||"unknown error"})`)),{proceed:!0}}}var ct,at,io=j(()=>{Ze();me();ct={claude:["ANTHROPIC_API_KEY","CLAUDE_CODE_OAUTH_TOKEN"],cursor:["CURSOR_API_KEY"],codex:["OPENAI_API_KEY"],gemini:["GOOGLE_API_KEY"]};at={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 co={};Ee(co,{listEnvCommand:()=>gt,pushEnvCommand:()=>mt,setEnvCommand:()=>yt,syncEnvFromFiles:()=>wt,unsetEnvCommand:()=>ht});import v 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(v.red("\n Not authenticated \u2014 run `zibby login` or pass --api-key.\n")),process.exit(1)),{authToken:n,apiUrl:S()}}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(l){r&&r.fail(`Network error: ${l.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(v.red(`
21
21
  ${c.error||c.message||`HTTP ${s.status}`}
22
- `)),process.exit(1)),c}async function yt(e,o={}){e||(console.log(v.red(`
22
+ `)),process.exit(1)),c}async function gt(e,o={}){e||(console.log(v.red(`
23
23
  Workflow UUID is required`)),console.log(v.gray(` Usage: zibby workflow env list <uuid>
24
24
  `)),process.exit(1));let{authToken:t,apiUrl:n}=await oe(o),r=ee(`Fetching env keys for ${e}...`).start(),i=await te("GET",L(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(he(s)),i.envUpdatedAt&&console.log(v.gray(`
25
- Last updated: ${i.envUpdatedAt}`)),console.log("")}async function ht(e,o,t={}){(!e||!o)&&(console.log(v.red(`
25
+ Last updated: ${i.envUpdatedAt}`)),console.log("")}async function yt(e,o,t={}){(!e||!o)&&(console.log(v.red(`
26
26
  Both UUID and KEY=value are required`)),console.log(v.gray(` Usage: zibby workflow env set <uuid> KEY=value
27
- `)),process.exit(1));let n,r;try{({key:n,value:r}=We(o))}catch(d){console.log(v.red(`
28
- ${d.message}
29
- `)),process.exit(1)}let{authToken:i,apiUrl:s}=await oe(t),c=ee(`Setting ${n} on workflow ${e}...`).start(),l=((await te("PATCH",L(s,e,n),i,{value:r},c)).keys||[]).length;c.succeed(`Set ${v.cyan(n)} (workflow now has ${l} env var${l===1?"":"s"})`)}async function mt(e,o,t={}){(!e||!o)&&(console.log(v.red(`
27
+ `)),process.exit(1));let n,r;try{({key:n,value:r}=We(o))}catch(g){console.log(v.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",L(s,e,n),i,{value:r},c)).keys||[]).length;c.succeed(`Set ${v.cyan(n)} (workflow now has ${a} env var${a===1?"":"s"})`)}async function ht(e,o,t={}){(!e||!o)&&(console.log(v.red(`
30
30
  Both UUID and KEY are required`)),console.log(v.gray(` Usage: zibby workflow env unset <uuid> KEY
31
31
  `)),process.exit(1)),X(o)||(console.log(v.red(`
32
32
  Invalid env var name "${o}"
33
- `)),process.exit(1));let{authToken:n,apiUrl:r}=await oe(t),i=ee(`Unsetting ${o} on workflow ${e}...`).start(),s=await te("DELETE",L(r,e,o),n,null,i),c=(s.keys||[]).length;s.removed?i.succeed(`Unset ${v.cyan(o)} (workflow now has ${c} env var${c===1?"":"s"})`):i.warn(`Key ${v.cyan(o)} was not set on workflow ${e} \u2014 nothing to do`)}async function wt(e,o={}){e||(console.log(v.red(`
33
+ `)),process.exit(1));let{authToken:n,apiUrl:r}=await oe(t),i=ee(`Unsetting ${o} on workflow ${e}...`).start(),s=await te("DELETE",L(r,e,o),n,null,i),c=(s.keys||[]).length;s.removed?i.succeed(`Unset ${v.cyan(o)} (workflow now has ${c} env var${c===1?"":"s"})`):i.warn(`Key ${v.cyan(o)} was not set on workflow ${e} \u2014 nothing to do`)}async function mt(e,o={}){e||(console.log(v.red(`
34
34
  Workflow UUID is required`)),console.log(v.gray(` Usage: zibby workflow env push <uuid> --file .env [--file .env.prod]
35
35
  `)),process.exit(1));let t=Array.isArray(o.file)?o.file:o.file?[o.file]:[];t.length===0&&(console.log(v.red(`
36
36
  At least one --file is required`)),console.log(v.gray(` Usage: zibby workflow env push <uuid> --file .env
37
- `)),process.exit(1));let n;try{n=V(t)}catch(u){console.log(v.red(`
38
- ${u.message}
37
+ `)),process.exit(1));let n;try{n=M(t)}catch(l){console.log(v.red(`
38
+ ${l.message}
39
39
  `)),process.exit(1)}let r=Object.keys(n);r.length===0&&(console.log(v.yellow(`
40
40
  No env vars found in ${t.join(", ")} \u2014 nothing to push.
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",L(s,e),i,{env:n},c),c.succeed(`Pushed ${r.length} env var${r.length===1?"":"s"} from ${t.join(", ")}`),console.log(""),console.log(he(r)),console.log("")}async function kt({uuid:e,files:o,authToken:t,apiUrl:n,spinner:r}){let i=V(o),s=Object.keys(i);if(s.length===0)return{count:0,files:o};let c=L(n,e),u={method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({env:i})},l=await fetch(c,u);if(!l.ok){let d=await l.json().catch(()=>({}));throw new Error(`Env push failed: ${d.error||d.message||`HTTP ${l.status}`}`)}return r&&(r.text=`Synced ${s.length} env var${s.length===1?"":"s"} to workflow`),{count:s.length,files:o}}var ao=N(()=>{de();Z();me()});import{existsSync as K,readFileSync as be,writeFileSync as vt}from"fs";import{join as P}from"path";import w from"chalk";import ne from"ora";import bt from"dotenv";import{select as lo}from"@inquirer/prompts";import{existsSync as ko}from"fs";import{join as vo}from"path";import{pathToFileURL as bo}from"url";async function _e(e){let o=vo(e,".zibby.config.mjs");if(!ko(o))throw new Error(".zibby.config.mjs not found");try{let t=await import(bo(o).href);return t.default||t}catch(t){throw new Error(`Failed to load .zibby.config.mjs: ${t.message}`,{cause:t})}}Z();import{createHash as xe}from"crypto";import{readFileSync as $o,readdirSync as Ao,statSync as Eo,existsSync as _o}from"fs";import{join as xo,sep as Io}from"path";function Ie(e){let o=ae(e);o.sort((n,r)=>n.rel<r.rel?-1:n.rel>r.rel?1:0);let t=xe("sha256");for(let{rel:n,abs:r}of o){let i=xe("sha256").update($o(r)).digest("hex");t.update(`${n}
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",L(s,e),i,{env:n},c),c.succeed(`Pushed ${r.length} env var${r.length===1?"":"s"} from ${t.join(", ")}`),console.log(""),console.log(he(r)),console.log("")}async function wt({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=L(n,e),l={method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({env:i})},a=await fetch(c,l);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 ao=j(()=>{de();Z();me()});import{existsSync as R,readFileSync as be,writeFileSync as kt}from"fs";import{join as P}from"path";import k from"chalk";import ne from"ora";import vt from"dotenv";import{select as lo}from"@inquirer/prompts";import{existsSync as wo}from"fs";import{join as ko}from"path";import{pathToFileURL as vo}from"url";async function _e(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();import{createHash as xe}from"crypto";import{readFileSync as bo,readdirSync as $o,statSync as Ao,existsSync as Eo}from"fs";import{join as _o,sep as xo}from"path";function Ie(e){let o=ae(e);o.sort((n,r)=>n.rel<r.rel?-1:n.rel>r.rel?1:0);let t=xe("sha256");for(let{rel:n,abs:r}of o){let i=xe("sha256").update(bo(r)).digest("hex");t.update(`${n}
42
42
  ${i}
43
- `)}return t.digest("hex")}function ae(e){let o=new Set(["node_modules",".git","dist",".zibby","__tests__","__mocks__"]),t=[/^\.zibby-deploy\.json$/,/^\.DS_Store$/,/\.test\.[mc]?js$/,/\.spec\.[mc]?js$/],n=[];if(!_o(e))return n;function r(s){return t.some(c=>c.test(s))}function i(s,c){for(let u of To(s)){let l=xo(s,u),d;try{d=Eo(l)}catch{continue}if(d.isDirectory()){if(o.has(u))continue;let b=c?`${c}/${u}`:u;i(l,b);continue}if(!d.isFile()||r(u))continue;let x=(c?`${c}/${u}`:u).split(Io).join("/");n.push({rel:x,abs:l})}}return i(e,""),n}function To(e){try{return Ao(e)}catch{return[]}}function Te(e,o){return e?.uuid||e?.workflowUuid||o?.uuid||null}var So=4;function le({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}/${So}] ${t.label}${r}`:o?`Building bundle on Zibby Cloud... (${o.toLowerCase()})${r}`:`Building bundle on Zibby Cloud...${r}`}var Uo=/\[(\d+)\/\d+\]\s+(.+?)\s*\.{0,3}\s*$/;function Se(e){if(!e)return null;let o=Uo.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 Ue(){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(!jo(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 jo(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 je({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()}}de();bt.config();async function $t({apiUrl:e,projectId:o,workflowName:t,buildId:n,authToken:r,spinner:i,verbose:s}){let c=Date.now(),u,l=null,d=null,x=Ue(),b=setInterval(()=>{i.text=le({elapsedMs:Date.now()-c,phase:l,step:d})},1e3);try{for(;;){let h=new URL(`${e}/projects/${o}/workflows/${t}/build/${n}`);u&&h.searchParams.set("logsToken",u);let $;try{let k=await fetch(h,{headers:{Authorization:`Bearer ${r}`}});if(!k.ok)throw new Error(`HTTP ${k.status}`);$=await k.json()}catch{await new Promise(a=>setTimeout(a,2e3));continue}$.phase&&$.phase!==l&&(l=$.phase),$.nextLogsToken&&$.nextLogsToken!==u&&(u=$.nextLogsToken);for(let k of $.logEvents||[]){let a=String(k.m||"").trimEnd();if(!a)continue;let f=Se(a);if(f&&(d=f),s){process.stdout.write(` ${a}
44
- `);continue}x(a)||f||process.stdout.write(` ${a}
45
- `)}if(i.text=le({elapsedMs:Date.now()-c,phase:l,step:d}),$.done){let k=(Date.now()-c)/1e3;return{status:$.status,elapsedSec:k,lastPhase:l}}await new Promise(k=>setTimeout(k,2e3))}}finally{clearInterval(b)}}async function At(e,o){let t=j(),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(l=>{let d=l.projectId||l.id||l._id||"unknown";return{name:`${l.name||l.projectName||"Unnamed"} (${d})`,value:d}});return await lo({message:"Select a project to deploy to:",choices:c})}catch(r){n.fail(`Error: ${r.message}`),process.exit(1)}}async function Mn(e,o={}){let t=process.cwd(),n="workflows",r=null;try{r=await _e(t),n=r?.paths?.workflows||"workflows"}catch{}if(e){let a=P(t,n,e);K(a)||(console.log(`
43
+ `)}return t.digest("hex")}function ae(e){let o=new Set(["node_modules",".git","dist",".zibby","__tests__","__mocks__"]),t=[/^\.zibby-deploy\.json$/,/^\.DS_Store$/,/\.test\.[mc]?js$/,/\.spec\.[mc]?js$/],n=[];if(!Eo(e))return n;function r(s){return t.some(c=>c.test(s))}function i(s,c){for(let l of Io(s)){let a=_o(s,l),g;try{g=Ao(a)}catch{continue}if(g.isDirectory()){if(o.has(l))continue;let y=c?`${c}/${l}`:l;i(a,y);continue}if(!g.isFile()||r(l))continue;let b=(c?`${c}/${l}`:l).split(xo).join("/");n.push({rel:b,abs:a})}}return i(e,""),n}function Io(e){try{return $o(e)}catch{return[]}}function Te(e,o){return e?.uuid||e?.workflowUuid||o?.uuid||null}var To=4;function le({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}/${To}] ${t.label}${r}`:o?`Building bundle on Zibby Cloud... (${o.toLowerCase()})${r}`:`Building bundle on Zibby Cloud...${r}`}var So=/\[(\d+)\/\d+\]\s+(.+?)\s*\.{0,3}\s*$/;function Se(e){if(!e)return null;let o=So.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 Ue(){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(!Uo(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 Uo(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 je({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()}}de();vt.config();async function bt({apiUrl:e,projectId:o,workflowName:t,buildId:n,authToken:r,spinner:i,verbose:s}){let c=Date.now(),l,a=null,g=null,b=Ue(),y=setInterval(()=>{i.text=le({elapsedMs:Date.now()-c,phase:a,step:g})},1e3);try{for(;;){let _=new URL(`${e}/projects/${o}/workflows/${t}/build/${n}`);l&&_.searchParams.set("logsToken",l);let $;try{let u=await fetch(_,{headers:{Authorization:`Bearer ${r}`}});if(!u.ok)throw new Error(`HTTP ${u.status}`);$=await u.json()}catch{await new Promise(f=>setTimeout(f,2e3));continue}$.phase&&$.phase!==a&&(a=$.phase),$.nextLogsToken&&$.nextLogsToken!==l&&(l=$.nextLogsToken);for(let u of $.logEvents||[]){let f=String(u.m||"").trimEnd();if(!f)continue;let p=Se(f);if(p&&(g=p),s){process.stdout.write(` ${f}
44
+ `);continue}b(f)||p||process.stdout.write(` ${f}
45
+ `)}if(i.text=le({elapsedMs:Date.now()-c,phase:a,step:g}),$.done){let u=(Date.now()-c)/1e3;return{status:$.status,elapsedSec:u,lastPhase:a}}await new Promise(u=>setTimeout(u,2e3))}}finally{clearInterval(y)}}async function $t(e,o){let t=S(),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 lo({message:"Select a project to deploy to:",choices:c})}catch(r){n.fail(`Error: ${r.message}`),process.exit(1)}}async function Hn(e,o={}){let t=process.cwd(),n="workflows",r=null;try{r=await _e(t),n=r?.paths?.workflows||"workflows"}catch{}if(e){let u=P(t,n,e);R(u)||(console.log(`
46
46
  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}
47
- `),process.exit(1))}else{let a=P(t,n);K(a)||(console.log(`
47
+ `),process.exit(1))}else{let u=P(t,n);R(u)||(console.log(`
48
48
  Error: No workflows found in ${n}/`),console.log(` Create one with: zibby workflow new <name>
49
- `),process.exit(1));let{readdir:f,stat:A}=await import("fs/promises"),R=await f(a),T=[];for(let I of R){let _=P(a,I);if(!(await A(_)).isDirectory())continue;(K(P(_,"graph.mjs"))||K(P(_,"graph.js")))&&T.push(I)}T.length===0&&(console.log(`
49
+ `),process.exit(1));let{readdir:f,stat:p}=await import("fs/promises"),B=await f(u),x=[];for(let I of B){let A=P(u,I);if(!(await p(A)).isDirectory())continue;(R(P(A,"graph.mjs"))||R(P(A,"graph.js")))&&x.push(I)}x.length===0&&(console.log(`
50
50
  Error: No workflows found in ${n}/`),console.log(` Create one with: zibby workflow new <name>
51
- `),process.exit(1)),console.log(""),e=await lo({message:"Select a workflow to deploy:",choices:T.map(I=>({name:I,value:I}))})}let{sessionToken:i,apiKey:s}=await q({apiKey:o.apiKey}),c=o.project||process.env.ZIBBY_PROJECT_ID;c||(console.log(""),c=await At(s,i));let u=i||s,l=P(t,n,e),d=P(l,"graph.mjs"),x=P(l,"workflow.json");K(d)||(console.log(`
52
- Error: graph.mjs not found in ${n}/${e}/`),process.exit(1));let b=(()=>{try{return Ie(l)}catch(a){return console.log(w.gray(` (checksum skipped: ${a.message})`)),null}})();if(!o.force&&b)try{let a=j(),f=await fetch(`${a}/projects/${c}/workflows/${e}`,{headers:{Authorization:`Bearer ${u}`}});if(f.ok){let A=await f.json();if(A&&A.sourceChecksum===b){console.log(""),console.log(`Already up to date. ${w.gray("(use --force to redeploy)")}`),console.log("");return}}}catch(a){console.log(w.gray(` (checksum lookup failed: ${a.message} \u2014 proceeding with deploy)`))}if(o.credsCheck!==!1)try{let{runCloudCredsCheck:a}=await Promise.resolve().then(()=>(io(),so));(await a({userConfig:r,workflowDir:l,projectId:c,sessionToken:u,apiUrl:j(),deployOptions:o})).proceed||(console.log(""),process.exit(1))}catch(a){console.log(w.gray(` (creds-check skipped: ${a.message})`))}console.log(`
51
+ `),process.exit(1)),console.log(""),e=await lo({message:"Select a workflow to deploy:",choices:x.map(I=>({name:I,value:I}))})}let{sessionToken:i,apiKey:s}=await q({apiKey:o.apiKey}),c=o.project||process.env.ZIBBY_PROJECT_ID;c||(console.log(""),c=await $t(s,i));let l=i||s,a=P(t,n,e),g=P(a,"graph.mjs");R(g)||(console.log(`
52
+ Error: graph.mjs not found in ${n}/${e}/`),process.exit(1));let b=(()=>{try{return Ie(a)}catch(u){return console.log(k.gray(` (checksum skipped: ${u.message})`)),null}})();if(!o.force&&b)try{let u=S(),f=await fetch(`${u}/projects/${c}/workflows/${e}`,{headers:{Authorization:`Bearer ${l}`}});if(f.ok){let p=await f.json();if(p&&p.sourceChecksum===b){console.log(""),console.log(`Already up to date. ${k.gray("(use --force to redeploy)")}`),console.log("");return}}}catch(u){console.log(k.gray(` (checksum lookup failed: ${u.message} \u2014 proceeding with deploy)`))}if(o.credsCheck!==!1)try{let{runCloudCredsCheck:u}=await Promise.resolve().then(()=>(io(),so));(await u({userConfig:r,workflowDir:a,projectId:c,sessionToken:l,apiUrl:S(),deployOptions:o})).proceed||(console.log(""),process.exit(1))}catch(u){console.log(k.gray(` (creds-check skipped: ${u.message})`))}console.log(`
53
53
  Deploying Workflow
54
- `),console.log(" ".padEnd(60,"-")),console.log(` Workflow: ${e}`),console.log(` Project: ${c}`),console.log(" ".padEnd(60,"-")),console.log("");let h=ne("Validating workflow...").start(),$=be(d,"utf-8");if($.includes("@zibby/core")||$.includes("@zibby/skills")){let a=P(l,"package.json");K(a)||(h.fail("Missing package.json"),console.log(""),console.log(w.red(" \u2717 graph.mjs imports @zibby packages but no package.json found")),console.log(""),console.log(w.yellow(" Create package.json with:")),console.log(""),console.log(w.gray(" {")),console.log(w.gray(' "type": "module",')),console.log(w.gray(' "dependencies": {')),console.log(w.gray(' "@zibby/core": "workspace:*"')),console.log(w.gray(" }")),console.log(w.gray(" }")),console.log(""),process.exit(1));let f=JSON.parse(be(a,"utf-8"));!{...f.dependencies,...f.devDependencies}["@zibby/core"]&&$.includes("@zibby/core")&&(h.fail("Missing @zibby/core dependency"),console.log(""),console.log(w.red(" \u2717 graph.mjs imports @zibby/core but it's not in package.json")),console.log(""),console.log(w.yellow(" Add to package.json dependencies:")),console.log(w.gray(' "@zibby/core": "workspace:*"')),console.log(""),process.exit(1))}h.text="Loading workflow graph...";try{let{pathToFileURL:a}=await import("url"),f=await import(a(d).href),A;if(f.default)if(typeof f.default=="function"){let p=f.default.prototype;p&&p.buildGraph?A=new f.default:A=f.default()}else h.fail("graph.mjs must export a class or factory function"),process.exit(1);else{let p=Object.values(f).find(y=>y.prototype&&y.prototype.buildGraph);p?A=new p:(h.fail("graph.mjs must export a WorkflowAgent class or factory function"),process.exit(1))}let T=A.buildGraph().serialize(),{readFile:I}=await import("fs/promises"),_={};h.text="Packaging workflow sources...";let z=ae(l);for(let{rel:p,abs:y}of z)_[p]=await I(y,"utf-8");let U=null;if(_["workflow.json"])try{let p=JSON.parse(_["workflow.json"]);p&&typeof p.triggers=="object"&&(U=p.triggers)}catch{}r&&typeof r=="object"&&(delete _["zibby.config.mjs"],_["zibby.config.json"]=JSON.stringify(r,null,2)),h.text=`Uploading to cloud (${T.nodes.size||Object.keys(T.nodes||{}).length} nodes, ${Object.keys(_).length} files)...`;let O=j(),G=JSON.stringify({format:1,sources:_}),D=Buffer.byteLength(G,"utf8"),S=await fetch(`${O}/projects/${c}/workflows/${e}/sources/presign`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`},body:JSON.stringify({contentLength:D})});if(!S.ok){let p=await S.json().catch(()=>({}));h.fail("Deploy failed (presign)"),console.log(` Error: ${p.error||p.message||S.statusText}
55
- `),process.exit(1)}let $e=await S.json(),{uploadUrl:uo,key:fo,headers:po}=$e,re=await fetch(uo,{method:"PUT",headers:{...po||{},"Content-Length":String(D)},body:G});if(!re.ok){let p=await re.text().catch(()=>"");h.fail("Deploy failed (S3 upload)"),console.log(` S3 PUT failed: ${re.status} ${p.slice(0,200)}
56
- `),process.exit(1)}h.text="Saving workflow definition...";let Y=await fetch(`${O}/projects/${c}/workflows/${e}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`},body:JSON.stringify({graph:T,sourcesStagingKey:fo,isDefault:!1,...b?{sourceChecksum:b}:{},...typeof o.warm=="number"?{warmEnabled:!0,warmCount:o.warm}:o.warm===!1?{warmEnabled:!1,warmCount:0}:{},...U?{triggers:U}:{}})});if(!Y.ok){let p=await Y.json().catch(()=>({})),y=p.message||p.error||Y.statusText;if(h.fail(`Deploy failed (${Y.status})`),console.log(""),Y.status===402){let E=y.match(/(https?:\/\/\S+)/),ce=E?y.replace(E[0],"").replace(/Upgrade at\s*$/i,"").trim():y;console.log(` \u{1F4B3} ${w.yellow("Payment required")}`),console.log(""),console.log(` ${ce}`),E&&(console.log(""),console.log(` Upgrade: ${w.cyan(E[0])}`)),console.log("")}else console.log(` Error: ${y}
57
- `);process.exit(1)}let se=await Y.json(),J=P(l,".zibby-deploy.json"),ie=K(J)?(()=>{try{return JSON.parse(be(J,"utf-8"))}catch{return null}})():null,C=Te(se,ie);if(C){let p=je({uuid:C,name:e,projectId:c,result:se,existingManifest:ie});try{vt(J,`${JSON.stringify(p,null,2)}
58
- `,"utf-8")}catch(y){console.log(` Warning: failed to write ${J}: ${y.message}`)}}let go=ie?"Updated":"Deployed";if(h.succeed(`${go} ${e} (v${se.version||1})`),typeof o.warm=="number"?console.log(` ${w.cyan("\u25CF")} Warm pool: ${o.warm} task${o.warm===1?"":"s"} (paid feature \u2014 provisioning may take ~60s)`):o.warm===!1&&console.log(` ${w.gray("\u25CB")} Warm pool: disabled (workflow uses default cold-start path)`),!(o.noWait===!0||process.env.ZIBBY_DEPLOY_NO_BUNDLE==="1")){console.log("");let p=ne("Building bundle on Zibby Cloud...").start();try{let y=await fetch(`${O}/projects/${c}/workflows/${e}/build`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`}});if(y.ok){let E=await y.json(),{buildId:ce}=E,yo=o.verbose===!0||process.env.ZIBBY_DEPLOY_VERBOSE==="1",{status:Ae,elapsedSec:ho,lastPhase:mo}=await $t({apiUrl:O,projectId:c,workflowName:e,buildId:ce,authToken:u,spinner:p,verbose:yo});Ae==="SUCCEEDED"?p.succeed(`Bundle ready (${ho.toFixed(1)}s) \u2014 runtime npm install eliminated`):p.warn(`Bundle build ${Ae} at phase ${mo||"unknown"} \u2014 workflow will fall back to runtime install`)}else{let E=await y.json().catch(()=>({}));p.warn(`Bundle build skipped: ${E.error||E.message||y.statusText}`),console.log(` Workflow will use slower runtime install path until next deploy.
59
- `)}}catch(y){p.warn(`Bundle build error: ${y.message}`)}}let F=Array.isArray(o.env)?o.env:o.env?[o.env]:[];if(F.length>0)if(!C)console.log(w.yellow(" Skipping --env sync: deploy did not return a workflow UUID."));else{console.log("");let p=ne(`Syncing env from ${F.join(", ")}...`).start();try{let{syncEnvFromFiles:y}=await Promise.resolve().then(()=>(ao(),co)),{count:E}=await y({uuid:C,files:F,authToken:u,apiUrl:O,spinner:p});E===0?p.warn(`No env vars found in ${F.join(", ")} \u2014 workflow env unchanged.`):p.succeed(`Synced ${E} env var${E===1?"":"s"} from ${F.join(", ")}`)}catch(y){p.fail(`Env sync failed: ${y.message}`),console.log(w.gray(` Re-run after fixing: zibby workflow env push ${C} ${F.map(E=>`--file ${E}`).join(" ")}
60
- `))}}console.log(""),C&&console.log(` UUID: ${C}`),console.log(""),console.log(" Next steps:"),console.log(` zibby workflow run ${e} Run locally`),C&&console.log(` zibby workflow trigger ${C} Run in cloud`),console.log(" zibby workflow list View all workflows"),console.log("")}catch(a){h.fail("Deploy failed"),console.log(` Error: ${a.message}
61
- `),process.exit(1)}}export{Mn as deployWorkflowCommand};
54
+ `),console.log(" ".padEnd(60,"-")),console.log(` Workflow: ${e}`),console.log(` Project: ${c}`),console.log(" ".padEnd(60,"-")),console.log("");let y=ne("Validating workflow...").start(),_=be(g,"utf-8");if(_.includes("@zibby/core")||_.includes("@zibby/skills")){let u=P(a,"package.json");R(u)||(y.fail("Missing package.json"),console.log(""),console.log(k.red(" \u2717 graph.mjs imports @zibby packages but no package.json found")),console.log(""),console.log(k.yellow(" Create package.json with:")),console.log(""),console.log(k.gray(" {")),console.log(k.gray(' "type": "module",')),console.log(k.gray(' "dependencies": {')),console.log(k.gray(' "@zibby/core": "workspace:*"')),console.log(k.gray(" }")),console.log(k.gray(" }")),console.log(""),process.exit(1));let f=JSON.parse(be(u,"utf-8"));!{...f.dependencies,...f.devDependencies}["@zibby/core"]&&_.includes("@zibby/core")&&(y.fail("Missing @zibby/core dependency"),console.log(""),console.log(k.red(" \u2717 graph.mjs imports @zibby/core but it's not in package.json")),console.log(""),console.log(k.yellow(" Add to package.json dependencies:")),console.log(k.gray(' "@zibby/core": "workspace:*"')),console.log(""),process.exit(1))}y.text="Loading workflow graph...";try{let{pathToFileURL:u}=await import("url"),f=await import(u(g).href),p;if(f.default)if(typeof f.default=="function"){let d=f.default.prototype;d&&d.buildGraph?p=new f.default:p=f.default()}else y.fail("graph.mjs must export a class or factory function"),process.exit(1);else{let d=Object.values(f).find(m=>m.prototype&&m.prototype.buildGraph);d?p=new d:(y.fail("graph.mjs must export a WorkflowAgent class or factory function"),process.exit(1))}let x=p.buildGraph().serialize(),{readFile:I}=await import("fs/promises"),A={};y.text="Packaging workflow sources...";let V=ae(a);for(let{rel:d,abs:m}of V)A[d]=await I(m,"utf-8");let O=null;if(A["workflow.json"])try{let d=JSON.parse(A["workflow.json"]);d&&typeof d.triggers=="object"&&(O=d.triggers)}catch{}r&&typeof r=="object"&&(delete A["zibby.config.mjs"],A["zibby.config.json"]=JSON.stringify(r,null,2)),y.text=`Uploading to cloud (${x.nodes.size||Object.keys(x.nodes||{}).length} nodes, ${Object.keys(A).length} files)...`;let T=S(),z=JSON.stringify({format:1,sources:A}),F=Buffer.byteLength(z,"utf8"),C=await fetch(`${T}/projects/${c}/workflows/${e}/sources/presign`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({contentLength:F})});if(!C.ok){let d=await C.json().catch(()=>({}));y.fail("Deploy failed (presign)"),console.log(` Error: ${d.error||d.message||C.statusText}
55
+ `),process.exit(1)}let N=await C.json(),{uploadUrl:$e,key:uo,headers:fo}=N,re=await fetch($e,{method:"PUT",headers:{...fo||{},"Content-Length":String(F)},body:z});if(!re.ok){let d=await re.text().catch(()=>"");y.fail("Deploy failed (S3 upload)"),console.log(` S3 PUT failed: ${re.status} ${d.slice(0,200)}
56
+ `),process.exit(1)}y.text="Saving workflow definition...";let D=await fetch(`${T}/projects/${c}/workflows/${e}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({graph:x,sourcesStagingKey:uo,isDefault:!1,...b?{sourceChecksum:b}:{},...typeof o.warm=="number"?{warmEnabled:!0,warmCount:o.warm}:o.warm===!1?{warmEnabled:!1,warmCount:0}:{},...O?{triggers:O}:{}})});if(!D.ok){let d=await D.json().catch(()=>({})),m=d.message||d.error||D.statusText;if(y.fail(`Deploy failed (${D.status})`),console.log(""),D.status===402){let E=m.match(/(https?:\/\/\S+)/),ce=E?m.replace(E[0],"").replace(/Upgrade at\s*$/i,"").trim():m;console.log(` \u{1F4B3} ${k.yellow("Payment required")}`),console.log(""),console.log(` ${ce}`),E&&(console.log(""),console.log(` Upgrade: ${k.cyan(E[0])}`)),console.log("")}else console.log(` Error: ${m}
57
+ `);process.exit(1)}let se=await D.json(),J=P(a,".zibby-deploy.json"),ie=R(J)?(()=>{try{return JSON.parse(be(J,"utf-8"))}catch{return null}})():null,U=Te(se,ie);if(U){let d=je({uuid:U,name:e,projectId:c,result:se,existingManifest:ie});try{kt(J,`${JSON.stringify(d,null,2)}
58
+ `,"utf-8")}catch(m){console.log(` Warning: failed to write ${J}: ${m.message}`)}}let po=ie?"Updated":"Deployed";if(y.succeed(`${po} ${e} (v${se.version||1})`),typeof o.warm=="number"?console.log(` ${k.cyan("\u25CF")} Warm pool: ${o.warm} task${o.warm===1?"":"s"} (paid feature \u2014 provisioning may take ~60s)`):o.warm===!1&&console.log(` ${k.gray("\u25CB")} Warm pool: disabled (workflow uses default cold-start path)`),!(o.noWait===!0||process.env.ZIBBY_DEPLOY_NO_BUNDLE==="1")){console.log("");let d=ne("Building bundle on Zibby Cloud...").start();try{let m=await fetch(`${T}/projects/${c}/workflows/${e}/build`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`}});if(m.ok){let E=await m.json(),{buildId:ce}=E,go=o.verbose===!0||process.env.ZIBBY_DEPLOY_VERBOSE==="1",{status:Ae,elapsedSec:yo,lastPhase:ho}=await bt({apiUrl:T,projectId:c,workflowName:e,buildId:ce,authToken:l,spinner:d,verbose:go});Ae==="SUCCEEDED"?d.succeed(`Bundle ready (${yo.toFixed(1)}s) \u2014 runtime npm install eliminated`):d.warn(`Bundle build ${Ae} at phase ${ho||"unknown"} \u2014 workflow will fall back to runtime install`)}else{let E=await m.json().catch(()=>({}));d.warn(`Bundle build skipped: ${E.error||E.message||m.statusText}`),console.log(` Workflow will use slower runtime install path until next deploy.
59
+ `)}}catch(m){d.warn(`Bundle build error: ${m.message}`)}}let Y=Array.isArray(o.env)?o.env:o.env?[o.env]:[];if(Y.length>0)if(!U)console.log(k.yellow(" Skipping --env sync: deploy did not return a workflow UUID."));else{console.log("");let d=ne(`Syncing env from ${Y.join(", ")}...`).start();try{let{syncEnvFromFiles:m}=await Promise.resolve().then(()=>(ao(),co)),{count:E}=await m({uuid:U,files:Y,authToken:l,apiUrl:T,spinner:d});E===0?d.warn(`No env vars found in ${Y.join(", ")} \u2014 workflow env unchanged.`):d.succeed(`Synced ${E} env var${E===1?"":"s"} from ${Y.join(", ")}`)}catch(m){d.fail(`Env sync failed: ${m.message}`),console.log(k.gray(` Re-run after fixing: zibby workflow env push ${U} ${Y.map(E=>`--file ${E}`).join(" ")}
60
+ `))}}console.log(""),U&&console.log(` UUID: ${U}`),console.log(""),console.log(" Next steps:"),console.log(` zibby workflow run ${e} Run locally`),U&&console.log(` zibby workflow trigger ${U} Run in cloud`),console.log(" zibby workflow list View all workflows"),console.log("")}catch(u){y.fail("Deploy failed"),console.log(` Error: ${u.message}
61
+ `),process.exit(1)}}export{Hn as deployWorkflowCommand};
@@ -73,7 +73,7 @@ ${s}`),console.log(i.white(" Last 10 runs:"));for(let r of t.recent.slice(0,10)
73
73
  npm install @zibby/ui-memory # add the package
74
74
  brew install dolt # macOS
75
75
  # or: curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash
76
- `});var Oo={};L(Oo,{setupCiCommand:()=>sn,setupPlaywrightMcpCommand:()=>jo,testWithVideoCommand:()=>an});import{spawn as Se,execSync as Pe}from"child_process";import{join as Z,dirname as _e,resolve as Io}from"path";import{readFileSync as So,writeFileSync as Po,existsSync as X,mkdirSync as _o}from"fs";import{homedir as Eo}from"os";import{createRequire as Vt}from"module";import I from"chalk";function Jt(){try{return _e(Ie.resolve("@zibby/core/package.json"))}catch{return null}}function zo(o){try{return Pe(`command -v ${o}`,{stdio:"pipe"}),!0}catch{return!1}}function qt(){try{let o=Ie.resolve("@zibby/mcp-browser/bin/mcp-browser-zibby.js");if(X(o))return o}catch{}try{let o=Ie.resolve("@playwright/mcp/package.json"),e=_e(o),t=JSON.parse(So(o,"utf-8")),s=typeof t.bin=="string"?t.bin:t.bin?.["playwright-mcp"];if(s){let r=Z(e,s);if(X(r))return r}let n=Z(e,"cli.js");if(X(n))return n}catch{}return null}function Ao(o,e,t={}){return new Promise((s,n)=>{let r=Se(o,e,{stdio:"inherit",...t});r.on("close",u=>s(u??1)),r.on("error",n)})}async function Xt(o){return zo("playwright")?await Ao("playwright",["install","ffmpeg"],{cwd:o})===0:await Ao("npx",["--yes","playwright","install","ffmpeg"],{cwd:o})===0}function Qt({headed:o=!1,viewport:e=null}){let t=process.execPath,s=_e(t),n=qt(),r=Number(e?.width)||1280,u=Number(e?.height)||720,l=`${r}x${u}`,a=[];a.push(`--viewport-size=${l}`,"--output-dir=test-results"),o||a.push("--headless");let g;n?g={command:t,args:[n,...a],env:{PATH:`${s}:/usr/bin:/bin:/usr/sbin:/sbin`}}:g={command:"npx",args:["-y","@playwright/mcp",...a],env:{PATH:`${s}:/usr/bin:/bin:/usr/sbin:/sbin`}},g.description="Zibby MCP Browser - Playwright MCP with Zibby defaults";let f=Z(Eo(),".cursor"),w=Z(f,"mcp.json");X(f)||_o(f,{recursive:!0});let m={mcpServers:{}};if(X(w))try{m=JSON.parse(So(w,"utf-8")),(!m.mcpServers||typeof m.mcpServers!="object")&&(m.mcpServers={})}catch{m={mcpServers:{}}}m.mcpServers["playwright-official"]=g,Po(w,`${JSON.stringify(m,null,2)}
76
+ `});var Oo={};L(Oo,{setupCiCommand:()=>sn,setupPlaywrightMcpCommand:()=>jo,testWithVideoCommand:()=>an});import{spawn as Se,execSync as Pe}from"child_process";import{join as Z,dirname as _e,resolve as Io}from"path";import{readFileSync as So,writeFileSync as Po,existsSync as X,mkdirSync as _o}from"fs";import{homedir as Eo}from"os";import{createRequire as Vt}from"module";import I from"chalk";function Jt(){try{return _e(Ie.resolve("@zibby/core/package.json"))}catch{return null}}function zo(o){try{return Pe(`command -v ${o}`,{stdio:"pipe"}),!0}catch{return!1}}function qt(){try{let o=Ie.resolve("@zibby/mcp-browser/dist/bin/mcp-browser-zibby.js");if(X(o))return o}catch{}try{let o=Ie.resolve("@playwright/mcp/package.json"),e=_e(o),t=JSON.parse(So(o,"utf-8")),s=typeof t.bin=="string"?t.bin:t.bin?.["playwright-mcp"];if(s){let r=Z(e,s);if(X(r))return r}let n=Z(e,"cli.js");if(X(n))return n}catch{}return null}function Ao(o,e,t={}){return new Promise((s,n)=>{let r=Se(o,e,{stdio:"inherit",...t});r.on("close",u=>s(u??1)),r.on("error",n)})}async function Xt(o){return zo("playwright")?await Ao("playwright",["install","ffmpeg"],{cwd:o})===0:await Ao("npx",["--yes","playwright","install","ffmpeg"],{cwd:o})===0}function Qt({headed:o=!1,viewport:e=null}){let t=process.execPath,s=_e(t),n=qt(),r=Number(e?.width)||1280,u=Number(e?.height)||720,l=`${r}x${u}`,a=[];a.push(`--viewport-size=${l}`,"--output-dir=test-results"),o||a.push("--headless");let g;n?g={command:t,args:[n,...a],env:{PATH:`${s}:/usr/bin:/bin:/usr/sbin:/sbin`}}:g={command:"npx",args:["-y","@playwright/mcp",...a],env:{PATH:`${s}:/usr/bin:/bin:/usr/sbin:/sbin`}},g.description="Zibby MCP Browser - Playwright MCP with Zibby defaults";let f=Z(Eo(),".cursor"),w=Z(f,"mcp.json");X(f)||_o(f,{recursive:!0});let m={mcpServers:{}};if(X(w))try{m=JSON.parse(So(w,"utf-8")),(!m.mcpServers||typeof m.mcpServers!="object")&&(m.mcpServers={})}catch{m={mcpServers:{}}}m.mcpServers["playwright-official"]=g,Po(w,`${JSON.stringify(m,null,2)}
77
77
  `,"utf-8")}async function en(){let o=Jt();if(!o)return;let e=Z(o,"scripts","patch-cursor-mcp.js");if(X(e))try{await new Promise((t,s)=>{let n=Se(process.execPath,[e],{cwd:process.cwd(),stdio:"ignore"});n.on("close",r=>t(r??0)),n.on("error",s)})}catch{}}function on(o){return Io(o).replace(/^\/+/,"").replace(/\//g,"-")}function tn(o){let e=String(o||""),t=e.split(`
78
78
  `).find(r=>/playwright-official/i.test(r)&&/APPROVAL|🔑/i.test(r));if(t){let r=t.match(/=>\s*(\S+)/);if(r)return r[1]}let s=e.match(/playwright-official[^=]*=>\s*(\S+)/);if(s)return s[1];let n=e.match(/playwright-official-[a-f0-9]+/i);return n?n[0]:null}function nn(o,e){let t=on(o),s=Z(Eo(),".cursor","projects",t);_o(s,{recursive:!0});let n=Z(s,"mcp-approvals.json");return Po(n,`${JSON.stringify([e],null,2)}
79
79
  `,"utf-8"),n}function Co(o){try{return Pe("cursor-agent mcp list",{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:process.env,maxBuffer:2*1024*1024})}catch(e){let t=e.stdout!=null?String(e.stdout):"",s=e.stderr!=null?String(e.stderr):"";return t+s}}function rn(o){try{return Pe("cursor-agent mcp enable playwright-official",{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:process.env,maxBuffer:1024*1024}),!0}catch{return!1}}async function jo(o={}){let e=!!o.headed,t=o.viewport||{width:1280,height:720};if(!process.execPath)throw new Error("Node.js runtime not found");let s=await Xt(process.cwd());console.log(s?I.gray(" \u2713 ffmpeg installed for Playwright video"):I.yellow(" \u26A0 Could not install ffmpeg (video may be unavailable)")),Qt({headed:e,viewport:t}),await en();let n=Io(process.cwd());if(zo("cursor-agent")){Co(n);let r=rn(n);r&&console.log(I.gray(" \u2713 cursor-agent: mcp enable playwright-official"));let u=Co(n),l=tn(u);if(l)try{let a=nn(n,l);console.log(I.gray(` \u2713 MCP auto-approval key saved (${a})`))}catch(a){console.log(I.yellow(` \u26A0 Could not write mcp-approvals.json: ${a.message}`))}else r||(console.log(I.yellow(" \u26A0 Could not auto-approve MCP (mcp enable failed and no approval key in cursor-agent output)")),console.log(I.gray(" Try: cursor-agent mcp enable playwright-official")))}else console.log(I.yellow(" \u26A0 cursor-agent not found; install it to use Cursor MCP tools"))}async function sn(o){try{console.log(I.cyan(`
@@ -579,7 +579,7 @@ Analyze the input and return a summary with a status.\`,
579
579
  outputSchema: ExampleOutputSchema,
580
580
  };
581
581
  `}function Yo(o,e){return`${JSON.stringify({name:o,description:`${e} workflow`,entryClass:e,triggers:{api:!0}},null,2)}
582
- `}var Xn=new Set(["cwd","sessionPath","outputPath","context","input"]);async function Qn(o){try{let e=await Dn(S(o,"graph.mjs"),"utf-8"),t=new Set,s=/addNode\(\s*['"`]([A-Za-z_][\w-]*)['"`]/g,n;for(;(n=s.exec(e))!==null;)t.add(n[1]);return t}catch{return new Set}}async function er(o){try{let e=await import(`@zibby/core/templates/${o}/state.js`);for(let t of Object.values(e))if(!(!t||typeof t!="object"))try{let s=t.shape;if(s&&typeof s=="object"&&Object.keys(s).length>0)return{schema:t,shape:s}}catch{}return null}catch{return null}}function or(o,e){try{let t=[],s=[];for(let[n,r]of Object.entries(o)){if(Xn.has(n)||e.has(n))continue;let u=!1;try{u=r?.isOptional?.()===!0}catch{}u?s.push(n):t.push(n)}return{required:t,optional:s}}catch{return null}}async function tr(o,e,t){let s=null;if(e)try{let n=await er(e);if(n){let r=await Qn(t);s=or(n.shape,r)}}catch{s=null}if(console.log(d.white(" Pass inputs:")),s&&s.required.length+s.optional.length>0){let{required:n,optional:r}=s,u=n[0]||r[0],l=`<${u}>`;console.log(d.gray(` ${d.white(`zibby workflow run ${o} -p ${u}="${l}"`)}`));let a=[...n.slice(0,3),...r.slice(0,1)],g={};for(let m of a)m==="model"?g[m]="opus-4.6":g[m]=`<${m}>`;console.log(d.gray(` ${d.white(`zibby workflow run ${o} --input '${JSON.stringify(g)}'`)}`)),console.log(d.gray(` ${d.white(`zibby workflow run ${o} --input-file inputs.json`)}`)),console.log(d.gray(` Same flags work on ${d.white("zibby workflow trigger <uuid>")} for cloud runs.`));let f=a,w=f.length>0?f.map(m=>d.white(`state.${m}`)).join(", ")+", etc":d.white("state.<field>");console.log(d.gray(` Inside any node, read ${w} \u2014 top-level.`)),console.log(d.gray(` See workflows/${o}/state.js for the full input schema.
582
+ `}var Xn=new Set(["cwd","sessionPath","outputPath","context","input"]);async function Qn(o){try{let e=await Dn(S(o,"graph.mjs"),"utf-8"),t=new Set,s=/addNode\(\s*['"`]([A-Za-z_][\w-]*)['"`]/g,n;for(;(n=s.exec(e))!==null;)t.add(n[1]);return t}catch{return new Set}}async function er(o){try{let e=await import(`@zibby/core/templates/${o}/state.js`);for(let t of Object.values(e))if(!(!t||typeof t!="object"))try{let s=t.shape;if(s&&typeof s=="object"&&Object.keys(s).length>0)return{schema:t,shape:s}}catch{}return null}catch{return null}}function or(o,e){try{let t=[],s=[];for(let[n,r]of Object.entries(o)){if(Xn.has(n)||e.has(n))continue;let u=!1;try{u=r?.isOptional?.()===!0}catch{}u?s.push(n):t.push(n)}return{required:t,optional:s}}catch{return null}}async function tr(o,e,t){let s=null;if(e)try{let n=await er(e);if(n){let r=await Qn(t);s=or(n.shape,r)}}catch{s=null}if(console.log(d.white(" Pass inputs:")),s&&s.required.length+s.optional.length>0){let{required:n,optional:r}=s,u=n[0]||r[0],l=`<${u}>`;console.log(d.gray(` ${d.white(`zibby workflow run ${o} -p ${u}="${l}"`)}`));let a=[...n.slice(0,3),...r.slice(0,1)],g={};for(let m of a)m==="model"?g[m]="opus-4.6":g[m]=`<${m}>`;console.log(d.gray(` ${d.white(`zibby workflow run ${o} --input '${JSON.stringify(g)}'`)}`)),console.log(d.gray(` ${d.white(`zibby workflow run ${o} --input-file inputs.json`)}`)),console.log(d.gray(` Same flags work on ${d.white("zibby workflow trigger <uuid>")} for cloud runs.`));let f=a,w=f.length>0?`${f.map(m=>d.white(`state.${m}`)).join(", ")}, etc`:d.white("state.<field>");console.log(d.gray(` Inside any node, read ${w} \u2014 top-level.`)),console.log(d.gray(` See workflows/${o}/state.js for the full input schema.
583
583
  `))}else console.log(d.gray(` ${d.white(`zibby workflow run ${o} -p name=alice -p count=5`)}`)),console.log(d.gray(` ${d.white(`zibby workflow run ${o} --input '{"url":"https://example.com"}'`)}`)),console.log(d.gray(` ${d.white(`zibby workflow run ${o} --input-file inputs.json`)}`)),console.log(d.gray(` Same flags work on ${d.white("zibby workflow trigger <uuid>")} for cloud runs.`)),console.log(d.gray(` Inside your node, read ${d.white("state.name")}, ${d.white("state.count")}, etc \u2014 top-level.
584
584
  `))}function Fo(o){let e={"@zibby/core":"^0.3.0",...o};return`${JSON.stringify({type:"module",dependencies:e},null,2)}
585
585
  `}async function rs(o,e={}){if(!e.skipInitCheck){let{homedir:m}=await import("os"),A=process.env.ZIBBY_CONFIG_DIR?S(process.env.ZIBBY_CONFIG_DIR,"config.json"):S(m(),".zibby","config.json");if(!re(A)){console.log(d.gray(`
@@ -1,42 +1,42 @@
1
- import e from"chalk";import{readFileSync as v,existsSync as N,writeSync as R}from"fs";import{homedir as C}from"os";import{join as _}from"path";var x="https://logs.workflows.zibby.app",j="https://logs-stream.zibby.app/",b=null;async function A(i){return b||(process.env.ZIBBY_SSE_ENDPOINT?(b=process.env.ZIBBY_SSE_ENDPOINT,b):(b=j,b))}function L(i){let r=_(C(),".zibby","config.json");N(r)||(console.log(e.red(`
1
+ import e from"chalk";import{readFileSync as M,existsSync as O,writeSync as F}from"fs";import{homedir as z}from"os";import{join as B}from"path";var A="https://logs.workflows.zibby.app",J="https://logs-stream.zibby.app/",P=null;async function U(a){return P||(process.env.ZIBBY_SSE_ENDPOINT?(P=process.env.ZIBBY_SSE_ENDPOINT,P):(P=J,P))}function G(a){let s=B(z(),".zibby","config.json");O(s)||(console.log(e.red(`
2
2
  Not authenticated`)),console.log(e.gray(` Run: zibby login
3
- `)),process.exit(1));let s;try{s=JSON.parse(v(r,"utf-8"))}catch{console.log(e.red(`
3
+ `)),process.exit(1));let n;try{n=JSON.parse(M(s,"utf-8"))}catch{console.log(e.red(`
4
4
  Config file corrupt`)),console.log(e.gray(` Run: zibby login
5
- `)),process.exit(1)}let o=s.sessionToken;o||(console.log(e.red(`
5
+ `)),process.exit(1)}let o=n.sessionToken;o||(console.log(e.red(`
6
6
  Not authenticated`)),console.log(e.gray(` Run: zibby login
7
- `)),process.exit(1));let f=i.project;return{token:o,projectId:f}}function k(i){return new Date(i).toISOString().replace("T"," ").replace("Z","")}async function E(i,r){let s=await fetch(i,{headers:{Authorization:`Bearer ${r}`}});if(!s.ok){let o=await s.text();throw new Error(`API ${s.status}: ${o}`)}return s.json()}async function O(i,r,s,o){return i||(console.log(e.red(`
7
+ `)),process.exit(1));let f=a.project;return{token:o,projectId:f}}function C(a){return new Date(a).toISOString().replace("T"," ").replace("Z","")}async function j(a,s){let n=await fetch(a,{headers:{Authorization:`Bearer ${s}`}});if(!n.ok){let o=await n.text();throw new Error(`API ${n.status}: ${o}`)}return n.json()}async function W(a,s,n,o){return a||(console.log(e.red(`
8
8
  Workflow UUID is required`)),console.log(e.gray(" Usage: zibby workflow logs <workflow-uuid>")),console.log(e.gray(` zibby workflow logs <workflow-uuid> -t
9
- `)),process.exit(1)),i}function F(i,r){let o=((i||"")+r).split(`
10
- `),f=o.pop()||"",a=[],u=null,n=null;for(let d=0;d<o.length;d++){let l=o[d];if(l.trim()){if(l.startsWith("id:")){u=l.slice(3).trim();continue}if(l.startsWith("event:")){let g=l.slice(6).trim();if(g==="log")continue;if(g==="status"){let c=o[d+1];if(c&&c.startsWith("data:"))try{let y=JSON.parse(c.slice(5).trim());y.status==="new_execution"?a.push({type:"newExecution",executionId:y.executionId,taskId:y.taskId}):y.status==="waiting"&&a.push({type:"waiting"})}catch{}continue}if(g==="complete"){a.push({type:"complete"});continue}if(g==="error"){let c=o[d+1];if(c&&c.startsWith("data:"))try{if(JSON.parse(c.slice(5).trim()).error==="No executions found for workflow"){n={type:"notFound"};break}}catch{}n={type:"failed"};break}continue}if(l.startsWith("data:")){let g=l.slice(5).trim();if(!g)continue;try{let c=JSON.parse(g);c.timestamp&&c.message&&a.push({type:"log",timestamp:c.timestamp,message:c.message,taskId:c.taskId})}catch{}}}}return{actions:a,remainder:f,lastEventId:u,returnSignal:n}}async function J({token:i,executionId:r,sseEndpoint:s,stopped:o}){let f=null;try{let a=new URL(s);a.searchParams.set("jobId",r),f&&a.searchParams.set("lastEventId",f);let u=await fetch(a.toString(),{headers:{Authorization:`Bearer ${i}`,Accept:"text/event-stream"}});if(!u.ok)throw new Error(`SSE connection failed: ${u.status} ${u.statusText}`);let n=u.body.getReader(),d=new TextDecoder,l="",g=!1;for(;!o.value;){let{done:c,value:y}=await n.read();if(c)break;let w=F(l,d.decode(y,{stream:!0}));l=w.remainder,w.lastEventId&&(f=w.lastEventId);for(let t of w.actions)switch(t.type){case"newExecution":{let m=`${t.executionId.slice(0,8)}...${t.executionId.slice(-4)}`,h=t.taskId?t.taskId.slice(-8):"pending";console.log(e.cyan(`
11
- \u250C\u2500 Execution: ${m} (task: ${h})`)),console.log(e.cyan(` \u2514\u2500 Streaming logs...
12
- `));break}case"waiting":console.log(e.gray(`
13
- Waiting for next execution...`));break;case"complete":g=!0;break;case"log":{let m=e.gray(k(t.timestamp)),h=t.taskId?e.gray(`(${t.taskId.slice(-8)}) `):"";console.log(`${m} ${h}${t.message.replace(/\n$/,"")}`);break}}if(w.returnSignal)return w.returnSignal.type==="notFound"?{notFound:!0}:{failed:!0}}return{completed:g}}catch(a){if(a.name==="AbortError")return{aborted:!0};throw a}}function M(i,{baseMs:r=500,capMs:s=3e4,rand:o=Math.random}={}){let f=Math.min(s,r*Math.pow(2,Math.max(0,i)));return Math.floor(o()*f)}async function z({attemptStream:i,stopped:r,follow:s,logger:o,sleep:f=d=>new Promise(l=>setTimeout(l,d)),exit:a=d=>{throw new Error(`exit:${d}`)},backoff:u=M,notFoundPollMs:n=5e3}){let d=0,l=!1;for(;!r.value;){let g;try{g=await i(),d=0}catch(c){if(c.name==="AbortError"||r.value)return{reason:"aborted"};if(l||(o.error(` SSE Error: ${c.message}`),s&&o.gray(" Reconnecting..."),l=!0),!s)return a("error")??{reason:"error"};let y=u(d);d++,await f(y);continue}if(g.aborted||r.value)return{reason:"aborted"};if(g.notFound){if(s){l||(o.yellow(" No executions found yet. Waiting for workflow to be triggered..."),o.gray(" Press Ctrl+C to stop."),l=!0),await f(n);continue}return o.yellow(`
9
+ `)),process.exit(1)),a}function D(a,s){let o=((a||"")+s).split(`
10
+ `),f=o.pop()||"",i=[],u=null,t=null;for(let m=0;m<o.length;m++){let l=o[m];if(l.trim()){if(l.startsWith("id:")){u=l.slice(3).trim();continue}if(l.startsWith("event:")){let d=l.slice(6).trim();if(d==="log")continue;if(d==="status"){let c=o[m+1];if(c&&c.startsWith("data:"))try{let h=JSON.parse(c.slice(5).trim());h.status==="new_execution"?i.push({type:"newExecution",executionId:h.executionId,taskId:h.taskId}):h.status==="waiting"&&i.push({type:"waiting"})}catch{}continue}if(d==="complete"){i.push({type:"complete"});continue}if(d==="error"){let c=o[m+1];if(c&&c.startsWith("data:"))try{if(JSON.parse(c.slice(5).trim()).error==="No executions found for workflow"){t={type:"notFound"};break}}catch{}t={type:"failed"};break}continue}if(l.startsWith("data:")){let d=l.slice(5).trim();if(!d)continue;try{let c=JSON.parse(d);c.timestamp&&c.message&&i.push({type:"log",timestamp:c.timestamp,message:c.message,taskId:c.taskId})}catch{}}}}return{actions:i,remainder:f,lastEventId:u,returnSignal:t}}async function Y({token:a,executionId:s,sseEndpoint:n,stopped:o}){let f=null;try{let y=function(){let b=Array.from(I.entries()).slice(0,c);I.clear();for(let[w,p]of b)I.set(w,p);r=new Set(Array.from(I.values()).map(w=>w.taskId).filter(Boolean));for(let w of[...g.keys()])I.has(w)||g.delete(w)},$=function(k){for(let[b,w]of I)if(w.taskId===k)return b;return null},T=function(k){let b=I.get(k);!b||b.headerPrinted||(console.log(e.cyan(`
11
+ \u250C\u2500 Execution: ${b.shortId} (task: ${b.taskSuffix})`)),console.log(e.cyan(` \u2514\u2500 Streaming logs...
12
+ `)),b.headerPrinted=!0)},v=function(k){let b=e.gray(C(k.timestamp)),w=k.taskId?e.gray(`(${k.taskId.slice(-8)}) `):"";console.log(`${b} ${w}${k.message.replace(/\n$/,"")}`)},R=function(){if(!x)return;x=!1,S&&(clearTimeout(S),S=null);let k=Array.from(I.entries()).reverse();for(let[b]of k){let w=g.get(b);if(!(!w||w.length===0)){T(b);for(let p of w)v(p)}}g.clear()},N=function(){x&&(S&&clearTimeout(S),S=setTimeout(R,h))},i=new URL(n);i.searchParams.set("jobId",s),f&&i.searchParams.set("lastEventId",f);let u=await fetch(i.toString(),{headers:{Authorization:`Bearer ${a}`,Accept:"text/event-stream"}});if(!u.ok)throw new Error(`SSE connection failed: ${u.status} ${u.statusText}`);let t=u.body.getReader(),m=new TextDecoder,l="",d=!1,c=Number(process.env.ZIBBY_LOGS_HISTORY_LIMIT)||10,h=Number(process.env.ZIBBY_LOGS_REPLAY_TIMEOUT_MS)||3e3,I=new Map,r=new Set,g=new Map,x=!0,S=null;for(N();!o.value;){let{done:k,value:b}=await t.read();if(k)break;let w=D(l,m.decode(b,{stream:!0}));l=w.remainder,w.lastEventId&&(f=w.lastEventId);for(let p of w.actions)switch(p.type){case"newExecution":{let E=`${p.executionId.slice(0,8)}...${p.executionId.slice(-4)}`,_=p.taskId?p.taskId.slice(-8):"pending";I.set(p.executionId,{shortId:E,taskSuffix:_,taskId:p.taskId||null,headerPrinted:!1}),g.has(p.executionId)||g.set(p.executionId,[]),y(),N();break}case"waiting":R(),console.log(e.gray(`
13
+ Waiting for next execution...`));break;case"complete":R(),d=!0;break;case"log":{if(p.taskId&&r.size>0&&!r.has(p.taskId))break;if(x){let E=p.taskId?$(p.taskId):null;if(E){let _=g.get(E)||[];_.push(p),g.set(E,_),N()}else v(p)}else{if(p.taskId){let E=$(p.taskId);E&&T(E)}v(p)}break}}if(w.returnSignal)return w.returnSignal.type==="notFound"?{notFound:!0}:{failed:!0}}return R(),{completed:d}}catch(i){if(i.name==="AbortError")return{aborted:!0};throw i}}function H(a,{baseMs:s=500,capMs:n=3e4,rand:o=Math.random}={}){let f=Math.min(n,s*Math.pow(2,Math.max(0,a)));return Math.floor(o()*f)}async function Z({attemptStream:a,stopped:s,follow:n,logger:o,sleep:f=m=>new Promise(l=>setTimeout(l,m)),exit:i=m=>{throw new Error(`exit:${m}`)},backoff:u=H,notFoundPollMs:t=5e3}){let m=0,l=!1;for(;!s.value;){let d;try{d=await a(),m=0}catch(c){if(c.name==="AbortError"||s.value)return{reason:"aborted"};if(l||(o.error(` SSE Error: ${c.message}`),n&&o.gray(" Reconnecting..."),l=!0),!n)return i("error")??{reason:"error"};let h=u(m);m++,await f(h);continue}if(d.aborted||s.value)return{reason:"aborted"};if(d.notFound){if(n){l||(o.yellow(" No executions found yet. Waiting for workflow to be triggered..."),o.gray(" Press Ctrl+C to stop."),l=!0),await f(t);continue}return o.yellow(`
14
14
  No executions found for this workflow. Trigger the workflow first.
15
- `),a("notFound")??{reason:"notFound"}}if(l&&(o.gray(` Reconnected.
16
- `),l=!1),g.failed)return o.red(`
17
- Execution failed.`),s?{reason:"failed"}:a("failed")??{reason:"failed"};if(g.completed)return a("completed")??{reason:"completed"};if(!s)return{reason:"disconnected"}}return{reason:"stopped"}}async function W({token:i,jobId:r,follow:s,projectId:o}){console.log(e.gray(` Streaming logs for workflow ${e.cyan(r)}...`)),console.log(s?e.gray(` Press Ctrl+C to stop.
18
- `):"");let f=await A(i);if(!f)return console.log(e.yellow(` SSE endpoint not configured, using CloudWatch polling...
19
- `)),T({token:i,projectId:null,jobId:r,follow:s,limit:1e5});let a={value:!1},u=()=>{a.value=!0;try{R(2,`
15
+ `),i("notFound")??{reason:"notFound"}}if(l&&(o.gray(` Reconnected.
16
+ `),l=!1),d.failed)return o.red(`
17
+ Execution failed.`),n?{reason:"failed"}:i("failed")??{reason:"failed"};if(d.completed)return i("completed")??{reason:"completed"};if(!n)return{reason:"disconnected"}}return{reason:"stopped"}}async function V({token:a,jobId:s,follow:n,projectId:o}){console.log(e.gray(` Streaming logs for workflow ${e.cyan(s)}...`)),console.log(n?e.gray(` Press Ctrl+C to stop.
18
+ `):"");let f=await U(a);if(!f)return console.log(e.yellow(` SSE endpoint not configured, using CloudWatch polling...
19
+ `)),L({token:a,projectId:null,jobId:s,follow:n,limit:1e5});let i={value:!1},u=()=>{i.value=!0;try{F(2,`
20
20
  Stopped streaming.
21
- `)}catch{}process.exit(0)};process.prependListener("SIGINT",u),process.prependListener("SIGTERM",u),await z({attemptStream:()=>J({token:i,executionId:r,sseEndpoint:f,stopped:a}),stopped:a,follow:s,logger:{gray:n=>console.log(e.gray(n)),red:n=>console.log(e.red(n)),yellow:n=>console.log(e.yellow(n)),error:n=>console.error(e.red(n))},exit:n=>{n==="completed"&&process.exit(0),(n==="error"||n==="notFound"||n==="failed")&&process.exit(1)}})}async function T({token:i,projectId:r,jobId:s,follow:o,limit:f}){let a=r?`${x}/logs/${r}/${s}`:`${x}/job/${s}`,u=null,n=0,d=new Set,l=!1,g=0,c=5,y=()=>{l=!0,console.log(e.gray(`
21
+ `)}catch{}process.exit(0)};process.prependListener("SIGINT",u),process.prependListener("SIGTERM",u),await Z({attemptStream:()=>Y({token:a,executionId:s,sseEndpoint:f,stopped:i}),stopped:i,follow:n,logger:{gray:t=>console.log(e.gray(t)),red:t=>console.log(e.red(t)),yellow:t=>console.log(e.yellow(t)),error:t=>console.error(e.red(t))},exit:t=>{t==="completed"&&process.exit(0),(t==="error"||t==="notFound"||t==="failed")&&process.exit(1)}})}async function L({token:a,projectId:s,jobId:n,follow:o,limit:f}){let i=s?`${A}/logs/${s}/${n}`:`${A}/job/${n}`,u=null,t=0,m=new Set,l=!1,d=0,c=5,h=()=>{l=!0,console.log(e.gray(`
22
22
  Stopped tailing.
23
- `)),process.exit(0)};for(process.on("SIGINT",y),process.on("SIGTERM",y),console.log(e.gray(` Fetching logs for workflow ${e.cyan(s)}...`)),console.log(o?e.gray(` Press Ctrl+C to stop.
24
- `):"");!l;)try{let w=new URLSearchParams({limit:String(f)});u&&w.set("nextToken",u);let t=await E(`${a}?${w}`,i);g=0,t.message&&t.lines?.length===0&&n===0&&console.log(e.gray(` ${t.message}`)),t.status==="starting"&&t.lines?.length===0&&n===0&&console.log(e.gray(" Container starting..."));for(let p of t.lines||[]){let $=`${p.timestamp}:${p.message}`;if(d.has($))continue;d.add($);let I=e.gray(k(p.timestamp)),P=t.taskId?e.gray(`(${t.taskId.slice(-8)}) `):"";console.log(`${I} ${P}${p.message.replace(/\n$/,"")}`)}if(n=t.lines?.length>0?0:n+1,u=t.nextForwardToken||null,t.status==="completed"||t.status==="failed"){let p=t.status==="completed"?e.green:e.red;console.log(p(`
25
- Job ${t.status}.`)),process.exit(t.status==="completed"?0:1)}if(!o){t.status&&console.log(e.gray(`
26
- Status: ${t.status}`));break}let S=t.lines?.length>0?500:n>5?5e3:2e3;await new Promise(p=>setTimeout(p,S))}catch(w){if(w.name==="AbortError")break;w.message.match(/API (400|401|403|404):/)&&(console.error(e.red(`
27
- ${w.message}
28
- `)),process.exit(1)),g++,console.error(e.red(` Error: ${w.message}`)),g>=c&&(console.error(e.red(`
23
+ `)),process.exit(0)};for(process.on("SIGINT",h),process.on("SIGTERM",h),console.log(e.gray(` Fetching logs for workflow ${e.cyan(n)}...`)),console.log(o?e.gray(` Press Ctrl+C to stop.
24
+ `):"");!l;)try{let I=new URLSearchParams({limit:String(f)});u&&I.set("nextToken",u);let r=await j(`${i}?${I}`,a);d=0,r.message&&r.lines?.length===0&&t===0&&console.log(e.gray(` ${r.message}`)),r.status==="starting"&&r.lines?.length===0&&t===0&&console.log(e.gray(" Container starting..."));for(let y of r.lines||[]){let $=`${y.timestamp}:${y.message}`;if(m.has($))continue;m.add($);let T=e.gray(C(y.timestamp)),v=r.taskId?e.gray(`(${r.taskId.slice(-8)}) `):"";console.log(`${T} ${v}${y.message.replace(/\n$/,"")}`)}if(t=r.lines?.length>0?0:t+1,u=r.nextForwardToken||null,r.status==="completed"||r.status==="failed"){let y=r.status==="completed"?e.green:e.red;console.log(y(`
25
+ Job ${r.status}.`)),process.exit(r.status==="completed"?0:1)}if(!o){r.status&&console.log(e.gray(`
26
+ Status: ${r.status}`));break}let S=r.lines?.length>0?500:t>5?5e3:2e3;await new Promise(y=>setTimeout(y,S))}catch(I){if(I.name==="AbortError")break;I.message.match(/API (400|401|403|404):/)&&(console.error(e.red(`
27
+ ${I.message}
28
+ `)),process.exit(1)),d++,console.error(e.red(` Error: ${I.message}`)),d>=c&&(console.error(e.red(`
29
29
  Too many consecutive errors (${c}). Stopping.
30
- `)),process.exit(1)),o||process.exit(1),await new Promise(m=>setTimeout(m,3e3))}}async function U({token:i,projectId:r,workflow:s,follow:o,limit:f}){let a=`${x}/all/${r}`,u=null,n=0,d=new Set,l=null,g=!1,c=0,y=5,w=()=>{g=!0,console.log(e.gray(`
30
+ `)),process.exit(1)),o||process.exit(1),await new Promise(g=>setTimeout(g,3e3))}}async function X({token:a,projectId:s,workflow:n,follow:o,limit:f}){let i=`${A}/all/${s}`,u=null,t=0,m=new Set,l=null,d=!1,c=0,h=5,I=()=>{d=!0,console.log(e.gray(`
31
31
  Stopped tailing.
32
- `)),process.exit(0)};for(process.on("SIGINT",w),process.on("SIGTERM",w),console.log(e.gray(`
33
- Tailing all runs for ${e.cyan(s)}...`)),console.log(o?e.gray(` Press Ctrl+C to stop.
34
- `):"");!g;)try{let t=new URLSearchParams({workflow:s,limit:String(f)});u&&t.set("nextToken",u);let m=await E(`${a}?${t}`,i);c=0,m.message&&m.lines?.length===0&&n===0&&console.log(e.gray(` ${m.message}`));for(let p of m.lines||[]){let $=`${p.timestamp}:${p.jobId}:${p.message}`;if(d.has($))continue;d.add($),p.jobId!==l&&(l!==null&&console.log(""),console.log(e.dim(` \u2500\u2500 ${p.jobId} \u2500\u2500`)),l=p.jobId);let I=e.gray(k(p.timestamp));console.log(`${I} ${p.message.replace(/\n$/,"")}`)}if(n=m.lines?.length>0?0:n+1,u=m.nextToken||null,!o){u&&console.log(e.gray(`
35
- ... more logs available. Run again or use --follow to stream.`)),m.jobCount&&console.log(e.gray(` ${m.jobCount} job(s) found.`));break}if(!m.hasRunning&&!u&&n>2){console.log(e.gray(`
36
- No running jobs. All caught up.`));break}let S=m.lines?.length>0?500:n>5?5e3:2e3;await new Promise(p=>setTimeout(p,S))}catch(t){if(t.name==="AbortError")break;t.message.match(/API (400|401|403|404):/)&&(console.error(e.red(`
37
- ${t.message}
38
- `)),process.exit(1)),c++,console.error(e.red(` Error: ${t.message}`)),c>=y&&(console.error(e.red(`
39
- Too many consecutive errors (${y}). Stopping.
40
- `)),process.exit(1)),o||process.exit(1),await new Promise(h=>setTimeout(h,3e3))}}async function V(i,r){let{token:s,projectId:o}=L(r),f=r.follow===!0,a=r.lines?parseInt(r.lines,10):1e5;if(r.all){let n=r.workflow;return n||(console.log(e.red(`
32
+ `)),process.exit(0)};for(process.on("SIGINT",I),process.on("SIGTERM",I),console.log(e.gray(`
33
+ Tailing all runs for ${e.cyan(n)}...`)),console.log(o?e.gray(` Press Ctrl+C to stop.
34
+ `):"");!d;)try{let r=new URLSearchParams({workflow:n,limit:String(f)});u&&r.set("nextToken",u);let g=await j(`${i}?${r}`,a);c=0,g.message&&g.lines?.length===0&&t===0&&console.log(e.gray(` ${g.message}`));for(let y of g.lines||[]){let $=`${y.timestamp}:${y.jobId}:${y.message}`;if(m.has($))continue;m.add($),y.jobId!==l&&(l!==null&&console.log(""),console.log(e.dim(` \u2500\u2500 ${y.jobId} \u2500\u2500`)),l=y.jobId);let T=e.gray(C(y.timestamp));console.log(`${T} ${y.message.replace(/\n$/,"")}`)}if(t=g.lines?.length>0?0:t+1,u=g.nextToken||null,!o){u&&console.log(e.gray(`
35
+ ... more logs available. Run again or use --follow to stream.`)),g.jobCount&&console.log(e.gray(` ${g.jobCount} job(s) found.`));break}if(!g.hasRunning&&!u&&t>2){console.log(e.gray(`
36
+ No running jobs. All caught up.`));break}let S=g.lines?.length>0?500:t>5?5e3:2e3;await new Promise(y=>setTimeout(y,S))}catch(r){if(r.name==="AbortError")break;r.message.match(/API (400|401|403|404):/)&&(console.error(e.red(`
37
+ ${r.message}
38
+ `)),process.exit(1)),c++,console.error(e.red(` Error: ${r.message}`)),c>=h&&(console.error(e.red(`
39
+ Too many consecutive errors (${h}). Stopping.
40
+ `)),process.exit(1)),o||process.exit(1),await new Promise(x=>setTimeout(x,3e3))}}async function oe(a,s){let{token:n,projectId:o}=G(s),f=s.follow===!0,i=s.lines?parseInt(s.lines,10):1e5;if(s.all){let t=s.workflow;return t||(console.log(e.red(`
41
41
  --workflow is required with --all`)),console.log(e.gray(` Example: zibby workflow logs --workflow ticket-triage --all --project <id>
42
- `)),process.exit(1)),U({token:s,projectId:o,workflow:n,follow:f,limit:a})}let u=await O(i,r,s,o);return f?W({token:s,jobId:u,follow:f,projectId:o}):T({token:s,projectId:o,jobId:u,follow:!1,limit:a})}export{V as logsCommand,F as parseSseChunk,z as runReconnectLoop,M as sseBackoffMs};
42
+ `)),process.exit(1)),X({token:n,projectId:o,workflow:t,follow:f,limit:i})}let u=await W(a,s,n,o);return f?V({token:n,jobId:u,follow:f,projectId:o}):L({token:n,projectId:o,jobId:u,follow:!1,limit:i})}export{oe as logsCommand,D as parseSseChunk,Z as runReconnectLoop,H as sseBackoffMs};
@@ -1,63 +1,63 @@
1
- var F=Object.defineProperty;var J=(e,o)=>()=>(e&&(o=e(e=0)),o);var Y=(e,o)=>{for(var t in o)F(e,t,{get:o[t],enumerable:!0})};var O={};Y(O,{logsCommand:()=>le,parseSseChunk:()=>P,runReconnectLoop:()=>B,sseBackoffMs:()=>A});import i from"chalk";import{readFileSync as K,existsSync as q,writeSync as H}from"fs";import{homedir as X}from"os";import{join as Q}from"path";async function oe(e){return $||(process.env.ZIBBY_SSE_ENDPOINT?($=process.env.ZIBBY_SSE_ENDPOINT,$):($=ee,$))}function te(e){let o=Q(X(),".zibby","config.json");q(o)||(console.log(i.red(`
1
+ var K=Object.defineProperty;var q=(e,o)=>()=>(e&&(o=e(e=0)),o);var H=(e,o)=>{for(var t in o)K(e,t,{get:o[t],enumerable:!0})};var W={};H(W,{logsCommand:()=>me,parseSseChunk:()=>Y,runReconnectLoop:()=>M,sseBackoffMs:()=>J});import i from"chalk";import{readFileSync as ne,existsSync as re,writeSync as se}from"fs";import{homedir as ie}from"os";import{join as le}from"path";async function ce(e){return T||(process.env.ZIBBY_SSE_ENDPOINT?(T=process.env.ZIBBY_SSE_ENDPOINT,T):(T=ae,T))}function fe(e){let o=le(ie(),".zibby","config.json");re(o)||(console.log(i.red(`
2
2
  Not authenticated`)),console.log(i.gray(` Run: zibby login
3
- `)),process.exit(1));let t;try{t=JSON.parse(K(o,"utf-8"))}catch{console.log(i.red(`
3
+ `)),process.exit(1));let t;try{t=JSON.parse(ne(o,"utf-8"))}catch{console.log(i.red(`
4
4
  Config file corrupt`)),console.log(i.gray(` Run: zibby login
5
5
  `)),process.exit(1)}let n=t.sessionToken;n||(console.log(i.red(`
6
6
  Not authenticated`)),console.log(i.gray(` Run: zibby login
7
- `)),process.exit(1));let s=e.project;return{token:n,projectId:s}}function v(e){return new Date(e).toISOString().replace("T"," ").replace("Z","")}async function R(e,o){let t=await fetch(e,{headers:{Authorization:`Bearer ${o}`}});if(!t.ok){let n=await t.text();throw new Error(`API ${t.status}: ${n}`)}return t.json()}async function ne(e,o,t,n){return e||(console.log(i.red(`
7
+ `)),process.exit(1));let s=e.project;return{token:n,projectId:s}}function B(e){return new Date(e).toISOString().replace("T"," ").replace("Z","")}async function F(e,o){let t=await fetch(e,{headers:{Authorization:`Bearer ${o}`}});if(!t.ok){let n=await t.text();throw new Error(`API ${t.status}: ${n}`)}return t.json()}async function pe(e,o,t,n){return e||(console.log(i.red(`
8
8
  Workflow UUID is required`)),console.log(i.gray(" Usage: zibby workflow logs <workflow-uuid>")),console.log(i.gray(` zibby workflow logs <workflow-uuid> -t
9
- `)),process.exit(1)),e}function P(e,o){let n=((e||"")+o).split(`
10
- `),s=n.pop()||"",l=[],a=null,r=null;for(let c=0;c<n.length;c++){let f=n[c];if(f.trim()){if(f.startsWith("id:")){a=f.slice(3).trim();continue}if(f.startsWith("event:")){let g=f.slice(6).trim();if(g==="log")continue;if(g==="status"){let u=n[c+1];if(u&&u.startsWith("data:"))try{let d=JSON.parse(u.slice(5).trim());d.status==="new_execution"?l.push({type:"newExecution",executionId:d.executionId,taskId:d.taskId}):d.status==="waiting"&&l.push({type:"waiting"})}catch{}continue}if(g==="complete"){l.push({type:"complete"});continue}if(g==="error"){let u=n[c+1];if(u&&u.startsWith("data:"))try{if(JSON.parse(u.slice(5).trim()).error==="No executions found for workflow"){r={type:"notFound"};break}}catch{}r={type:"failed"};break}continue}if(f.startsWith("data:")){let g=f.slice(5).trim();if(!g)continue;try{let u=JSON.parse(g);u.timestamp&&u.message&&l.push({type:"log",timestamp:u.timestamp,message:u.message,taskId:u.taskId})}catch{}}}}return{actions:l,remainder:s,lastEventId:a,returnSignal:r}}async function re({token:e,executionId:o,sseEndpoint:t,stopped:n}){let s=null;try{let l=new URL(t);l.searchParams.set("jobId",o),s&&l.searchParams.set("lastEventId",s);let a=await fetch(l.toString(),{headers:{Authorization:`Bearer ${e}`,Accept:"text/event-stream"}});if(!a.ok)throw new Error(`SSE connection failed: ${a.status} ${a.statusText}`);let r=a.body.getReader(),c=new TextDecoder,f="",g=!1;for(;!n.value;){let{done:u,value:d}=await r.read();if(u)break;let y=P(f,c.decode(d,{stream:!0}));f=y.remainder,y.lastEventId&&(s=y.lastEventId);for(let p of y.actions)switch(p.type){case"newExecution":{let m=`${p.executionId.slice(0,8)}...${p.executionId.slice(-4)}`,h=p.taskId?p.taskId.slice(-8):"pending";console.log(i.cyan(`
11
- \u250C\u2500 Execution: ${m} (task: ${h})`)),console.log(i.cyan(` \u2514\u2500 Streaming logs...
12
- `));break}case"waiting":console.log(i.gray(`
13
- Waiting for next execution...`));break;case"complete":g=!0;break;case"log":{let m=i.gray(v(p.timestamp)),h=p.taskId?i.gray(`(${p.taskId.slice(-8)}) `):"";console.log(`${m} ${h}${p.message.replace(/\n$/,"")}`);break}}if(y.returnSignal)return y.returnSignal.type==="notFound"?{notFound:!0}:{failed:!0}}return{completed:g}}catch(l){if(l.name==="AbortError")return{aborted:!0};throw l}}function A(e,{baseMs:o=500,capMs:t=3e4,rand:n=Math.random}={}){let s=Math.min(t,o*Math.pow(2,Math.max(0,e)));return Math.floor(n()*s)}async function B({attemptStream:e,stopped:o,follow:t,logger:n,sleep:s=c=>new Promise(f=>setTimeout(f,c)),exit:l=c=>{throw new Error(`exit:${c}`)},backoff:a=A,notFoundPollMs:r=5e3}){let c=0,f=!1;for(;!o.value;){let g;try{g=await e(),c=0}catch(u){if(u.name==="AbortError"||o.value)return{reason:"aborted"};if(f||(n.error(` SSE Error: ${u.message}`),t&&n.gray(" Reconnecting..."),f=!0),!t)return l("error")??{reason:"error"};let d=a(c);c++,await s(d);continue}if(g.aborted||o.value)return{reason:"aborted"};if(g.notFound){if(t){f||(n.yellow(" No executions found yet. Waiting for workflow to be triggered..."),n.gray(" Press Ctrl+C to stop."),f=!0),await s(r);continue}return n.yellow(`
9
+ `)),process.exit(1)),e}function Y(e,o){let n=((e||"")+o).split(`
10
+ `),s=n.pop()||"",l=[],a=null,r=null;for(let c=0;c<n.length;c++){let f=n[c];if(f.trim()){if(f.startsWith("id:")){a=f.slice(3).trim();continue}if(f.startsWith("event:")){let d=f.slice(6).trim();if(d==="log")continue;if(d==="status"){let p=n[c+1];if(p&&p.startsWith("data:"))try{let g=JSON.parse(p.slice(5).trim());g.status==="new_execution"?l.push({type:"newExecution",executionId:g.executionId,taskId:g.taskId}):g.status==="waiting"&&l.push({type:"waiting"})}catch{}continue}if(d==="complete"){l.push({type:"complete"});continue}if(d==="error"){let p=n[c+1];if(p&&p.startsWith("data:"))try{if(JSON.parse(p.slice(5).trim()).error==="No executions found for workflow"){r={type:"notFound"};break}}catch{}r={type:"failed"};break}continue}if(f.startsWith("data:")){let d=f.slice(5).trim();if(!d)continue;try{let p=JSON.parse(d);p.timestamp&&p.message&&l.push({type:"log",timestamp:p.timestamp,message:p.message,taskId:p.taskId})}catch{}}}}return{actions:l,remainder:s,lastEventId:a,returnSignal:r}}async function ue({token:e,executionId:o,sseEndpoint:t,stopped:n}){let s=null;try{let h=function(){let b=Array.from(y.entries()).slice(0,p);y.clear();for(let[I,w]of b)y.set(I,w);u=new Set(Array.from(y.values()).map(I=>I.taskId).filter(Boolean));for(let I of[...m.keys()])y.has(I)||m.delete(I)},E=function($){for(let[b,I]of y)if(I.taskId===$)return b;return null},v=function($){let b=y.get($);!b||b.headerPrinted||(console.log(i.cyan(`
11
+ \u250C\u2500 Execution: ${b.shortId} (task: ${b.taskSuffix})`)),console.log(i.cyan(` \u2514\u2500 Streaming logs...
12
+ `)),b.headerPrinted=!0)},_=function($){let b=i.gray(B($.timestamp)),I=$.taskId?i.gray(`(${$.taskId.slice(-8)}) `):"";console.log(`${b} ${I}${$.message.replace(/\n$/,"")}`)},R=function(){if(!k)return;k=!1,x&&(clearTimeout(x),x=null);let $=Array.from(y.entries()).reverse();for(let[b]of $){let I=m.get(b);if(!(!I||I.length===0)){v(b);for(let w of I)_(w)}}m.clear()},P=function(){k&&(x&&clearTimeout(x),x=setTimeout(R,g))},l=new URL(t);l.searchParams.set("jobId",o),s&&l.searchParams.set("lastEventId",s);let a=await fetch(l.toString(),{headers:{Authorization:`Bearer ${e}`,Accept:"text/event-stream"}});if(!a.ok)throw new Error(`SSE connection failed: ${a.status} ${a.statusText}`);let r=a.body.getReader(),c=new TextDecoder,f="",d=!1,p=Number(process.env.ZIBBY_LOGS_HISTORY_LIMIT)||10,g=Number(process.env.ZIBBY_LOGS_REPLAY_TIMEOUT_MS)||3e3,y=new Map,u=new Set,m=new Map,k=!0,x=null;for(P();!n.value;){let{done:$,value:b}=await r.read();if($)break;let I=Y(f,c.decode(b,{stream:!0}));f=I.remainder,I.lastEventId&&(s=I.lastEventId);for(let w of I.actions)switch(w.type){case"newExecution":{let S=`${w.executionId.slice(0,8)}...${w.executionId.slice(-4)}`,N=w.taskId?w.taskId.slice(-8):"pending";y.set(w.executionId,{shortId:S,taskSuffix:N,taskId:w.taskId||null,headerPrinted:!1}),m.has(w.executionId)||m.set(w.executionId,[]),h(),P();break}case"waiting":R(),console.log(i.gray(`
13
+ Waiting for next execution...`));break;case"complete":R(),d=!0;break;case"log":{if(w.taskId&&u.size>0&&!u.has(w.taskId))break;if(k){let S=w.taskId?E(w.taskId):null;if(S){let N=m.get(S)||[];N.push(w),m.set(S,N),P()}else _(w)}else{if(w.taskId){let S=E(w.taskId);S&&v(S)}_(w)}break}}if(I.returnSignal)return I.returnSignal.type==="notFound"?{notFound:!0}:{failed:!0}}return R(),{completed:d}}catch(l){if(l.name==="AbortError")return{aborted:!0};throw l}}function J(e,{baseMs:o=500,capMs:t=3e4,rand:n=Math.random}={}){let s=Math.min(t,o*Math.pow(2,Math.max(0,e)));return Math.floor(n()*s)}async function M({attemptStream:e,stopped:o,follow:t,logger:n,sleep:s=c=>new Promise(f=>setTimeout(f,c)),exit:l=c=>{throw new Error(`exit:${c}`)},backoff:a=J,notFoundPollMs:r=5e3}){let c=0,f=!1;for(;!o.value;){let d;try{d=await e(),c=0}catch(p){if(p.name==="AbortError"||o.value)return{reason:"aborted"};if(f||(n.error(` SSE Error: ${p.message}`),t&&n.gray(" Reconnecting..."),f=!0),!t)return l("error")??{reason:"error"};let g=a(c);c++,await s(g);continue}if(d.aborted||o.value)return{reason:"aborted"};if(d.notFound){if(t){f||(n.yellow(" No executions found yet. Waiting for workflow to be triggered..."),n.gray(" Press Ctrl+C to stop."),f=!0),await s(r);continue}return n.yellow(`
14
14
  No executions found for this workflow. Trigger the workflow first.
15
15
  `),l("notFound")??{reason:"notFound"}}if(f&&(n.gray(` Reconnected.
16
- `),f=!1),g.failed)return n.red(`
17
- Execution failed.`),t?{reason:"failed"}:l("failed")??{reason:"failed"};if(g.completed)return l("completed")??{reason:"completed"};if(!t)return{reason:"disconnected"}}return{reason:"stopped"}}async function se({token:e,jobId:o,follow:t,projectId:n}){console.log(i.gray(` Streaming logs for workflow ${i.cyan(o)}...`)),console.log(t?i.gray(` Press Ctrl+C to stop.
18
- `):"");let s=await oe(e);if(!s)return console.log(i.yellow(` SSE endpoint not configured, using CloudWatch polling...
19
- `)),C({token:e,projectId:null,jobId:o,follow:t,limit:1e5});let l={value:!1},a=()=>{l.value=!0;try{H(2,`
16
+ `),f=!1),d.failed)return n.red(`
17
+ Execution failed.`),t?{reason:"failed"}:l("failed")??{reason:"failed"};if(d.completed)return l("completed")??{reason:"completed"};if(!t)return{reason:"disconnected"}}return{reason:"stopped"}}async function de({token:e,jobId:o,follow:t,projectId:n}){console.log(i.gray(` Streaming logs for workflow ${i.cyan(o)}...`)),console.log(t?i.gray(` Press Ctrl+C to stop.
18
+ `):"");let s=await ce(e);if(!s)return console.log(i.yellow(` SSE endpoint not configured, using CloudWatch polling...
19
+ `)),Z({token:e,projectId:null,jobId:o,follow:t,limit:1e5});let l={value:!1},a=()=>{l.value=!0;try{se(2,`
20
20
  Stopped streaming.
21
- `)}catch{}process.exit(0)};process.prependListener("SIGINT",a),process.prependListener("SIGTERM",a),await B({attemptStream:()=>re({token:e,executionId:o,sseEndpoint:s,stopped:l}),stopped:l,follow:t,logger:{gray:r=>console.log(i.gray(r)),red:r=>console.log(i.red(r)),yellow:r=>console.log(i.yellow(r)),error:r=>console.error(i.red(r))},exit:r=>{r==="completed"&&process.exit(0),(r==="error"||r==="notFound"||r==="failed")&&process.exit(1)}})}async function C({token:e,projectId:o,jobId:t,follow:n,limit:s}){let l=o?`${S}/logs/${o}/${t}`:`${S}/job/${t}`,a=null,r=0,c=new Set,f=!1,g=0,u=5,d=()=>{f=!0,console.log(i.gray(`
21
+ `)}catch{}process.exit(0)};process.prependListener("SIGINT",a),process.prependListener("SIGTERM",a),await M({attemptStream:()=>ue({token:e,executionId:o,sseEndpoint:s,stopped:l}),stopped:l,follow:t,logger:{gray:r=>console.log(i.gray(r)),red:r=>console.log(i.red(r)),yellow:r=>console.log(i.yellow(r)),error:r=>console.error(i.red(r))},exit:r=>{r==="completed"&&process.exit(0),(r==="error"||r==="notFound"||r==="failed")&&process.exit(1)}})}async function Z({token:e,projectId:o,jobId:t,follow:n,limit:s}){let l=o?`${A}/logs/${o}/${t}`:`${A}/job/${t}`,a=null,r=0,c=new Set,f=!1,d=0,p=5,g=()=>{f=!0,console.log(i.gray(`
22
22
  Stopped tailing.
23
- `)),process.exit(0)};for(process.on("SIGINT",d),process.on("SIGTERM",d),console.log(i.gray(` Fetching logs for workflow ${i.cyan(t)}...`)),console.log(n?i.gray(` Press Ctrl+C to stop.
24
- `):"");!f;)try{let y=new URLSearchParams({limit:String(s)});a&&y.set("nextToken",a);let p=await R(`${l}?${y}`,e);g=0,p.message&&p.lines?.length===0&&r===0&&console.log(i.gray(` ${p.message}`)),p.status==="starting"&&p.lines?.length===0&&r===0&&console.log(i.gray(" Container starting..."));for(let w of p.lines||[]){let I=`${w.timestamp}:${w.message}`;if(c.has(I))continue;c.add(I);let E=i.gray(v(w.timestamp)),D=p.taskId?i.gray(`(${p.taskId.slice(-8)}) `):"";console.log(`${E} ${D}${w.message.replace(/\n$/,"")}`)}if(r=p.lines?.length>0?0:r+1,a=p.nextForwardToken||null,p.status==="completed"||p.status==="failed"){let w=p.status==="completed"?i.green:i.red;console.log(w(`
25
- Job ${p.status}.`)),process.exit(p.status==="completed"?0:1)}if(!n){p.status&&console.log(i.gray(`
26
- Status: ${p.status}`));break}let x=p.lines?.length>0?500:r>5?5e3:2e3;await new Promise(w=>setTimeout(w,x))}catch(y){if(y.name==="AbortError")break;y.message.match(/API (400|401|403|404):/)&&(console.error(i.red(`
23
+ `)),process.exit(0)};for(process.on("SIGINT",g),process.on("SIGTERM",g),console.log(i.gray(` Fetching logs for workflow ${i.cyan(t)}...`)),console.log(n?i.gray(` Press Ctrl+C to stop.
24
+ `):"");!f;)try{let y=new URLSearchParams({limit:String(s)});a&&y.set("nextToken",a);let u=await F(`${l}?${y}`,e);d=0,u.message&&u.lines?.length===0&&r===0&&console.log(i.gray(` ${u.message}`)),u.status==="starting"&&u.lines?.length===0&&r===0&&console.log(i.gray(" Container starting..."));for(let h of u.lines||[]){let E=`${h.timestamp}:${h.message}`;if(c.has(E))continue;c.add(E);let v=i.gray(B(h.timestamp)),_=u.taskId?i.gray(`(${u.taskId.slice(-8)}) `):"";console.log(`${v} ${_}${h.message.replace(/\n$/,"")}`)}if(r=u.lines?.length>0?0:r+1,a=u.nextForwardToken||null,u.status==="completed"||u.status==="failed"){let h=u.status==="completed"?i.green:i.red;console.log(h(`
25
+ Job ${u.status}.`)),process.exit(u.status==="completed"?0:1)}if(!n){u.status&&console.log(i.gray(`
26
+ Status: ${u.status}`));break}let x=u.lines?.length>0?500:r>5?5e3:2e3;await new Promise(h=>setTimeout(h,x))}catch(y){if(y.name==="AbortError")break;y.message.match(/API (400|401|403|404):/)&&(console.error(i.red(`
27
27
  ${y.message}
28
- `)),process.exit(1)),g++,console.error(i.red(` Error: ${y.message}`)),g>=u&&(console.error(i.red(`
29
- Too many consecutive errors (${u}). Stopping.
30
- `)),process.exit(1)),n||process.exit(1),await new Promise(m=>setTimeout(m,3e3))}}async function ie({token:e,projectId:o,workflow:t,follow:n,limit:s}){let l=`${S}/all/${o}`,a=null,r=0,c=new Set,f=null,g=!1,u=0,d=5,y=()=>{g=!0,console.log(i.gray(`
28
+ `)),process.exit(1)),d++,console.error(i.red(` Error: ${y.message}`)),d>=p&&(console.error(i.red(`
29
+ Too many consecutive errors (${p}). Stopping.
30
+ `)),process.exit(1)),n||process.exit(1),await new Promise(m=>setTimeout(m,3e3))}}async function ge({token:e,projectId:o,workflow:t,follow:n,limit:s}){let l=`${A}/all/${o}`,a=null,r=0,c=new Set,f=null,d=!1,p=0,g=5,y=()=>{d=!0,console.log(i.gray(`
31
31
  Stopped tailing.
32
32
  `)),process.exit(0)};for(process.on("SIGINT",y),process.on("SIGTERM",y),console.log(i.gray(`
33
33
  Tailing all runs for ${i.cyan(t)}...`)),console.log(n?i.gray(` Press Ctrl+C to stop.
34
- `):"");!g;)try{let p=new URLSearchParams({workflow:t,limit:String(s)});a&&p.set("nextToken",a);let m=await R(`${l}?${p}`,e);u=0,m.message&&m.lines?.length===0&&r===0&&console.log(i.gray(` ${m.message}`));for(let w of m.lines||[]){let I=`${w.timestamp}:${w.jobId}:${w.message}`;if(c.has(I))continue;c.add(I),w.jobId!==f&&(f!==null&&console.log(""),console.log(i.dim(` \u2500\u2500 ${w.jobId} \u2500\u2500`)),f=w.jobId);let E=i.gray(v(w.timestamp));console.log(`${E} ${w.message.replace(/\n$/,"")}`)}if(r=m.lines?.length>0?0:r+1,a=m.nextToken||null,!n){a&&console.log(i.gray(`
34
+ `):"");!d;)try{let u=new URLSearchParams({workflow:t,limit:String(s)});a&&u.set("nextToken",a);let m=await F(`${l}?${u}`,e);p=0,m.message&&m.lines?.length===0&&r===0&&console.log(i.gray(` ${m.message}`));for(let h of m.lines||[]){let E=`${h.timestamp}:${h.jobId}:${h.message}`;if(c.has(E))continue;c.add(E),h.jobId!==f&&(f!==null&&console.log(""),console.log(i.dim(` \u2500\u2500 ${h.jobId} \u2500\u2500`)),f=h.jobId);let v=i.gray(B(h.timestamp));console.log(`${v} ${h.message.replace(/\n$/,"")}`)}if(r=m.lines?.length>0?0:r+1,a=m.nextToken||null,!n){a&&console.log(i.gray(`
35
35
  ... more logs available. Run again or use --follow to stream.`)),m.jobCount&&console.log(i.gray(` ${m.jobCount} job(s) found.`));break}if(!m.hasRunning&&!a&&r>2){console.log(i.gray(`
36
- No running jobs. All caught up.`));break}let x=m.lines?.length>0?500:r>5?5e3:2e3;await new Promise(w=>setTimeout(w,x))}catch(p){if(p.name==="AbortError")break;p.message.match(/API (400|401|403|404):/)&&(console.error(i.red(`
37
- ${p.message}
38
- `)),process.exit(1)),u++,console.error(i.red(` Error: ${p.message}`)),u>=d&&(console.error(i.red(`
39
- Too many consecutive errors (${d}). Stopping.
40
- `)),process.exit(1)),n||process.exit(1),await new Promise(h=>setTimeout(h,3e3))}}async function le(e,o){let{token:t,projectId:n}=te(o),s=o.follow===!0,l=o.lines?parseInt(o.lines,10):1e5;if(o.all){let r=o.workflow;return r||(console.log(i.red(`
36
+ No running jobs. All caught up.`));break}let x=m.lines?.length>0?500:r>5?5e3:2e3;await new Promise(h=>setTimeout(h,x))}catch(u){if(u.name==="AbortError")break;u.message.match(/API (400|401|403|404):/)&&(console.error(i.red(`
37
+ ${u.message}
38
+ `)),process.exit(1)),p++,console.error(i.red(` Error: ${u.message}`)),p>=g&&(console.error(i.red(`
39
+ Too many consecutive errors (${g}). Stopping.
40
+ `)),process.exit(1)),n||process.exit(1),await new Promise(k=>setTimeout(k,3e3))}}async function me(e,o){let{token:t,projectId:n}=fe(o),s=o.follow===!0,l=o.lines?parseInt(o.lines,10):1e5;if(o.all){let r=o.workflow;return r||(console.log(i.red(`
41
41
  --workflow is required with --all`)),console.log(i.gray(` Example: zibby workflow logs --workflow ticket-triage --all --project <id>
42
- `)),process.exit(1)),ie({token:t,projectId:n,workflow:r,follow:s,limit:l})}let a=await ne(e,o,t,n);return s?se({token:t,jobId:a,follow:s,projectId:n}):C({token:t,projectId:n,jobId:a,follow:!1,limit:l})}var S,ee,$,z=J(()=>{S="https://logs.workflows.zibby.app",ee="https://logs-stream.zibby.app/",$=null});import T from"ora";import{select as L}from"@inquirer/prompts";import{readFileSync as ae,existsSync as ce}from"fs";import{homedir as fe}from"os";import{join as pe}from"path";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 k(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";b[o]?e=b[o].apiUrl:e=b.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)`),b.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),b.prod.apiUrl}}var Z=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function U(e){return e?Z.test(e)?{ok:!0}:{ok:!1,error:`'${e}' is not a UUID. Cloud workflows are identified by UUID only. Run \`zibby workflow list\` to find yours, or run \`zibby workflow trigger\` with no argument for interactive selection.`}:{ok:!0}}import{existsSync as W,readFileSync as G}from"fs";import{resolve as M}from"path";function j(e){return e==="true"?!0:e==="false"?!1:e==="null"?null:e!==""&&!isNaN(Number(e))?Number(e):e}function _(e){let o={};for(let t of e||[]){let n=t.indexOf("=");if(n===-1){console.warn(` Warning: ignored param "${t}" \u2014 expected key=value format`);continue}let s=t.slice(0,n).trim(),l=j(t.slice(n+1)),a=s.split("."),r=o;for(let c=0;c<a.length-1;c++)(typeof r[a[c]]!="object"||r[a[c]]===null)&&(r[a[c]]={}),r=r[a[c]];r[a[a.length-1]]=l}return o}function V(e){let o=M(e);W(o)||(console.log(`
42
+ `)),process.exit(1)),ge({token:t,projectId:n,workflow:r,follow:s,limit:l})}let a=await pe(e,o,t,n);return s?de({token:t,jobId:a,follow:s,projectId:n}):Z({token:t,projectId:n,jobId:a,follow:!1,limit:l})}var A,ae,T,G=q(()=>{A="https://logs.workflows.zibby.app",ae="https://logs-stream.zibby.app/",T=null});import C from"ora";import{select as V}from"@inquirer/prompts";import{readFileSync as ye,existsSync as we}from"fs";import{homedir as he}from"os";import{join as Ie}from"path";var U={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 j(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";U[o]?e=U[o].apiUrl:e=U.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)`),U.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),U.prod.apiUrl}}var X=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function L(e){return e?X.test(e)?{ok:!0}:{ok:!1,error:`'${e}' is not a UUID. Cloud workflows are identified by UUID only. Run \`zibby workflow list\` to find yours, or run \`zibby workflow trigger\` with no argument for interactive selection.`}:{ok:!0}}import{existsSync as Q,readFileSync as ee}from"fs";import{resolve as oe}from"path";function O(e){return e==="true"?!0:e==="false"?!1:e==="null"?null:e!==""&&!isNaN(Number(e))?Number(e):e}function z(e){let o={};for(let t of e||[]){let n=t.indexOf("=");if(n===-1){console.warn(` Warning: ignored param "${t}" \u2014 expected key=value format`);continue}let s=t.slice(0,n).trim(),l=O(t.slice(n+1)),a=s.split("."),r=o;for(let c=0;c<a.length-1;c++)(typeof r[a[c]]!="object"||r[a[c]]===null)&&(r[a[c]]={}),r=r[a[c]];r[a[a.length-1]]=l}return o}function te(e){let o=oe(e);Q(o)||(console.log(`
43
43
  Error: --input-file not found: ${e}
44
- `),process.exit(1));try{return JSON.parse(G(o,"utf-8"))}catch(t){console.log(`
44
+ `),process.exit(1));try{return JSON.parse(ee(o,"utf-8"))}catch(t){console.log(`
45
45
  Error: --input-file is not valid JSON: ${t.message}
46
- `),process.exit(1)}}function N(e){let o={};if(e.inputFile&&(o={...V(e.inputFile)}),e.input)try{o={...o,...JSON.parse(e.input)}}catch(t){console.log(`
46
+ `),process.exit(1)}}function D(e){let o={};if(e.inputFile&&(o={...te(e.inputFile)}),e.input)try{o={...o,...JSON.parse(e.input)}}catch(t){console.log(`
47
47
  Error: --input is not valid JSON`),console.log(` ${t.message}
48
- `),process.exit(1)}return e.param?.length&&(o={...o,..._(e.param)}),o}function ue(){let e=pe(fe(),".zibby","config.json");if(ce(e))try{let t=JSON.parse(ae(e,"utf-8"));if(t.sessionToken)return t.sessionToken}catch{}let o=process.env.ZIBBY_API_KEY;if(o)return o;console.log(`
48
+ `),process.exit(1)}return e.param?.length&&(o={...o,...z(e.param)}),o}function be(){let e=Ie(he(),".zibby","config.json");if(we(e))try{let t=JSON.parse(ye(e,"utf-8"));if(t.sessionToken)return t.sessionToken}catch{}let o=process.env.ZIBBY_API_KEY;if(o)return o;console.log(`
49
49
  Not authenticated`),console.log(" Run: zibby login"),console.log(` OR set ZIBBY_API_KEY env var (for CI/CD)
50
- `),process.exit(1)}async function ge(e){let o=k(),t=T("Fetching projects...").start();try{let n=await fetch(`${o}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}});n.ok||(t.fail("Failed to fetch projects"),process.exit(1));let s=await n.json();Array.isArray(s)||(s.projects?s=s.projects:s.data&&(s=s.data)),(!s||s.length===0)&&(t.fail("No projects found"),process.exit(1)),t.succeed(`Found ${s.length} project${s.length===1?"":"s"}`),console.log("");let l=s.map(a=>({name:`${a.name||"Unnamed"} (${a.projectId||a.id})`,value:a.projectId||a.id}));return await L({message:"Select a project:",choices:l})}catch(n){t.fail(`Error: ${n.message}`),process.exit(1)}}async function de(e,o){let t=k(),n=T("Fetching deployed workflows...").start();try{let s=["analysis","implementation","run_test"],l=[];for(let r of s){let c=await fetch(`${t}/projects/${e}/workflows/${r}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}});if(c.ok){let f=await c.json();f.graph&&l.push({name:r,version:f.version||0,isDefault:f.isDefault!==!1})}}l.length===0&&(n.fail("No deployed workflows found for this project"),process.exit(1)),n.succeed(`Found ${l.length} deployed workflow${l.length===1?"":"s"}`),console.log("");let a=l.map(r=>({name:`${r.name} (v${r.version})${r.isDefault?" [default]":""}`,value:r.name}));return await L({message:"Select a workflow to trigger:",choices:a})}catch(s){n.fail(`Error: ${s.message}`),process.exit(1)}}async function Pe(e,o={}){let t=U(e);t.ok||(console.log(`
50
+ `),process.exit(1)}async function $e(e){let o=j(),t=C("Fetching projects...").start();try{let n=await fetch(`${o}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}});n.ok||(t.fail("Failed to fetch projects"),process.exit(1));let s=await n.json();Array.isArray(s)||(s.projects?s=s.projects:s.data&&(s=s.data)),(!s||s.length===0)&&(t.fail("No projects found"),process.exit(1)),t.succeed(`Found ${s.length} project${s.length===1?"":"s"}`),console.log("");let l=s.map(a=>({name:`${a.name||"Unnamed"} (${a.projectId||a.id})`,value:a.projectId||a.id}));return await V({message:"Select a project:",choices:l})}catch(n){t.fail(`Error: ${n.message}`),process.exit(1)}}async function ke(e,o){let t=j(),n=C("Fetching deployed workflows...").start();try{let s=["analysis","implementation","run_test"],l=[];for(let r of s){let c=await fetch(`${t}/projects/${e}/workflows/${r}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}});if(c.ok){let f=await c.json();f.graph&&l.push({name:r,version:f.version||0,isDefault:f.isDefault!==!1})}}l.length===0&&(n.fail("No deployed workflows found for this project"),process.exit(1)),n.succeed(`Found ${l.length} deployed workflow${l.length===1?"":"s"}`),console.log("");let a=l.map(r=>({name:`${r.name} (v${r.version})${r.isDefault?" [default]":""}`,value:r.name}));return await V({message:"Select a workflow to trigger:",choices:a})}catch(s){n.fail(`Error: ${s.message}`),process.exit(1)}}async function Fe(e,o={}){let t=L(e);t.ok||(console.log(`
51
51
  Error: ${t.error}
52
- `),process.exit(1));let n=ue(),s=o.project||process.env.ZIBBY_PROJECT_ID,l;if(e){let c=k();try{let f=await fetch(`${c}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});if(f.ok){let u=(await f.json()).projects||[];for(let d of u){let y=await fetch(`${c}/projects/${d.projectId}/workflows`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});if(y.ok){let m=(await y.json()).find(h=>h.uuid===e);if(m){s=d.projectId,l=m.workflowType||m.name,console.log(`
52
+ `),process.exit(1));let n=be(),s=o.project||process.env.ZIBBY_PROJECT_ID,l;if(e){let c=j();try{let f=await fetch(`${c}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});if(f.ok){let p=(await f.json()).projects||[];for(let g of p){let y=await fetch(`${c}/projects/${g.projectId}/workflows`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});if(y.ok){let m=(await y.json()).find(k=>k.uuid===e);if(m){s=g.projectId,l=m.workflowType||m.name,console.log(`
53
53
  \u2713 Found workflow "${l}" (UUID: ${e})
54
54
  `);break}}}(!l||l===e)&&(console.log(`
55
55
  Error: Workflow with UUID "${e}" not found`),console.log(` Check: zibby workflow list
56
56
  `),process.exit(1))}}catch(f){console.log(`
57
57
  Error looking up workflow UUID: ${f.message}
58
- `),process.exit(1)}}s||(console.log(""),s=await ge(n)),l||(console.log(""),l=await de(s,n));let a=N(o);if(console.log(`
58
+ `),process.exit(1)}}s||(console.log(""),s=await $e(n)),l||(console.log(""),l=await ke(s,n));let a=D(o);if(console.log(`
59
59
  Triggering Workflow
60
- `),console.log(" ".padEnd(60,"-")),console.log(` Workflow: ${l}`),console.log(` Project: ${s}`),Object.keys(a).length>0){let c=JSON.stringify(a);console.log(` Input: ${c.length>60?`${c.substring(0,57)}...`:c}`)}o.idempotencyKey&&console.log(` Idempotency: ${o.idempotencyKey}`),console.log(" ".padEnd(60,"-")),console.log("");let r=T("Triggering workflow execution...").start();try{let c=k(),f={input:a};o.idempotencyKey&&(f.idempotencyKey=o.idempotencyKey);let g=await fetch(`${c}/projects/${s}/workflows/${l}/trigger`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(f)});if(!g.ok){let d=await g.json().catch(()=>({}));g.status===429&&(r.fail("Quota exceeded"),console.log(`
61
- Your workflow execution quota has been exceeded`),d.quotaInfo&&(console.log(` Used: ${d.quotaInfo.used}/${d.quotaInfo.limit} executions`),console.log(` Plan: ${d.quotaInfo.planId}`),d.quotaInfo.periodEnd&&console.log(` Resets: ${new Date(d.quotaInfo.periodEnd).toLocaleDateString()}`)),console.log(""),process.exit(1)),r.fail("Trigger failed"),console.log(` Error: ${d.message||g.statusText}
62
- `),process.exit(1)}let u=await g.json();if(r.succeed("Workflow triggered successfully"),console.log(""),console.log(" Job Details:"),console.log(` Job ID: ${u.jobId}`),console.log(` Status: ${u.status}`),console.log(` Version: ${u.version}`),console.log(` Triggered: ${new Date(u.triggeredAt).toLocaleString()}`),console.log(""),o.follow){console.log(" Streaming logs (Ctrl+C to stop)..."),console.log("");let{logsCommand:d}=await Promise.resolve().then(()=>(z(),O));return d(u.jobId,{follow:!0,project:s,apiKey:o.apiKey})}console.log(" Monitor execution:"),e?(console.log(` zibby workflow logs ${e}`),console.log(` zibby workflow logs ${e} -t`)):(console.log(` zibby workflow logs --workflow ${l} --project ${s}`),console.log(` zibby workflow logs --workflow ${l} --project ${s} -t`)),console.log("")}catch(c){r.fail("Trigger failed"),console.log(` Error: ${c.message}
63
- `),process.exit(1)}}export{j as coerceValue,_ as parseParams,N as resolveInput,Pe as triggerWorkflowCommand};
60
+ `),console.log(" ".padEnd(60,"-")),console.log(` Workflow: ${l}`),console.log(` Project: ${s}`),Object.keys(a).length>0){let c=JSON.stringify(a);console.log(` Input: ${c.length>60?`${c.substring(0,57)}...`:c}`)}o.idempotencyKey&&console.log(` Idempotency: ${o.idempotencyKey}`),console.log(" ".padEnd(60,"-")),console.log("");let r=C("Triggering workflow execution...").start();try{let c=j(),f={input:a};o.idempotencyKey&&(f.idempotencyKey=o.idempotencyKey);let d=await fetch(`${c}/projects/${s}/workflows/${l}/trigger`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(f)});if(!d.ok){let g=await d.json().catch(()=>({}));d.status===429&&(r.fail("Quota exceeded"),console.log(`
61
+ Your workflow execution quota has been exceeded`),g.quotaInfo&&(console.log(` Used: ${g.quotaInfo.used}/${g.quotaInfo.limit} executions`),console.log(` Plan: ${g.quotaInfo.planId}`),g.quotaInfo.periodEnd&&console.log(` Resets: ${new Date(g.quotaInfo.periodEnd).toLocaleDateString()}`)),console.log(""),process.exit(1)),r.fail("Trigger failed"),console.log(` Error: ${g.message||d.statusText}
62
+ `),process.exit(1)}let p=await d.json();if(r.succeed("Workflow triggered successfully"),console.log(""),console.log(" Job Details:"),console.log(` Job ID: ${p.jobId}`),console.log(` Status: ${p.status}`),console.log(` Version: ${p.version}`),console.log(` Triggered: ${new Date(p.triggeredAt).toLocaleString()}`),console.log(""),o.follow){console.log(" Streaming logs (Ctrl+C to stop)..."),console.log("");let{logsCommand:g}=await Promise.resolve().then(()=>(G(),W));return g(p.jobId,{follow:!0,project:s,apiKey:o.apiKey})}console.log(" Monitor execution:"),e?(console.log(` zibby workflow logs ${e}`),console.log(` zibby workflow logs ${e} -t`)):(console.log(` zibby workflow logs --workflow ${l} --project ${s}`),console.log(` zibby workflow logs --workflow ${l} --project ${s} -t`)),console.log("")}catch(c){r.fail("Trigger failed"),console.log(` Error: ${c.message}
63
+ `),process.exit(1)}}export{O as coerceValue,z as parseParams,D as resolveInput,Fe as triggerWorkflowCommand};
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/cli",
3
- "version": "0.4.11",
3
+ "version": "0.4.12",
4
4
  "description": "Zibby CLI - Test automation generator and runner",
5
5
  "type": "module",
6
6
  "bin": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/cli",
3
- "version": "0.4.11",
3
+ "version": "0.4.12",
4
4
  "description": "Zibby CLI - Test automation generator and runner",
5
5
  "type": "module",
6
6
  "bin": {