@zibby/cli 0.1.87 → 0.1.90

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
- function f(e,r){return e?.uuid||e?.workflowUuid||r?.uuid||null}var o=4;function l({elapsedMs:e,phase:r,step:t}){let n=` \u2014 ${Math.max(0,Math.floor(e/1e3))}s`;return t?`Building bundle on Zibby Cloud... [${t.n}/${o}] ${t.label}${n}`:r?`Building bundle on Zibby Cloud... (${r.toLowerCase()})${n}`:`Building bundle on Zibby Cloud...${n}`}var d=/\[(\d+)\/\d+\]\s+(.+?)\s*\.{0,3}\s*$/;function a(e){if(!e)return null;let r=d.exec(e);if(!r)return null;let t=parseInt(r[1],10);return!Number.isInteger(t)||t<1?null:{n:t,label:r[2].trim()}}function c(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 m({uuid:e,name:r,projectId:t,result:u,existingManifest:n=null,now:i=()=>new Date().toISOString()}){let s=u?.version??(n?.version??0)+1;return{uuid:e,name:r,projectId:t,version:s,deployedAt:i()}}export{o as BUNDLE_BUILD_TOTAL_STEPS,m as buildDeployManifest,l as formatBundleSpinnerText,c as isBundleNoiseLine,a as parseBundleStepLine,f as pickCloudUuid};
1
+ function l(e,r){return e?.uuid||e?.workflowUuid||r?.uuid||null}var o=4;function a({elapsedMs:e,phase:r,step:t}){let n=` \u2014 ${Math.max(0,Math.floor(e/1e3))}s`;return t?`Building bundle on Zibby Cloud... [${t.n}/${o}] ${t.label}${n}`:r?`Building bundle on Zibby Cloud... (${r.toLowerCase()})${n}`:`Building bundle on Zibby Cloud...${n}`}var d=/\[(\d+)\/\d+\]\s+(.+?)\s*\.{0,3}\s*$/;function c(e){if(!e)return null;let r=d.exec(e);if(!r)return null;let t=parseInt(r[1],10);return!Number.isInteger(t)||t<1?null:{n:t,label:r[2].trim()}}function m(){let e=!1;return function(t){if(!t)return!0;let u=t.replace(/\s+$/,"");if(e)return/^\s*"\s*$/.test(u)&&(e=!1),!0;if(!f(t))return!1;let n=u.replace(/^\[Container\]\s+\d{4}\/\d{2}\/\d{2}\s+\d{2}:\d{2}:\d{2}\.\d+\s*/,"");return n.startsWith("Running command ")&&(n.match(/"/g)||[]).length%2===1&&(e=!0),!0}}function f(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 p({uuid:e,name:r,projectId:t,result:u,existingManifest:n=null,now:i=()=>new Date().toISOString()}){let s=u?.version??(n?.version??0)+1;return{uuid:e,name:r,projectId:t,version:s,deployedAt:i()}}export{o as BUNDLE_BUILD_TOTAL_STEPS,p as buildDeployManifest,a as formatBundleSpinnerText,f as isBundleNoiseLine,m as makeBundleLogFilter,c as parseBundleStepLine,l as pickCloudUuid};
@@ -1,34 +1,34 @@
1
- import{existsSync as k,readFileSync as G,writeFileSync as qo}from"fs";import{join as w}from"path";import j from"chalk";import V from"ora";import Xo from"dotenv";import{select as vo}from"@inquirer/prompts";import{existsSync as Ao}from"fs";import{join as _o}from"path";import{pathToFileURL as Eo}from"url";async function to(o){let t=_o(o,".zibby.config.mjs");if(!Ao(t))throw new Error(".zibby.config.mjs not found");try{let e=await import(Eo(t).href);return e.default||e}catch(e){throw new Error(`Failed to load .zibby.config.mjs: ${e.message}`,{cause:e})}}var A={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.app",description:"Production environment"}};function C(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let t=process.env.ZIBBY_ENV||"prod";A[t]?o=A[t].apiUrl:o=A.prod.apiUrl}try{let t=new URL(o);return t.protocol!=="http:"&&t.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${t.protocol} (only http/https allowed)`),A.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),A.prod.apiUrl}}function no(o,t){return o?.uuid||o?.workflowUuid||t?.uuid||null}var Lo=4;function M({elapsedMs:o,phase:t,step:e}){let p=` \u2014 ${Math.max(0,Math.floor(o/1e3))}s`;return e?`Building bundle on Zibby Cloud... [${e.n}/${Lo}] ${e.label}${p}`:t?`Building bundle on Zibby Cloud... (${t.toLowerCase()})${p}`:`Building bundle on Zibby Cloud...${p}`}var zo=/\[(\d+)\/\d+\]\s+(.+?)\s*\.{0,3}\s*$/;function ro(o){if(!o)return null;let t=zo.exec(o);if(!t)return null;let e=parseInt(t[1],10);return!Number.isInteger(e)||e<1?null:{n:e,label:t[2].trim()}}function so(o){if(!o)return!0;let e=o.trim().replace(/^\[Container\]\s+\d{4}\/\d{2}\/\d{2}\s+\d{2}:\d{2}:\d{2}\.\d+\s*/,"");return!!(/^Phase complete:/.test(e)||/^Phase context status code:/.test(e)||/^Entering phase /.test(e)||/^Running command /.test(e)||/^Phase is /.test(e)||/^Waiting for /.test(e)||/^Registering with agent$/.test(e)||/^Running on CodeBuild /.test(e)||/^Phases found in YAML:/.test(e)||/^CODEBUILD_SRC_DIR=/.test(e)||/^YAML location is /.test(e)||/^Processing environment variables$/.test(e)||/^Moving to directory /.test(e)||/^Cache is not defined /.test(e)||/^Skip cache due to:/.test(e)||/^\s*INSTALL: \d+ commands?$/.test(e)||/^\s*BUILD: \d+ commands?$/.test(e)||/^Set report auto-discover timeout/.test(e)||/^Expanding /.test(e)||/^Assembling file list$/.test(e)||/^No matching auto-discover/.test(e)||/^Report auto-discover/.test(e)||e==="")}function io({uuid:o,name:t,projectId:e,result:n,existingManifest:p=null,now:f=()=>new Date().toISOString()}){let r=n?.version??(p?.version??0)+1;return{uuid:o,name:t,projectId:e,version:r,deployedAt:f()}}import{existsSync as Wo,readFileSync as Go}from"fs";import{join as Vo}from"path";import W from"chalk";import{confirm as Ho}from"@inquirer/prompts";import a from"chalk";import J from"ora";import{spawn as Fo}from"child_process";import{existsSync as lo,mkdirSync as Do,readFileSync as Ro,writeFileSync as Oo}from"fs";import{homedir as co}from"os";import{join as R}from"path";function ao(){return process.env.ZIBBY_CONFIG_DIR||R(co(),".zibby")}function uo(){return R(ao(),"config.json")}var No=R(co(),".zibby"),pe=R(No,"config.json");function Yo(){let o=ao();lo(o)||Do(o,{recursive:!0})}function I(){try{let o=uo();if(lo(o)){let t=Ro(o,"utf-8");return JSON.parse(t)}}catch{}return{}}function _(o){Yo(),Oo(uo(),JSON.stringify(o,null,2))}function po(){return I().sessionToken||null}function fo(o){let t=I();t.sessionToken=o,_(t)}function go(){return I().user||null}function yo(o){let t=I();t.user=o,_(t)}function ho(o){let t=I();t.proxyUrl=o,_(t)}function mo(o){let t=I();t.mem0ProxyUrl=o,_(t)}function wo(o){let t=I();t.projects=o,_(t)}import{existsSync as ge,mkdirSync as ye,readFileSync as he,writeFileSync as me,unlinkSync as we}from"fs";import{resolve as ke}from"path";import{homedir as xe}from"os";function Zo(o){let t=process.platform;try{let e,n;return t==="darwin"?(e="open",n=[o]):t==="win32"?(e="cmd",n=["/c","start","",o]):(e="xdg-open",n=[o]),Fo(e,n,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function Mo(){let o=po(),t=go();return o&&t?{loggedIn:!0,user:t,token:o}:{loggedIn:!1}}async function ko(){try{console.log(a.cyan(`
1
+ import{existsSync as b,readFileSync as G,writeFileSync as qe}from"fs";import{join as m}from"path";import k from"chalk";import V from"ora";import Xe from"dotenv";import{select as xe}from"@inquirer/prompts";import{existsSync as Ce}from"fs";import{join as Ae}from"path";import{pathToFileURL as _e}from"url";async function te(e){let t=Ae(e,".zibby.config.mjs");if(!Ce(t))throw new Error(".zibby.config.mjs not found");try{let o=await import(_e(t).href);return o.default||o}catch(o){throw new Error(`Failed to load .zibby.config.mjs: ${o.message}`,{cause:o})}}var A={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.app",description:"Production environment"}};function C(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let t=process.env.ZIBBY_ENV||"prod";A[t]?e=A[t].apiUrl:e=A.prod.apiUrl}try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${t.protocol} (only http/https allowed)`),A.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),A.prod.apiUrl}}function ne(e,t){return e?.uuid||e?.workflowUuid||t?.uuid||null}var Ee=4;function M({elapsedMs:e,phase:t,step:o}){let u=` \u2014 ${Math.max(0,Math.floor(e/1e3))}s`;return o?`Building bundle on Zibby Cloud... [${o.n}/${Ee}] ${o.label}${u}`:t?`Building bundle on Zibby Cloud... (${t.toLowerCase()})${u}`:`Building bundle on Zibby Cloud...${u}`}var Le=/\[(\d+)\/\d+\]\s+(.+?)\s*\.{0,3}\s*$/;function re(e){if(!e)return null;let t=Le.exec(e);if(!t)return null;let o=parseInt(t[1],10);return!Number.isInteger(o)||o<1?null:{n:o,label:t[2].trim()}}function se(){let e=!1;return function(o){if(!o)return!0;let n=o.replace(/\s+$/,"");if(e)return/^\s*"\s*$/.test(n)&&(e=!1),!0;if(!ze(o))return!1;let u=n.replace(/^\[Container\]\s+\d{4}\/\d{2}\/\d{2}\s+\d{2}:\d{2}:\d{2}\.\d+\s*/,"");return u.startsWith("Running command ")&&(u.match(/"/g)||[]).length%2===1&&(e=!0),!0}}function ze(e){if(!e)return!0;let o=e.trim().replace(/^\[Container\]\s+\d{4}\/\d{2}\/\d{2}\s+\d{2}:\d{2}:\d{2}\.\d+\s*/,"");return!!(/^Phase complete:/.test(o)||/^Phase context status code:/.test(o)||/^Entering phase /.test(o)||/^Running command /.test(o)||/^Phase is /.test(o)||/^Waiting for /.test(o)||/^Registering with agent$/.test(o)||/^Running on CodeBuild /.test(o)||/^Phases found in YAML:/.test(o)||/^CODEBUILD_SRC_DIR=/.test(o)||/^YAML location is /.test(o)||/^Processing environment variables$/.test(o)||/^Moving to directory /.test(o)||/^Cache is not defined /.test(o)||/^Skip cache due to:/.test(o)||/^\s*INSTALL: \d+ commands?$/.test(o)||/^\s*BUILD: \d+ commands?$/.test(o)||/^Set report auto-discover timeout/.test(o)||/^Expanding /.test(o)||/^Assembling file list$/.test(o)||/^No matching auto-discover/.test(o)||/^Report auto-discover/.test(o)||o==="")}function ie({uuid:e,name:t,projectId:o,result:n,existingManifest:u=null,now:f=()=>new Date().toISOString()}){let r=n?.version??(u?.version??0)+1;return{uuid:e,name:t,projectId:o,version:r,deployedAt:f()}}import{existsSync as We,readFileSync as Ge}from"fs";import{join as Ve}from"path";import W from"chalk";import{confirm as He}from"@inquirer/prompts";import a from"chalk";import J from"ora";import{spawn as Ye}from"child_process";import{existsSync as le,mkdirSync as De,readFileSync as Re,writeFileSync as Oe}from"fs";import{homedir as ce}from"os";import{join as R}from"path";function ae(){return process.env.ZIBBY_CONFIG_DIR||R(ce(),".zibby")}function ue(){return R(ae(),"config.json")}var Ne=R(ce(),".zibby"),po=R(Ne,"config.json");function Fe(){let e=ae();le(e)||De(e,{recursive:!0})}function I(){try{let e=ue();if(le(e)){let t=Re(e,"utf-8");return JSON.parse(t)}}catch{}return{}}function _(e){Fe(),Oe(ue(),JSON.stringify(e,null,2))}function pe(){return I().sessionToken||null}function fe(e){let t=I();t.sessionToken=e,_(t)}function de(){return I().user||null}function ge(e){let t=I();t.user=e,_(t)}function ye(e){let t=I();t.proxyUrl=e,_(t)}function he(e){let t=I();t.mem0ProxyUrl=e,_(t)}function me(e){let t=I();t.projects=e,_(t)}import{existsSync as yo,mkdirSync as ho,readFileSync as mo,writeFileSync as wo,unlinkSync as bo}from"fs";import{resolve as jo}from"path";import{homedir as vo}from"os";function Ze(e){let t=process.platform;try{let o,n;return t==="darwin"?(o="open",n=[e]):t==="win32"?(o="cmd",n=["/c","start","",e]):(o="xdg-open",n=[e]),Ye(o,n,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function Me(){let e=pe(),t=de();return e&&t?{loggedIn:!0,user:t,token:e}:{loggedIn:!1}}async function be(){try{console.log(a.cyan(`
2
2
  \u{1F510} Initiating login...
3
- `));let o=Mo();if(o.loggedIn){console.log(a.green("\u2705 Already logged in!")),console.log(a.gray(`User: ${o.user.email}`)),console.log(a.gray(`Name: ${o.user.name}
4
- `));let{createInterface:t}=await import("readline"),e=t({input:process.stdin,output:process.stdout});return new Promise((n,p)=>{let f=()=>{e.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},r=()=>{console.log(a.yellow(`
3
+ `));let e=Me();if(e.loggedIn){console.log(a.green("\u2705 Already logged in!")),console.log(a.gray(`User: ${e.user.email}`)),console.log(a.gray(`Name: ${e.user.name}
4
+ `));let{createInterface:t}=await import("readline"),o=t({input:process.stdin,output:process.stdout});return new Promise((n,u)=>{let f=()=>{o.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},r=()=>{console.log(a.yellow(`
5
5
 
6
6
  \u26A0\uFE0F Login cancelled
7
- `)),f(),process.exit(0)};process.on("SIGINT",r),e.question(a.yellow("Continue with this session? (Y/n): "),async y=>{process.removeListener("SIGINT",r),f();try{if(y.toLowerCase()==="n"||y.toLowerCase()==="no"){console.log(a.gray(`Starting new login...
8
- `));let g=await bo();n(g)}else console.log(a.green(`Using existing session.
9
- `)),n({success:!0,...o})}catch(g){p(g)}})})}return await bo()}catch(o){return console.error(a.red(`
10
- \u274C Login failed:`,o.message)),{success:!1,error:o.message}}}async function Jo(o){let t=C();try{let e=await fetch(`${t}/projects`,{headers:{Authorization:`Bearer ${o}`}});if(e.ok){let p=((await e.json()).projects||[]).map(f=>({name:f.name,projectId:f.projectId,apiToken:f.apiToken}));return wo(p),p}}catch(e){console.log(a.gray(`\u26A0\uFE0F Could not fetch projects: ${e.message}`))}return[]}async function bo(){let o=C(),t=J("Requesting login code...").start(),e=await fetch(`${o}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){t.fail("Failed to request login code");let l=await e.json();throw new Error(l.error||"Failed to initiate login")}let{deviceCode:n,userCode:p,verificationUrl:f,expiresIn:r,interval:y}=await e.json();t.succeed("Login code generated"),console.log(""),console.log(a.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(a.cyan("\u2551")+a.white.bold(" Complete login in your browser ")+a.cyan("\u2551")),console.log(a.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(a.white("Opening browser to login page...")),console.log(a.gray(`Code expires in ${Math.floor(r/60)} minutes`)),console.log(""),await Zo(f)||(console.log(a.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(a.white("Please open this URL manually: ")+a.blue(f)),console.log(""));let u=J("Waiting for authorization...").start(),b=(y||3)*1e3,d=Math.floor(r/(y||3)),v=0,m=!1,i=()=>{m=!0,u.stop(),console.log(a.yellow(`
7
+ `)),f(),process.exit(0)};process.on("SIGINT",r),o.question(a.yellow("Continue with this session? (Y/n): "),async y=>{process.removeListener("SIGINT",r),f();try{if(y.toLowerCase()==="n"||y.toLowerCase()==="no"){console.log(a.gray(`Starting new login...
8
+ `));let g=await we();n(g)}else console.log(a.green(`Using existing session.
9
+ `)),n({success:!0,...e})}catch(g){u(g)}})})}return await we()}catch(e){return console.error(a.red(`
10
+ \u274C Login failed:`,e.message)),{success:!1,error:e.message}}}async function Je(e){let t=C();try{let o=await fetch(`${t}/projects`,{headers:{Authorization:`Bearer ${e}`}});if(o.ok){let u=((await o.json()).projects||[]).map(f=>({name:f.name,projectId:f.projectId,apiToken:f.apiToken}));return me(u),u}}catch(o){console.log(a.gray(`\u26A0\uFE0F Could not fetch projects: ${o.message}`))}return[]}async function we(){let e=C(),t=J("Requesting login code...").start(),o=await fetch(`${e}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!o.ok){t.fail("Failed to request login code");let s=await o.json();throw new Error(s.error||"Failed to initiate login")}let{deviceCode:n,userCode:u,verificationUrl:f,expiresIn:r,interval:y}=await o.json();t.succeed("Login code generated"),console.log(""),console.log(a.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(a.cyan("\u2551")+a.white.bold(" Complete login in your browser ")+a.cyan("\u2551")),console.log(a.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(a.white("Opening browser to login page...")),console.log(a.gray(`Code expires in ${Math.floor(r/60)} minutes`)),console.log(""),await Ze(f)||(console.log(a.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(a.white("Please open this URL manually: ")+a.blue(f)),console.log(""));let p=J("Waiting for authorization...").start(),w=(y||3)*1e3,d=Math.floor(r/(y||3)),$=0,T=!1,l=()=>{T=!0,p.stop(),console.log(a.yellow(`
11
11
 
12
12
  \u26A0\uFE0F Login cancelled
13
- `)),process.exit(0)};process.on("SIGINT",i);try{for(;v<d&&!m;){await Ko(b),v++;let l=await fetch(`${o}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:n})});if(l.status===202)continue;if(!l.ok){u.fail("Authorization failed");let T=await l.json();throw new Error(T.error||"Authorization failed")}let c=await l.json();if(c.status==="authorized"){u.succeed(a.white("Authorization successful!")),fo(c.token),yo(c.user),c.proxyUrl&&ho(c.proxyUrl),c.mem0ProxyUrl&&mo(c.mem0ProxyUrl),console.log(""),console.log(a.gray(`User: ${c.user.email}`));let T=J("Fetching projects...").start(),x=await Jo(c.token);return T.succeed(`Fetched ${x.length} project${x.length!==1?"s":""}`),console.log(a.gray(`Session saved to: ~/.zibby/config.json
14
- `)),{success:!0,loggedIn:!0,user:c.user,token:c.token}}if(c.status==="denied")throw u.fail("Authorization denied"),new Error("User denied authorization")}throw u.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",i)}}function Ko(o){return new Promise(t=>setTimeout(t,o))}function jo(){try{let o=process.env.HOME||process.env.USERPROFILE;if(!o)return null;let t=Vo(o,".zibby","config.json");return Wo(t)&&JSON.parse(Go(t,"utf-8")).sessionToken||null}catch{return null}}function K(){console.log(`
13
+ `)),process.exit(0)};process.on("SIGINT",l);try{for(;$<d&&!T;){await Ke(w),$++;let s=await fetch(`${e}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:n})});if(s.status===202)continue;if(!s.ok){p.fail("Authorization failed");let j=await s.json();throw new Error(j.error||"Authorization failed")}let c=await s.json();if(c.status==="authorized"){p.succeed(a.white("Authorization successful!")),fe(c.token),ge(c.user),c.proxyUrl&&ye(c.proxyUrl),c.mem0ProxyUrl&&he(c.mem0ProxyUrl),console.log(""),console.log(a.gray(`User: ${c.user.email}`));let j=J("Fetching projects...").start(),x=await Je(c.token);return j.succeed(`Fetched ${x.length} project${x.length!==1?"s":""}`),console.log(a.gray(`Session saved to: ~/.zibby/config.json
14
+ `)),{success:!0,loggedIn:!0,user:c.user,token:c.token}}if(c.status==="denied")throw p.fail("Authorization denied"),new Error("User denied authorization")}throw p.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",l)}}function Ke(e){return new Promise(t=>setTimeout(t,e))}function ke(){try{let e=process.env.HOME||process.env.USERPROFILE;if(!e)return null;let t=Ve(e,".zibby","config.json");return We(t)&&JSON.parse(Ge(t,"utf-8")).sessionToken||null}catch{return null}}function K(){console.log(`
15
15
  Not authenticated.`),console.log(` Run ${W.cyan("zibby login")} or set ${W.cyan("ZIBBY_API_KEY")} in your environment.
16
- `)}async function xo(o={}){let t=o.apiKey||process.env.ZIBBY_API_KEY||null,e=jo();if(e||t)return{sessionToken:e,apiKey:t};if(!process.stdin.isTTY){if(o.optional)return{sessionToken:null,apiKey:null};K(),process.exit(1)}console.log(W.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(o.optional)return{sessionToken:null,apiKey:null};K(),process.exit(1)}if(await ko(),e=jo(),!e){if(o.optional)return{sessionToken:null,apiKey:null};K(),process.exit(1)}return{sessionToken:e,apiKey:null}}Xo.config();async function Qo({apiUrl:o,projectId:t,workflowName:e,buildId:n,authToken:p,spinner:f,verbose:r}){let y=Date.now(),g,u=null,b=null,d=setInterval(()=>{f.text=M({elapsedMs:Date.now()-y,phase:u,step:b})},1e3);try{for(;;){let v=new URL(`${o}/projects/${t}/workflows/${e}/build/${n}`);g&&v.searchParams.set("logsToken",g);let m;try{let i=await fetch(v,{headers:{Authorization:`Bearer ${p}`}});if(!i.ok)throw new Error(`HTTP ${i.status}`);m=await i.json()}catch{await new Promise(l=>setTimeout(l,2e3));continue}m.phase&&m.phase!==u&&(u=m.phase),m.nextLogsToken&&m.nextLogsToken!==g&&(g=m.nextLogsToken);for(let i of m.logEvents||[]){let l=String(i.m||"").trimEnd();if(!l)continue;let c=ro(l);if(c&&(b=c),r){process.stdout.write(` ${l}
18
- `);continue}so(l)||c||process.stdout.write(` ${l}
19
- `)}if(f.text=M({elapsedMs:Date.now()-y,phase:u,step:b}),m.done){let i=(Date.now()-y)/1e3;return{status:m.status,elapsedSec:i,lastPhase:u}}await new Promise(i=>setTimeout(i,2e3))}}finally{clearInterval(d)}}async function oe(o,t){let e=C(),n=V("Fetching projects...").start();try{let p=t||o,f=await fetch(`${e}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`}});f.ok||(n.fail("Failed to fetch projects"),process.exit(1));let r=await f.json();Array.isArray(r)||(r.projects&&Array.isArray(r.projects)?r=r.projects:r.data&&Array.isArray(r.data)?r=r.data:(n.fail("Unexpected response format"),process.exit(1))),(!r||r.length===0)&&(n.fail("No projects found"),process.exit(1)),n.succeed(`Found ${r.length} project${r.length===1?"":"s"}`),console.log("");let y=r.map(u=>{let b=u.projectId||u.id||u._id||"unknown";return{name:`${u.name||u.projectName||"Unnamed"} (${b})`,value:b}});return await vo({message:"Select a project to deploy to:",choices:y})}catch(p){n.fail(`Error: ${p.message}`),process.exit(1)}}async function Ve(o,t={}){let e=process.cwd(),n=".zibby/workflows";try{n=(await to(e))?.paths?.workflows||".zibby/workflows"}catch{}if(o){let i=w(e,n,o);k(i)||(console.log(`
20
- Error: Workflow not found: ${n}/${o}/`),console.log(" Run `zibby workflow list` to see local workflows,"),console.log(` or scaffold a new one: zibby workflow new ${o}
21
- `),process.exit(1))}else{let i=w(e,n);k(i)||(console.log(`
16
+ `)}async function je(e={}){let t=e.apiKey||process.env.ZIBBY_API_KEY||null,o=ke();if(o||t)return{sessionToken:o,apiKey:t};if(!process.stdin.isTTY){if(e.optional)return{sessionToken:null,apiKey:null};K(),process.exit(1)}console.log(W.yellow(`
17
+ Not logged in.`));let n;try{n=await He({message:"Open browser to log in now?",default:!0})}catch{n=!1}if(!n){if(e.optional)return{sessionToken:null,apiKey:null};K(),process.exit(1)}if(await be(),o=ke(),!o){if(e.optional)return{sessionToken:null,apiKey:null};K(),process.exit(1)}return{sessionToken:o,apiKey:null}}Xe.config();async function Qe({apiUrl:e,projectId:t,workflowName:o,buildId:n,authToken:u,spinner:f,verbose:r}){let y=Date.now(),g,p=null,w=null,d=se(),$=setInterval(()=>{f.text=M({elapsedMs:Date.now()-y,phase:p,step:w})},1e3);try{for(;;){let T=new URL(`${e}/projects/${t}/workflows/${o}/build/${n}`);g&&T.searchParams.set("logsToken",g);let l;try{let s=await fetch(T,{headers:{Authorization:`Bearer ${u}`}});if(!s.ok)throw new Error(`HTTP ${s.status}`);l=await s.json()}catch{await new Promise(c=>setTimeout(c,2e3));continue}l.phase&&l.phase!==p&&(p=l.phase),l.nextLogsToken&&l.nextLogsToken!==g&&(g=l.nextLogsToken);for(let s of l.logEvents||[]){let c=String(s.m||"").trimEnd();if(!c)continue;let j=re(c);if(j&&(w=j),r){process.stdout.write(` ${c}
18
+ `);continue}d(c)||j||process.stdout.write(` ${c}
19
+ `)}if(f.text=M({elapsedMs:Date.now()-y,phase:p,step:w}),l.done){let s=(Date.now()-y)/1e3;return{status:l.status,elapsedSec:s,lastPhase:p}}await new Promise(s=>setTimeout(s,2e3))}}finally{clearInterval($)}}async function eo(e,t){let o=C(),n=V("Fetching projects...").start();try{let u=t||e,f=await fetch(`${o}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`}});f.ok||(n.fail("Failed to fetch projects"),process.exit(1));let r=await f.json();Array.isArray(r)||(r.projects&&Array.isArray(r.projects)?r=r.projects:r.data&&Array.isArray(r.data)?r=r.data:(n.fail("Unexpected response format"),process.exit(1))),(!r||r.length===0)&&(n.fail("No projects found"),process.exit(1)),n.succeed(`Found ${r.length} project${r.length===1?"":"s"}`),console.log("");let y=r.map(p=>{let w=p.projectId||p.id||p._id||"unknown";return{name:`${p.name||p.projectName||"Unnamed"} (${w})`,value:w}});return await xe({message:"Select a project to deploy to:",choices:y})}catch(u){n.fail(`Error: ${u.message}`),process.exit(1)}}async function Ho(e,t={}){let o=process.cwd(),n=".zibby/workflows";try{n=(await te(o))?.paths?.workflows||".zibby/workflows"}catch{}if(e){let l=m(o,n,e);b(l)||(console.log(`
20
+ 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}
21
+ `),process.exit(1))}else{let l=m(o,n);b(l)||(console.log(`
22
22
  Error: No workflows found in ${n}/`),console.log(` Create one with: zibby workflow new <name>
23
- `),process.exit(1));let{readdir:l,stat:c}=await import("fs/promises"),T=await l(i),x=[];for(let U of T){let $=w(i,U);if(!(await c($)).isDirectory())continue;(k(w($,"graph.mjs"))||k(w($,"graph.js")))&&x.push(U)}x.length===0&&(console.log(`
23
+ `),process.exit(1));let{readdir:s,stat:c}=await import("fs/promises"),j=await s(l),x=[];for(let U of j){let v=m(l,U);if(!(await c(v)).isDirectory())continue;(b(m(v,"graph.mjs"))||b(m(v,"graph.js")))&&x.push(U)}x.length===0&&(console.log(`
24
24
  Error: No workflows found in ${n}/`),console.log(` Create one with: zibby workflow new <name>
25
- `),process.exit(1)),console.log(""),o=await vo({message:"Select a workflow to deploy:",choices:x.map(U=>({name:U,value:U}))})}let{sessionToken:p,apiKey:f}=await xo({apiKey:t.apiKey}),r=t.project||process.env.ZIBBY_PROJECT_ID;r||(console.log(""),r=await oe(f,p));let y=p||f,g=w(e,n,o),u=w(g,"graph.mjs"),b=w(g,"workflow.json");k(u)||(console.log(`
26
- Error: graph.mjs not found in ${n}/${o}/`),process.exit(1)),console.log(`
25
+ `),process.exit(1)),console.log(""),e=await xe({message:"Select a workflow to deploy:",choices:x.map(U=>({name:U,value:U}))})}let{sessionToken:u,apiKey:f}=await je({apiKey:t.apiKey}),r=t.project||process.env.ZIBBY_PROJECT_ID;r||(console.log(""),r=await eo(f,u));let y=u||f,g=m(o,n,e),p=m(g,"graph.mjs"),w=m(g,"workflow.json");b(p)||(console.log(`
26
+ Error: graph.mjs not found in ${n}/${e}/`),process.exit(1)),console.log(`
27
27
  Deploying Workflow
28
- `),console.log(" ".padEnd(60,"-")),console.log(` Workflow: ${o}`),console.log(` Project: ${r}`),console.log(" ".padEnd(60,"-")),console.log("");let d=V("Validating workflow...").start(),v=G(u,"utf-8");if(v.includes("@zibby/core")||v.includes("@zibby/skills")){let i=w(g,"package.json");k(i)||(d.fail("Missing package.json"),console.log(""),console.log(j.red(" \u2717 graph.mjs imports @zibby packages but no package.json found")),console.log(""),console.log(j.yellow(" Create package.json with:")),console.log(""),console.log(j.gray(" {")),console.log(j.gray(' "type": "module",')),console.log(j.gray(' "dependencies": {')),console.log(j.gray(' "@zibby/core": "workspace:*"')),console.log(j.gray(" }")),console.log(j.gray(" }")),console.log(""),process.exit(1));let l=JSON.parse(G(i,"utf-8"));!{...l.dependencies,...l.devDependencies}["@zibby/core"]&&v.includes("@zibby/core")&&(d.fail("Missing @zibby/core dependency"),console.log(""),console.log(j.red(" \u2717 graph.mjs imports @zibby/core but it's not in package.json")),console.log(""),console.log(j.yellow(" Add to package.json dependencies:")),console.log(j.gray(' "@zibby/core": "workspace:*"')),console.log(""),process.exit(1))}d.text="Loading workflow graph...";try{let{pathToFileURL:i}=await import("url"),l=await import(i(u).href),c;if(l.default)if(typeof l.default=="function"){let s=l.default.prototype;s&&s.buildGraph?c=new l.default:c=l.default()}else d.fail("graph.mjs must export a class or factory function"),process.exit(1);else{let s=Object.values(l).find(h=>h.prototype&&h.prototype.buildGraph);s?c=new s:(d.fail("graph.mjs must export a WorkflowAgent class or factory function"),process.exit(1))}let x=c.buildGraph().serialize(),{readdir:U,readFile:$}=await import("fs/promises"),S={};d.text="Packaging workflow sources...";let H=await $(u,"utf-8");if(S["graph.mjs"]=H,k(b)){let s=await $(b,"utf-8");S["workflow.json"]=s}let O=w(g,"nodes");if(k(O)){let s=await U(O);for(let h of s)if(h.endsWith(".mjs")||h.endsWith(".js")){let B=w(O,h),Z=await $(B,"utf-8");S[`nodes/${h}`]=Z}}let q=w(g,"package.json");if(k(q)){let s=await $(q,"utf-8");S["package.json"]=s,d.text="Including package.json for dependencies..."}let X=w(g,"package-lock.json");if(k(X)){let s=await $(X,"utf-8");S["package-lock.json"]=s}d.text=`Uploading to cloud (${x.nodes.size||Object.keys(x.nodes||{}).length} nodes, ${Object.keys(S).length} files)...`;let E=C(),Q=JSON.stringify({format:1,sources:S}),oo=Buffer.byteLength(Q,"utf8"),L=await fetch(`${E}/projects/${r}/workflows/${o}/sources/presign`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`},body:JSON.stringify({contentLength:oo})});if(!L.ok){let s=await L.json().catch(()=>({}));d.fail("Deploy failed (presign)"),console.log(` Error: ${s.error||s.message||L.statusText}
29
- `),process.exit(1)}let $o=await L.json(),{uploadUrl:So,key:Uo,headers:Io}=$o,N=await fetch(So,{method:"PUT",headers:{...Io||{},"Content-Length":String(oo)},body:Q});if(!N.ok){let s=await N.text().catch(()=>"");d.fail("Deploy failed (S3 upload)"),console.log(` S3 PUT failed: ${N.status} ${s.slice(0,200)}
30
- `),process.exit(1)}d.text="Saving workflow definition...";let z=await fetch(`${E}/projects/${r}/workflows/${o}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`},body:JSON.stringify({graph:x,sourcesStagingKey:Uo,isDefault:!1})});if(!z.ok){let s=await z.json().catch(()=>({}));d.fail("Deploy failed"),console.log(` Error: ${s.message||s.error||z.statusText}
31
- `),process.exit(1)}let Y=await z.json(),D=w(g,".zibby-deploy.json"),F=k(D)?(()=>{try{return JSON.parse(G(D,"utf-8"))}catch{return null}})():null,P=no(Y,F);if(P){let s=io({uuid:P,name:o,projectId:r,result:Y,existingManifest:F});try{qo(D,`${JSON.stringify(s,null,2)}
32
- `,"utf-8")}catch(h){console.log(` Warning: failed to write ${D}: ${h.message}`)}}let To=F?"Updated":"Deployed";if(d.succeed(`${To} ${o} (v${Y.version||1})`),!(t.noWait===!0||process.env.ZIBBY_DEPLOY_NO_BUNDLE==="1")){console.log("");let s=V("Building bundle on Zibby Cloud...").start();try{let h=await fetch(`${E}/projects/${r}/workflows/${o}/build`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`}});if(h.ok){let B=await h.json(),{buildId:Z}=B,Po=t.verbose===!0||process.env.ZIBBY_DEPLOY_VERBOSE==="1",{status:eo,elapsedSec:Bo,lastPhase:Co}=await Qo({apiUrl:E,projectId:r,workflowName:o,buildId:Z,authToken:y,spinner:s,verbose:Po});eo==="SUCCEEDED"?s.succeed(`Bundle ready (${Bo.toFixed(1)}s) \u2014 runtime npm install eliminated`):s.warn(`Bundle build ${eo} at phase ${Co||"unknown"} \u2014 workflow will fall back to runtime install`)}else{let B=await h.json().catch(()=>({}));s.warn(`Bundle build skipped: ${B.error||B.message||h.statusText}`),console.log(` Workflow will use slower runtime install path until next deploy.
33
- `)}}catch(h){s.warn(`Bundle build error: ${h.message}`)}}console.log(""),P&&console.log(` UUID: ${P}`),console.log(""),console.log(" Next steps:"),console.log(` zibby workflow start ${o} Run locally`),P&&console.log(` zibby workflow trigger ${P} Run in cloud`),console.log(" zibby workflow list View all workflows"),console.log("")}catch(i){d.fail("Deploy failed"),console.log(` Error: ${i.message}
34
- `),process.exit(1)}}export{Ve as deployWorkflowCommand};
28
+ `),console.log(" ".padEnd(60,"-")),console.log(` Workflow: ${e}`),console.log(` Project: ${r}`),console.log(" ".padEnd(60,"-")),console.log("");let d=V("Validating workflow...").start(),$=G(p,"utf-8");if($.includes("@zibby/core")||$.includes("@zibby/skills")){let l=m(g,"package.json");b(l)||(d.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 s=JSON.parse(G(l,"utf-8"));!{...s.dependencies,...s.devDependencies}["@zibby/core"]&&$.includes("@zibby/core")&&(d.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))}d.text="Loading workflow graph...";try{let{pathToFileURL:l}=await import("url"),s=await import(l(p).href),c;if(s.default)if(typeof s.default=="function"){let i=s.default.prototype;i&&i.buildGraph?c=new s.default:c=s.default()}else d.fail("graph.mjs must export a class or factory function"),process.exit(1);else{let i=Object.values(s).find(h=>h.prototype&&h.prototype.buildGraph);i?c=new i:(d.fail("graph.mjs must export a WorkflowAgent class or factory function"),process.exit(1))}let x=c.buildGraph().serialize(),{readdir:U,readFile:v}=await import("fs/promises"),S={};d.text="Packaging workflow sources...";let H=await v(p,"utf-8");if(S["graph.mjs"]=H,b(w)){let i=await v(w,"utf-8");S["workflow.json"]=i}let O=m(g,"nodes");if(b(O)){let i=await U(O);for(let h of i)if(h.endsWith(".mjs")||h.endsWith(".js")){let B=m(O,h),Z=await v(B,"utf-8");S[`nodes/${h}`]=Z}}let q=m(g,"package.json");if(b(q)){let i=await v(q,"utf-8");S["package.json"]=i,d.text="Including package.json for dependencies..."}let X=m(g,"package-lock.json");if(b(X)){let i=await v(X,"utf-8");S["package-lock.json"]=i}d.text=`Uploading to cloud (${x.nodes.size||Object.keys(x.nodes||{}).length} nodes, ${Object.keys(S).length} files)...`;let E=C(),Q=JSON.stringify({format:1,sources:S}),ee=Buffer.byteLength(Q,"utf8"),L=await fetch(`${E}/projects/${r}/workflows/${e}/sources/presign`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`},body:JSON.stringify({contentLength:ee})});if(!L.ok){let i=await L.json().catch(()=>({}));d.fail("Deploy failed (presign)"),console.log(` Error: ${i.error||i.message||L.statusText}
29
+ `),process.exit(1)}let ve=await L.json(),{uploadUrl:$e,key:Se,headers:Ue}=ve,N=await fetch($e,{method:"PUT",headers:{...Ue||{},"Content-Length":String(ee)},body:Q});if(!N.ok){let i=await N.text().catch(()=>"");d.fail("Deploy failed (S3 upload)"),console.log(` S3 PUT failed: ${N.status} ${i.slice(0,200)}
30
+ `),process.exit(1)}d.text="Saving workflow definition...";let z=await fetch(`${E}/projects/${r}/workflows/${e}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`},body:JSON.stringify({graph:x,sourcesStagingKey:Se,isDefault:!1})});if(!z.ok){let i=await z.json().catch(()=>({}));d.fail("Deploy failed"),console.log(` Error: ${i.message||i.error||z.statusText}
31
+ `),process.exit(1)}let F=await z.json(),D=m(g,".zibby-deploy.json"),Y=b(D)?(()=>{try{return JSON.parse(G(D,"utf-8"))}catch{return null}})():null,P=ne(F,Y);if(P){let i=ie({uuid:P,name:e,projectId:r,result:F,existingManifest:Y});try{qe(D,`${JSON.stringify(i,null,2)}
32
+ `,"utf-8")}catch(h){console.log(` Warning: failed to write ${D}: ${h.message}`)}}let Ie=Y?"Updated":"Deployed";if(d.succeed(`${Ie} ${e} (v${F.version||1})`),!(t.noWait===!0||process.env.ZIBBY_DEPLOY_NO_BUNDLE==="1")){console.log("");let i=V("Building bundle on Zibby Cloud...").start();try{let h=await fetch(`${E}/projects/${r}/workflows/${e}/build`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`}});if(h.ok){let B=await h.json(),{buildId:Z}=B,Te=t.verbose===!0||process.env.ZIBBY_DEPLOY_VERBOSE==="1",{status:oe,elapsedSec:Pe,lastPhase:Be}=await Qe({apiUrl:E,projectId:r,workflowName:e,buildId:Z,authToken:y,spinner:i,verbose:Te});oe==="SUCCEEDED"?i.succeed(`Bundle ready (${Pe.toFixed(1)}s) \u2014 runtime npm install eliminated`):i.warn(`Bundle build ${oe} at phase ${Be||"unknown"} \u2014 workflow will fall back to runtime install`)}else{let B=await h.json().catch(()=>({}));i.warn(`Bundle build skipped: ${B.error||B.message||h.statusText}`),console.log(` Workflow will use slower runtime install path until next deploy.
33
+ `)}}catch(h){i.warn(`Bundle build error: ${h.message}`)}}console.log(""),P&&console.log(` UUID: ${P}`),console.log(""),console.log(" Next steps:"),console.log(` zibby workflow start ${e} Run locally`),P&&console.log(` zibby workflow trigger ${P} Run in cloud`),console.log(" zibby workflow list View all workflows"),console.log("")}catch(l){d.fail("Deploy failed"),console.log(` Error: ${l.message}
34
+ `),process.exit(1)}}export{Ho as deployWorkflowCommand};
@@ -128,7 +128,7 @@ Analyze the input and return a summary with a status.\`,
128
128
  outputSchema: ExampleOutputSchema,
129
129
  };
130
130
  `}function D(o,n){return`${JSON.stringify({name:o,description:`${n} workflow`,entryClass:n,triggers:{api:!0}},null,2)}
131
- `}function Z(){return`${JSON.stringify({type:"module",dependencies:{"@zibby/core":"^0.1.47"}},null,2)}
131
+ `}function Z(){return`${JSON.stringify({type:"module",dependencies:{"@zibby/core":"^0.1.48"}},null,2)}
132
132
  `}async function Ze(o,n={}){let e;o?e=o.toLowerCase():(e=Y(),console.log(t.gray(`
133
133
  No name provided \u2014 generated: ${t.white(e)}`))),T.test(e)||(console.log(t.red(`
134
134
  Invalid workflow name: "${o}"`)),console.log(t.gray(" Must be lowercase, start with a letter, use only a-z, 0-9, hyphens")),console.log(t.gray(" Length: 2\u201364 characters")),console.log(t.gray(` Example: ticket-triage, pr-review, deploy-checker
@@ -1,42 +1,42 @@
1
- import e from"chalk";import{readFileSync as v,existsSync as N}from"fs";import{homedir as R}from"os";import{join as j}from"path";var I="https://logs.workflows.zibby.app",C="https://logs-stream.zibby.app/",S=null;async function _(a){return S||(process.env.ZIBBY_SSE_ENDPOINT?(S=process.env.ZIBBY_SSE_ENDPOINT,S):(S=C,S))}function A(a){let r=j(R(),".zibby","config.json");N(r)||(console.log(e.red(`
1
+ import e from"chalk";import{readFileSync as v,existsSync as N}from"fs";import{homedir as R}from"os";import{join as C}from"path";var x="https://logs.workflows.zibby.app",j="https://logs-stream.zibby.app/",b=null;async function _(i){return b||(process.env.ZIBBY_SSE_ENDPOINT?(b=process.env.ZIBBY_SSE_ENDPOINT,b):(b=j,b))}function A(i){let r=C(R(),".zibby","config.json");N(r)||(console.log(e.red(`
2
2
  Not authenticated`)),console.log(e.gray(` Run: zibby login
3
- `)),process.exit(1));let t;try{t=JSON.parse(v(r,"utf-8"))}catch{console.log(e.red(`
3
+ `)),process.exit(1));let n;try{n=JSON.parse(v(r,"utf-8"))}catch{console.log(e.red(`
4
4
  Config file corrupt`)),console.log(e.gray(` Run: zibby login
5
- `)),process.exit(1)}let n=t.sessionToken;n||(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=a.project;return{token:n,projectId:f}}function E(a){return new Date(a).toISOString().replace("T"," ").replace("Z","")}async function k(a,r){let t=await fetch(a,{headers:{Authorization:`Bearer ${r}`}});if(!t.ok){let n=await t.text();throw new Error(`API ${t.status}: ${n}`)}return t.json()}async function O(a,r,t,n){return a||(console.log(e.red(`
7
+ `)),process.exit(1));let g=i.project;return{token:o,projectId:g}}function k(i){return new Date(i).toISOString().replace("T"," ").replace("Z","")}async function E(i,r){let n=await fetch(i,{headers:{Authorization:`Bearer ${r}`}});if(!n.ok){let o=await n.text();throw new Error(`API ${n.status}: ${o}`)}return n.json()}async function O(i,r,n,o){return i||(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)),a}async function J({token:a,executionId:r,sseEndpoint:t,stopped:n}){let f=null;try{let l=new URL(t);l.searchParams.set("jobId",r),f&&l.searchParams.set("lastEventId",f);let c=await fetch(l.toString(),{headers:{Authorization:`Bearer ${a}`,Accept:"text/event-stream"}});if(!c.ok)throw new Error(`SSE connection failed: ${c.status} ${c.statusText}`);let s=c.body.getReader(),p=new TextDecoder,u="",y=!1;for(;!n.value;){let{done:h,value:$}=await s.read();if(h)break;u+=p.decode($,{stream:!0});let m=u.split(`
10
- `);u=m.pop()||"";for(let o of m)if(o.trim()){if(o.startsWith("id:"))f=o.slice(3).trim();else if(o.startsWith("event:")){let g=o.slice(6).trim();if(g==="log")continue;if(g==="status"){let d=m[m.indexOf(o)+1];if(d&&d.startsWith("data:"))try{let w=JSON.parse(d.slice(5).trim());if(w.status==="new_execution"){let i=w.executionId,b=`${i.slice(0,8)}...${i.slice(-4)}`,x=w.taskId?w.taskId.slice(-8):"pending";console.log(e.cyan(`
11
- \u250C\u2500 Execution: ${b} (task: ${x})`)),console.log(e.cyan(` \u2514\u2500 Streaming logs...
12
- `))}else w.status==="waiting"&&console.log(e.gray(`
13
- Waiting for next execution...`))}catch{}continue}if(g==="complete"){y=!0;continue}if(g==="error"){let d=m[m.indexOf(o)+1];if(d&&d.startsWith("data:"))try{if(JSON.parse(d.slice(5).trim()).error==="No executions found for workflow")return{notFound:!0}}catch{}return{failed:!0}}}else if(o.startsWith("data:")){let g=o.slice(5).trim();if(!g)continue;try{let d=JSON.parse(g);if(d.timestamp&&d.message){let w=e.gray(E(d.timestamp)),i=d.taskId?e.gray(`(${d.taskId.slice(-8)}) `):"";console.log(`${w} ${i}${d.message.replace(/\n$/,"")}`)}}catch{}}}}return{completed:y}}catch(l){if(l.name==="AbortError")return{aborted:!0};throw l}}function M(a,{baseMs:r=500,capMs:t=3e4,rand:n=Math.random}={}){let f=Math.min(t,r*Math.pow(2,Math.max(0,a)));return Math.floor(n()*f)}async function z({attemptStream:a,stopped:r,follow:t,logger:n,sleep:f=p=>new Promise(u=>setTimeout(u,p)),exit:l=p=>{throw new Error(`exit:${p}`)},backoff:c=M,notFoundPollMs:s=5e3}){let p=0,u=!1;for(;!r.value;){let y;try{y=await a(),p=0}catch(h){if(h.name==="AbortError"||r.value)return{reason:"aborted"};if(u||(n.error(` SSE Error: ${h.message}`),t&&n.gray(" Reconnecting..."),u=!0),!t)return l("error")??{reason:"error"};let $=c(p);p++,await f($);continue}if(y.aborted||r.value)return{reason:"aborted"};if(y.notFound){if(t){u||(n.yellow(" No executions found yet. Waiting for workflow to be triggered..."),n.gray(" Press Ctrl+C to stop."),u=!0),await f(s);continue}return n.yellow(`
9
+ `)),process.exit(1)),i}function F(i,r){let o=((i||"")+r).split(`
10
+ `),g=o.pop()||"",a=[],u=null,s=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 f=l.slice(6).trim();if(f==="log")continue;if(f==="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(f==="complete"){a.push({type:"complete"});continue}if(f==="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"){s={type:"notFound"};break}}catch{}s={type:"failed"};break}continue}if(l.startsWith("data:")){let f=l.slice(5).trim();if(!f)continue;try{let c=JSON.parse(f);c.timestamp&&c.message&&a.push({type:"log",timestamp:c.timestamp,message:c.message,taskId:c.taskId})}catch{}}}}return{actions:a,remainder:g,lastEventId:u,returnSignal:s}}async function J({token:i,executionId:r,sseEndpoint:n,stopped:o}){let g=null;try{let a=new URL(n);a.searchParams.set("jobId",r),g&&a.searchParams.set("lastEventId",g);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 s=u.body.getReader(),d=new TextDecoder,l="",f=!1;for(;!o.value;){let{done:c,value:y}=await s.read();if(c)break;let w=F(l,d.decode(y,{stream:!0}));l=w.remainder,w.lastEventId&&(g=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":f=!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:f}}catch(a){if(a.name==="AbortError")return{aborted:!0};throw a}}function M(i,{baseMs:r=500,capMs:n=3e4,rand:o=Math.random}={}){let g=Math.min(n,r*Math.pow(2,Math.max(0,i)));return Math.floor(o()*g)}async function z({attemptStream:i,stopped:r,follow:n,logger:o,sleep:g=d=>new Promise(l=>setTimeout(l,d)),exit:a=d=>{throw new Error(`exit:${d}`)},backoff:u=M,notFoundPollMs:s=5e3}){let d=0,l=!1;for(;!r.value;){let f;try{f=await i(),d=0}catch(c){if(c.name==="AbortError"||r.value)return{reason:"aborted"};if(l||(o.error(` SSE Error: ${c.message}`),n&&o.gray(" Reconnecting..."),l=!0),!n)return a("error")??{reason:"error"};let y=u(d);d++,await g(y);continue}if(f.aborted||r.value)return{reason:"aborted"};if(f.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 g(s);continue}return o.yellow(`
14
14
  No executions found for this workflow. Trigger the workflow first.
15
- `),l("notFound")??{reason:"notFound"}}if(u&&(n.gray(` Reconnected.
16
- `),u=!1),y.failed)return n.red(`
17
- Execution failed.`),t?{reason:"failed"}:l("failed")??{reason:"failed"};if(y.completed)return l("completed")??{reason:"completed"};if(!t)return{reason:"disconnected"}}return{reason:"stopped"}}async function L({token:a,jobId:r,follow:t,projectId:n}){console.log(e.gray(` Streaming logs for workflow ${e.cyan(r)}...`)),console.log(t?e.gray(` Press Ctrl+C to stop.
18
- `):"");let f=await _(a);if(!f)return console.log(e.yellow(` SSE endpoint not configured, using CloudWatch polling...
19
- `)),T({token:a,projectId:null,jobId:r,follow:t,limit:1e5});let l={value:!1},c=()=>{l.value=!0,console.log(e.gray(`
15
+ `),a("notFound")??{reason:"notFound"}}if(l&&(o.gray(` Reconnected.
16
+ `),l=!1),f.failed)return o.red(`
17
+ Execution failed.`),n?{reason:"failed"}:a("failed")??{reason:"failed"};if(f.completed)return a("completed")??{reason:"completed"};if(!n)return{reason:"disconnected"}}return{reason:"stopped"}}async function L({token:i,jobId:r,follow:n,projectId:o}){console.log(e.gray(` Streaming logs for workflow ${e.cyan(r)}...`)),console.log(n?e.gray(` Press Ctrl+C to stop.
18
+ `):"");let g=await _(i);if(!g)return console.log(e.yellow(` SSE endpoint not configured, using CloudWatch polling...
19
+ `)),T({token:i,projectId:null,jobId:r,follow:n,limit:1e5});let a={value:!1},u=()=>{a.value=!0,console.log(e.gray(`
20
20
  Stopped streaming.
21
- `)),process.exit(0)};process.on("SIGINT",c),process.on("SIGTERM",c),await z({attemptStream:()=>J({token:a,executionId:r,sseEndpoint:f,stopped:l}),stopped:l,follow:t,logger:{gray:s=>console.log(e.gray(s)),red:s=>console.log(e.red(s)),yellow:s=>console.log(e.yellow(s)),error:s=>console.error(e.red(s))},exit:s=>{s==="completed"&&process.exit(0),(s==="error"||s==="notFound"||s==="failed")&&process.exit(1)}})}async function T({token:a,projectId:r,jobId:t,follow:n,limit:f}){let l=r?`${I}/logs/${r}/${t}`:`${I}/job/${t}`,c=null,s=0,p=new Set,u=!1,y=0,h=5,$=()=>{u=!0,console.log(e.gray(`
21
+ `)),process.exit(0)};process.on("SIGINT",u),process.on("SIGTERM",u),await z({attemptStream:()=>J({token:i,executionId:r,sseEndpoint:g,stopped:a}),stopped:a,follow:n,logger:{gray:s=>console.log(e.gray(s)),red:s=>console.log(e.red(s)),yellow:s=>console.log(e.yellow(s)),error:s=>console.error(e.red(s))},exit:s=>{s==="completed"&&process.exit(0),(s==="error"||s==="notFound"||s==="failed")&&process.exit(1)}})}async function T({token:i,projectId:r,jobId:n,follow:o,limit:g}){let a=r?`${x}/logs/${r}/${n}`:`${x}/job/${n}`,u=null,s=0,d=new Set,l=!1,f=0,c=5,y=()=>{l=!0,console.log(e.gray(`
22
22
  Stopped tailing.
23
- `)),process.exit(0)};for(process.on("SIGINT",$),process.on("SIGTERM",$),console.log(e.gray(` Fetching logs for workflow ${e.cyan(t)}...`)),console.log(n?e.gray(` Press Ctrl+C to stop.
24
- `):"");!u;)try{let m=new URLSearchParams({limit:String(f)});c&&m.set("nextToken",c);let o=await k(`${l}?${m}`,a);y=0,o.message&&o.lines?.length===0&&s===0&&console.log(e.gray(` ${o.message}`)),o.status==="starting"&&o.lines?.length===0&&s===0&&console.log(e.gray(" Container starting..."));for(let i of o.lines||[]){let b=`${i.timestamp}:${i.message}`;if(p.has(b))continue;p.add(b);let x=e.gray(E(i.timestamp)),P=o.taskId?e.gray(`(${o.taskId.slice(-8)}) `):"";console.log(`${x} ${P}${i.message.replace(/\n$/,"")}`)}if(s=o.lines?.length>0?0:s+1,c=o.nextForwardToken||null,o.status==="completed"||o.status==="failed"){let i=o.status==="completed"?e.green:e.red;console.log(i(`
25
- Job ${o.status}.`)),process.exit(o.status==="completed"?0:1)}if(!n){o.status&&console.log(e.gray(`
26
- Status: ${o.status}`));break}let w=o.lines?.length>0?500:s>5?5e3:2e3;await new Promise(i=>setTimeout(i,w))}catch(m){if(m.name==="AbortError")break;m.message.match(/API (400|401|403|404):/)&&(console.error(e.red(`
27
- ${m.message}
28
- `)),process.exit(1)),y++,console.error(e.red(` Error: ${m.message}`)),y>=h&&(console.error(e.red(`
29
- Too many consecutive errors (${h}). Stopping.
30
- `)),process.exit(1)),n||process.exit(1),await new Promise(g=>setTimeout(g,3e3))}}async function F({token:a,projectId:r,workflow:t,follow:n,limit:f}){let l=`${I}/all/${r}`,c=null,s=0,p=new Set,u=null,y=!1,h=0,$=5,m=()=>{y=!0,console.log(e.gray(`
23
+ `)),process.exit(0)};for(process.on("SIGINT",y),process.on("SIGTERM",y),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 w=new URLSearchParams({limit:String(g)});u&&w.set("nextToken",u);let t=await E(`${a}?${w}`,i);f=0,t.message&&t.lines?.length===0&&s===0&&console.log(e.gray(` ${t.message}`)),t.status==="starting"&&t.lines?.length===0&&s===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(s=t.lines?.length>0?0:s+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:s>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)),f++,console.error(e.red(` Error: ${w.message}`)),f>=c&&(console.error(e.red(`
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:n,follow:o,limit:g}){let a=`${x}/all/${r}`,u=null,s=0,d=new Set,l=null,f=!1,c=0,y=5,w=()=>{f=!0,console.log(e.gray(`
31
31
  Stopped tailing.
32
- `)),process.exit(0)};for(process.on("SIGINT",m),process.on("SIGTERM",m),console.log(e.gray(`
33
- Tailing all runs for ${e.cyan(t)}...`)),console.log(n?e.gray(` Press Ctrl+C to stop.
34
- `):"");!y;)try{let o=new URLSearchParams({workflow:t,limit:String(f)});c&&o.set("nextToken",c);let g=await k(`${l}?${o}`,a);h=0,g.message&&g.lines?.length===0&&s===0&&console.log(e.gray(` ${g.message}`));for(let i of g.lines||[]){let b=`${i.timestamp}:${i.jobId}:${i.message}`;if(p.has(b))continue;p.add(b),i.jobId!==u&&(u!==null&&console.log(""),console.log(e.dim(` \u2500\u2500 ${i.jobId} \u2500\u2500`)),u=i.jobId);let x=e.gray(E(i.timestamp));console.log(`${x} ${i.message.replace(/\n$/,"")}`)}if(s=g.lines?.length>0?0:s+1,c=g.nextToken||null,!n){c&&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&&!c&&s>2){console.log(e.gray(`
36
- No running jobs. All caught up.`));break}let w=g.lines?.length>0?500:s>5?5e3:2e3;await new Promise(i=>setTimeout(i,w))}catch(o){if(o.name==="AbortError")break;o.message.match(/API (400|401|403|404):/)&&(console.error(e.red(`
37
- ${o.message}
38
- `)),process.exit(1)),h++,console.error(e.red(` Error: ${o.message}`)),h>=$&&(console.error(e.red(`
39
- Too many consecutive errors (${$}). Stopping.
40
- `)),process.exit(1)),n||process.exit(1),await new Promise(d=>setTimeout(d,3e3))}}async function B(a,r){let{token:t,projectId:n}=A(r),f=r.follow===!0,l=r.lines?parseInt(r.lines,10):1e5;if(r.all){let s=r.workflow;return s||(console.log(e.red(`
32
+ `)),process.exit(0)};for(process.on("SIGINT",w),process.on("SIGTERM",w),console.log(e.gray(`
33
+ Tailing all runs for ${e.cyan(n)}...`)),console.log(o?e.gray(` Press Ctrl+C to stop.
34
+ `):"");!f;)try{let t=new URLSearchParams({workflow:n,limit:String(g)});u&&t.set("nextToken",u);let m=await E(`${a}?${t}`,i);c=0,m.message&&m.lines?.length===0&&s===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(s=m.lines?.length>0?0:s+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&&s>2){console.log(e.gray(`
36
+ No running jobs. All caught up.`));break}let S=m.lines?.length>0?500:s>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 H(i,r){let{token:n,projectId:o}=A(r),g=r.follow===!0,a=r.lines?parseInt(r.lines,10):1e5;if(r.all){let s=r.workflow;return s||(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)),F({token:t,projectId:n,workflow:s,follow:f,limit:l})}let c=await O(a,r,t,n);return f?L({token:t,jobId:c,follow:f,projectId:n}):T({token:t,projectId:n,jobId:c,follow:!1,limit:l})}export{B as logsCommand,z as runReconnectLoop,M as sseBackoffMs};
42
+ `)),process.exit(1)),U({token:n,projectId:o,workflow:s,follow:g,limit:a})}let u=await O(i,r,n,o);return g?L({token:n,jobId:u,follow:g,projectId:o}):T({token:n,projectId:o,jobId:u,follow:!1,limit:a})}export{H as logsCommand,F as parseSseChunk,z as runReconnectLoop,M as sseBackoffMs};
@@ -0,0 +1,2 @@
1
+ function u({workflowType:o,jobId:e,projectId:t,agentType:r,model:a}){let n="\u2500".repeat(60),l=`${r||"default"} (model: ${a||"auto"})`;return["",n,` Workflow: ${o}`,` Job: ${e||"local"}`,` Project: ${t||"none"}`,` Agent: ${l}`,n].join(`
2
+ `)}export{u as formatRunBanner};
@@ -1,8 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{mkdirSync as D,writeFileSync as M,existsSync as w}from"fs";import{join as g,dirname as q,resolve as F}from"path";import{pathToFileURL as A}from"url";import{execSync as X,spawn as L}from"node:child_process";import{SQSClient as z,SendMessageCommand as Q}from"@aws-sdk/client-sqs";var P=null;function J(){return P||(P=new z({region:process.env.AWS_REGION||"ap-southeast-2"})),P}async function N(i,{status:e,error:n}){let{EXECUTION_ID:s,SQS_AUTH_TOKEN:a,PROGRESS_API_URL:r,PROGRESS_QUEUE_URL:o,PROJECT_API_TOKEN:f}=i;if(!s)return;let l={executionId:s,...a&&{sqsAuthToken:a},status:e,...n&&{error:n},timestamp:new Date().toISOString()},d=r?"HTTP":o?"SQS":"NONE",p=JSON.stringify(l).length;console.log(`Sending final status: ${e} via ${d} (${(p/1024).toFixed(1)}KB)`);try{if(r)await j(r,s,l,f);else if(o){let c=["completed","failed","insufficient_context","blocked"].includes(e)?"execution_completed":"progress_update";await H(o,s,l,c)}else{console.warn("No transport configured for final status \u2014 neither PROGRESS_API_URL nor PROGRESS_QUEUE_URL set");return}console.log(`Final status ${e} sent via ${d}`)}catch(c){console.error(`Failed to send final status (${e}) via ${d}:`),console.error(` Payload: ${(p/1024).toFixed(1)}KB`),console.error(` Error: ${c.message}`),c.name&&console.error(` Error type: ${c.name}`),c.code&&console.error(` Error code: ${c.code}`)}}async function j(i,e,n,s){let a=`${i}/${e}/progress`,r={"Content-Type":"application/json"};s&&(r.Authorization=`Bearer ${s}`);let o=await fetch(a,{method:"POST",headers:r,body:JSON.stringify(n)});if(!o.ok){let f=await o.text();throw new Error(`HTTP ${o.status}: ${f}`)}}async function H(i,e,n,s="progress_update"){let a=JSON.stringify(n),r=(a.length/1024).toFixed(1);a.length>256*1024&&console.error(`\u274C SQS message too large: ${r}KB (limit 256KB) for ${e} [${s}]`),await J().send(new Q({QueueUrl:i,MessageBody:a,MessageGroupId:e,MessageAttributes:{executionId:{DataType:"String",StringValue:e},messageType:{DataType:"String",StringValue:s}}}))}import"@zibby/core";var T=process.env.WORKSPACE||"/workspace";async function V(i,e){D(e,{recursive:!0});let n=Date.now();console.log("Fetching pre-built bundle (streaming curl \u2192 tar)...");let s=setInterval(()=>{let r=((Date.now()-n)/1e3).toFixed(1);console.log(` ...still extracting (${r}s elapsed)`)},3e3);try{await new Promise((r,o)=>{let f=L("curl",["-fsSL",i],{stdio:["ignore","pipe","inherit"]}),l=L("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(l.stdin);let d,p,c=()=>{if(d!==void 0&&p!==void 0){if(d!==0)return o(new Error(`curl exited ${d}`));if(p!==0)return o(new Error(`tar exited ${p}`));r()}};f.on("close",S=>{d=S,c()}),l.on("close",S=>{p=S,c()}),f.on("error",o),l.on("error",o)})}finally{clearInterval(s)}let a=((Date.now()-n)/1e3).toFixed(1);return console.log(` Bundle extracted in ${a}s`),e}async function W(){let i=process.env.WORKFLOW_SOURCES_URL;if(!i)throw new Error("WORKFLOW_SOURCES_URL env var is required");console.log("Fetching workflow sources via pre-signed URL...");let e=await fetch(i);if(!e.ok)throw new Error(`Failed to fetch sources: ${e.status} ${e.statusText}`);let n=await e.json();if(!n.sources||typeof n.sources!="object")throw new Error('Invalid sources payload \u2014 missing "sources" map');return n}function Y(i,e){let n=F(e),s=0;for(let[a,r]of Object.entries(i)){let o=F(e,a);if(!o.startsWith(`${n}/`)&&o!==n){console.error(` \u26D4 Skipping unsafe path: ${a}`);continue}D(q(o),{recursive:!0}),M(o,r,"utf-8"),s++}return s}async function Z(i,e){let n=g(i,"graph.mjs");if(!w(n))throw new Error(`graph.mjs not found at ${n}`);let s=await import(A(n).href),a=e?.entryClass,r=a&&s[a]||s.default||Object.values(s).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!r)throw new Error("No WorkflowAgent class found in graph.mjs");return r}async function ce(){if(!process.env.NODE_PATH){process.env.NODE_PATH="/opt/zibby/packages";let t=await import("module");t.default._initPaths&&t.default._initPaths()}let{WORKFLOW_JOB_ID:i,WORKFLOW_TYPE:e,PROJECT_ID:n,AGENT_TYPE:s,MODEL:a}=process.env;e||(console.error("Missing WORKFLOW_TYPE env var"),process.exit(1)),console.log(`
3
- Zibby Custom Workflow Runner`),console.log(` Job: ${i||"local"}`),console.log(` Workflow: ${e}`),console.log(` Project: ${n||"none"}`),console.log(` Agent: ${s||"default"}`),console.log(` Model: ${a||"auto"}`),console.log("\u2500".repeat(60));let r=process.env.WORKFLOW_BUNDLE_URL,o,f={},l,d;if(r){l=e,o=g(T,".zibby","workflows",l);try{await V(r,o),console.log(" Extracted pre-built bundle (no npm install needed)");try{let t=await W();f=t.input||{},d=t.version}catch(t){console.warn(` Could not fetch input payload: ${t.message}`)}}catch(t){console.warn(` Bundle extract failed (${t.message}); falling back to source install`),o=null}}if(!o){let t=await W(),{sources:u,input:y,workflowType:O,version:E}=t;f=y||{},l=O||e,d=E,console.log(` Workflow v${d||"?"} \u2014 ${Object.keys(u).length} source files`),o=g(T,".zibby","workflows",l);let b=Y(u,o);console.log(` Wrote ${b} files to ${o}`),console.log(" Installing dependencies...");try{X("npm install --silent --no-audit --no-fund",{cwd:o,stdio:"inherit"}),console.log(" Dependencies installed")}catch($){console.warn(` npm install failed: ${$.message}`)}}let p={},c=g(o,"workflow.json");if(w(c)){let{readFileSync:t}=await import("fs");p=JSON.parse(t(c,"utf-8"))}let S=await Z(o,p);console.log(` Loaded ${S.name}`);let m=[],x=g(o,"node_modules","@zibby","agent-workflow"),k=g(o,"node_modules","@zibby","core","node_modules","@zibby","agent-workflow");w(x)&&m.push({kind:"hoisted",path:x}),w(k)&&m.push({kind:"nested",path:k});let R=process.env.ZIBBY_RUN_DIAG==="1";if(R){let{readdirSync:t}=await import("fs");console.log(` [diag] @zibby/agent-workflow copies in bundle: ${m.length}`);for(let u of m)console.log(` [diag] ${u.kind}: ${u.path}`);try{let u=g(o,"node_modules","@zibby");w(u)&&console.log(` [diag] node_modules/@zibby/ contents: [${t(u).join(", ")}]`)}catch{}}let I=g(o,"node_modules","@zibby","core","dist","index.js");if(w(I)&&m.length>0)try{let t=await import(A(I).href),u=[t.AssistantStrategy,t.CursorAgentStrategy,t.ClaudeAgentStrategy,t.CodexAgentStrategy,t.GeminiAgentStrategy].filter(Boolean);for(let y of m){let O=g(y.path,"dist","index.js");if(!w(O))continue;let E=await import(A(O).href),b=R?E.listStrategies():null;for(let $ of u)try{E.registerStrategy(new $)}catch(G){console.warn(` register ${$.name} into ${y.kind} failed: ${G.message}`)}R&&console.log(` [diag] ${y.kind} registry: before=[${b.join(",")||"empty"}] after=[${E.listStrategies().join(",")||"empty"}]`)}console.log(" Registered built-in agent strategies (cursor/claude/codex/gemini/assistant)")}catch(t){console.warn(` Failed to bridge strategies into bundle: ${t.message}`)}else console.warn(" No @zibby/core or @zibby/agent-workflow in bundle \u2014 agent strategies may be unavailable");let K=Date.now(),_=new S({workflow:l||e}),C=_.buildGraph(),B={input:f||{},cwd:T,runId:i||`run-${Date.now()}`};console.log(`
4
- Running graph (${C.nodes?.size||"?"} nodes)...
5
- `);let h;try{h=await C.run(_,B)}catch(t){console.error(`
6
- Workflow execution failed: ${t.message}`),console.error(t.stack),await U("failed",t.message),process.exit(1)}let v=((Date.now()-K)/1e3).toFixed(1);h?.success!==!1?(console.log(`
7
- Workflow "${l||e}" completed in ${v}s`),await U("completed")):(console.error(`
8
- Workflow "${l||e}" failed after ${v}s`),await U("failed",h?.error||"Workflow execution failed"),process.exit(1)),_.onComplete&&await _.onComplete(h)}async function U(i,e=null){let n={EXECUTION_ID:process.env.WORKFLOW_JOB_ID,PROGRESS_API_URL:process.env.PROGRESS_API_URL,PROGRESS_QUEUE_URL:process.env.PROGRESS_QUEUE_URL,PROJECT_API_TOKEN:process.env.PROJECT_API_TOKEN,SQS_AUTH_TOKEN:process.env.SQS_AUTH_TOKEN};if(n.EXECUTION_ID)try{await N(n,{status:i,...e&&{error:e}})}catch(s){console.error(`\u26A0\uFE0F Failed to report status: ${s.message}`)}}export{ce as runWorkflowCommand};
2
+ import{mkdirSync as W,writeFileSync as Y,existsSync as w}from"fs";import{join as g,dirname as Z,resolve as B}from"path";import{pathToFileURL as A}from"url";import{execSync as ee,spawn as D}from"node:child_process";import{SQSClient as H,SendMessageCommand as M}from"@aws-sdk/client-sqs";var P=null;function q(){return P||(P=new H({region:process.env.AWS_REGION||"ap-southeast-2"})),P}async function F(i,{status:e,error:o}){let{EXECUTION_ID:n,SQS_AUTH_TOKEN:c,PROGRESS_API_URL:r,PROGRESS_QUEUE_URL:s,PROJECT_API_TOKEN:a}=i;if(!n)return;let f={executionId:n,...c&&{sqsAuthToken:c},status:e,...o&&{error:o},timestamp:new Date().toISOString()},l=r?"HTTP":s?"SQS":"NONE",u=JSON.stringify(f).length;console.log(`Sending final status: ${e} via ${l} (${(u/1024).toFixed(1)}KB)`);try{if(r)await X(r,n,f,a);else if(s){let d=["completed","failed","insufficient_context","blocked"].includes(e)?"execution_completed":"progress_update";await V(s,n,f,d)}else{console.warn("No transport configured for final status \u2014 neither PROGRESS_API_URL nor PROGRESS_QUEUE_URL set");return}console.log(`Final status ${e} sent via ${l}`)}catch(d){console.error(`Failed to send final status (${e}) via ${l}:`),console.error(` Payload: ${(u/1024).toFixed(1)}KB`),console.error(` Error: ${d.message}`),d.name&&console.error(` Error type: ${d.name}`),d.code&&console.error(` Error code: ${d.code}`)}}async function X(i,e,o,n){let c=`${i}/${e}/progress`,r={"Content-Type":"application/json"};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(c,{method:"POST",headers:r,body:JSON.stringify(o)});if(!s.ok){let a=await s.text();throw new Error(`HTTP ${s.status}: ${a}`)}}async function V(i,e,o,n="progress_update"){let c=JSON.stringify(o),r=(c.length/1024).toFixed(1);c.length>256*1024&&console.error(`\u274C SQS message too large: ${r}KB (limit 256KB) for ${e} [${n}]`),await q().send(new M({QueueUrl:i,MessageBody:c,MessageGroupId:e,MessageAttributes:{executionId:{DataType:"String",StringValue:e},messageType:{DataType:"String",StringValue:n}}}))}function L({workflowType:i,jobId:e,projectId:o,agentType:n,model:c}){let r="\u2500".repeat(60),s=`${n||"default"} (model: ${c||"auto"})`;return["",r,` Workflow: ${i}`,` Job: ${e||"local"}`,` Project: ${o||"none"}`,` Agent: ${s}`,r].join(`
3
+ `)}import"@zibby/core";var T=process.env.WORKSPACE||"/workspace";async function oe(i,e){W(e,{recursive:!0});let o=Date.now();console.log("[setup] Fetching bundle...");let n=setInterval(()=>{let r=((Date.now()-o)/1e3).toFixed(1);console.log(`[setup] still fetching (${r}s elapsed)`)},3e3);try{await new Promise((r,s)=>{let a=D("curl",["-fsSL",i],{stdio:["ignore","pipe","inherit"]}),f=D("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});a.stdout.pipe(f.stdin);let l,u,d=()=>{if(l!==void 0&&u!==void 0){if(l!==0)return s(new Error(`curl exited ${l}`));if(u!==0)return s(new Error(`tar exited ${u}`));r()}};a.on("close",S=>{l=S,d()}),f.on("close",S=>{u=S,d()}),a.on("error",s),f.on("error",s)})}finally{clearInterval(n)}let c=((Date.now()-o)/1e3).toFixed(1);return console.log(`[setup] Bundle extracted (${c}s)`),e}async function K(){let i=process.env.WORKFLOW_SOURCES_URL;if(!i)throw new Error("WORKFLOW_SOURCES_URL env var is required");let e=await fetch(i);if(!e.ok)throw new Error(`Failed to fetch sources: ${e.status} ${e.statusText}`);let o=await e.json();if(!o.sources||typeof o.sources!="object")throw new Error('Invalid sources payload \u2014 missing "sources" map');return o}function te(i,e){let o=B(e),n=0;for(let[c,r]of Object.entries(i)){let s=B(e,c);if(!s.startsWith(`${o}/`)&&s!==o){console.error(` \u26D4 Skipping unsafe path: ${c}`);continue}W(Z(s),{recursive:!0}),Y(s,r,"utf-8"),n++}return n}async function ne(i,e){let o=g(i,"graph.mjs");if(!w(o))throw new Error(`graph.mjs not found at ${o}`);let n=await import(A(o).href),c=e?.entryClass,r=c&&n[c]||n.default||Object.values(n).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!r)throw new Error("No WorkflowAgent class found in graph.mjs");return r}async function ge(){if(!process.env.NODE_PATH){process.env.NODE_PATH="/opt/zibby/packages";let t=await import("module");t.default._initPaths&&t.default._initPaths()}let{WORKFLOW_JOB_ID:i,WORKFLOW_TYPE:e,PROJECT_ID:o,AGENT_TYPE:n,MODEL:c}=process.env;e||(console.error("Missing WORKFLOW_TYPE env var"),process.exit(1));let r=L({workflowType:e,jobId:i,projectId:o,agentType:n,model:c});console.log(r);let s=process.env.WORKFLOW_BUNDLE_URL,a,f={},l,u;if(s){l=e,a=g(T,".zibby","workflows",l);try{await oe(s,a);try{let t=await K();f=t.input||{},u=t.version}catch(t){console.warn(`[setup] Could not fetch input payload: ${t.message}`)}}catch(t){console.warn(`[setup] Bundle extract failed (${t.message}); falling back to source install`),a=null}}if(!a){let t=await K(),{sources:p,input:y,workflowType:O,version:E}=t;f=y||{},l=O||e,u=E,console.log(`[setup] Workflow v${u||"?"} (${Object.keys(p).length} files)`),a=g(T,".zibby","workflows",l);let b=te(p,a);console.log(`[setup] Wrote ${b} files`),console.log("[setup] Installing dependencies...");try{ee("npm install --silent --no-audit --no-fund",{cwd:a,stdio:"inherit"}),console.log("[setup] Dependencies installed")}catch($){console.warn(`[setup] npm install failed: ${$.message}`)}}let d={},S=g(a,"workflow.json");if(w(S)){let{readFileSync:t}=await import("fs");d=JSON.parse(t(S,"utf-8"))}let I=await ne(a,d);console.log(`[setup] Loaded ${I.name}`);let m=[],x=g(a,"node_modules","@zibby","agent-workflow"),C=g(a,"node_modules","@zibby","core","node_modules","@zibby","agent-workflow");w(x)&&m.push({kind:"hoisted",path:x}),w(C)&&m.push({kind:"nested",path:C});let R=process.env.ZIBBY_RUN_DIAG==="1";if(R){let{readdirSync:t}=await import("fs");console.log(` [diag] @zibby/agent-workflow copies in bundle: ${m.length}`);for(let p of m)console.log(` [diag] ${p.kind}: ${p.path}`);try{let p=g(a,"node_modules","@zibby");w(p)&&console.log(` [diag] node_modules/@zibby/ contents: [${t(p).join(", ")}]`)}catch{}}let k=g(a,"node_modules","@zibby","core","dist","index.js");if(w(k)&&m.length>0)try{let t=await import(A(k).href),p=[t.AssistantStrategy,t.CursorAgentStrategy,t.ClaudeAgentStrategy,t.CodexAgentStrategy,t.GeminiAgentStrategy].filter(Boolean);for(let y of m){let O=g(y.path,"dist","index.js");if(!w(O))continue;let E=await import(A(O).href),b=R?E.listStrategies():null;for(let $ of p)try{E.registerStrategy(new $)}catch(J){console.warn(` register ${$.name} into ${y.kind} failed: ${J.message}`)}R&&console.log(` [diag] ${y.kind} registry: before=[${b.join(",")||"empty"}] after=[${E.listStrategies().join(",")||"empty"}]`)}console.log("[setup] Registered 5 agent strategies (assistant, cursor, claude, codex, gemini)")}catch(t){console.warn(`[setup] Failed to bridge strategies: ${t.message}`)}else console.warn("[setup] No @zibby/core or @zibby/agent-workflow in bundle \u2014 agent strategies may be unavailable");let G=Date.now(),_=new I({workflow:l||e}),z=_.buildGraph(),Q={input:f||{},cwd:T,runId:i||`run-${Date.now()}`};console.log("");let h;try{h=await z.run(_,Q)}catch(t){console.error(`
4
+ Workflow execution failed: ${t.message}`),console.error(t.stack),await U("failed",t.message),process.exit(1)}let v=((Date.now()-G)/1e3).toFixed(1),j=h?.success!==!1,N=l||e;j?(console.log(`
5
+ [done] ${N} completed in ${v}s`),await U("completed")):(console.error(`
6
+ [done] ${N} failed after ${v}s`),await U("failed",h?.error||"Workflow execution failed"),process.exit(1)),_.onComplete&&await _.onComplete(h)}async function U(i,e=null){let o={EXECUTION_ID:process.env.WORKFLOW_JOB_ID,PROGRESS_API_URL:process.env.PROGRESS_API_URL,PROGRESS_QUEUE_URL:process.env.PROGRESS_QUEUE_URL,PROJECT_API_TOKEN:process.env.PROJECT_API_TOKEN,SQS_AUTH_TOKEN:process.env.SQS_AUTH_TOKEN};if(o.EXECUTION_ID)try{await F(o,{status:i,...e&&{error:e}})}catch(n){console.error(`\u26A0\uFE0F Failed to report status: ${n.message}`)}}export{ge as runWorkflowCommand};
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/cli",
3
- "version": "0.1.87",
3
+ "version": "0.1.90",
4
4
  "description": "Zibby CLI - Test automation generator and runner",
5
5
  "type": "module",
6
6
  "bin": {
@@ -8,7 +8,7 @@
8
8
  },
9
9
  "scripts": {
10
10
  "build": "node ../scripts/build.mjs --extra-dirs bin",
11
- "test": "vitest run test/auth*.test.js test/two-layer-auth.test.js test/trigger-params.test.js test/trigger-helpers.test.js test/deploy-helpers.test.js test/cli-namespace-consistency.test.js test/cli-workflow-subcommands.test.js test/run-bundle-core-import.test.js test/start-respects-config.test.js test/sse-backoff.test.js test/sse-reconnect-loop.test.js",
11
+ "test": "vitest run test/auth*.test.js test/two-layer-auth.test.js test/trigger-params.test.js test/trigger-helpers.test.js test/deploy-helpers.test.js test/cli-namespace-consistency.test.js test/cli-workflow-subcommands.test.js test/run-bundle-core-import.test.js test/start-respects-config.test.js test/sse-backoff.test.js test/sse-reconnect-loop.test.js test/run-helpers.test.js test/sse-parser.test.js",
12
12
  "test:unit": "vitest run src/",
13
13
  "test:auth": "vitest run test/auth*.test.js test/two-layer-auth.test.js",
14
14
  "lint": "eslint .",
@@ -34,7 +34,7 @@
34
34
  "dependencies": {
35
35
  "@aws-sdk/client-sqs": "^3.1038.0",
36
36
  "@zibby/agent-workflow": "^0.1.2",
37
- "@zibby/core": "^0.1.47",
37
+ "@zibby/core": "^0.1.48",
38
38
  "@zibby/memory": "^0.1.5",
39
39
  "@zibby/skills": "^0.1.11",
40
40
  "adm-zip": "^0.5.17",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/cli",
3
- "version": "0.1.87",
3
+ "version": "0.1.90",
4
4
  "description": "Zibby CLI - Test automation generator and runner",
5
5
  "type": "module",
6
6
  "bin": {
@@ -8,7 +8,7 @@
8
8
  },
9
9
  "scripts": {
10
10
  "build": "node ../scripts/build.mjs --extra-dirs bin",
11
- "test": "vitest run test/auth*.test.js test/two-layer-auth.test.js test/trigger-params.test.js test/trigger-helpers.test.js test/deploy-helpers.test.js test/cli-namespace-consistency.test.js test/cli-workflow-subcommands.test.js test/run-bundle-core-import.test.js test/start-respects-config.test.js test/sse-backoff.test.js test/sse-reconnect-loop.test.js",
11
+ "test": "vitest run test/auth*.test.js test/two-layer-auth.test.js test/trigger-params.test.js test/trigger-helpers.test.js test/deploy-helpers.test.js test/cli-namespace-consistency.test.js test/cli-workflow-subcommands.test.js test/run-bundle-core-import.test.js test/start-respects-config.test.js test/sse-backoff.test.js test/sse-reconnect-loop.test.js test/run-helpers.test.js test/sse-parser.test.js",
12
12
  "test:unit": "vitest run src/",
13
13
  "test:auth": "vitest run test/auth*.test.js test/two-layer-auth.test.js",
14
14
  "lint": "eslint .",
@@ -34,7 +34,7 @@
34
34
  "dependencies": {
35
35
  "@aws-sdk/client-sqs": "^3.1038.0",
36
36
  "@zibby/agent-workflow": "^0.1.2",
37
- "@zibby/core": "^0.1.47",
37
+ "@zibby/core": "^0.1.48",
38
38
  "@zibby/memory": "^0.1.5",
39
39
  "@zibby/skills": "^0.1.11",
40
40
  "adm-zip": "^0.5.17",