@zibby/cli 0.4.12 → 0.4.13
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,42 +1,42 @@
|
|
|
1
|
-
import e from"chalk";import{readFileSync as
|
|
1
|
+
import e from"chalk";import{readFileSync as j,existsSync as O,writeSync as B}from"fs";import{homedir as F}from"os";import{join as z}from"path";var A="https://logs.workflows.zibby.app",J="https://logs-stream.zibby.app/",v=null;async function U(a){return v||(process.env.ZIBBY_SSE_ENDPOINT?(v=process.env.ZIBBY_SSE_ENDPOINT,v):(v=J,v))}function G(a){let t=z(F(),".zibby","config.json");O(t)||(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 o;try{o=JSON.parse(j(t,"utf-8"))}catch{console.log(e.red(`
|
|
4
4
|
Config file corrupt`)),console.log(e.gray(` Run: zibby login
|
|
5
|
-
`)),process.exit(1)}let o
|
|
5
|
+
`)),process.exit(1)}let n=o.sessionToken;n||(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 u=a.project;return{token:n,projectId:u}}function C(a){let t=new Date(a);if(process.env.ZIBBY_LOGS_UTC==="1")return t.toISOString().replace("T"," ").replace("Z","");let o=(n,u=2)=>String(n).padStart(u,"0");return`${t.getFullYear()}-${o(t.getMonth()+1)}-${o(t.getDate())} ${o(t.getHours())}:${o(t.getMinutes())}:${o(t.getSeconds())}.${o(t.getMilliseconds(),3)}`}async function L(a,t){let o=await fetch(a,{headers:{Authorization:`Bearer ${t}`}});if(!o.ok){let n=await o.text();throw new Error(`API ${o.status}: ${n}`)}return o.json()}async function W(a,t,o,n){return a||(console.log(e.red(`
|
|
8
8
|
Workflow UUID is required`)),console.log(e.gray(" Usage: zibby workflow logs <workflow-uuid>")),console.log(e.gray(` zibby workflow logs <workflow-uuid> -t
|
|
9
|
-
`)),process.exit(1)),a}function D(a,
|
|
10
|
-
`),
|
|
9
|
+
`)),process.exit(1)),a}function D(a,t){let n=((a||"")+t).split(`
|
|
10
|
+
`),u=n.pop()||"",i=[],f=null,s=null;for(let m=0;m<n.length;m++){let l=n[m];if(l.trim()){if(l.startsWith("id:")){f=l.slice(3).trim();continue}if(l.startsWith("event:")){let g=l.slice(6).trim();if(g==="log")continue;if(g==="status"){let c=n[m+1];if(c&&c.startsWith("data:"))try{let h=JSON.parse(c.slice(5).trim());h.status==="new_execution"?i.push({type:"newExecution",executionId:h.executionId,taskId:h.taskId}):h.status==="waiting"&&i.push({type:"waiting"})}catch{}continue}if(g==="complete"){i.push({type:"complete"});continue}if(g==="error"){let c=n[m+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 g=l.slice(5).trim();if(!g)continue;try{let c=JSON.parse(g);c.timestamp&&c.message&&i.push({type:"log",timestamp:c.timestamp,message:c.message,taskId:c.taskId})}catch{}}}}return{actions:i,remainder:u,lastEventId:f,returnSignal:s}}async function Y({token:a,executionId:t,sseEndpoint:o,stopped:n}){let u=null;try{let y=function(){let b=Array.from(I.entries()).slice(0,c);I.clear();for(let[w,p]of b)I.set(w,p);r=new Set(Array.from(I.values()).map(w=>w.taskId).filter(Boolean));for(let w of[...d.keys()])I.has(w)||d.delete(w)},x=function(S){for(let[b,w]of I)if(w.taskId===S)return b;return null},T=function(S){let b=I.get(S);!b||b.headerPrinted||(console.log(e.cyan(`
|
|
11
11
|
\u250C\u2500 Execution: ${b.shortId} (task: ${b.taskSuffix})`)),console.log(e.cyan(` \u2514\u2500 Streaming logs...
|
|
12
|
-
`)),b.headerPrinted=!0)},
|
|
13
|
-
Waiting for next execution...`));break;case"complete":
|
|
12
|
+
`)),b.headerPrinted=!0)},P=function(S){let b=e.gray(C(S.timestamp)),w=S.taskId?e.gray(`(${S.taskId.slice(-8)}) `):"";console.log(`${b} ${w}${S.message.replace(/\n$/,"")}`)},_=function(){if(!k)return;k=!1,$&&(clearTimeout($),$=null);let S=Array.from(I.entries()).reverse();for(let[b]of S){let w=d.get(b);if(!(!w||w.length===0)){T(b);for(let p of w)P(p)}}d.clear()},N=function(){k&&($&&clearTimeout($),$=setTimeout(_,h))},i=new URL(o);i.searchParams.set("jobId",t),u&&i.searchParams.set("lastEventId",u);let f=await fetch(i.toString(),{headers:{Authorization:`Bearer ${a}`,Accept:"text/event-stream"}});if(!f.ok)throw new Error(`SSE connection failed: ${f.status} ${f.statusText}`);let s=f.body.getReader(),m=new TextDecoder,l="",g=!1,c=Number(process.env.ZIBBY_LOGS_HISTORY_LIMIT)||10,h=Number(process.env.ZIBBY_LOGS_REPLAY_TIMEOUT_MS)||3e3,I=new Map,r=new Set,d=new Map,k=!0,$=null;for(N();!n.value;){let{done:S,value:b}=await s.read();if(S)break;let w=D(l,m.decode(b,{stream:!0}));l=w.remainder,w.lastEventId&&(u=w.lastEventId);for(let p of w.actions)switch(p.type){case"newExecution":{let E=`${p.executionId.slice(0,8)}...${p.executionId.slice(-4)}`,R=p.taskId?p.taskId.slice(-8):"pending";I.set(p.executionId,{shortId:E,taskSuffix:R,taskId:p.taskId||null,headerPrinted:!1}),d.has(p.executionId)||d.set(p.executionId,[]),y(),N();break}case"waiting":_(),console.log(e.gray(`
|
|
13
|
+
Waiting for next execution...`));break;case"complete":_(),g=!0;break;case"log":{if(p.taskId&&r.size>0&&!r.has(p.taskId))break;if(k){let E=p.taskId?x(p.taskId):null;if(E){let R=d.get(E)||[];R.push(p),d.set(E,R),N()}else P(p)}else{if(p.taskId){let E=x(p.taskId);E&&T(E)}P(p)}break}}if(w.returnSignal)return w.returnSignal.type==="notFound"?{notFound:!0}:{failed:!0}}return _(),{completed:g}}catch(i){if(i.name==="AbortError")return{aborted:!0};throw i}}function H(a,{baseMs:t=500,capMs:o=3e4,rand:n=Math.random}={}){let u=Math.min(o,t*Math.pow(2,Math.max(0,a)));return Math.floor(n()*u)}async function Z({attemptStream:a,stopped:t,follow:o,logger:n,sleep:u=m=>new Promise(l=>setTimeout(l,m)),exit:i=m=>{throw new Error(`exit:${m}`)},backoff:f=H,notFoundPollMs:s=5e3}){let m=0,l=!1;for(;!t.value;){let g;try{g=await a(),m=0}catch(c){if(c.name==="AbortError"||t.value)return{reason:"aborted"};if(l||(n.error(` SSE Error: ${c.message}`),o&&n.gray(" Reconnecting..."),l=!0),!o)return i("error")??{reason:"error"};let h=f(m);m++,await u(h);continue}if(g.aborted||t.value)return{reason:"aborted"};if(g.notFound){if(o){l||(n.yellow(" No executions found yet. Waiting for workflow to be triggered..."),n.gray(" Press Ctrl+C to stop."),l=!0),await u(s);continue}return n.yellow(`
|
|
14
14
|
No executions found for this workflow. Trigger the workflow first.
|
|
15
|
-
`),i("notFound")??{reason:"notFound"}}if(l&&(
|
|
16
|
-
`),l=!1),
|
|
17
|
-
Execution failed.`),
|
|
18
|
-
`):"");let
|
|
19
|
-
`)),
|
|
15
|
+
`),i("notFound")??{reason:"notFound"}}if(l&&(n.gray(` Reconnected.
|
|
16
|
+
`),l=!1),g.failed)return n.red(`
|
|
17
|
+
Execution failed.`),o?{reason:"failed"}:i("failed")??{reason:"failed"};if(g.completed)return i("completed")??{reason:"completed"};if(!o)return{reason:"disconnected"}}return{reason:"stopped"}}async function V({token:a,jobId:t,follow:o,projectId:n}){console.log(e.gray(` Streaming logs for workflow ${e.cyan(t)}...`)),console.log(o?e.gray(` Press Ctrl+C to stop.
|
|
18
|
+
`):"");let u=await U(a);if(!u)return console.log(e.yellow(` SSE endpoint not configured, using CloudWatch polling...
|
|
19
|
+
`)),M({token:a,projectId:null,jobId:t,follow:o,limit:1e5});let i={value:!1},f=()=>{i.value=!0;try{B(2,`
|
|
20
20
|
Stopped streaming.
|
|
21
|
-
`)}catch{}process.exit(0)};process.prependListener("SIGINT",
|
|
21
|
+
`)}catch{}process.exit(0)};process.prependListener("SIGINT",f),process.prependListener("SIGTERM",f),await Z({attemptStream:()=>Y({token:a,executionId:t,sseEndpoint:u,stopped:i}),stopped:i,follow:o,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 M({token:a,projectId:t,jobId:o,follow:n,limit:u}){let i=t?`${A}/logs/${t}/${o}`:`${A}/job/${o}`,f=null,s=0,m=new Set,l=!1,g=0,c=5,h=()=>{l=!0,console.log(e.gray(`
|
|
22
22
|
Stopped tailing.
|
|
23
|
-
`)),process.exit(0)};for(process.on("SIGINT",h),process.on("SIGTERM",h),console.log(e.gray(` Fetching logs for workflow ${e.cyan(
|
|
24
|
-
`):"");!l;)try{let I=new URLSearchParams({limit:String(
|
|
25
|
-
Job ${r.status}.`)),process.exit(r.status==="completed"?0:1)}if(!
|
|
26
|
-
Status: ${r.status}`));break}let
|
|
23
|
+
`)),process.exit(0)};for(process.on("SIGINT",h),process.on("SIGTERM",h),console.log(e.gray(` Fetching logs for workflow ${e.cyan(o)}...`)),console.log(n?e.gray(` Press Ctrl+C to stop.
|
|
24
|
+
`):"");!l;)try{let I=new URLSearchParams({limit:String(u)});f&&I.set("nextToken",f);let r=await L(`${i}?${I}`,a);g=0,r.message&&r.lines?.length===0&&s===0&&console.log(e.gray(` ${r.message}`)),r.status==="starting"&&r.lines?.length===0&&s===0&&console.log(e.gray(" Container starting..."));for(let y of r.lines||[]){let x=`${y.timestamp}:${y.message}`;if(m.has(x))continue;m.add(x);let T=e.gray(C(y.timestamp)),P=r.taskId?e.gray(`(${r.taskId.slice(-8)}) `):"";console.log(`${T} ${P}${y.message.replace(/\n$/,"")}`)}if(s=r.lines?.length>0?0:s+1,f=r.nextForwardToken||null,r.status==="completed"||r.status==="failed"){let y=r.status==="completed"?e.green:e.red;console.log(y(`
|
|
25
|
+
Job ${r.status}.`)),process.exit(r.status==="completed"?0:1)}if(!n){r.status&&console.log(e.gray(`
|
|
26
|
+
Status: ${r.status}`));break}let $=r.lines?.length>0?500:s>5?5e3:2e3;await new Promise(y=>setTimeout(y,$))}catch(I){if(I.name==="AbortError")break;I.message.match(/API (400|401|403|404):/)&&(console.error(e.red(`
|
|
27
27
|
${I.message}
|
|
28
|
-
`)),process.exit(1)),
|
|
28
|
+
`)),process.exit(1)),g++,console.error(e.red(` Error: ${I.message}`)),g>=c&&(console.error(e.red(`
|
|
29
29
|
Too many consecutive errors (${c}). Stopping.
|
|
30
|
-
`)),process.exit(1)),
|
|
30
|
+
`)),process.exit(1)),n||process.exit(1),await new Promise(d=>setTimeout(d,3e3))}}async function X({token:a,projectId:t,workflow:o,follow:n,limit:u}){let i=`${A}/all/${t}`,f=null,s=0,m=new Set,l=null,g=!1,c=0,h=5,I=()=>{g=!0,console.log(e.gray(`
|
|
31
31
|
Stopped tailing.
|
|
32
32
|
`)),process.exit(0)};for(process.on("SIGINT",I),process.on("SIGTERM",I),console.log(e.gray(`
|
|
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
|
|
33
|
+
Tailing all runs for ${e.cyan(o)}...`)),console.log(n?e.gray(` Press Ctrl+C to stop.
|
|
34
|
+
`):"");!g;)try{let r=new URLSearchParams({workflow:o,limit:String(u)});f&&r.set("nextToken",f);let d=await L(`${i}?${r}`,a);c=0,d.message&&d.lines?.length===0&&s===0&&console.log(e.gray(` ${d.message}`));for(let y of d.lines||[]){let x=`${y.timestamp}:${y.jobId}:${y.message}`;if(m.has(x))continue;m.add(x),y.jobId!==l&&(l!==null&&console.log(""),console.log(e.dim(` \u2500\u2500 ${y.jobId} \u2500\u2500`)),l=y.jobId);let T=e.gray(C(y.timestamp));console.log(`${T} ${y.message.replace(/\n$/,"")}`)}if(s=d.lines?.length>0?0:s+1,f=d.nextToken||null,!n){f&&console.log(e.gray(`
|
|
35
|
+
... more logs available. Run again or use --follow to stream.`)),d.jobCount&&console.log(e.gray(` ${d.jobCount} job(s) found.`));break}if(!d.hasRunning&&!f&&s>2){console.log(e.gray(`
|
|
36
|
+
No running jobs. All caught up.`));break}let $=d.lines?.length>0?500:s>5?5e3:2e3;await new Promise(y=>setTimeout(y,$))}catch(r){if(r.name==="AbortError")break;r.message.match(/API (400|401|403|404):/)&&(console.error(e.red(`
|
|
37
37
|
${r.message}
|
|
38
38
|
`)),process.exit(1)),c++,console.error(e.red(` Error: ${r.message}`)),c>=h&&(console.error(e.red(`
|
|
39
39
|
Too many consecutive errors (${h}). Stopping.
|
|
40
|
-
`)),process.exit(1)),
|
|
40
|
+
`)),process.exit(1)),n||process.exit(1),await new Promise(k=>setTimeout(k,3e3))}}async function oe(a,t){let{token:o,projectId:n}=G(t),u=t.follow===!0,i=t.lines?parseInt(t.lines,10):1e5;if(t.all){let s=t.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)),X({token:
|
|
42
|
+
`)),process.exit(1)),X({token:o,projectId:n,workflow:s,follow:u,limit:i})}let f=await W(a,t,o,n);return u?V({token:o,jobId:f,follow:u,projectId:n}):M({token:o,projectId:n,jobId:f,follow:!1,limit:i})}export{oe as logsCommand,D as parseSseChunk,Z as runReconnectLoop,H as sseBackoffMs};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import{existsSync as h,writeFileSync as l}from"fs";import{join as a}from"path";var s={width:1280,height:720},f="on",w="tests",p="test-results/playwright";function d(t={}){let r=t.viewport&&typeof t.viewport=="object"?{width:Number(t.viewport.width)||s.width,height:Number(t.viewport.height)||s.height}:s,i=typeof t.video=="string"?t.video:f,n=t.paths?.generated||w,e=t.playwrightArtifacts!==!1,o=e?"on":"off",c=e?"only-on-failure":"off";return`// AUTO-GENERATED at workflow run start by @zibby/cli's
|
|
2
|
+
// playwright-config-materialize.js. Derived from the bundled
|
|
3
|
+
// zibby.config.json (which @zibby/workflow-deploy serialized from your
|
|
4
|
+
// project's .zibby.config.mjs). Do NOT edit by hand \u2014 re-run a workflow
|
|
5
|
+
// to regenerate, or commit a hand-rolled playwright.config.{js,ts,mjs}
|
|
6
|
+
// inside the workflow bundle and the runner will respect it.
|
|
7
|
+
|
|
8
|
+
import { defineConfig } from '@playwright/test';
|
|
9
|
+
|
|
10
|
+
export default defineConfig({
|
|
11
|
+
testDir: '${n.replace(/'/g,"\\'")}',
|
|
12
|
+
outputDir: '${p}',
|
|
13
|
+
timeout: 60000,
|
|
14
|
+
retries: 0,
|
|
15
|
+
workers: 1,
|
|
16
|
+
|
|
17
|
+
use: {
|
|
18
|
+
headless: process.env.PLAYWRIGHT_HEADLESS === '1',
|
|
19
|
+
viewport: { width: ${r.width}, height: ${r.height} },
|
|
20
|
+
video: '${i}',
|
|
21
|
+
trace: '${o}',
|
|
22
|
+
screenshot: '${c}',
|
|
23
|
+
},
|
|
24
|
+
|
|
25
|
+
reporter: [['list']],
|
|
26
|
+
});
|
|
27
|
+
`}function m(t,r){if(!t)return{written:!1,path:null,reason:"no workspaceDir"};for(let e of["js","mjs","ts"]){let o=a(t,`playwright.config.${e}`);if(h(o))return{written:!1,path:o,reason:`existing playwright.config.${e} in workspace`}}let i=a(t,"playwright.config.js"),n=d(r||{});try{return l(i,n,"utf-8"),{written:!0,path:i,reason:"derived from zibby.config"}}catch(e){return{written:!1,path:null,reason:`write failed: ${e.message}`}}}export{d as buildPlaywrightConfig,m as materializePlaywrightConfig};
|
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}import
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
var ce=Object.defineProperty;var le=(t,e)=>()=>(t&&(e=t(t=0)),e);var pe=(t,e)=>{for(var o in e)ce(t,o,{get:e[o],enumerable:!0})};var q={};pe(q,{uploadSessionArtifacts:()=>ke});import{readdirSync as Y,statSync as U,createReadStream as _e,existsSync as be}from"node:fs";import{join as M,relative as Oe,sep as Re,extname as Te}from"node:path";function ve(t){let e=Te(t).toLowerCase();return Ae[e]||"application/octet-stream"}function H(t){let e=[],o;try{o=Y(t)}catch{return e}for(let r of o){if(Pe.has(r)||r.startsWith("."))continue;let n=M(t,r),i;try{i=U(n)}catch{continue}i.isDirectory()?e.push(...H(n)):i.isFile()&&e.push(n)}return e}async function xe({apiUrl:t,apiKey:e,executionId:o,nodeName:r,filename:n,absolutePath:i,sizeBytes:s,contentType:f}){let p;try{let c=await fetch(`${t}/executions/${o}/artifacts/upload-url`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({nodeName:r,filename:n,contentType:f,sizeBytes:s})});if(!c.ok){let a=await c.text();return console.warn(`[artifacts] upload-url failed for ${r}/${n}: ${c.status} ${a.slice(0,200)}`),null}p=await c.json()}catch(c){return console.warn(`[artifacts] upload-url request errored for ${r}/${n}: ${c.message}`),null}try{let c=_e(i),a=await fetch(p.url,{method:"PUT",headers:{"Content-Type":f,"Content-Length":String(s)},body:c,duplex:"half"});if(!a.ok)return console.warn(`[artifacts] S3 PUT failed for ${r}/${n}: ${a.status}`),null}catch(c){return console.warn(`[artifacts] S3 PUT errored for ${r}/${n}: ${c.message}`),null}return{nodeName:r,filename:n,s3Key:p.s3Key,contentType:f,sizeBytes:s}}async function ke({sessionPath:t,executionId:e,apiUrl:o,apiKey:r}){let n={uploaded:[],skipped:[]};if(!t||!be(t))return n;if(!o||!r||!e)return console.warn("[artifacts] uploader missing required input \u2014 skipping"),n;let i;try{i=Y(t)}catch(a){return console.warn(`[artifacts] could not read session folder ${t}: ${a.message}`),n}let s=[];for(let a of i){let d=M(t,a),g;try{g=U(d)}catch{continue}if(!g.isDirectory()||a.startsWith(".")||a.startsWith("_"))continue;let T=H(d);for(let w of T){let b=Oe(d,w).split(Re).join("/"),m;try{m=U(w).size}catch{continue}if(m>Q){n.skipped.push({nodeName:a,filename:b,reason:`size ${m} > ${Q}`});continue}if(m===0){n.skipped.push({nodeName:a,filename:b,reason:"empty"});continue}s.push({apiUrl:o,apiKey:r,executionId:e,nodeName:a,filename:b,absolutePath:w,sizeBytes:m,contentType:ve(b)})}}if(s.length===0)return n;let f=4,p=s.slice(),c=Array.from({length:Math.min(f,p.length)},async()=>{for(;p.length;){let a=p.shift(),d=await xe(a);d?n.uploaded.push(d):n.skipped.push({nodeName:a.nodeName,filename:a.filename,reason:"upload failed"})}});if(await Promise.all(c),n.uploaded.length>0)try{let a=await fetch(`${o}/executions/${e}/artifacts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({files:n.uploaded})});if(!a.ok){let d=await a.text();console.warn(`[artifacts] record failed: ${a.status} ${d.slice(0,200)}`)}}catch(a){console.warn(`[artifacts] record errored: ${a.message}`)}return n}var Q,Pe,Ae,X=le(()=>{Q=500*1024*1024,Pe=new Set([".DS_Store","Thumbs.db",".zibby-stop"]),Ae={".webm":"video/webm",".mp4":"video/mp4",".mov":"video/quicktime",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".txt":"text/plain",".md":"text/markdown",".html":"text/html",".csv":"text/csv",".log":"text/plain",".json":"application/json",".yaml":"application/yaml",".yml":"application/yaml",".pdf":"application/pdf",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip"}});import{mkdirSync as oe,writeFileSync as Ue,existsSync as E,readFileSync as V}from"fs";import{join as h,dirname as Ie,resolve as Z}from"path";import{pathToFileURL as C}from"url";import{execSync as Ce,spawn as ee}from"node:child_process";import{SQSClient as de,SendMessageCommand as fe}from"@aws-sdk/client-sqs";var x=null;function ue(){return x||(x=new de({region:process.env.AWS_REGION||"ap-southeast-2"})),x}async function K(t,{status:e,error:o}){let{EXECUTION_ID:r,SQS_AUTH_TOKEN:n,PROGRESS_API_URL:i,PROGRESS_QUEUE_URL:s,PROJECT_API_TOKEN:f}=t;if(!r)return;let p={executionId:r,...n&&{sqsAuthToken:n},status:e,...o&&{error:o},timestamp:new Date().toISOString()},c=i?"HTTP":s?"SQS":"NONE",a=JSON.stringify(p).length;console.log(`Sending final status: ${e} via ${c} (${(a/1024).toFixed(1)}KB)`);try{if(i)await ge(i,r,p,f);else if(s){let d=["completed","failed","insufficient_context","blocked"].includes(e)?"execution_completed":"progress_update";await he(s,r,p,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 ${c}`)}catch(d){console.error(`Failed to send final status (${e}) via ${c}:`),console.error(` Payload: ${(a/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 ge(t,e,o,r){let n=`${t}/${e}/progress`,i={"Content-Type":"application/json"};r&&(i.Authorization=`Bearer ${r}`);let s=await fetch(n,{method:"POST",headers:i,body:JSON.stringify(o)});if(!s.ok){let f=await s.text();throw new Error(`HTTP ${s.status}: ${f}`)}}async function he(t,e,o,r="progress_update"){let n=JSON.stringify(o),i=(n.length/1024).toFixed(1);n.length>256*1024&&console.error(`\u274C SQS message too large: ${i}KB (limit 256KB) for ${e} [${r}]`),await ue().send(new fe({QueueUrl:t,MessageBody:n,MessageGroupId:e,MessageAttributes:{executionId:{DataType:"String",StringValue:e},messageType:{DataType:"String",StringValue:r}}}))}function W({workflowType:t,jobId:e,projectId:o,agentType:r,model:n,egressIp:i,egressKind:s}){let f="\u2500".repeat(60),p=`${r||"default"} (model: ${n||"auto"})`,c=["",f,` Workflow: ${t}`,` Job: ${e||"local"}`,` Project: ${o||"none"}`,` Agent: ${p}`];if(i||s){let a=i||"unknown",d=s||"static";c.push(` Egress: ${a} (${d})`)}return c.push(f),c.join(`
|
|
3
|
+
`)}import{existsSync as we,writeFileSync as ye}from"fs";import{join as G}from"path";var k={width:1280,height:720},me="on",Se="tests",Ee="test-results/playwright";function $e(t={}){let e=t.viewport&&typeof t.viewport=="object"?{width:Number(t.viewport.width)||k.width,height:Number(t.viewport.height)||k.height}:k,o=typeof t.video=="string"?t.video:me,r=t.paths?.generated||Se,n=t.playwrightArtifacts!==!1,i=n?"on":"off",s=n?"only-on-failure":"off";return`// AUTO-GENERATED at workflow run start by @zibby/cli's
|
|
4
|
+
// playwright-config-materialize.js. Derived from the bundled
|
|
5
|
+
// zibby.config.json (which @zibby/workflow-deploy serialized from your
|
|
6
|
+
// project's .zibby.config.mjs). Do NOT edit by hand \u2014 re-run a workflow
|
|
7
|
+
// to regenerate, or commit a hand-rolled playwright.config.{js,ts,mjs}
|
|
8
|
+
// inside the workflow bundle and the runner will respect it.
|
|
9
|
+
|
|
10
|
+
import { defineConfig } from '@playwright/test';
|
|
11
|
+
|
|
12
|
+
export default defineConfig({
|
|
13
|
+
testDir: '${r.replace(/'/g,"\\'")}',
|
|
14
|
+
outputDir: '${Ee}',
|
|
15
|
+
timeout: 60000,
|
|
16
|
+
retries: 0,
|
|
17
|
+
workers: 1,
|
|
18
|
+
|
|
19
|
+
use: {
|
|
20
|
+
headless: process.env.PLAYWRIGHT_HEADLESS === '1',
|
|
21
|
+
viewport: { width: ${e.width}, height: ${e.height} },
|
|
22
|
+
video: '${o}',
|
|
23
|
+
trace: '${i}',
|
|
24
|
+
screenshot: '${s}',
|
|
25
|
+
},
|
|
26
|
+
|
|
27
|
+
reporter: [['list']],
|
|
28
|
+
});
|
|
29
|
+
`}function J(t,e){if(!t)return{written:!1,path:null,reason:"no workspaceDir"};for(let n of["js","mjs","ts"]){let i=G(t,`playwright.config.${n}`);if(we(i))return{written:!1,path:i,reason:`existing playwright.config.${n} in workspace`}}let o=G(t,"playwright.config.js"),r=$e(e||{});try{return ye(o,r,"utf-8"),{written:!0,path:o,reason:"derived from zibby.config"}}catch(n){return{written:!1,path:null,reason:`write failed: ${n.message}`}}}import"@zibby/core";var A=process.env.WORKSPACE||"/workspace";async function De(t,e){oe(e,{recursive:!0});let o=Date.now();console.log("[setup] Fetching bundle...");let r=setInterval(()=>{let i=((Date.now()-o)/1e3).toFixed(1);console.log(`[setup] still fetching (${i}s elapsed)`)},3e3);try{await new Promise((i,s)=>{let f=ee("curl",["-fsSL",t],{stdio:["ignore","pipe","inherit"]}),p=ee("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(p.stdin);let c,a,d=()=>{if(c!==void 0&&a!==void 0){if(c!==0)return s(new Error(`curl exited ${c}`));if(a!==0)return s(new Error(`tar exited ${a}`));i()}};f.on("close",g=>{c=g,d()}),p.on("close",g=>{a=g,d()}),f.on("error",s),p.on("error",s)})}finally{clearInterval(r)}let n=((Date.now()-o)/1e3).toFixed(1);return console.log(`[setup] Bundle extracted (${n}s)`),e}async function te(){let t=process.env.WORKFLOW_SOURCES_URL;if(!t)throw new Error("WORKFLOW_SOURCES_URL env var is required");let e=await fetch(t);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 Ne(t){let e=t?.agent;if(!e)return null;if(typeof e=="string")return e;if(typeof e=="object"){if(typeof e.provider=="string")return e.provider;for(let o of["claude","cursor","codex","gemini"])if(e[o])return o}return null}function Fe(t,e){let o=Z(e),r=0;for(let[n,i]of Object.entries(t)){let s=Z(e,n);if(!s.startsWith(`${o}/`)&&s!==o){console.error(` \u26D4 Skipping unsafe path: ${n}`);continue}oe(Ie(s),{recursive:!0}),Ue(s,i,"utf-8"),r++}return r}async function je(){let t=process.env.ZIBBY_EGRESS_PROXY_URL,e=process.env.ZIBBY_EGRESS_TOKEN;if(!(!t||!e))try{let o=await import("undici"),r=new o.ProxyAgent({uri:t,token:`Bearer ${e}`});o.setGlobalDispatcher(r)}catch(o){console.warn(`[setup] Failed to install egress proxy dispatcher: ${o.message}`)}}async function Le(){if(process.env.ZIBBY_EGRESS_IP)return{ip:process.env.ZIBBY_EGRESS_IP,kind:"static"};try{let t=new AbortController,e=setTimeout(()=>t.abort(),1500),o=await fetch("https://api.ipify.org?format=json",{signal:t.signal});return clearTimeout(e),o.ok?{ip:(await o.json())?.ip||null,kind:"dynamic"}:{ip:null,kind:"dynamic"}}catch{return{ip:null,kind:"dynamic"}}}async function Be(t,e){let o=h(t,"graph.mjs");if(!E(o))throw new Error(`graph.mjs not found at ${o}`);let r=await import(C(o).href),n=e?.entryClass,i=n&&r[n]||r.default||Object.values(r).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!i)throw new Error("No WorkflowAgent class found in graph.mjs");return i}async function rt(){if(!process.env.NODE_PATH){process.env.NODE_PATH="/opt/zibby/packages";let l=await import("module");l.default._initPaths&&l.default._initPaths()}await je();let{WORKFLOW_JOB_ID:t,WORKFLOW_TYPE:e,PROJECT_ID:o,AGENT_TYPE:r,MODEL:n}=process.env;e||(console.error("Missing WORKFLOW_TYPE env var"),process.exit(1));let i=process.env.WORKFLOW_BUNDLE_URL,s,f={},p,c;if(i){p=e,s=h(A,".zibby","workflows",p);try{await De(i,s);try{let l=await te();f=l.input||{},c=l.version}catch{}}catch(l){console.warn(`[setup] Bundle extract failed (${l.message}); falling back to source install`),s=null}}if(!s){let l=await te(),{sources:u,input:S,workflowType:$,version:y}=l;f=S||{},p=$||e,c=y,console.log(`[setup] Workflow v${c||"?"} (${Object.keys(u).length} files)`),s=h(A,".zibby","workflows",p);let R=Fe(u,s);console.log(`[setup] Wrote ${R} files`),console.log("[setup] Installing dependencies...");try{Ce("npm install --silent --no-audit --no-fund",{cwd:s,stdio:"inherit"}),console.log("[setup] Dependencies installed")}catch(_){console.warn(`[setup] npm install failed: ${_.message}`)}}let a={},d=h(s,"workflow.json");E(d)&&(a=JSON.parse(V(d,"utf-8")));let g={},T=h(s,"zibby.config.json");if(E(T))try{g=JSON.parse(V(T,"utf-8")),console.log("[setup] Loaded user config from zibby.config.json")}catch(l){console.warn(`[setup] Failed to parse zibby.config.json: ${l.message} \u2014 falling back to defaults`)}let w=J(A,g);w.written?console.log(`[setup] Materialized playwright.config.js \u2192 ${w.path} (${w.reason})`):w.path&&console.log(`[setup] Using existing playwright config: ${w.path}`);let b=Ne(g)||r,m=await Le();console.log(W({workflowType:e,jobId:t,projectId:o,agentType:b,model:n,egressIp:m.ip,egressKind:m.kind}));let D=await Be(s,a);console.log(`[setup] Loaded ${D.name}`);let O=[],N=h(s,"node_modules","@zibby","agent-workflow"),F=h(s,"node_modules","@zibby","core","node_modules","@zibby","agent-workflow");E(N)&&O.push({kind:"hoisted",path:N}),E(F)&&O.push({kind:"nested",path:F});let v=process.env.ZIBBY_RUN_DIAG==="1";if(v){let{readdirSync:l}=await import("fs");console.log(` [diag] @zibby/agent-workflow copies in bundle: ${O.length}`);for(let u of O)console.log(` [diag] ${u.kind}: ${u.path}`);try{let u=h(s,"node_modules","@zibby");E(u)&&console.log(` [diag] node_modules/@zibby/ contents: [${l(u).join(", ")}]`)}catch{}}let j=h(s,"node_modules","@zibby","core","dist","index.js");if(E(j)&&O.length>0)try{let l=await import(C(j).href),u=[l.AssistantStrategy,l.CursorAgentStrategy,l.ClaudeAgentStrategy,l.CodexAgentStrategy,l.GeminiAgentStrategy].filter(Boolean);for(let S of O){let $=h(S.path,"dist","index.js");if(!E($))continue;let y=await import(C($).href),R=v?y.listStrategies():null;for(let _ of u)try{y.registerStrategy(new _)}catch(ae){console.warn(` register ${_.name} into ${S.kind} failed: ${ae.message}`)}v&&console.log(` [diag] ${S.kind} registry: before=[${R.join(",")||"empty"}] after=[${y.listStrategies().join(",")||"empty"}]`)}console.log("[setup] Registered 5 agent strategies (assistant, cursor, claude, codex, gemini)")}catch(l){console.warn(`[setup] Failed to bridge strategies: ${l.message}`)}else console.warn("[setup] No @zibby/core or @zibby/agent-workflow in bundle \u2014 agent strategies may be unavailable");let ne=Date.now(),L=new D({workflow:p||e}),se=L.buildGraph(),re={...f||{},cwd:A,runId:t||`run-${Date.now()}`,config:g,input:f||{}};console.log("");let P;try{P=await se.run(L,re)}catch(l){console.error(`
|
|
30
|
+
Workflow execution failed: ${l.message}`),console.error(l.stack),await I("failed",l.message),process.exit(1)}let B=((Date.now()-ne)/1e3).toFixed(1),ie=P?.success!==!1,z=p||e;if(process.env.UPLOAD_ARTIFACTS!=="0"){let l=P?.state?.sessionPath,u=process.env.PROGRESS_API_URL||process.env.ZIBBY_API_BASE,S=process.env.PROJECT_API_TOKEN,$=process.env.WORKFLOW_JOB_ID;if(l&&u&&S&&$)try{let{uploadSessionArtifacts:y}=await Promise.resolve().then(()=>(X(),q)),{uploaded:R,skipped:_}=await y({sessionPath:l,executionId:$,apiUrl:u,apiKey:S});console.log(`[artifacts] uploaded ${R.length} file(s)${_.length?`, skipped ${_.length}`:""}`)}catch(y){console.warn(`[artifacts] uploader threw: ${y.message}`)}else console.log("[artifacts] skipping upload \u2014 sessionPath/apiUrl/apiKey/executionId missing")}ie?(console.log(`
|
|
31
|
+
[done] ${z} completed in ${B}s`),await I("completed")):(console.error(`
|
|
32
|
+
[done] ${z} failed after ${B}s`),await I("failed",P?.error||"Workflow execution failed"),process.exit(1))}async function I(t,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 K(o,{status:t,...e&&{error:e}})}catch(r){console.error(`\u26A0\uFE0F Failed to report status: ${r.message}`)}}export{Ne as resolveAgentFromConfig,rt as runWorkflowCommand};
|
|
@@ -1,63 +1,63 @@
|
|
|
1
|
-
var K=Object.defineProperty;var q=(e
|
|
1
|
+
var K=Object.defineProperty;var q=(o,e)=>()=>(o&&(e=o(o=0)),e);var H=(o,e)=>{for(var t in e)K(o,t,{get:e[t],enumerable:!0})};var G={};H(G,{logsCommand:()=>me,parseSseChunk:()=>F,runReconnectLoop:()=>J,sseBackoffMs:()=>M});import i from"chalk";import{readFileSync as ne,existsSync as re,writeSync as se}from"fs";import{homedir as ie}from"os";import{join as le}from"path";async function ce(o){return T||(process.env.ZIBBY_SSE_ENDPOINT?(T=process.env.ZIBBY_SSE_ENDPOINT,T):(T=ae,T))}function fe(o){let e=le(ie(),".zibby","config.json");re(e)||(console.log(i.red(`
|
|
2
2
|
Not authenticated`)),console.log(i.gray(` Run: zibby login
|
|
3
|
-
`)),process.exit(1));let t;try{t=JSON.parse(ne(
|
|
3
|
+
`)),process.exit(1));let t;try{t=JSON.parse(ne(e,"utf-8"))}catch{console.log(i.red(`
|
|
4
4
|
Config file corrupt`)),console.log(i.gray(` Run: zibby login
|
|
5
5
|
`)),process.exit(1)}let n=t.sessionToken;n||(console.log(i.red(`
|
|
6
6
|
Not authenticated`)),console.log(i.gray(` Run: zibby login
|
|
7
|
-
`)),process.exit(1));let s=
|
|
7
|
+
`)),process.exit(1));let s=o.project;return{token:n,projectId:s}}function B(o){let e=new Date(o);if(process.env.ZIBBY_LOGS_UTC==="1")return e.toISOString().replace("T"," ").replace("Z","");let t=(n,s=2)=>String(n).padStart(s,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}.${t(e.getMilliseconds(),3)}`}async function Y(o,e){let t=await fetch(o,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok){let n=await t.text();throw new Error(`API ${t.status}: ${n}`)}return t.json()}async function pe(o,e,t,n){return o||(console.log(i.red(`
|
|
8
8
|
Workflow UUID is required`)),console.log(i.gray(" Usage: zibby workflow logs <workflow-uuid>")),console.log(i.gray(` zibby workflow logs <workflow-uuid> -t
|
|
9
|
-
`)),process.exit(1)),
|
|
10
|
-
`),s=n.pop()||"",l=[],a=null,r=null;for(let c=0;c<n.length;c++){let f=n[c];if(f.trim()){if(f.startsWith("id:")){a=f.slice(3).trim();continue}if(f.startsWith("event:")){let d=f.slice(6).trim();if(d==="log")continue;if(d==="status"){let p=n[c+1];if(p&&p.startsWith("data:"))try{let g=JSON.parse(p.slice(5).trim());g.status==="new_execution"?l.push({type:"newExecution",executionId:g.executionId,taskId:g.taskId}):g.status==="waiting"&&l.push({type:"waiting"})}catch{}continue}if(d==="complete"){l.push({type:"complete"});continue}if(d==="error"){let p=n[c+1];if(p&&p.startsWith("data:"))try{if(JSON.parse(p.slice(5).trim()).error==="No executions found for workflow"){r={type:"notFound"};break}}catch{}r={type:"failed"};break}continue}if(f.startsWith("data:")){let d=f.slice(5).trim();if(!d)continue;try{let p=JSON.parse(d);p.timestamp&&p.message&&l.push({type:"log",timestamp:p.timestamp,message:p.message,taskId:p.taskId})}catch{}}}}return{actions:l,remainder:s,lastEventId:a,returnSignal:r}}async function ue({token:
|
|
11
|
-
\u250C\u2500 Execution: ${
|
|
12
|
-
`))
|
|
13
|
-
Waiting for next execution...`));break;case"complete":R(),d=!0;break;case"log":{if(w.taskId&&u.size>0&&!u.has(w.taskId))break;if(k){let S=w.taskId?E(w.taskId):null;if(S){let N=m.get(S)||[];N.push(w),m.set(S,N),P()}else _(w)}else{if(w.taskId){let S=E(w.taskId);S&&v(S)}_(w)}break}}if(I.returnSignal)return I.returnSignal.type==="notFound"?{notFound:!0}:{failed:!0}}return R(),{completed:d}}catch(l){if(l.name==="AbortError")return{aborted:!0};throw l}}function
|
|
9
|
+
`)),process.exit(1)),o}function F(o,e){let n=((o||"")+e).split(`
|
|
10
|
+
`),s=n.pop()||"",l=[],a=null,r=null;for(let c=0;c<n.length;c++){let f=n[c];if(f.trim()){if(f.startsWith("id:")){a=f.slice(3).trim();continue}if(f.startsWith("event:")){let d=f.slice(6).trim();if(d==="log")continue;if(d==="status"){let p=n[c+1];if(p&&p.startsWith("data:"))try{let g=JSON.parse(p.slice(5).trim());g.status==="new_execution"?l.push({type:"newExecution",executionId:g.executionId,taskId:g.taskId}):g.status==="waiting"&&l.push({type:"waiting"})}catch{}continue}if(d==="complete"){l.push({type:"complete"});continue}if(d==="error"){let p=n[c+1];if(p&&p.startsWith("data:"))try{if(JSON.parse(p.slice(5).trim()).error==="No executions found for workflow"){r={type:"notFound"};break}}catch{}r={type:"failed"};break}continue}if(f.startsWith("data:")){let d=f.slice(5).trim();if(!d)continue;try{let p=JSON.parse(d);p.timestamp&&p.message&&l.push({type:"log",timestamp:p.timestamp,message:p.message,taskId:p.taskId})}catch{}}}}return{actions:l,remainder:s,lastEventId:a,returnSignal:r}}async function ue({token:o,executionId:e,sseEndpoint:t,stopped:n}){let s=null;try{let h=function(){let $=Array.from(y.entries()).slice(0,p);y.clear();for(let[I,w]of $)y.set(I,w);u=new Set(Array.from(y.values()).map(I=>I.taskId).filter(Boolean));for(let I of[...m.keys()])y.has(I)||m.delete(I)},E=function(b){for(let[$,I]of y)if(I.taskId===b)return $;return null},v=function(b){let $=y.get(b);!$||$.headerPrinted||(console.log(i.cyan(`
|
|
11
|
+
\u250C\u2500 Execution: ${$.shortId} (task: ${$.taskSuffix})`)),console.log(i.cyan(` \u2514\u2500 Streaming logs...
|
|
12
|
+
`)),$.headerPrinted=!0)},_=function(b){let $=i.gray(B(b.timestamp)),I=b.taskId?i.gray(`(${b.taskId.slice(-8)}) `):"";console.log(`${$} ${I}${b.message.replace(/\n$/,"")}`)},R=function(){if(!k)return;k=!1,x&&(clearTimeout(x),x=null);let b=Array.from(y.entries()).reverse();for(let[$]of b){let I=m.get($);if(!(!I||I.length===0)){v($);for(let w of I)_(w)}}m.clear()},P=function(){k&&(x&&clearTimeout(x),x=setTimeout(R,g))},l=new URL(t);l.searchParams.set("jobId",e),s&&l.searchParams.set("lastEventId",s);let a=await fetch(l.toString(),{headers:{Authorization:`Bearer ${o}`,Accept:"text/event-stream"}});if(!a.ok)throw new Error(`SSE connection failed: ${a.status} ${a.statusText}`);let r=a.body.getReader(),c=new TextDecoder,f="",d=!1,p=Number(process.env.ZIBBY_LOGS_HISTORY_LIMIT)||10,g=Number(process.env.ZIBBY_LOGS_REPLAY_TIMEOUT_MS)||3e3,y=new Map,u=new Set,m=new Map,k=!0,x=null;for(P();!n.value;){let{done:b,value:$}=await r.read();if(b)break;let I=F(f,c.decode($,{stream:!0}));f=I.remainder,I.lastEventId&&(s=I.lastEventId);for(let w of I.actions)switch(w.type){case"newExecution":{let S=`${w.executionId.slice(0,8)}...${w.executionId.slice(-4)}`,N=w.taskId?w.taskId.slice(-8):"pending";y.set(w.executionId,{shortId:S,taskSuffix:N,taskId:w.taskId||null,headerPrinted:!1}),m.has(w.executionId)||m.set(w.executionId,[]),h(),P();break}case"waiting":R(),console.log(i.gray(`
|
|
13
|
+
Waiting for next execution...`));break;case"complete":R(),d=!0;break;case"log":{if(w.taskId&&u.size>0&&!u.has(w.taskId))break;if(k){let S=w.taskId?E(w.taskId):null;if(S){let N=m.get(S)||[];N.push(w),m.set(S,N),P()}else _(w)}else{if(w.taskId){let S=E(w.taskId);S&&v(S)}_(w)}break}}if(I.returnSignal)return I.returnSignal.type==="notFound"?{notFound:!0}:{failed:!0}}return R(),{completed:d}}catch(l){if(l.name==="AbortError")return{aborted:!0};throw l}}function M(o,{baseMs:e=500,capMs:t=3e4,rand:n=Math.random}={}){let s=Math.min(t,e*Math.pow(2,Math.max(0,o)));return Math.floor(n()*s)}async function J({attemptStream:o,stopped:e,follow:t,logger:n,sleep:s=c=>new Promise(f=>setTimeout(f,c)),exit:l=c=>{throw new Error(`exit:${c}`)},backoff:a=M,notFoundPollMs:r=5e3}){let c=0,f=!1;for(;!e.value;){let d;try{d=await o(),c=0}catch(p){if(p.name==="AbortError"||e.value)return{reason:"aborted"};if(f||(n.error(` SSE Error: ${p.message}`),t&&n.gray(" Reconnecting..."),f=!0),!t)return l("error")??{reason:"error"};let g=a(c);c++,await s(g);continue}if(d.aborted||e.value)return{reason:"aborted"};if(d.notFound){if(t){f||(n.yellow(" No executions found yet. Waiting for workflow to be triggered..."),n.gray(" Press Ctrl+C to stop."),f=!0),await s(r);continue}return n.yellow(`
|
|
14
14
|
No executions found for this workflow. Trigger the workflow first.
|
|
15
15
|
`),l("notFound")??{reason:"notFound"}}if(f&&(n.gray(` Reconnected.
|
|
16
16
|
`),f=!1),d.failed)return n.red(`
|
|
17
|
-
Execution failed.`),t?{reason:"failed"}:l("failed")??{reason:"failed"};if(d.completed)return l("completed")??{reason:"completed"};if(!t)return{reason:"disconnected"}}return{reason:"stopped"}}async function de({token:
|
|
18
|
-
`):"");let s=await ce(
|
|
19
|
-
`)),Z({token:
|
|
17
|
+
Execution failed.`),t?{reason:"failed"}:l("failed")??{reason:"failed"};if(d.completed)return l("completed")??{reason:"completed"};if(!t)return{reason:"disconnected"}}return{reason:"stopped"}}async function de({token:o,jobId:e,follow:t,projectId:n}){console.log(i.gray(` Streaming logs for workflow ${i.cyan(e)}...`)),console.log(t?i.gray(` Press Ctrl+C to stop.
|
|
18
|
+
`):"");let s=await ce(o);if(!s)return console.log(i.yellow(` SSE endpoint not configured, using CloudWatch polling...
|
|
19
|
+
`)),Z({token:o,projectId:null,jobId:e,follow:t,limit:1e5});let l={value:!1},a=()=>{l.value=!0;try{se(2,`
|
|
20
20
|
Stopped streaming.
|
|
21
|
-
`)}catch{}process.exit(0)};process.prependListener("SIGINT",a),process.prependListener("SIGTERM",a),await
|
|
21
|
+
`)}catch{}process.exit(0)};process.prependListener("SIGINT",a),process.prependListener("SIGTERM",a),await J({attemptStream:()=>ue({token:o,executionId:e,sseEndpoint:s,stopped:l}),stopped:l,follow:t,logger:{gray:r=>console.log(i.gray(r)),red:r=>console.log(i.red(r)),yellow:r=>console.log(i.yellow(r)),error:r=>console.error(i.red(r))},exit:r=>{r==="completed"&&process.exit(0),(r==="error"||r==="notFound"||r==="failed")&&process.exit(1)}})}async function Z({token:o,projectId:e,jobId:t,follow:n,limit:s}){let l=e?`${A}/logs/${e}/${t}`:`${A}/job/${t}`,a=null,r=0,c=new Set,f=!1,d=0,p=5,g=()=>{f=!0,console.log(i.gray(`
|
|
22
22
|
Stopped tailing.
|
|
23
23
|
`)),process.exit(0)};for(process.on("SIGINT",g),process.on("SIGTERM",g),console.log(i.gray(` Fetching logs for workflow ${i.cyan(t)}...`)),console.log(n?i.gray(` Press Ctrl+C to stop.
|
|
24
|
-
`):"");!f;)try{let y=new URLSearchParams({limit:String(s)});a&&y.set("nextToken",a);let u=await
|
|
24
|
+
`):"");!f;)try{let y=new URLSearchParams({limit:String(s)});a&&y.set("nextToken",a);let u=await Y(`${l}?${y}`,o);d=0,u.message&&u.lines?.length===0&&r===0&&console.log(i.gray(` ${u.message}`)),u.status==="starting"&&u.lines?.length===0&&r===0&&console.log(i.gray(" Container starting..."));for(let h of u.lines||[]){let E=`${h.timestamp}:${h.message}`;if(c.has(E))continue;c.add(E);let v=i.gray(B(h.timestamp)),_=u.taskId?i.gray(`(${u.taskId.slice(-8)}) `):"";console.log(`${v} ${_}${h.message.replace(/\n$/,"")}`)}if(r=u.lines?.length>0?0:r+1,a=u.nextForwardToken||null,u.status==="completed"||u.status==="failed"){let h=u.status==="completed"?i.green:i.red;console.log(h(`
|
|
25
25
|
Job ${u.status}.`)),process.exit(u.status==="completed"?0:1)}if(!n){u.status&&console.log(i.gray(`
|
|
26
26
|
Status: ${u.status}`));break}let x=u.lines?.length>0?500:r>5?5e3:2e3;await new Promise(h=>setTimeout(h,x))}catch(y){if(y.name==="AbortError")break;y.message.match(/API (400|401|403|404):/)&&(console.error(i.red(`
|
|
27
27
|
${y.message}
|
|
28
28
|
`)),process.exit(1)),d++,console.error(i.red(` Error: ${y.message}`)),d>=p&&(console.error(i.red(`
|
|
29
29
|
Too many consecutive errors (${p}). Stopping.
|
|
30
|
-
`)),process.exit(1)),n||process.exit(1),await new Promise(m=>setTimeout(m,3e3))}}async function ge({token:
|
|
30
|
+
`)),process.exit(1)),n||process.exit(1),await new Promise(m=>setTimeout(m,3e3))}}async function ge({token:o,projectId:e,workflow:t,follow:n,limit:s}){let l=`${A}/all/${e}`,a=null,r=0,c=new Set,f=null,d=!1,p=0,g=5,y=()=>{d=!0,console.log(i.gray(`
|
|
31
31
|
Stopped tailing.
|
|
32
32
|
`)),process.exit(0)};for(process.on("SIGINT",y),process.on("SIGTERM",y),console.log(i.gray(`
|
|
33
33
|
Tailing all runs for ${i.cyan(t)}...`)),console.log(n?i.gray(` Press Ctrl+C to stop.
|
|
34
|
-
`):"");!d;)try{let u=new URLSearchParams({workflow:t,limit:String(s)});a&&u.set("nextToken",a);let m=await
|
|
34
|
+
`):"");!d;)try{let u=new URLSearchParams({workflow:t,limit:String(s)});a&&u.set("nextToken",a);let m=await Y(`${l}?${u}`,o);p=0,m.message&&m.lines?.length===0&&r===0&&console.log(i.gray(` ${m.message}`));for(let h of m.lines||[]){let E=`${h.timestamp}:${h.jobId}:${h.message}`;if(c.has(E))continue;c.add(E),h.jobId!==f&&(f!==null&&console.log(""),console.log(i.dim(` \u2500\u2500 ${h.jobId} \u2500\u2500`)),f=h.jobId);let v=i.gray(B(h.timestamp));console.log(`${v} ${h.message.replace(/\n$/,"")}`)}if(r=m.lines?.length>0?0:r+1,a=m.nextToken||null,!n){a&&console.log(i.gray(`
|
|
35
35
|
... more logs available. Run again or use --follow to stream.`)),m.jobCount&&console.log(i.gray(` ${m.jobCount} job(s) found.`));break}if(!m.hasRunning&&!a&&r>2){console.log(i.gray(`
|
|
36
36
|
No running jobs. All caught up.`));break}let x=m.lines?.length>0?500:r>5?5e3:2e3;await new Promise(h=>setTimeout(h,x))}catch(u){if(u.name==="AbortError")break;u.message.match(/API (400|401|403|404):/)&&(console.error(i.red(`
|
|
37
37
|
${u.message}
|
|
38
38
|
`)),process.exit(1)),p++,console.error(i.red(` Error: ${u.message}`)),p>=g&&(console.error(i.red(`
|
|
39
39
|
Too many consecutive errors (${g}). Stopping.
|
|
40
|
-
`)),process.exit(1)),n||process.exit(1),await new Promise(k=>setTimeout(k,3e3))}}async function me(e
|
|
40
|
+
`)),process.exit(1)),n||process.exit(1),await new Promise(k=>setTimeout(k,3e3))}}async function me(o,e){let{token:t,projectId:n}=fe(e),s=e.follow===!0,l=e.lines?parseInt(e.lines,10):1e5;if(e.all){let r=e.workflow;return r||(console.log(i.red(`
|
|
41
41
|
--workflow is required with --all`)),console.log(i.gray(` Example: zibby workflow logs --workflow ticket-triage --all --project <id>
|
|
42
|
-
`)),process.exit(1)),ge({token:t,projectId:n,workflow:r,follow:s,limit:l})}let a=await pe(e,
|
|
43
|
-
Error: --input-file not found: ${
|
|
44
|
-
`),process.exit(1));try{return JSON.parse(ee(
|
|
42
|
+
`)),process.exit(1)),ge({token:t,projectId:n,workflow:r,follow:s,limit:l})}let a=await pe(o,e,t,n);return s?de({token:t,jobId:a,follow:s,projectId:n}):Z({token:t,projectId:n,jobId:a,follow:!1,limit:l})}var A,ae,T,W=q(()=>{A="https://logs.workflows.zibby.app",ae="https://logs-stream.zibby.app/",T=null});import C from"ora";import{select as V}from"@inquirer/prompts";import{readFileSync as ye,existsSync as we}from"fs";import{homedir as he}from"os";import{join as Ie}from"path";var U={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function j(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";U[e]?o=U[e].apiUrl:o=U.prod.apiUrl}try{let e=new URL(o);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),U.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),U.prod.apiUrl}}var X=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function L(o){return o?X.test(o)?{ok:!0}:{ok:!1,error:`'${o}' is not a UUID. Cloud workflows are identified by UUID only. Run \`zibby workflow list\` to find yours, or run \`zibby workflow trigger\` with no argument for interactive selection.`}:{ok:!0}}import{existsSync as Q,readFileSync as ee}from"fs";import{resolve as oe}from"path";function O(o){return o==="true"?!0:o==="false"?!1:o==="null"?null:o!==""&&!isNaN(Number(o))?Number(o):o}function z(o){let e={};for(let t of o||[]){let n=t.indexOf("=");if(n===-1){console.warn(` Warning: ignored param "${t}" \u2014 expected key=value format`);continue}let s=t.slice(0,n).trim(),l=O(t.slice(n+1)),a=s.split("."),r=e;for(let c=0;c<a.length-1;c++)(typeof r[a[c]]!="object"||r[a[c]]===null)&&(r[a[c]]={}),r=r[a[c]];r[a[a.length-1]]=l}return e}function te(o){let e=oe(o);Q(e)||(console.log(`
|
|
43
|
+
Error: --input-file not found: ${o}
|
|
44
|
+
`),process.exit(1));try{return JSON.parse(ee(e,"utf-8"))}catch(t){console.log(`
|
|
45
45
|
Error: --input-file is not valid JSON: ${t.message}
|
|
46
|
-
`),process.exit(1)}}function D(
|
|
46
|
+
`),process.exit(1)}}function D(o){let e={};if(o.inputFile&&(e={...te(o.inputFile)}),o.input)try{e={...e,...JSON.parse(o.input)}}catch(t){console.log(`
|
|
47
47
|
Error: --input is not valid JSON`),console.log(` ${t.message}
|
|
48
|
-
`),process.exit(1)}return
|
|
48
|
+
`),process.exit(1)}return o.param?.length&&(e={...e,...z(o.param)}),e}function $e(){let o=Ie(he(),".zibby","config.json");if(we(o))try{let t=JSON.parse(ye(o,"utf-8"));if(t.sessionToken)return t.sessionToken}catch{}let e=process.env.ZIBBY_API_KEY;if(e)return e;console.log(`
|
|
49
49
|
Not authenticated`),console.log(" Run: zibby login"),console.log(` OR set ZIBBY_API_KEY env var (for CI/CD)
|
|
50
|
-
`),process.exit(1)}async function
|
|
50
|
+
`),process.exit(1)}async function be(o){let e=j(),t=C("Fetching projects...").start();try{let n=await fetch(`${e}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}});n.ok||(t.fail("Failed to fetch projects"),process.exit(1));let s=await n.json();Array.isArray(s)||(s.projects?s=s.projects:s.data&&(s=s.data)),(!s||s.length===0)&&(t.fail("No projects found"),process.exit(1)),t.succeed(`Found ${s.length} project${s.length===1?"":"s"}`),console.log("");let l=s.map(a=>({name:`${a.name||"Unnamed"} (${a.projectId||a.id})`,value:a.projectId||a.id}));return await V({message:"Select a project:",choices:l})}catch(n){t.fail(`Error: ${n.message}`),process.exit(1)}}async function ke(o,e){let t=j(),n=C("Fetching deployed workflows...").start();try{let s=["analysis","implementation","run_test"],l=[];for(let r of s){let c=await fetch(`${t}/projects/${o}/workflows/${r}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}});if(c.ok){let f=await c.json();f.graph&&l.push({name:r,version:f.version||0,isDefault:f.isDefault!==!1})}}l.length===0&&(n.fail("No deployed workflows found for this project"),process.exit(1)),n.succeed(`Found ${l.length} deployed workflow${l.length===1?"":"s"}`),console.log("");let a=l.map(r=>({name:`${r.name} (v${r.version})${r.isDefault?" [default]":""}`,value:r.name}));return await V({message:"Select a workflow to trigger:",choices:a})}catch(s){n.fail(`Error: ${s.message}`),process.exit(1)}}async function Ye(o,e={}){let t=L(o);t.ok||(console.log(`
|
|
51
51
|
Error: ${t.error}
|
|
52
|
-
`),process.exit(1));let n
|
|
53
|
-
\u2713 Found workflow "${l}" (UUID: ${
|
|
54
|
-
`);break}}}(!l||l===
|
|
55
|
-
Error: Workflow with UUID "${
|
|
52
|
+
`),process.exit(1));let n=$e(),s=e.project||process.env.ZIBBY_PROJECT_ID,l;if(o){let c=j();try{let f=await fetch(`${c}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});if(f.ok){let p=(await f.json()).projects||[];for(let g of p){let y=await fetch(`${c}/projects/${g.projectId}/workflows`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});if(y.ok){let m=(await y.json()).find(k=>k.uuid===o);if(m){s=g.projectId,l=m.workflowType||m.name,console.log(`
|
|
53
|
+
\u2713 Found workflow "${l}" (UUID: ${o})
|
|
54
|
+
`);break}}}(!l||l===o)&&(console.log(`
|
|
55
|
+
Error: Workflow with UUID "${o}" not found`),console.log(` Check: zibby workflow list
|
|
56
56
|
`),process.exit(1))}}catch(f){console.log(`
|
|
57
57
|
Error looking up workflow UUID: ${f.message}
|
|
58
|
-
`),process.exit(1)}}s||(console.log(""),s=await
|
|
58
|
+
`),process.exit(1)}}s||(console.log(""),s=await be(n)),l||(console.log(""),l=await ke(s,n));let a=D(e);if(console.log(`
|
|
59
59
|
Triggering Workflow
|
|
60
|
-
`),console.log(" ".padEnd(60,"-")),console.log(` Workflow: ${l}`),console.log(` Project: ${s}`),Object.keys(a).length>0){let c=JSON.stringify(a);console.log(` Input: ${c.length>60?`${c.substring(0,57)}...`:c}`)}
|
|
60
|
+
`),console.log(" ".padEnd(60,"-")),console.log(` Workflow: ${l}`),console.log(` Project: ${s}`),Object.keys(a).length>0){let c=JSON.stringify(a);console.log(` Input: ${c.length>60?`${c.substring(0,57)}...`:c}`)}e.idempotencyKey&&console.log(` Idempotency: ${e.idempotencyKey}`),console.log(" ".padEnd(60,"-")),console.log("");let r=C("Triggering workflow execution...").start();try{let c=j(),f={input:a};e.idempotencyKey&&(f.idempotencyKey=e.idempotencyKey);let d=await fetch(`${c}/projects/${s}/workflows/${l}/trigger`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(f)});if(!d.ok){let g=await d.json().catch(()=>({}));d.status===429&&(r.fail("Quota exceeded"),console.log(`
|
|
61
61
|
Your workflow execution quota has been exceeded`),g.quotaInfo&&(console.log(` Used: ${g.quotaInfo.used}/${g.quotaInfo.limit} executions`),console.log(` Plan: ${g.quotaInfo.planId}`),g.quotaInfo.periodEnd&&console.log(` Resets: ${new Date(g.quotaInfo.periodEnd).toLocaleDateString()}`)),console.log(""),process.exit(1)),r.fail("Trigger failed"),console.log(` Error: ${g.message||d.statusText}
|
|
62
|
-
`),process.exit(1)}let p=await d.json();if(r.succeed("Workflow triggered successfully"),console.log(""),console.log(" Job Details:"),console.log(` Job ID: ${p.jobId}`),console.log(` Status: ${p.status}`),console.log(` Version: ${p.version}`),console.log(` Triggered: ${new Date(p.triggeredAt).toLocaleString()}`),console.log(""),
|
|
63
|
-
`),process.exit(1)}}export{O as coerceValue,z as parseParams,D as resolveInput,
|
|
62
|
+
`),process.exit(1)}let p=await d.json();if(r.succeed("Workflow triggered successfully"),console.log(""),console.log(" Job Details:"),console.log(` Job ID: ${p.jobId}`),console.log(` Status: ${p.status}`),console.log(` Version: ${p.version}`),console.log(` Triggered: ${new Date(p.triggeredAt).toLocaleString()}`),console.log(""),e.follow){console.log(" Streaming logs (Ctrl+C to stop)..."),console.log("");let{logsCommand:g}=await Promise.resolve().then(()=>(W(),G));return g(p.jobId,{follow:!0,project:s,apiKey:e.apiKey})}console.log(" Monitor execution:"),o?(console.log(` zibby workflow logs ${o}`),console.log(` zibby workflow logs ${o} -t`)):(console.log(` zibby workflow logs --workflow ${l} --project ${s}`),console.log(` zibby workflow logs --workflow ${l} --project ${s} -t`)),console.log("")}catch(c){r.fail("Trigger failed"),console.log(` Error: ${c.message}
|
|
63
|
+
`),process.exit(1)}}export{O as coerceValue,z as parseParams,D as resolveInput,Ye as triggerWorkflowCommand};
|
package/dist/package.json
CHANGED