@zibby/core 0.1.40 → 0.1.42

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/index.js CHANGED
@@ -1,22 +1,20 @@
1
- var Sn=Object.defineProperty;var wn=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var M=(i,e)=>()=>(i&&(e=i(i=0)),e);var lt=(i,e)=>{for(var t in e)Sn(i,t,{get:e[t],enumerable:!0})};var B,H,q,ut,Rt,_n,bn,xn,kt,ee=M(()=>{B=".zibby/output",H="sessions",q=".session-info.json",ut=".zibby-studio-stop",Rt="result.json",_n="raw_stream_output.txt",bn="events.json",xn={BROWSER:"browser",JIRA:"jira",GITHUB:"github",SLACK:"slack",MEMORY:"memory",CHAT_MEMORY:"chat-memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",WORKFLOW_BUILDER:"workflow-builder"},kt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"]});var te,Je=M(()=>{te=class i{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(e){if(!e)return null;this.buffer+=e;let t=this.buffer.split(`
1
+ var gn=Object.defineProperty;var hn=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var B=(i,e)=>()=>(i&&(e=i(i=0)),e);var it=(i,e)=>{for(var t in e)gn(i,t,{get:e[t],enumerable:!0})};var j,X,Q,at,Ct,yn,Sn,wn,Nt,re=B(()=>{j=".zibby/output",X="sessions",Q=".session-info.json",at=".zibby-studio-stop",Ct="result.json",yn="raw_stream_output.txt",Sn="events.json",wn={BROWSER:"browser",JIRA:"jira",GITHUB:"github",SLACK:"slack",MEMORY:"memory",CHAT_MEMORY:"chat-memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",WORKFLOW_BUILDER:"workflow-builder"},Nt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"]});var se,Je=B(()=>{se=class i{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(e){if(!e)return null;this.buffer+=e;let t=this.buffer.split(`
2
2
  `);this.buffer=t.pop()||"";let r="";for(let s of t)if(s.trim())try{let n=JSON.parse(s);this._emitToolCalls(n);let o=this.extractText(n);if(o){if(this.rawText&&o.startsWith(this.rawText)){let c=o.substring(this.rawText.length);this.rawText=o,r+=c}else(!this.rawText.includes(o)||o.length<20)&&(this.rawText+=o,r+=o);this.tryExtractResult(this.rawText)}else this.isValidResult(n)&&(this.rawText+=`${s}
3
3
  `,r+=`${s}
4
- `,this.extractedResult=n)}catch{if(s.includes('"text"')||s.includes('"content"')){let o=s.match(/"text"\s*:\s*"([^"]*)/),c=s.match(/"content"\s*:\s*"([^"]*)/),l=o?o[1]:c?c[1]:null;l&&!this.rawText.includes(l)&&(r+=l,this.rawText+=l)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(o,c)=>{if(!o)return;let l=`${o}:${JSON.stringify(c??{})}`;this._lastToolEmit!==l&&(this._lastToolEmit=l,this.onToolCall(o,c??void 0))},r=o=>{if(o!=null){if(typeof o=="object"&&!Array.isArray(o))return o;if(typeof o=="string")try{return JSON.parse(o)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,r(e.input??e.arguments));return}let o=e.tool_call;if(o&&typeof o=="object"&&!Array.isArray(o)){let c=Object.keys(o);if(c.length===1){let l=c[0],a=o[l],u=a&&typeof a=="object"?a.args??a.input??a:void 0;t(l,r(u))}return}return}if(Array.isArray(e.tool_calls)){for(let o of e.tool_calls)t(o.name,r(o.input??o.arguments));return}let s=e.message??e;if(Array.isArray(s?.tool_calls)){for(let o of s.tool_calls)t(o.name,r(o.input??o.arguments));return}let n=s?.content??e.content;if(Array.isArray(n))for(let o of n)(o.type==="tool_use"||o.type==="tool_call")&&o.name&&t(o.name,r(o.input??o.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return e.type==="thinking"&&e.text||e.text?e.text:e.content&&typeof e.content=="string"?e.content:e.delta?e.delta:null}tryExtractResult(e){if(!e||typeof e!="string")return;let t=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,s;for(;(s=r.exec(e))!==null;){let p=s[1].trim();try{JSON.parse(p),t.push({text:p,source:"markdown"})}catch{}}let n=0,o=0;for(;n<e.length&&(n=e.indexOf("{",n),n!==-1);){let p=0,d=n;for(let f=n;f<e.length;f++)if(e[f]==="{")p++;else if(e[f]==="}"&&(p--,p===0)){d=f,t.push({text:e.substring(n,d+1),source:"brace"}),o++;break}n=d+1}let c=this.extractedResult,l=c?JSON.stringify(c).length:0,a=0,u=-1;for(let p=0;p<t.length;p++){let d=t[p];try{let f=d.text.replace(/,(\s*[}\]])/g,"$1"),m=JSON.parse(f);this.isValidResult(m)&&(a++,l=JSON.stringify(m).length,c=m,u=p)}catch{}}c&&(this.extractedResult=c)}isValidResult(e){if(!e||typeof e!="object"||Array.isArray(e)||e.session_id||e.timestamp_ms||e.type||e.call_id||e.tool_call||e.result&&typeof e.result=="object"&&(e.result.success&&typeof e.result.success=="object"||e.result.error&&typeof e.result.error=="object")||e.args&&typeof e.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(e),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(e,t=null){let r=new i;r.zodSchema=t,r.processChunk(e),r.flush();let s=r.getResult();return!s&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),s}}});var Wr={};lt(Wr,{WorkflowState:()=>We});function Jt(i){if(Kn.has(i))throw new Error(`Invalid state key: "${i}"`)}var Kn,We,Wt=M(()=>{Kn=new Set(["__proto__","constructor","prototype"]);We=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){Jt(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let r of t)Jt(r);this._history.push({...this._state});for(let r of t)this._state[r]=e[r]}append(e,t){Jt(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}}});var ht,Yr=M(()=>{ht=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let r=e.match(/\{[\s\S]*\}/);return r?this.validate(JSON.parse(r[0])):this.validate({result:e.trim()})}validate(e){let t=[];for(let[r,s]of Object.entries(this.schema)){if(s.required&&!(r in e)&&t.push(`Missing required field: ${r}`),r in e&&s.type){let n=typeof e[r];n!==s.type&&t.push(`Field '${r}' expected ${s.type}, got ${n}`)}if(s.validate&&r in e){let n=s.validate(e[r]);n&&t.push(`Field '${r}': ${n}`)}}if(t.length>0)throw new Error(`Output validation failed:
5
- ${t.join(`
6
- `)}`);return e}}});import Ye from"chalk";var X,gt,h,V=M(()=>{X={debug:0,info:1,warn:2,error:3,silent:4},gt=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return X.debug;if(process.env.ZIBBY_VERBOSE==="true")return X.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in X?X[e]:X.info}_shouldLog(e){return X[e]>=this._level}_formatMessage(e,t,r={}){let s=new Date().toISOString(),o=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(o+=Ye.dim(` ${JSON.stringify(r)}`)),o}_getPrefix(e){return{debug:Ye.gray("[DEBUG]"),info:Ye.cyan("[INFO]"),warn:Ye.yellow("[WARN]"),error:Ye.red("\u274C [ERROR]")}[e]||""}debug(e,t){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,t))}info(e,t){this._shouldLog("info")&&console.log(this._formatMessage("info",e,t))}warn(e,t){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,t))}error(e,t){this._shouldLog("error")&&console.error(this._formatMessage("error",e,t))}setLevel(e){e in X&&(this._level=X[e])}getLevel(){return Object.keys(X).find(e=>X[e]===this._level)}},h=new gt});import j from"chalk";function Xr(i){return i<1e3?`${i}ms`:`${(i/1e3).toFixed(1)}s`}function Qr(i,e){return(t,r,s)=>{if(typeof t!="string")return i(t,r,s);let n=process.stdout.columns||120,o="";for(let c=0;c<t.length;c++){let l=t[c];e.lineStart&&(o+=Vr,e.col=qr,e.lineStart=!1),l===`
4
+ `,this.extractedResult=n)}catch{if(s.includes('"text"')||s.includes('"content"')){let o=s.match(/"text"\s*:\s*"([^"]*)/),c=s.match(/"content"\s*:\s*"([^"]*)/),l=o?o[1]:c?c[1]:null;l&&!this.rawText.includes(l)&&(r+=l,this.rawText+=l)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(o,c)=>{if(!o)return;let l=`${o}:${JSON.stringify(c??{})}`;this._lastToolEmit!==l&&(this._lastToolEmit=l,this.onToolCall(o,c??void 0))},r=o=>{if(o!=null){if(typeof o=="object"&&!Array.isArray(o))return o;if(typeof o=="string")try{return JSON.parse(o)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,r(e.input??e.arguments));return}let o=e.tool_call;if(o&&typeof o=="object"&&!Array.isArray(o)){let c=Object.keys(o);if(c.length===1){let l=c[0],a=o[l],u=a&&typeof a=="object"?a.args??a.input??a:void 0;t(l,r(u))}return}return}if(Array.isArray(e.tool_calls)){for(let o of e.tool_calls)t(o.name,r(o.input??o.arguments));return}let s=e.message??e;if(Array.isArray(s?.tool_calls)){for(let o of s.tool_calls)t(o.name,r(o.input??o.arguments));return}let n=s?.content??e.content;if(Array.isArray(n))for(let o of n)(o.type==="tool_use"||o.type==="tool_call")&&o.name&&t(o.name,r(o.input??o.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return e.type==="thinking"&&e.text||e.text?e.text:e.content&&typeof e.content=="string"?e.content:e.delta?e.delta:null}tryExtractResult(e){if(!e||typeof e!="string")return;let t=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,s;for(;(s=r.exec(e))!==null;){let p=s[1].trim();try{JSON.parse(p),t.push({text:p,source:"markdown"})}catch{}}let n=0,o=0;for(;n<e.length&&(n=e.indexOf("{",n),n!==-1);){let p=0,d=n;for(let f=n;f<e.length;f++)if(e[f]==="{")p++;else if(e[f]==="}"&&(p--,p===0)){d=f,t.push({text:e.substring(n,d+1),source:"brace"}),o++;break}n=d+1}let c=this.extractedResult,l=c?JSON.stringify(c).length:0,a=0,u=-1;for(let p=0;p<t.length;p++){let d=t[p];try{let f=d.text.replace(/,(\s*[}\]])/g,"$1"),m=JSON.parse(f);this.isValidResult(m)&&(a++,l=JSON.stringify(m).length,c=m,u=p)}catch{}}c&&(this.extractedResult=c)}isValidResult(e){if(!e||typeof e!="object"||Array.isArray(e)||e.session_id||e.timestamp_ms||e.type||e.call_id||e.tool_call||e.result&&typeof e.result=="object"&&(e.result.success&&typeof e.result.success=="object"||e.result.error&&typeof e.result.error=="object")||e.args&&typeof e.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(e),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(e,t=null){let r=new i;r.zodSchema=t,r.processChunk(e),r.flush();let s=r.getResult();return!s&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),s}}});var Fr={};it(Fr,{WorkflowState:()=>jt});import{WorkflowState as jt}from"@zibby/workflow";var Gt=B(()=>{});import{OutputParser as jr,SchemaTypes as Ya}from"@zibby/workflow";var Gr=B(()=>{});import Ye from"chalk";var ee,dt,g,q=B(()=>{ee={debug:0,info:1,warn:2,error:3,silent:4},dt=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return ee.debug;if(process.env.ZIBBY_VERBOSE==="true")return ee.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in ee?ee[e]:ee.info}_shouldLog(e){return ee[e]>=this._level}_formatMessage(e,t,r={}){let s=new Date().toISOString(),o=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(o+=Ye.dim(` ${JSON.stringify(r)}`)),o}_getPrefix(e){return{debug:Ye.gray("[DEBUG]"),info:Ye.cyan("[INFO]"),warn:Ye.yellow("[WARN]"),error:Ye.red("\u274C [ERROR]")}[e]||""}debug(e,t){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,t))}info(e,t){this._shouldLog("info")&&console.log(this._formatMessage("info",e,t))}warn(e,t){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,t))}error(e,t){this._shouldLog("error")&&console.error(this._formatMessage("error",e,t))}setLevel(e){e in ee&&(this._level=ee[e])}getLevel(){return Object.keys(ee).find(e=>ee[e]===this._level)}},g=new dt});import G from"chalk";function Zr(i){return i<1e3?`${i}ms`:`${(i/1e3).toFixed(1)}s`}function Hr(i,e){return(t,r,s)=>{if(typeof t!="string")return i(t,r,s);let n=process.stdout.columns||120,o="";for(let c=0;c<t.length;c++){let l=t[c];e.lineStart&&(o+=Wr,e.col=Kr,e.lineStart=!1),l===`
7
5
  `?(o+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,o+=l):e.inEsc?(o+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,o+=l,e.col>=n&&(o+=`
8
- ${Vr}`,e.col=qr))}return i(o,r,s)}}var Zn,Ke,Hn,Kr,Yt,Zr,Hr,Kt,Vr,qr,Zt,D,le=M(()=>{Zn="__WORKFLOW_GRAPH_LOG__",Ke=j.gray("\u2502"),Hn=j.gray("\u250C"),Kr=j.gray("\u2514"),Yt=j.green("\u25C6"),Zr=j.hex("#c084fc")("\u25C6"),Hr=j.hex("#2dd4bf")("\u25C6"),Kt=j.red("\u25C6"),Vr=`${Ke} `,qr=2;Zt=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null;let e=String(process.env.ZIBBY_RUN_SOURCE||"").trim().toLowerCase(),t=String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1";this._emitWorkflowGraphMarkers=t||e==="studio"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=Qr(this._origStdoutWrite,e),process.stderr.write=Qr(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
6
+ ${Wr}`,e.col=Kr))}return i(o,r,s)}}var zn,We,Jn,zr,zt,Jr,Yr,Jt,Wr,Kr,Yt,F,pe=B(()=>{zn="__WORKFLOW_GRAPH_LOG__",We=G.gray("\u2502"),Jn=G.gray("\u250C"),zr=G.gray("\u2514"),zt=G.green("\u25C6"),Jr=G.hex("#c084fc")("\u25C6"),Yr=G.hex("#2dd4bf")("\u25C6"),Jt=G.red("\u25C6"),Wr=`${We} `,Kr=2;Yt=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null;let e=String(process.env.ZIBBY_RUN_SOURCE||"").trim().toLowerCase(),t=String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1";this._emitWorkflowGraphMarkers=t||e==="studio"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=Hr(this._origStdoutWrite,e),process.stderr.write=Hr(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
9
7
  `),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
10
8
  `),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
11
- `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Zn}${JSON.stringify(e)}
9
+ `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${zn}${JSON.stringify(e)}
12
10
  `;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
13
11
  `),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
14
12
  `)):process.stdout.write.bind(process.stdout)(`${e} ${t}
15
- `)}step(e){this._origStdoutWrite?this._writeDot(Yt,e):process.stdout.write.bind(process.stdout)(`${Ke} ${Yt} ${e}
16
- `)}stepTool(e){this._origStdoutWrite?this._writeDot(Zr,e):process.stdout.write.bind(process.stdout)(`${Ke} ${Zr} ${e}
17
- `)}stepMemory(e){let t=j.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(Hr,t):process.stdout.write.bind(process.stdout)(`${Ke} ${Hr} ${t}
18
- `)}stepFail(e){this._origStdoutWrite?this._writeDot(Kt,j.red(e)):process.stdout.write.bind(process.stdout)(`${Ke} ${Kt} ${j.red(e)}
19
- `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Hn} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:s}=t;if(s)for(let o of s)this._rawWrite(`${Yt} ${o}`);let n=r?j.dim(` ${Xr(r)}`):"";this._rawWrite(`${Kr} ${j.green("done")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:s}=r,n=s?j.dim(` ${Xr(s)}`):"";this._rawWrite(`${Kt} ${j.red(t)}`),this._rawWrite(`${Kr} ${j.red("failed")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(j.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){this._rawWrite(j.green.bold("\u2713 Workflow completed"))}},D=new Zt});var K,ue=M(()=>{K=class{constructor(e,t,r=0){this.name=e,this.description=t,this.priority=r}async invoke(e,t={}){throw new Error("AgentStrategy.invoke() must be implemented by subclass")}canHandle(e){throw new Error("AgentStrategy.canHandle() must be implemented by subclass")}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var G,Vn,qn,Ht,Vt,es,yt,oe=M(()=>{G={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"},Vn={ASSISTANT:"assistant",CLAUDE:"claude",CURSOR:"cursor",CODEX:"codex",GEMINI:"gemini"},qn={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error",SILENT:"silent"},Ht={auto:"claude-sonnet-4-6","sonnet-4.6":"claude-sonnet-4-6","sonnet-4-6":"claude-sonnet-4-6","opus-4.6":"claude-opus-4-6","opus-4-6":"claude-opus-4-6","sonnet-4.5":"claude-sonnet-4-5-20250929","sonnet-4-5":"claude-sonnet-4-5-20250929","opus-4.5":"claude-opus-4-20250514","opus-4-5":"claude-opus-4-20250514","claude-sonnet-4-6":"claude-sonnet-4-6","claude-opus-4-6":"claude-opus-4-6","claude-sonnet-4-5-20250929":"claude-sonnet-4-5-20250929","claude-opus-4-20250514":"claude-opus-4-20250514"},Vt={auto:"o4-mini","o4-mini":"o4-mini",o3:"o3","o3-mini":"o3-mini","codex-mini":"codex-mini-latest","gpt-4o":"gpt-4o","gpt-4o-mini":"gpt-4o-mini","gpt-5.2-codex":"gpt-5.2-codex","gpt-5.2":"gpt-5.2","gpt-5.3":"gpt-5.3","gpt-5.4":"gpt-5.4"},es={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},yt={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4}});var qt={};lt(qt,{getAllSkills:()=>St,getSkill:()=>z,hasSkill:()=>rs,listSkillIds:()=>ss,registerSkill:()=>ts});function ts(i){if(!i||typeof i.id!="string")throw new Error("Skill definition must include a string id");Ze.set(i.id,Object.freeze({...i}))}function z(i){return Ze.get(i)||null}function rs(i){return Ze.has(i)}function St(){return new Map(Ze)}function ss(){return Array.from(Ze.keys())}var Ze,se=M(()=>{Ze=new Map});import{zodToJsonSchema as Xn}from"zod-to-json-schema";var _e,Xt=M(()=>{_e=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=Xn(e,{target:"openApi3"}):r=e;let s=this._buildExample(r);return`
13
+ `)}step(e){this._origStdoutWrite?this._writeDot(zt,e):process.stdout.write.bind(process.stdout)(`${We} ${zt} ${e}
14
+ `)}stepTool(e){this._origStdoutWrite?this._writeDot(Jr,e):process.stdout.write.bind(process.stdout)(`${We} ${Jr} ${e}
15
+ `)}stepMemory(e){let t=G.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(Yr,t):process.stdout.write.bind(process.stdout)(`${We} ${Yr} ${t}
16
+ `)}stepFail(e){this._origStdoutWrite?this._writeDot(Jt,G.red(e)):process.stdout.write.bind(process.stdout)(`${We} ${Jt} ${G.red(e)}
17
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Jn} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:s}=t;if(s)for(let o of s)this._rawWrite(`${zt} ${o}`);let n=r?G.dim(` ${Zr(r)}`):"";this._rawWrite(`${zr} ${G.green("done")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:s}=r,n=s?G.dim(` ${Zr(s)}`):"";this._rawWrite(`${Jt} ${G.red(t)}`),this._rawWrite(`${zr} ${G.red("failed")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(G.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){this._rawWrite(G.green.bold("\u2713 Workflow completed"))}},F=new Yt});var Z,fe=B(()=>{Z=class{constructor(e,t,r=0){this.name=e,this.description=t,this.priority=r}async invoke(e,t={}){throw new Error("AgentStrategy.invoke() must be implemented by subclass")}canHandle(e){throw new Error("AgentStrategy.canHandle() must be implemented by subclass")}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var J,Yn,Wn,Wt,Kt,Vr,mt,ae=B(()=>{J={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"},Yn={ASSISTANT:"assistant",CLAUDE:"claude",CURSOR:"cursor",CODEX:"codex",GEMINI:"gemini"},Wn={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error",SILENT:"silent"},Wt={auto:"claude-sonnet-4-6","sonnet-4.6":"claude-sonnet-4-6","sonnet-4-6":"claude-sonnet-4-6","opus-4.6":"claude-opus-4-6","opus-4-6":"claude-opus-4-6","sonnet-4.5":"claude-sonnet-4-5-20250929","sonnet-4-5":"claude-sonnet-4-5-20250929","opus-4.5":"claude-opus-4-20250514","opus-4-5":"claude-opus-4-20250514","claude-sonnet-4-6":"claude-sonnet-4-6","claude-opus-4-6":"claude-opus-4-6","claude-sonnet-4-5-20250929":"claude-sonnet-4-5-20250929","claude-opus-4-20250514":"claude-opus-4-20250514"},Kt={auto:"o4-mini","o4-mini":"o4-mini",o3:"o3","o3-mini":"o3-mini","codex-mini":"codex-mini-latest","gpt-4o":"gpt-4o","gpt-4o-mini":"gpt-4o-mini","gpt-5.2-codex":"gpt-5.2-codex","gpt-5.2":"gpt-5.2","gpt-5.3":"gpt-5.3","gpt-5.4":"gpt-5.4"},Vr={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},mt={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4}});var Zt={};it(Zt,{getAllSkills:()=>gt,getSkill:()=>Y,hasSkill:()=>qr,listSkillIds:()=>Qr,registerSkill:()=>Xr});import{registerSkill as Xr,getSkill as Y,hasSkill as qr,getAllSkills as gt,listSkillIds as Qr}from"@zibby/workflow";var ne=B(()=>{});import{zodToJsonSchema as Kn}from"zod-to-json-schema";var ht,es=B(()=>{ht=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=Kn(e,{target:"openApi3"}):r=e;let s=this._buildExample(r);return`
20
18
  \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
21
19
  \u{1F6A8} MANDATORY: WRITE RESULT TO FILE \u{1F6A8}
22
20
  \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
@@ -36,18 +34,28 @@ JSON types (strict \u2014 validators reject wrong types):
36
34
  - Use true/false without quotes for booleans.
37
35
  - Use unquoted null where a field may be null.
38
36
 
39
- Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(e){if(!e)return{};let t=e.type;if(t==="object"&&e.properties){let r={};for(let[s,n]of Object.entries(e.properties))r[s]=this._buildExample(n);return r}if(t==="array"&&e.items)return[this._buildExample(e.items)];if(e.enum&&Array.isArray(e.enum)&&e.enum.length>0)return`<${e.enum.join("|")}>`;if(t==="string")return"<string>";if(t==="number"||t==="integer")return 0;if(t==="boolean")return!1;if(e.description)return`<${e.description}>`;if(e.nullable||e.oneOf||e.anyOf){let r=e.oneOf?.find(s=>s.type!=="null")||e.anyOf?.find(s=>s.type!=="null");return r?this._buildExample(r):null}return"<value>"}}});import Qn from"axios";import{homedir as eo}from"node:os";import{join as to}from"node:path";import{existsSync as ro,readFileSync as so}from"node:fs";import{toJSONSchema as no}from"zod";function oo(){if(process.env.OPENAI_PROXY_TOKEN)return h.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return h.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let i=to(eo(),".zibby","config.json");if(ro(i)){let e=JSON.parse(so(i,"utf-8"));if(e.sessionToken)return h.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(i){h.debug(`[Auth] Could not read zibby login session: ${i.message}`)}return null}function io(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function be(i){if(!(typeof i!="object"||i===null)){if(Object.keys(i).length===0){i.type="object",i.additionalProperties=!0;return}if(i.type||(i.properties?i.type="object":i.items&&(i.type="array")),i.type==="object")if(i.properties){for(let[e,t]of Object.entries(i.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(i.properties[e]={type:["object","null"]});i.additionalProperties=!1,i.required=Object.keys(i.properties),Object.values(i.properties).forEach(be)}else"additionalProperties"in i||(i.additionalProperties=!0);i.type==="array"&&i.items&&be(i.items),i.anyOf&&i.anyOf.forEach(be),i.oneOf&&i.oneOf.forEach(be),i.allOf&&i.allOf.forEach(be)}}async function ns(i,e){h.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=oo();if(!t)throw new Error("Authentication required for structured output processing.\n Local development: Run `zibby login`\n CI/CD: Set ZIBBY_USER_TOKEN environment variable (Personal Access Token from UI settings)");let r=io();h.info(`\u{1F517} Using OpenAI proxy: ${r}`);let s=no(e),n=s;if(s.$ref&&s.definitions){let u=s.$ref.split("/").pop();n=s.definitions[u]||s,h.debug(`Extracted schema from $ref: ${u}`)}delete n.$schema,be(n);let o=4e5,c=i;i.length>o&&(h.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${i.length} chars) exceeds limit, keeping last ${o} chars`),c=`... [truncated early content] ...
37
+ Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(e){if(!e)return{};let t=e.type;if(t==="object"&&e.properties){let r={};for(let[s,n]of Object.entries(e.properties))r[s]=this._buildExample(n);return r}if(t==="array"&&e.items)return[this._buildExample(e.items)];if(e.enum&&Array.isArray(e.enum)&&e.enum.length>0)return`<${e.enum.join("|")}>`;if(t==="string")return"<string>";if(t==="number"||t==="integer")return 0;if(t==="boolean")return!1;if(e.description)return`<${e.description}>`;if(e.nullable||e.oneOf||e.anyOf){let r=e.oneOf?.find(s=>s.type!=="null")||e.anyOf?.find(s=>s.type!=="null");return r?this._buildExample(r):null}return"<value>"}}});var be,Ht=B(()=>{es();be=class i{constructor(e=""){this.userPrompt=e,this.systemInstructions=[],this.metadata={}}setUserPrompt(e){return this.userPrompt=e,this}appendUserPrompt(e){return this.userPrompt?this.userPrompt+=`
38
+
39
+ ${e}`:this.userPrompt=e,this}addSkillHints(e){return e&&this.systemInstructions.push({type:"skill_hints",content:e,position:"prepend"}),this}addStructuredOutput(e,t){if(e&&t){let r=ht.generateFileOutputInstructions(e,t);this.systemInstructions.push({type:"structured_output",content:r,position:"append"}),this.metadata.structuredOutputPath=t}return this}addExtraInstructions(e){if(e?.trim()){let t=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
40
+ \u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
41
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
42
+
43
+ ${e.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:t,position:"append"})}return this}addSkillFragments(e){return e&&e.length>0&&this.systemInstructions.push({type:"skill_fragments",content:e.join(`
44
+
45
+ `),position:"append"}),this}addSystemInstruction(e,t="custom",r="append"){return e&&this.systemInstructions.push({type:t,content:e,position:r}),this}getUserPrompt(){return this.userPrompt}getSystemInstructions(){return this.systemInstructions}getMetadata(){return this.metadata}build(){let e=this.systemInstructions.filter(s=>s.position==="prepend").map(s=>s.content),t=this.systemInstructions.filter(s=>s.position==="append").map(s=>s.content);return[...e,this.userPrompt,...t].filter(Boolean).join(`
46
+
47
+ `)}getStats(){let e=this.userPrompt.length,t=this.build().length;return{userPromptLength:e,fullPromptLength:t,systemInstructionsLength:t-e,instructionCount:this.systemInstructions.length,instructionTypes:this.systemInstructions.map(r=>r.type)}}clone(){let e=new i(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}}});import Zn from"axios";import{homedir as Hn}from"node:os";import{join as Vn}from"node:path";import{existsSync as Xn,readFileSync as qn}from"node:fs";import{toJSONSchema as Qn}from"zod";function eo(){if(process.env.OPENAI_PROXY_TOKEN)return g.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return g.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let i=Vn(Hn(),".zibby","config.json");if(Xn(i)){let e=JSON.parse(qn(i,"utf-8"));if(e.sessionToken)return g.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(i){g.debug(`[Auth] Could not read zibby login session: ${i.message}`)}return null}function to(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function xe(i){if(!(typeof i!="object"||i===null)){if(Object.keys(i).length===0){i.type="object",i.additionalProperties=!0;return}if(i.type||(i.properties?i.type="object":i.items&&(i.type="array")),i.type==="object")if(i.properties){for(let[e,t]of Object.entries(i.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(i.properties[e]={type:["object","null"]});i.additionalProperties=!1,i.required=Object.keys(i.properties),Object.values(i.properties).forEach(xe)}else"additionalProperties"in i||(i.additionalProperties=!0);i.type==="array"&&i.items&&xe(i.items),i.anyOf&&i.anyOf.forEach(xe),i.oneOf&&i.oneOf.forEach(xe),i.allOf&&i.allOf.forEach(xe)}}async function ts(i,e){g.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=eo();if(!t)throw new Error("Authentication required for structured output processing.\n Local development: Run `zibby login`\n CI/CD: Set ZIBBY_USER_TOKEN environment variable (Personal Access Token from UI settings)");let r=to();g.info(`\u{1F517} Using OpenAI proxy: ${r}`);let s=Qn(e),n=s;if(s.$ref&&s.definitions){let u=s.$ref.split("/").pop();n=s.definitions[u]||s,g.debug(`Extracted schema from $ref: ${u}`)}delete n.$schema,xe(n);let o=4e5,c=i;i.length>o&&(g.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${i.length} chars) exceeds limit, keeping last ${o} chars`),c=`... [truncated early content] ...
40
48
  ${i.slice(-o)}`);let l=`Extract and format the following information into structured JSON matching the schema.
41
49
 
42
50
  RAW CONTENT:
43
51
  ${c}
44
52
 
45
- Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,a={model:G.OPENAI_POSTPROCESSING,messages:[{role:"user",content:l}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:n,strict:!0}}};h.info(`\u{1F4E4} Sending to OpenAI proxy: model=${G.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(n.properties||{}).join(", ")}`),h.debug(` Schema size: ${JSON.stringify(n).length} chars`),h.debug(` Prompt size: ${l.length} chars`);try{let u={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(u["x-proxy-token"]=t,u["x-execution-id"]=process.env.EXECUTION_ID||""):(u.Authorization=`Bearer ${t}`,u["x-api-key"]=process.env.ZIBBY_API_KEY||"",u["x-execution-id"]=process.env.EXECUTION_ID||"");let d=(await Qn.post(r,a,{headers:u,timeout:yt.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!d)throw new Error("OpenAI proxy returned empty response");let f=JSON.parse(d);return h.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:f,raw:i}}catch(u){if(u.response){let p=u.response.status,d=u.response.data;throw h.error(`\u274C OpenAI proxy request failed: ${p}`),h.error(` Status: ${p}`),h.error(` Response: ${JSON.stringify(d,null,2)}`),p===401||p===403?new Error(`Authentication failed for OpenAI proxy.
53
+ Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,a={model:J.OPENAI_POSTPROCESSING,messages:[{role:"user",content:l}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:n,strict:!0}}};g.info(`\u{1F4E4} Sending to OpenAI proxy: model=${J.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(n.properties||{}).join(", ")}`),g.debug(` Schema size: ${JSON.stringify(n).length} chars`),g.debug(` Prompt size: ${l.length} chars`);try{let u={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(u["x-proxy-token"]=t,u["x-execution-id"]=process.env.EXECUTION_ID||""):(u.Authorization=`Bearer ${t}`,u["x-api-key"]=process.env.ZIBBY_API_KEY||"",u["x-execution-id"]=process.env.EXECUTION_ID||"");let d=(await Zn.post(r,a,{headers:u,timeout:mt.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!d)throw new Error("OpenAI proxy returned empty response");let f=JSON.parse(d);return g.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:f,raw:i}}catch(u){if(u.response){let p=u.response.status,d=u.response.data;throw g.error(`\u274C OpenAI proxy request failed: ${p}`),g.error(` Status: ${p}`),g.error(` Response: ${JSON.stringify(d,null,2)}`),p===401||p===403?new Error(`Authentication failed for OpenAI proxy.
46
54
  Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
47
- Response: ${JSON.stringify(d)}`,{cause:u}):new Error(`Failed to format Cursor output: ${d?.error?.message||"Unknown error"}`,{cause:u})}throw h.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}var os=M(()=>{V();oe()});import{copyFileSync as ao,existsSync as Qt,lstatSync as co,mkdirSync as is,rmSync as lo,symlinkSync as uo,unlinkSync as po}from"node:fs";import{join as ne}from"node:path";import{homedir as fo}from"node:os";import{randomBytes as mo}from"node:crypto";function as(i){return!(!i||typeof i!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function cs(i){let e=ne(i||process.cwd(),".zibby","tmp");is(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${mo(4).toString("hex")}`,r=ne(e,`cursor-agent-home-${t}`),s=ne(r,".cursor");is(s,{recursive:!0});let n=fo(),o=ne(n,".cursor");if(Qt(o))for(let c of ho){let l=ne(o,c);if(Qt(l))try{ao(l,ne(s,c))}catch{}}if(process.platform==="darwin"){let c=ne(n,"Library");if(Qt(c))try{uo(c,ne(r,"Library"))}catch{}}return r}function ls(i){if(!(!i||typeof i!="string"))try{let e=ne(i,"Library");try{co(e).isSymbolicLink()&&po(e)}catch{}lo(i,{recursive:!0,force:!0})}catch{}}var ho,us=M(()=>{ho=["cli-config.json","config.json","auth.json","argv.json"]});import{spawn as go,execSync as pe}from"node:child_process";import{writeFileSync as ps,readFileSync as fs,mkdirSync as ds,existsSync as He,accessSync as ms,constants as hs,unlinkSync as yo}from"node:fs";import{join as Q,resolve as So}from"node:path";import{homedir as Ve}from"node:os";var xe,gs=M(()=>{ue();V();oe();ee();se();Je();Xt();os();le();us();xe=class extends K{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[Q(Ve(),".local","bin","cursor-agent"),Q(Ve(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"];for(let r of t)try{if(r.startsWith("/")){ms(r,hs.X_OK);let s=pe(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return h.debug(`[Cursor] Found agent at: ${r} (version: ${s.trim().slice(0,50)})`),!0}else{let s=pe(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!s)continue;let n=pe(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(n&&n.length>0)return h.debug(`[Cursor] Found '${r}' in PATH at ${s} (version: ${n.trim().slice(0,50)})`),!0}}catch{continue}return h.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:r=process.cwd(),print:s=!1,schema:n=null,skills:o=null,sessionPath:c=null,nodeName:l=null,timeout:a=yt.CURSOR_AGENT_DEFAULT,config:u={}}=t,p=u?.agent?.strictMode||!1,d=t.model??u?.agent?.cursor?.model??G.CURSOR;h.debug(`[Cursor] Invoking (model: ${d}, timeout: ${a/1e3}s, skills: ${JSON.stringify(o)})`);let m=(this._setupMcpConfig(c,r,u,o,l)||{}).isolatedMcpHome??null,S=[Q(Ve(),".local","bin","cursor-agent"),Q(Ve(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],g=null;for(let N of S)try{if(N.startsWith("/"))ms(N,hs.X_OK),pe(`"${N}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!pe(`which ${N}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");pe(`${N} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}g=N,h.debug(`[Agent] Using binary: ${N}`);break}catch(b){h.debug(`[Agent] Binary '${N}' check failed: ${b.message}`);continue}if(!g)throw new Error(`Cursor Agent CLI not found or not working.
55
+ Response: ${JSON.stringify(d)}`,{cause:u}):new Error(`Failed to format Cursor output: ${d?.error?.message||"Unknown error"}`,{cause:u})}throw g.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}var rs=B(()=>{q();ae()});import{copyFileSync as ro,existsSync as Vt,lstatSync as so,mkdirSync as ss,rmSync as no,symlinkSync as oo,unlinkSync as io}from"node:fs";import{join as oe}from"node:path";import{homedir as ao}from"node:os";import{randomBytes as co}from"node:crypto";function ns(i){return!(!i||typeof i!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function os(i){let e=oe(i||process.cwd(),".zibby","tmp");ss(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${co(4).toString("hex")}`,r=oe(e,`cursor-agent-home-${t}`),s=oe(r,".cursor");ss(s,{recursive:!0});let n=ao(),o=oe(n,".cursor");if(Vt(o))for(let c of lo){let l=oe(o,c);if(Vt(l))try{ro(l,oe(s,c))}catch{}}if(process.platform==="darwin"){let c=oe(n,"Library");if(Vt(c))try{oo(c,oe(r,"Library"))}catch{}}return r}function is(i){if(!(!i||typeof i!="string"))try{let e=oe(i,"Library");try{so(e).isSymbolicLink()&&io(e)}catch{}no(i,{recursive:!0,force:!0})}catch{}}var lo,as=B(()=>{lo=["cli-config.json","config.json","auth.json","argv.json"]});import{spawn as uo,execSync as de}from"node:child_process";import{writeFileSync as cs,readFileSync as ls,mkdirSync as us,existsSync as Ke,accessSync as ps,constants as fs,unlinkSync as po}from"node:fs";import{join as te,resolve as fo}from"node:path";import{homedir as Ze}from"node:os";var Ee,ds=B(()=>{fe();q();ae();re();ne();Je();Ht();rs();pe();as();Ee=class extends Z{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[te(Ze(),".local","bin","cursor-agent"),te(Ze(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"];for(let r of t)try{if(r.startsWith("/")){ps(r,fs.X_OK);let s=de(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return g.debug(`[Cursor] Found agent at: ${r} (version: ${s.trim().slice(0,50)})`),!0}else{let s=de(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!s)continue;let n=de(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(n&&n.length>0)return g.debug(`[Cursor] Found '${r}' in PATH at ${s} (version: ${n.trim().slice(0,50)})`),!0}}catch{continue}return g.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:r=process.cwd(),print:s=!1,schema:n=null,skills:o=null,sessionPath:c=null,nodeName:l=null,timeout:a=mt.CURSOR_AGENT_DEFAULT,config:u={}}=t,p=u?.agent?.strictMode||!1,d=t.model??u?.agent?.cursor?.model??J.CURSOR;g.debug(`[Cursor] Invoking (model: ${d}, timeout: ${a/1e3}s, skills: ${JSON.stringify(o)})`);let m=(this._setupMcpConfig(c,r,u,o,l)||{}).isolatedMcpHome??null,S=[te(Ze(),".local","bin","cursor-agent"),te(Ze(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],h=null;for(let w of S)try{if(w.startsWith("/"))ps(w,fs.X_OK),de(`"${w}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!de(`which ${w}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");de(`${w} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}h=w,g.debug(`[Agent] Using binary: ${w}`);break}catch($){g.debug(`[Agent] Binary '${w}' check failed: ${$.message}`);continue}if(!h)throw new Error(`Cursor Agent CLI not found or not working.
48
56
 
49
57
  Checked paths:
50
- ${S.map(N=>` - ${N}`).join(`
58
+ ${S.map(w=>` - ${w}`).join(`
51
59
  `)}
52
60
 
53
61
  Install cursor-agent:
@@ -56,82 +64,75 @@ Install cursor-agent:
56
64
  Then add to PATH:
57
65
  echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
58
66
 
59
- Test with: agent --version`);let w=null;if(n){let N=`zibby-result-${Date.now()}.json`;w=Q(r,".zibby","tmp",N);let b=Q(r,".zibby","tmp");He(b)||ds(b,{recursive:!0});let A=_e.generateFileOutputInstructions(n,w);e=`${e}
60
-
61
- ${A}`}let y=process.env.CURSOR_API_KEY,E=y?` | key: ***${y.slice(-4)}`:" | key: not set";console.log(`
67
+ Test with: agent --version`);let _=new be(e),y=null;if(n){let w=`zibby-result-${Date.now()}.json`;y=te(r,".zibby","tmp",w);let $=te(r,".zibby","tmp");Ke($)||us($,{recursive:!0}),_.addStructuredOutput(n,y)}let x=process.env.CURSOR_API_KEY,E=x?` | key: ***${x.slice(-4)}`:" | key: not set";console.log(`
62
68
  \u25C6 Model: ${d||"auto"}${E}
63
- `);let x=(await import("chalk")).default;console.log(`
64
- ${x.bold("Prompt sent to LLM:")}`),console.log(x.dim("\u2500".repeat(60))),console.log(x.dim(e)),console.log(x.dim("\u2500".repeat(60)));let v=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",d||"auto"];if(process.env.CURSOR_API_KEY&&v.push("--api-key",process.env.CURSOR_API_KEY),v.push(e),h.debug(`[Agent] Prompt: ${e.length} chars, model: ${d||"auto"}`),h.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${d||"auto"} (from .zibby.config.js agent.cursor.model)
65
- `)}catch{}let $,T=null;try{let N=c||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);$=await this._spawnWithStreaming(g,v,r,a,null,N,m)}catch(N){T=N}let I=$?.stdout||"";if(n){let N=typeof n.parse=="function",b=null,A=!!(w&&He(w));if(w&&h.info(`[Agent] Result file: ${A?"present":"missing"} at ${w}`),A)try{let _=fs(w,"utf-8").trim();b=JSON.parse(_),h.info(`[Agent] Parsed JSON from result file OK (${_.length} chars) \u2192 object ready for validation`),T&&h.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(_){h.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${_.message}`)}else if(T)h.warn(`[Agent] Result file missing at ${w} (agent process error \u2014 may still recover if strictMode repairs)`);else throw h.error(`\u274C [Agent] Result file was never created at ${w}`),new Error(`Agent did not write required result file at ${w}`);if(b&&N)try{let _=n.parse(b);return h.info("\u2705 [Agent] Zod validation passed for structured result file"),p&&h.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:I,structured:_}}catch(_){let C=_.issues?_.issues.map(R=>` - ${R.path.join(".")}: ${R.message}`).join(`
66
- `):_.message?.slice(0,400);if(h.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
67
- ${C}`),h.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
68
- ${JSON.stringify(b,null,2).slice(0,500)}`),!p)throw new Error(`Agent output failed schema validation:
69
- ${C}
69
+ `);let T=(await import("chalk")).default,v=_.getUserPrompt();console.log(`
70
+ ${T.bold("Prompt sent to LLM:")}`),console.log(T.dim("\u2500".repeat(60))),console.log(T.dim(v)),console.log(T.dim("\u2500".repeat(60)));let I=_.build(),A=_.getStats(),P=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",d||"auto"];if(process.env.CURSOR_API_KEY&&P.push("--api-key",process.env.CURSOR_API_KEY),P.push(I),g.debug(`[Agent] User prompt: ${A.userPromptLength} chars, System instructions: ${A.systemInstructionsLength} chars (${A.instructionCount} blocks), Full: ${A.fullPromptLength} chars, model: ${d||"auto"}`),g.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${d||"auto"} (from .zibby.config.js agent.cursor.model)
71
+ `)}catch{}let k,b=null;try{let w=c||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);k=await this._spawnWithStreaming(h,P,r,a,null,w,m)}catch(w){b=w}let C=k?.stdout||"";if(n){let w=typeof n.parse=="function",$=null,N=!!(y&&Ke(y));if(y&&g.info(`[Agent] Result file: ${N?"present":"missing"} at ${y}`),N)try{let R=ls(y,"utf-8").trim();$=JSON.parse(R),g.info(`[Agent] Parsed JSON from result file OK (${R.length} chars) \u2192 object ready for validation`),b&&g.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(R){g.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${R.message}`)}else if(b)g.warn(`[Agent] Result file missing at ${y} (agent process error \u2014 may still recover if strictMode repairs)`);else throw g.error(`\u274C [Agent] Result file was never created at ${y}`),new Error(`Agent did not write required result file at ${y}`);if($&&w)try{let R=n.parse($);return g.info("\u2705 [Agent] Zod validation passed for structured result file"),p&&g.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:C,structured:R}}catch(R){let M=R.issues?R.issues.map(L=>` - ${L.path.join(".")}: ${L.message}`).join(`
72
+ `):R.message?.slice(0,400);if(g.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
73
+ ${M}`),g.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
74
+ ${JSON.stringify($,null,2).slice(0,500)}`),!p)throw new Error(`Agent output failed schema validation:
75
+ ${M}
70
76
 
71
77
  The agent wrote invalid data that doesn't match the required outputSchema.
72
- Enable strictMode in .zibby.config.js for automatic repair.`,{cause:_})}else{if(b)return h.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),p&&h.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:I,structured:b};A&&h.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(p&&!T){let _=$.parsedText,C=b?JSON.stringify(b):_;h.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${C.length} chars in)`);try{let R=await ns(C,n);if(N){let L=n.parse(R.structured);return h.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:I,structured:L}}return{raw:I,...R}}catch(R){if(h.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${R.message}`),b)return h.warn("[Agent] Using agent's original result file as fallback"),{raw:I,structured:b}}}if(T)throw T;let O=A?b==null?"file existed but JSON.parse failed \u2014 see WARN log above":N?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw h.error(`\u274C [Agent] No validated structured output: ${O}`),h.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error(`Agent did not produce a valid result file at ${w}. Enable strictMode for proxy fallback.`)}if(T)throw T;return this._extractFinalResult(I)||$?.parsedText||I}_extractFinalResult(e){if(!e)return null;let t=e.split(`
73
- `),r=null;for(let s of t){let n=s.trim();if(n)try{let o=JSON.parse(n);if(o.type==="assistant"&&o.message?.content){let c=o.message.content;if(Array.isArray(c)){let l=c.filter(a=>a.type==="text"&&a.text).map(a=>a.text).join("");l&&(r=l)}else typeof c=="string"&&c&&(r=c)}}catch{}}return r?.trim()||null}_setupMcpConfig(e,t,r,s=null,n=null){let o=r?.headless,c=Q(Ve(),".cursor"),l=Q(c,"mcp.json"),a={};if(He(l))try{a=JSON.parse(fs(l,"utf-8"))}catch{}let u=a.mcpServers||{},p=r?.paths?.output||B,d=Q(t||process.cwd(),p,q),f=Array.isArray(s)?s.map(g=>z(g)).filter(Boolean):[...St()].map(([,g])=>g),m=new Set;for(let g of f)typeof g.resolve=="function"&&(m.has(g.serverName)||(m.add(g.serverName),this._ensureSkillConfigured(u,g,e,d,n,o)));if(e){let g=z("browser");g&&typeof g.resolve=="function"&&!m.has(g.serverName)&&this._ensureSkillConfigured(u,g,e,d,"execute_live",o)}if(Object.keys(u).length===0)return h.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let S=`${JSON.stringify({mcpServers:u},null,2)}
74
- `;if(as(e)){let g=cs(t||process.cwd()),w=Q(g,".cursor","mcp.json");return ps(w,S,"utf8"),h.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${g} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:g}}return He(c)||ds(c,{recursive:!0}),ps(l,S,"utf8"),h.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,s,n=null,o){let c=t.cursorKey||t.serverName,l=e[c]?c:e[t.serverName]?t.serverName:null;if(l&&r){let u=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:n,headless:o}):null;u?.args?e[l].args=u.args:e[l].args=(e[l].args||[]).map(f=>f.startsWith("--output-dir=")?`--output-dir=${r}`:f);let p=u?.env||{},d=t.sessionEnvKey?{[t.sessionEnvKey]:s}:{};e[l].env={...e[l].env||{},...p,...d},h.debug(`[MCP] Updated ${l} session \u2192 ${r}`);return}if(l)return;let a=t.resolve({sessionPath:r,nodeName:n,headless:o});a&&(e[c]={...a,...t.sessionEnvKey&&{env:{...a.env||{},[t.sessionEnvKey]:s}}},h.debug(`[MCP] Configured ${c}`))}_spawnWithStreaming(e,t,r,s,n=null,o=null,c=null){return new Promise((l,a)=>{let u=Date.now(),p="",d="",f=Date.now(),m=0,S=!1,g=null,w=!1,y=!1,E=null;if(o)try{E=Q(So(String(o)),ut)}catch{E=null}let x=!1,v=()=>{x||(x=!0,ls(c))},$={...process.env};c&&($.HOME=c,process.platform==="win32"&&($.USERPROFILE=c),h.debug(`[Agent] cursor-agent HOME=${c} (isolated MCP config)`));let T=go(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:$});h.debug(`[Agent] PID: ${T.pid}`),T.stdin.on("error",_=>{_.code!=="EPIPE"&&h.warn(`[Agent] stdin error: ${_.message}`)}),T.stdout.on("error",_=>{_.code!=="EPIPE"&&h.warn(`[Agent] stdout error: ${_.message}`)}),T.stderr.on("error",_=>{_.code!=="EPIPE"&&h.warn(`[Agent] stderr error: ${_.message}`)}),n?(T.stdin.write(n,_=>{_&&_.code!=="EPIPE"&&h.warn(`[Agent] Failed to write to stdin: ${_.message}`),T.stdin.end()}),h.debug(`[Agent] Prompt also piped to stdin (${n.length} chars)`)):T.stdin.end();let I=null;E&&(I=setInterval(()=>{if(!(S||y))try{if(He(E)){S=!0,g="studio-stop";try{yo(E)}catch{}h.warn("\u{1F6D1} Studio stop requested \u2014 terminating Cursor agent (and MCP browser session)"),T.kill("SIGTERM"),setTimeout(()=>{T.killed||T.kill("SIGKILL")},2e3)}}catch{}},600));let P=new Set,N=new Date(u).toISOString().replace(/\.\d+Z$/,""),b=setInterval(()=>{let _=Math.round((Date.now()-u)/1e3),C=Math.round((Date.now()-f)/1e3),R=[];try{let U=Math.ceil(_/60)+1,k=pe(`find "${r}" -type f -mmin -${U} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(k)for(let W of k.split(`
75
- `)){let F=W.replace(`${r}/`,"");P.has(F)||(P.add(F),R.push(F))}}catch{}let L="";R.length>0&&(L=` | \u{1F4C1} new: ${R.map(k=>k.split("/").pop()).join(", ")}`),P.size>0&&(L+=` | \u{1F4E6} total: ${P.size} files`),h.debug(`\u{1F493} [Agent] Running for ${_}s | ${m} lines output${L}`),m===0&&_>=30&&P.size===0&&(_<35&&h.warn(`\u26A0\uFE0F [Agent] No output after ${_}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),_>=60&&(S=!0,g=g||"stall",h.error(`\u274C [Agent] No response after ${_}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),T.kill("SIGTERM"),setTimeout(()=>{T.killed||T.kill("SIGKILL")},3e3)))},3e4),A=setTimeout(()=>{S=!0,g=g||"timeout";let _=Math.round((Date.now()-u)/1e3);h.error(`\u23F1\uFE0F [Agent] Timeout after ${_}s \u2014 killing process (PID: ${T.pid})`),p.trim()&&h.warn(`\u{1F4E4} [Agent] Partial output (${p.length} chars) before timeout:
76
- ${p.slice(-2e3)}`),T.kill("SIGTERM"),setTimeout(()=>{T.killed||T.kill("SIGKILL")},5e3)},s),O=new te;O.onToolCall=(_,C)=>{let R=_,L=C;if(_==="mcpToolCall"&&C?.name)R=C.name.replace(/^mcp_+[^_]+_+/,""),R.includes("-")&&R.split("-")[0]===R.split("-")[1]&&(R=R.split("-")[0]),L=C.args??C.input??C;else{if(_==="readToolCall"||_==="editToolCall"||_==="writeToolCall")return;(_.startsWith("mcp__")||_.includes("ToolCall"))&&(R=_.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(R.includes("memory")?D.stepMemory(`Tool: ${R}`):D.stepTool(`Tool: ${R}`),L!=null&&typeof L=="object"&&Object.keys(L).length>0&&!y){let k=JSON.stringify(L),W=k.length>100?`${k.substring(0,100)}...`:k;console.log(` Input: ${W}`)}},T.stdout.on("data",_=>{let C=_.toString();p+=C,f=Date.now(),w||(w=!0);let R=O.processChunk(C);R&&!y&&process.stdout.write(R);let L=C.split(`
77
- `).filter(U=>U.trim());m+=L.length}),T.stderr.on("data",_=>{let C=_.toString();d+=C,f=Date.now(),w||(w=!0);let R=C.split(`
78
- `).filter(L=>L.trim());for(let L of R)h.warn(`\u26A0\uFE0F [Agent stderr] ${L}`)}),T.on("close",(_,C)=>{y=!0,v(),clearTimeout(A),clearInterval(b),I&&clearInterval(I),O.flush();let R=Math.round((Date.now()-u)/1e3);if(h.debug(`[Agent] Exited: code=${_}, signal=${C}, elapsed=${R}s, output=${p.length} chars`),S){if(g==="studio-stop"){a(new Error("Stopped from Zibby Studio"));return}a(new Error(`Cursor Agent timed out after ${R}s (limit: ${s/1e3}s). ${m} lines produced. Last output ${Math.round((Date.now()-f)/1e3)}s ago. ${p.trim()?`
78
+ Enable strictMode in .zibby.config.js for automatic repair.`,{cause:R})}else{if($)return g.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),p&&g.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:C,structured:$};N&&g.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(p&&!b){let R=k.parsedText,M=$?JSON.stringify($):R;g.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${M.length} chars in)`);try{let L=await ts(M,n);if(w){let D=n.parse(L.structured);return g.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:C,structured:D}}return{raw:C,...L}}catch(L){if(g.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${L.message}`),$)return g.warn("[Agent] Using agent's original result file as fallback"),{raw:C,structured:$}}}if(b)throw b;let U=N?$==null?"file existed but JSON.parse failed \u2014 see WARN log above":w?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw g.error(`\u274C [Agent] No validated structured output: ${U}`),g.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error(`Agent did not produce a valid result file at ${y}. Enable strictMode for proxy fallback.`)}if(b)throw b;return this._extractFinalResult(C)||k?.parsedText||C}_extractFinalResult(e){if(!e)return null;let t=e.split(`
79
+ `),r=null;for(let s of t){let n=s.trim();if(n)try{let o=JSON.parse(n);if(o.type==="assistant"&&o.message?.content){let c=o.message.content;if(Array.isArray(c)){let l=c.filter(a=>a.type==="text"&&a.text).map(a=>a.text).join("");l&&(r=l)}else typeof c=="string"&&c&&(r=c)}}catch{}}return r?.trim()||null}_setupMcpConfig(e,t,r,s=null,n=null){let o=r?.headless,c=te(Ze(),".cursor"),l=te(c,"mcp.json"),a={};if(Ke(l))try{a=JSON.parse(ls(l,"utf-8"))}catch{}let u=a.mcpServers||{},p=r?.paths?.output||j,d=te(t||process.cwd(),p,Q),f=Array.isArray(s)?s.map(h=>Y(h)).filter(Boolean):[...gt()].map(([,h])=>h),m=new Set;for(let h of f)typeof h.resolve=="function"&&(m.has(h.serverName)||(m.add(h.serverName),this._ensureSkillConfigured(u,h,e,d,n,o)));if(e){let h=Y("browser");h&&typeof h.resolve=="function"&&!m.has(h.serverName)&&this._ensureSkillConfigured(u,h,e,d,"execute_live",o)}if(Object.keys(u).length===0)return g.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let S=`${JSON.stringify({mcpServers:u},null,2)}
80
+ `;if(ns(e)){let h=os(t||process.cwd()),_=te(h,".cursor","mcp.json");return cs(_,S,"utf8"),g.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${h} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:h}}return Ke(c)||us(c,{recursive:!0}),cs(l,S,"utf8"),g.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,s,n=null,o){let c=t.cursorKey||t.serverName,l=e[c]?c:e[t.serverName]?t.serverName:null;if(l&&r){let u=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:n,headless:o}):null;u?.args?e[l].args=u.args:e[l].args=(e[l].args||[]).map(f=>f.startsWith("--output-dir=")?`--output-dir=${r}`:f);let p=u?.env||{},d=t.sessionEnvKey?{[t.sessionEnvKey]:s}:{};e[l].env={...e[l].env||{},...p,...d},g.debug(`[MCP] Updated ${l} session \u2192 ${r}`);return}if(l)return;let a=t.resolve({sessionPath:r,nodeName:n,headless:o});a&&(e[c]={...a,...t.sessionEnvKey&&{env:{...a.env||{},[t.sessionEnvKey]:s}}},g.debug(`[MCP] Configured ${c}`))}_spawnWithStreaming(e,t,r,s,n=null,o=null,c=null){return new Promise((l,a)=>{let u=Date.now(),p="",d="",f=Date.now(),m=0,S=!1,h=null,_=!1,y=!1,x=null;if(o)try{x=te(fo(String(o)),at)}catch{x=null}let E=!1,T=()=>{E||(E=!0,is(c))},v={...process.env};c&&(v.HOME=c,process.platform==="win32"&&(v.USERPROFILE=c),g.debug(`[Agent] cursor-agent HOME=${c} (isolated MCP config)`));let I=uo(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:v});g.debug(`[Agent] PID: ${I.pid}`),I.stdin.on("error",w=>{w.code!=="EPIPE"&&g.warn(`[Agent] stdin error: ${w.message}`)}),I.stdout.on("error",w=>{w.code!=="EPIPE"&&g.warn(`[Agent] stdout error: ${w.message}`)}),I.stderr.on("error",w=>{w.code!=="EPIPE"&&g.warn(`[Agent] stderr error: ${w.message}`)}),n?(I.stdin.write(n,w=>{w&&w.code!=="EPIPE"&&g.warn(`[Agent] Failed to write to stdin: ${w.message}`),I.stdin.end()}),g.debug(`[Agent] Prompt also piped to stdin (${n.length} chars)`)):I.stdin.end();let A=null;x&&(A=setInterval(()=>{if(!(S||y))try{if(Ke(x)){S=!0,h="studio-stop";try{po(x)}catch{}g.warn("\u{1F6D1} Studio stop requested \u2014 terminating Cursor agent (and MCP browser session)"),I.kill("SIGTERM"),setTimeout(()=>{I.killed||I.kill("SIGKILL")},2e3)}}catch{}},600));let P=new Set,k=new Date(u).toISOString().replace(/\.\d+Z$/,""),b=setInterval(()=>{let w=Math.round((Date.now()-u)/1e3),$=Math.round((Date.now()-f)/1e3),N=[];try{let R=Math.ceil(w/60)+1,M=de(`find "${r}" -type f -mmin -${R} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(M)for(let L of M.split(`
81
+ `)){let D=L.replace(`${r}/`,"");P.has(D)||(P.add(D),N.push(D))}}catch{}let U="";N.length>0&&(U=` | \u{1F4C1} new: ${N.map(M=>M.split("/").pop()).join(", ")}`),P.size>0&&(U+=` | \u{1F4E6} total: ${P.size} files`),g.debug(`\u{1F493} [Agent] Running for ${w}s | ${m} lines output${U}`),m===0&&w>=30&&P.size===0&&(w<35&&g.warn(`\u26A0\uFE0F [Agent] No output after ${w}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),w>=60&&(S=!0,h=h||"stall",g.error(`\u274C [Agent] No response after ${w}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),I.kill("SIGTERM"),setTimeout(()=>{I.killed||I.kill("SIGKILL")},3e3)))},3e4),C=setTimeout(()=>{S=!0,h=h||"timeout";let w=Math.round((Date.now()-u)/1e3);g.error(`\u23F1\uFE0F [Agent] Timeout after ${w}s \u2014 killing process (PID: ${I.pid})`),p.trim()&&g.warn(`\u{1F4E4} [Agent] Partial output (${p.length} chars) before timeout:
82
+ ${p.slice(-2e3)}`),I.kill("SIGTERM"),setTimeout(()=>{I.killed||I.kill("SIGKILL")},5e3)},s),O=new se;O.onToolCall=(w,$)=>{let N=w,U=$;if(w==="mcpToolCall"&&$?.name)N=$.name.replace(/^mcp_+[^_]+_+/,""),N.includes("-")&&N.split("-")[0]===N.split("-")[1]&&(N=N.split("-")[0]),U=$.args??$.input??$;else{if(w==="readToolCall"||w==="editToolCall"||w==="writeToolCall")return;(w.startsWith("mcp__")||w.includes("ToolCall"))&&(N=w.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(N.includes("memory")?F.stepMemory(`Tool: ${N}`):F.stepTool(`Tool: ${N}`),U!=null&&typeof U=="object"&&Object.keys(U).length>0&&!y){let M=JSON.stringify(U),L=M.length>100?`${M.substring(0,100)}...`:M;console.log(` Input: ${L}`)}},I.stdout.on("data",w=>{let $=w.toString();p+=$,f=Date.now(),_||(_=!0);let N=O.processChunk($);N&&!y&&process.stdout.write(N);let U=$.split(`
83
+ `).filter(R=>R.trim());m+=U.length}),I.stderr.on("data",w=>{let $=w.toString();d+=$,f=Date.now(),_||(_=!0);let N=$.split(`
84
+ `).filter(U=>U.trim());for(let U of N)g.warn(`\u26A0\uFE0F [Agent stderr] ${U}`)}),I.on("close",(w,$)=>{y=!0,T(),clearTimeout(C),clearInterval(b),A&&clearInterval(A),O.flush();let N=Math.round((Date.now()-u)/1e3);if(g.debug(`[Agent] Exited: code=${w}, signal=${$}, elapsed=${N}s, output=${p.length} chars`),S){if(h==="studio-stop"){a(new Error("Stopped from Zibby Studio"));return}a(new Error(`Cursor Agent timed out after ${N}s (limit: ${s/1e3}s). ${m} lines produced. Last output ${Math.round((Date.now()-f)/1e3)}s ago. ${p.trim()?`
79
85
  Partial output (last 500 chars):
80
- ${p.slice(-500)}`:"No output captured."}`));return}if(_!==0){a(new Error(`Cursor Agent failed: exit code ${_}, signal ${C}. ${d.trim()?`
86
+ ${p.slice(-500)}`:"No output captured."}`));return}if(w!==0){a(new Error(`Cursor Agent failed: exit code ${w}, signal ${$}. ${d.trim()?`
81
87
  Stderr: ${d.slice(-1e3)}`:""}${p.trim()?`
82
- Stdout (last 500 chars): ${p.slice(-500)}`:""}`));return}let L=O.getResult(),U=L?JSON.stringify(L,null,2):O.getRawText()||p||"";l({stdout:p||d||"",parsedText:U})}),T.on("error",_=>{v(),clearTimeout(A),clearInterval(b),I&&clearInterval(I),a(new Error(`Cursor Agent spawn error: ${_.message}
88
+ Stdout (last 500 chars): ${p.slice(-500)}`:""}`));return}let U=O.getResult(),R=U?JSON.stringify(U,null,2):O.getRawText()||p||"";l({stdout:p||d||"",parsedText:R})}),I.on("error",w=>{T(),clearTimeout(C),clearInterval(b),A&&clearInterval(A),a(new Error(`Cursor Agent spawn error: ${w.message}
83
89
  Binary: ${e}
84
90
  This usually means the binary is not in PATH. Try:
85
- echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}}});import{query as wo}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as _o}from"zod-to-json-schema";var Ee,ys=M(()=>{ue();V();le();oe();se();Ee=class extends K{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!process.env.ANTHROPIC_API_KEY;return t||h.debug("ClaudeAgentStrategy: ANTHROPIC_API_KEY not set"),t}async invoke(e,t={}){let{model:r,workspace:s=process.cwd(),schema:n=null,images:o=[],skills:c=null,sessionPath:l=null,nodeName:a=null,timeout:u,config:p={}}=t,d=r;(!d||d==="auto")&&(h.debug(`Model is '${d||"undefined"}', using default: ${G.CLAUDE}`),d=G.CLAUDE);let f=Ht[d]||d;Ht[d]&&d!==f&&h.debug(`Mapped model: ${d} \u2192 ${f}`),h.debug(`Invoking Claude Agent SDK with model: ${f}, skills: ${JSON.stringify(c)}`);let m=process.env.ANTHROPIC_API_KEY,S=m?` | key: ***${m.slice(-4)}`:" | key: not set";console.log(`
91
+ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}}});import{query as mo}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as go}from"zod-to-json-schema";var Ie,ms=B(()=>{fe();q();pe();ae();ne();Ie=class extends Z{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!process.env.ANTHROPIC_API_KEY;return t||g.debug("ClaudeAgentStrategy: ANTHROPIC_API_KEY not set"),t}async invoke(e,t={}){let{model:r,workspace:s=process.cwd(),schema:n=null,images:o=[],skills:c=null,sessionPath:l=null,nodeName:a=null,timeout:u,config:p={}}=t,d=r;(!d||d==="auto")&&(g.debug(`Model is '${d||"undefined"}', using default: ${J.CLAUDE}`),d=J.CLAUDE);let f=Wt[d]||d;Wt[d]&&d!==f&&g.debug(`Mapped model: ${d} \u2192 ${f}`),g.debug(`Invoking Claude Agent SDK with model: ${f}, skills: ${JSON.stringify(c)}`);let m=process.env.ANTHROPIC_API_KEY,S=m?` | key: ***${m.slice(-4)}`:" | key: not set";console.log(`
86
92
  \u25C6 Model: ${f}${S}
87
- `);let g=(await import("chalk")).default;console.log(`
88
- ${g.bold("Prompt sent to LLM:")}`),console.log(g.dim("\u2500".repeat(60))),console.log(g.dim(e)),console.log(g.dim("\u2500".repeat(60)));let{allowedTools:w,mcpServers:y}=this._resolveSkills(c,{sessionPath:l,workspace:s,nodeName:a});try{let E={cwd:s,allowedTools:w,permissionMode:"bypassPermissions",model:f,...Object.keys(y).length>0&&{mcpServers:y}};if(n){let A=typeof n.parse=="function"?_o(n,{target:"openApi3"}):n;E.outputFormat={type:"json_schema",schema:A},h.debug("Structured output enforced via SDK outputFormat")}h.debug(`Agent SDK options: ${JSON.stringify({cwd:E.cwd,toolCount:w.length,permissionMode:E.permissionMode,model:E.model,hasOutputFormat:!!E.outputFormat})}`);let x="",v=0,$=[];h.debug("Starting Claude Agent SDK query stream");let T;try{T=wo({prompt:e,options:E})}catch(b){throw h.error(`Failed to initialize Claude Agent SDK: ${b.message}`),b}let I=null,P=0,N=3;try{for await(let b of T){if($.push(b),b.type==="error"||b.error){let O=b.error?.message||b.error||b.message||"Unknown API error";throw new Error(typeof O=="string"?O:JSON.stringify(O))}let A=JSON.stringify(b.message?.content||b.text||"").slice(0,200);if(A===I){if(P++,P>=N){let O=(b.message?.content?.[0]?.text||b.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${P}x repeated): ${O}`)}}else I=A,P=1;if(b.type==="assistant"||b.constructor?.name==="AssistantMessage"){let O=b.message?.content||b.content||[];for(let _ of O)if(_.type==="thinking"&&_.thinking)console.log(`${_.thinking.substring(0,200)}${_.thinking.length>200?"...":""}`);else if(_.type==="text"&&_.text)x+=_.text,_.text.length<500?console.log(`${_.text}`):console.log(`${_.text.substring(0,200)}... (${_.text.length} chars)`);else if(_.type==="tool_use"){v++,_.name.includes("memory")?D.stepMemory(`Tool: ${_.name}`):D.stepTool(`Tool: ${_.name}`);let R=JSON.stringify(_.input).substring(0,100);console.log(` Input: ${R}${JSON.stringify(_.input).length>100?"...":""}`)}}else if(!(b.type==="user"&&b.tool_use_result)){if(b.type==="result"||b.constructor?.name==="ResultMessage"){let O=b.result||b.text||b.content||x;if(n){if(b.structured_output){h.debug("Using SDK native structured_output");let C=typeof n.parse=="function"?n.parse(b.structured_output):b.structured_output;return{raw:O,structured:C}}if(O){let _=this._extractJson(O,n);if(_)return{raw:O,structured:_}}h.warn(`Could not extract structured output \u2014 returning raw text (${(O||"").length} chars)`)}return O||""}}}if(h.warn(`Agent SDK ended without result. Collected ${$.length} messages`),x.length>0)return h.debug("Returning accumulated text from messages"),x;throw new Error("Claude Agent SDK query ended without result")}catch(b){throw h.error(`Error during query stream: ${b.message}`),b}}catch(E){throw h.error("Claude Agent SDK call failed",{error:E.message}),E}}_resolveSkills(e,t){if(e===null)return h.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return h.debug("Default IDE skills for code generation"),{allowedTools:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};let r=[],s={};for(let n of e){let o=z(n);if(!o){h.warn(`Unknown skill "${n}" \u2014 skipping`);continue}if(o.allowedTools&&r.push(...o.allowedTools),typeof o.resolve=="function"){let c=o.resolve(t);c&&(s[o.serverName]=c,h.debug(`MCP: ${o.serverName} \u2192 ${c.command} ${c.args[0]}`))}}return{allowedTools:r,mcpServers:s}}_extractJson(e,t){let r=[()=>{if(e.includes("===JSON_START===")){let s=e.indexOf("===JSON_START===")+16,n=e.indexOf("===JSON_END===");return e.substring(s,n).trim()}},()=>e.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!e.startsWith("{"))return e.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>e.trim(),()=>{let s=e.indexOf("{"),n=e.lastIndexOf("}");if(s!==-1&&n>s)return e.substring(s,n+1)}];for(let s of r)try{let n=s();if(!n)continue;let o=JSON.parse(n);if(typeof o!="object"||o===null)continue;return typeof t.parse=="function"?t.parse(o):o}catch{}return null}}});import{execSync as bo}from"node:child_process";import{zodToJsonSchema as xo}from"zod-to-json-schema";var Te,Ss=M(()=>{ue();V();le();oe();se();Te=class extends K{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.CODEX_API_KEY))return h.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return bo("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return h.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:r,workspace:s=process.cwd(),schema:n=null,skills:o=null,sessionPath:c=null,nodeName:l=null,timeout:a,config:u={}}=t,{Codex:p}=await import("@openai/codex-sdk"),d=r;(!d||d==="auto")&&(h.debug(`Model is '${d||"undefined"}', using default: ${G.CODEX}`),d=G.CODEX);let f=Vt[d]||d;Vt[d]&&d!==f&&h.debug(`Mapped model: ${d} \u2192 ${f}`),h.debug(`Invoking Codex SDK with model: ${f}, skills: ${JSON.stringify(o)}`);let m=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;m&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=m);let S=m?` | key: ***${m.slice(-4)}`:" | key: not set";console.log(`
93
+ `);let h=(await import("chalk")).default;console.log(`
94
+ ${h.bold("Prompt sent to LLM:")}`),console.log(h.dim("\u2500".repeat(60))),console.log(h.dim(e)),console.log(h.dim("\u2500".repeat(60)));let{allowedTools:_,mcpServers:y}=this._resolveSkills(c,{sessionPath:l,workspace:s,nodeName:a});try{let x={cwd:s,allowedTools:_,permissionMode:"bypassPermissions",model:f,...Object.keys(y).length>0&&{mcpServers:y}};if(n){let C=typeof n.parse=="function"?go(n,{target:"openApi3"}):n;x.outputFormat={type:"json_schema",schema:C},g.debug("Structured output enforced via SDK outputFormat")}g.debug(`Agent SDK options: ${JSON.stringify({cwd:x.cwd,toolCount:_.length,permissionMode:x.permissionMode,model:x.model,hasOutputFormat:!!x.outputFormat})}`);let E="",T=0,v=[];g.debug("Starting Claude Agent SDK query stream");let I;try{I=mo({prompt:e,options:x})}catch(b){throw g.error(`Failed to initialize Claude Agent SDK: ${b.message}`),b}let A=null,P=0,k=3;try{for await(let b of I){if(v.push(b),b.type==="error"||b.error){let O=b.error?.message||b.error||b.message||"Unknown API error";throw new Error(typeof O=="string"?O:JSON.stringify(O))}let C=JSON.stringify(b.message?.content||b.text||"").slice(0,200);if(C===A){if(P++,P>=k){let O=(b.message?.content?.[0]?.text||b.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${P}x repeated): ${O}`)}}else A=C,P=1;if(b.type==="assistant"||b.constructor?.name==="AssistantMessage"){let O=b.message?.content||b.content||[];for(let w of O)if(w.type==="thinking"&&w.thinking)console.log(`${w.thinking.substring(0,200)}${w.thinking.length>200?"...":""}`);else if(w.type==="text"&&w.text)E+=w.text,w.text.length<500?console.log(`${w.text}`):console.log(`${w.text.substring(0,200)}... (${w.text.length} chars)`);else if(w.type==="tool_use"){T++,w.name.includes("memory")?F.stepMemory(`Tool: ${w.name}`):F.stepTool(`Tool: ${w.name}`);let N=JSON.stringify(w.input).substring(0,100);console.log(` Input: ${N}${JSON.stringify(w.input).length>100?"...":""}`)}}else if(!(b.type==="user"&&b.tool_use_result)){if(b.type==="result"||b.constructor?.name==="ResultMessage"){let O=b.result||b.text||b.content||E;if(n){if(b.structured_output){g.debug("Using SDK native structured_output");let $=typeof n.parse=="function"?n.parse(b.structured_output):b.structured_output;return{raw:O,structured:$}}if(O){let w=this._extractJson(O,n);if(w)return{raw:O,structured:w}}g.warn(`Could not extract structured output \u2014 returning raw text (${(O||"").length} chars)`)}return O||""}}}if(g.warn(`Agent SDK ended without result. Collected ${v.length} messages`),E.length>0)return g.debug("Returning accumulated text from messages"),E;throw new Error("Claude Agent SDK query ended without result")}catch(b){throw g.error(`Error during query stream: ${b.message}`),b}}catch(x){throw g.error("Claude Agent SDK call failed",{error:x.message}),x}}_resolveSkills(e,t){if(e===null)return g.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return g.debug("Default IDE skills for code generation"),{allowedTools:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};let r=[],s={};for(let n of e){let o=Y(n);if(!o){g.warn(`Unknown skill "${n}" \u2014 skipping`);continue}if(o.allowedTools&&r.push(...o.allowedTools),typeof o.resolve=="function"){let c=o.resolve(t);c&&(s[o.serverName]=c,g.debug(`MCP: ${o.serverName} \u2192 ${c.command} ${c.args[0]}`))}}return{allowedTools:r,mcpServers:s}}_extractJson(e,t){let r=[()=>{if(e.includes("===JSON_START===")){let s=e.indexOf("===JSON_START===")+16,n=e.indexOf("===JSON_END===");return e.substring(s,n).trim()}},()=>e.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!e.startsWith("{"))return e.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>e.trim(),()=>{let s=e.indexOf("{"),n=e.lastIndexOf("}");if(s!==-1&&n>s)return e.substring(s,n+1)}];for(let s of r)try{let n=s();if(!n)continue;let o=JSON.parse(n);if(typeof o!="object"||o===null)continue;return typeof t.parse=="function"?t.parse(o):o}catch{}return null}}});import{execSync as ho}from"node:child_process";import{zodToJsonSchema as yo}from"zod-to-json-schema";var Te,gs=B(()=>{fe();q();pe();ae();ne();Te=class extends Z{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.CODEX_API_KEY))return g.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return ho("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return g.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:r,workspace:s=process.cwd(),schema:n=null,skills:o=null,sessionPath:c=null,nodeName:l=null,timeout:a,config:u={}}=t,{Codex:p}=await import("@openai/codex-sdk"),d=r;(!d||d==="auto")&&(g.debug(`Model is '${d||"undefined"}', using default: ${J.CODEX}`),d=J.CODEX);let f=Kt[d]||d;Kt[d]&&d!==f&&g.debug(`Mapped model: ${d} \u2192 ${f}`),g.debug(`Invoking Codex SDK with model: ${f}, skills: ${JSON.stringify(o)}`);let m=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;m&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=m);let S=m?` | key: ***${m.slice(-4)}`:" | key: not set";console.log(`
89
95
  \u25C6 Model: ${f}${S}
90
- `);let g=(await import("chalk")).default;console.log(`
91
- ${g.bold("Prompt sent to LLM:")}`),console.log(g.dim("\u2500".repeat(60))),console.log(g.dim(e)),console.log(g.dim("\u2500".repeat(60)));let w=this._resolveSkillsToMcp(o,{sessionPath:c,workspace:s,nodeName:l}),y={};Object.keys(w).length>0&&(y.mcp_servers=w,h.debug(`[Codex] MCP servers: ${Object.keys(w).join(", ")}`));let x=new p({...Object.keys(y).length>0&&{config:y}}).startThread({workingDirectory:s,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),v=n&&typeof n.parse=="function",$={};if(n)try{let T=v?xo(n,{target:"openAi"}):n;$.outputSchema=T,h.debug("Structured output via SDK outputSchema")}catch(T){h.warn(`[Codex] Schema conversion failed, will extract from text: ${T.message}`)}try{let{events:T}=await x.runStreamed(e,$),I=0,P="";for await(let N of T){let b=N.type;if(b==="item.completed"){let A=N.item,O=A?.type;if(O==="mcp_tool_call"){I++;let _=`${A.server}/${A.tool}`;if(D.stepTool(`Tool: ${_}`),A.arguments){let C=JSON.stringify(A.arguments),R=C.length>100?`${C.substring(0,100)}...`:C;console.log(` Input: ${R}`)}}else if(O==="tool_call"||O==="function_call"||O==="command_execution"){I++;let _=A.name||A.tool||A.command||"unknown";D.stepTool(`Tool: ${_}`)}else O==="agent_message"&&(P=A.text||"",P.length<500?console.log(P):console.log(`${P.substring(0,200)}... (${P.length} chars)`))}else b==="turn.completed"?h.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(N.usage||{})}`):h.debug(`[Codex] Event: ${b} ${JSON.stringify(N).slice(0,300)}`)}if(h.debug(`[Codex] Last agent message (${P.length} chars): ${P.slice(0,500)}`),n){if(!P)throw new Error("Codex agent returned no response");let N=JSON.parse(P),b=v?n.parse(N):N;return h.debug("\u2705 [Codex] Structured output validated"),{raw:P,structured:b}}return P||""}catch(T){let I=T.message||String(T);throw h.error(`\u274C [Codex] SDK call failed: ${I}`),I.includes("exited with code")&&(h.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),h.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),T}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let s of e){let n=z(s);if(!n){h.warn(`[Codex] Unknown skill "${s}" \u2014 skipping`);continue}if(typeof n.resolve!="function")continue;let o=n.resolve(t);if(!o)continue;let c=n.serverName||s,l={command:o.command};o.args?.length&&(l.args=o.args),o.env&&Object.keys(o.env).length>0&&(l.env=o.env),r[c]=l,h.debug(`[Codex] MCP: ${c} \u2192 ${o.command} ${(o.args||[]).join(" ")}`)}return r}}});import{execSync as Eo,spawn as To}from"node:child_process";import{zodToJsonSchema as vo}from"zod-to-json-schema";import{existsSync as ws,mkdirSync as _s,readFileSync as bs,rmSync as $o,writeFileSync as xs}from"node:fs";import{join as fe}from"node:path";function Io(i){if(!i)return null;let e=String(i),t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t?.[1])try{return JSON.parse(t[1].trim())}catch{}let r=e.indexOf("{");if(r<0)return null;let s=0,n=!1,o=!1,c=-1;for(let l=r;l<e.length;l++){let a=e[l];if(n){o?o=!1:a==="\\"?o=!0:a==='"'&&(n=!1);continue}if(a==='"'){n=!0;continue}if(a==="{"){s===0&&(c=l),s+=1;continue}if(a==="}"){if(s===0)continue;if(s-=1,s===0&&c>=0){let u=e.slice(c,l+1);try{return JSON.parse(u)}catch{c=-1}}}}return null}function Ao(i){let e=String(i||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return Io(e)}}function Oo(i){try{let e=JSON.parse(i);if(typeof e=="string")return e;if(typeof e?.response=="string")return e.response;if(typeof e?.text=="string")return e.text;if(typeof e?.output=="string")return e.output;if(Array.isArray(e?.candidates)&&e.candidates.length>0){let t=e.candidates[0];if(typeof t?.content=="string")return t.content;if(Array.isArray(t?.content?.parts)){let r=t.content.parts.map(s=>typeof s?.text=="string"?s.text:"").join("");if(r.trim())return r}}}catch{}return i}var ve,Es=M(()=>{ue();V();oe();se();Xt();Je();ve=class extends K{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY))return h.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return Eo("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return h.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:r,workspace:s=process.cwd(),schema:n=null,skills:o=null,sessionPath:c=null,nodeName:l=null,timeout:a=600*1e3}=t,u=r;(!u||u==="auto")&&(u=G.GEMINI);let p=es[u]||u,d=String(process.env.GEMINI_API_KEY||"").trim(),f=String(process.env.GOOGLE_API_KEY||"").trim(),m=this._resolveSkillsToMcp(o,{sessionPath:c,workspace:s,nodeName:l}),S=Object.keys(m).length>0,g=e,w=n&&typeof n.parse=="function",y=null;if(n){let A;try{let O=w?vo(n,{target:"openAi"}):n;A=JSON.stringify(O,null,2)}catch{A="{}"}if(S){g+=`
92
-
93
- Write valid JSON that matches this schema:
94
- ${A}`;let O=`zibby-result-${Date.now()}.json`,_=fe(s,".zibby","tmp");y=fe(_,O),_s(_,{recursive:!0}),g+=_e.generateFileOutputInstructions(n,y)}else g+=`
95
-
96
- Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
97
- ${A}`}let E=this._createGeminiConfigDir(s,m),x=["--output-format","json"];p&&p!=="auto"&&x.push("--model",p);let v=Object.keys(m);if(v.length>0){x.push("--approval-mode","yolo");for(let A of v)x.push("--allowed-mcp-server-names",A);h.info(`[Gemini] Enabling MCP servers: ${v.join(", ")}`)}else o&&o.length>0&&h.warn(`[Gemini] Skills requested but no MCP servers configured: ${o.join(", ")}`);x.push("-p",g);let $={...process.env,GEMINI_CLI_HOME:E};d?($.GEMINI_API_KEY=d,delete $.GOOGLE_API_KEY):f&&($.GOOGLE_API_KEY=f,delete $.GEMINI_API_KEY),h.debug(`[Gemini] Command: gemini ${x.slice(0,8).join(" ")}... (${x.length} total args)`),h.debug(`[Gemini] Config home: ${E}`),h.debug(`[Gemini] GEMINI_CLI_HOME env: ${$.GEMINI_CLI_HOME}`);let T="",I=null;try{T=await new Promise((O,_)=>{let C=To("gemini",x,{cwd:s,env:$,stdio:["ignore","pipe","pipe"]}),R="",L="",U=setTimeout(()=>{try{C.kill("SIGTERM")}catch{}},a);C.stdout.on("data",k=>{R+=k.toString()}),C.stderr.on("data",k=>{L+=k.toString()}),C.on("error",k=>{clearTimeout(U),_(k)}),C.on("close",k=>{if(clearTimeout(U),k===0)return O(R.trim());_(new Error(`gemini failed with code ${k}: ${(L||R).trim()}`))})})}catch(A){I=A}finally{try{$o(E,{recursive:!0,force:!0})}catch{}}let P=Oo(T).trim();if(!n){if(I)throw I;return P}if(y){let A=ws(y);if(h.info(`[Gemini] Result file: ${A?"present":"missing"} at ${y}`),A)try{let O=bs(y,"utf-8").trim(),_=JSON.parse(O),C=w?n.parse(_):_;return h.info("[Gemini] Structured output recovered from result file"),{raw:P,structured:C}}catch(O){h.warn(`[Gemini] Result file parse/validation failed: ${O.message}`)}else I||h.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let N=null;if(n){let A=new te;A.zodSchema=n,A.processChunk(P),A.flush(),N=A.getResult()}if(h.info(`[Gemini] Raw stdout length: ${T.length} chars`),h.info(`[Gemini] Extracted text length: ${P.length} chars`),h.info(`[Gemini] StreamParser result: ${N?"extracted":"null"}`),N||(P.length<2e3?h.info(`[Gemini] Raw text preview:
98
- ${P}`):h.info(`[Gemini] Raw text preview (first 1000 chars):
99
- ${P.slice(0,1e3)}`),N=Ao(P)),!N)throw I||(h.error("[Gemini] Failed to extract valid JSON from output"),h.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error("Gemini did not return valid JSON for structured output. Enable strictMode for proxy fallback."));let b=w?n.parse(N):N;return{raw:P,structured:b}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let s of e){let n=z(s);if(!n||typeof n.resolve!="function")continue;let o=n.resolve(t);if(!o)continue;let c=n.cursorKey||n.serverName||s,l={command:o.command};o.args?.length&&(l.args=o.args),o.env&&Object.keys(o.env).length>0&&(l.env=o.env),o.cwd&&(l.cwd=o.cwd),r[c]=l}return r}_createGeminiConfigDir(e,t){let r=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,s=fe(e||process.cwd(),".zibby","tmp",`gemini-home-${r}`),n=fe(s,".gemini");_s(n,{recursive:!0});let o=fe(n,"settings.json"),c={},l=fe(process.env.HOME||"",".gemini","settings.json");if(ws(l))try{c=JSON.parse(bs(l,"utf-8"))}catch{c={}}let a={...c,mcpServers:{...c.mcpServers&&typeof c.mcpServers=="object"?c.mcpServers:{},...t||{}}};xs(o,`${JSON.stringify(a,null,2)}
100
- `,"utf-8");let u=fe(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{xs(u,`${JSON.stringify(a,null,2)}
101
- `,"utf-8")}catch{}return h.debug(`[Gemini] Created isolated config with ${Object.keys(a.mcpServers||{}).length} MCP servers`),h.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(a.mcpServers||{}),null,2)}`),s}}});var $e,er=M(()=>{$e=class{formatTools(e){throw new Error("formatTools() must be implemented")}hasToolCalls(e){throw new Error("hasToolCalls() must be implemented")}parseToolCalls(e){throw new Error("parseToolCalls() must be implemented")}getTextContent(e){throw new Error("getTextContent() must be implemented")}buildAssistantMessage(e){throw new Error("buildAssistantMessage() must be implemented")}buildToolResultMessage(e,t){throw new Error("buildToolResultMessage() must be implemented")}injectToolsIntoBody(e,t){throw new Error("injectToolsIntoBody() must be implemented")}}});var de,Ts=M(()=>{er();de=class extends $e{formatTools(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters||t.input_schema||{type:"object",properties:{}}}}))}hasToolCalls(e){let t=e.choices?.[0]?.message;return!!(t?.tool_calls&&t.tool_calls.length>0)}parseToolCalls(e){return(e.choices?.[0]?.message?.tool_calls||[]).map(r=>({id:r.id,name:r.function.name,args:JSON.parse(r.function.arguments||"{}")}))}getTextContent(e){return e.choices?.[0]?.message?.content||""}buildAssistantMessage(e){return e.choices?.[0]?.message}buildToolResultMessage(e,t){return{role:"tool",tool_call_id:e,content:typeof t=="string"?t:JSON.stringify(t)}}injectToolsIntoBody(e,t){return t.length>0&&(e.tools=t),e}}});var qe,tr=M(()=>{qe=class{async fetchCompletion(e,t,r={}){throw new Error("fetchCompletion() must be implemented")}async fetchStreamingCompletion(e,t,r={}){throw new Error("fetchStreamingCompletion() must be implemented")}}});function wt(i){return Buffer.byteLength(JSON.stringify(i),"utf8")}function _t(i,e){let t=String(i||"");if(t.length<=e)return t;let r=Math.max(0,e-28);return`${t.slice(0,r)}
102
-
103
- [truncated for size budget]`}function rr(i,e=0){if(!i||typeof i!="object"||e>8)return i;if(Array.isArray(i))return i.map(r=>rr(r,e+1));let t={};for(let[r,s]of Object.entries(i))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=rr(s,e+1));return t}function Po(i=[]){return i.map(e=>({...e,function:{...e.function,description:_t(e.function?.description||"",180),parameters:rr(e.function?.parameters||{type:"object",properties:{}})}}))}function vs(i){let e=new Set;for(let s of i)if(s.role==="assistant"&&Array.isArray(s.tool_calls))for(let n of s.tool_calls)e.add(n.id);let t=i.filter(s=>s.role==="tool"?e.has(s.tool_call_id):!0),r=new Set;for(let s of t)s.role==="tool"&&r.add(s.tool_call_id);return t.map(s=>{if(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.every(l=>r.has(l.id)))return s;let{tool_calls:o,...c}=s;return{...c,content:c.content||""}})}function sr(i,e={}){let t=e.maxBytes||49e3,r=e.systemMaxChars||12e3,s={...i,messages:Array.isArray(i.messages)?[...i.messages]:[],tools:Array.isArray(i.tools)?Po(i.tools):i.tools};s.messages.length>0&&s.messages[0]?.role==="system"&&(s.messages[0]={...s.messages[0],content:_t(s.messages[0].content,r)});let n=!1;for(;wt(s)>t&&s.messages.length>2;)s.messages.splice(1,1),n=!0;if(n&&(s.messages=vs(s.messages)),wt(s)>t&&s.messages.length>0&&(s.messages[0]={...s.messages[0],content:_t(s.messages[0].content,6e3)},n=!0),wt(s)>t){let o=s.messages.find(l=>l.role==="system")||s.messages[0],c=s.messages.slice(-2);s.messages=vs([o,...c].filter(Boolean).map((l,a)=>({...l,content:_t(l.content,a===0?4e3:8e3)}))),n=!0}return{body:s,meta:{bytes:wt(s),trimmed:n,maxBytes:t,messageCount:s.messages.length}}}var $s=M(()=>{});var Is,Ie,As=M(()=>{tr();$s();Is=i=>Buffer.byteLength(JSON.stringify(i),"utf8"),Ie=class extends qe{async fetchCompletion(e,t,r={}){let s=Is(e),{body:n,meta:o}=sr(e,r.payloadCompaction);r.onBudget?.({streaming:!1,beforeBytes:s,meta:o});let c=this.#e(r),l=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,a=await fetch(l,{method:"POST",headers:t.headers,body:JSON.stringify(n),signal:c});if(!a.ok){let u=await a.text();throw a.status===401||a.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${a.status}: ${u}`)}return a.json()}async fetchStreamingCompletion(e,t,r={}){let s={...e,stream:!0},n=Is(s),{body:o,meta:c}=sr(s,r.payloadCompaction);r.onBudget?.({streaming:!0,beforeBytes:n,meta:c});let l=this.#e(r),a=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,u=await fetch(a,{method:"POST",headers:t.headers,body:JSON.stringify(o),signal:l});if(!u.ok){let g=await u.text();throw u.status===401||u.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${u.status}: ${g}`)}let p=u.body.getReader(),d=new TextDecoder,f="",m="",S=new Map;for(;;){let{done:g,value:w}=await p.read();if(g)break;f+=d.decode(w,{stream:!0});let y=f.split(`
104
- `);f=y.pop();for(let E of y){if(!E.startsWith("data: "))continue;let x=E.slice(6).trim();if(x==="[DONE]")continue;let v;try{v=JSON.parse(x)}catch{continue}let $=v.choices?.[0]?.delta;if($&&($.content&&(m+=$.content,r.onToken&&r.onToken($.content)),$.tool_calls))for(let T of $.tool_calls){let I=T.index??0;S.has(I)||S.set(I,{id:"",name:"",args:""});let P=S.get(I);T.id&&(P.id=T.id),T.function?.name&&(P.name=T.function.name),T.function?.arguments!=null&&(P.args+=T.function.arguments)}}}if(S.size>0){let g=[...S.entries()].sort(([w],[y])=>w-y).map(([,w])=>({id:w.id,type:"function",function:{name:w.name,arguments:w.args}}));return{choices:[{message:{role:"assistant",content:m||null,tool_calls:g}}]}}return{choices:[{message:{role:"assistant",content:m}}]}}#e(e={}){let t=[e.signal,e.timeout?AbortSignal.timeout(e.timeout):null].filter(Boolean);return t.length>1?AbortSignal.any(t):t[0]||void 0}}});var nr=M(()=>{er();Ts();tr();As()});import{Client as Co}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as No}from"@modelcontextprotocol/sdk/client/stdio.js";var Xe,or=M(()=>{V();Xe=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:r,args:s=[],env:n={}}=t;h.debug(`[MCP] Starting ${e}: ${r} ${s.join(" ")}`);let o=new No({command:r,args:s,env:{...process.env,...n}}),c=new Co({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await c.connect(o);let l={client:c,transport:o,serverConfig:t};return this.#e.set(e,l),l}async callTool(e,t,r={}){let s=this.#e.get(e);if(!s)throw new Error(`MCP server "${e}" not running`);h.debug(`[MCP] ${e}.${t}(${JSON.stringify(r).slice(0,200)})`);let n=await s.client.callTool({name:t,arguments:r});return{text:n.content?.filter(c=>c.type==="text").map(c=>c.text).join(`
105
- `)||"",isError:n.isError||!1}}isRunning(e){return this.#e.has(e)}async stopServer(e){let t=this.#e.get(e);if(t){try{await t.client.close()}catch(r){h.debug(`[MCP] Error closing ${e}: ${r.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}}});import{existsSync as Ro,readFileSync as ko}from"node:fs";import{join as Mo}from"node:path";import{homedir as Lo}from"node:os";function Do(){try{let i=Mo(Lo(),".zibby","config.json");return Ro(i)?JSON.parse(ko(i,"utf-8")):{}}catch{return{}}}function bt(i){return String(i||"").replace(/\/v1\/?$/,"")}function Bo(i,e){let t=process.env.OPENAI_PROXY_URL;if(t)return bt(t);if(i==="session")return e.proxyUrl?bt(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(i==="byok"){let r=process.env.OPENAI_BASE_URL;return bt(r||"https://api.openai.com")}return bt(t||"")}function ir(){let i=Do(),e=process.env.ZIBBY_USER_TOKEN||i.sessionToken||null,t=process.env.OPENAI_API_KEY||null,r=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),s=process.env.OPENAI_PROXY_NO_AUTH==="true",n=process.env.OPENAI_PROXY_URL,o="session";r==="byok"||r==="local"||r==="session"?o=r:e?o="session":t?o="byok":n&&s&&(o="local");let c=Bo(o,i),l={"Content-Type":"application/json"};if(o==="session"){if(!e)return{ok:!1,mode:o,reason:"missing_session_token"};l.Authorization=`Bearer ${e}`}else if(o==="byok"){if(!t)return{ok:!1,mode:o,reason:"missing_openai_api_key"};l.Authorization=`Bearer ${t}`}else if(o==="local"){if(!c)return{ok:!1,mode:o,reason:"missing_openai_proxy_url"};!s&&t&&(l.Authorization=`Bearer ${t}`)}return c?{ok:!0,mode:o,baseUrl:c,headers:l,tokenPreview:l.Authorization?`***${l.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:o,reason:"missing_base_url"}}var Os=M(()=>{});function xt(i,e){let t=String(i??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
106
-
107
- [tool result truncated for size]`}function Fo(i,e){if(typeof i=="string")return xt(i,e);try{return xt(JSON.stringify(i),e)}catch{return xt(String(i),e)}}function Ps(i){let e=new Set;for(let s of i)if(s.role==="assistant"&&Array.isArray(s.tool_calls))for(let n of s.tool_calls)e.add(n.id);let t=i.filter(s=>s.role==="tool"?e.has(s.tool_call_id):!0),r=new Set;for(let s of t)s.role==="tool"&&r.add(s.tool_call_id);return t.map(s=>{if(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.every(l=>r.has(l.id)))return s;let{tool_calls:o,...c}=s;return{...c,content:c.content||""}})}function Uo(i){let e=Array.isArray(i?.messages)?i.messages:[],t=e.find(n=>n.role==="system"),r=e.slice(-4).map(n=>({...n,content:xt(n.content,n.role==="tool"?1200:2500)}));r=Ps(r);let s={...i,messages:[t,...r].filter(Boolean)};return delete s.tools,s}async function jo({body:i,streaming:e,auth:t,options:r,fetchCompletion:s,fetchStreamingCompletion:n,onFallbackLog:o}){try{return e?await n(i,t,r):await s(i,t,r)}catch(c){let l=String(c?.message||c||"");if(!/proxy error 413|payload too large/i.test(l))throw c;let a=Uo(i);return typeof o=="function"&&o(i,a),{data:e?await n(a,t,r):await s(a,t,r),fallback:a}}}async function Cs({body:i,auth:e,options:t,streaming:r,toolContext:s,activeSkills:n,round:o,verbose:c,dependencies:l,config:a={}}){let u=a.maxToolResultChars||3e3,{fetchCompletion:p,fetchStreamingCompletion:d,onFallbackLog:f,hasToolCalls:m,getTextContent:S,parseToolCalls:g,buildAssistantMessage:w,buildToolResultMessage:y,executeTool:E,onToolCallLog:x,injectTools:v}=l;Array.isArray(i?.messages)&&(i.messages=Ps(i.messages));let $=await jo({body:i,streaming:r,auth:e,options:t,fetchCompletion:p,fetchStreamingCompletion:d,onFallbackLog:f}),T=$?.data||$;if(!m(T))return{done:!0,text:S(T),body:$?.fallback||i};let I=g(T),P=$?.fallback||i;P.messages.push(w(T)),c&&typeof x=="function"&&x(I);let N=await Promise.all(I.map((b,A)=>(typeof t.onToolCall=="function"&&t.onToolCall(b.name,b.args,{round:o,index:A,total:I.length}),E(b,s))));for(let b=0;b<I.length;b++){let O=I[b].name==="get_skill_context"?typeof N[b]=="string"?N[b]:JSON.stringify(N[b]):Fo(N[b],u);P.messages.push(y(I[b].id,O))}return typeof t.onToolCall=="function"&&t.onToolCall(null),v(P,n),{done:!1,body:P}}var Ns=M(()=>{});function Oe(i){!i||typeof i!="object"||(i.type==="object"&&i.properties&&(i.required=Object.keys(i.properties),i.additionalProperties=!1,Object.values(i.properties).forEach(Oe)),i.type==="array"&&i.items&&Oe(i.items),i.anyOf&&i.anyOf.forEach(Oe),i.oneOf&&i.oneOf.forEach(Oe),i.allOf&&i.allOf.forEach(Oe))}function Et(i){return Array.isArray(i)?new Set(i.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function Wo(i){return Array.isArray(i)?i.map(e=>String(e||"").trim()).filter(Boolean):[]}var Go,zo,ar,Rs,Ae,Jo,Pe,ks=M(()=>{ue();V();oe();nr();or();se();Os();Ns();Go=G.ASSISTANT,zo=15,ar="get_skill_context";Rs={maxBytes:49e3,systemMaxChars:12e3},Ae=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Jo=i=>Buffer.byteLength(JSON.stringify(i),"utf8");Pe=class extends K{#e;#t;#r=new Xe;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new de,this.#t=e.completionProvider||new Ie):(this.#e=e||new de,this.#t=new Ie)}canHandle(e){return ir().ok}async invoke(e,t={}){let r=t.model&&t.model!=="auto"?t.model:Go,s=ir();if(!s.ok)throw s.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):s.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):s.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${s.reason}).`);let n=t.messages||[{role:"user",content:e}],o=s.baseUrl,c=Ae();if(c?await this.#m(n,r,o,s.tokenPreview||"none"):h.debug(`[Assistant] ${o} | model: ${r} | messages: ${n.length}`),t.schema)return this.#l(r,n,s,t);let l=t.activeSkills||[],a=this.#p(t),u=this.#f(l,a),p=this.#d(u),d=this.#u(t),f={...t,payloadCompaction:d},m={activeSkills:u,options:f,executionRegistry:p,capabilityPolicy:a},S=!!t.stream,g={model:r,messages:[...n],stream:!1};this.#n(g,u,a);for(let w=0;w<zo;w++){if(t.signal?.aborted)throw new Error("Aborted");let y=await Cs({body:g,auth:s,options:f,streaming:S,toolContext:m,activeSkills:u,round:w,verbose:c,dependencies:{fetchCompletion:this.#o.bind(this),fetchStreamingCompletion:this.#c.bind(this),onFallbackLog:(E,x)=>{Ae()&&console.log(`413 fallback: messages ${E.messages.length} -> ${x.messages.length}, bytes=${Jo(x)}`)},hasToolCalls:E=>this.#e.hasToolCalls(E),getTextContent:E=>this.#e.getTextContent(E),parseToolCalls:E=>this.#e.parseToolCalls(E),buildAssistantMessage:E=>this.#e.buildAssistantMessage(E),buildToolResultMessage:(E,x)=>this.#e.buildToolResultMessage(E,x),executeTool:(E,x)=>this.#a(E,x),onToolCallLog:async E=>{let x=(await import("chalk")).default;console.log(x.dim(` ${E.map(v=>`${v.name}(${JSON.stringify(v.args).slice(0,80)})`).join(", ")}`))},injectTools:(E,x)=>this.#n(E,x,a)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(y.done)return y.text;g.messages=y.body.messages,y.body.tools?g.tools=y.body.tools:delete g.tools}return"I hit my tool-calling limit for this turn. Please try again."}async cleanup(){await this.#r.stopAll()}#n(e,t,r=null){let s=this.#i(t,r),n=this.#e.formatTools(s);this.#e.injectToolsIntoBody(e,n)}#i(e,t=null){let r=[],s=new Set;for(let n of e){let o=z(n);if(o?.tools?.length)for(let c of o.tools)this.#s(c.name,t)&&(s.has(c.name)||(s.add(c.name),r.push({name:c.name,description:c.description,parameters:c.parameters||c.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#s(ar,t)&&r.push({name:ar,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),r}async#a(e,t){let{activeSkills:r,options:s,executionRegistry:n,capabilityPolicy:o}=t;if(!this.#s(e.name,o))return`Tool "${e.name}" blocked by policy`;if(e.name===ar){let a=String(e.args?.skillId||"").trim();if(!a)return JSON.stringify({error:"skillId is required"});if(!r.includes(a))return JSON.stringify({error:`Skill "${a}" is not active`,activeSkills:r});let u=z(a);if(!u)return JSON.stringify({error:`Skill "${a}" not found`});let p=typeof u.promptFragment=="function"?u.promptFragment():u.promptFragment||"",d=(u.tools||[]).map(m=>m.name),f=JSON.stringify({skillId:a,description:u.description||"",toolNames:d,promptFragment:p||""});return Ae()&&(console.log(`
96
+ `);let h=(await import("chalk")).default;console.log(`
97
+ ${h.bold("Prompt sent to LLM:")}`),console.log(h.dim("\u2500".repeat(60))),console.log(h.dim(e)),console.log(h.dim("\u2500".repeat(60)));let _=this._resolveSkillsToMcp(o,{sessionPath:c,workspace:s,nodeName:l}),y={};Object.keys(_).length>0&&(y.mcp_servers=_,g.debug(`[Codex] MCP servers: ${Object.keys(_).join(", ")}`));let E=new p({...Object.keys(y).length>0&&{config:y}}).startThread({workingDirectory:s,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),T=n&&typeof n.parse=="function",v={};if(n)try{let I=T?yo(n,{target:"openAi"}):n;v.outputSchema=I,g.debug("Structured output via SDK outputSchema")}catch(I){g.warn(`[Codex] Schema conversion failed, will extract from text: ${I.message}`)}try{let{events:I}=await E.runStreamed(e,v),A=0,P="";for await(let k of I){let b=k.type;if(b==="item.completed"){let C=k.item,O=C?.type;if(O==="mcp_tool_call"){A++;let w=`${C.server}/${C.tool}`;if(F.stepTool(`Tool: ${w}`),C.arguments){let $=JSON.stringify(C.arguments),N=$.length>100?`${$.substring(0,100)}...`:$;console.log(` Input: ${N}`)}}else if(O==="tool_call"||O==="function_call"||O==="command_execution"){A++;let w=C.name||C.tool||C.command||"unknown";F.stepTool(`Tool: ${w}`)}else O==="agent_message"&&(P=C.text||"",P.length<500?console.log(P):console.log(`${P.substring(0,200)}... (${P.length} chars)`))}else b==="turn.completed"?g.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(k.usage||{})}`):g.debug(`[Codex] Event: ${b} ${JSON.stringify(k).slice(0,300)}`)}if(g.debug(`[Codex] Last agent message (${P.length} chars): ${P.slice(0,500)}`),n){if(!P)throw new Error("Codex agent returned no response");let k=JSON.parse(P),b=T?n.parse(k):k;return g.debug("\u2705 [Codex] Structured output validated"),{raw:P,structured:b}}return P||""}catch(I){let A=I.message||String(I);throw g.error(`\u274C [Codex] SDK call failed: ${A}`),A.includes("exited with code")&&(g.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),g.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),I}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let s of e){let n=Y(s);if(!n){g.warn(`[Codex] Unknown skill "${s}" \u2014 skipping`);continue}if(typeof n.resolve!="function")continue;let o=n.resolve(t);if(!o)continue;let c=n.serverName||s,l={command:o.command};o.args?.length&&(l.args=o.args),o.env&&Object.keys(o.env).length>0&&(l.env=o.env),r[c]=l,g.debug(`[Codex] MCP: ${c} \u2192 ${o.command} ${(o.args||[]).join(" ")}`)}return r}}});import{execSync as So,spawn as wo}from"node:child_process";import{zodToJsonSchema as _o}from"zod-to-json-schema";import{existsSync as hs,mkdirSync as ys,readFileSync as Ss,rmSync as bo,writeFileSync as ws}from"node:fs";import{join as me}from"node:path";function xo(i){if(!i)return null;let e=String(i),t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t?.[1])try{return JSON.parse(t[1].trim())}catch{}let r=e.indexOf("{");if(r<0)return null;let s=0,n=!1,o=!1,c=-1;for(let l=r;l<e.length;l++){let a=e[l];if(n){o?o=!1:a==="\\"?o=!0:a==='"'&&(n=!1);continue}if(a==='"'){n=!0;continue}if(a==="{"){s===0&&(c=l),s+=1;continue}if(a==="}"){if(s===0)continue;if(s-=1,s===0&&c>=0){let u=e.slice(c,l+1);try{return JSON.parse(u)}catch{c=-1}}}}return null}function Eo(i){let e=String(i||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return xo(e)}}function Io(i){try{let e=JSON.parse(i);if(typeof e=="string")return e;if(typeof e?.response=="string")return e.response;if(typeof e?.text=="string")return e.text;if(typeof e?.output=="string")return e.output;if(Array.isArray(e?.candidates)&&e.candidates.length>0){let t=e.candidates[0];if(typeof t?.content=="string")return t.content;if(Array.isArray(t?.content?.parts)){let r=t.content.parts.map(s=>typeof s?.text=="string"?s.text:"").join("");if(r.trim())return r}}}catch{}return i}var $e,_s=B(()=>{fe();q();ae();ne();Ht();Je();$e=class extends Z{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY))return g.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return So("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return g.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:r,workspace:s=process.cwd(),schema:n=null,skills:o=null,sessionPath:c=null,nodeName:l=null,timeout:a=600*1e3}=t,u=r;(!u||u==="auto")&&(u=J.GEMINI);let p=Vr[u]||u,d=String(process.env.GEMINI_API_KEY||"").trim(),f=String(process.env.GOOGLE_API_KEY||"").trim(),m=this._resolveSkillsToMcp(o,{sessionPath:c,workspace:s,nodeName:l}),S=Object.keys(m).length>0,h=new be(e),_=n&&typeof n.parse=="function",y=null;if(n){let R;try{let M=_?_o(n,{target:"openAi"}):n;R=JSON.stringify(M,null,2)}catch{R="{}"}if(S){h.addSystemInstruction(`Write valid JSON that matches this schema:
98
+ ${R}`,"schema_instruction","append");let M=`zibby-result-${Date.now()}.json`,L=me(s,".zibby","tmp");y=me(L,M),ys(L,{recursive:!0}),h.addStructuredOutput(n,y)}else h.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
99
+ ${R}`,"json_instruction","append")}let x=h.build(),E=h.getUserPrompt(),T=h.getStats(),v=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),I=v?` | key: ***${v.slice(-4)}`:" | key: not set";console.log(`
100
+ \u25C6 Model: ${p||"auto"}${I}
101
+ `);let A=(await import("chalk")).default;console.log(`
102
+ ${A.bold("Prompt sent to LLM:")}`),console.log(A.dim("\u2500".repeat(60))),console.log(A.dim(E)),console.log(A.dim("\u2500".repeat(60)));let P=this._createGeminiConfigDir(s,m),k=["--output-format","json"];p&&p!=="auto"&&k.push("--model",p);let b=Object.keys(m);if(b.length>0){k.push("--approval-mode","yolo");for(let R of b)k.push("--allowed-mcp-server-names",R);g.info(`[Gemini] Enabling MCP servers: ${b.join(", ")}`)}else o&&o.length>0&&g.warn(`[Gemini] Skills requested but no MCP servers configured: ${o.join(", ")}`);k.push("-p",x);let C={...process.env,GEMINI_CLI_HOME:P};d?(C.GEMINI_API_KEY=d,delete C.GOOGLE_API_KEY):f&&(C.GOOGLE_API_KEY=f,delete C.GEMINI_API_KEY),g.debug(`[Gemini] Command: gemini ${k.slice(0,8).join(" ")}... (${k.length} total args)`),g.debug(`[Gemini] User prompt: ${T.userPromptLength} chars, System instructions: ${T.systemInstructionsLength} chars (${T.instructionCount} blocks), Full: ${T.fullPromptLength} chars`),g.debug(`[Gemini] Config home: ${P}`),g.debug(`[Gemini] GEMINI_CLI_HOME env: ${C.GEMINI_CLI_HOME}`);let O="",w=null;try{O=await new Promise((M,L)=>{let D=wo("gemini",k,{cwd:s,env:C,stdio:["ignore","pipe","pipe"]}),z="",ie="",V=setTimeout(()=>{try{D.kill("SIGTERM")}catch{}},a);D.stdout.on("data",H=>{z+=H.toString()}),D.stderr.on("data",H=>{ie+=H.toString()}),D.on("error",H=>{clearTimeout(V),L(H)}),D.on("close",H=>{if(clearTimeout(V),H===0)return M(z.trim());L(new Error(`gemini failed with code ${H}: ${(ie||z).trim()}`))})})}catch(R){w=R}finally{try{bo(P,{recursive:!0,force:!0})}catch{}}let $=Io(O).trim();if(!n){if(w)throw w;return $}if(y){let R=hs(y);if(g.info(`[Gemini] Result file: ${R?"present":"missing"} at ${y}`),R)try{let M=Ss(y,"utf-8").trim(),L=JSON.parse(M),D=_?n.parse(L):L;return g.info("[Gemini] Structured output recovered from result file"),{raw:$,structured:D}}catch(M){g.warn(`[Gemini] Result file parse/validation failed: ${M.message}`)}else w||g.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let N=null;if(n){let R=new se;R.zodSchema=n,R.processChunk($),R.flush(),N=R.getResult()}if(g.info(`[Gemini] Raw stdout length: ${O.length} chars`),g.info(`[Gemini] Extracted text length: ${$.length} chars`),g.info(`[Gemini] StreamParser result: ${N?"extracted":"null"}`),N||($.length<2e3?g.info(`[Gemini] Raw text preview:
103
+ ${$}`):g.info(`[Gemini] Raw text preview (first 1000 chars):
104
+ ${$.slice(0,1e3)}`),N=Eo($)),!N)throw w||(g.error("[Gemini] Failed to extract valid JSON from output"),g.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error("Gemini did not return valid JSON for structured output. Enable strictMode for proxy fallback."));let U=_?n.parse(N):N;return{raw:$,structured:U}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let s of e){let n=Y(s);if(!n||typeof n.resolve!="function")continue;let o=n.resolve(t);if(!o)continue;let c=n.cursorKey||n.serverName||s,l={command:o.command};o.args?.length&&(l.args=o.args),o.env&&Object.keys(o.env).length>0&&(l.env=o.env),o.cwd&&(l.cwd=o.cwd),r[c]=l}return r}_createGeminiConfigDir(e,t){let r=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,s=me(e||process.cwd(),".zibby","tmp",`gemini-home-${r}`),n=me(s,".gemini");ys(n,{recursive:!0});let o=me(n,"settings.json"),c={},l=me(process.env.HOME||"",".gemini","settings.json");if(hs(l))try{c=JSON.parse(Ss(l,"utf-8"))}catch{c={}}let a={...c,mcpServers:{...c.mcpServers&&typeof c.mcpServers=="object"?c.mcpServers:{},...t||{}}};ws(o,`${JSON.stringify(a,null,2)}
105
+ `,"utf-8");let u=me(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{ws(u,`${JSON.stringify(a,null,2)}
106
+ `,"utf-8")}catch{}return g.debug(`[Gemini] Created isolated config with ${Object.keys(a.mcpServers||{}).length} MCP servers`),g.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(a.mcpServers||{}),null,2)}`),s}}});var ve,Xt=B(()=>{ve=class{formatTools(e){throw new Error("formatTools() must be implemented")}hasToolCalls(e){throw new Error("hasToolCalls() must be implemented")}parseToolCalls(e){throw new Error("parseToolCalls() must be implemented")}getTextContent(e){throw new Error("getTextContent() must be implemented")}buildAssistantMessage(e){throw new Error("buildAssistantMessage() must be implemented")}buildToolResultMessage(e,t){throw new Error("buildToolResultMessage() must be implemented")}injectToolsIntoBody(e,t){throw new Error("injectToolsIntoBody() must be implemented")}}});var ge,bs=B(()=>{Xt();ge=class extends ve{formatTools(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters||t.input_schema||{type:"object",properties:{}}}}))}hasToolCalls(e){let t=e.choices?.[0]?.message;return!!(t?.tool_calls&&t.tool_calls.length>0)}parseToolCalls(e){return(e.choices?.[0]?.message?.tool_calls||[]).map(r=>({id:r.id,name:r.function.name,args:JSON.parse(r.function.arguments||"{}")}))}getTextContent(e){return e.choices?.[0]?.message?.content||""}buildAssistantMessage(e){return e.choices?.[0]?.message}buildToolResultMessage(e,t){return{role:"tool",tool_call_id:e,content:typeof t=="string"?t:JSON.stringify(t)}}injectToolsIntoBody(e,t){return t.length>0&&(e.tools=t),e}}});var He,qt=B(()=>{He=class{async fetchCompletion(e,t,r={}){throw new Error("fetchCompletion() must be implemented")}async fetchStreamingCompletion(e,t,r={}){throw new Error("fetchStreamingCompletion() must be implemented")}}});function yt(i){return Buffer.byteLength(JSON.stringify(i),"utf8")}function St(i,e){let t=String(i||"");if(t.length<=e)return t;let r=Math.max(0,e-28);return`${t.slice(0,r)}
107
+
108
+ [truncated for size budget]`}function Qt(i,e=0){if(!i||typeof i!="object"||e>8)return i;if(Array.isArray(i))return i.map(r=>Qt(r,e+1));let t={};for(let[r,s]of Object.entries(i))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=Qt(s,e+1));return t}function To(i=[]){return i.map(e=>({...e,function:{...e.function,description:St(e.function?.description||"",180),parameters:Qt(e.function?.parameters||{type:"object",properties:{}})}}))}function xs(i){let e=new Set;for(let s of i)if(s.role==="assistant"&&Array.isArray(s.tool_calls))for(let n of s.tool_calls)e.add(n.id);let t=i.filter(s=>s.role==="tool"?e.has(s.tool_call_id):!0),r=new Set;for(let s of t)s.role==="tool"&&r.add(s.tool_call_id);return t.map(s=>{if(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.every(l=>r.has(l.id)))return s;let{tool_calls:o,...c}=s;return{...c,content:c.content||""}})}function er(i,e={}){let t=e.maxBytes||49e3,r=e.systemMaxChars||12e3,s={...i,messages:Array.isArray(i.messages)?[...i.messages]:[],tools:Array.isArray(i.tools)?To(i.tools):i.tools};s.messages.length>0&&s.messages[0]?.role==="system"&&(s.messages[0]={...s.messages[0],content:St(s.messages[0].content,r)});let n=!1;for(;yt(s)>t&&s.messages.length>2;)s.messages.splice(1,1),n=!0;if(n&&(s.messages=xs(s.messages)),yt(s)>t&&s.messages.length>0&&(s.messages[0]={...s.messages[0],content:St(s.messages[0].content,6e3)},n=!0),yt(s)>t){let o=s.messages.find(l=>l.role==="system")||s.messages[0],c=s.messages.slice(-2);s.messages=xs([o,...c].filter(Boolean).map((l,a)=>({...l,content:St(l.content,a===0?4e3:8e3)}))),n=!0}return{body:s,meta:{bytes:yt(s),trimmed:n,maxBytes:t,messageCount:s.messages.length}}}var Es=B(()=>{});var Is,Ae,Ts=B(()=>{qt();Es();Is=i=>Buffer.byteLength(JSON.stringify(i),"utf8"),Ae=class extends He{async fetchCompletion(e,t,r={}){let s=Is(e),{body:n,meta:o}=er(e,r.payloadCompaction);r.onBudget?.({streaming:!1,beforeBytes:s,meta:o});let c=this.#e(r),l=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,a=await fetch(l,{method:"POST",headers:t.headers,body:JSON.stringify(n),signal:c});if(!a.ok){let u=await a.text();throw a.status===401||a.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${a.status}: ${u}`)}return a.json()}async fetchStreamingCompletion(e,t,r={}){let s={...e,stream:!0},n=Is(s),{body:o,meta:c}=er(s,r.payloadCompaction);r.onBudget?.({streaming:!0,beforeBytes:n,meta:c});let l=this.#e(r),a=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,u=await fetch(a,{method:"POST",headers:t.headers,body:JSON.stringify(o),signal:l});if(!u.ok){let h=await u.text();throw u.status===401||u.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${u.status}: ${h}`)}let p=u.body.getReader(),d=new TextDecoder,f="",m="",S=new Map;for(;;){let{done:h,value:_}=await p.read();if(h)break;f+=d.decode(_,{stream:!0});let y=f.split(`
109
+ `);f=y.pop();for(let x of y){if(!x.startsWith("data: "))continue;let E=x.slice(6).trim();if(E==="[DONE]")continue;let T;try{T=JSON.parse(E)}catch{continue}let v=T.choices?.[0]?.delta;if(v&&(v.content&&(m+=v.content,r.onToken&&r.onToken(v.content)),v.tool_calls))for(let I of v.tool_calls){let A=I.index??0;S.has(A)||S.set(A,{id:"",name:"",args:""});let P=S.get(A);I.id&&(P.id=I.id),I.function?.name&&(P.name=I.function.name),I.function?.arguments!=null&&(P.args+=I.function.arguments)}}}if(S.size>0){let h=[...S.entries()].sort(([_],[y])=>_-y).map(([,_])=>({id:_.id,type:"function",function:{name:_.name,arguments:_.args}}));return{choices:[{message:{role:"assistant",content:m||null,tool_calls:h}}]}}return{choices:[{message:{role:"assistant",content:m}}]}}#e(e={}){let t=[e.signal,e.timeout?AbortSignal.timeout(e.timeout):null].filter(Boolean);return t.length>1?AbortSignal.any(t):t[0]||void 0}}});var tr=B(()=>{Xt();bs();qt();Ts()});import{Client as $o}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as vo}from"@modelcontextprotocol/sdk/client/stdio.js";var Ve,rr=B(()=>{q();Ve=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:r,args:s=[],env:n={}}=t;g.debug(`[MCP] Starting ${e}: ${r} ${s.join(" ")}`);let o=new vo({command:r,args:s,env:{...process.env,...n}}),c=new $o({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await c.connect(o);let l={client:c,transport:o,serverConfig:t};return this.#e.set(e,l),l}async callTool(e,t,r={}){let s=this.#e.get(e);if(!s)throw new Error(`MCP server "${e}" not running`);g.debug(`[MCP] ${e}.${t}(${JSON.stringify(r).slice(0,200)})`);let n=await s.client.callTool({name:t,arguments:r});return{text:n.content?.filter(c=>c.type==="text").map(c=>c.text).join(`
110
+ `)||"",isError:n.isError||!1}}isRunning(e){return this.#e.has(e)}async stopServer(e){let t=this.#e.get(e);if(t){try{await t.client.close()}catch(r){g.debug(`[MCP] Error closing ${e}: ${r.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}}});import{existsSync as Ao,readFileSync as Po}from"node:fs";import{join as Oo}from"node:path";import{homedir as Co}from"node:os";function No(){try{let i=Oo(Co(),".zibby","config.json");return Ao(i)?JSON.parse(Po(i,"utf-8")):{}}catch{return{}}}function wt(i){return String(i||"").replace(/\/v1\/?$/,"")}function Ro(i,e){let t=process.env.OPENAI_PROXY_URL;if(t)return wt(t);if(i==="session")return e.proxyUrl?wt(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(i==="byok"){let r=process.env.OPENAI_BASE_URL;return wt(r||"https://api.openai.com")}return wt(t||"")}function sr(){let i=No(),e=process.env.ZIBBY_USER_TOKEN||i.sessionToken||null,t=process.env.OPENAI_API_KEY||null,r=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),s=process.env.OPENAI_PROXY_NO_AUTH==="true",n=process.env.OPENAI_PROXY_URL,o="session";r==="byok"||r==="local"||r==="session"?o=r:e?o="session":t?o="byok":n&&s&&(o="local");let c=Ro(o,i),l={"Content-Type":"application/json"};if(o==="session"){if(!e)return{ok:!1,mode:o,reason:"missing_session_token"};l.Authorization=`Bearer ${e}`}else if(o==="byok"){if(!t)return{ok:!1,mode:o,reason:"missing_openai_api_key"};l.Authorization=`Bearer ${t}`}else if(o==="local"){if(!c)return{ok:!1,mode:o,reason:"missing_openai_proxy_url"};!s&&t&&(l.Authorization=`Bearer ${t}`)}return c?{ok:!0,mode:o,baseUrl:c,headers:l,tokenPreview:l.Authorization?`***${l.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:o,reason:"missing_base_url"}}var $s=B(()=>{});function _t(i,e){let t=String(i??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
111
+
112
+ [tool result truncated for size]`}function ko(i,e){if(typeof i=="string")return _t(i,e);try{return _t(JSON.stringify(i),e)}catch{return _t(String(i),e)}}function vs(i){let e=new Set;for(let s of i)if(s.role==="assistant"&&Array.isArray(s.tool_calls))for(let n of s.tool_calls)e.add(n.id);let t=i.filter(s=>s.role==="tool"?e.has(s.tool_call_id):!0),r=new Set;for(let s of t)s.role==="tool"&&r.add(s.tool_call_id);return t.map(s=>{if(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.every(l=>r.has(l.id)))return s;let{tool_calls:o,...c}=s;return{...c,content:c.content||""}})}function Mo(i){let e=Array.isArray(i?.messages)?i.messages:[],t=e.find(n=>n.role==="system"),r=e.slice(-4).map(n=>({...n,content:_t(n.content,n.role==="tool"?1200:2500)}));r=vs(r);let s={...i,messages:[t,...r].filter(Boolean)};return delete s.tools,s}async function Lo({body:i,streaming:e,auth:t,options:r,fetchCompletion:s,fetchStreamingCompletion:n,onFallbackLog:o}){try{return e?await n(i,t,r):await s(i,t,r)}catch(c){let l=String(c?.message||c||"");if(!/proxy error 413|payload too large/i.test(l))throw c;let a=Mo(i);return typeof o=="function"&&o(i,a),{data:e?await n(a,t,r):await s(a,t,r),fallback:a}}}async function As({body:i,auth:e,options:t,streaming:r,toolContext:s,activeSkills:n,round:o,verbose:c,dependencies:l,config:a={}}){let u=a.maxToolResultChars||3e3,{fetchCompletion:p,fetchStreamingCompletion:d,onFallbackLog:f,hasToolCalls:m,getTextContent:S,parseToolCalls:h,buildAssistantMessage:_,buildToolResultMessage:y,executeTool:x,onToolCallLog:E,injectTools:T}=l;Array.isArray(i?.messages)&&(i.messages=vs(i.messages));let v=await Lo({body:i,streaming:r,auth:e,options:t,fetchCompletion:p,fetchStreamingCompletion:d,onFallbackLog:f}),I=v?.data||v;if(!m(I))return{done:!0,text:S(I),body:v?.fallback||i};let A=h(I),P=v?.fallback||i;P.messages.push(_(I)),c&&typeof E=="function"&&E(A);let k=await Promise.all(A.map((b,C)=>(typeof t.onToolCall=="function"&&t.onToolCall(b.name,b.args,{round:o,index:C,total:A.length}),x(b,s))));for(let b=0;b<A.length;b++){let O=A[b].name==="get_skill_context"?typeof k[b]=="string"?k[b]:JSON.stringify(k[b]):ko(k[b],u);P.messages.push(y(A[b].id,O))}return typeof t.onToolCall=="function"&&t.onToolCall(null),T(P,n),{done:!1,body:P}}var Ps=B(()=>{});function Oe(i){!i||typeof i!="object"||(i.type==="object"&&i.properties&&(i.required=Object.keys(i.properties),i.additionalProperties=!1,Object.values(i.properties).forEach(Oe)),i.type==="array"&&i.items&&Oe(i.items),i.anyOf&&i.anyOf.forEach(Oe),i.oneOf&&i.oneOf.forEach(Oe),i.allOf&&i.allOf.forEach(Oe))}function bt(i){return Array.isArray(i)?new Set(i.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function Fo(i){return Array.isArray(i)?i.map(e=>String(e||"").trim()).filter(Boolean):[]}var Do,Bo,nr,Os,Pe,Uo,Ce,Cs=B(()=>{fe();q();ae();tr();rr();ne();$s();Ps();Do=J.ASSISTANT,Bo=15,nr="get_skill_context";Os={maxBytes:49e3,systemMaxChars:12e3},Pe=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Uo=i=>Buffer.byteLength(JSON.stringify(i),"utf8");Ce=class extends Z{#e;#t;#r=new Ve;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new ge,this.#t=e.completionProvider||new Ae):(this.#e=e||new ge,this.#t=new Ae)}canHandle(e){return sr().ok}async invoke(e,t={}){let r=t.model&&t.model!=="auto"?t.model:Do,s=sr();if(!s.ok)throw s.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):s.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):s.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${s.reason}).`);let n=t.messages||[{role:"user",content:e}],o=s.baseUrl,c=Pe();if(c?await this.#m(n,r,o,s.tokenPreview||"none"):g.debug(`[Assistant] ${o} | model: ${r} | messages: ${n.length}`),t.schema)return this.#l(r,n,s,t);let l=t.activeSkills||[],a=this.#p(t),u=this.#f(l,a),p=this.#d(u),d=this.#u(t),f={...t,payloadCompaction:d},m={activeSkills:u,options:f,executionRegistry:p,capabilityPolicy:a},S=!!t.stream,h={model:r,messages:[...n],stream:!1};this.#n(h,u,a);for(let _=0;_<Bo;_++){if(t.signal?.aborted)throw new Error("Aborted");let y=await As({body:h,auth:s,options:f,streaming:S,toolContext:m,activeSkills:u,round:_,verbose:c,dependencies:{fetchCompletion:this.#o.bind(this),fetchStreamingCompletion:this.#c.bind(this),onFallbackLog:(x,E)=>{Pe()&&console.log(`413 fallback: messages ${x.messages.length} -> ${E.messages.length}, bytes=${Uo(E)}`)},hasToolCalls:x=>this.#e.hasToolCalls(x),getTextContent:x=>this.#e.getTextContent(x),parseToolCalls:x=>this.#e.parseToolCalls(x),buildAssistantMessage:x=>this.#e.buildAssistantMessage(x),buildToolResultMessage:(x,E)=>this.#e.buildToolResultMessage(x,E),executeTool:(x,E)=>this.#a(x,E),onToolCallLog:async x=>{let E=(await import("chalk")).default;console.log(E.dim(` ${x.map(T=>`${T.name}(${JSON.stringify(T.args).slice(0,80)})`).join(", ")}`))},injectTools:(x,E)=>this.#n(x,E,a)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(y.done)return y.text;h.messages=y.body.messages,y.body.tools?h.tools=y.body.tools:delete h.tools}return"I hit my tool-calling limit for this turn. Please try again."}async cleanup(){await this.#r.stopAll()}#n(e,t,r=null){let s=this.#i(t,r),n=this.#e.formatTools(s);this.#e.injectToolsIntoBody(e,n)}#i(e,t=null){let r=[],s=new Set;for(let n of e){let o=Y(n);if(o?.tools?.length)for(let c of o.tools)this.#s(c.name,t)&&(s.has(c.name)||(s.add(c.name),r.push({name:c.name,description:c.description,parameters:c.parameters||c.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#s(nr,t)&&r.push({name:nr,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),r}async#a(e,t){let{activeSkills:r,options:s,executionRegistry:n,capabilityPolicy:o}=t;if(!this.#s(e.name,o))return`Tool "${e.name}" blocked by policy`;if(e.name===nr){let a=String(e.args?.skillId||"").trim();if(!a)return JSON.stringify({error:"skillId is required"});if(!r.includes(a))return JSON.stringify({error:`Skill "${a}" is not active`,activeSkills:r});let u=Y(a);if(!u)return JSON.stringify({error:`Skill "${a}" not found`});let p=typeof u.promptFragment=="function"?u.promptFragment():u.promptFragment||"",d=(u.tools||[]).map(m=>m.name),f=JSON.stringify({skillId:a,description:u.description||"",toolNames:d,promptFragment:p||""});return Pe()&&(console.log(`
108
113
  \u{1F4D6} get_skill_context("${a}") \u2192 ${f.length} chars (fragment: ${p.length} chars)`),console.log(` tools: [${d.join(", ")}]`),console.log(` fragment preview: ${p.slice(0,200).replace(/\n/g,"\\n")}\u2026
109
- `)),f}let c=n?.get(e.name)||null;if(!c)return`Unknown tool: ${e.name}`;let l=z(c.skillId);if(!l)return`Skill "${c.skillId}" not found for tool "${e.name}"`;if(c.mode==="handler")try{return l.handleToolCall(e.name,e.args,t)}catch(a){return`Error in ${e.name}: ${a.message}`}if(c.mode==="mcp")try{if(!this.#r.isRunning(l.serverName)){let u=l.resolve(s);if(!u)return`Skill "${c.skillId}" is not available (cannot start server)`;await this.#r.ensureServer(l.serverName,u)}let a=await this.#r.callTool(l.serverName,e.name,e.args);return a.text||(a.isError?"Tool call failed":"Done")}catch(a){return`MCP error (${l.serverName}): ${a.message}`}return`Skill "${c.skillId}" owns tool "${e.name}" but has no execution mode`}async#c(e,t,r){return this.#t.fetchStreamingCompletion(e,t,{...r,onBudget:({beforeBytes:s,meta:n})=>{Ae()&&console.log(`payload bytes (stream) before=${s} after=${n.bytes} trimmed=${n.trimmed} messages=${n.messageCount}`)}})}async#o(e,t,r){return this.#t.fetchCompletion(e,t,{...r,onBudget:({beforeBytes:s,meta:n})=>{Ae()&&console.log(`payload bytes before=${s} after=${n.bytes} trimmed=${n.trimmed} messages=${n.messageCount}`)}})}async#l(e,t,r,s){let{zodToJsonSchema:n}=await import("zod-to-json-schema"),o=typeof s.schema?.parse=="function",c=o?n(s.schema):s.schema;delete c.$schema,Oe(c);let l={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:c,strict:!0}}},a=await this.#o(l,r,s),u=this.#e.getTextContent(a),p=JSON.parse(u),d=o?s.schema.parse(p):p;return{raw:u,structured:d}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||Rs.maxBytes),systemMaxChars:Number(t.systemMaxChars||Rs.systemMaxChars)}}#p(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:Et(t.allowTools||e.allowTools),denyTools:Et(t.denyTools||e.denyTools),denyPrefixes:Wo(t.denyPrefixes||e.denyToolPrefixes),includeSkills:Et(t.includeSkills||e.includeSkills),excludeSkills:Et(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#f(e,t){let r=t?.includeSkills||new Set,s=t?.excludeSkills||new Set;return r.size===0&&s.size===0?e:e.filter(n=>!(r.size>0&&!r.has(n)||s.has(n)))}#s(e,t){let r=String(e||"").trim();if(!r)return!1;let s=t?.allowTools;if(s&&s.size>0&&!s.has(r))return!1;let n=t?.denyTools;return!(n&&n.has(r)||(t?.denyPrefixes||[]).some(c=>r.startsWith(c)))}#d(e){let t=new Map,r=[];for(let s of e){let n=z(s);if(!n?.tools?.length)continue;let o=typeof n.handleToolCall=="function"?"handler":n.serverName&&typeof n.resolve=="function"?"mcp":null;if(o)for(let c of n.tools){let l=String(c?.name||"").trim();if(l){if(t.has(l)){r.push({tool:l,winner:t.get(l).skillId,skipped:s});continue}t.set(l,{skillId:s,mode:o})}}}if(r.length>0&&Ae()){let s=r.slice(0,5).map(n=>`${n.tool}:${n.winner}>${n.skipped}`).join(", ");console.log(`tool registry collisions: ${s}${r.length>5?" ...":""}`)}return t}async#m(e,t,r,s){console.log(`
114
+ `)),f}let c=n?.get(e.name)||null;if(!c)return`Unknown tool: ${e.name}`;let l=Y(c.skillId);if(!l)return`Skill "${c.skillId}" not found for tool "${e.name}"`;if(c.mode==="handler")try{return l.handleToolCall(e.name,e.args,t)}catch(a){return`Error in ${e.name}: ${a.message}`}if(c.mode==="mcp")try{if(!this.#r.isRunning(l.serverName)){let u=l.resolve(s);if(!u)return`Skill "${c.skillId}" is not available (cannot start server)`;await this.#r.ensureServer(l.serverName,u)}let a=await this.#r.callTool(l.serverName,e.name,e.args);return a.text||(a.isError?"Tool call failed":"Done")}catch(a){return`MCP error (${l.serverName}): ${a.message}`}return`Skill "${c.skillId}" owns tool "${e.name}" but has no execution mode`}async#c(e,t,r){return this.#t.fetchStreamingCompletion(e,t,{...r,onBudget:({beforeBytes:s,meta:n})=>{Pe()&&console.log(`payload bytes (stream) before=${s} after=${n.bytes} trimmed=${n.trimmed} messages=${n.messageCount}`)}})}async#o(e,t,r){return this.#t.fetchCompletion(e,t,{...r,onBudget:({beforeBytes:s,meta:n})=>{Pe()&&console.log(`payload bytes before=${s} after=${n.bytes} trimmed=${n.trimmed} messages=${n.messageCount}`)}})}async#l(e,t,r,s){let{zodToJsonSchema:n}=await import("zod-to-json-schema"),o=typeof s.schema?.parse=="function",c=o?n(s.schema):s.schema;delete c.$schema,Oe(c);let l={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:c,strict:!0}}},a=await this.#o(l,r,s),u=this.#e.getTextContent(a),p=JSON.parse(u),d=o?s.schema.parse(p):p;return{raw:u,structured:d}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||Os.maxBytes),systemMaxChars:Number(t.systemMaxChars||Os.systemMaxChars)}}#p(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:bt(t.allowTools||e.allowTools),denyTools:bt(t.denyTools||e.denyTools),denyPrefixes:Fo(t.denyPrefixes||e.denyToolPrefixes),includeSkills:bt(t.includeSkills||e.includeSkills),excludeSkills:bt(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#f(e,t){let r=t?.includeSkills||new Set,s=t?.excludeSkills||new Set;return r.size===0&&s.size===0?e:e.filter(n=>!(r.size>0&&!r.has(n)||s.has(n)))}#s(e,t){let r=String(e||"").trim();if(!r)return!1;let s=t?.allowTools;if(s&&s.size>0&&!s.has(r))return!1;let n=t?.denyTools;return!(n&&n.has(r)||(t?.denyPrefixes||[]).some(c=>r.startsWith(c)))}#d(e){let t=new Map,r=[];for(let s of e){let n=Y(s);if(!n?.tools?.length)continue;let o=typeof n.handleToolCall=="function"?"handler":n.serverName&&typeof n.resolve=="function"?"mcp":null;if(o)for(let c of n.tools){let l=String(c?.name||"").trim();if(l){if(t.has(l)){r.push({tool:l,winner:t.get(l).skillId,skipped:s});continue}t.set(l,{skillId:s,mode:o})}}}if(r.length>0&&Pe()){let s=r.slice(0,5).map(n=>`${n.tool}:${n.winner}>${n.skipped}`).join(", ");console.log(`tool registry collisions: ${s}${r.length>5?" ...":""}`)}return t}async#m(e,t,r,s){console.log(`
110
115
  \u25C6 Model: ${t} | proxy: ${r} | token: ${s||"none"}
111
- `);let n=(await import("chalk")).default;console.log(n.bold("Prompt sent to LLM:")),console.log(n.dim("\u2500".repeat(60)));let o=!1;for(let c of e)if(c.role==="system")console.log(n.dim(`[System] ${c.content||""}`));else{o||(console.log(n.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),o=!0);let l=c.role==="user"?"Human":"AI",a=c.content?.length>200?`${c.content.slice(0,200)}...`:c.content||"";console.log(n.dim(`[${l}] ${a}`))}console.log(n.dim("\u2500".repeat(60)))}}});var lr={};lt(lr,{AgentStrategy:()=>K,AssistantStrategy:()=>Pe,ClaudeAgentStrategy:()=>Ee,CodexAgentStrategy:()=>Te,CursorAgentStrategy:()=>xe,GeminiAgentStrategy:()=>ve,getAgentStrategy:()=>cr,invokeAgent:()=>Ls});function cr(i={}){let{state:e={},preferredAgent:t=null}=i,r=t||e.agentType||process.env.AGENT_TYPE;if(!r)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");h.debug(`Agent selection: requested=${r}`);let s=Ms.find(n=>n.getName()===r);if(!s)throw new Error(`Unknown agent '${r}'. Available: ${Ms.map(n=>n.getName()).join(", ")}`);if(h.debug(`Checking if ${r} can handle this environment...`),!s.canHandle(i)){let o={assistant:"Run `zibby login` to authenticate",claude:"Set ANTHROPIC_API_KEY in .env",cursor:"Install cursor-agent CLI or set CURSOR_API_KEY",codex:"Install codex CLI (npm i -g @openai/codex) and set OPENAI_API_KEY in .env",gemini:"Install gemini CLI (npm i -g @google/gemini-cli) and set GEMINI_API_KEY in .env"}[r]||"Check your environment configuration";throw new Error(`Agent '${r}' is not available. ${o}`)}return h.debug(`Using agent: ${s.getName()}`),s}async function Ls(i,e={},t={}){try{await import("@zibby/skills")}catch{}let r=cr(e),s=e.state?.config||t.config||{},n=s.models||{},o=t.nodeName&&n[t.nodeName]||null,c=n.default||null,l=r.name,a=s.agent?.[l]?.model||null,u=o||c||a||t.model||null,p={...t,model:u,workspace:e.state?.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:s},d=p.skills||[];if(d.length>0&&!t.skipPromptFragments){let{getSkill:m}=await Promise.resolve().then(()=>(se(),qt)),S=d.map(g=>{let w=m(g)?.promptFragment;return typeof w=="function"?w():w}).filter(Boolean);S.length>0&&(i+=`
116
+ `);let n=(await import("chalk")).default;console.log(n.bold("Prompt sent to LLM:")),console.log(n.dim("\u2500".repeat(60)));let o=!1;for(let c of e)if(c.role==="system")console.log(n.dim(`[System] ${c.content||""}`));else{o||(console.log(n.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),o=!0);let l=c.role==="user"?"Human":"AI",a=c.content?.length>200?`${c.content.slice(0,200)}...`:c.content||"";console.log(n.dim(`[${l}] ${a}`))}console.log(n.dim("\u2500".repeat(60)))}}});var ir={};it(ir,{AgentStrategy:()=>Z,AssistantStrategy:()=>Ce,ClaudeAgentStrategy:()=>Ie,CodexAgentStrategy:()=>Te,CursorAgentStrategy:()=>Ee,GeminiAgentStrategy:()=>$e,getAgentStrategy:()=>or,invokeAgent:()=>Rs});function or(i={}){let{state:e={},preferredAgent:t=null}=i,r=t||e.agentType||process.env.AGENT_TYPE;if(!r)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");g.debug(`Agent selection: requested=${r}`);let s=Ns.find(n=>n.getName()===r);if(!s)throw new Error(`Unknown agent '${r}'. Available: ${Ns.map(n=>n.getName()).join(", ")}`);if(g.debug(`Checking if ${r} can handle this environment...`),!s.canHandle(i)){let o={assistant:"Run `zibby login` to authenticate",claude:"Set ANTHROPIC_API_KEY in .env",cursor:"Install cursor-agent CLI or set CURSOR_API_KEY",codex:"Install codex CLI (npm i -g @openai/codex) and set OPENAI_API_KEY in .env",gemini:"Install gemini CLI (npm i -g @google/gemini-cli) and set GEMINI_API_KEY in .env"}[r]||"Check your environment configuration";throw new Error(`Agent '${r}' is not available. ${o}`)}return g.debug(`Using agent: ${s.getName()}`),s}async function Rs(i,e={},t={}){try{await import("@zibby/skills")}catch{}let r=or(e),s=e.state?.config||t.config||{},n=s.models||{},o=t.nodeName&&n[t.nodeName]||null,c=n.default||null,l=r.name,a=s.agent?.[l]?.model||null,u=o||c||a||t.model||null,p={...t,model:u,workspace:e.state?.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:s},d=p.skills||[],f=i;if(d.length>0&&!t.skipPromptFragments){let{getSkill:S}=await Promise.resolve().then(()=>(ne(),Zt)),h=d.map(_=>{let y=S(_)?.promptFragment;return typeof y=="function"?y():y}).filter(Boolean);h.length>0&&(f+=`
112
117
 
113
- ${S.join(`
118
+ ${h.join(`
114
119
 
115
- `)}`)}let f=e.state?._currentNodeConfig?.extraPromptInstructions?.trim();return f&&(i+=`
120
+ `)}`)}let m=e.state?._currentNodeConfig?.extraPromptInstructions?.trim();return m&&(f+=`
116
121
 
117
122
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
118
123
  \u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
119
124
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
120
125
 
121
- ${f}
122
- `),h.debug(`Prompt length: ${i.length} chars`),process.env.STAGE!=="prod"&&h.debug(`Full prompt:
123
- ${i}`),r.invoke(i,p)}var Ms,Tt=M(()=>{gs();ys();Ss();Es();ks();V();ue();Ms=[new Pe,new xe,new Ee,new Te,new ve]});var Fs={};lt(Fs,{ConditionalNode:()=>Qe,Node:()=>me});import{writeFileSync as ur,readFileSync as Ds,existsSync as Bs,mkdirSync as Yo}from"node:fs";import{join as pr,dirname as Ko}from"node:path";import vt from"chalk";var me,Qe,fr=M(()=>{Yr();V();le();ee();me=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new ht(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=p=>t&&typeof t.get=="function"?t.get(p):e?.[p];if(typeof this.customExecute=="function"){h.info("\u26A1 Using custom execute method (skipping LLM)");try{let p=await this.customExecute(e);return typeof p=="object"&&p!==null&&p.success===!1?{success:!1,error:p.error||"Node execution failed",raw:p.raw||null}:this.isZodSchema?(h.debug("Validating return value against outputSchema..."),{success:!0,output:this.outputSchema.parse(p),raw:null}):{success:!0,output:p,raw:null}}catch(p){return h.error(`\u274C Node '${this.name}' execution failed: ${p.message}`),p.name==="ZodError"&&h.error(`Schema validation errors: ${JSON.stringify(p.errors,null,2)}`),{success:!1,error:p.message,raw:null}}}let n=typeof this.prompt=="function"?this.prompt(r()):this.prompt,o=s("_skillHints");o&&(n=`${o}
124
-
125
- ${n}`);let c=r(),l=c.cwd||process.cwd(),a=c.sessionPath;try{if(a){let p=pr(a,q);if(Bs(p)){let f=JSON.parse(Ds(p,"utf-8"));f.currentNode=this.name,ur(p,JSON.stringify(f,null,2),"utf-8")}let d=pr(a,"..",q);if(Bs(d))try{let f=JSON.parse(Ds(d,"utf-8"));f.currentNode=this.name,ur(d,JSON.stringify(f,null,2),"utf-8")}catch{}}}catch(p){h.debug(`Could not update session info: ${p.message}`)}let u=null;for(let p=0;p<=this.retries;p++)try{h.debug(`Node.execute attempt ${p} for '${this.name}'`);let d=r(),f=d.config||{},m={state:d},S={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:a,config:f,nodeName:this.name,timeout:this.config?.timeout||3e5},g=e?._coreInvokeAgent;g||(g=(await Promise.resolve().then(()=>(Tt(),lr))).invokeAgent);let w=await g(n,m,S),y,E;if(typeof w=="string"?(y=w,E=null):w.structured?(y=w.raw||JSON.stringify(w.structured,null,2),E=w.structured):(y=w.raw||JSON.stringify(w,null,2),E=w.extracted||null),a)try{let x=pr(a,this.name,"raw_stream_output.txt");Yo(Ko(x),{recursive:!0}),ur(x,typeof y=="string"?y:JSON.stringify(y),"utf-8")}catch(x){h.debug(`Could not save raw output: ${x.message}`)}if(this.isZodSchema&&E){console.log(`
126
- \u{1F50D} ${vt.cyan("Validated output:")} ${vt.white(JSON.stringify(E,null,2))}`);let x=E;if(typeof this.onComplete=="function")try{x=await this.onComplete(r(),E)}catch(v){h.warn(`onComplete hook failed: ${v.message}`)}return{success:!0,output:x,raw:y}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:y}),raw:y}}catch(x){throw new Error(`onComplete failed: ${x.message}`,{cause:x})}if(this.parser){let x=this.parser.parse(y);return console.log(`
127
- \u{1F50D} ${vt.cyan("Parsed output:")} ${vt.white(JSON.stringify(x,null,2))}`),D.step("Output parsed"),{success:!0,output:x,raw:y}}return{success:!0,output:y,raw:y}}catch(d){u=d,p<this.retries&&h.info(`Node '${this.name}' failed, retrying (${p+1}/${this.retries})...`)}return{success:!1,error:u.message,raw:null}}},Qe=class extends me{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,t){let r=t&&typeof t.getAll=="function"?t.getAll():e;return{success:!0,output:{nextNode:this.condition(r)},raw:null}}}});ee();import{readFileSync as dn,existsSync as mn}from"node:fs";import{join as Fe,resolve as hn,isAbsolute as ua}from"node:path";import{existsSync as ze,readdirSync as Lr,statSync as Rn}from"fs";import{join as Y,relative as Dt,sep as Ge,resolve as ce}from"path";ee();import{appendFileSync as En,readFileSync as Tn,existsSync as Ar,mkdirSync as vn}from"node:fs";import{join as pt}from"node:path";var Or="run-index.jsonl";function Pr(i,e=B){let t=pt(i,e);return pt(t,Or)}function ft(i){if(!i||!i.sessionId)return;let e=i.cwd||process.cwd(),t=i.outputBase||B,r=pt(e,t);Ar(r)||vn(r,{recursive:!0});let s=pt(r,Or),n=`${JSON.stringify(i)}
128
- `;En(s,n,"utf8")}function Cr(i){if(!i||!Ar(i))return[];let e;try{e=Tn(i,"utf8")}catch{return[]}let t=[];for(let r of e.split(`
129
- `)){let s=r.trim();if(s)try{t.push(JSON.parse(s))}catch{}}return t}import{existsSync as $n,mkdirSync as In,readFileSync as An,readdirSync as xa,statSync as Ea,writeFileSync as On}from"node:fs";import{join as Pn}from"node:path";var Cn="zibby-run-state.json";function Nr(i){return Pn(i,Cn)}function Mt(i){if(!i||typeof i!="string")return null;let e=Nr(i);if(!$n(e))return null;try{let t=An(e,"utf8"),r=JSON.parse(t);return r&&typeof r=="object"?r:null}catch{return null}}function dt(i,e){if(!i||typeof i!="string")return;try{In(i,{recursive:!0})}catch{return}let r={...Mt(i)||{v:1},...e,v:1,updatedAt:Date.now()};try{On(Nr(i),`${JSON.stringify(r)}
130
- `,"utf8")}catch(s){console.warn(`[zibby run-state] ${s.message}`)}}function Nn(i){return i?.recordKind==="progress"}function Rr(i){let e=Number(i)||0;return e<=0?0:e<1e12?e*1e3:e}function kr(i,e={}){let t=e.maxProgressAgeMs!=null&&Number.isFinite(e.maxProgressAgeMs)?Math.max(0,e.maxProgressAgeMs):21e5,r=typeof e.now=="number"?e.now:Date.now(),{summary:s,progress:n}=i||{};if(!n)return!1;let o=Rr(n.ts);if(t>0&&o>0&&r-o>t)return!1;if(!s)return o>0;let c=Rr(s.ts);return o>c}function Mr(i){let e=new Map;for(let t of i||[]){if(!t?.sessionId)continue;let r=e.get(t.sessionId);r||(r={summary:null,progress:null});let s=Number(t.ts)||0;Nn(t)?(!r.progress||s>=(Number(r.progress.ts)||0))&&(r.progress=t):(!r.summary||s>=(Number(r.summary.ts)||0))&&(r.summary=t),e.set(t.sessionId,r)}return e}ee();var Lt=Object.freeze(["preflight","execute_live","generate_script"]);function Bt(i){let e=process.env.ZIBBY_STUDIO_TEST_CASE_ID;return e!=null&&String(e).trim()!==""?String(e).trim():i!=null?String(i):""}var kn=[Y("generate_script","generated-test.spec.js"),Y("generate_script","generated-test.spec.ts"),Y("generate_script","playwright.spec.ts"),Y("generate_script","test.spec.ts")];function Mn(i){let e=[Y(i,"execute_live","videos"),Y(i,"execute_live"),i];for(let t of e){if(!ze(t))continue;let r;try{r=Lr(t)}catch{continue}let s=r.find(n=>n.endsWith(".webm"));if(s)return Y(t,s)}return null}function Ln(i){let e=[Y(i,"execute_live","events.json"),Y(i,"events.json")];for(let t of e)if(ze(t))return t;return null}function Dn(i){for(let e of kn){let t=Y(i,e);if(ze(t))return t}return null}function Bn(i){return!i||!ze(i)?{videoPathAbs:null,eventsPathAbs:null,scriptPathAbs:null}:{videoPathAbs:Mn(i),eventsPathAbs:Ln(i),scriptPathAbs:Dn(i)}}function Dr(i){let e=i.cwd||process.cwd(),t=i.outputBase||B,n=((i.result||{}).state||{}).sessionPath;if(!n||typeof n!="string")return null;let o=n.split(/[/\\]/).filter(Boolean).pop();if(!o)return null;let{videoPathAbs:c,eventsPathAbs:l,scriptPathAbs:a}=Bn(n),u=d=>{if(!d)return null;try{return Dt(e,d).split(Ge).join("/")}catch{return null}},p=null;if(i.specPath)try{let d=ce(e,i.specPath);p=Dt(e,d).split(Ge).join("/")}catch{p=String(i.specPath).split(Ge).join("/")}return{v:1,recordKind:"summary",ts:Date.now(),sessionId:o,status:i.status??(i.success?"completed":"failed"),cwd:e,outputBase:t,sessionPathAbs:n,sessionDirRel:u(n),videoPathAbs:c||null,eventsPathAbs:l||null,scriptPathAbs:a||null,videoRel:u(c),eventsRel:u(l),scriptRel:u(a),specRel:p,source:process.env.ZIBBY_RUN_SOURCE||"cli",studioTestCaseId:Bt(o)||null,errorMessage:i.errorMessage||null}}function Br({cwd:i,config:e,result:t,success:r,specPath:s,errorMessage:n}){try{let o=Dr({cwd:i||process.cwd(),result:t,success:r,outputBase:e?.paths?.output||B,specPath:s,errorMessage:n});o&&(ft(o),o.sessionPathAbs&&dt(o.sessionPathAbs,{sessionId:o.sessionId,studioTestCaseId:o.studioTestCaseId||o.sessionId,status:o.status,activeNode:null,activeStageIndex:null,errorMessage:o.errorMessage||null,runSource:o.source||"cli",cwd:o.cwd,outputBase:o.outputBase,sessionPathAbs:o.sessionPathAbs}))}catch(o){console.warn(`[zibby browser-test run-index] ${o.message}`)}}function Fn({sessionPath:i,sessionId:e,cwd:t,outputBase:r=B}={}){let s=t||process.cwd(),n=r||B,o=e!=null&&String(e).trim()!==""?String(e).trim():null,c=process.env.ZIBBY_RUN_SOURCE==="studio",l=process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim();if(c&&l)return ce(l);let a=i&&String(i).trim();if(a)return ce(a);let u=process.env.ZIBBY_SESSIONS_ROOT&&String(process.env.ZIBBY_SESSIONS_ROOT).trim();return u&&o?ce(Y(u,o)):process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim()?ce(String(process.env.ZIBBY_SESSION_PATH).trim()):ce(Y(s,n,H,o||"invalid"))}function Un(i){try{let e=i?.currentNode;if(!e||!Lt.includes(e))return;let t=i.sessionPath,r=i.sessionId||t&&String(t).split(/[/\\]/).filter(Boolean).pop()||null;if(!r)return;let s=i.cwd||process.cwd(),n=i.outputBase||B,o=Lt.indexOf(e),c=i?.specPath!=null?String(i.specPath).trim():"",l=i?.taskDescription!=null?String(i.taskDescription):"",a=null;if(c)try{let p=ce(s,c);a=Dt(s,p).split(Ge).join("/")}catch{a=c.split(Ge).join("/")}let u=Fn({sessionPath:t,sessionId:r,cwd:s,outputBase:n});ft({v:1,recordKind:"progress",ts:Date.now(),sessionId:r,cwd:s,outputBase:n,sessionPathAbs:u,activeNode:e,activeStageIndex:o,specRel:a,taskDescription:l||null,studioTestCaseId:Bt(r)||null,source:process.env.ZIBBY_RUN_SOURCE||"cli"}),dt(u,{sessionId:r,studioTestCaseId:Bt(r)||r,status:"running",activeNode:e,activeStageIndex:o,sessionPathAbs:u,cwd:s,outputBase:n,specPath:a||null,task:l||null,taskDescription:l||null,runSource:process.env.ZIBBY_RUN_SOURCE||"cli",pid:typeof process.pid=="number"?process.pid:null})}catch(e){console.warn(`[zibby browser-test run-index progress] ${e.message}`)}}function Fr({cwd:i,config:e}={}){let t=i||process.cwd(),r=e?.paths?.output||B;return s=>{Un({cwd:s?.cwd||t,outputBase:s?.outputBase||r,sessionPath:s?.sessionPath,sessionId:s?.sessionId,currentNode:s?.currentNode,specPath:s?.specPath,taskDescription:s?.taskDescription})}}function Ur(i={}){try{let e=i.cwd||process.cwd(),t=i.config?.paths?.output||i.outputBase||B,r=Pr(e,t),s=Cr(r),n=Mr(s),o=new Set,c=i.errorMessage||"Run stopped (SIGINT/SIGTERM) before a normal summary was written.",l=(p,d)=>{if(!p||!d||o.has(p))return;o.add(p);let f=Dr({cwd:e,outputBase:t,result:{state:{sessionPath:d}},success:!1,specPath:null,status:"interrupted",errorMessage:c});f&&(ft(f),dt(d,{sessionId:p,studioTestCaseId:f.studioTestCaseId||p,status:"interrupted",activeNode:null,activeStageIndex:null,errorMessage:f.errorMessage||null,runSource:f.source||"cli",cwd:e,outputBase:t,sessionPathAbs:d}))};for(let[p,d]of n){if(!kr(d))continue;let f=d.progress;if(!f)continue;let m=String(p),S=f.sessionPathAbs&&String(f.sessionPathAbs)||Y(e,t,H,m);l(m,S)}let a=Y(e,t,H);if(!ze(a))return;let u;try{u=Lr(a)}catch{return}for(let p of u){let d=Y(a,p),f;try{f=Rn(d)}catch{continue}if(!f.isDirectory())continue;let m=Mt(d);!m||m.status!=="running"||l(String(p),d)}}catch(e){console.warn(`[zibby browser-test run-index interrupt] ${e.message}`)}}function mt(i){Br(i)}function Ft(i){Ur(i)}function jr(i){return Fr(i)}import{spawn as Xo}from"node:child_process";import{mkdirSync as Ks,existsSync as Qo,writeFileSync as ei}from"node:fs";import{join as mr}from"node:path";import{existsSync as Gr,readFileSync as jn}from"node:fs";import{join as Ut,dirname as zr}from"node:path";var we=class{static async loadContext(e,t,r={}){let s={},n=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let c=zr(Ut(t,e));for(let l of n){let a=await this.findAndMergeContextFiles(l,c,t);if(a){let u=l.replace(/\.[^.]+$/,"").toLowerCase();s[u]=a}}}let o=r.discovery||{};for(let[c,l]of Object.entries(o))try{let a=Ut(t,l);if(Gr(a)){let u=await this.loadFile(a);s[c]=u}}catch(a){console.warn(`\u26A0\uFE0F Could not load context '${c}' from '${l}': ${a.message}`)}return s}static async findAndMergeContextFiles(e,t,r){let s=[],n=t;for(;n.startsWith(r);){let o=Ut(n,e);if(Gr(o))try{let l=await this.loadFile(o);s.unshift(l)}catch(l){console.warn(`\u26A0\uFE0F Could not load ${e} from ${o}: ${l.message}`)}let c=zr(n);if(c===n)break;n=c}return s.length===0?null:s.every(o=>typeof o=="string")?s.join(`
126
+ ${m}
127
+ `),g.debug(`Prompt length: ${f.length} chars`),process.env.STAGE!=="prod"&&g.debug(`Full prompt:
128
+ ${f}`),r.invoke(f,p)}var Ns,xt=B(()=>{ds();ms();gs();_s();Cs();q();fe();Ns=[new Ce,new Ee,new Ie,new Te,new $e]});var Ls={};it(Ls,{ConditionalNode:()=>Xe,Node:()=>he});import{writeFileSync as ar,readFileSync as ks,existsSync as Ms,mkdirSync as jo}from"node:fs";import{join as cr,dirname as Go}from"node:path";import Et from"chalk";var he,Xe,lr=B(()=>{Gr();q();pe();re();he=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new jr(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=p=>t&&typeof t.get=="function"?t.get(p):e?.[p];if(typeof this.customExecute=="function"){g.info("\u26A1 Using custom execute method (skipping LLM)");try{let p=await this.customExecute(e);return typeof p=="object"&&p!==null&&p.success===!1?{success:!1,error:p.error||"Node execution failed",raw:p.raw||null}:this.isZodSchema?(g.debug("Validating return value against outputSchema..."),{success:!0,output:this.outputSchema.parse(p),raw:null}):{success:!0,output:p,raw:null}}catch(p){return g.error(`\u274C Node '${this.name}' execution failed: ${p.message}`),p.name==="ZodError"&&g.error(`Schema validation errors: ${JSON.stringify(p.errors,null,2)}`),{success:!1,error:p.message,raw:null}}}let n=typeof this.prompt=="function"?this.prompt(r()):this.prompt,o=s("_skillHints");o&&(n=`${o}
131
129
 
132
- ---
133
-
134
- `):s.every(o=>typeof o=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=jn(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),s=await import(r(e).href);return s.default||s}return t}};Je();import{exec as Gn}from"node:child_process";import{promisify as zn}from"node:util";import{existsSync as Jn}from"node:fs";import{join as jt}from"node:path";import{homedir as Gt}from"node:os";var Jr=zn(Gn);async function zt(){try{return await Jr("cursor-agent --version"),"cursor-agent"}catch{let e=[jt(Gt(),".local","bin","cursor-agent"),jt(Gt(),".cursor","bin","cursor-agent"),jt(Gt(),".cursor-agent","bin","cursor-agent")];for(let t of e)if(Jn(t))try{return await Jr(`"${t}" --version`),t}catch{}return null}}async function Wn(){return await zt()!==null}function Yn(){return`
130
+ ${n}`);let c=r(),l=c.cwd||process.cwd(),a=c.sessionPath;try{if(a){let p=cr(a,Q);if(Ms(p)){let f=JSON.parse(ks(p,"utf-8"));f.currentNode=this.name,ar(p,JSON.stringify(f,null,2),"utf-8")}let d=cr(a,"..",Q);if(Ms(d))try{let f=JSON.parse(ks(d,"utf-8"));f.currentNode=this.name,ar(d,JSON.stringify(f,null,2),"utf-8")}catch{}}}catch(p){g.debug(`Could not update session info: ${p.message}`)}let u=null;for(let p=0;p<=this.retries;p++)try{g.debug(`Node.execute attempt ${p} for '${this.name}'`);let d=r(),f=d.config||{},m={state:d},S={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:a,config:f,nodeName:this.name,timeout:this.config?.timeout||3e5},h=e?._coreInvokeAgent;h||(h=(await Promise.resolve().then(()=>(xt(),ir))).invokeAgent);let _=await h(n,m,S),y,x;if(typeof _=="string"?(y=_,x=null):_.structured?(y=_.raw||JSON.stringify(_.structured,null,2),x=_.structured):(y=_.raw||JSON.stringify(_,null,2),x=_.extracted||null),a)try{let E=cr(a,this.name,"raw_stream_output.txt");jo(Go(E),{recursive:!0}),ar(E,typeof y=="string"?y:JSON.stringify(y),"utf-8")}catch(E){g.debug(`Could not save raw output: ${E.message}`)}if(this.isZodSchema&&x){console.log(`
131
+ \u{1F50D} ${Et.cyan("Validated output:")} ${Et.white(JSON.stringify(x,null,2))}`);let E=x;if(typeof this.onComplete=="function")try{E=await this.onComplete(r(),x)}catch(T){g.warn(`onComplete hook failed: ${T.message}`)}return{success:!0,output:E,raw:y}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:y}),raw:y}}catch(E){throw new Error(`onComplete failed: ${E.message}`,{cause:E})}if(this.parser){let E=this.parser.parse(y);return console.log(`
132
+ \u{1F50D} ${Et.cyan("Parsed output:")} ${Et.white(JSON.stringify(E,null,2))}`),F.step("Output parsed"),{success:!0,output:E,raw:y}}return{success:!0,output:y,raw:y}}catch(d){u=d,p<this.retries&&g.info(`Node '${this.name}' failed, retrying (${p+1}/${this.retries})...`)}return{success:!1,error:u.message,raw:null}}},Xe=class extends he{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,t){let r=t&&typeof t.getAll=="function"?t.getAll():e;return{success:!0,output:{nextNode:this.condition(r)},raw:null}}}});re();import{readFileSync as un,existsSync as pn}from"node:fs";import{join as Fe,resolve as fn,isAbsolute as oa}from"node:path";import{existsSync as ze,readdirSync as Rr,statSync as On}from"fs";import{join as K,relative as Mt,sep as Ge,resolve as ue}from"path";re();import{appendFileSync as _n,readFileSync as bn,existsSync as Tr,mkdirSync as xn}from"node:fs";import{join as ct}from"node:path";var $r="run-index.jsonl";function vr(i,e=j){let t=ct(i,e);return ct(t,$r)}function lt(i){if(!i||!i.sessionId)return;let e=i.cwd||process.cwd(),t=i.outputBase||j,r=ct(e,t);Tr(r)||xn(r,{recursive:!0});let s=ct(r,$r),n=`${JSON.stringify(i)}
133
+ `;_n(s,n,"utf8")}function Ar(i){if(!i||!Tr(i))return[];let e;try{e=bn(i,"utf8")}catch{return[]}let t=[];for(let r of e.split(`
134
+ `)){let s=r.trim();if(s)try{t.push(JSON.parse(s))}catch{}}return t}import{existsSync as En,mkdirSync as In,readFileSync as Tn,readdirSync as ya,statSync as Sa,writeFileSync as $n}from"node:fs";import{join as vn}from"node:path";var An="zibby-run-state.json";function Pr(i){return vn(i,An)}function Rt(i){if(!i||typeof i!="string")return null;let e=Pr(i);if(!En(e))return null;try{let t=Tn(e,"utf8"),r=JSON.parse(t);return r&&typeof r=="object"?r:null}catch{return null}}function ut(i,e){if(!i||typeof i!="string")return;try{In(i,{recursive:!0})}catch{return}let r={...Rt(i)||{v:1},...e,v:1,updatedAt:Date.now()};try{$n(Pr(i),`${JSON.stringify(r)}
135
+ `,"utf8")}catch(s){console.warn(`[zibby run-state] ${s.message}`)}}function Pn(i){return i?.recordKind==="progress"}function Or(i){let e=Number(i)||0;return e<=0?0:e<1e12?e*1e3:e}function Cr(i,e={}){let t=e.maxProgressAgeMs!=null&&Number.isFinite(e.maxProgressAgeMs)?Math.max(0,e.maxProgressAgeMs):21e5,r=typeof e.now=="number"?e.now:Date.now(),{summary:s,progress:n}=i||{};if(!n)return!1;let o=Or(n.ts);if(t>0&&o>0&&r-o>t)return!1;if(!s)return o>0;let c=Or(s.ts);return o>c}function Nr(i){let e=new Map;for(let t of i||[]){if(!t?.sessionId)continue;let r=e.get(t.sessionId);r||(r={summary:null,progress:null});let s=Number(t.ts)||0;Pn(t)?(!r.progress||s>=(Number(r.progress.ts)||0))&&(r.progress=t):(!r.summary||s>=(Number(r.summary.ts)||0))&&(r.summary=t),e.set(t.sessionId,r)}return e}re();var kt=Object.freeze(["preflight","execute_live","generate_script"]);function Lt(i){let e=process.env.ZIBBY_STUDIO_TEST_CASE_ID;return e!=null&&String(e).trim()!==""?String(e).trim():i!=null?String(i):""}var Cn=[K("generate_script","generated-test.spec.js"),K("generate_script","generated-test.spec.ts"),K("generate_script","playwright.spec.ts"),K("generate_script","test.spec.ts")];function Nn(i){let e=[K(i,"execute_live","videos"),K(i,"execute_live"),i];for(let t of e){if(!ze(t))continue;let r;try{r=Rr(t)}catch{continue}let s=r.find(n=>n.endsWith(".webm"));if(s)return K(t,s)}return null}function Rn(i){let e=[K(i,"execute_live","events.json"),K(i,"events.json")];for(let t of e)if(ze(t))return t;return null}function kn(i){for(let e of Cn){let t=K(i,e);if(ze(t))return t}return null}function Mn(i){return!i||!ze(i)?{videoPathAbs:null,eventsPathAbs:null,scriptPathAbs:null}:{videoPathAbs:Nn(i),eventsPathAbs:Rn(i),scriptPathAbs:kn(i)}}function kr(i){let e=i.cwd||process.cwd(),t=i.outputBase||j,n=((i.result||{}).state||{}).sessionPath;if(!n||typeof n!="string")return null;let o=n.split(/[/\\]/).filter(Boolean).pop();if(!o)return null;let{videoPathAbs:c,eventsPathAbs:l,scriptPathAbs:a}=Mn(n),u=d=>{if(!d)return null;try{return Mt(e,d).split(Ge).join("/")}catch{return null}},p=null;if(i.specPath)try{let d=ue(e,i.specPath);p=Mt(e,d).split(Ge).join("/")}catch{p=String(i.specPath).split(Ge).join("/")}return{v:1,recordKind:"summary",ts:Date.now(),sessionId:o,status:i.status??(i.success?"completed":"failed"),cwd:e,outputBase:t,sessionPathAbs:n,sessionDirRel:u(n),videoPathAbs:c||null,eventsPathAbs:l||null,scriptPathAbs:a||null,videoRel:u(c),eventsRel:u(l),scriptRel:u(a),specRel:p,source:process.env.ZIBBY_RUN_SOURCE||"cli",studioTestCaseId:Lt(o)||null,errorMessage:i.errorMessage||null}}function Mr({cwd:i,config:e,result:t,success:r,specPath:s,errorMessage:n}){try{let o=kr({cwd:i||process.cwd(),result:t,success:r,outputBase:e?.paths?.output||j,specPath:s,errorMessage:n});o&&(lt(o),o.sessionPathAbs&&ut(o.sessionPathAbs,{sessionId:o.sessionId,studioTestCaseId:o.studioTestCaseId||o.sessionId,status:o.status,activeNode:null,activeStageIndex:null,errorMessage:o.errorMessage||null,runSource:o.source||"cli",cwd:o.cwd,outputBase:o.outputBase,sessionPathAbs:o.sessionPathAbs}))}catch(o){console.warn(`[zibby browser-test run-index] ${o.message}`)}}function Ln({sessionPath:i,sessionId:e,cwd:t,outputBase:r=j}={}){let s=t||process.cwd(),n=r||j,o=e!=null&&String(e).trim()!==""?String(e).trim():null,c=process.env.ZIBBY_RUN_SOURCE==="studio",l=process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim();if(c&&l)return ue(l);let a=i&&String(i).trim();if(a)return ue(a);let u=process.env.ZIBBY_SESSIONS_ROOT&&String(process.env.ZIBBY_SESSIONS_ROOT).trim();return u&&o?ue(K(u,o)):process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim()?ue(String(process.env.ZIBBY_SESSION_PATH).trim()):ue(K(s,n,X,o||"invalid"))}function Dn(i){try{let e=i?.currentNode;if(!e||!kt.includes(e))return;let t=i.sessionPath,r=i.sessionId||t&&String(t).split(/[/\\]/).filter(Boolean).pop()||null;if(!r)return;let s=i.cwd||process.cwd(),n=i.outputBase||j,o=kt.indexOf(e),c=i?.specPath!=null?String(i.specPath).trim():"",l=i?.taskDescription!=null?String(i.taskDescription):"",a=null;if(c)try{let p=ue(s,c);a=Mt(s,p).split(Ge).join("/")}catch{a=c.split(Ge).join("/")}let u=Ln({sessionPath:t,sessionId:r,cwd:s,outputBase:n});lt({v:1,recordKind:"progress",ts:Date.now(),sessionId:r,cwd:s,outputBase:n,sessionPathAbs:u,activeNode:e,activeStageIndex:o,specRel:a,taskDescription:l||null,studioTestCaseId:Lt(r)||null,source:process.env.ZIBBY_RUN_SOURCE||"cli"}),ut(u,{sessionId:r,studioTestCaseId:Lt(r)||r,status:"running",activeNode:e,activeStageIndex:o,sessionPathAbs:u,cwd:s,outputBase:n,specPath:a||null,task:l||null,taskDescription:l||null,runSource:process.env.ZIBBY_RUN_SOURCE||"cli",pid:typeof process.pid=="number"?process.pid:null})}catch(e){console.warn(`[zibby browser-test run-index progress] ${e.message}`)}}function Lr({cwd:i,config:e}={}){let t=i||process.cwd(),r=e?.paths?.output||j;return s=>{Dn({cwd:s?.cwd||t,outputBase:s?.outputBase||r,sessionPath:s?.sessionPath,sessionId:s?.sessionId,currentNode:s?.currentNode,specPath:s?.specPath,taskDescription:s?.taskDescription})}}function Dr(i={}){try{let e=i.cwd||process.cwd(),t=i.config?.paths?.output||i.outputBase||j,r=vr(e,t),s=Ar(r),n=Nr(s),o=new Set,c=i.errorMessage||"Run stopped (SIGINT/SIGTERM) before a normal summary was written.",l=(p,d)=>{if(!p||!d||o.has(p))return;o.add(p);let f=kr({cwd:e,outputBase:t,result:{state:{sessionPath:d}},success:!1,specPath:null,status:"interrupted",errorMessage:c});f&&(lt(f),ut(d,{sessionId:p,studioTestCaseId:f.studioTestCaseId||p,status:"interrupted",activeNode:null,activeStageIndex:null,errorMessage:f.errorMessage||null,runSource:f.source||"cli",cwd:e,outputBase:t,sessionPathAbs:d}))};for(let[p,d]of n){if(!Cr(d))continue;let f=d.progress;if(!f)continue;let m=String(p),S=f.sessionPathAbs&&String(f.sessionPathAbs)||K(e,t,X,m);l(m,S)}let a=K(e,t,X);if(!ze(a))return;let u;try{u=Rr(a)}catch{return}for(let p of u){let d=K(a,p),f;try{f=On(d)}catch{continue}if(!f.isDirectory())continue;let m=Rt(d);!m||m.status!=="running"||l(String(p),d)}}catch(e){console.warn(`[zibby browser-test run-index interrupt] ${e.message}`)}}function pt(i){Mr(i)}function Dt(i){Dr(i)}function Br(i){return Lr(i)}import{spawn as Ko}from"node:child_process";import{mkdirSync as Js,existsSync as Zo,writeFileSync as Ho}from"node:fs";import{join as pr}from"node:path";import{ContextLoader as ft}from"@zibby/workflow";Je();import{exec as Bn}from"node:child_process";import{promisify as Un}from"node:util";import{existsSync as Fn}from"node:fs";import{join as Bt}from"node:path";import{homedir as Ut}from"node:os";var Ur=Un(Bn);async function Ft(){try{return await Ur("cursor-agent --version"),"cursor-agent"}catch{let e=[Bt(Ut(),".local","bin","cursor-agent"),Bt(Ut(),".cursor","bin","cursor-agent"),Bt(Ut(),".cursor-agent","bin","cursor-agent")];for(let t of e)if(Fn(t))try{return await Ur(`"${t}" --version`),t}catch{}return null}}async function jn(){return await Ft()!==null}function Gn(){return`
135
136
  \u274C cursor-agent CLI not found!
136
137
 
137
138
  To use the Cursor agent, install it from:
@@ -148,11 +149,11 @@ After installation:
148
149
  2. Or restart your terminal/shell
149
150
 
150
151
  Then retry your command.
151
- `}ee();Wt();fr();ee();le();import{mkdirSync as Gs,existsSync as dr,writeFileSync as Us,unlinkSync as Zo}from"node:fs";import{join as he,resolve as zs}from"node:path";import{config as Ho}from"dotenv";import{zodToJsonSchema as js}from"zod-to-json-schema";import Vo from"handlebars";function qo({traceFrom:i,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:s}){if(process.env.ZIBBY_SESSION_LOG==="0"||process.env.ZIBBY_SESSION_LOG==="false")return;let n=typeof process.ppid=="number"?process.ppid:"n/a",o=`[zibby:session] from=${i} pid=${process.pid} ppid=${n} sessionId=${e} source=${r} mkdir=${s?"yes":"no"} path=${t}`;if(console.log(o),(process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true")&&process.env.ZIBBY_SESSION_LOG!=="0"&&process.env.ZIBBY_SESSION_LOG!=="false"){let a=(new Error("session trace").stack||"").split(`
152
+ `}re();Gt();lr();re();pe();import{mkdirSync as Us,existsSync as ur,writeFileSync as Ds,unlinkSync as zo}from"node:fs";import{join as ye,resolve as Fs}from"node:path";import{config as Jo}from"dotenv";import{zodToJsonSchema as Bs}from"zod-to-json-schema";import Yo from"handlebars";function Wo({traceFrom:i,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:s}){if(process.env.ZIBBY_SESSION_LOG==="0"||process.env.ZIBBY_SESSION_LOG==="false")return;let n=typeof process.ppid=="number"?process.ppid:"n/a",o=`[zibby:session] from=${i} pid=${process.pid} ppid=${n} sessionId=${e} source=${r} mkdir=${s?"yes":"no"} path=${t}`;if(console.log(o),(process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true")&&process.env.ZIBBY_SESSION_LOG!=="0"&&process.env.ZIBBY_SESSION_LOG!=="false"){let a=(new Error("session trace").stack||"").split(`
152
153
  `).slice(2,14).join(`
153
154
  `);console.log(`[zibby:session] stack (${i}):
154
- ${a}`)}}function Js(){return process.env.ZIBBY_RUN_SOURCE==="studio"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function $t(){if(process.env.ZIBBY_RUN_SOURCE!=="studio")return;let i=process.env.ZIBBY_SESSION_PATH;if(!(i==null||String(i).trim()===""))try{return zs(String(i).trim())}catch{return String(i).trim()}}function It(){Js()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Ws({sessionPath:i,sessionId:e}){i&&typeof i=="string"&&(process.env.ZIBBY_SESSION_PATH=i),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Ys(i={}){let e=kt.map(n=>process.env[n]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,s=i.paths?.sessionPrefix;return s?`${s}_${r}`:r}function At({cwd:i=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let s=t.sessionPath,n=t.sessionTimestamp,o="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let a=zs(String(process.env.ZIBBY_SESSION_PATH));a&&(s=a,o="ZIBBY_SESSION_PATH")}catch{}let c;if(s)c=String(s).split(/[/\\]/).filter(Boolean).pop(),n==null&&(n=Date.now());else{let a=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(a)c=a,o="ZIBBY_SESSION_ID";else{let p=e.sessionId!=null?String(e.sessionId).trim():"";p&&p!=="last"?(c=p,o="config.sessionId"):(c=Ys(e),o="generated")}n=n??Date.now();let u=e.paths?.output||B;s=he(i,u,H,c)}let l=!dr(s);return l&&Gs(s,{recursive:!0}),qo({traceFrom:r,sessionId:c,sessionPath:s,idSource:o,mkdirFresh:l}),Ws({sessionPath:s,sessionId:c}),{sessionPath:s,sessionId:c,sessionTimestamp:n}}var et=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null}setStateSchema(e){return this.stateSchema=e,this}getStateSchema(){return this.stateSchema}addNode(e,t,r={}){let s=t instanceof me?t:new me(t);return s.name=e,this.nodes.set(e,s),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addConditionalNode(e,t){let r=new Qe({...t,name:e});return this.nodes.set(e,r),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:r}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,s,n){let o=r;for(let c=e.length-1;c>=0;c--){let l=e[c],a=o;o=()=>l(t,a,s,n)}return o()}serialize(){let e=[],t={};for(let[n,o]of this.nodes){let c=this.nodeTypeMap.get(n)||n;e.push({id:n,type:c,data:{nodeType:c,label:n}});let l=o._isCustomCode||!1,a={};l&&typeof o.execute=="function"&&(a.customCode=o.execute.toString());let u=this.nodePrompts.get(n);if(u&&(a.prompt=u),typeof o.customExecute=="function"&&(a.executeCode=o.customExecute.toString()),o.outputSchema)try{if(typeof o.outputSchema._def<"u"){let f=js(o.outputSchema,{target:"openApi3"}),m=this._flattenJsonSchemaToVariables(f);a.outputSchema={jsonSchema:f,variables:m}}else a.outputSchema={schema:o.outputSchema}}catch(d){console.warn(`Failed to convert schema for ${n}:`,d.message)}let p=(this.resolvedToolsMap||{})[n];p?.toolIds&&(a.tools=p.toolIds),Object.keys(a).length>0&&(t[n]=a)}let r=[];for(let[n,o]of this.edges)if(typeof o=="string")r.push({source:n,target:o});else if(o.conditional){let c=this.conditionalCodeMap.get(n)||o.routes.toString(),l=this._inferConditionalTargets(o.routes),a=o.labels||{};for(let u of l){let p={source:n,target:u,data:{conditionalCode:c}};a[u]&&(p.label=a[u]),r.push(p)}}let s=null;if(this.stateSchema)try{s=js(this.stateSchema,{target:"openApi3"})}catch{s=this.stateSchema}return{nodes:e,edges:r,nodeConfigs:t,stateSchema:s}}_inferConditionalTargets(e){let t=e.toString(),r=new Set,s=/return\s+['"]([^'"]+)['"]/g,n;for(;(n=s.exec(t))!==null;)r.add(n[1]);return[...r]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");r=e.definitions[s]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],s=e.properties||{},n=e.required||[];for(let[o,c]of Object.entries(s)){let l=t?`${t}.${o}`:o,a=!n.includes(o);if(r.push({path:l,type:c.type||"unknown",label:c.description||this._formatLabel(o),optional:a}),c.type==="object"&&c.properties){let u=this._flattenSchema(c,l);r.push(...u)}if(c.type==="array"&&c.items?.type==="object"&&c.items.properties){let u=this._flattenSchema(c.items,`${l}[]`);r.push(...u)}}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,n]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof n=="string"&&n.length<=80)r.push(`${s}: ${n}`);else if(Array.isArray(n)){let o=n.length,c=n.filter(a=>a?.passed===!0).length;if(n.some(a=>a?.passed!==void 0)){let a=o-c;r.push(`${s}: ${c}/${o} passed${a?`, ${a} failed`:""}`)}else r.push(`${s}: ${o} items`)}if(r.length>=4)break}return r}async run(e,t={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let r=t.cwd||process.cwd();Ho({path:he(r,".env")});let s=t.config||{};if(!s||Object.keys(s).length===0)try{let v=he(r,".zibby.config.js");dr(v)&&(s=(await import(v)).default||{})}catch{}process.env.EXECUTION_ID&&!s.agent?.strictMode&&(s.agent={...s.agent,strictMode:!0});let n=t.agentType;if(!n){let v=s?.agent;v?.provider?n=v.provider:v?.gemini?n="gemini":v?.claude?n="claude":v?.cursor?n="cursor":v?.codex?n="codex":n=process.env.AGENT_TYPE||"cursor"}let o=t.contextConfig||e?.config?.contextConfig||e?.config?.context||s?.context||{};if(this.stateSchema){let v=this.stateSchema.safeParse(t);if(!v.success){let $=v.error.issues.map(T=>`${T.path.join(".")}: ${T.message}`);throw console.error("\u274C Initial state validation failed:"),$.forEach(T=>console.error(` - ${T}`)),new Error(`State validation failed: ${$.join(", ")}`)}D.step("State validated against schema")}let c=$t(),l=t.sessionPath||c;l||It();let{sessionPath:a,sessionTimestamp:u,sessionId:p}=At({cwd:r,config:s,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:t.sessionTimestamp}});D.step(`Session ${p}`);let d=await we.loadContext(t.specPath||"",r,o);Object.keys(d).length>0&&D.step(`Context loaded: ${Object.keys(d).join(", ")}`);let f=t.outputPath;!f&&t.specPath&&(e?.calculateOutputPath?f=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let m=new We({...t,config:s,agentType:n,outputPath:f,sessionPath:a,sessionTimestamp:u,context:d,resolvedTools:this.resolvedToolsMap||{}}),S=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:g}=await Promise.resolve().then(()=>(se(),qt)),w=new Set;for(let[,v]of this.nodes)for(let $ of v.config?.skills||[])w.add($);for(let v of w){let $=g(v);if(typeof $?.middleware=="function")try{let T=await $.middleware();typeof T=="function"&&S.set(v,T)}catch{}}let y=this.entryPoint,E=[];for(;y&&y!=="END";){let v=he(a,ut);if(dr(v)){console.warn(`
155
- \u{1F6D1} Studio stop requested \u2014 ending workflow.`);try{Zo(v)}catch{}if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch{}return D.step("Workflow stopped by Studio"),{success:!0,state:m.getAll(),executionLog:E,stoppedByStudio:!0}}let $=this.nodes.get(y);if(!$)throw new Error(`Node '${y}' not found in graph`);let T=JSON.stringify({sessionPath:a,sessionTimestamp:u,currentNode:y,createdAt:new Date().toISOString(),config:m.get("config")}),I=he(a,q);Us(I,T,"utf-8");let P=m.get("config")?.paths?.output||B,N=he(r,P,q);Gs(he(r,P),{recursive:!0});try{Us(N,T,"utf-8")}catch{}let b=t.onPipelineProgress;if(typeof b=="function")try{b({cwd:r,sessionPath:a,sessionId:p,outputBase:m.get("config")?.paths?.output||B,currentNode:y})}catch{}let A=(this.resolvedToolsMap||{})[y]||null;m.set("_currentNodeTools",A);let O=m.get("nodeConfigs")||{};m.set("_currentNodeConfig",O[y]||{}),D.nodeStart(y);let _=Date.now(),C=this.nodePrompts.get(y);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(Tt(),lr));this._invokeAgent=k.invokeAgent}let R=this._invokeAgent,U={state:m,invokeAgent:async(k={},W={})=>{let F=W.prompt||"";if(C)try{F=Vo.compile(C,{noEscape:!0})(k)}catch(re){throw console.error(`\u274C Template rendering failed for node '${y}':`,re.message),new Error(`Template rendering failed: ${re.message}`,{cause:re})}else if(!F)throw new Error(`No prompt template configured for node '${y}' and no prompt provided in options`);let Z={state:m.getAll(),images:W.images||[]},Ue={model:W.model||m.get("model"),workspace:m.get("workspace"),schema:W.schema,...W};return R(F,Z,Ue)},_coreInvokeAgent:R,agent:e,nodeId:y,promptTemplate:C,getPromptTemplate:()=>C,...m.getAll()};try{let k=($.config?.skills||[]).map(at=>S.get(at)).filter(Boolean),W=[...this.middleware,...k],F;W.length>0?F=await this._composeMiddleware(W,y,async()=>$.execute(U,m),m.getAll(),m):F=await $.execute(U,m);let Z=Date.now()-_;if(E.push({node:y,success:F.success,duration:Z,timestamp:new Date().toISOString()}),!F.success){if(String(F.error||"").includes("Stopped from Zibby Studio")){if(D.step("Workflow stopped by Studio"),m.set("stoppedByStudio",!0),e&&typeof e.cleanup=="function")try{await e.cleanup()}catch{}return{success:!0,state:m.getAll(),executionLog:E,stoppedByStudio:!0}}m.append("errors",{node:y,error:F.error});let je=$.config?.retries||0,Ir=`${y}_retries`,ct=m.getAll()[Ir]||0;if(ct<je){D.stepInfo(`Retrying (attempt ${ct+1}/${je})`),m.update({[Ir]:ct+1,[`${y}_raw`]:F.raw});continue}throw D.nodeFailed(y,F.error,{duration:Z}),new Error(`Node '${y}' failed after ${ct} attempts: ${F.error}`)}m.update({[y]:F.output});let Ue=this._summarizeNodeOutput(y,F.output);D.nodeComplete(y,{duration:Z,details:Ue});let re=this.edges.get(y);if(!re)y="END";else if(re.conditional){let at=m.getAll(),je=re.routes(at);D.route(y,je),y=je}else y=re}catch(k){throw D.isInsideNode&&D.nodeFailed(y,k.message,{duration:Date.now()-_}),m.set("failed",!0),m.set("failedAt",y),k}}D.graphComplete();let x={success:!0,state:m.getAll(),executionLog:E};return e&&typeof e.onComplete=="function"&&await e.onComplete(x),x}};var Ce=class i{constructor(e={}){this.config=e,this.adapter=null,this.paths=e.paths||{specs:"test-specs",generated:"tests"},this.agentCommand=e.agentCommand||"cursor-agent",this.buildArgs=e.buildArgs||((t,r=!0)=>{let s=["-p",t,"--approve-mcps","--force"];return r&&(s.push("--output-format","stream-json"),s.push("--stream-partial-output")),s})}static extractJsonFromStream(e){return te.extractResult(e)}async initialize(e){this.adapter=e,e&&!e.isConnected()&&await e.connect()}buildGraph(){throw new Error("buildGraph() must be implemented by subclass")}async onComplete(e){}async run(e,t={}){let r=this.buildGraph(),s=typeof e=="object"&&!Array.isArray(e)?{input:e,...e,...t}:{input:e,...t};return await r.run(this,s)}async executeNode(e,t){let{prompt:r,outputSchema:s,model:n}=e,o=typeof r=="function"?r(t):r;console.log(`
155
+ ${a}`)}}function js(){return process.env.ZIBBY_RUN_SOURCE==="studio"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function It(){if(process.env.ZIBBY_RUN_SOURCE!=="studio")return;let i=process.env.ZIBBY_SESSION_PATH;if(!(i==null||String(i).trim()===""))try{return Fs(String(i).trim())}catch{return String(i).trim()}}function Tt(){js()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Gs({sessionPath:i,sessionId:e}){i&&typeof i=="string"&&(process.env.ZIBBY_SESSION_PATH=i),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function zs(i={}){let e=Nt.map(n=>process.env[n]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,s=i.paths?.sessionPrefix;return s?`${s}_${r}`:r}function $t({cwd:i=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let s=t.sessionPath,n=t.sessionTimestamp,o="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let a=Fs(String(process.env.ZIBBY_SESSION_PATH));a&&(s=a,o="ZIBBY_SESSION_PATH")}catch{}let c;if(s)c=String(s).split(/[/\\]/).filter(Boolean).pop(),n==null&&(n=Date.now());else{let a=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(a)c=a,o="ZIBBY_SESSION_ID";else{let p=e.sessionId!=null?String(e.sessionId).trim():"";p&&p!=="last"?(c=p,o="config.sessionId"):(c=zs(e),o="generated")}n=n??Date.now();let u=e.paths?.output||j;s=ye(i,u,X,c)}let l=!ur(s);return l&&Us(s,{recursive:!0}),(l||o!=="initialState.sessionPath")&&Wo({traceFrom:r,sessionId:c,sessionPath:s,idSource:o,mkdirFresh:l}),Gs({sessionPath:s,sessionId:c}),{sessionPath:s,sessionId:c,sessionTimestamp:n}}var qe=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null}setStateSchema(e){return this.stateSchema=e,this}getStateSchema(){return this.stateSchema}addNode(e,t,r={}){let s=t instanceof he?t:new he(t);return s.name=e,this.nodes.set(e,s),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addConditionalNode(e,t){let r=new Xe({...t,name:e});return this.nodes.set(e,r),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:r}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,s,n){let o=r;for(let c=e.length-1;c>=0;c--){let l=e[c],a=o;o=()=>l(t,a,s,n)}return o()}serialize(){let e=[],t={};for(let[n,o]of this.nodes){let c=this.nodeTypeMap.get(n)||n;e.push({id:n,type:c,data:{nodeType:c,label:n}});let l=o._isCustomCode||!1,a={};l&&typeof o.execute=="function"&&(a.customCode=o.execute.toString());let u=this.nodePrompts.get(n);if(u&&(a.prompt=u),typeof o.customExecute=="function"&&(a.executeCode=o.customExecute.toString()),o.outputSchema)try{if(typeof o.outputSchema._def<"u"){let f=Bs(o.outputSchema,{target:"openApi3"}),m=this._flattenJsonSchemaToVariables(f);a.outputSchema={jsonSchema:f,variables:m}}else a.outputSchema={schema:o.outputSchema}}catch(d){console.warn(`Failed to convert schema for ${n}:`,d.message)}let p=(this.resolvedToolsMap||{})[n];p?.toolIds&&(a.tools=p.toolIds),Object.keys(a).length>0&&(t[n]=a)}let r=[];for(let[n,o]of this.edges)if(typeof o=="string")r.push({source:n,target:o});else if(o.conditional){let c=this.conditionalCodeMap.get(n)||o.routes.toString(),l=this._inferConditionalTargets(o.routes),a=o.labels||{};for(let u of l){let p={source:n,target:u,data:{conditionalCode:c}};a[u]&&(p.label=a[u]),r.push(p)}}let s=null;if(this.stateSchema)try{s=Bs(this.stateSchema,{target:"openApi3"})}catch{s=this.stateSchema}return{nodes:e,edges:r,nodeConfigs:t,stateSchema:s}}_inferConditionalTargets(e){let t=e.toString(),r=new Set,s=/return\s+['"]([^'"]+)['"]/g,n;for(;(n=s.exec(t))!==null;)r.add(n[1]);return[...r]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");r=e.definitions[s]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],s=e.properties||{},n=e.required||[];for(let[o,c]of Object.entries(s)){let l=t?`${t}.${o}`:o,a=!n.includes(o);if(r.push({path:l,type:c.type||"unknown",label:c.description||this._formatLabel(o),optional:a}),c.type==="object"&&c.properties){let u=this._flattenSchema(c,l);r.push(...u)}if(c.type==="array"&&c.items?.type==="object"&&c.items.properties){let u=this._flattenSchema(c.items,`${l}[]`);r.push(...u)}}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,n]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof n=="string"&&n.length<=80)r.push(`${s}: ${n}`);else if(Array.isArray(n)){let o=n.length,c=n.filter(a=>a?.passed===!0).length;if(n.some(a=>a?.passed!==void 0)){let a=o-c;r.push(`${s}: ${c}/${o} passed${a?`, ${a} failed`:""}`)}else r.push(`${s}: ${o} items`)}if(r.length>=4)break}return r}async run(e,t={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let r=t.cwd||process.cwd();Jo({path:ye(r,".env")});let s=t.config||{};if(!s||Object.keys(s).length===0)try{let T=ye(r,".zibby.config.js");ur(T)&&(s=(await import(T)).default||{})}catch{}process.env.EXECUTION_ID&&!s.agent?.strictMode&&(s.agent={...s.agent,strictMode:!0});let n=t.agentType;if(!n){let T=s?.agent;T?.provider?n=T.provider:T?.gemini?n="gemini":T?.claude?n="claude":T?.cursor?n="cursor":T?.codex?n="codex":n=process.env.AGENT_TYPE||"cursor"}let o=t.contextConfig||e?.config?.contextConfig||e?.config?.context||s?.context||{};if(this.stateSchema){let T=this.stateSchema.safeParse(t);if(!T.success){let v=T.error.issues.map(I=>`${I.path.join(".")}: ${I.message}`);throw console.error("\u274C Initial state validation failed:"),v.forEach(I=>console.error(` - ${I}`)),new Error(`State validation failed: ${v.join(", ")}`)}F.step("State validated against schema")}let c=It(),l=t.sessionPath||c;l||Tt();let{sessionPath:a,sessionTimestamp:u,sessionId:p}=$t({cwd:r,config:s,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:t.sessionTimestamp}});F.step(`Session ${p}`);let d=await ft.loadContext(t.specPath||"",r,o);Object.keys(d).length>0&&F.step(`Context loaded: ${Object.keys(d).join(", ")}`);let f=t.outputPath;!f&&t.specPath&&(e?.calculateOutputPath?f=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let m=new jt({...t,config:s,agentType:n,outputPath:f,sessionPath:a,sessionTimestamp:u,context:d,resolvedTools:this.resolvedToolsMap||{}}),S=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:h}=await Promise.resolve().then(()=>(ne(),Zt)),_=new Set;for(let[,T]of this.nodes)for(let v of T.config?.skills||[])_.add(v);for(let T of _){let v=h(T);if(typeof v?.middleware=="function")try{let I=await v.middleware();typeof I=="function"&&S.set(T,I)}catch{}}let y=this.entryPoint,x=[];for(;y&&y!=="END";){let T=ye(a,at);if(ur(T)){console.warn(`
156
+ \u{1F6D1} Studio stop requested \u2014 ending workflow.`);try{zo(T)}catch{}if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch{}return F.step("Workflow stopped by Studio"),{success:!0,state:m.getAll(),executionLog:x,stoppedByStudio:!0}}let v=this.nodes.get(y);if(!v)throw new Error(`Node '${y}' not found in graph`);let I=JSON.stringify({sessionPath:a,sessionTimestamp:u,currentNode:y,createdAt:new Date().toISOString(),config:m.get("config")}),A=ye(a,Q);Ds(A,I,"utf-8");let P=m.get("config")?.paths?.output||j,k=ye(r,P,Q);Us(ye(r,P),{recursive:!0});try{Ds(k,I,"utf-8")}catch{}let b=t.onPipelineProgress;if(typeof b=="function")try{b({cwd:r,sessionPath:a,sessionId:p,outputBase:m.get("config")?.paths?.output||j,currentNode:y})}catch{}let C=(this.resolvedToolsMap||{})[y]||null;m.set("_currentNodeTools",C);let O=m.get("nodeConfigs")||{};m.set("_currentNodeConfig",O[y]||{}),F.nodeStart(y);let w=Date.now(),$=this.nodePrompts.get(y);if(!this._invokeAgent){let M=await Promise.resolve().then(()=>(xt(),ir));this._invokeAgent=M.invokeAgent}let N=this._invokeAgent,R={state:m,invokeAgent:async(M={},L={})=>{let D=L.prompt||"";if($)try{D=Yo.compile($,{noEscape:!0})(M)}catch(V){throw console.error(`\u274C Template rendering failed for node '${y}':`,V.message),new Error(`Template rendering failed: ${V.message}`,{cause:V})}else if(!D)throw new Error(`No prompt template configured for node '${y}' and no prompt provided in options`);let z={state:m.getAll(),images:L.images||[]},ie={model:L.model||m.get("model"),workspace:m.get("workspace"),schema:L.schema,...L};return N(D,z,ie)},_coreInvokeAgent:N,agent:e,nodeId:y,promptTemplate:$,getPromptTemplate:()=>$,...m.getAll()};try{let M=(v.config?.skills||[]).map(H=>S.get(H)).filter(Boolean),L=[...this.middleware,...M],D;L.length>0?D=await this._composeMiddleware(L,y,async()=>v.execute(R,m),m.getAll(),m):D=await v.execute(R,m);let z=Date.now()-w;if(x.push({node:y,success:D.success,duration:z,timestamp:new Date().toISOString()}),!D.success){if(String(D.error||"").includes("Stopped from Zibby Studio")){if(F.step("Workflow stopped by Studio"),m.set("stoppedByStudio",!0),e&&typeof e.cleanup=="function")try{await e.cleanup()}catch{}return{success:!0,state:m.getAll(),executionLog:x,stoppedByStudio:!0}}m.append("errors",{node:y,error:D.error});let je=v.config?.retries||0,Ir=`${y}_retries`,ot=m.getAll()[Ir]||0;if(ot<je){F.stepInfo(`Retrying (attempt ${ot+1}/${je})`),m.update({[Ir]:ot+1,[`${y}_raw`]:D.raw});continue}throw F.nodeFailed(y,D.error,{duration:z}),new Error(`Node '${y}' failed after ${ot} attempts: ${D.error}`)}m.update({[y]:D.output});let ie=this._summarizeNodeOutput(y,D.output);F.nodeComplete(y,{duration:z,details:ie});let V=this.edges.get(y);if(!V)y="END";else if(V.conditional){let H=m.getAll(),je=V.routes(H);F.route(y,je),y=je}else y=V}catch(M){throw F.isInsideNode&&F.nodeFailed(y,M.message,{duration:Date.now()-w}),m.set("failed",!0),m.set("failedAt",y),M}}F.graphComplete();let E={success:!0,state:m.getAll(),executionLog:x};return e&&typeof e.onComplete=="function"&&await e.onComplete(E),E}};var Ne=class i{constructor(e={}){this.config=e,this.adapter=null,this.paths=e.paths||{specs:"test-specs",generated:"tests"},this.agentCommand=e.agentCommand||"cursor-agent",this.buildArgs=e.buildArgs||((t,r=!0)=>{let s=["-p",t,"--approve-mcps","--force"];return r&&(s.push("--output-format","stream-json"),s.push("--stream-partial-output")),s})}static extractJsonFromStream(e){return se.extractResult(e)}async initialize(e){this.adapter=e,e&&!e.isConnected()&&await e.connect()}buildGraph(){throw new Error("buildGraph() must be implemented by subclass")}async onComplete(e){}async run(e,t={}){let r=this.buildGraph(),s=typeof e=="object"&&!Array.isArray(e)?{input:e,...e,...t}:{input:e,...t};return await r.run(this,s)}async executeNode(e,t){let{prompt:r,outputSchema:s,model:n}=e,o=typeof r=="function"?r(t):r;console.log(`
156
157
  \u{1F4DD} Prompt:
157
158
  ${o}
158
159
  `);let c=await this.executePrompt(o,t.cwd,3e5,n);console.log(`
@@ -161,20 +162,20 @@ ${c}
161
162
  `);let l=null;if(s)try{if(l=i.extractJsonFromStream(c),!l)throw new Error("No valid result JSON found in output");console.log(`
162
163
  \u2705 Parsed Output:
163
164
  ${JSON.stringify(l,null,2)}
164
- `)}catch(a){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${a.message}`)}return{success:!0,output:l,raw:c}}async cleanup(){this.adapter&&this.adapter.isConnected()&&await this.adapter.disconnect()}async executePrompt(e,t=process.cwd(),r=3e5,s=null,n=!0){let o=this.agentCommand;if(o==="cursor-agent"){let c=await zt();c&&(o=c)}return new Promise((c,l)=>{let a="",u=this.buildArgs(e,n);s&&u.push("--model",s);let p={...process.env},d=Xo(o,u,{cwd:t,env:p,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),f=setTimeout(()=>{console.log(`
165
- \u23F1\uFE0F Timeout reached (${r/1e3}s) - killing agent...`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||(console.log("\u26A0\uFE0F Forcing kill (SIGKILL)..."),d.kill("SIGKILL"))},2e3),l(new Error(`Agent timed out after ${r/1e3}s. The agent may be stuck or waiting for user input.`))},r),m=0,S=Date.now(),g=setInterval(()=>{if(a.length>m)m=a.length,S=Date.now();else{let x=Date.now()-S;x>1e4&&console.log(`\u23F3 AI agent is thinking... (${Math.floor(x/1e3)}s, ${a.length} bytes so far)`)}},1e4),w=()=>{clearTimeout(f),clearInterval(g),d&&!d.killed&&(d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},2e3))},y=()=>{console.log(`
165
+ `)}catch(a){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${a.message}`)}return{success:!0,output:l,raw:c}}async cleanup(){this.adapter&&this.adapter.isConnected()&&await this.adapter.disconnect()}async executePrompt(e,t=process.cwd(),r=3e5,s=null,n=!0){let o=this.agentCommand;if(o==="cursor-agent"){let c=await Ft();c&&(o=c)}return new Promise((c,l)=>{let a="",u=this.buildArgs(e,n);s&&u.push("--model",s);let p={...process.env},d=Ko(o,u,{cwd:t,env:p,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),f=setTimeout(()=>{console.log(`
166
+ \u23F1\uFE0F Timeout reached (${r/1e3}s) - killing agent...`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||(console.log("\u26A0\uFE0F Forcing kill (SIGKILL)..."),d.kill("SIGKILL"))},2e3),l(new Error(`Agent timed out after ${r/1e3}s. The agent may be stuck or waiting for user input.`))},r),m=0,S=Date.now(),h=setInterval(()=>{if(a.length>m)m=a.length,S=Date.now();else{let E=Date.now()-S;E>1e4&&console.log(`\u23F3 AI agent is thinking... (${Math.floor(E/1e3)}s, ${a.length} bytes so far)`)}},1e4),_=()=>{clearTimeout(f),clearInterval(h),d&&!d.killed&&(d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},2e3))},y=()=>{console.log(`
166
167
 
167
- \u{1F6D1} Interrupted by user (Ctrl+C)`),w(),l(new Error("Interrupted by user"))};process.on("SIGINT",y);let E=new te;d.stdout.on("data",x=>{let v=x.toString();a+=v;let $=E.processChunk(v);$&&(process.stdout.write($,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),S=Date.now(),m+=$.length)}),d.on("close",x=>{process.off("SIGINT",y),clearTimeout(f),clearInterval(g);let v=E.flush();v&&process.stdout.write(v),a=E.getRawText();let $=E.getResult();x===0?c({raw:a,extracted:$}):l(new Error(`Agent exited with code ${x}`))}),d.on("error",x=>{process.off("SIGINT",y),clearTimeout(f),clearInterval(g),l(new Error(`Failed to spawn agent: ${x.message}`))})})}async runSingleNode(e,t,r){let s=t[e];if(!s)throw new Error(`Unknown node: ${e}. Available nodes: ${Object.keys(t).join(", ")}`);let{cwd:n}=r;if(!n)throw new Error("cwd is required for single node execution");let o=r.sessionPath,c=r.sessionTimestamp,l=r.config||{};if(!o){let y=process.env.CI_JOB_ID||process.env.GITHUB_RUN_ID||process.env.CIRCLE_WORKFLOW_ID||process.env.BUILD_ID||Date.now().toString(),E=l.paths?.sessionPrefix,x=E?`${E}_${y}`:y;c=c||Date.now();let v=l.paths?.output||B;o=mr(n,v,H,x),Qo(o)||Ks(o,{recursive:!0})}let a=l.paths?.output||B,u=mr(n,a,q);Ks(mr(n,a),{recursive:!0}),ei(u,JSON.stringify({sessionPath:o,sessionTimestamp:c||o.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
168
+ \u{1F6D1} Interrupted by user (Ctrl+C)`),_(),l(new Error("Interrupted by user"))};process.on("SIGINT",y);let x=new se;d.stdout.on("data",E=>{let T=E.toString();a+=T;let v=x.processChunk(T);v&&(process.stdout.write(v,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),S=Date.now(),m+=v.length)}),d.on("close",E=>{process.off("SIGINT",y),clearTimeout(f),clearInterval(h);let T=x.flush();T&&process.stdout.write(T),a=x.getRawText();let v=x.getResult();E===0?c({raw:a,extracted:v}):l(new Error(`Agent exited with code ${E}`))}),d.on("error",E=>{process.off("SIGINT",y),clearTimeout(f),clearInterval(h),l(new Error(`Failed to spawn agent: ${E.message}`))})})}async runSingleNode(e,t,r){let s=t[e];if(!s)throw new Error(`Unknown node: ${e}. Available nodes: ${Object.keys(t).join(", ")}`);let{cwd:n}=r;if(!n)throw new Error("cwd is required for single node execution");let o=r.sessionPath,c=r.sessionTimestamp,l=r.config||{};if(!o){let y=process.env.CI_JOB_ID||process.env.GITHUB_RUN_ID||process.env.CIRCLE_WORKFLOW_ID||process.env.BUILD_ID||Date.now().toString(),x=l.paths?.sessionPrefix,E=x?`${x}_${y}`:y;c=c||Date.now();let T=l.paths?.output||j;o=pr(n,T,X,E),Zo(o)||Js(o,{recursive:!0})}let a=l.paths?.output||j,u=pr(n,a,Q);Js(pr(n,a),{recursive:!0}),Ho(u,JSON.stringify({sessionPath:o,sessionTimestamp:c||o.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
168
169
  ${"=".repeat(80)}`),console.log(`\u{1F3AF} SINGLE NODE EXECUTION: ${e}`),console.log(`\u{1F4C1} Session: ${o.split("/").pop()}${r.sessionPath?" (reusing)":""}`),console.log(`${"=".repeat(80)}
169
- `);let p=await we.loadContext(r.specPath||"",n,r.contextConfig||{}),{Node:d}=await Promise.resolve().then(()=>(fr(),Fs)),{WorkflowState:f}=await Promise.resolve().then(()=>(Wt(),Wr)),m=new f({...r,sessionPath:o,sessionTimestamp:c,context:p}),g=await new d(s).execute(this,m);return console.log(`
170
+ `);let p=await ft.loadContext(r.specPath||"",n,r.contextConfig||{}),{Node:d}=await Promise.resolve().then(()=>(lr(),Ls)),{WorkflowState:f}=await Promise.resolve().then(()=>(Gt(),Fr)),m=new f({...r,sessionPath:o,sessionTimestamp:c,context:p}),h=await new d(s).execute(this,m);return console.log(`
170
171
  ${"=".repeat(80)}`),console.log(`\u2705 Node ${e} completed`),console.log(`${"=".repeat(80)}
171
- `),{success:!0,output:g.output,outputPath:r.outputPath,state:g}}calculateOutputPath(e){let{specs:t,generated:r}=this.paths;if(!e)return`${r}/generated-test.spec.js`;let s=e.replace(new RegExp(`^${t}/`),"").replace(/\.[^.]+$/,".spec.js");return`${r}/${s}`.replace(/\/+/g,"/")}};function ti(i,e={}){let t=new Ce(e);return t.buildGraph=function(){let r=new et;return i(r),r},e.onComplete&&(t.onComplete=e.onComplete),t}V();import{writeFileSync as Zs,existsSync as ri,mkdirSync as si}from"node:fs";import{join as hr}from"node:path";var gr=class i{static saveTitle(e,t){let r=e.state.sessionPath;if(!r)return;let s=i._findInState(e.state,"title")||i._findInState(e.state,"result");if(!(!s||typeof s!="string"))try{let n=hr(r,"title.txt");Zs(n,s,"utf-8"),h.info(`Saved title to session: "${s}"`)}catch(n){console.warn("\u26A0\uFE0F Could not save title file:",n.message)}}static _findInState(e,t){for(let[,r]of Object.entries(e))if(r&&typeof r=="object"&&r[t]!==void 0)return r[t]}static async saveExecutionData(e){let t=e.state.sessionPath;if(t)for(let[r,s]of Object.entries(e.state)){if(!s||typeof s!="object")continue;let n=Array.isArray(s.actions)&&s.actions.length>0,o=typeof s.scriptPath=="string"&&s.scriptPath.trim().length>0;if(!(!n&&!o))try{let c=hr(t,r);ri(c)||si(c,{recursive:!0});let l=hr(c,"result.json");Zs(l,JSON.stringify(s,null,2),"utf-8"),h.info(`Saved execution data to ${r} folder`),await this.onNodeSaved(c,s)}catch(c){console.warn(`\u26A0\uFE0F Could not save execution data for ${r}:`,c.message)}}}static async onNodeSaved(e,t){}static logResult(e,t){let r=Object.entries(e.state).filter(([,o])=>o&&typeof o=="object"&&o.success!==void 0),s=r.length>0&&r.every(([,o])=>o.success),n=r.some(([,o])=>o.success===!1);if(s)h.info("Workflow completed successfully."),t&&h.info(`Output: ${t}`);else if(n){let o=r.filter(([,c])=>!c.success).map(([c])=>c);h.info(`Workflow completed with failures in: ${o.join(", ")}`),t&&h.info(`Output: ${t}`)}return s}static handle(e,t,r){return this.saveTitle(e,t),this.saveExecutionData(e),this.logResult(e,r)}};Tt();nr();or();ee();se();import{z as vf}from"zod/v3";var ni={READ_FILE:"read_file",WRITE_FILE:"write_file",LIST_DIRECTORY:"list_directory",RUN_COMMAND:"run_command",OPEN_URL:"open_url",WAIT:"wait"},oi={LIST_PROJECTS:"jira_list_projects",SEARCH:"jira_search",GET_ISSUE:"jira_get_issue",CREATE_ISSUE:"jira_create_issue",LIST_SPRINTS:"jira_list_sprints",GET_SPRINT_ISSUES:"jira_get_sprint_issues",GET_COMMENTS:"jira_get_comments",ADD_COMMENT:"jira_add_comment",EDIT_ISSUE:"jira_edit_issue",TRANSITION_ISSUE:"jira_transition_issue"},ii={GET_USER:"github_get_user",LIST_ORGS:"github_list_orgs",LIST_REPOS:"github_list_repos",CLONE:"github_clone",SEARCH_REPOS:"github_search_repos",SEARCH_ISSUES:"github_search_issues",SEARCH_CODE:"github_search_code",GET_PR:"github_get_pr",GET_PR_DIFF:"github_get_pr_diff",LIST_PR_FILES:"github_list_pr_files",LIST_PR_COMMENTS:"github_list_pr_comments",LIST_COMMITS:"github_list_commits",GET_COMMIT:"github_get_commit",GET_FILE:"github_get_file",CREATE_ISSUE:"github_create_issue"},ai={LIST_CHANNELS:"slack_list_channels",POST_MESSAGE:"slack_post_message",REPLY_TO_THREAD:"slack_reply_to_thread",ADD_REACTION:"slack_add_reaction",GET_CHANNEL_HISTORY:"slack_get_channel_history",GET_THREAD_REPLIES:"slack_get_thread_replies",GET_USERS:"slack_get_users",GET_USER_PROFILE:"slack_get_user_profile"},ci={GENERATE:"run_generate",TEST:"run_test",STATUS:"run_status",CANCEL:"run_cancel",WAIT:"run_wait",ARTIFACTS:"run_artifacts",LIST_SPECS:"list_specs"},li={GET_TEST_HISTORY:"memory_get_test_history",GET_SELECTORS:"memory_get_selectors",GET_PAGE_MODEL:"memory_get_page_model",GET_NAVIGATION:"memory_get_navigation",SAVE_INSIGHT:"memory_save_insight"},ui={STORE:"memory_store",RECALL:"memory_recall",BRIEF:"memory_brief",END_SESSION:"memory_end_session",TASK_LOG:"task_log",TASK_HISTORY:"task_history"},pi={INSTALL:"install_skill",UNINSTALL:"uninstall_skill",LIST_AVAILABLE:"list_available_skills"},wu={...ni,...oi,...ii,...ai,...ci,...li,...ui,...pi};import{existsSync as fi,readFileSync as di}from"node:fs";import{homedir as mi}from"node:os";import{join as hi}from"node:path";var Ot=new Map;function gi(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let i=hi(mi(),".zibby","config.json");return fi(i)&&JSON.parse(di(i,"utf-8")).sessionToken||null}catch{return null}}function yi(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app"}async function Si(i){let e=Date.now(),t=Ot.get(i);if(t&&t.expiresAt>e)return t.data;let r=gi();if(!r)throw new Error("No session token. Run `zibby login` first.");let s=`${yi()}/integrations/token/${i}`,n=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!n.ok){let l=await n.text().catch(()=>"");throw n.status===404?new Error(`${i} is not connected. Connect it at https://studio.zibby.app/integrations`):n.status===401||n.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Failed to resolve ${i} token (${n.status}): ${l}`)}let o=await n.json();if(!o||typeof o!="object")throw new Error(`Invalid response from ${i} token endpoint: expected object, got ${typeof o}`);if(i==="jira"){if(!o.token||typeof o.token!="string")throw new Error(`Invalid jira token response: token is ${typeof o.token}, expected string`);if(!o.cloudId)throw new Error("Invalid jira token response: missing cloudId")}else if(i==="github"&&(!o.token||typeof o.token!="string"))throw new Error(`Invalid github token response: token is ${typeof o.token}, expected string`);let c=((o.expiresInSec||3e3)-120)*1e3;return Ot.set(i,{data:o,expiresAt:e+c}),o}function wi(i){i?Ot.delete(i):Ot.clear()}import{readdir as _i,access as Hs,copyFile as bi,constants as Vs}from"fs/promises";import{join as Pt,relative as xi}from"node:path";async function Ei(i={}){let{testResultsDir:e="test-results",testsDir:t="tests",projectRoot:r=process.cwd(),verbose:s=!0}=i;s&&console.log(`\u{1F3A5} Organizing test videos...
172
- `);let n=Pt(r,e),o=Pt(r,t);try{let c=await _i(n),l=0;for(let a of c){if(a.startsWith("."))continue;let u=Pt(n,a,"video.webm");try{await Hs(u,Vs.F_OK)}catch{continue}let p=a.replace(/-chromium$/,"").replace(/-firefox$/,"").replace(/-webkit$/,""),d=await Ti(o,p);if(d){let f=d.replace(/\.spec\.(js|ts)$/,".spec.webm");await bi(u,f),s&&console.log(`\u2705 ${xi(r,f)}`),l++}else s&&console.log(`\u26A0\uFE0F Could not find test file for: ${a}`)}return s&&(console.log(`
173
- \u{1F3AC} Organized ${l} video(s)`),console.log(`\u{1F4C2} Videos are now next to their test files in ${t}/`)),{movedCount:l,success:!0}}catch(c){return s&&console.error("\u274C Error organizing videos:",c.message),{movedCount:0,success:!1,error:c.message}}}async function Ti(i,e){let t=e.split("-");for(let r=t.length;r>0;r--){let n=t.slice(0,r).join("/");for(let o of["js","ts"]){let c=Pt(i,`${n}.spec.${o}`);try{return await Hs(c,Vs.F_OK),c}catch{}}}return null}var tt=class{constructor(e,t={}){this.apiKey=e,this.baseUrl=t.baseUrl||process.env.ZIBBY_API_URL||"https://api-prod.zibby.app",this.enabled=!!e}isEnabled(){return this.enabled}};function qs(){let i=process.env.ZIBBY_API_KEY;return new tt(i)}import{execSync as vi}from"node:child_process";import{existsSync as $i,mkdirSync as Ii}from"node:fs";import{join as Ai}from"node:path";async function Oi(i={}){let{baseDir:e="/workspace/repos",repos:t=null,depth:r=1,branch:s=null}=i,n=process.env.REPOS;if(!n)throw new Error("REPOS environment variable not set. Are you running in a Zibby workflow container?");let o;try{o=JSON.parse(n)}catch(a){throw new Error(`Failed to parse REPOS env var: ${a.message}`,{cause:a})}if(!Array.isArray(o)||o.length===0)throw new Error("No repositories configured for this project");let c=t?o.filter(a=>t.includes(a.name)):o;if(c.length===0)throw new Error(`No matching repositories found. Available: ${o.map(a=>a.name).join(", ")}`);$i(e)||Ii(e,{recursive:!0});let l={};return await Promise.all(c.map(async a=>{let u=a.provider||"github",p=u==="gitlab"?process.env.GITLAB_TOKEN:process.env.GITHUB_TOKEN;if(!p){console.error(`${u.toUpperCase()}_TOKEN not set, skipping ${a.name}`),l[a.name]=null;return}let d=a.name.replace(/\//g,"-"),f=Ai(e,d),m=a.cloneUrl||a.url;if(!m){console.error(`Repository "${a.name}" has no clone URL`),l[a.name]=null;return}let S;u==="gitlab"?S=m.replace(/^https:\/\//,`https://oauth2:${p}@`):S=m.replace(/^https:\/\//,`https://x-access-token:${p}@`);let g=["clone"];r>0&&g.push("--depth",r.toString()),s&&g.push("--branch",s),g.push(S,f);let w=`git ${g.join(" ")}`;console.log(`Cloning ${a.name} (${u}) to ${f}...`);try{vi(w,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),console.log(`Repository ${a.name} cloned successfully`),l[a.name]=f}catch(y){let E=y.message.replace(p,"***").replace(S,m);console.error(`Failed to clone ${a.name}: ${E}`),l[a.name]=null}})),l}import{spawn as Xs}from"node:child_process";import{readFileSync as Pi,writeFileSync as Ci,existsSync as Ct}from"node:fs";import{homedir as Qs}from"node:os";import{join as Ne}from"node:path";async function Ni(){let i=Ne(Qs(),".local/share/cursor-agent/versions");if(!Ct(i))throw new Error(`cursor-agent not found at ${i}. Please install cursor-agent first.`);return console.log(`\u{1F527} Patching cursor-agent for CI/CD...
174
- `),new Promise((e,t)=>{let r=Ne(__dirname,"../../scripts/patch-cursor-mcp.py");if(!Ct(r)){t(new Error("Patch script not found"));return}let s=Xs("python3",[r],{stdio:"inherit"});s.on("close",n=>{n===0?e({success:!0}):t(new Error(`Patch failed with code ${n}`))}),s.on("error",n=>{t(n)})})}function Ri(){let i=Ne(Qs(),".local/share/cursor-agent/versions");if(!Ct(i))return{patched:!1,installed:!1};try{let e=wn("fs").readdirSync(i);if(e.length===0)return{patched:!1,installed:!1};let t=e.sort().reverse()[0],r=Ne(i,t,"index.js");return Ct(r)?{patched:Pi(r,"utf-8").includes("AUTO-APPROVE MCP TOOLS FOR CI/CD"),installed:!0,path:r}:{patched:!1,installed:!1}}catch(e){return{patched:!1,installed:!1,error:e.message}}}async function ki(i){return console.log(`\u{1F511} Getting MCP approval keys...
175
- `),new Promise((e,t)=>{let r=Xs("cursor-agent",["mcp","list"],{cwd:i,stdio:"pipe"}),s="";r.stdout.on("data",n=>{s+=n.toString(),process.stdout.write(n)}),r.stderr.on("data",n=>{process.stderr.write(n)}),r.on("close",n=>{if(n===0){let o=Mi(s);e({success:!0,keys:o,output:s})}else t(new Error(`Failed to get approval keys (exit code ${n})`))}),r.on("error",n=>{t(n)})})}function Mi(i){let e={},t=/🔑 APPROVAL KEY:\s+(\S+)\s+=>\s+(\S+)/g,r;for(;(r=t.exec(i))!==null;)e[r[1]]=r[2];return e}function Li(i,e){let t=Ne(i,".cursor/projects"),r=Ne(t,"mcp-approvals.json");Ci(r,JSON.stringify(e,null,2)),console.log(`
172
+ `),{success:!0,output:h.output,outputPath:r.outputPath,state:h}}calculateOutputPath(e){let{specs:t,generated:r}=this.paths;if(!e)return`${r}/generated-test.spec.js`;let s=e.replace(new RegExp(`^${t}/`),"").replace(/\.[^.]+$/,".spec.js");return`${r}/${s}`.replace(/\/+/g,"/")}};function Vo(i,e={}){let t=new Ne(e);return t.buildGraph=function(){let r=new qe;return i(r),r},e.onComplete&&(t.onComplete=e.onComplete),t}q();import{writeFileSync as Ys,existsSync as Xo,mkdirSync as qo}from"node:fs";import{join as fr}from"node:path";var dr=class i{static saveTitle(e,t){let r=e.state.sessionPath;if(!r)return;let s=i._findInState(e.state,"title")||i._findInState(e.state,"result");if(!(!s||typeof s!="string"))try{let n=fr(r,"title.txt");Ys(n,s,"utf-8"),g.info(`Saved title to session: "${s}"`)}catch(n){console.warn("\u26A0\uFE0F Could not save title file:",n.message)}}static _findInState(e,t){for(let[,r]of Object.entries(e))if(r&&typeof r=="object"&&r[t]!==void 0)return r[t]}static async saveExecutionData(e){let t=e.state.sessionPath;if(t)for(let[r,s]of Object.entries(e.state)){if(!s||typeof s!="object")continue;let n=Array.isArray(s.actions)&&s.actions.length>0,o=typeof s.scriptPath=="string"&&s.scriptPath.trim().length>0;if(!(!n&&!o))try{let c=fr(t,r);Xo(c)||qo(c,{recursive:!0});let l=fr(c,"result.json");Ys(l,JSON.stringify(s,null,2),"utf-8"),g.info(`Saved execution data to ${r} folder`),await this.onNodeSaved(c,s)}catch(c){console.warn(`\u26A0\uFE0F Could not save execution data for ${r}:`,c.message)}}}static async onNodeSaved(e,t){}static logResult(e,t){let r=Object.entries(e.state).filter(([,o])=>o&&typeof o=="object"&&o.success!==void 0),s=r.length>0&&r.every(([,o])=>o.success),n=r.some(([,o])=>o.success===!1);if(s)g.info("Workflow completed successfully."),t&&g.info(`Output: ${t}`);else if(n){let o=r.filter(([,c])=>!c.success).map(([c])=>c);g.info(`Workflow completed with failures in: ${o.join(", ")}`),t&&g.info(`Output: ${t}`)}return s}static handle(e,t,r){return this.saveTitle(e,t),this.saveExecutionData(e),this.logResult(e,r)}};xt();tr();rr();re();ne();import{z as Tf}from"zod/v3";var Qo={READ_FILE:"read_file",WRITE_FILE:"write_file",LIST_DIRECTORY:"list_directory",RUN_COMMAND:"run_command",OPEN_URL:"open_url",WAIT:"wait"},ei={LIST_PROJECTS:"jira_list_projects",SEARCH:"jira_search",GET_ISSUE:"jira_get_issue",CREATE_ISSUE:"jira_create_issue",LIST_SPRINTS:"jira_list_sprints",GET_SPRINT_ISSUES:"jira_get_sprint_issues",GET_COMMENTS:"jira_get_comments",ADD_COMMENT:"jira_add_comment",EDIT_ISSUE:"jira_edit_issue",TRANSITION_ISSUE:"jira_transition_issue"},ti={GET_USER:"github_get_user",LIST_ORGS:"github_list_orgs",LIST_REPOS:"github_list_repos",CLONE:"github_clone",SEARCH_REPOS:"github_search_repos",SEARCH_ISSUES:"github_search_issues",SEARCH_CODE:"github_search_code",GET_PR:"github_get_pr",GET_PR_DIFF:"github_get_pr_diff",LIST_PR_FILES:"github_list_pr_files",LIST_PR_COMMENTS:"github_list_pr_comments",LIST_COMMITS:"github_list_commits",GET_COMMIT:"github_get_commit",GET_FILE:"github_get_file",CREATE_ISSUE:"github_create_issue"},ri={LIST_CHANNELS:"slack_list_channels",POST_MESSAGE:"slack_post_message",REPLY_TO_THREAD:"slack_reply_to_thread",ADD_REACTION:"slack_add_reaction",GET_CHANNEL_HISTORY:"slack_get_channel_history",GET_THREAD_REPLIES:"slack_get_thread_replies",GET_USERS:"slack_get_users",GET_USER_PROFILE:"slack_get_user_profile"},si={GENERATE:"run_generate",TEST:"run_test",STATUS:"run_status",CANCEL:"run_cancel",WAIT:"run_wait",ARTIFACTS:"run_artifacts",LIST_SPECS:"list_specs"},ni={GET_TEST_HISTORY:"memory_get_test_history",GET_SELECTORS:"memory_get_selectors",GET_PAGE_MODEL:"memory_get_page_model",GET_NAVIGATION:"memory_get_navigation",SAVE_INSIGHT:"memory_save_insight"},oi={STORE:"memory_store",RECALL:"memory_recall",BRIEF:"memory_brief",END_SESSION:"memory_end_session",TASK_LOG:"task_log",TASK_HISTORY:"task_history"},ii={INSTALL:"install_skill",UNINSTALL:"uninstall_skill",LIST_AVAILABLE:"list_available_skills"},wu={...Qo,...ei,...ti,...ri,...si,...ni,...oi,...ii};import{existsSync as ai,readFileSync as ci}from"node:fs";import{homedir as li}from"node:os";import{join as ui}from"node:path";var vt=new Map;function pi(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let i=ui(li(),".zibby","config.json");return ai(i)&&JSON.parse(ci(i,"utf-8")).sessionToken||null}catch{return null}}function fi(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app"}async function di(i){let e=Date.now(),t=vt.get(i);if(t&&t.expiresAt>e)return t.data;let r=pi();if(!r)throw new Error("No session token. Run `zibby login` first.");let s=`${fi()}/integrations/token/${i}`,n=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!n.ok){let l=await n.text().catch(()=>"");throw n.status===404?new Error(`${i} is not connected. Connect it at https://studio.zibby.app/integrations`):n.status===401||n.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Failed to resolve ${i} token (${n.status}): ${l}`)}let o=await n.json();if(!o||typeof o!="object")throw new Error(`Invalid response from ${i} token endpoint: expected object, got ${typeof o}`);if(i==="jira"){if(!o.token||typeof o.token!="string")throw new Error(`Invalid jira token response: token is ${typeof o.token}, expected string`);if(!o.cloudId)throw new Error("Invalid jira token response: missing cloudId")}else if(i==="github"&&(!o.token||typeof o.token!="string"))throw new Error(`Invalid github token response: token is ${typeof o.token}, expected string`);let c=((o.expiresInSec||3e3)-120)*1e3;return vt.set(i,{data:o,expiresAt:e+c}),o}function mi(i){i?vt.delete(i):vt.clear()}import{readdir as gi,access as Ws,copyFile as hi,constants as Ks}from"fs/promises";import{join as At,relative as yi}from"node:path";async function Si(i={}){let{testResultsDir:e="test-results",testsDir:t="tests",projectRoot:r=process.cwd(),verbose:s=!0}=i;s&&console.log(`\u{1F3A5} Organizing test videos...
173
+ `);let n=At(r,e),o=At(r,t);try{let c=await gi(n),l=0;for(let a of c){if(a.startsWith("."))continue;let u=At(n,a,"video.webm");try{await Ws(u,Ks.F_OK)}catch{continue}let p=a.replace(/-chromium$/,"").replace(/-firefox$/,"").replace(/-webkit$/,""),d=await wi(o,p);if(d){let f=d.replace(/\.spec\.(js|ts)$/,".spec.webm");await hi(u,f),s&&console.log(`\u2705 ${yi(r,f)}`),l++}else s&&console.log(`\u26A0\uFE0F Could not find test file for: ${a}`)}return s&&(console.log(`
174
+ \u{1F3AC} Organized ${l} video(s)`),console.log(`\u{1F4C2} Videos are now next to their test files in ${t}/`)),{movedCount:l,success:!0}}catch(c){return s&&console.error("\u274C Error organizing videos:",c.message),{movedCount:0,success:!1,error:c.message}}}async function wi(i,e){let t=e.split("-");for(let r=t.length;r>0;r--){let n=t.slice(0,r).join("/");for(let o of["js","ts"]){let c=At(i,`${n}.spec.${o}`);try{return await Ws(c,Ks.F_OK),c}catch{}}}return null}var Qe=class{constructor(e,t={}){this.apiKey=e,this.baseUrl=t.baseUrl||process.env.ZIBBY_API_URL||"https://api-prod.zibby.app",this.enabled=!!e}isEnabled(){return this.enabled}};function Zs(){let i=process.env.ZIBBY_API_KEY;return new Qe(i)}import{execSync as _i}from"node:child_process";import{existsSync as bi,mkdirSync as xi}from"node:fs";import{join as Ei}from"node:path";async function Ii(i={}){let{baseDir:e="/workspace/repos",repos:t=null,depth:r=1,branch:s=null}=i,n=process.env.REPOS;if(!n)throw new Error("REPOS environment variable not set. Are you running in a Zibby workflow container?");let o;try{o=JSON.parse(n)}catch(a){throw new Error(`Failed to parse REPOS env var: ${a.message}`,{cause:a})}if(!Array.isArray(o)||o.length===0)throw new Error("No repositories configured for this project");let c=t?o.filter(a=>t.includes(a.name)):o;if(c.length===0)throw new Error(`No matching repositories found. Available: ${o.map(a=>a.name).join(", ")}`);bi(e)||xi(e,{recursive:!0});let l={};return await Promise.all(c.map(async a=>{let u=a.provider||"github",p=u==="gitlab"?process.env.GITLAB_TOKEN:process.env.GITHUB_TOKEN;if(!p){console.error(`${u.toUpperCase()}_TOKEN not set, skipping ${a.name}`),l[a.name]=null;return}let d=a.name.replace(/\//g,"-"),f=Ei(e,d),m=a.cloneUrl||a.url;if(!m){console.error(`Repository "${a.name}" has no clone URL`),l[a.name]=null;return}let S;u==="gitlab"?S=m.replace(/^https:\/\//,`https://oauth2:${p}@`):S=m.replace(/^https:\/\//,`https://x-access-token:${p}@`);let h=["clone"];r>0&&h.push("--depth",r.toString()),s&&h.push("--branch",s),h.push(S,f);let _=`git ${h.join(" ")}`;console.log(`Cloning ${a.name} (${u}) to ${f}...`);try{_i(_,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),console.log(`Repository ${a.name} cloned successfully`),l[a.name]=f}catch(y){let x=y.message.replace(p,"***").replace(S,m);console.error(`Failed to clone ${a.name}: ${x}`),l[a.name]=null}})),l}import{spawn as Hs}from"node:child_process";import{readFileSync as Ti,writeFileSync as $i,existsSync as Pt}from"node:fs";import{homedir as Vs}from"node:os";import{join as Re}from"node:path";async function vi(){let i=Re(Vs(),".local/share/cursor-agent/versions");if(!Pt(i))throw new Error(`cursor-agent not found at ${i}. Please install cursor-agent first.`);return console.log(`\u{1F527} Patching cursor-agent for CI/CD...
175
+ `),new Promise((e,t)=>{let r=Re(__dirname,"../../scripts/patch-cursor-mcp.py");if(!Pt(r)){t(new Error("Patch script not found"));return}let s=Hs("python3",[r],{stdio:"inherit"});s.on("close",n=>{n===0?e({success:!0}):t(new Error(`Patch failed with code ${n}`))}),s.on("error",n=>{t(n)})})}function Ai(){let i=Re(Vs(),".local/share/cursor-agent/versions");if(!Pt(i))return{patched:!1,installed:!1};try{let e=hn("fs").readdirSync(i);if(e.length===0)return{patched:!1,installed:!1};let t=e.sort().reverse()[0],r=Re(i,t,"index.js");return Pt(r)?{patched:Ti(r,"utf-8").includes("AUTO-APPROVE MCP TOOLS FOR CI/CD"),installed:!0,path:r}:{patched:!1,installed:!1}}catch(e){return{patched:!1,installed:!1,error:e.message}}}async function Pi(i){return console.log(`\u{1F511} Getting MCP approval keys...
176
+ `),new Promise((e,t)=>{let r=Hs("cursor-agent",["mcp","list"],{cwd:i,stdio:"pipe"}),s="";r.stdout.on("data",n=>{s+=n.toString(),process.stdout.write(n)}),r.stderr.on("data",n=>{process.stderr.write(n)}),r.on("close",n=>{if(n===0){let o=Oi(s);e({success:!0,keys:o,output:s})}else t(new Error(`Failed to get approval keys (exit code ${n})`))}),r.on("error",n=>{t(n)})})}function Oi(i){let e={},t=/🔑 APPROVAL KEY:\s+(\S+)\s+=>\s+(\S+)/g,r;for(;(r=t.exec(i))!==null;)e[r[1]]=r[2];return e}function Ci(i,e){let t=Re(i,".cursor/projects"),r=Re(t,"mcp-approvals.json");$i(r,JSON.stringify(e,null,2)),console.log(`
176
177
  \u2705 Saved approval keys to: ${r}
177
- `)}oe();ee();var en=`
178
+ `)}ae();re();var Xs=`
178
179
  const style = document.createElement('style');
179
180
  style.textContent = \`
180
181
  @keyframes zibby-ripple {
@@ -235,7 +236,7 @@ ${"=".repeat(80)}`),console.log(`\u2705 Node ${e} completed`),console.log(`${"="
235
236
  setTimeout(() => ripple.remove(), 600);
236
237
  }
237
238
  };
238
- `;function Di(i){return i.addInitScript(en)}function Bi(){return`
239
+ `;function Ni(i){return i.addInitScript(Xs)}function Ri(){return`
239
240
  async function showRipple(page, locator) {
240
241
  const box = await locator.boundingBox().catch(() => null);
241
242
  if (box) {
@@ -248,10 +249,10 @@ async function showRipple(page, locator) {
248
249
  }, { x, y }).catch(() => {});
249
250
  }
250
251
  }
251
- `.trim()}var rt=class{static generate(e,t="element"){let{selectors:r}=e;if(!r||typeof r!="object")return this.generateFallbackSelector(e,t);let s=[];return r.role&&s.push(this.generateRoleSelector(r.role)),r.attributes&&s.push(this.generateAttributeSelector(r.attributes)),r.partialMatch&&s.push(this.generatePartialMatchSelector(r.partialMatch)),r.structure&&s.push(this.generateStructuralSelector(r.structure)),s.length===0?this.generateFallbackSelector(e,t):s.length===1?`const ${t} = ${s[0]};`:`const ${t} = ${s[0]}
252
+ `.trim()}var et=class{static generate(e,t="element"){let{selectors:r}=e;if(!r||typeof r!="object")return this.generateFallbackSelector(e,t);let s=[];return r.role&&s.push(this.generateRoleSelector(r.role)),r.attributes&&s.push(this.generateAttributeSelector(r.attributes)),r.partialMatch&&s.push(this.generatePartialMatchSelector(r.partialMatch)),r.structure&&s.push(this.generateStructuralSelector(r.structure)),s.length===0?this.generateFallbackSelector(e,t):s.length===1?`const ${t} = ${s[0]};`:`const ${t} = ${s[0]}
252
253
  ${s.slice(1).map(o=>` .or(${o})`).join(`
253
254
  `)};`}static generateRoleSelector(e){let{role:t,name:r}=e;if(!t)return null;if(r){let s=this.escapeRegex(r);return`page.getByRole('${t}', { name: /${s}/i })`}return`page.getByRole('${t}')`}static generateAttributeSelector(e){if(!e||typeof e!="object")return null;let t=Object.entries(e).filter(([s,n])=>n!=null).map(([s,n])=>s==="placeholder"||s==="aria-label"?s==="placeholder"?`page.getByPlaceholder('${this.escapeString(n)}')`:`page.locator('[${s}="${this.escapeString(n)}"]')`:`[${s}="${this.escapeString(n)}"]`);if(e.placeholder)return`page.getByPlaceholder('${this.escapeString(e.placeholder)}')`;let r=t.filter(s=>!s.startsWith("page.")).join("");return r?`page.locator('${r}')`:null}static generatePartialMatchSelector(e){if(!e||typeof e!="object")return null;let t=Object.entries(e).filter(([r,s])=>s!==void 0).map(([r,s])=>{let n=s.replace(/^\^/,"");return`[${r}^="${this.escapeString(n)}"]`});return t.length>0?`page.locator('${t.join("")}')`:null}static generateStructuralSelector(e){return!e||typeof e!="string"?null:`page.locator('${this.escapeString(e)}')`}static generateFallbackSelector(e,t){let{description:r,type:s}=e;if(s==="fill"||s==="type")return`const ${t} = page.locator('input').first();`;if(s==="click"){if(r.toLowerCase().includes("button"))return`const ${t} = page.locator('button').first();`;if(r.toLowerCase().includes("link"))return`const ${t} = page.locator('a').first();`}return`const ${t} = page.locator('body');`}static escapeString(e){return typeof e!="string"?String(e):e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/"/g,'\\"')}static escapeRegex(e){return typeof e!="string"?String(e):e.replace(/[.*+?^${}()[\]\\]/g,"\\$&")}static generateActionCode(e,t){let{type:r,value:s,description:n,selectors:o}=e,c=`element${t}`,l=this.generate(e,c),a=this.generateActionMethod(r,c,s);return`${l}
254
- ${a}`}static generateActionMethod(e,t,r){switch(e){case"fill":case"type":return`await ${t}.fill('${this.escapeString(r||"")}');`;case"click":return`await ${t}.click();`;case"navigate":return`await page.goto('${this.escapeString(r||"")}');`;case"wait":return`await page.waitForTimeout(${parseInt(r)||2e3});`;default:return`// Unknown action type: ${e}`}}static generateAssertionCode(e,t){let{description:r,expected:s,actual:n,passed:o}=e;return r.toLowerCase().includes("url")?`await expect(page).toHaveURL(/${this.escapeRegex(n)}/);`:r.toLowerCase().includes("visible")?"await expect(page.locator('body')).toBeVisible();":`// ${r}`}};import st from"fs/promises";var yr=class{static async generateFromEvents(e,t,r,s){try{console.log("[TestPostProcessor] \u{1F3AF} Generating test from events.json (100% accurate)");let{readFileSync:n}=await import("fs"),o=JSON.parse(n(t,"utf-8")),c=o.filter(f=>["navigate","type","fill","click","select_option"].includes(f.type)),l=c.filter(f=>f.type!=="navigate");console.log(`[TestPostProcessor] Found ${c.length} action events, ${r.length} trace actions`);let a=`import { ZibbyRuntime } from '@zibby/core';
255
+ ${a}`}static generateActionMethod(e,t,r){switch(e){case"fill":case"type":return`await ${t}.fill('${this.escapeString(r||"")}');`;case"click":return`await ${t}.click();`;case"navigate":return`await page.goto('${this.escapeString(r||"")}');`;case"wait":return`await page.waitForTimeout(${parseInt(r)||2e3});`;default:return`// Unknown action type: ${e}`}}static generateAssertionCode(e,t){let{description:r,expected:s,actual:n,passed:o}=e;return r.toLowerCase().includes("url")?`await expect(page).toHaveURL(/${this.escapeRegex(n)}/);`:r.toLowerCase().includes("visible")?"await expect(page.locator('body')).toBeVisible();":`// ${r}`}};import tt from"fs/promises";var mr=class{static async generateFromEvents(e,t,r,s){try{console.log("[TestPostProcessor] \u{1F3AF} Generating test from events.json (100% accurate)");let{readFileSync:n}=await import("fs"),o=JSON.parse(n(t,"utf-8")),c=o.filter(f=>["navigate","type","fill","click","select_option"].includes(f.type)),l=c.filter(f=>f.type!=="navigate");console.log(`[TestPostProcessor] Found ${c.length} action events, ${r.length} trace actions`);let a=`import { ZibbyRuntime } from '@zibby/core';
255
256
  import { test, expect } from '@playwright/test';
256
257
 
257
258
  `;a+=`test('${s}', async ({ page }) => {
@@ -259,86 +260,86 @@ import { test, expect } from '@playwright/test';
259
260
 
260
261
  `;let u=0;for(let f of c)if(f.type==="navigate")a+=` await page.goto('${f.data.params.url}');
261
262
 
262
- `;else if(f.type==="type"||f.type==="fill"){let{element:m,text:S}=f.data.params,g=r[u]?.strategies||[];a+=` await ZibbyRuntime.step(page, ${JSON.stringify({name:m,action:"fill",value:S,strategies:g},null,2)});
263
+ `;else if(f.type==="type"||f.type==="fill"){let{element:m,text:S}=f.data.params,h=r[u]?.strategies||[];a+=` await ZibbyRuntime.step(page, ${JSON.stringify({name:m,action:"fill",value:S,strategies:h},null,2)});
263
264
 
264
265
  `,u++}else if(f.type==="click"){let{element:m}=f.data.params,S=r[u]?.strategies||[];a+=` await ZibbyRuntime.step(page, ${JSON.stringify({name:m,action:"click",value:"",strategies:S},null,2)});
265
266
 
266
- `,u++}else if(f.type==="select_option"){let{element:m,values:S}=f.data.params,g=r[u]?.strategies||[],w={name:m,action:"selectOption",value:Array.isArray(S)?S[0]:S,strategies:g};a+=` await ZibbyRuntime.step(page, ${JSON.stringify(w,null,2)});
267
+ `,u++}else if(f.type==="select_option"){let{element:m,values:S}=f.data.params,h=r[u]?.strategies||[],_={name:m,action:"selectOption",value:Array.isArray(S)?S[0]:S,strategies:h};a+=` await ZibbyRuntime.step(page, ${JSON.stringify(_,null,2)});
267
268
 
268
269
  `,u++}a+=`});
269
- `;let{dirname:p}=await import("path"),{mkdirSync:d}=await import("fs");return d(p(e),{recursive:!0}),await st.writeFile(e,a,"utf-8"),console.log(`[TestPostProcessor] \u2705 Generated test with ${o.filter(f=>["type","fill","click","select_option"].includes(f.type)).length} actions`),!0}catch(n){return console.warn("[TestPostProcessor] Failed to generate from events:",n.message),!1}}static async enhanceSelectorsWithTrace(e,t,r){try{console.log("[TestPostProcessor] \u{1F6E1}\uFE0F Applying Zibby Safe Action Wrappers...");let s=await st.readFile(e,"utf-8");s.includes("ZibbyRuntime")||(s=`import { ZibbyRuntime } from '@zibby/core';
270
- ${s}`);for(let n=0;n<t.length;n++){let o=t[n],c=`element${n}`,l=new RegExp(`const ${c}\\b\\s*=\\s*page\\.[^;]+;(\\s*await ${c}\\.waitFor\\([^)]*\\);)?\\s*await ${c}\\.(click|fill|type|selectOption|pressSequentially)\\(([^)]*)\\);`,"s"),a=s.match(l);if(!a)continue;let u={name:o.name||`Action ${n}`,action:o.method==="type"?"fill":o.method,value:a[3].trim().replace(/^['"]|['"]$/g,""),strategies:o.strategies||[]},p=`await ZibbyRuntime.step(page, ${JSON.stringify(u,null,2)});`;s=s.replace(a[0],p)}return await st.writeFile(e,s,"utf-8"),console.log("[TestPostProcessor] \u2705 Successfully converted test to Resilient Zibby format"),!0}catch(s){return console.warn("[TestPostProcessor] Failed to apply safe wrappers:",s.message),!1}}static async enhanceSelectors(e,t){try{let{actions:r=[]}=t;if(!r.length)return!1;let s=await st.readFile(e,"utf-8"),n=this.buildSelectorMap(r);return s=this.replaceSimpleSelectors(s,n),await st.writeFile(e,s,"utf-8"),!0}catch(r){return console.warn("Failed to enhance selectors:",r),!1}}static buildSelectorMap(e){let t=new Map;for(let r=0;r<e.length;r++){let s=e[r];if(!s.selectors||s.type==="navigate")continue;let n=`element${r}`,c=rt.generate(s,n).match(/= (.+);/s);if(c){let l=c[1].trim(),a=`${s.type}:${this.normalizeDescription(s.description)}`;t.set(a,l),s.selectors.role&&t.set(`role:${s.selectors.role.name}`,l),s.selectors.attributes?.placeholder&&t.set(`placeholder:${s.selectors.attributes.placeholder}`,l)}}return t}static replaceSimpleSelectors(e,t){let r=e,s=[/await page\.(getByRole|getByPlaceholder|getByText|getByLabel|locator)\([^)]+\)\.(fill|click|type)\([^)]*\)/g];for(let n of s)r=r.replace(n,o=>{for(let[c,l]of t.entries())if(o.includes(c.split(":")[1])){let a=o.match(/\.(fill|click|type)\(([^)]*)\)/);if(a){let[,u,p]=a,d="element";return`const ${d} = ${l};
271
- await ${d}.${u}(${p})`}}return o});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as Fi,existsSync as tn,readdirSync as rn}from"node:fs";import{join as Sr}from"node:path";import{execSync as Ui}from"node:child_process";import{tmpdir as ji}from"node:os";var nt=class{static async parseTraceZip(e){let t;if(e.endsWith(".zip")&&tn(e)){let r=Sr(ji(),`trace-${Date.now()}`);Ui(`unzip -q "${e}" -d "${r}"`,{stdio:"pipe"});let n=rn(r).find(o=>o.endsWith(".trace"));if(!n)throw new Error("No .trace file found in zip");t=Sr(r,n)}else if(tn(e)){let s=rn(e).find(n=>n.endsWith(".trace"));if(!s)throw new Error("No .trace file found");t=Sr(e,s)}else throw new Error(`Trace not found at ${e}`);try{let s=Fi(t,"utf-8").trim().split(`
272
- `),n=[],o=new Map,c=new Map;for(let l of s)try{let a=JSON.parse(l);if(a.type==="snapshot"&&a.snapshot&&a.snapshot.accessibility){let u=new Map;for(let p of a.snapshot.accessibility)p.ref&&u.set(p.ref,p);o.set(a.snapshotName,u)}if(a.type==="frame-snapshot"&&a.snapshot){let u=Buffer.from(a.snapshot.html||"","base64").toString("utf-8");u&&u.length>100&&c.set(a.pageId||"default",u)}}catch{}for(let l of s)try{let a=JSON.parse(l);if(a.type==="before"&&a.params&&a.params.selector){let u=a.method;if(["click","fill","type","selectOption"].includes(u)){let p=a.params.selector,d=a.params.text||a.params.value||"",f=[],m=null,S=null,g=null,w=p.match(/aria-ref=([a-z0-9]+)/i);if(w&&a.snapshotName){let b=w[1],A=o.get(a.snapshotName);if(A&&A.has(b)){let O=A.get(b);m=O.name||null,S=O.role||null,g=O.label||null,console.log(`[TraceParser] \u2705 Found ACTUAL element data: text="${m}", role="${S}"`)}}let y=p.match(/internal:text="([^"]+)"/i),E=p.match(/internal:label="([^"]+)"/i),x=p.match(/internal:placeholder="([^"]+)"/i),v=p.match(/internal:role=([^ ]+)/i),$=p.match(/internal:describe="([^"]+)"/i),T=p.match(/name="([^"]+)"/i);if(y){f.push({type:"text",text:y[1]});let b=y[1].split(" ");b.length>1&&(f.push({type:"text",text:b[0],fuzzy:!0}),f.push({type:"text",text:b[b.length-1],fuzzy:!0}))}if(E&&f.push({type:"label",label:E[1]}),x&&f.push({type:"placeholder",placeholder:x[1]}),m){f.unshift({type:"text",text:m,source:"accessibility-tree"});let b=m.split(" ");b.length>1&&f.push({type:"text",text:b[0],fuzzy:!0,source:"accessibility-tree"})}if(S||v){let b=S||v[1],A=m||(T?T[1]:y?y[1]:null);f.unshift({type:"role",role:b,name:A,source:m?"accessibility-tree":"selector"})}if(g&&f.unshift({type:"label",label:g,source:"accessibility-tree"}),$){let b=$[1],A=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],O=null,_=b;for(let C of A)if(b.toLowerCase().endsWith(` ${C}`)){O=C.replace(" ",""),_=b.substring(0,b.length-C.length-1);break}if(O){f.push({type:"role",role:O,name:_});let C=_.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:C}),f.push({type:"text",text:_});let R=_.split(" ");R.length>1&&(f.push({type:"text",text:R[0],fuzzy:!0}),f.push({type:"text",text:R.slice(0,2).join(" "),fuzzy:!0}))}else{let C=b.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:C}),f.push({type:"text",text:b})}}let I=this.extractDOMStrategies(p,c,y?.[1]||$?.[1],a.pageId);f.push(...I);let P=this.extractStructuralContext(p);(P.parent||P.sibling)&&f.forEach(b=>{["role","text","label","testid"].includes(b.type)&&(P.parent&&(b.parent=P.parent),P.sibling&&(b.sibling=P.sibling))}),f.push({type:"css",value:p});let N=m||y?y[1]:$?$[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${n.length}`;n.push({method:u,name:N,action:u==="type"?"fill":u,value:d,strategies:f,timestamp:a.startTime,actualText:m,actualRole:S,actualAriaLabel:g})}}}catch{}return n}catch(r){throw new Error(`Failed to parse trace: ${r.message}`,{cause:r})}}static extractDOMStrategies(e,t,r,s){let n=[];if(!t||t.size===0||!r)return n;try{let o=t.get(s);if(!o)return n;let c=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),a=o.match(l);a&&n.push({type:"testid",value:a[1],priority:"high"});let u=new RegExp(`class=["']([^"']+)["'][^>]*>[^<]*${c}`,"gi"),p=o.matchAll(u);for(let m of p){let S=m[1].split(/\s+/).filter(g=>g&&!g.match(/^(css|jss|makeStyles|MuiBox|MuiStack)-\w+/)&&g.length>2);S.length>0&&(n.push({type:"class",value:S.join("."),priority:"medium"}),S.length===1&&n.push({type:"class",value:S[0],priority:"medium"}))}let d=new RegExp(`id=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),f=o.match(d);f&&!f[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&n.push({type:"id",value:f[1],priority:"high"})}catch(o){console.warn(`[TraceParser] DOM extraction failed: ${o.message}`)}return n}static extractStructuralContext(e){let t={parent:null,sibling:null},r=e.split(">>").map(o=>o.trim());if(r.length>1){let c=r[r.length-2].replace(/internal:text="[^"]+"\s*/gi,"").replace(/internal:role=\S+\s*/gi,"").replace(/internal:label="[^"]+"\s*/gi,"").trim();c&&(c.match(/^(form|section|nav|header|aside|main|article)\b/)||c.includes("[")||c.match(/[#.]\w/))&&(t.parent=c)}let n=r[r.length-1].match(/([^+~]+)\s*[+~]\s*(.+)/);return n&&(t.sibling=n[1].trim()),t}};Je();var wr=class{static async step(e,t){let{name:r,action:s,value:n,strategies:o,options:c={timeout:1e4},enrichedData:l}=t;console.log(`[Zibby] \u26A1 Executing step: ${r}`),await this.waitForPageStability(e,c.timeout);let a=await this.findBestMatch(e,o,r);if(!a)throw new Error(`[Zibby] \u274C Failed to find "${r}" using ${o.length} strategies`);l?.position&&await this.verifyPosition(a,l.position),await this.performActionWithRetry(e,a,s,n,3),console.log(`[Zibby] \u2728 Step "${r}" completed.`)}static async waitForPageStability(e,t=1e4){try{await e.waitForLoadState("networkidle",{timeout:3e3}).catch(()=>{}),await e.evaluate(()=>new Promise(r=>{let s,n=new MutationObserver(()=>{clearTimeout(s),s=setTimeout(()=>{n.disconnect(),r()},500)});n.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),s=setTimeout(()=>{n.disconnect(),r()},500)})).catch(()=>{})}catch{}}static async verifyPosition(e,t){try{let r=await e.boundingBox();if(!r)return;let s=Math.abs(r.x-t.x),n=Math.abs(r.y-t.y);(s>50||n>50)&&(console.log(`[Zibby] \u26A0\uFE0F Element moved: expected (${t.x}, ${t.y}), got (${r.x}, ${r.y})`),await new Promise(o=>setTimeout(o,500)))}catch{}}static async performActionWithRetry(e,t,r,s,n=3){for(let o=1;o<=n;o++)try{r==="click"?await t.click():r==="fill"?await t.fill(s||""):r==="type"?await t.pressSequentially(s||""):r==="selectOption"&&await t.selectOption(s||"");return}catch(c){if(o===n)throw c;console.log(`[Zibby] \u26A0\uFE0F Action failed (attempt ${o}/${n}), retrying...`),await new Promise(l=>setTimeout(l,1e3*o))}}static async findBestMatch(e,t,r){let n=Date.now(),o=t.map(async(a,u)=>{try{let d=await this.getLocator(e,a).all();return d.length===0?[]:(await Promise.all(d.map(async(m,S)=>{try{if(!await m.isVisible({timeout:100}))return null;let w=await this.scoreCandidate(m,a,e);return{element:m,strategy:a,score:w,strategyIdx:u,elIdx:S}}catch{return null}}))).filter(m=>m!==null)}catch{return[]}}),c=(await Promise.all(o)).flat();if(c.length===0)return console.log(`[Zibby] \u274C No visible candidates found for "${r}"`),null;c.sort((a,u)=>u.score-a.score);let l=c[0];return console.log(`[Zibby] \u2705 Found element using ${l.strategy.type} (score: ${l.score.toFixed(2)}, ${c.length} candidates)`),l.element}static async scoreCandidate(e,t,r){let s=0;if(s+={testid:120,id:110,role:100,label:90,class:85,placeholder:85,text:80,css:50}[t.type]||50,t.priority==="high"&&(s+=20),t.priority==="medium"&&(s+=10),t.fuzzy&&(s-=15),t.parent)try{await e.locator("xpath=ancestor::*").first().evaluate((l,a)=>l.matches(a),t.parent)&&(s+=30)}catch{}if(t.sibling)try{await e.evaluate((c,l)=>c.parentElement?.querySelector(l)!==null,t.sibling)&&(s+=20)}catch{}try{let o=await e.boundingBox();o&&o.y<1e3&&(s+=10)}catch{}try{let o=await e.evaluate(c=>{let l=0,a=c;for(;a;)a.tagName==="IFRAME"&&l++,a=a.parentElement;return l});s-=o*5}catch{}return s}static getLocator(e,t){let r;switch(t.type){case"testid":r=e.getByTestId(t.value);break;case"id":r=e.locator(`#${t.value}`);break;case"class":r=e.locator(`.${t.value.replace(/\./g,".")}`);break;case"text":t.fuzzy?r=e.getByText(new RegExp(t.text,"i")):r=e.getByText(t.text,{exact:!1});break;case"role":r=e.getByRole(t.role,{name:t.name,exact:!1});break;case"label":r=e.getByLabel(t.label,{exact:!1});break;case"placeholder":r=e.getByPlaceholder(t.placeholder);break;default:{let s=t.value?.replace(/aria-ref=e\d+ >> /g,"")||t.css;r=e.locator(s);break}}return t.parent&&(r=r.filter({has:e.locator(t.parent)})),r}};var _r=class{static async beforeEach(e){await this.injectStableIds(e),e.on("load",async()=>{await this.injectStableIds(e)})}static async afterNavigation(e){await e.waitForLoadState("domcontentloaded").catch(()=>{}),await this.injectStableIds(e)}static async clickWithRetry(e,t,r={}){let s=r.timeout||1e4,n=`[data-zibby-id="${t}"]`,o=Date.now();for(;Date.now()-o<s;){await this.injectStableIds(e);let c=e.locator(n);if(await c.count()>0)try{await c.click({timeout:2e3});return}catch(l){if(l.message.includes("intercepts pointer")){await c.click({force:!0});return}}await e.waitForTimeout(200)}throw new Error(`Element ${n} not found after ${s}ms`)}static async fillWithRetry(e,t,r,s=1e4){let n=`[data-zibby-id="${t}"]`,o=Date.now();for(;Date.now()-o<s;){await this.injectStableIds(e);let c=e.locator(n);if(await c.count()>0){await c.fill(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${n} not found after ${s}ms`)}static async selectWithRetry(e,t,r,s=1e4){let n=`[data-zibby-id="${t}"]`,o=Date.now();for(;Date.now()-o<s;){await this.injectStableIds(e);let c=e.locator(n);if(await c.count()>0){await c.selectOption(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${n} not found after ${s}ms`)}static async injectStableIds(e){try{await e.evaluate(()=>{function t(l){if(l.getAttribute("aria-label"))return l.getAttribute("aria-label").trim();let a=l.getAttribute("aria-labelledby");if(a){let d=document.getElementById(a);if(d)return d.textContent.trim()}if(l.id){let d=document.querySelector(`label[for="${l.id}"]`);if(d)return d.textContent.trim()}let u=l.closest("label");if(u){let d=u.cloneNode(!0);d.querySelectorAll("input, select, textarea").forEach(m=>m.remove());let f=d.textContent.trim();if(f)return f}if(l.placeholder)return l.placeholder;let p=l.tagName.toLowerCase();return p==="button"||p==="a"||l.getAttribute("role")==="button"?(l.textContent||"").trim().slice(0,50):l.title?l.title:p==="input"&&(l.type==="submit"||l.type==="button")&&l.value||""}function r(l){let a=[],u=l.closest("form");if(u)if(u.id)a.push(`form#${u.id}`);else if(u.name)a.push(`form[name=${u.name}]`);else if(u.action)try{let S=new URL(u.action,window.location.origin).pathname;a.push(`form[action=${S}]`)}catch{a.push(`form[action=${u.getAttribute("action")}]`)}else{let S=document.querySelectorAll("form"),g=Array.from(S).indexOf(u);a.push(`form:nth(${g})`)}let p=l.closest('header, nav, main, footer, aside, [role="banner"], [role="navigation"], [role="main"], [role="contentinfo"]');if(p){let S=p.tagName.toLowerCase(),g=p.getAttribute("role");a.push(g||S)}let d=l.closest('section, article, [role="region"]');if(d){let S=d.querySelector("h1, h2, h3, h4, h5, h6");S&&a.push(`section:${S.textContent.trim().slice(0,30)}`)}let f=l.closest("fieldset");if(f){let S=f.querySelector("legend");S&&a.push(`fieldset:${S.textContent.trim()}`)}let m=l.closest('dialog, [role="dialog"], [role="alertdialog"]');if(m){let S=m.querySelector('[role="heading"], h1, h2, h3');S?a.push(`dialog:${S.textContent.trim().slice(0,30)}`):a.push("dialog")}return a.join("/")}function s(l){let a=l.tagName.toLowerCase(),u=l.id||"",p=l.name||"",d=l.type||"",f=l.getAttribute("role")||"",m="";if(l.href)try{m=new URL(l.href,window.location.origin).pathname.slice(0,50)}catch{m=l.getAttribute("href")?.slice(0,50)||""}let S=t(l).slice(0,50).replace(/\s+/g," "),g=r(l),w=[a,u,p,d,f,m,S,g].join("|"),y=5381;for(let E=0;E<w.length;E++)y=(y<<5)+y^w.charCodeAt(E);return`zibby-${(y>>>0).toString(36)}`}let n=["button","a","input","select","textarea","label[for]",'[role="button"]','[role="link"]','[role="textbox"]','[role="checkbox"]','[role="radio"]','[role="combobox"]','[role="menuitem"]','[role="tab"]','[role="option"]','[role="switch"]','[role="slider"]',"[onclick]","[data-action]"].join(", "),o=new Map,c=0;document.querySelectorAll(n).forEach(l=>{let a=window.getComputedStyle(l);if(a.display==="none"||a.visibility==="hidden")return;let u=s(l),p=u,d=o.get(p)||0;d>0&&(u=`${p}-${d}`),o.set(p,d+1),l.setAttribute("data-zibby-id",u),c++}),console.log(`[Zibby] Injected ${c} stable IDs`)})}catch{}}};V();le();var Gi=8,zi=1,Ji=64;function Wi(i){if(!i||typeof i!="object")return 8;let e=i.parallel;if(!e||typeof e!="object")return 8;let t=e.maxConcurrentRuns??e.maxConcurrent,r=Number(t);if(!Number.isFinite(r))return 8;let s=Math.floor(r);return s<1?8:Math.min(64,s)}import{readFileSync as Ki,writeFileSync as nn,existsSync as Zi}from"node:fs";import{join as on}from"node:path";var J=class{constructor(e={}){this.config=e,this.enabled=e.enabled!==!1,this.priority=e.priority||50}getName(){throw new Error("EventEnricher.getName() must be implemented")}canEnrich(e){return this.enabled}async enrich(e,t){throw new Error("EventEnricher.enrich() must be implemented")}handleError(e,t){return console.warn(`[${this.getName()}] Enrichment failed for event ${t.type}:`,e.message),null}};import{existsSync as Yi}from"node:fs";import{join as sn}from"node:path";var ge=class extends J{constructor(e={}){super(e),this.priority=190,this.traceData=null}getName(){return"TraceText"}getPriority(){return this.priority}async loadTrace(e){if(this.traceData)return;let t=sn(e,"traces"),r=sn(e,"trace.zip");if(Yi(r))try{this.traceData=await nt.parseTraceZip(r),console.log(`[TraceTextEnricher] \u2705 Loaded trace with ${this.traceData.length} actions`)}catch(s){console.log(`[TraceTextEnricher] \u26A0\uFE0F Failed to parse trace: ${s.message}`)}}async enrich(e,t){let r=e.data?.params?.ref,s=e.id;if(r===void 0&&s===void 0||(!this.traceData&&t.sessionPath&&await this.loadTrace(t.sessionPath),!this.traceData))return null;let n=this.traceData[s];if(!n)return console.log(`[TraceTextEnricher] \u26A0\uFE0F No trace action for event ${s}`),null;let o=n.actualText||this._extractTextFromSelector(n.selector),c=n.actualRole,l=n.actualAriaLabel;return o||c||l?(console.log(`[TraceTextEnricher] \u2705 Event ${s}: text="${o}", role="${c}", label="${l}"`),{traceActualText:o,traceActualRole:c,traceActualAriaLabel:l,traceSelector:n.selector,traceStrategies:n.strategies}):null}_extractTextFromSelector(e){if(!e)return null;let t=e.match(/internal:label="([^"]+)"/);if(t)return t[1];let r=e.match(/internal:text="([^"]+)"/);if(r)return r[1];let s=e.match(/getByText\(['"]([^'"]+)['"]\)/);if(s)return s[1];let n=e.match(/name:\s*['"]([^'"]+)['"]/);return n?n[1]:null}};async function Hi(i){let e=on(i,"events.json"),t=on(i,"events-enriched.json");if(!Zi(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(Ki(e,"utf-8")),s=new ge,n=0,o=0;for(let c of r)try{let l=await s.enrich(c,{sessionPath:i});l&&(c.enrichedData={...c.enrichedData||{},...l},n++)}catch(l){console.log(`[PostProcess] Failed to enrich event ${c.id}: ${l.message}`),o++}return n>0&&(nn(t,JSON.stringify(r,null,2)),nn(e,JSON.stringify(r,null,2)),console.log(`[PostProcess] \u2705 Enriched ${n} events (${o} failed)`)),{enriched:n,failed:o}}catch(r){return console.log(`[PostProcess] \u274C Failed to post-process events: ${r.message}`),{enriched:0,failed:0}}}import{spawn as Vi}from"node:child_process";import{existsSync as qi}from"node:fs";import{dirname as Xi,resolve as an,relative as Qi}from"node:path";var Nt=new Map,ot=8,cn={name:"run_playwright_test",description:`Run a Playwright test file and return results. Use this after writing a test to verify it works. If it fails, fix the issues and run again. Maximum ${ot} attempts per session.`,inputSchema:{type:"object",properties:{scriptPath:{type:"string",description:"Path to the Playwright test file (e.g., tests/login.spec.js)"}},required:["scriptPath"]},async execute({scriptPath:i},e){let r=`${e?.sessionId||"default"}:${i}`,s=(Nt.get(r)||0)+1;if(Nt.set(r,s),s>ot)return{success:!1,executionCount:s,maxReached:!0,error:`Maximum ${ot} executions reached. Stop retrying and return your best result.`};let n=e?.projectRoot||process.cwd(),o=an(n,i),c=Qi(n,o);return c.startsWith("..")||an(o)!==o&&c.includes("..")?{success:!1,executionCount:s,error:"Path traversal detected: scriptPath must be within the project root."}:qi(o)?new Promise(l=>{let a=Xi(o),u=Vi("npx",["playwright","test",o,"--reporter=line"],{cwd:n,env:{...process.env,FORCE_COLOR:"0"}}),p="",d="";u.stdout.on("data",m=>{p+=m.toString()}),u.stderr.on("data",m=>{d+=m.toString()});let f=setTimeout(()=>{u.kill("SIGTERM"),l({success:!1,executionCount:s,error:"Test timed out after 60 seconds",stdout:p.slice(-2e3),stderr:d.slice(-1e3)})},6e4);u.on("close",m=>{clearTimeout(f);let g=`${p}
270
+ `;let{dirname:p}=await import("path"),{mkdirSync:d}=await import("fs");return d(p(e),{recursive:!0}),await tt.writeFile(e,a,"utf-8"),console.log(`[TestPostProcessor] \u2705 Generated test with ${o.filter(f=>["type","fill","click","select_option"].includes(f.type)).length} actions`),!0}catch(n){return console.warn("[TestPostProcessor] Failed to generate from events:",n.message),!1}}static async enhanceSelectorsWithTrace(e,t,r){try{console.log("[TestPostProcessor] \u{1F6E1}\uFE0F Applying Zibby Safe Action Wrappers...");let s=await tt.readFile(e,"utf-8");s.includes("ZibbyRuntime")||(s=`import { ZibbyRuntime } from '@zibby/core';
271
+ ${s}`);for(let n=0;n<t.length;n++){let o=t[n],c=`element${n}`,l=new RegExp(`const ${c}\\b\\s*=\\s*page\\.[^;]+;(\\s*await ${c}\\.waitFor\\([^)]*\\);)?\\s*await ${c}\\.(click|fill|type|selectOption|pressSequentially)\\(([^)]*)\\);`,"s"),a=s.match(l);if(!a)continue;let u={name:o.name||`Action ${n}`,action:o.method==="type"?"fill":o.method,value:a[3].trim().replace(/^['"]|['"]$/g,""),strategies:o.strategies||[]},p=`await ZibbyRuntime.step(page, ${JSON.stringify(u,null,2)});`;s=s.replace(a[0],p)}return await tt.writeFile(e,s,"utf-8"),console.log("[TestPostProcessor] \u2705 Successfully converted test to Resilient Zibby format"),!0}catch(s){return console.warn("[TestPostProcessor] Failed to apply safe wrappers:",s.message),!1}}static async enhanceSelectors(e,t){try{let{actions:r=[]}=t;if(!r.length)return!1;let s=await tt.readFile(e,"utf-8"),n=this.buildSelectorMap(r);return s=this.replaceSimpleSelectors(s,n),await tt.writeFile(e,s,"utf-8"),!0}catch(r){return console.warn("Failed to enhance selectors:",r),!1}}static buildSelectorMap(e){let t=new Map;for(let r=0;r<e.length;r++){let s=e[r];if(!s.selectors||s.type==="navigate")continue;let n=`element${r}`,c=et.generate(s,n).match(/= (.+);/s);if(c){let l=c[1].trim(),a=`${s.type}:${this.normalizeDescription(s.description)}`;t.set(a,l),s.selectors.role&&t.set(`role:${s.selectors.role.name}`,l),s.selectors.attributes?.placeholder&&t.set(`placeholder:${s.selectors.attributes.placeholder}`,l)}}return t}static replaceSimpleSelectors(e,t){let r=e,s=[/await page\.(getByRole|getByPlaceholder|getByText|getByLabel|locator)\([^)]+\)\.(fill|click|type)\([^)]*\)/g];for(let n of s)r=r.replace(n,o=>{for(let[c,l]of t.entries())if(o.includes(c.split(":")[1])){let a=o.match(/\.(fill|click|type)\(([^)]*)\)/);if(a){let[,u,p]=a,d="element";return`const ${d} = ${l};
272
+ await ${d}.${u}(${p})`}}return o});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as ki,existsSync as qs,readdirSync as Qs}from"node:fs";import{join as gr}from"node:path";import{execSync as Mi}from"node:child_process";import{tmpdir as Li}from"node:os";var rt=class{static async parseTraceZip(e){let t;if(e.endsWith(".zip")&&qs(e)){let r=gr(Li(),`trace-${Date.now()}`);Mi(`unzip -q "${e}" -d "${r}"`,{stdio:"pipe"});let n=Qs(r).find(o=>o.endsWith(".trace"));if(!n)throw new Error("No .trace file found in zip");t=gr(r,n)}else if(qs(e)){let s=Qs(e).find(n=>n.endsWith(".trace"));if(!s)throw new Error("No .trace file found");t=gr(e,s)}else throw new Error(`Trace not found at ${e}`);try{let s=ki(t,"utf-8").trim().split(`
273
+ `),n=[],o=new Map,c=new Map;for(let l of s)try{let a=JSON.parse(l);if(a.type==="snapshot"&&a.snapshot&&a.snapshot.accessibility){let u=new Map;for(let p of a.snapshot.accessibility)p.ref&&u.set(p.ref,p);o.set(a.snapshotName,u)}if(a.type==="frame-snapshot"&&a.snapshot){let u=Buffer.from(a.snapshot.html||"","base64").toString("utf-8");u&&u.length>100&&c.set(a.pageId||"default",u)}}catch{}for(let l of s)try{let a=JSON.parse(l);if(a.type==="before"&&a.params&&a.params.selector){let u=a.method;if(["click","fill","type","selectOption"].includes(u)){let p=a.params.selector,d=a.params.text||a.params.value||"",f=[],m=null,S=null,h=null,_=p.match(/aria-ref=([a-z0-9]+)/i);if(_&&a.snapshotName){let b=_[1],C=o.get(a.snapshotName);if(C&&C.has(b)){let O=C.get(b);m=O.name||null,S=O.role||null,h=O.label||null,console.log(`[TraceParser] \u2705 Found ACTUAL element data: text="${m}", role="${S}"`)}}let y=p.match(/internal:text="([^"]+)"/i),x=p.match(/internal:label="([^"]+)"/i),E=p.match(/internal:placeholder="([^"]+)"/i),T=p.match(/internal:role=([^ ]+)/i),v=p.match(/internal:describe="([^"]+)"/i),I=p.match(/name="([^"]+)"/i);if(y){f.push({type:"text",text:y[1]});let b=y[1].split(" ");b.length>1&&(f.push({type:"text",text:b[0],fuzzy:!0}),f.push({type:"text",text:b[b.length-1],fuzzy:!0}))}if(x&&f.push({type:"label",label:x[1]}),E&&f.push({type:"placeholder",placeholder:E[1]}),m){f.unshift({type:"text",text:m,source:"accessibility-tree"});let b=m.split(" ");b.length>1&&f.push({type:"text",text:b[0],fuzzy:!0,source:"accessibility-tree"})}if(S||T){let b=S||T[1],C=m||(I?I[1]:y?y[1]:null);f.unshift({type:"role",role:b,name:C,source:m?"accessibility-tree":"selector"})}if(h&&f.unshift({type:"label",label:h,source:"accessibility-tree"}),v){let b=v[1],C=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],O=null,w=b;for(let $ of C)if(b.toLowerCase().endsWith(` ${$}`)){O=$.replace(" ",""),w=b.substring(0,b.length-$.length-1);break}if(O){f.push({type:"role",role:O,name:w});let $=w.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:$}),f.push({type:"text",text:w});let N=w.split(" ");N.length>1&&(f.push({type:"text",text:N[0],fuzzy:!0}),f.push({type:"text",text:N.slice(0,2).join(" "),fuzzy:!0}))}else{let $=b.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:$}),f.push({type:"text",text:b})}}let A=this.extractDOMStrategies(p,c,y?.[1]||v?.[1],a.pageId);f.push(...A);let P=this.extractStructuralContext(p);(P.parent||P.sibling)&&f.forEach(b=>{["role","text","label","testid"].includes(b.type)&&(P.parent&&(b.parent=P.parent),P.sibling&&(b.sibling=P.sibling))}),f.push({type:"css",value:p});let k=m||y?y[1]:v?v[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${n.length}`;n.push({method:u,name:k,action:u==="type"?"fill":u,value:d,strategies:f,timestamp:a.startTime,actualText:m,actualRole:S,actualAriaLabel:h})}}}catch{}return n}catch(r){throw new Error(`Failed to parse trace: ${r.message}`,{cause:r})}}static extractDOMStrategies(e,t,r,s){let n=[];if(!t||t.size===0||!r)return n;try{let o=t.get(s);if(!o)return n;let c=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),a=o.match(l);a&&n.push({type:"testid",value:a[1],priority:"high"});let u=new RegExp(`class=["']([^"']+)["'][^>]*>[^<]*${c}`,"gi"),p=o.matchAll(u);for(let m of p){let S=m[1].split(/\s+/).filter(h=>h&&!h.match(/^(css|jss|makeStyles|MuiBox|MuiStack)-\w+/)&&h.length>2);S.length>0&&(n.push({type:"class",value:S.join("."),priority:"medium"}),S.length===1&&n.push({type:"class",value:S[0],priority:"medium"}))}let d=new RegExp(`id=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),f=o.match(d);f&&!f[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&n.push({type:"id",value:f[1],priority:"high"})}catch(o){console.warn(`[TraceParser] DOM extraction failed: ${o.message}`)}return n}static extractStructuralContext(e){let t={parent:null,sibling:null},r=e.split(">>").map(o=>o.trim());if(r.length>1){let c=r[r.length-2].replace(/internal:text="[^"]+"\s*/gi,"").replace(/internal:role=\S+\s*/gi,"").replace(/internal:label="[^"]+"\s*/gi,"").trim();c&&(c.match(/^(form|section|nav|header|aside|main|article)\b/)||c.includes("[")||c.match(/[#.]\w/))&&(t.parent=c)}let n=r[r.length-1].match(/([^+~]+)\s*[+~]\s*(.+)/);return n&&(t.sibling=n[1].trim()),t}};Je();var hr=class{static async step(e,t){let{name:r,action:s,value:n,strategies:o,options:c={timeout:1e4},enrichedData:l}=t;console.log(`[Zibby] \u26A1 Executing step: ${r}`),await this.waitForPageStability(e,c.timeout);let a=await this.findBestMatch(e,o,r);if(!a)throw new Error(`[Zibby] \u274C Failed to find "${r}" using ${o.length} strategies`);l?.position&&await this.verifyPosition(a,l.position),await this.performActionWithRetry(e,a,s,n,3),console.log(`[Zibby] \u2728 Step "${r}" completed.`)}static async waitForPageStability(e,t=1e4){try{await e.waitForLoadState("networkidle",{timeout:3e3}).catch(()=>{}),await e.evaluate(()=>new Promise(r=>{let s,n=new MutationObserver(()=>{clearTimeout(s),s=setTimeout(()=>{n.disconnect(),r()},500)});n.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),s=setTimeout(()=>{n.disconnect(),r()},500)})).catch(()=>{})}catch{}}static async verifyPosition(e,t){try{let r=await e.boundingBox();if(!r)return;let s=Math.abs(r.x-t.x),n=Math.abs(r.y-t.y);(s>50||n>50)&&(console.log(`[Zibby] \u26A0\uFE0F Element moved: expected (${t.x}, ${t.y}), got (${r.x}, ${r.y})`),await new Promise(o=>setTimeout(o,500)))}catch{}}static async performActionWithRetry(e,t,r,s,n=3){for(let o=1;o<=n;o++)try{r==="click"?await t.click():r==="fill"?await t.fill(s||""):r==="type"?await t.pressSequentially(s||""):r==="selectOption"&&await t.selectOption(s||"");return}catch(c){if(o===n)throw c;console.log(`[Zibby] \u26A0\uFE0F Action failed (attempt ${o}/${n}), retrying...`),await new Promise(l=>setTimeout(l,1e3*o))}}static async findBestMatch(e,t,r){let n=Date.now(),o=t.map(async(a,u)=>{try{let d=await this.getLocator(e,a).all();return d.length===0?[]:(await Promise.all(d.map(async(m,S)=>{try{if(!await m.isVisible({timeout:100}))return null;let _=await this.scoreCandidate(m,a,e);return{element:m,strategy:a,score:_,strategyIdx:u,elIdx:S}}catch{return null}}))).filter(m=>m!==null)}catch{return[]}}),c=(await Promise.all(o)).flat();if(c.length===0)return console.log(`[Zibby] \u274C No visible candidates found for "${r}"`),null;c.sort((a,u)=>u.score-a.score);let l=c[0];return console.log(`[Zibby] \u2705 Found element using ${l.strategy.type} (score: ${l.score.toFixed(2)}, ${c.length} candidates)`),l.element}static async scoreCandidate(e,t,r){let s=0;if(s+={testid:120,id:110,role:100,label:90,class:85,placeholder:85,text:80,css:50}[t.type]||50,t.priority==="high"&&(s+=20),t.priority==="medium"&&(s+=10),t.fuzzy&&(s-=15),t.parent)try{await e.locator("xpath=ancestor::*").first().evaluate((l,a)=>l.matches(a),t.parent)&&(s+=30)}catch{}if(t.sibling)try{await e.evaluate((c,l)=>c.parentElement?.querySelector(l)!==null,t.sibling)&&(s+=20)}catch{}try{let o=await e.boundingBox();o&&o.y<1e3&&(s+=10)}catch{}try{let o=await e.evaluate(c=>{let l=0,a=c;for(;a;)a.tagName==="IFRAME"&&l++,a=a.parentElement;return l});s-=o*5}catch{}return s}static getLocator(e,t){let r;switch(t.type){case"testid":r=e.getByTestId(t.value);break;case"id":r=e.locator(`#${t.value}`);break;case"class":r=e.locator(`.${t.value.replace(/\./g,".")}`);break;case"text":t.fuzzy?r=e.getByText(new RegExp(t.text,"i")):r=e.getByText(t.text,{exact:!1});break;case"role":r=e.getByRole(t.role,{name:t.name,exact:!1});break;case"label":r=e.getByLabel(t.label,{exact:!1});break;case"placeholder":r=e.getByPlaceholder(t.placeholder);break;default:{let s=t.value?.replace(/aria-ref=e\d+ >> /g,"")||t.css;r=e.locator(s);break}}return t.parent&&(r=r.filter({has:e.locator(t.parent)})),r}};var yr=class{static async beforeEach(e){await this.injectStableIds(e),e.on("load",async()=>{await this.injectStableIds(e)})}static async afterNavigation(e){await e.waitForLoadState("domcontentloaded").catch(()=>{}),await this.injectStableIds(e)}static async clickWithRetry(e,t,r={}){let s=r.timeout||1e4,n=`[data-zibby-id="${t}"]`,o=Date.now();for(;Date.now()-o<s;){await this.injectStableIds(e);let c=e.locator(n);if(await c.count()>0)try{await c.click({timeout:2e3});return}catch(l){if(l.message.includes("intercepts pointer")){await c.click({force:!0});return}}await e.waitForTimeout(200)}throw new Error(`Element ${n} not found after ${s}ms`)}static async fillWithRetry(e,t,r,s=1e4){let n=`[data-zibby-id="${t}"]`,o=Date.now();for(;Date.now()-o<s;){await this.injectStableIds(e);let c=e.locator(n);if(await c.count()>0){await c.fill(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${n} not found after ${s}ms`)}static async selectWithRetry(e,t,r,s=1e4){let n=`[data-zibby-id="${t}"]`,o=Date.now();for(;Date.now()-o<s;){await this.injectStableIds(e);let c=e.locator(n);if(await c.count()>0){await c.selectOption(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${n} not found after ${s}ms`)}static async injectStableIds(e){try{await e.evaluate(()=>{function t(l){if(l.getAttribute("aria-label"))return l.getAttribute("aria-label").trim();let a=l.getAttribute("aria-labelledby");if(a){let d=document.getElementById(a);if(d)return d.textContent.trim()}if(l.id){let d=document.querySelector(`label[for="${l.id}"]`);if(d)return d.textContent.trim()}let u=l.closest("label");if(u){let d=u.cloneNode(!0);d.querySelectorAll("input, select, textarea").forEach(m=>m.remove());let f=d.textContent.trim();if(f)return f}if(l.placeholder)return l.placeholder;let p=l.tagName.toLowerCase();return p==="button"||p==="a"||l.getAttribute("role")==="button"?(l.textContent||"").trim().slice(0,50):l.title?l.title:p==="input"&&(l.type==="submit"||l.type==="button")&&l.value||""}function r(l){let a=[],u=l.closest("form");if(u)if(u.id)a.push(`form#${u.id}`);else if(u.name)a.push(`form[name=${u.name}]`);else if(u.action)try{let S=new URL(u.action,window.location.origin).pathname;a.push(`form[action=${S}]`)}catch{a.push(`form[action=${u.getAttribute("action")}]`)}else{let S=document.querySelectorAll("form"),h=Array.from(S).indexOf(u);a.push(`form:nth(${h})`)}let p=l.closest('header, nav, main, footer, aside, [role="banner"], [role="navigation"], [role="main"], [role="contentinfo"]');if(p){let S=p.tagName.toLowerCase(),h=p.getAttribute("role");a.push(h||S)}let d=l.closest('section, article, [role="region"]');if(d){let S=d.querySelector("h1, h2, h3, h4, h5, h6");S&&a.push(`section:${S.textContent.trim().slice(0,30)}`)}let f=l.closest("fieldset");if(f){let S=f.querySelector("legend");S&&a.push(`fieldset:${S.textContent.trim()}`)}let m=l.closest('dialog, [role="dialog"], [role="alertdialog"]');if(m){let S=m.querySelector('[role="heading"], h1, h2, h3');S?a.push(`dialog:${S.textContent.trim().slice(0,30)}`):a.push("dialog")}return a.join("/")}function s(l){let a=l.tagName.toLowerCase(),u=l.id||"",p=l.name||"",d=l.type||"",f=l.getAttribute("role")||"",m="";if(l.href)try{m=new URL(l.href,window.location.origin).pathname.slice(0,50)}catch{m=l.getAttribute("href")?.slice(0,50)||""}let S=t(l).slice(0,50).replace(/\s+/g," "),h=r(l),_=[a,u,p,d,f,m,S,h].join("|"),y=5381;for(let x=0;x<_.length;x++)y=(y<<5)+y^_.charCodeAt(x);return`zibby-${(y>>>0).toString(36)}`}let n=["button","a","input","select","textarea","label[for]",'[role="button"]','[role="link"]','[role="textbox"]','[role="checkbox"]','[role="radio"]','[role="combobox"]','[role="menuitem"]','[role="tab"]','[role="option"]','[role="switch"]','[role="slider"]',"[onclick]","[data-action]"].join(", "),o=new Map,c=0;document.querySelectorAll(n).forEach(l=>{let a=window.getComputedStyle(l);if(a.display==="none"||a.visibility==="hidden")return;let u=s(l),p=u,d=o.get(p)||0;d>0&&(u=`${p}-${d}`),o.set(p,d+1),l.setAttribute("data-zibby-id",u),c++}),console.log(`[Zibby] Injected ${c} stable IDs`)})}catch{}}};q();pe();var Di=8,Bi=1,Ui=64;function Fi(i){if(!i||typeof i!="object")return 8;let e=i.parallel;if(!e||typeof e!="object")return 8;let t=e.maxConcurrentRuns??e.maxConcurrent,r=Number(t);if(!Number.isFinite(r))return 8;let s=Math.floor(r);return s<1?8:Math.min(64,s)}import{readFileSync as Gi,writeFileSync as tn,existsSync as zi}from"node:fs";import{join as rn}from"node:path";var W=class{constructor(e={}){this.config=e,this.enabled=e.enabled!==!1,this.priority=e.priority||50}getName(){throw new Error("EventEnricher.getName() must be implemented")}canEnrich(e){return this.enabled}async enrich(e,t){throw new Error("EventEnricher.enrich() must be implemented")}handleError(e,t){return console.warn(`[${this.getName()}] Enrichment failed for event ${t.type}:`,e.message),null}};import{existsSync as ji}from"node:fs";import{join as en}from"node:path";var Se=class extends W{constructor(e={}){super(e),this.priority=190,this.traceData=null}getName(){return"TraceText"}getPriority(){return this.priority}async loadTrace(e){if(this.traceData)return;let t=en(e,"traces"),r=en(e,"trace.zip");if(ji(r))try{this.traceData=await rt.parseTraceZip(r),console.log(`[TraceTextEnricher] \u2705 Loaded trace with ${this.traceData.length} actions`)}catch(s){console.log(`[TraceTextEnricher] \u26A0\uFE0F Failed to parse trace: ${s.message}`)}}async enrich(e,t){let r=e.data?.params?.ref,s=e.id;if(r===void 0&&s===void 0||(!this.traceData&&t.sessionPath&&await this.loadTrace(t.sessionPath),!this.traceData))return null;let n=this.traceData[s];if(!n)return console.log(`[TraceTextEnricher] \u26A0\uFE0F No trace action for event ${s}`),null;let o=n.actualText||this._extractTextFromSelector(n.selector),c=n.actualRole,l=n.actualAriaLabel;return o||c||l?(console.log(`[TraceTextEnricher] \u2705 Event ${s}: text="${o}", role="${c}", label="${l}"`),{traceActualText:o,traceActualRole:c,traceActualAriaLabel:l,traceSelector:n.selector,traceStrategies:n.strategies}):null}_extractTextFromSelector(e){if(!e)return null;let t=e.match(/internal:label="([^"]+)"/);if(t)return t[1];let r=e.match(/internal:text="([^"]+)"/);if(r)return r[1];let s=e.match(/getByText\(['"]([^'"]+)['"]\)/);if(s)return s[1];let n=e.match(/name:\s*['"]([^'"]+)['"]/);return n?n[1]:null}};async function Ji(i){let e=rn(i,"events.json"),t=rn(i,"events-enriched.json");if(!zi(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(Gi(e,"utf-8")),s=new Se,n=0,o=0;for(let c of r)try{let l=await s.enrich(c,{sessionPath:i});l&&(c.enrichedData={...c.enrichedData||{},...l},n++)}catch(l){console.log(`[PostProcess] Failed to enrich event ${c.id}: ${l.message}`),o++}return n>0&&(tn(t,JSON.stringify(r,null,2)),tn(e,JSON.stringify(r,null,2)),console.log(`[PostProcess] \u2705 Enriched ${n} events (${o} failed)`)),{enriched:n,failed:o}}catch(r){return console.log(`[PostProcess] \u274C Failed to post-process events: ${r.message}`),{enriched:0,failed:0}}}import{spawn as Yi}from"node:child_process";import{existsSync as Wi}from"node:fs";import{dirname as Ki,resolve as sn,relative as Zi}from"node:path";var Ot=new Map,st=8,nn={name:"run_playwright_test",description:`Run a Playwright test file and return results. Use this after writing a test to verify it works. If it fails, fix the issues and run again. Maximum ${st} attempts per session.`,inputSchema:{type:"object",properties:{scriptPath:{type:"string",description:"Path to the Playwright test file (e.g., tests/login.spec.js)"}},required:["scriptPath"]},async execute({scriptPath:i},e){let r=`${e?.sessionId||"default"}:${i}`,s=(Ot.get(r)||0)+1;if(Ot.set(r,s),s>st)return{success:!1,executionCount:s,maxReached:!0,error:`Maximum ${st} executions reached. Stop retrying and return your best result.`};let n=e?.projectRoot||process.cwd(),o=sn(n,i),c=Zi(n,o);return c.startsWith("..")||sn(o)!==o&&c.includes("..")?{success:!1,executionCount:s,error:"Path traversal detected: scriptPath must be within the project root."}:Wi(o)?new Promise(l=>{let a=Ki(o),u=Yi("npx",["playwright","test",o,"--reporter=line"],{cwd:n,env:{...process.env,FORCE_COLOR:"0"}}),p="",d="";u.stdout.on("data",m=>{p+=m.toString()}),u.stderr.on("data",m=>{d+=m.toString()});let f=setTimeout(()=>{u.kill("SIGTERM"),l({success:!1,executionCount:s,error:"Test timed out after 60 seconds",stdout:p.slice(-2e3),stderr:d.slice(-1e3)})},6e4);u.on("close",m=>{clearTimeout(f);let h=`${p}
273
274
  ${d}`.split(`
274
- `),w="",y=null;for(let E=0;E<g.length;E++){let x=g[E];if(x.includes("Error:")||x.includes("error:")||x.includes("\u2718")){w+=`${x}
275
- `;for(let v=E+1;v<Math.min(E+5,g.length);v++)w+=`${g[v]}
276
- `}if(x.includes("at ")&&x.includes(".spec.")){let v=x.match(/:(\d+):\d+/);v&&(y=parseInt(v[1]))}}l(m===0?{success:!0,executionCount:s,message:"All tests passed!",output:p.slice(-500)}:{success:!1,executionCount:s,remainingAttempts:ot-s,error:w.slice(0,1500)||"Test failed (see output)",failedAtLine:y,stdout:p.slice(-1500),stderr:d.slice(-500),hint:s<ot?"Fix the error and run again.":"Last attempt - make your best fix."})}),u.on("error",m=>{clearTimeout(f),l({success:!1,executionCount:s,error:`Failed to run test: ${m.message}`})})}):{success:!1,executionCount:s,error:`Test file not found: ${o}. Make sure you wrote the file first using the write tool.`}},resetCount(i){for(let e of Nt.keys())e.startsWith(`${i}:`)&&Nt.delete(e)}};function ea(i){cn.resetCount(i)}var ie=class{async generate(e){throw new Error("TestGenerationStrategy.generate() must be implemented")}canGenerate(e){throw new Error("TestGenerationStrategy.canGenerate() must be implemented")}getName(){throw new Error("TestGenerationStrategy.getName() must be implemented")}getPriority(){return 0}};import{readFileSync as ln,writeFileSync as ta}from"node:fs";var Re=class extends ie{constructor(){super("mcp-ref","MCP Reference Replay (Exact 1:1)",200)}canGenerate(e){let t=e.eventsPath||`${e.sessionPath}/execute_live/events.json`;try{return JSON.parse(ln(t,"utf-8")).some(n=>n.data?.params?.element)?(console.log("[MCPRefStrategy] \u2705 MCP element descriptions available"),!0):(console.log("[MCPRefStrategy] \u274C No MCP element descriptions found in events"),!1)}catch(r){return console.log("[MCPRefStrategy] \u274C Failed to read events:",r.message),!1}}getName(){return"MCP Reference Replay (Exact 1:1)"}getPriority(){return 200}async generate(e){let{testFilePath:t,sessionPath:r,state:s}=e,n=`${r}/execute_live/events.json`,o=s?.title||"Generated Test";console.log("[MCPRefStrategy] \u{1F3AF} Generating test using MCP element descriptions (1:1 replay)"),console.log(`[MCPRefStrategy] events: ${n}`),console.log(`[MCPRefStrategy] output: ${t}`);let l=JSON.parse(ln(n,"utf-8")).filter(u=>["navigate","type","fill","click","select_option"].includes(u.type)),a=`import { test, expect } from '@playwright/test';
275
+ `),_="",y=null;for(let x=0;x<h.length;x++){let E=h[x];if(E.includes("Error:")||E.includes("error:")||E.includes("\u2718")){_+=`${E}
276
+ `;for(let T=x+1;T<Math.min(x+5,h.length);T++)_+=`${h[T]}
277
+ `}if(E.includes("at ")&&E.includes(".spec.")){let T=E.match(/:(\d+):\d+/);T&&(y=parseInt(T[1]))}}l(m===0?{success:!0,executionCount:s,message:"All tests passed!",output:p.slice(-500)}:{success:!1,executionCount:s,remainingAttempts:st-s,error:_.slice(0,1500)||"Test failed (see output)",failedAtLine:y,stdout:p.slice(-1500),stderr:d.slice(-500),hint:s<st?"Fix the error and run again.":"Last attempt - make your best fix."})}),u.on("error",m=>{clearTimeout(f),l({success:!1,executionCount:s,error:`Failed to run test: ${m.message}`})})}):{success:!1,executionCount:s,error:`Test file not found: ${o}. Make sure you wrote the file first using the write tool.`}},resetCount(i){for(let e of Ot.keys())e.startsWith(`${i}:`)&&Ot.delete(e)}};function Hi(i){nn.resetCount(i)}var ce=class{async generate(e){throw new Error("TestGenerationStrategy.generate() must be implemented")}canGenerate(e){throw new Error("TestGenerationStrategy.canGenerate() must be implemented")}getName(){throw new Error("TestGenerationStrategy.getName() must be implemented")}getPriority(){return 0}};import{readFileSync as on,writeFileSync as Vi}from"node:fs";var ke=class extends ce{constructor(){super("mcp-ref","MCP Reference Replay (Exact 1:1)",200)}canGenerate(e){let t=e.eventsPath||`${e.sessionPath}/execute_live/events.json`;try{return JSON.parse(on(t,"utf-8")).some(n=>n.data?.params?.element)?(console.log("[MCPRefStrategy] \u2705 MCP element descriptions available"),!0):(console.log("[MCPRefStrategy] \u274C No MCP element descriptions found in events"),!1)}catch(r){return console.log("[MCPRefStrategy] \u274C Failed to read events:",r.message),!1}}getName(){return"MCP Reference Replay (Exact 1:1)"}getPriority(){return 200}async generate(e){let{testFilePath:t,sessionPath:r,state:s}=e,n=`${r}/execute_live/events.json`,o=s?.title||"Generated Test";console.log("[MCPRefStrategy] \u{1F3AF} Generating test using MCP element descriptions (1:1 replay)"),console.log(`[MCPRefStrategy] events: ${n}`),console.log(`[MCPRefStrategy] output: ${t}`);let l=JSON.parse(on(n,"utf-8")).filter(u=>["navigate","type","fill","click","select_option"].includes(u.type)),a=`import { test, expect } from '@playwright/test';
277
278
  `;a+=`import { ZibbyRuntime } from '@zibby/core';
278
279
 
279
280
  `,a+=`test('${o}', async ({ page }) => {
280
281
  `,a+=` const timestamp = Date.now();
281
282
 
282
- `;for(let u of l){let p=u.data?.params?.element||"element",d=u.data?.params?.ref,f=u.enrichedData?.traceActualText,m=u.enrichedData?.traceActualRole,S=u.enrichedData?.traceActualAriaLabel,g=u.enrichedData?.actualText,w=f||g,y=m||u.enrichedData?.actualRole,E=w||p,x=w||this._extractName(p),v=y||this._extractRole(p),$=f?" [accessibility-tree]":g?" [live]":" [AI]";if(u.type==="navigate")a+=` await page.goto('${u.data.params.url}');
283
+ `;for(let u of l){let p=u.data?.params?.element||"element",d=u.data?.params?.ref,f=u.enrichedData?.traceActualText,m=u.enrichedData?.traceActualRole,S=u.enrichedData?.traceActualAriaLabel,h=u.enrichedData?.actualText,_=f||h,y=m||u.enrichedData?.actualRole,x=_||p,E=_||this._extractName(p),T=y||this._extractRole(p),v=f?" [accessibility-tree]":h?" [live]":" [AI]";if(u.type==="navigate")a+=` await page.goto('${u.data.params.url}');
283
284
 
284
- `;else if(u.type==="click")a+=` // ${p}${w?` (actual: "${w}")${$}`:""}
285
+ `;else if(u.type==="click")a+=` // ${p}${_?` (actual: "${_}")${v}`:""}
285
286
  `,a+=` await ZibbyRuntime.step(page, {
286
287
  `,a+=` name: '${this._escapeString(p)}',
287
288
  `,a+=` action: 'click',
288
289
  `,a+=` strategies: [
289
- `,a+=` { type: 'role', role: '${v}', name: '${this._escapeString(x)}' },
290
- `,a+=` { type: 'text', text: '${this._escapeString(x)}' }
290
+ `,a+=` { type: 'role', role: '${T}', name: '${this._escapeString(E)}' },
291
+ `,a+=` { type: 'text', text: '${this._escapeString(E)}' }
291
292
  `,a+=` ]
292
293
  `,a+=` });
293
294
 
294
- `;else if(u.type==="fill"||u.type==="type"){let T=u.data.params.text;a+=` // ${p}${w?` (actual: "${w}")${$}`:""}
295
+ `;else if(u.type==="fill"||u.type==="type"){let I=u.data.params.text;a+=` // ${p}${_?` (actual: "${_}")${v}`:""}
295
296
  `,a+=` await ZibbyRuntime.step(page, {
296
297
  `,a+=` name: '${this._escapeString(p)}',
297
298
  `,a+=` action: 'fill',
298
- `,a+=` value: '${this._escapeString(T)}',
299
+ `,a+=` value: '${this._escapeString(I)}',
299
300
  `,a+=` strategies: [
300
- `,a+=` { type: 'role', role: '${v}', name: '${this._escapeString(x)}' },
301
- `,a+=` { type: 'attributes', placeholder: '${this._escapeString(x)}' }
301
+ `,a+=` { type: 'role', role: '${T}', name: '${this._escapeString(E)}' },
302
+ `,a+=` { type: 'attributes', placeholder: '${this._escapeString(E)}' }
302
303
  `,a+=` ]
303
304
  `,a+=` });
304
305
 
305
- `}else if(u.type==="select_option"){let T=u.data.params.values,I=Array.isArray(T)?T[0]:T;a+=` // ${p}${w?` (actual: "${w}")${$}`:""}
306
+ `}else if(u.type==="select_option"){let I=u.data.params.values,A=Array.isArray(I)?I[0]:I;a+=` // ${p}${_?` (actual: "${_}")${v}`:""}
306
307
  `,a+=` await ZibbyRuntime.step(page, {
307
308
  `,a+=` name: '${this._escapeString(p)}',
308
309
  `,a+=` action: 'select',
309
- `,a+=` value: '${this._escapeString(I)}',
310
+ `,a+=` value: '${this._escapeString(A)}',
310
311
  `,a+=` strategies: [
311
- `,a+=` { type: 'role', role: 'combobox', name: '${this._escapeString(x)}' }
312
+ `,a+=` { type: 'role', role: 'combobox', name: '${this._escapeString(E)}' }
312
313
  `,a+=` ]
313
314
  `,a+=` });
314
315
 
315
316
  `}}return a+=`});
316
- `,ta(t,a),console.log(`[MCPRefStrategy] \u2705 Generated test with ${l.length} actions using MCP descriptions`),{success:!0,testPath:t,method:"MCP Reference Replay (1:1)",actionsGenerated:l.length}}_extractRole(e){let t=e.toLowerCase();return t.includes("button")?"button":t.includes("textbox")?"textbox":t.includes("link")?"link":t.includes("checkbox")?"checkbox":t.includes("radio")?"radio":t.includes("combobox")?"combobox":t.includes("heading")?"heading":"button"}_extractName(e){return e.replace(/\s+(button|textbox|link|checkbox|radio|combobox)$/i,"").trim()}_escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}};import{readFileSync as un,writeFileSync as ra}from"node:fs";var ke=class extends ie{constructor(){super("stable-id","Stable ID Injection (Experimental)",300)}canGenerate(e){let t=e.eventsPath||`${e.sessionPath}/execute_live/events.json`;try{return JSON.parse(un(t,"utf-8")).some(n=>n.stableId||n.data?.stableId)?(console.log("[StableIdStrategy] \u2705 Stable IDs available"),!0):(console.log("[StableIdStrategy] \u274C No stable IDs found in events"),!1)}catch(r){return console.log("[StableIdStrategy] \u274C Failed to read events:",r.message),!1}}getName(){return"Stable ID Injection (Experimental)"}getPriority(){return 300}async generate(e){let{testFilePath:t,sessionPath:r,state:s}=e,n=`${r}/execute_live/events.json`,o=s?.title||"Generated Test";console.log("[StableIdStrategy] \u{1F3AF} Generating test using stable IDs"),console.log(`[StableIdStrategy] events: ${n}`),console.log(`[StableIdStrategy] output: ${t}`);let l=JSON.parse(un(n,"utf-8")).filter(d=>["navigate","type","fill","click","select_option","select"].includes(d.type)),a=`import { test, expect } from '@playwright/test';
317
+ `,Vi(t,a),console.log(`[MCPRefStrategy] \u2705 Generated test with ${l.length} actions using MCP descriptions`),{success:!0,testPath:t,method:"MCP Reference Replay (1:1)",actionsGenerated:l.length}}_extractRole(e){let t=e.toLowerCase();return t.includes("button")?"button":t.includes("textbox")?"textbox":t.includes("link")?"link":t.includes("checkbox")?"checkbox":t.includes("radio")?"radio":t.includes("combobox")?"combobox":t.includes("heading")?"heading":"button"}_extractName(e){return e.replace(/\s+(button|textbox|link|checkbox|radio|combobox)$/i,"").trim()}_escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}};import{readFileSync as an,writeFileSync as Xi}from"node:fs";var Me=class extends ce{constructor(){super("stable-id","Stable ID Injection (Experimental)",300)}canGenerate(e){let t=e.eventsPath||`${e.sessionPath}/execute_live/events.json`;try{return JSON.parse(an(t,"utf-8")).some(n=>n.stableId||n.data?.stableId)?(console.log("[StableIdStrategy] \u2705 Stable IDs available"),!0):(console.log("[StableIdStrategy] \u274C No stable IDs found in events"),!1)}catch(r){return console.log("[StableIdStrategy] \u274C Failed to read events:",r.message),!1}}getName(){return"Stable ID Injection (Experimental)"}getPriority(){return 300}async generate(e){let{testFilePath:t,sessionPath:r,state:s}=e,n=`${r}/execute_live/events.json`,o=s?.title||"Generated Test";console.log("[StableIdStrategy] \u{1F3AF} Generating test using stable IDs"),console.log(`[StableIdStrategy] events: ${n}`),console.log(`[StableIdStrategy] output: ${t}`);let l=JSON.parse(an(n,"utf-8")).filter(d=>["navigate","type","fill","click","select_option","select"].includes(d.type)),a=`import { test, expect } from '@playwright/test';
317
318
  `;a+=`import { StableIdRuntime } from '@zibby/core';
318
319
 
319
320
  `,a+=`test('${o}', async ({ page }) => {
320
- `;let u=!1,p=null;for(let d=0;d<l.length;d++){let f=l[d],m=f.stableId||f.data?.stableId,S=f.data?.element||f.data?.params?.element||"element";if(f.type==="click"&&m&&m===p){console.log(`[StableIdStrategy] Skipping duplicate click on ${m}`);continue}if(f.type==="navigate"){let g=f.data?.url||f.data?.params?.url;g&&!u&&(a+=` await page.goto('${g}');
321
+ `;let u=!1,p=null;for(let d=0;d<l.length;d++){let f=l[d],m=f.stableId||f.data?.stableId,S=f.data?.element||f.data?.params?.element||"element";if(f.type==="click"&&m&&m===p){console.log(`[StableIdStrategy] Skipping duplicate click on ${m}`);continue}if(f.type==="navigate"){let h=f.data?.url||f.data?.params?.url;h&&!u&&(a+=` await page.goto('${h}');
321
322
  `,a+=` await StableIdRuntime.injectStableIds(page);
322
323
 
323
324
  `)}else if(f.type==="click")if(u=!0,p=m,m)a+=` await StableIdRuntime.clickWithRetry(page, '${m}');
324
- `;else{let g=this._generateSemanticSelector(S);a+=` await ${g}.click();
325
+ `;else{let h=this._generateSemanticSelector(S);a+=` await ${h}.click();
325
326
  `,a+=` await StableIdRuntime.afterNavigation(page);
326
- `}else if(f.type==="fill"||f.type==="type"){u=!1;let g=f.data?.text||f.data?.params?.text||"";m?a+=` await StableIdRuntime.fillWithRetry(page, '${m}', '${this._escapeString(g)}');
327
- `:a+=` await page.getByPlaceholder('${this._escapeString(S)}').fill('${this._escapeString(g)}');
328
- `}else if(f.type==="select_option"||f.type==="select"){u=!1;let g=f.data?.values||f.data?.params?.values,w=Array.isArray(g)?g[0]:g||"";m?a+=` await StableIdRuntime.selectWithRetry(page, '${m}', '${this._escapeString(w)}');
329
- `:a+=` await page.locator('select').selectOption('${this._escapeString(w)}');
327
+ `}else if(f.type==="fill"||f.type==="type"){u=!1;let h=f.data?.text||f.data?.params?.text||"";m?a+=` await StableIdRuntime.fillWithRetry(page, '${m}', '${this._escapeString(h)}');
328
+ `:a+=` await page.getByPlaceholder('${this._escapeString(S)}').fill('${this._escapeString(h)}');
329
+ `}else if(f.type==="select_option"||f.type==="select"){u=!1;let h=f.data?.values||f.data?.params?.values,_=Array.isArray(h)?h[0]:h||"";m?a+=` await StableIdRuntime.selectWithRetry(page, '${m}', '${this._escapeString(_)}');
330
+ `:a+=` await page.locator('select').selectOption('${this._escapeString(_)}');
330
331
  `}}return a+=`});
331
- `,ra(t,a),console.log(`[StableIdStrategy] \u2705 Generated test with ${l.length} actions using stable IDs`),{success:!0,testPath:t,method:"Stable ID Injection (Experimental)",actionsGenerated:l.length}}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}_generateSemanticSelector(e){let t=e.toLowerCase(),r="locator",s=e;return t.includes("button")?(r="button",s=e.replace(/\s*button\s*/gi,"").trim()):t.includes("link")?(r="link",s=e.replace(/\s*link\s*/gi,"").trim()):t.includes("textbox")?(r="textbox",s=e.replace(/\s*textbox\s*/gi,"").trim()):t.includes("checkbox")?(r="checkbox",s=e.replace(/\s*checkbox\s*/gi,"").trim()):(t.includes("combobox")||t.includes("dropdown")||t.includes("select"))&&(r="combobox",s=e.replace(/\s*(combobox|dropdown|select)\s*/gi,"").trim()),r!=="locator"&&s?`page.getByRole('${r}', { name: '${this._escapeString(s)}' })`:`page.getByText('${this._escapeString(e)}')`}};var br=class{constructor(){this.strategies=[new ke,new Re],this.strategies.sort((e,t)=>t.getPriority()-e.getPriority())}registerStrategy(e){this.strategies.push(e),this.strategies.sort((t,r)=>r.getPriority()-t.getPriority())}async generate(e){console.log(`
332
+ `,Xi(t,a),console.log(`[StableIdStrategy] \u2705 Generated test with ${l.length} actions using stable IDs`),{success:!0,testPath:t,method:"Stable ID Injection (Experimental)",actionsGenerated:l.length}}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}_generateSemanticSelector(e){let t=e.toLowerCase(),r="locator",s=e;return t.includes("button")?(r="button",s=e.replace(/\s*button\s*/gi,"").trim()):t.includes("link")?(r="link",s=e.replace(/\s*link\s*/gi,"").trim()):t.includes("textbox")?(r="textbox",s=e.replace(/\s*textbox\s*/gi,"").trim()):t.includes("checkbox")?(r="checkbox",s=e.replace(/\s*checkbox\s*/gi,"").trim()):(t.includes("combobox")||t.includes("dropdown")||t.includes("select"))&&(r="combobox",s=e.replace(/\s*(combobox|dropdown|select)\s*/gi,"").trim()),r!=="locator"&&s?`page.getByRole('${r}', { name: '${this._escapeString(s)}' })`:`page.getByText('${this._escapeString(e)}')`}};var Sr=class{constructor(){this.strategies=[new Me,new ke],this.strategies.sort((e,t)=>t.getPriority()-e.getPriority())}registerStrategy(e){this.strategies.push(e),this.strategies.sort((t,r)=>r.getPriority()-t.getPriority())}async generate(e){console.log(`
332
333
  \u{1F4CB} Available generation strategies (${this.strategies.length}):`),this.strategies.forEach(t=>{let r=t.canGenerate(e);console.log(` ${r?"\u2713":"\u2717"} ${t.getName()} (priority: ${t.getPriority()})`)});for(let t of this.strategies)if(t.canGenerate(e))return console.log(`
333
- \u{1F3AF} Selected: ${t.getName()}`),t.generate(e);throw new Error("No generation strategy available for this context")}getStrategy(e){return this.strategies.find(t=>t.getName().includes(e))||null}},sa=new br;var Me=class{async verify(e){throw new Error("TestVerificationStrategy.verify() must be implemented")}canVerify(e){throw new Error("TestVerificationStrategy.canVerify() must be implemented")}getName(){throw new Error("TestVerificationStrategy.getName() must be implemented")}getPriority(){return 0}};import{execSync as na}from"node:child_process";import{existsSync as oa}from"node:fs";var Le=class extends Me{getName(){return"Playwright JSON Reporter"}getPriority(){return 100}canVerify(e){let{testFilePath:t}=e;return oa(t)}async verify(e){let{testFilePath:t,cwd:r,timeout:s=3e4}=e;try{console.log(`\u{1F9EA} Running test: ${t}`);let n=`npx playwright test ${t} --reporter=json --timeout=${s}`,o=na(n,{cwd:r,encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:s+1e4}),l=JSON.parse(o).stats||{};return{success:l.unexpected===0,passed:l.expected||0,failed:l.unexpected||0,error:null,errorDetails:null}}catch(n){let o=n.stdout||n.stderr||n.message;try{let c=JSON.parse(o),l=c.stats||{},a="Test execution failed";if(c.suites&&c.suites.length>0){let p=c.suites[0];if(p.specs&&p.specs.length>0){let d=p.specs[0];if(d.tests&&d.tests.length>0){let f=d.tests[0];if(f.results&&f.results.length>0){let m=f.results[0];m.error&&(a=m.error.message||a)}}}}let u=a.includes("Executable doesn't exist")||a.includes("browserType.launch")||a.includes("Please run the following command")||a.includes("npx playwright install")||o.includes("Executable doesn't exist")||o.includes("npx playwright install");return{success:!1,passed:l.expected||0,failed:l.unexpected||0,error:a,errorDetails:a,isEnvironmentError:u}}catch{let l=o.match(/Error: (.+)/),a=l?l[1]:"Test execution failed",u=a.includes("Executable doesn't exist")||a.includes("browserType.launch")||a.includes("Please run the following command")||a.includes("npx playwright install")||o.includes("Executable doesn't exist")||o.includes("npx playwright install");return{success:!1,passed:0,failed:1,error:a,errorDetails:a,isEnvironmentError:u}}}}};var xr=class{constructor(){this.strategies=[new Le],this.strategies.sort((e,t)=>t.getPriority()-e.getPriority())}registerStrategy(e){this.strategies.push(e),this.strategies.sort((t,r)=>r.getPriority()-t.getPriority())}async verify(e){console.log(`
334
+ \u{1F3AF} Selected: ${t.getName()}`),t.generate(e);throw new Error("No generation strategy available for this context")}getStrategy(e){return this.strategies.find(t=>t.getName().includes(e))||null}},qi=new Sr;var Le=class{async verify(e){throw new Error("TestVerificationStrategy.verify() must be implemented")}canVerify(e){throw new Error("TestVerificationStrategy.canVerify() must be implemented")}getName(){throw new Error("TestVerificationStrategy.getName() must be implemented")}getPriority(){return 0}};import{execSync as Qi}from"node:child_process";import{existsSync as ea}from"node:fs";var De=class extends Le{getName(){return"Playwright JSON Reporter"}getPriority(){return 100}canVerify(e){let{testFilePath:t}=e;return ea(t)}async verify(e){let{testFilePath:t,cwd:r,timeout:s=3e4}=e;try{console.log(`\u{1F9EA} Running test: ${t}`);let n=`npx playwright test ${t} --reporter=json --timeout=${s}`,o=Qi(n,{cwd:r,encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:s+1e4}),l=JSON.parse(o).stats||{};return{success:l.unexpected===0,passed:l.expected||0,failed:l.unexpected||0,error:null,errorDetails:null}}catch(n){let o=n.stdout||n.stderr||n.message;try{let c=JSON.parse(o),l=c.stats||{},a="Test execution failed";if(c.suites&&c.suites.length>0){let p=c.suites[0];if(p.specs&&p.specs.length>0){let d=p.specs[0];if(d.tests&&d.tests.length>0){let f=d.tests[0];if(f.results&&f.results.length>0){let m=f.results[0];m.error&&(a=m.error.message||a)}}}}let u=a.includes("Executable doesn't exist")||a.includes("browserType.launch")||a.includes("Please run the following command")||a.includes("npx playwright install")||o.includes("Executable doesn't exist")||o.includes("npx playwright install");return{success:!1,passed:l.expected||0,failed:l.unexpected||0,error:a,errorDetails:a,isEnvironmentError:u}}catch{let l=o.match(/Error: (.+)/),a=l?l[1]:"Test execution failed",u=a.includes("Executable doesn't exist")||a.includes("browserType.launch")||a.includes("Please run the following command")||a.includes("npx playwright install")||o.includes("Executable doesn't exist")||o.includes("npx playwright install");return{success:!1,passed:0,failed:1,error:a,errorDetails:a,isEnvironmentError:u}}}}};var wr=class{constructor(){this.strategies=[new De],this.strategies.sort((e,t)=>t.getPriority()-e.getPriority())}registerStrategy(e){this.strategies.push(e),this.strategies.sort((t,r)=>r.getPriority()-t.getPriority())}async verify(e){console.log(`
334
335
  \u{1F4CB} Available verification strategies (${this.strategies.length}):`),this.strategies.forEach(t=>{let r=t.canVerify(e);console.log(` ${r?"\u2713":"\u2717"} ${t.getName()} (priority: ${t.getPriority()})`)});for(let t of this.strategies)if(t.canVerify(e))return console.log(`
335
- \u{1F3AF} Selected: ${t.getName()}`),t.verify(e);throw new Error("No verification strategy available for this context")}getStrategy(e){return this.strategies.find(t=>t.getName().includes(e))||null}},ia=new xr;var ae=class{constructor(e={}){this.enrichers=[],this.config=e,this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}register(e){return this.enrichers.push(e),this.enrichers.sort((t,r)=>r.getPriority()-t.getPriority()),this}unregister(e){return this.enrichers=this.enrichers.filter(t=>t.getName()!==e),this}get(e){return this.enrichers.find(t=>t.getName()===e)}setEnabled(e,t){let r=this.get(e);return r&&(r.enabled=t),this}async enrich(e,t){this.stats.totalEvents++;let r={...e},s=[],n=[],o=[];for(let c of this.enrichers)try{if(!c.canEnrich(t)){n.push(c.getName());continue}let l=Date.now(),a=await c.enrich(e,t),u=Date.now()-l;a?(Object.assign(r,a),s.push({name:c.getName(),duration:u})):n.push(c.getName())}catch(l){console.warn(`[EnrichmentPipeline] ${c.getName()} failed:`,l.message),o.push(c.getName()),this.stats.errors[c.getName()]=(this.stats.errors[c.getName()]||0)+1}return r._enrichment={version:"1.0",timestamp:new Date().toISOString(),enrichers:{run:s,skipped:n,failed:o}},s.length>0?this.stats.enrichedEvents++:this.stats.skippedEvents++,r}async enrichBatch(e,t){let r=[];for(let s of e){let n=await this.enrich(s,t);r.push(n)}return r}getStats(){return{...this.stats,enrichers:this.enrichers.map(e=>({name:e.getName(),enabled:e.enabled,priority:e.getPriority(),errors:this.stats.errors[e.getName()]||0}))}}resetStats(){this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}logStatus(){console.log(`
336
+ \u{1F3AF} Selected: ${t.getName()}`),t.verify(e);throw new Error("No verification strategy available for this context")}getStrategy(e){return this.strategies.find(t=>t.getName().includes(e))||null}},ta=new wr;var le=class{constructor(e={}){this.enrichers=[],this.config=e,this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}register(e){return this.enrichers.push(e),this.enrichers.sort((t,r)=>r.getPriority()-t.getPriority()),this}unregister(e){return this.enrichers=this.enrichers.filter(t=>t.getName()!==e),this}get(e){return this.enrichers.find(t=>t.getName()===e)}setEnabled(e,t){let r=this.get(e);return r&&(r.enabled=t),this}async enrich(e,t){this.stats.totalEvents++;let r={...e},s=[],n=[],o=[];for(let c of this.enrichers)try{if(!c.canEnrich(t)){n.push(c.getName());continue}let l=Date.now(),a=await c.enrich(e,t),u=Date.now()-l;a?(Object.assign(r,a),s.push({name:c.getName(),duration:u})):n.push(c.getName())}catch(l){console.warn(`[EnrichmentPipeline] ${c.getName()} failed:`,l.message),o.push(c.getName()),this.stats.errors[c.getName()]=(this.stats.errors[c.getName()]||0)+1}return r._enrichment={version:"1.0",timestamp:new Date().toISOString(),enrichers:{run:s,skipped:n,failed:o}},s.length>0?this.stats.enrichedEvents++:this.stats.skippedEvents++,r}async enrichBatch(e,t){let r=[];for(let s of e){let n=await this.enrich(s,t);r.push(n)}return r}getStats(){return{...this.stats,enrichers:this.enrichers.map(e=>({name:e.getName(),enabled:e.enabled,priority:e.getPriority(),errors:this.stats.errors[e.getName()]||0}))}}resetStats(){this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}logStatus(){console.log(`
336
337
  \u{1F4CA} Enrichment Pipeline Status:`),console.log(` Total events: ${this.stats.totalEvents}`),console.log(` Enriched: ${this.stats.enrichedEvents}`),console.log(` Skipped: ${this.stats.skippedEvents}`),console.log(`
337
- Registered enrichers (${this.enrichers.length}):`);for(let e of this.enrichers){let t=e.enabled?"\u2713":"\u2717",r=this.stats.errors[e.getName()]||0,s=r>0?` (${r} errors)`:"";console.log(` ${t} ${e.getName()} (priority: ${e.getPriority()})${s}`)}console.log()}};var De=class extends J{getName(){return"PositionEnricher"}getPriority(){return 90}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:s}=t,n=await s.boundingBox();if(!n)return null;let o=await r.evaluate(()=>({scrollX:window.scrollX,scrollY:window.scrollY,width:window.innerWidth,height:window.innerHeight})),c=n.y>=o.scrollY&&n.y+n.height<=o.scrollY+o.height&&n.x>=0&&n.x+n.width<=o.width;return{position:{boundingBox:n,viewport:o,inViewport:c,centerPoint:{x:Math.round(n.x+n.width/2),y:Math.round(n.y+n.height/2)}}}}catch(r){return this.handleError(r,e)}}};import pn from"node:crypto";var ye=class extends J{getName(){return"AccessibilityEnricher"}getPriority(){return 100}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:s}=t,n=await r.accessibility.snapshot(),o=await this.findAxNode(s,n);if(!o)return null;let c=await this.getAxContext(o,n),l=this.hashAxSubtree(o),a=this.hashAxPath(c.path);return{accessibility:{role:o.role,name:o.name||"",level:c.level,parent:c.parent,siblings:c.siblings,axTreeHash:l,axPathHash:a}}}catch(r){return this.handleError(r,e)}}async findAxNode(e,t){let r=await e.evaluate(s=>({role:s.getAttribute("role")||s.tagName.toLowerCase(),name:s.getAttribute("aria-label")||s.textContent?.trim()||"",tagName:s.tagName.toLowerCase()}));return this.searchAxTree(t,r)}searchAxTree(e,t){if(!e)return null;if(e.role===t.role&&(e.name||"").includes(t.name.substring(0,20)))return e;if(e.children)for(let r of e.children){let s=this.searchAxTree(r,t);if(s)return s}return null}getAxContext(e,t){let r={level:0,parent:null,siblings:[],path:[]},s=this.findParent(e,t);return s&&(r.parent={role:s.role,name:s.name},r.siblings=(s.children||[]).filter(n=>n!==e).map(n=>({role:n.role,name:n.name})).slice(0,3)),r.level=this.calculateLevel(e,t),r.path=this.buildPath(e,t),r}findParent(e,t,r=t){if(!r||!r.children)return null;if(r.children.includes(e))return r;for(let s of r.children){let n=this.findParent(e,t,s);if(n)return n}return null}calculateLevel(e,t,r=t,s=0){if(r===e)return s;if(r.children)for(let n of r.children){let o=this.calculateLevel(e,t,n,s+1);if(o>=0)return o}return-1}buildPath(e,t,r=t,s=[]){if(r===e)return[...s,{role:r.role,name:r.name}];if(r.children)for(let n of r.children){let o=this.buildPath(e,t,n,[...s,{role:r.role,name:r.name}]);if(o)return o}return null}hashAxSubtree(e){let t=JSON.stringify({role:e.role,name:e.name,children:(e.children||[]).map(r=>({role:r.role,name:r.name}))});return pn.createHash("md5").update(t).digest("hex").substring(0,12)}hashAxPath(e){let t=e.map(r=>`${r.role}:${r.name}`).join("/");return pn.createHash("md5").update(t).digest("hex").substring(0,12)}};var Se=class extends J{constructor(e={}){super(e),this.pendingRequests=new Set,this.setupNetworkTracking=!1}getName(){return"PageStateEnricher"}getPriority(){return 95}canEnrich(e){return this.enabled&&e.page}async setupTracking(e){this.setupNetworkTracking||(e.on("request",t=>{["document","xhr","fetch"].includes(t.resourceType())&&this.pendingRequests.add(t.url())}),e.on("requestfinished",t=>{this.pendingRequests.delete(t.url())}),e.on("requestfailed",t=>{this.pendingRequests.delete(t.url())}),this.setupNetworkTracking=!0)}async enrich(e,t){try{let{page:r}=t;await this.setupTracking(r);let s=await r.evaluate(()=>({readyState:document.readyState,domContentLoaded:document.readyState!=="loading",loadComplete:document.readyState==="complete",url:document.location.href})),n=await this.checkDOMStability(r);return{page:{networkIdle:this.pendingRequests.size===0,pendingRequests:this.pendingRequests.size,domStable:n,...s}}}catch(r){return this.handleError(r,e)}}async checkDOMStability(e,t=500){try{return await e.evaluate(s=>new Promise(n=>{let o,c=0,l=new MutationObserver(()=>{c++,clearTimeout(o),o=setTimeout(()=>{l.disconnect(),n(c===0)},s)});l.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),o=setTimeout(()=>{l.disconnect(),n(!0)},s)}),t)}catch{return!1}}reset(){this.pendingRequests.clear(),this.setupNetworkTracking=!1}};var Be=class extends J{getName(){return"DOMEnricher"}getPriority(){return 85}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{element:r}=t,s=await r.evaluate(n=>{let o=f=>{let m=[],S=f;for(;S&&S!==document.body;){let g=S.tagName.toLowerCase(),w=S.parentElement;if(w){let y=Array.from(w.children).filter(E=>E.tagName===S.tagName);if(y.length>1){let E=y.indexOf(S)+1;g+=`:nth-child(${E})`}}m.unshift(g),S=S.parentElement}return`body > ${m.join(" > ")}`},c=f=>{let m=[],S=f;for(;S&&S!==document.body;){let g=1,w=S.previousSibling;for(;w;)w.nodeType===1&&w.tagName===S.tagName&&g++,w=w.previousSibling;let y=S.tagName.toLowerCase();m.unshift(`${y}[${g}]`),S=S.parentElement}return`/html/body/${m.join("/")}`},l={};for(let f of n.attributes)l[f.name]=f.value;let a=window.getComputedStyle(n),u={display:a.display,visibility:a.visibility,opacity:a.opacity,pointerEvents:a.pointerEvents},p=0,d=n.parentElement;for(;d;)p++,d=d.parentElement;return{path:o(n),xpath:c(n),depth:p,parent:n.parentElement?n.parentElement.tagName.toLowerCase():null,tagName:n.tagName.toLowerCase(),attributes:l,state:{visible:a.display!=="none"&&a.visibility!=="hidden",enabled:!n.disabled,focused:document.activeElement===n,...u}}});return{dom:{path:s.path,xpath:s.xpath,depth:s.depth,parent:s.parent,selector:this.buildSmartSelector(s)},attributes:s.attributes,state:s.state}}catch(r){return this.handleError(r,e)}}buildSmartSelector(e){let t=e.tagName;if(e.attributes.id)return`#${e.attributes.id}`;if(e.attributes["data-test-id"])return`[data-test-id="${e.attributes["data-test-id"]}"]`;if(e.attributes.class){let r=e.attributes.class.split(" ").filter(s=>s&&!s.match(/^(active|focus|hover|disabled)/));r.length>0&&(t+=`.${r.slice(0,2).join(".")}`)}return e.parent&&(t=`${e.parent} > ${t}`),t}};var it=class extends J{constructor(e={}){super(e),this.priority=200}getName(){return"MCPRef"}getPriority(){return this.priority}async enrich(e,t){let r=e.data?.params?.ref,s=e.data?.params?.element;if(!r&&!s)return null;let n=null,o=null,c=null;if(t?.element)try{let l=await t.element.evaluate(a=>({text:a.textContent?.trim()||"",innerText:a.innerText?.trim()||"",value:a.value||"",label:a.getAttribute("aria-label")||a.getAttribute("label")||"",role:a.getAttribute("role")||a.tagName.toLowerCase(),placeholder:a.getAttribute("placeholder")||"",title:a.getAttribute("title")||""}));n=l.text||l.innerText||l.value||l.placeholder,o=l.role,c=l.label||l.title,console.log(`[MCPRefEnricher] \u2705 Captured actual text: "${n}" (AI said: "${s}")`)}catch(l){console.log(`[MCPRefEnricher] \u26A0\uFE0F Could not extract actual text: ${l.message}`)}return{mcpRef:r,mcpElement:s,actualText:n,actualRole:o,actualLabel:c,recordedSelector:n||s}}};function Er(i={}){let e=new ae(i);return i.enableMCPRef!==!1&&e.register(new it(i)),i.enableTraceText!==!1&&e.register(new ge(i)),i.enableAccessibility!==!1&&e.register(new ye(i)),i.enablePageState!==!1&&e.register(new Se(i)),i.enablePosition!==!1&&e.register(new De(i)),i.enableDOM!==!1&&e.register(new Be(i)),e}function Tr(i={}){let e=new ae(i);return e.register(new ye(i)),e.register(new Se(i)),e}function aa(i,e={}){let t=new ae(e);for(let r of i)t.register(r);return t}import{readFileSync as ca,writeFileSync as vr}from"node:fs";import{join as fn}from"node:path";async function la(i,e={}){let t=fn(i,"events.json"),r=fn(i,"trace.zip");try{let s=JSON.parse(ca(t,"utf-8")),n=s.map(c=>({...c,_enrichmentNote:"Full enrichment requires live Playwright access. Use EnrichmentPipeline during test execution."})),o=`${t}.backup`;return vr(o,JSON.stringify(s,null,2)),vr(t,JSON.stringify(n,null,2)),{enrichedCount:n.length,skippedCount:0,errors:[]}}catch(s){return console.error("[EnrichmentIntegration] Failed to enrich events:",s.message),{enrichedCount:0,skippedCount:0,errors:[s.message]}}}var $r=class{constructor(e={}){this.pipeline=e.minimal?Tr(e):Er(e),this.events=[],this.config=e}async recordEvent(e,t,r){let s={id:this.events.length,type:e,timestamp:new Date().toISOString(),data:t},n=await this.pipeline.enrich(s,{...r,event:s});return this.events.push(n),n}saveEvents(e){vr(e,JSON.stringify(this.events,null,2)),console.log(`[LiveEnrichment] Saved ${this.events.length} enriched events to ${e}`),this.pipeline.logStatus()}getStats(){return this.pipeline.getStats()}};var gn=i=>{i?.message?.includes("Connection closed")||i?.message?.includes("MCP error -32000")||i?.code===-32e3||console.error("Unhandled rejection:",i)};process.listeners("unhandledRejection").includes(gn)||process.on("unhandledRejection",gn);async function pa(i,e={}){let{agent:t,mcp:r,headless:s,cwd:n=process.cwd(),specPath:o,sessionPath:c,sessionTimestamp:l,...a}=e,u=dn(i,"utf-8"),p=null,{agent:d,error:f}=await ma(n,a),m=d;if(!m&&e.fallbackAgentModule){let w=e.fallbackAgentModule,y=w.BrowserTestAutomationAgent||w.default;y&&(m=new y(a))}if(!m&&f&&console.warn(`\u26A0\uFE0F Failed to load local agent: ${f}`),!m)throw new Error(`No agent found. Please run:
338
+ Registered enrichers (${this.enrichers.length}):`);for(let e of this.enrichers){let t=e.enabled?"\u2713":"\u2717",r=this.stats.errors[e.getName()]||0,s=r>0?` (${r} errors)`:"";console.log(` ${t} ${e.getName()} (priority: ${e.getPriority()})${s}`)}console.log()}};var Be=class extends W{getName(){return"PositionEnricher"}getPriority(){return 90}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:s}=t,n=await s.boundingBox();if(!n)return null;let o=await r.evaluate(()=>({scrollX:window.scrollX,scrollY:window.scrollY,width:window.innerWidth,height:window.innerHeight})),c=n.y>=o.scrollY&&n.y+n.height<=o.scrollY+o.height&&n.x>=0&&n.x+n.width<=o.width;return{position:{boundingBox:n,viewport:o,inViewport:c,centerPoint:{x:Math.round(n.x+n.width/2),y:Math.round(n.y+n.height/2)}}}}catch(r){return this.handleError(r,e)}}};import cn from"node:crypto";var we=class extends W{getName(){return"AccessibilityEnricher"}getPriority(){return 100}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:s}=t,n=await r.accessibility.snapshot(),o=await this.findAxNode(s,n);if(!o)return null;let c=await this.getAxContext(o,n),l=this.hashAxSubtree(o),a=this.hashAxPath(c.path);return{accessibility:{role:o.role,name:o.name||"",level:c.level,parent:c.parent,siblings:c.siblings,axTreeHash:l,axPathHash:a}}}catch(r){return this.handleError(r,e)}}async findAxNode(e,t){let r=await e.evaluate(s=>({role:s.getAttribute("role")||s.tagName.toLowerCase(),name:s.getAttribute("aria-label")||s.textContent?.trim()||"",tagName:s.tagName.toLowerCase()}));return this.searchAxTree(t,r)}searchAxTree(e,t){if(!e)return null;if(e.role===t.role&&(e.name||"").includes(t.name.substring(0,20)))return e;if(e.children)for(let r of e.children){let s=this.searchAxTree(r,t);if(s)return s}return null}getAxContext(e,t){let r={level:0,parent:null,siblings:[],path:[]},s=this.findParent(e,t);return s&&(r.parent={role:s.role,name:s.name},r.siblings=(s.children||[]).filter(n=>n!==e).map(n=>({role:n.role,name:n.name})).slice(0,3)),r.level=this.calculateLevel(e,t),r.path=this.buildPath(e,t),r}findParent(e,t,r=t){if(!r||!r.children)return null;if(r.children.includes(e))return r;for(let s of r.children){let n=this.findParent(e,t,s);if(n)return n}return null}calculateLevel(e,t,r=t,s=0){if(r===e)return s;if(r.children)for(let n of r.children){let o=this.calculateLevel(e,t,n,s+1);if(o>=0)return o}return-1}buildPath(e,t,r=t,s=[]){if(r===e)return[...s,{role:r.role,name:r.name}];if(r.children)for(let n of r.children){let o=this.buildPath(e,t,n,[...s,{role:r.role,name:r.name}]);if(o)return o}return null}hashAxSubtree(e){let t=JSON.stringify({role:e.role,name:e.name,children:(e.children||[]).map(r=>({role:r.role,name:r.name}))});return cn.createHash("md5").update(t).digest("hex").substring(0,12)}hashAxPath(e){let t=e.map(r=>`${r.role}:${r.name}`).join("/");return cn.createHash("md5").update(t).digest("hex").substring(0,12)}};var _e=class extends W{constructor(e={}){super(e),this.pendingRequests=new Set,this.setupNetworkTracking=!1}getName(){return"PageStateEnricher"}getPriority(){return 95}canEnrich(e){return this.enabled&&e.page}async setupTracking(e){this.setupNetworkTracking||(e.on("request",t=>{["document","xhr","fetch"].includes(t.resourceType())&&this.pendingRequests.add(t.url())}),e.on("requestfinished",t=>{this.pendingRequests.delete(t.url())}),e.on("requestfailed",t=>{this.pendingRequests.delete(t.url())}),this.setupNetworkTracking=!0)}async enrich(e,t){try{let{page:r}=t;await this.setupTracking(r);let s=await r.evaluate(()=>({readyState:document.readyState,domContentLoaded:document.readyState!=="loading",loadComplete:document.readyState==="complete",url:document.location.href})),n=await this.checkDOMStability(r);return{page:{networkIdle:this.pendingRequests.size===0,pendingRequests:this.pendingRequests.size,domStable:n,...s}}}catch(r){return this.handleError(r,e)}}async checkDOMStability(e,t=500){try{return await e.evaluate(s=>new Promise(n=>{let o,c=0,l=new MutationObserver(()=>{c++,clearTimeout(o),o=setTimeout(()=>{l.disconnect(),n(c===0)},s)});l.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),o=setTimeout(()=>{l.disconnect(),n(!0)},s)}),t)}catch{return!1}}reset(){this.pendingRequests.clear(),this.setupNetworkTracking=!1}};var Ue=class extends W{getName(){return"DOMEnricher"}getPriority(){return 85}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{element:r}=t,s=await r.evaluate(n=>{let o=f=>{let m=[],S=f;for(;S&&S!==document.body;){let h=S.tagName.toLowerCase(),_=S.parentElement;if(_){let y=Array.from(_.children).filter(x=>x.tagName===S.tagName);if(y.length>1){let x=y.indexOf(S)+1;h+=`:nth-child(${x})`}}m.unshift(h),S=S.parentElement}return`body > ${m.join(" > ")}`},c=f=>{let m=[],S=f;for(;S&&S!==document.body;){let h=1,_=S.previousSibling;for(;_;)_.nodeType===1&&_.tagName===S.tagName&&h++,_=_.previousSibling;let y=S.tagName.toLowerCase();m.unshift(`${y}[${h}]`),S=S.parentElement}return`/html/body/${m.join("/")}`},l={};for(let f of n.attributes)l[f.name]=f.value;let a=window.getComputedStyle(n),u={display:a.display,visibility:a.visibility,opacity:a.opacity,pointerEvents:a.pointerEvents},p=0,d=n.parentElement;for(;d;)p++,d=d.parentElement;return{path:o(n),xpath:c(n),depth:p,parent:n.parentElement?n.parentElement.tagName.toLowerCase():null,tagName:n.tagName.toLowerCase(),attributes:l,state:{visible:a.display!=="none"&&a.visibility!=="hidden",enabled:!n.disabled,focused:document.activeElement===n,...u}}});return{dom:{path:s.path,xpath:s.xpath,depth:s.depth,parent:s.parent,selector:this.buildSmartSelector(s)},attributes:s.attributes,state:s.state}}catch(r){return this.handleError(r,e)}}buildSmartSelector(e){let t=e.tagName;if(e.attributes.id)return`#${e.attributes.id}`;if(e.attributes["data-test-id"])return`[data-test-id="${e.attributes["data-test-id"]}"]`;if(e.attributes.class){let r=e.attributes.class.split(" ").filter(s=>s&&!s.match(/^(active|focus|hover|disabled)/));r.length>0&&(t+=`.${r.slice(0,2).join(".")}`)}return e.parent&&(t=`${e.parent} > ${t}`),t}};var nt=class extends W{constructor(e={}){super(e),this.priority=200}getName(){return"MCPRef"}getPriority(){return this.priority}async enrich(e,t){let r=e.data?.params?.ref,s=e.data?.params?.element;if(!r&&!s)return null;let n=null,o=null,c=null;if(t?.element)try{let l=await t.element.evaluate(a=>({text:a.textContent?.trim()||"",innerText:a.innerText?.trim()||"",value:a.value||"",label:a.getAttribute("aria-label")||a.getAttribute("label")||"",role:a.getAttribute("role")||a.tagName.toLowerCase(),placeholder:a.getAttribute("placeholder")||"",title:a.getAttribute("title")||""}));n=l.text||l.innerText||l.value||l.placeholder,o=l.role,c=l.label||l.title,console.log(`[MCPRefEnricher] \u2705 Captured actual text: "${n}" (AI said: "${s}")`)}catch(l){console.log(`[MCPRefEnricher] \u26A0\uFE0F Could not extract actual text: ${l.message}`)}return{mcpRef:r,mcpElement:s,actualText:n,actualRole:o,actualLabel:c,recordedSelector:n||s}}};function _r(i={}){let e=new le(i);return i.enableMCPRef!==!1&&e.register(new nt(i)),i.enableTraceText!==!1&&e.register(new Se(i)),i.enableAccessibility!==!1&&e.register(new we(i)),i.enablePageState!==!1&&e.register(new _e(i)),i.enablePosition!==!1&&e.register(new Be(i)),i.enableDOM!==!1&&e.register(new Ue(i)),e}function br(i={}){let e=new le(i);return e.register(new we(i)),e.register(new _e(i)),e}function ra(i,e={}){let t=new le(e);for(let r of i)t.register(r);return t}import{readFileSync as sa,writeFileSync as xr}from"node:fs";import{join as ln}from"node:path";async function na(i,e={}){let t=ln(i,"events.json"),r=ln(i,"trace.zip");try{let s=JSON.parse(sa(t,"utf-8")),n=s.map(c=>({...c,_enrichmentNote:"Full enrichment requires live Playwright access. Use EnrichmentPipeline during test execution."})),o=`${t}.backup`;return xr(o,JSON.stringify(s,null,2)),xr(t,JSON.stringify(n,null,2)),{enrichedCount:n.length,skippedCount:0,errors:[]}}catch(s){return console.error("[EnrichmentIntegration] Failed to enrich events:",s.message),{enrichedCount:0,skippedCount:0,errors:[s.message]}}}var Er=class{constructor(e={}){this.pipeline=e.minimal?br(e):_r(e),this.events=[],this.config=e}async recordEvent(e,t,r){let s={id:this.events.length,type:e,timestamp:new Date().toISOString(),data:t},n=await this.pipeline.enrich(s,{...r,event:s});return this.events.push(n),n}saveEvents(e){xr(e,JSON.stringify(this.events,null,2)),console.log(`[LiveEnrichment] Saved ${this.events.length} enriched events to ${e}`),this.pipeline.logStatus()}getStats(){return this.pipeline.getStats()}};var dn=i=>{i?.message?.includes("Connection closed")||i?.message?.includes("MCP error -32000")||i?.code===-32e3||console.error("Unhandled rejection:",i)};process.listeners("unhandledRejection").includes(dn)||process.on("unhandledRejection",dn);async function ia(i,e={}){let{agent:t,mcp:r,headless:s,cwd:n=process.cwd(),specPath:o,sessionPath:c,sessionTimestamp:l,...a}=e,u=un(i,"utf-8"),p=null,{agent:d,error:f}=await la(n,a),m=d;if(!m&&e.fallbackAgentModule){let _=e.fallbackAgentModule,y=_.BrowserTestAutomationAgent||_.default;y&&(m=new y(a))}if(!m&&f&&console.warn(`\u26A0\uFE0F Failed to load local agent: ${f}`),!m)throw new Error(`No agent found. Please run:
338
339
  zibby init
339
340
 
340
- This will create .zibby/graph.mjs with your workflow definition.`);await m.initialize(p);let S=!1,g=()=>{if(!S)try{Ft({cwd:n||process.cwd(),config:e}),S=!0}catch(w){console.warn("[zibby] run-index interrupt row:",w?.message||w)}};process.on("SIGINT",g),process.on("SIGTERM",g);try{if(e.singleNode){console.log(`
341
+ This will create .zibby/graph.mjs with your workflow definition.`);await m.initialize(p);let S=!1,h=()=>{if(!S)try{Dt({cwd:n||process.cwd(),config:e}),S=!0}catch(_){console.warn("[zibby] run-index interrupt row:",_?.message||_)}};process.on("SIGINT",h),process.on("SIGTERM",h);try{if(e.singleNode){console.log(`
341
342
  \u{1F3AF} Running Single Node: ${e.singleNode} (Framework Mode)
342
- `);let I=m.calculateOutputPath(o||i),P=m.buildGraph(),N={};for(let[O,_]of P.nodes.entries())N[O]=_.config||_;let b={};if(e.sessionId){let O=e.sessionId,_=e.paths?.output||B;if(O==="last"){let U=Fe(n,_,H);if(mn(U)){let{readdirSync:k,statSync:W}=await import("fs"),F=k(U).filter(Z=>W(Fe(U,Z)).isDirectory()).map(Z=>({name:Z,time:W(Fe(U,Z)).mtimeMs})).sort((Z,Ue)=>Ue.time-Z.time);F.length>0?(O=F[0].name,console.log(`\u{1F4C2} Using latest session: ${O}`)):console.log(`\u26A0\uFE0F No sessions found in ${U}`)}}let C=Fe(n,_,H,O),R=Fe(C,"execute_live"),L=Fe(R,Rt);mn(L)?(console.log(`\u{1F4C2} Loading session: ${O}`),b={sessionPath:C,execute_live_output:JSON.parse(dn(L,"utf-8"))}):console.log(`\u26A0\uFE0F Session not found: ${C}`)}let A=await m.runSingleNode(e.singleNode,N,{testSpec:u,outputPath:I,cwd:n||process.cwd(),contextConfig:e.contextConfig,specPath:o||i,config:e,...b});return typeof m.onComplete=="function"&&await m.onComplete(A),mt({cwd:n,config:e,result:A,success:!0,specPath:o||i}),A}let w;typeof e.onPipelineProgress=="function"?w=e.onPipelineProgress:e.runIndex?.pipelineProgress!==!1&&(w=jr({cwd:n||process.cwd(),config:e}));let y=n||process.cwd(),E=c!=null&&String(c).trim()!==""?(()=>{let I=String(c).trim();try{return ua(I)?hn(I):hn(y,I)}catch{return I}})():void 0,x=$t(),v=E??x;It();let $=At({cwd:y,config:e,traceFrom:"runTest",initialState:{sessionPath:v,sessionTimestamp:l}}),T;try{T=await m.run(u,{testSpec:u,specPath:o||i,cwd:y,config:e,sessionPath:$.sessionPath,sessionTimestamp:$.sessionTimestamp,...w?{onPipelineProgress:w}:{}})}catch(I){throw typeof I?.message=="string"&&I.message.includes("Interrupted by user")&&Ft({cwd:n||process.cwd(),config:e}),S||mt({cwd:n,config:e,result:I?.partialResult||{},success:!1,specPath:o||i,errorMessage:I?.message}),I}return mt({cwd:n,config:e,result:T,success:!0,specPath:o||i}),T}finally{process.off("SIGINT",g),process.off("SIGTERM",g),await m.cleanup()}}function fa(i){return i.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function da(i,e){if(i[e])return i[e];let t=fa(e);if(i[t])return i[t];let r=`${t}Workflow`;return i[r]?i[r]:null}async function _f(i=process.cwd()){try{let{join:e}=await import("path"),{existsSync:t}=await import("fs"),{pathToFileURL:r}=await import("url"),s=e(i,".zibby/graph.mjs");if(!t(s))return{available:[],default:null,error:"No .zibby/graph.mjs found"};let n=await import(r(s).href),o=Object.keys(n).filter(l=>l!=="default"&&typeof n[l]=="function"&&n[l].prototype instanceof Ce),c=n.BrowserTestAutomationAgent?"BrowserTestAutomationAgent":n.CursorAgent?"CursorAgent":n.default?"default":o[0]||null;return{available:o,default:c,error:null}}catch(e){return{available:[],default:null,error:e.message}}}async function ma(i,e){try{let{join:t}=await import("path"),{existsSync:r}=await import("fs"),{pathToFileURL:s}=await import("url"),n=t(i,".zibby/graph.mjs");if(!r(n))return{agent:null,error:null};let o=await import(s(n).href),c=e.workflow,l;if(c){if(l=da(o,c),!l){let u=Object.keys(o).filter(p=>p!=="default"&&typeof o[p]=="function");throw new Error(`Workflow "${c}" not found.
343
+ `);let A=m.calculateOutputPath(o||i),P=m.buildGraph(),k={};for(let[O,w]of P.nodes.entries())k[O]=w.config||w;let b={};if(e.sessionId){let O=e.sessionId,w=e.paths?.output||j;if(O==="last"){let R=Fe(n,w,X);if(pn(R)){let{readdirSync:M,statSync:L}=await import("fs"),D=M(R).filter(z=>L(Fe(R,z)).isDirectory()).map(z=>({name:z,time:L(Fe(R,z)).mtimeMs})).sort((z,ie)=>ie.time-z.time);D.length>0?(O=D[0].name,console.log(`\u{1F4C2} Using latest session: ${O}`)):console.log(`\u26A0\uFE0F No sessions found in ${R}`)}}let $=Fe(n,w,X,O),N=Fe($,"execute_live"),U=Fe(N,Ct);pn(U)?(console.log(`\u{1F4C2} Loading session: ${O}`),b={sessionPath:$,execute_live_output:JSON.parse(un(U,"utf-8"))}):console.log(`\u26A0\uFE0F Session not found: ${$}`)}let C=await m.runSingleNode(e.singleNode,k,{testSpec:u,outputPath:A,cwd:n||process.cwd(),contextConfig:e.contextConfig,specPath:o||i,config:e,...b});return typeof m.onComplete=="function"&&await m.onComplete(C),pt({cwd:n,config:e,result:C,success:!0,specPath:o||i}),C}let _;typeof e.onPipelineProgress=="function"?_=e.onPipelineProgress:e.runIndex?.pipelineProgress!==!1&&(_=Br({cwd:n||process.cwd(),config:e}));let y=n||process.cwd(),x=c!=null&&String(c).trim()!==""?(()=>{let A=String(c).trim();try{return oa(A)?fn(A):fn(y,A)}catch{return A}})():void 0,E=It(),T=x??E;Tt();let v=$t({cwd:y,config:e,traceFrom:"runTest",initialState:{sessionPath:T,sessionTimestamp:l}}),I;try{I=await m.run(u,{testSpec:u,specPath:o||i,cwd:y,config:e,sessionPath:v.sessionPath,sessionTimestamp:v.sessionTimestamp,..._?{onPipelineProgress:_}:{}})}catch(A){throw typeof A?.message=="string"&&A.message.includes("Interrupted by user")&&Dt({cwd:n||process.cwd(),config:e}),S||pt({cwd:n,config:e,result:A?.partialResult||{},success:!1,specPath:o||i,errorMessage:A?.message}),A}return pt({cwd:n,config:e,result:I,success:!0,specPath:o||i}),I}finally{process.off("SIGINT",h),process.off("SIGTERM",h),await m.cleanup()}}function aa(i){return i.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function ca(i,e){if(i[e])return i[e];let t=aa(e);if(i[t])return i[t];let r=`${t}Workflow`;return i[r]?i[r]:null}async function _f(i=process.cwd()){try{let{join:e}=await import("path"),{existsSync:t}=await import("fs"),{pathToFileURL:r}=await import("url"),s=e(i,".zibby/graph.mjs");if(!t(s))return{available:[],default:null,error:"No .zibby/graph.mjs found"};let n=await import(r(s).href),o=Object.keys(n).filter(l=>l!=="default"&&typeof n[l]=="function"&&n[l].prototype instanceof Ne),c=n.BrowserTestAutomationAgent?"BrowserTestAutomationAgent":n.CursorAgent?"CursorAgent":n.default?"default":o[0]||null;return{available:o,default:c,error:null}}catch(e){return{available:[],default:null,error:e.message}}}async function la(i,e){try{let{join:t}=await import("path"),{existsSync:r}=await import("fs"),{pathToFileURL:s}=await import("url"),n=t(i,".zibby/graph.mjs");if(!r(n))return{agent:null,error:null};let o=await import(s(n).href),c=e.workflow,l;if(c){if(l=ca(o,c),!l){let u=Object.keys(o).filter(p=>p!=="default"&&typeof o[p]=="function");throw new Error(`Workflow "${c}" not found.
343
344
  Available workflows: ${u.join(", ")}
344
- Supported formats: QuickSmokeWorkflow, QuickSmoke, quick-smoke`)}let a=Object.keys(o).find(u=>o[u]===l);console.log(`\u2713 Using workflow: ${a} (from --workflow ${c})`)}else{if(l=o.BrowserTestAutomationAgent||o.CursorAgent||o.default,!l){let a=Object.keys(o).filter(u=>u!=="default"&&typeof o[u]=="function"&&o[u].prototype instanceof Ce);a.length>0&&(l=o[a[0]],console.log(`\u2713 Using workflow: ${a[0]} (auto-detected)`))}if(!l)return{agent:null,error:"Could not find any WorkflowAgent export in local graph.js"};l.name?.includes("auto-detected")||console.log("\u2713 Using local agent from .zibby/graph.mjs")}return{agent:new l(e),error:null}}catch(t){return{agent:null,error:t.message}}}var yn=class{constructor(e={}){this.config=e}async run(e){return pa(e.spec||e.specPath,{...this.config,...e})}};export{Vn as AGENT_TYPES,wu as ALL_TOOLS,ye as AccessibilityEnricher,K as AgentStrategy,Pe as AssistantStrategy,ui as CHAT_MEMORY_TOOLS,kt as CI_ENV_VARS,qn as CORE_LOG_LEVELS,ni as CORE_TOOLS,Ee as ClaudeAgentStrategy,Te as CodexAgentStrategy,xe as CursorAgentStrategy,Gi as DEFAULT_MAX_CONCURRENT_RUNS,G as DEFAULT_MODELS,B as DEFAULT_OUTPUT_BASE,Be as DOMEnricher,bn as EVENTS_FILE,ae as EnrichmentPipeline,J as EventEnricher,ii as GITHUB_TOOLS,ve as GeminiAgentStrategy,oi as JIRA_TOOLS,X as LOG_LEVELS,$r as LiveEnrichmentRecorder,gt as Logger,Ji as MAX_MAX_CONCURRENT_RUNS,Re as MCPRefStrategy,li as MEMORY_TOOLS,zi as MIN_MAX_CONCURRENT_RUNS,Xe as McpClientManager,de as OpenAIToolProvider,Se as PageStateEnricher,Le as PlaywrightJsonVerificationStrategy,De as PositionEnricher,_n as RAW_OUTPUT_FILE,Rt as RESULT_FILE,en as RIPPLE_EFFECT_SCRIPT,ci as RUNNER_TOOLS,gr as ResultHandler,H as SESSIONS_DIR,q as SESSION_INFO_FILE,xn as SKILLS,pi as SKILL_TOOLS,ai as SLACK_TOOLS,rt as SelectorGenerator,_r as StableIdRuntime,ke as StableIdStrategy,te as StreamingParser,yn as TestAutomation,ie as TestGenerationStrategy,yr as TestPostProcessor,Me as TestVerificationStrategy,$e as ToolCallProvider,nt as TraceParser,Ce as WorkflowAgent,et as WorkflowGraph,wr as ZibbyRuntime,tt as ZibbyUploader,Wn as checkCursorAgentInstalled,Ri as checkCursorAgentPatched,It as clearInheritedSessionEnvForFreshRun,wi as clearTokenCache,Oi as cloneRepo,aa as createCustomPipeline,Er as createDefaultPipeline,Tr as createMinimalPipeline,qs as createUploader,la as enrichRecordedEvents,Bi as generateRippleHelperCode,Ys as generateWorkflowSessionId,cr as getAgentStrategy,St as getAllSkills,ki as getApprovalKeys,Yn as getCursorAgentInstallInstructions,z as getSkill,rs as hasSkill,Di as injectRippleEffect,Ls as invokeAgent,ss as listSkillIds,_f as listWorkflows,h as logger,Ei as organizeVideos,Ni as patchCursorAgentForCI,Hi as postProcessEvents,$t as readStudioPinnedSessionPathFromEnv,ts as registerSkill,ea as resetExecutionCount,Si as resolveIntegrationToken,Wi as resolveMaxParallelRuns,At as resolveWorkflowSession,cn as runPlaywrightTestTool,pa as runTest,Li as saveApprovalKeys,Js as shouldTrustInheritedSessionEnv,Ws as syncProcessEnvToSession,sa as testGenerationManager,ia as testVerificationManager,D as timeline,ti as workflow,vf as z};
345
+ Supported formats: QuickSmokeWorkflow, QuickSmoke, quick-smoke`)}let a=Object.keys(o).find(u=>o[u]===l);console.log(`\u2713 Using workflow: ${a} (from --workflow ${c})`)}else{if(l=o.BrowserTestAutomationAgent||o.CursorAgent||o.default,!l){let a=Object.keys(o).filter(u=>u!=="default"&&typeof o[u]=="function"&&o[u].prototype instanceof Ne);a.length>0&&(l=o[a[0]],console.log(`\u2713 Using workflow: ${a[0]} (auto-detected)`))}if(!l)return{agent:null,error:"Could not find any WorkflowAgent export in local graph.js"};l.name?.includes("auto-detected")||console.log("\u2713 Using local agent from .zibby/graph.mjs")}return{agent:new l(e),error:null}}catch(t){return{agent:null,error:t.message}}}var mn=class{constructor(e={}){this.config=e}async run(e){return ia(e.spec||e.specPath,{...this.config,...e})}};export{Yn as AGENT_TYPES,wu as ALL_TOOLS,we as AccessibilityEnricher,Z as AgentStrategy,Ce as AssistantStrategy,oi as CHAT_MEMORY_TOOLS,Nt as CI_ENV_VARS,Wn as CORE_LOG_LEVELS,Qo as CORE_TOOLS,Ie as ClaudeAgentStrategy,Te as CodexAgentStrategy,Ee as CursorAgentStrategy,Di as DEFAULT_MAX_CONCURRENT_RUNS,J as DEFAULT_MODELS,j as DEFAULT_OUTPUT_BASE,Ue as DOMEnricher,Sn as EVENTS_FILE,le as EnrichmentPipeline,W as EventEnricher,ti as GITHUB_TOOLS,$e as GeminiAgentStrategy,ei as JIRA_TOOLS,ee as LOG_LEVELS,Er as LiveEnrichmentRecorder,dt as Logger,Ui as MAX_MAX_CONCURRENT_RUNS,ke as MCPRefStrategy,ni as MEMORY_TOOLS,Bi as MIN_MAX_CONCURRENT_RUNS,Ve as McpClientManager,ge as OpenAIToolProvider,_e as PageStateEnricher,De as PlaywrightJsonVerificationStrategy,Be as PositionEnricher,yn as RAW_OUTPUT_FILE,Ct as RESULT_FILE,Xs as RIPPLE_EFFECT_SCRIPT,si as RUNNER_TOOLS,dr as ResultHandler,X as SESSIONS_DIR,Q as SESSION_INFO_FILE,wn as SKILLS,ii as SKILL_TOOLS,ri as SLACK_TOOLS,et as SelectorGenerator,yr as StableIdRuntime,Me as StableIdStrategy,se as StreamingParser,mn as TestAutomation,ce as TestGenerationStrategy,mr as TestPostProcessor,Le as TestVerificationStrategy,ve as ToolCallProvider,rt as TraceParser,Ne as WorkflowAgent,qe as WorkflowGraph,hr as ZibbyRuntime,Qe as ZibbyUploader,jn as checkCursorAgentInstalled,Ai as checkCursorAgentPatched,Tt as clearInheritedSessionEnvForFreshRun,mi as clearTokenCache,Ii as cloneRepo,ra as createCustomPipeline,_r as createDefaultPipeline,br as createMinimalPipeline,Zs as createUploader,na as enrichRecordedEvents,Ri as generateRippleHelperCode,zs as generateWorkflowSessionId,or as getAgentStrategy,gt as getAllSkills,Pi as getApprovalKeys,Gn as getCursorAgentInstallInstructions,Y as getSkill,qr as hasSkill,Ni as injectRippleEffect,Rs as invokeAgent,Qr as listSkillIds,_f as listWorkflows,g as logger,Si as organizeVideos,vi as patchCursorAgentForCI,Ji as postProcessEvents,It as readStudioPinnedSessionPathFromEnv,Xr as registerSkill,Hi as resetExecutionCount,di as resolveIntegrationToken,Fi as resolveMaxParallelRuns,$t as resolveWorkflowSession,nn as runPlaywrightTestTool,ia as runTest,Ci as saveApprovalKeys,js as shouldTrustInheritedSessionEnv,Gs as syncProcessEnvToSession,qi as testGenerationManager,ta as testVerificationManager,F as timeline,Vo as workflow,Tf as z};