@zibby/cli 0.4.13 → 0.4.14

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,6 +1,6 @@
1
1
  #!/usr/bin/env node
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
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:()=>xe});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 ke(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 ve({apiUrl:t,apiKey:e,executionId:o,nodeName:r,filename:n,absolutePath:i,sizeBytes:s,contentType:f}){let p;try{let c=await fetch(`${t}/${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 xe({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:ke(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 ve(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}/${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",".txt":"text/plain",".md":"text/markdown",".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 v=null;function ue(){return v||(v=new de({region:process.env.AWS_REGION||"ap-southeast-2"})),v}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 x={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)||x.width,height:Number(t.viewport.height)||x.height}:x,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
4
  // playwright-config-materialize.js. Derived from the bundled
5
5
  // zibby.config.json (which @zibby/workflow-deploy serialized from your
6
6
  // project's .zibby.config.mjs). Do NOT edit by hand \u2014 re-run a workflow
@@ -26,7 +26,7 @@ export default defineConfig({
26
26
 
27
27
  reporter: [['list']],
28
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(`
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 k=process.env.ZIBBY_RUN_DIAG==="1";if(k){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=k?y.listStrategies():null;for(let _ of u)try{y.registerStrategy(new _)}catch(ae){console.warn(` register ${_.name} into ${S.kind} failed: ${ae.message}`)}k&&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
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
31
  [done] ${z} completed in ${B}s`),await I("completed")):(console.error(`
32
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};
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/cli",
3
- "version": "0.4.13",
3
+ "version": "0.4.14",
4
4
  "description": "Zibby CLI - Test automation generator and runner",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1 +1 @@
1
- import{readdirSync as $,statSync as m,createReadStream as b,existsSync as T}from"node:fs";import{join as w,relative as k,sep as j,extname as v}from"node:path";var y=500*1024*1024,C=new Set([".DS_Store","Thumbs.db",".zibby-stop"]),z={".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"};function E(r){let n=v(r).toLowerCase();return z[n]||"application/octet-stream"}function S(r){let n=[],s;try{s=$(r)}catch{return n}for(let o of s){if(C.has(o)||o.startsWith("."))continue;let e=w(r,o),i;try{i=m(e)}catch{continue}i.isDirectory()?n.push(...S(e)):i.isFile()&&n.push(e)}return n}async function _({apiUrl:r,apiKey:n,executionId:s,nodeName:o,filename:e,absolutePath:i,sizeBytes:l,contentType:u}){let p;try{let a=await fetch(`${r}/executions/${s}/artifacts/upload-url`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({nodeName:o,filename:e,contentType:u,sizeBytes:l})});if(!a.ok){let t=await a.text();return console.warn(`[artifacts] upload-url failed for ${o}/${e}: ${a.status} ${t.slice(0,200)}`),null}p=await a.json()}catch(a){return console.warn(`[artifacts] upload-url request errored for ${o}/${e}: ${a.message}`),null}try{let a=b(i),t=await fetch(p.url,{method:"PUT",headers:{"Content-Type":u,"Content-Length":String(l)},body:a,duplex:"half"});if(!t.ok)return console.warn(`[artifacts] S3 PUT failed for ${o}/${e}: ${t.status}`),null}catch(a){return console.warn(`[artifacts] S3 PUT errored for ${o}/${e}: ${a.message}`),null}return{nodeName:o,filename:e,s3Key:p.s3Key,contentType:u,sizeBytes:l}}async function F({sessionPath:r,executionId:n,apiUrl:s,apiKey:o}){let e={uploaded:[],skipped:[]};if(!r||!T(r))return e;if(!s||!o||!n)return console.warn("[artifacts] uploader missing required input \u2014 skipping"),e;let i;try{i=$(r)}catch(t){return console.warn(`[artifacts] could not read session folder ${r}: ${t.message}`),e}let l=[];for(let t of i){let c=w(r,t),g;try{g=m(c)}catch{continue}if(!g.isDirectory()||t.startsWith(".")||t.startsWith("_"))continue;let x=S(c);for(let h of x){let d=k(c,h).split(j).join("/"),f;try{f=m(h).size}catch{continue}if(f>y){e.skipped.push({nodeName:t,filename:d,reason:`size ${f} > ${y}`});continue}if(f===0){e.skipped.push({nodeName:t,filename:d,reason:"empty"});continue}l.push({apiUrl:s,apiKey:o,executionId:n,nodeName:t,filename:d,absolutePath:h,sizeBytes:f,contentType:E(d)})}}if(l.length===0)return e;let u=4,p=l.slice(),a=Array.from({length:Math.min(u,p.length)},async()=>{for(;p.length;){let t=p.shift(),c=await _(t);c?e.uploaded.push(c):e.skipped.push({nodeName:t.nodeName,filename:t.filename,reason:"upload failed"})}});if(await Promise.all(a),e.uploaded.length>0)try{let t=await fetch(`${s}/executions/${n}/artifacts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({files:e.uploaded})});if(!t.ok){let c=await t.text();console.warn(`[artifacts] record failed: ${t.status} ${c.slice(0,200)}`)}}catch(t){console.warn(`[artifacts] record errored: ${t.message}`)}return e}export{F as uploadSessionArtifacts};
1
+ import{readdirSync as $,statSync as m,createReadStream as T,existsSync as k}from"node:fs";import{join as w,relative as j,sep as x,extname as C}from"node:path";var g=500*1024*1024,v=new Set([".DS_Store","Thumbs.db",".zibby-stop"]),z={".webm":"video/webm",".mp4":"video/mp4",".mov":"video/quicktime",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".txt":"text/plain",".md":"text/markdown",".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"};function E(r){let n=C(r).toLowerCase();return z[n]||"application/octet-stream"}function S(r){let n=[],s;try{s=$(r)}catch{return n}for(let o of s){if(v.has(o)||o.startsWith("."))continue;let e=w(r,o),i;try{i=m(e)}catch{continue}i.isDirectory()?n.push(...S(e)):i.isFile()&&n.push(e)}return n}async function _({apiUrl:r,apiKey:n,executionId:s,nodeName:o,filename:e,absolutePath:i,sizeBytes:l,contentType:u}){let p;try{let a=await fetch(`${r}/${s}/artifacts/upload-url`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({nodeName:o,filename:e,contentType:u,sizeBytes:l})});if(!a.ok){let t=await a.text();return console.warn(`[artifacts] upload-url failed for ${o}/${e}: ${a.status} ${t.slice(0,200)}`),null}p=await a.json()}catch(a){return console.warn(`[artifacts] upload-url request errored for ${o}/${e}: ${a.message}`),null}try{let a=T(i),t=await fetch(p.url,{method:"PUT",headers:{"Content-Type":u,"Content-Length":String(l)},body:a,duplex:"half"});if(!t.ok)return console.warn(`[artifacts] S3 PUT failed for ${o}/${e}: ${t.status}`),null}catch(a){return console.warn(`[artifacts] S3 PUT errored for ${o}/${e}: ${a.message}`),null}return{nodeName:o,filename:e,s3Key:p.s3Key,contentType:u,sizeBytes:l}}async function F({sessionPath:r,executionId:n,apiUrl:s,apiKey:o}){let e={uploaded:[],skipped:[]};if(!r||!k(r))return e;if(!s||!o||!n)return console.warn("[artifacts] uploader missing required input \u2014 skipping"),e;let i;try{i=$(r)}catch(t){return console.warn(`[artifacts] could not read session folder ${r}: ${t.message}`),e}let l=[];for(let t of i){let c=w(r,t),y;try{y=m(c)}catch{continue}if(!y.isDirectory()||t.startsWith(".")||t.startsWith("_"))continue;let b=S(c);for(let h of b){let d=j(c,h).split(x).join("/"),f;try{f=m(h).size}catch{continue}if(f>g){e.skipped.push({nodeName:t,filename:d,reason:`size ${f} > ${g}`});continue}if(f===0){e.skipped.push({nodeName:t,filename:d,reason:"empty"});continue}l.push({apiUrl:s,apiKey:o,executionId:n,nodeName:t,filename:d,absolutePath:h,sizeBytes:f,contentType:E(d)})}}if(l.length===0)return e;let u=4,p=l.slice(),a=Array.from({length:Math.min(u,p.length)},async()=>{for(;p.length;){let t=p.shift(),c=await _(t);c?e.uploaded.push(c):e.skipped.push({nodeName:t.nodeName,filename:t.filename,reason:"upload failed"})}});if(await Promise.all(a),e.uploaded.length>0)try{let t=await fetch(`${s}/${n}/artifacts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({files:e.uploaded})});if(!t.ok){let c=await t.text();console.warn(`[artifacts] record failed: ${t.status} ${c.slice(0,200)}`)}}catch(t){console.warn(`[artifacts] record errored: ${t.message}`)}return e}export{F as uploadSessionArtifacts};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/cli",
3
- "version": "0.4.13",
3
+ "version": "0.4.14",
4
4
  "description": "Zibby CLI - Test automation generator and runner",
5
5
  "type": "module",
6
6
  "bin": {