@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.
- package/dist/commands/workflows/deploy-helpers.js +1 -1
- package/dist/commands/workflows/deploy.js +25 -25
- package/dist/commands/workflows/generate.js +1 -1
- package/dist/commands/workflows/logs.js +33 -33
- package/dist/commands/workflows/run-helpers.js +2 -0
- package/dist/commands/workflows/run.js +5 -7
- package/dist/package.json +3 -3
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
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
|
|
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
|
|
4
|
-
`));let{createInterface:t}=await import("readline"),
|
|
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),
|
|
8
|
-
`));let g=await
|
|
9
|
-
`)),n({success:!0,...
|
|
10
|
-
\u274C Login failed:`,
|
|
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",
|
|
14
|
-
`)),{success:!0,loggedIn:!0,user:c.user,token:c.token}}if(c.status==="denied")throw
|
|
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
|
|
17
|
-
Not logged in.`));let n;try{n=await
|
|
18
|
-
`);continue}
|
|
19
|
-
`)}if(f.text=M({elapsedMs:Date.now()-y,phase:
|
|
20
|
-
Error: Workflow not found: ${n}/${
|
|
21
|
-
`),process.exit(1))}else{let
|
|
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:
|
|
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(""),
|
|
26
|
-
Error: graph.mjs not found in ${n}/${
|
|
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: ${
|
|
29
|
-
`),process.exit(1)}let
|
|
30
|
-
`),process.exit(1)}d.text="Saving workflow definition...";let z=await fetch(`${E}/projects/${r}/workflows/${
|
|
31
|
-
`),process.exit(1)}let
|
|
32
|
-
`,"utf-8")}catch(h){console.log(` Warning: failed to write ${D}: ${h.message}`)}}let
|
|
33
|
-
`)}}catch(h){
|
|
34
|
-
`),process.exit(1)}}export{
|
|
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.
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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)),
|
|
10
|
-
`)
|
|
11
|
-
\u250C\u2500 Execution: ${
|
|
12
|
-
`))}
|
|
13
|
-
Waiting for next execution...`))
|
|
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
|
-
`),
|
|
16
|
-
`),
|
|
17
|
-
Execution failed.`),
|
|
18
|
-
`):"");let
|
|
19
|
-
`)),T({token:
|
|
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",
|
|
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"
|
|
24
|
-
`):"");!
|
|
25
|
-
Job ${
|
|
26
|
-
Status: ${
|
|
27
|
-
${
|
|
28
|
-
`)),process.exit(1)),
|
|
29
|
-
Too many consecutive errors (${
|
|
30
|
-
`)),process.exit(1)),
|
|
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",
|
|
33
|
-
Tailing all runs for ${e.cyan(
|
|
34
|
-
`):"");!
|
|
35
|
-
... more logs available. Run again or use --follow to stream.`)),
|
|
36
|
-
No running jobs. All caught up.`));break}let
|
|
37
|
-
${
|
|
38
|
-
`)),process.exit(1)),
|
|
39
|
-
Too many consecutive errors (${
|
|
40
|
-
`)),process.exit(1)),
|
|
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)),
|
|
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};
|
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{mkdirSync as
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
`)
|
|
6
|
-
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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",
|