@zibby/core 0.2.0 → 0.3.0

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,4 +1,4 @@
1
- var qr=(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')});import{readFileSync as Yr,existsSync as Hr}from"node:fs";import{join as Ie,resolve as Zr,isAbsolute as Xo}from"node:path";import{DEFAULT_OUTPUT_BASE as qo,SESSIONS_DIR as Wr,RESULT_FILE as Qo,resolveWorkflowSession as ei,clearInheritedSessionEnvForFreshRun as ti,readStudioPinnedSessionPathFromEnv as ri}from"@zibby/agent-workflow";import{registerStrategy as Ne}from"@zibby/agent-workflow";import{AgentStrategy as bn,DEFAULT_OUTPUT_BASE as wn,SESSION_INFO_FILE as xn,STUDIO_STOP_REQUEST_FILE as _n,getAllSkills as En,getSkill as Yt}from"@zibby/agent-workflow";import{spawn as Tn,execSync as q}from"node:child_process";import{writeFileSync as Ht,readFileSync as Zt,mkdirSync as Wt,existsSync as Pe,accessSync as Vt,constants as Xt,unlinkSync as vn}from"node:fs";import{join as J,resolve as In}from"node:path";import{homedir as Oe}from"node:os";import Ae from"chalk";var z={debug:0,info:1,warn:2,error:3,silent:4},ze=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return z.debug;if(process.env.ZIBBY_VERBOSE==="true")return z.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in z?z[e]:z.info}_shouldLog(e){return z[e]>=this._level}_formatMessage(e,t,r={}){let n=new Date().toISOString(),o=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(o+=Ae.dim(` ${JSON.stringify(r)}`)),o}_getPrefix(e){return{debug:Ae.gray("[DEBUG]"),info:Ae.cyan("[INFO]"),warn:Ae.yellow("[WARN]"),error:Ae.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 z&&(this._level=z[e])}getLevel(){return Object.keys(z).find(e=>z[e]===this._level)}},m=new ze;var F={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"},Qr={ASSISTANT:"assistant",CLAUDE:"claude",CURSOR:"cursor",CODEX:"codex",GEMINI:"gemini"},en={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error",SILENT:"silent"},lt={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"},ct={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"},Ft={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},Je={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var K=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 qr=(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')});import{readFileSync as Yr,existsSync as Hr}from"node:fs";import{join as Ie,resolve as Zr,isAbsolute as Xo}from"node:path";import{DEFAULT_OUTPUT_BASE as qo,SESSIONS_DIR as Wr,RESULT_FILE as Qo,resolveWorkflowSession as ei,clearInheritedSessionEnvForFreshRun as ti,readPinnedSessionPathFromEnv as ri}from"@zibby/agent-workflow";import{registerStrategy as Ne}from"@zibby/agent-workflow";import{AgentStrategy as bn,DEFAULT_OUTPUT_BASE as wn,SESSION_INFO_FILE as xn,STOP_REQUEST_FILE as _n,getAllSkills as En,getSkill as Yt}from"@zibby/agent-workflow";import{spawn as Tn,execSync as q}from"node:child_process";import{writeFileSync as Ht,readFileSync as Zt,mkdirSync as Wt,existsSync as Pe,accessSync as Vt,constants as Xt,unlinkSync as vn}from"node:fs";import{join as J,resolve as In}from"node:path";import{homedir as Oe}from"node:os";import Ae from"chalk";var z={debug:0,info:1,warn:2,error:3,silent:4},ze=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return z.debug;if(process.env.ZIBBY_VERBOSE==="true")return z.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in z?z[e]:z.info}_shouldLog(e){return z[e]>=this._level}_formatMessage(e,t,r={}){let n=new Date().toISOString(),o=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(o+=Ae.dim(` ${JSON.stringify(r)}`)),o}_getPrefix(e){return{debug:Ae.gray("[DEBUG]"),info:Ae.cyan("[INFO]"),warn:Ae.yellow("[WARN]"),error:Ae.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 z&&(this._level=z[e])}getLevel(){return Object.keys(z).find(e=>z[e]===this._level)}},m=new ze;var F={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"},Qr={ASSISTANT:"assistant",CLAUDE:"claude",CURSOR:"cursor",CODEX:"codex",GEMINI:"gemini"},en={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error",SILENT:"silent"},lt={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"},ct={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"},Ft={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},Je={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var K=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 n of t)if(n.trim())try{let s=JSON.parse(n);this._emitToolCalls(s);let o=this.extractText(s);if(o){if(this.rawText&&o.startsWith(this.rawText)){let l=o.substring(this.rawText.length);this.rawText=o,r+=l}else(!this.rawText.includes(o)||o.length<20)&&(this.rawText+=o,r+=o);this.tryExtractResult(this.rawText)}else this.isValidResult(s)&&(this.rawText+=`${n}
3
3
  `,r+=`${n}
4
4
  `,this.extractedResult=s)}catch{if(n.includes('"text"')||n.includes('"content"')){let o=n.match(/"text"\s*:\s*"([^"]*)/),l=n.match(/"content"\s*:\s*"([^"]*)/),c=o?o[1]:l?l[1]:null;c&&!this.rawText.includes(c)&&(r+=c,this.rawText+=c)}}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,l)=>{if(!o)return;let c=`${o}:${JSON.stringify(l??{})}`;this._lastToolEmit!==c&&(this._lastToolEmit=c,this.onToolCall(o,l??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 l=Object.keys(o);if(l.length===1){let c=l[0],a=o[c],u=a&&typeof a=="object"?a.args??a.input??a:void 0;t(c,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 n=e.message??e;if(Array.isArray(n?.tool_calls)){for(let o of n.tool_calls)t(o.name,r(o.input??o.arguments));return}let s=n?.content??e.content;if(Array.isArray(s))for(let o of s)(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,n;for(;(n=r.exec(e))!==null;){let f=n[1].trim();try{JSON.parse(f),t.push({text:f,source:"markdown"})}catch{}}let s=0,o=0;for(;s<e.length&&(s=e.indexOf("{",s),s!==-1);){let f=0,d=s;for(let p=s;p<e.length;p++)if(e[p]==="{")f++;else if(e[p]==="}"&&(f--,f===0)){d=p,t.push({text:e.substring(s,d+1),source:"brace"}),o++;break}s=d+1}let l=this.extractedResult,c=l?JSON.stringify(l).length:0,a=0,u=-1;for(let f=0;f<t.length;f++){let d=t[f];try{let p=d.text.replace(/,(\s*[}\]])/g,"$1"),g=JSON.parse(p);this.isValidResult(g)&&(a++,c=JSON.stringify(g).length,l=g,u=f)}catch{}}l&&(this.extractedResult=l)}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 n=r.getResult();return!n&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),n}};import{zodToJsonSchema as tn}from"zod-to-json-schema";var Ke=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=tn(e,{target:"openApi3"}):r=e;let n=this._buildExample(r);return`
@@ -55,24 +55,24 @@ Test with: agent --version`);let w=new fe(e),b=null;if(s){let E=`zibby-result-${
55
55
  \u25C6 Model: ${p||"auto"}${N}
56
56
  `);let P=(await import("chalk")).default,k=w.getUserPrompt();console.log(`
57
57
  ${P.bold("Prompt sent to LLM:")}`),console.log(P.dim("\u2500".repeat(60))),console.log(P.dim(k)),console.log(P.dim("\u2500".repeat(60)));let _=w.build(),C=w.getStats(),M=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",p||"auto"];if(process.env.CURSOR_API_KEY&&M.push("--api-key",process.env.CURSOR_API_KEY),M.push(_),m.debug(`[Agent] User prompt: ${C.userPromptLength} chars, System instructions: ${C.systemInstructionsLength} chars (${C.instructionCount} blocks), Full: ${C.fullPromptLength} chars, model: ${p||"auto"}`),m.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${p||"auto"} (from .zibby.config.js agent.cursor.model)
58
- `)}catch{}let T,x=null;try{let E=l||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);T=await this._spawnWithStreaming(S,M,r,a,null,E,y,f)}catch(E){x=E}let A=T?.stdout||"";if(s){let E=typeof s.parse=="function",O=null,I=!!(b&&Pe(b));if(b&&m.info(`[Agent] Result file: ${I?"present":"missing"} at ${b}`),I)try{let $=Zt(b,"utf-8").trim();O=JSON.parse($),m.info(`[Agent] Parsed JSON from result file OK (${$.length} chars) \u2192 object ready for validation`),x&&m.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch($){m.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${$.message}`)}else if(x)m.warn(`[Agent] Result file missing at ${b} (agent process error \u2014 may still recover if strictMode repairs)`);else throw m.error(`\u274C [Agent] Result file was never created at ${b}`),new Error(`Agent did not write required result file at ${b}`);if(O&&E)try{let $=s.parse(O);return m.info("\u2705 [Agent] Zod validation passed for structured result file"),d&&m.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:A,structured:$}}catch($){let L=$.issues?$.issues.map(U=>` - ${U.path.join(".")}: ${U.message}`).join(`
58
+ `)}catch{}let T,x=null;try{let E=l||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);T=await this._spawnWithStreaming(S,M,r,a,null,E,y,f)}catch(E){x=E}let A=T?.stdout||"";if(s){let E=typeof s.parse=="function",O=null,I=!!(b&&Pe(b));if(b&&m.info(`[Agent] Result file: ${I?"present":"missing"} at ${b}`),I)try{let $=Zt(b,"utf-8").trim();O=JSON.parse($),m.info(`[Agent] Parsed JSON from result file OK (${$.length} chars) \u2192 object ready for validation`),x&&m.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch($){m.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${$.message}`)}else if(x)m.warn(`[Agent] Result file missing at ${b} (agent process error \u2014 may still recover if strictMode repairs)`);else throw m.error(`\u274C [Agent] Result file was never created at ${b}`),new Error(`Agent did not write required result file at ${b}`);if(O&&E)try{let $=s.parse(O);return m.info("\u2705 [Agent] Zod validation passed for structured result file"),d&&m.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:A,structured:$}}catch($){let L=$.issues?$.issues.map(B=>` - ${B.path.join(".")}: ${B.message}`).join(`
59
59
  `):$.message?.slice(0,400);if(m.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
60
60
  ${L}`),m.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
61
61
  ${JSON.stringify(O,null,2).slice(0,500)}`),!d)throw new Error(`Agent output failed schema validation:
62
62
  ${L}
63
63
 
64
64
  The agent wrote invalid data that doesn't match the required outputSchema.
65
- Enable strictMode in .zibby.config.js for automatic repair.`,{cause:$})}else{if(O)return m.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),d&&m.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:A,structured:O};I&&m.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(d&&!x){let $=T.parsedText,L=O?JSON.stringify(O):$;m.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${L.length} chars in)`);try{let U=await jt(L,s);if(E){let D=s.parse(U.structured);return m.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:A,structured:D}}return{raw:A,...U}}catch(U){if(m.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${U.message}`),O)return m.warn("[Agent] Using agent's original result file as fallback"),{raw:A,structured:O}}}if(x)throw x;let B=I?O==null?"file existed but JSON.parse failed \u2014 see WARN log above":E?"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 m.error(`\u274C [Agent] No validated structured output: ${B}`),m.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 ${b}. Enable strictMode for proxy fallback.`)}if(x)throw x;return this._extractFinalResult(A)||T?.parsedText||A}_extractFinalResult(e){if(!e)return null;let t=e.split(`
65
+ Enable strictMode in .zibby.config.js for automatic repair.`,{cause:$})}else{if(O)return m.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),d&&m.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:A,structured:O};I&&m.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(d&&!x){let $=T.parsedText,L=O?JSON.stringify(O):$;m.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${L.length} chars in)`);try{let B=await jt(L,s);if(E){let D=s.parse(B.structured);return m.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:A,structured:D}}return{raw:A,...B}}catch(B){if(m.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${B.message}`),O)return m.warn("[Agent] Using agent's original result file as fallback"),{raw:A,structured:O}}}if(x)throw x;let U=I?O==null?"file existed but JSON.parse failed \u2014 see WARN log above":E?"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 m.error(`\u274C [Agent] No validated structured output: ${U}`),m.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 ${b}. Enable strictMode for proxy fallback.`)}if(x)throw x;return this._extractFinalResult(A)||T?.parsedText||A}_extractFinalResult(e){if(!e)return null;let t=e.split(`
66
66
  `),r=null;for(let n of t){let s=n.trim();if(s)try{let o=JSON.parse(s);if(o.type==="assistant"&&o.message?.content){let l=o.message.content;if(Array.isArray(l)){let c=l.filter(a=>a.type==="text"&&a.text).map(a=>a.text).join("");c&&(r=c)}else typeof l=="string"&&l&&(r=l)}}catch{}}return r?.trim()||null}_setupMcpConfig(e,t,r,n=null,s=null){let o=r?.headless,l=J(Oe(),".cursor"),c=J(l,"mcp.json"),a={};if(Pe(c))try{a=JSON.parse(Zt(c,"utf-8"))}catch{}let u=a.mcpServers||{},f=r?.paths?.output||wn,d=J(t||process.cwd(),f,xn),p=Array.isArray(n)?n.map(h=>Yt(h)).filter(Boolean):[...En()].map(([,h])=>h),g=new Set;for(let h of p)typeof h.resolve=="function"&&(g.has(h.serverName)||(g.add(h.serverName),this._ensureSkillConfigured(u,h,e,d,s,o)));if(e){let h=Yt("browser");h&&typeof h.resolve=="function"&&!g.has(h.serverName)&&this._ensureSkillConfigured(u,h,e,d,"execute_live",o)}if(Object.keys(u).length===0)return m.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let y=`${JSON.stringify({mcpServers:u},null,2)}
67
- `;if(zt(e)){let h=Jt(t||process.cwd()),S=J(h,".cursor","mcp.json");return Ht(S,y,"utf8"),m.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${h} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:h}}return Pe(l)||Wt(l,{recursive:!0}),Ht(c,y,"utf8"),m.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,n,s=null,o){let l=t.cursorKey||t.serverName,c=e[l]?l:e[t.serverName]?t.serverName:null;if(c&&r){let u=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:s,headless:o}):null;u?.args?e[c].args=u.args:e[c].args=(e[c].args||[]).map(p=>p.startsWith("--output-dir=")?`--output-dir=${r}`:p);let f=u?.env||{},d=t.sessionEnvKey?{[t.sessionEnvKey]:n}:{};e[c].env={...e[c].env||{},...f,...d},m.debug(`[MCP] Updated ${c} session \u2192 ${r}`);return}if(c)return;let a=t.resolve({sessionPath:r,nodeName:s,headless:o});a&&(e[l]={...a,...t.sessionEnvKey&&{env:{...a.env||{},[t.sessionEnvKey]:n}}},m.debug(`[MCP] Configured ${l}`))}_spawnWithStreaming(e,t,r,n,s=null,o=null,l=null,c=null){return new Promise((a,u)=>{let f=Date.now(),d="",p="",g=Date.now(),y=0,h=!1,S=null,w=!1,b=!1,v=null;if(o)try{v=J(In(String(o)),_n)}catch{v=null}let N=!1,P=()=>{N||(N=!0,Kt(l))},k={...process.env};l&&(k.HOME=l,process.platform==="win32"&&(k.USERPROFILE=l),m.debug(`[Agent] cursor-agent HOME=${l} (isolated MCP config)`));let _=Tn(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:k,...c&&{signal:c}});m.debug(`[Agent] PID: ${_.pid}`);let C=null,M=()=>{h||b||(h=!0,S="aborted",m.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),C=setTimeout(()=>{if(!b){m.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{_.kill("SIGKILL")}catch{}}},5e3))};c&&(c.aborted?M():c.addEventListener("abort",M,{once:!0})),_.stdin.on("error",I=>{I.code!=="EPIPE"&&m.warn(`[Agent] stdin error: ${I.message}`)}),_.stdout.on("error",I=>{I.code!=="EPIPE"&&m.warn(`[Agent] stdout error: ${I.message}`)}),_.stderr.on("error",I=>{I.code!=="EPIPE"&&m.warn(`[Agent] stderr error: ${I.message}`)}),s?(_.stdin.write(s,I=>{I&&I.code!=="EPIPE"&&m.warn(`[Agent] Failed to write to stdin: ${I.message}`),_.stdin.end()}),m.debug(`[Agent] Prompt also piped to stdin (${s.length} chars)`)):_.stdin.end();let T=null;v&&(T=setInterval(()=>{if(!(h||b))try{if(Pe(v)){h=!0,S="studio-stop";try{vn(v)}catch{}m.warn("\u{1F6D1} Studio stop requested \u2014 terminating Cursor agent (and MCP browser session)"),_.kill("SIGTERM"),setTimeout(()=>{_.killed||_.kill("SIGKILL")},2e3)}}catch{}},600));let x=new Set,A=new Date(f).toISOString().replace(/\.\d+Z$/,""),R=setInterval(()=>{let I=Math.round((Date.now()-f)/1e3),B=Math.round((Date.now()-g)/1e3),$=[];try{let U=Math.ceil(I/60)+1,D=q(`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(D)for(let H of D.split(`
67
+ `;if(zt(e)){let h=Jt(t||process.cwd()),S=J(h,".cursor","mcp.json");return Ht(S,y,"utf8"),m.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${h} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:h}}return Pe(l)||Wt(l,{recursive:!0}),Ht(c,y,"utf8"),m.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,n,s=null,o){let l=t.cursorKey||t.serverName,c=e[l]?l:e[t.serverName]?t.serverName:null;if(c&&r){let u=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:s,headless:o}):null;u?.args?e[c].args=u.args:e[c].args=(e[c].args||[]).map(p=>p.startsWith("--output-dir=")?`--output-dir=${r}`:p);let f=u?.env||{},d=t.sessionEnvKey?{[t.sessionEnvKey]:n}:{};e[c].env={...e[c].env||{},...f,...d},m.debug(`[MCP] Updated ${c} session \u2192 ${r}`);return}if(c)return;let a=t.resolve({sessionPath:r,nodeName:s,headless:o});a&&(e[l]={...a,...t.sessionEnvKey&&{env:{...a.env||{},[t.sessionEnvKey]:n}}},m.debug(`[MCP] Configured ${l}`))}_spawnWithStreaming(e,t,r,n,s=null,o=null,l=null,c=null){return new Promise((a,u)=>{let f=Date.now(),d="",p="",g=Date.now(),y=0,h=!1,S=null,w=!1,b=!1,v=null;if(o)try{v=J(In(String(o)),_n)}catch{v=null}let N=!1,P=()=>{N||(N=!0,Kt(l))},k={...process.env};l&&(k.HOME=l,process.platform==="win32"&&(k.USERPROFILE=l),m.debug(`[Agent] cursor-agent HOME=${l} (isolated MCP config)`));let _=Tn(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:k,...c&&{signal:c}});m.debug(`[Agent] PID: ${_.pid}`);let C=null,M=()=>{h||b||(h=!0,S="aborted",m.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),C=setTimeout(()=>{if(!b){m.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{_.kill("SIGKILL")}catch{}}},5e3))};c&&(c.aborted?M():c.addEventListener("abort",M,{once:!0})),_.stdin.on("error",I=>{I.code!=="EPIPE"&&m.warn(`[Agent] stdin error: ${I.message}`)}),_.stdout.on("error",I=>{I.code!=="EPIPE"&&m.warn(`[Agent] stdout error: ${I.message}`)}),_.stderr.on("error",I=>{I.code!=="EPIPE"&&m.warn(`[Agent] stderr error: ${I.message}`)}),s?(_.stdin.write(s,I=>{I&&I.code!=="EPIPE"&&m.warn(`[Agent] Failed to write to stdin: ${I.message}`),_.stdin.end()}),m.debug(`[Agent] Prompt also piped to stdin (${s.length} chars)`)):_.stdin.end();let T=null;v&&(T=setInterval(()=>{if(!(h||b))try{if(Pe(v)){h=!0,S="aborted";try{vn(v)}catch{}m.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),_.kill("SIGTERM"),setTimeout(()=>{_.killed||_.kill("SIGKILL")},2e3)}}catch{}},600));let x=new Set,A=new Date(f).toISOString().replace(/\.\d+Z$/,""),R=setInterval(()=>{let I=Math.round((Date.now()-f)/1e3),U=Math.round((Date.now()-g)/1e3),$=[];try{let B=Math.ceil(I/60)+1,D=q(`find "${r}" -type f -mmin -${B} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(D)for(let H of D.split(`
68
68
  `)){let pe=H.replace(`${r}/`,"");x.has(pe)||(x.add(pe),$.push(pe))}}catch{}let L="";$.length>0&&(L=` | \u{1F4C1} new: ${$.map(D=>D.split("/").pop()).join(", ")}`),x.size>0&&(L+=` | \u{1F4E6} total: ${x.size} files`),m.debug(`\u{1F493} [Agent] Running for ${I}s | ${y} lines output${L}`),y===0&&I>=30&&x.size===0&&(I<35&&m.warn(`\u26A0\uFE0F [Agent] No output after ${I}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),I>=60&&(h=!0,S=S||"stall",m.error(`\u274C [Agent] No response after ${I}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),_.kill("SIGTERM"),setTimeout(()=>{_.killed||_.kill("SIGKILL")},3e3)))},3e4),E=setTimeout(()=>{h=!0,S=S||"timeout";let I=Math.round((Date.now()-f)/1e3);m.error(`\u23F1\uFE0F [Agent] Timeout after ${I}s \u2014 killing process (PID: ${_.pid})`),d.trim()&&m.warn(`\u{1F4E4} [Agent] Partial output (${d.length} chars) before timeout:
69
- ${d.slice(-2e3)}`),_.kill("SIGTERM"),setTimeout(()=>{_.killed||_.kill("SIGKILL")},5e3)},n),O=new K;O.onToolCall=(I,B)=>{let $=I,L=B;if(I==="mcpToolCall"&&B?.name)$=B.name.replace(/^mcp_+[^_]+_+/,""),$.includes("-")&&$.split("-")[0]===$.split("-")[1]&&($=$.split("-")[0]),L=B.args??B.input??B;else{if(I==="readToolCall"||I==="editToolCall"||I==="writeToolCall")return;(I.startsWith("mcp__")||I.includes("ToolCall"))&&($=I.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if($.includes("memory")?Y.stepMemory(`Tool: ${$}`):Y.stepTool(`Tool: ${$}`),L!=null&&typeof L=="object"&&Object.keys(L).length>0&&!b){let D=JSON.stringify(L),H=D.length>100?`${D.substring(0,100)}...`:D;console.log(` Input: ${H}`)}},_.stdout.on("data",I=>{let B=I.toString();d+=B,g=Date.now(),w||(w=!0);let $=O.processChunk(B);$&&!b&&process.stdout.write($);let L=B.split(`
70
- `).filter(U=>U.trim());y+=L.length}),_.stderr.on("data",I=>{let B=I.toString();p+=B,g=Date.now(),w||(w=!0);let $=B.split(`
71
- `).filter(L=>L.trim());for(let L of $)m.warn(`\u26A0\uFE0F [Agent stderr] ${L}`)}),_.on("close",(I,B)=>{if(b=!0,P(),clearTimeout(E),clearInterval(R),T&&clearInterval(T),C&&clearTimeout(C),c&&!c.aborted)try{c.removeEventListener("abort",M)}catch{}O.flush();let $=Math.round((Date.now()-f)/1e3);if(m.debug(`[Agent] Exited: code=${I}, signal=${B}, elapsed=${$}s, output=${d.length} chars`),h){if(S==="studio-stop"){u(new Error("Stopped from Zibby Studio"));return}if(S==="aborted"){let D=new Error("Aborted via signal");D.name="AbortError",u(D);return}u(new Error(`Cursor Agent timed out after ${$}s (limit: ${n/1e3}s). ${y} lines produced. Last output ${Math.round((Date.now()-g)/1e3)}s ago. ${d.trim()?`
69
+ ${d.slice(-2e3)}`),_.kill("SIGTERM"),setTimeout(()=>{_.killed||_.kill("SIGKILL")},5e3)},n),O=new K;O.onToolCall=(I,U)=>{let $=I,L=U;if(I==="mcpToolCall"&&U?.name)$=U.name.replace(/^mcp_+[^_]+_+/,""),$.includes("-")&&$.split("-")[0]===$.split("-")[1]&&($=$.split("-")[0]),L=U.args??U.input??U;else{if(I==="readToolCall"||I==="editToolCall"||I==="writeToolCall")return;(I.startsWith("mcp__")||I.includes("ToolCall"))&&($=I.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if($.includes("memory")?Y.stepMemory(`Tool: ${$}`):Y.stepTool(`Tool: ${$}`),L!=null&&typeof L=="object"&&Object.keys(L).length>0&&!b){let D=JSON.stringify(L),H=D.length>100?`${D.substring(0,100)}...`:D;console.log(` Input: ${H}`)}},_.stdout.on("data",I=>{let U=I.toString();d+=U,g=Date.now(),w||(w=!0);let $=O.processChunk(U);$&&!b&&process.stdout.write($);let L=U.split(`
70
+ `).filter(B=>B.trim());y+=L.length}),_.stderr.on("data",I=>{let U=I.toString();p+=U,g=Date.now(),w||(w=!0);let $=U.split(`
71
+ `).filter(L=>L.trim());for(let L of $)m.warn(`\u26A0\uFE0F [Agent stderr] ${L}`)}),_.on("close",(I,U)=>{if(b=!0,P(),clearTimeout(E),clearInterval(R),T&&clearInterval(T),C&&clearTimeout(C),c&&!c.aborted)try{c.removeEventListener("abort",M)}catch{}O.flush();let $=Math.round((Date.now()-f)/1e3);if(m.debug(`[Agent] Exited: code=${I}, signal=${U}, elapsed=${$}s, output=${d.length} chars`),h){if(S==="aborted"){let D=new Error("Aborted via signal");D.name="AbortError",u(D);return}u(new Error(`Cursor Agent timed out after ${$}s (limit: ${n/1e3}s). ${y} lines produced. Last output ${Math.round((Date.now()-g)/1e3)}s ago. ${d.trim()?`
72
72
  Partial output (last 500 chars):
73
73
  ${d.slice(-500)}`:"No output captured."}`));return}if(I!==0){u(new Error(`Cursor Agent failed: exit code ${I}, signal ${c}. ${p.trim()?`
74
74
  Stderr: ${p.slice(-1e3)}`:""}${d.trim()?`
75
- Stdout (last 500 chars): ${d.slice(-500)}`:""}`));return}let L=O.getResult(),U=L?JSON.stringify(L,null,2):O.getRawText()||d||"";a({stdout:d||p||"",parsedText:U})}),_.on("error",I=>{if(P(),clearTimeout(E),clearInterval(R),T&&clearInterval(T),C&&clearTimeout(C),c&&!c.aborted)try{c.removeEventListener("abort",M)}catch{}u(new Error(`Cursor Agent spawn error: ${I.message}
75
+ Stdout (last 500 chars): ${d.slice(-500)}`:""}`));return}let L=O.getResult(),B=L?JSON.stringify(L,null,2):O.getRawText()||d||"";a({stdout:d||p||"",parsedText:B})}),_.on("error",I=>{if(P(),clearTimeout(E),clearInterval(R),T&&clearInterval(T),C&&clearTimeout(C),c&&!c.aborted)try{c.removeEventListener("abort",M)}catch{}u(new Error(`Cursor Agent spawn error: ${I.message}
76
76
  Binary: ${e}
77
77
  This usually means the binary is not in PATH. Try:
78
78
  echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};import{AgentStrategy as $n,getSkill as An}from"@zibby/agent-workflow";import{query as Pn}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as On}from"zod-to-json-schema";var ee=class extends $n{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!process.env.ANTHROPIC_API_KEY;return t||m.debug("ClaudeAgentStrategy: ANTHROPIC_API_KEY not set"),t}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,images:o=[],skills:l=null,sessionPath:c=null,nodeName:a=null,timeout:u,config:f={},signal:d=null}=t,p=r;(!p||p==="auto")&&(m.debug(`Model is '${p||"undefined"}', using default: ${F.CLAUDE}`),p=F.CLAUDE);let g=lt[p]||p;lt[p]&&p!==g&&m.debug(`Mapped model: ${p} \u2192 ${g}`),m.debug(`Invoking Claude Agent SDK with model: ${g}, skills: ${JSON.stringify(l)}`);let y=process.env.ANTHROPIC_API_KEY,h=y?` | key: ***${y.slice(-4)}`:" | key: not set";console.log(`
@@ -81,14 +81,14 @@ This usually means the binary is not in PATH. Try:
81
81
  ${S.bold("Prompt sent to LLM:")}`),console.log(S.dim("\u2500".repeat(60))),console.log(S.dim(e)),console.log(S.dim("\u2500".repeat(60)));let{allowedTools:w,mcpServers:b}=this._resolveSkills(l,{sessionPath:c,workspace:n,nodeName:a});try{let v={cwd:n,allowedTools:w,permissionMode:"bypassPermissions",model:g,...Object.keys(b).length>0&&{mcpServers:b}};if(s){let A=typeof s.parse=="function"?On(s,{target:"openApi3"}):s;v.outputFormat={type:"json_schema",schema:A},m.debug("Structured output enforced via SDK outputFormat")}m.debug(`Agent SDK options: ${JSON.stringify({cwd:v.cwd,toolCount:w.length,permissionMode:v.permissionMode,model:v.model,hasOutputFormat:!!v.outputFormat})}`);let N="",P=0,k=[];m.debug("Starting Claude Agent SDK query stream");let _;try{_=Pn({prompt:e,options:v})}catch(x){throw m.error(`Failed to initialize Claude Agent SDK: ${x.message}`),x}let C=null,M=0,T=3;if(d?.aborted){let x=new Error("Aborted via signal");throw x.name="AbortError",x}try{for await(let x of _){if(d?.aborted){let R=new Error("Aborted via signal");throw R.name="AbortError",R}if(k.push(x),x.type==="error"||x.error){let R=x.error?.message||x.error||x.message||"Unknown API error";throw new Error(typeof R=="string"?R:JSON.stringify(R))}let A=JSON.stringify(x.message?.content||x.text||"").slice(0,200);if(A===C){if(M++,M>=T){let R=(x.message?.content?.[0]?.text||x.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${M}x repeated): ${R}`)}}else C=A,M=1;if(x.type==="assistant"||x.constructor?.name==="AssistantMessage"){let R=x.message?.content||x.content||[];for(let E of R)if(E.type==="thinking"&&E.thinking)console.log(`${E.thinking.substring(0,200)}${E.thinking.length>200?"...":""}`);else if(E.type==="text"&&E.text)N+=E.text,E.text.length<500?console.log(`${E.text}`):console.log(`${E.text.substring(0,200)}... (${E.text.length} chars)`);else if(E.type==="tool_use"){P++,E.name.includes("memory")?Y.stepMemory(`Tool: ${E.name}`):Y.stepTool(`Tool: ${E.name}`);let I=JSON.stringify(E.input).substring(0,100);console.log(` Input: ${I}${JSON.stringify(E.input).length>100?"...":""}`)}}else if(!(x.type==="user"&&x.tool_use_result)){if(x.type==="result"||x.constructor?.name==="ResultMessage"){let R=x.result||x.text||x.content||N;if(s){if(x.structured_output){m.debug("Using SDK native structured_output");let O=typeof s.parse=="function"?s.parse(x.structured_output):x.structured_output;return{raw:R,structured:O}}if(R){let E=this._extractJson(R,s);if(E)return{raw:R,structured:E}}m.warn(`Could not extract structured output \u2014 returning raw text (${(R||"").length} chars)`)}return R||""}}}if(m.warn(`Agent SDK ended without result. Collected ${k.length} messages`),N.length>0)return m.debug("Returning accumulated text from messages"),N;throw new Error("Claude Agent SDK query ended without result")}catch(x){throw m.error(`Error during query stream: ${x.message}`),x}}catch(v){throw m.error("Claude Agent SDK call failed",{error:v.message}),v}}_resolveSkills(e,t){if(e===null)return m.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return m.debug("Default IDE skills for code generation"),{allowedTools:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};let r=[],n={};for(let s of e){let o=An(s);if(!o){m.warn(`Unknown skill "${s}" \u2014 skipping`);continue}if(o.allowedTools&&r.push(...o.allowedTools),typeof o.resolve=="function"){let l=o.resolve(t);l&&(n[o.serverName]=l,m.debug(`MCP: ${o.serverName} \u2192 ${l.command} ${l.args[0]}`))}}return{allowedTools:r,mcpServers:n}}_extractJson(e,t){let r=[()=>{if(e.includes("===JSON_START===")){let n=e.indexOf("===JSON_START===")+16,s=e.indexOf("===JSON_END===");return e.substring(n,s).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 n=e.indexOf("{"),s=e.lastIndexOf("}");if(n!==-1&&s>n)return e.substring(n,s+1)}];for(let n of r)try{let s=n();if(!s)continue;let o=JSON.parse(s);if(typeof o!="object"||o===null)continue;return typeof t.parse=="function"?t.parse(o):o}catch{}return null}};import{AgentStrategy as Cn,getSkill as Rn}from"@zibby/agent-workflow";import{execSync as Nn}from"node:child_process";import{zodToJsonSchema as kn}from"zod-to-json-schema";var te=class extends Cn{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.CODEX_API_KEY))return m.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return Nn("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return m.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,skills:o=null,sessionPath:l=null,nodeName:c=null,timeout:a,config:u={},signal:f=null}=t,{Codex:d}=await import("@openai/codex-sdk"),p=r;(!p||p==="auto")&&(m.debug(`Model is '${p||"undefined"}', using default: ${F.CODEX}`),p=F.CODEX);let g=ct[p]||p;ct[p]&&p!==g&&m.debug(`Mapped model: ${p} \u2192 ${g}`),m.debug(`Invoking Codex SDK with model: ${g}, skills: ${JSON.stringify(o)}`);let y=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;y&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=y);let h=y?` | key: ***${y.slice(-4)}`:" | key: not set";console.log(`
82
82
  \u25C6 Model: ${g}${h}
83
83
  `);let S=(await import("chalk")).default;console.log(`
84
- ${S.bold("Prompt sent to LLM:")}`),console.log(S.dim("\u2500".repeat(60))),console.log(S.dim(e)),console.log(S.dim("\u2500".repeat(60)));let w=this._resolveSkillsToMcp(o,{sessionPath:l,workspace:n,nodeName:c}),b={};Object.keys(w).length>0&&(b.mcp_servers=w,m.debug(`[Codex] MCP servers: ${Object.keys(w).join(", ")}`));let N=new d({...Object.keys(b).length>0&&{config:b}}).startThread({workingDirectory:n,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),P=s&&typeof s.parse=="function",k={};if(s)try{let _=P?kn(s,{target:"openAi"}):s;k.outputSchema=_,m.debug("Structured output via SDK outputSchema")}catch(_){m.warn(`[Codex] Schema conversion failed, will extract from text: ${_.message}`)}if(f?.aborted){let _=new Error("Aborted via signal");throw _.name="AbortError",_}try{let{events:_}=await N.runStreamed(e,k),C=0,M="";for await(let T of _){if(f?.aborted){let A=new Error("Aborted via signal");throw A.name="AbortError",A}let x=T.type;if(x==="item.completed"){let A=T.item,R=A?.type;if(R==="mcp_tool_call"){C++;let E=`${A.server}/${A.tool}`;if(Y.stepTool(`Tool: ${E}`),A.arguments){let O=JSON.stringify(A.arguments),I=O.length>100?`${O.substring(0,100)}...`:O;console.log(` Input: ${I}`)}}else if(R==="tool_call"||R==="function_call"||R==="command_execution"){C++;let E=A.name||A.tool||A.command||"unknown";Y.stepTool(`Tool: ${E}`)}else R==="agent_message"&&(M=A.text||"",M.length<500?console.log(M):console.log(`${M.substring(0,200)}... (${M.length} chars)`))}else x==="turn.completed"?m.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(T.usage||{})}`):m.debug(`[Codex] Event: ${x} ${JSON.stringify(T).slice(0,300)}`)}if(m.debug(`[Codex] Last agent message (${M.length} chars): ${M.slice(0,500)}`),s){if(!M)throw new Error("Codex agent returned no response");let T=JSON.parse(M),x=P?s.parse(T):T;return m.debug("\u2705 [Codex] Structured output validated"),{raw:M,structured:x}}return M||""}catch(_){let C=_.message||String(_);throw m.error(`\u274C [Codex] SDK call failed: ${C}`),C.includes("exited with code")&&(m.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),m.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),_}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=Rn(n);if(!s){m.warn(`[Codex] Unknown skill "${n}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let o=s.resolve(t);if(!o)continue;let l=s.serverName||n,c={command:o.command};o.args?.length&&(c.args=o.args),o.env&&Object.keys(o.env).length>0&&(c.env=o.env),r[l]=c,m.debug(`[Codex] MCP: ${l} \u2192 ${o.command} ${(o.args||[]).join(" ")}`)}return r}};import{AgentStrategy as Mn,getSkill as Ln}from"@zibby/agent-workflow";import{execSync as Dn,spawn as Un}from"node:child_process";import{zodToJsonSchema as Bn}from"zod-to-json-schema";import{existsSync as qt,mkdirSync as Qt,readFileSync as er,rmSync as Fn,writeFileSync as tr}from"node:fs";import{join as re}from"node:path";function jn(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 n=0,s=!1,o=!1,l=-1;for(let c=r;c<e.length;c++){let a=e[c];if(s){o?o=!1:a==="\\"?o=!0:a==='"'&&(s=!1);continue}if(a==='"'){s=!0;continue}if(a==="{"){n===0&&(l=c),n+=1;continue}if(a==="}"){if(n===0)continue;if(n-=1,n===0&&l>=0){let u=e.slice(l,c+1);try{return JSON.parse(u)}catch{l=-1}}}}return null}function Gn(i){let e=String(i||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return jn(e)}}function zn(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(n=>typeof n?.text=="string"?n.text:"").join("");if(r.trim())return r}}}catch{}return i}var ne=class extends Mn{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY))return m.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return Dn("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return m.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,skills:o=null,sessionPath:l=null,nodeName:c=null,timeout:a=600*1e3,signal:u=null}=t,f=r;(!f||f==="auto")&&(f=F.GEMINI);let d=Ft[f]||f,p=String(process.env.GEMINI_API_KEY||"").trim(),g=String(process.env.GOOGLE_API_KEY||"").trim(),y=this._resolveSkillsToMcp(o,{sessionPath:l,workspace:n,nodeName:c}),h=Object.keys(y).length>0,S=new fe(e),w=s&&typeof s.parse=="function",b=null;if(s){let $;try{let L=w?Bn(s,{target:"openAi"}):s;$=JSON.stringify(L,null,2)}catch{$="{}"}if(h){S.addSystemInstruction(`Write valid JSON that matches this schema:
85
- ${$}`,"schema_instruction","append");let L=`zibby-result-${Date.now()}.json`,U=re(n,".zibby","tmp");b=re(U,L),Qt(U,{recursive:!0}),S.addStructuredOutput(s,b)}else S.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
84
+ ${S.bold("Prompt sent to LLM:")}`),console.log(S.dim("\u2500".repeat(60))),console.log(S.dim(e)),console.log(S.dim("\u2500".repeat(60)));let w=this._resolveSkillsToMcp(o,{sessionPath:l,workspace:n,nodeName:c}),b={};Object.keys(w).length>0&&(b.mcp_servers=w,m.debug(`[Codex] MCP servers: ${Object.keys(w).join(", ")}`));let N=new d({...Object.keys(b).length>0&&{config:b}}).startThread({workingDirectory:n,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),P=s&&typeof s.parse=="function",k={};if(s)try{let _=P?kn(s,{target:"openAi"}):s;k.outputSchema=_,m.debug("Structured output via SDK outputSchema")}catch(_){m.warn(`[Codex] Schema conversion failed, will extract from text: ${_.message}`)}if(f?.aborted){let _=new Error("Aborted via signal");throw _.name="AbortError",_}try{let{events:_}=await N.runStreamed(e,k),C=0,M="";for await(let T of _){if(f?.aborted){let A=new Error("Aborted via signal");throw A.name="AbortError",A}let x=T.type;if(x==="item.completed"){let A=T.item,R=A?.type;if(R==="mcp_tool_call"){C++;let E=`${A.server}/${A.tool}`;if(Y.stepTool(`Tool: ${E}`),A.arguments){let O=JSON.stringify(A.arguments),I=O.length>100?`${O.substring(0,100)}...`:O;console.log(` Input: ${I}`)}}else if(R==="tool_call"||R==="function_call"||R==="command_execution"){C++;let E=A.name||A.tool||A.command||"unknown";Y.stepTool(`Tool: ${E}`)}else R==="agent_message"&&(M=A.text||"",M.length<500?console.log(M):console.log(`${M.substring(0,200)}... (${M.length} chars)`))}else x==="turn.completed"?m.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(T.usage||{})}`):m.debug(`[Codex] Event: ${x} ${JSON.stringify(T).slice(0,300)}`)}if(m.debug(`[Codex] Last agent message (${M.length} chars): ${M.slice(0,500)}`),s){if(!M)throw new Error("Codex agent returned no response");let T=JSON.parse(M),x=P?s.parse(T):T;return m.debug("\u2705 [Codex] Structured output validated"),{raw:M,structured:x}}return M||""}catch(_){let C=_.message||String(_);throw m.error(`\u274C [Codex] SDK call failed: ${C}`),C.includes("exited with code")&&(m.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),m.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),_}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=Rn(n);if(!s){m.warn(`[Codex] Unknown skill "${n}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let o=s.resolve(t);if(!o)continue;let l=s.serverName||n,c={command:o.command};o.args?.length&&(c.args=o.args),o.env&&Object.keys(o.env).length>0&&(c.env=o.env),r[l]=c,m.debug(`[Codex] MCP: ${l} \u2192 ${o.command} ${(o.args||[]).join(" ")}`)}return r}};import{AgentStrategy as Mn,getSkill as Ln}from"@zibby/agent-workflow";import{execSync as Dn,spawn as Bn}from"node:child_process";import{zodToJsonSchema as Un}from"zod-to-json-schema";import{existsSync as qt,mkdirSync as Qt,readFileSync as er,rmSync as Fn,writeFileSync as tr}from"node:fs";import{join as re}from"node:path";function jn(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 n=0,s=!1,o=!1,l=-1;for(let c=r;c<e.length;c++){let a=e[c];if(s){o?o=!1:a==="\\"?o=!0:a==='"'&&(s=!1);continue}if(a==='"'){s=!0;continue}if(a==="{"){n===0&&(l=c),n+=1;continue}if(a==="}"){if(n===0)continue;if(n-=1,n===0&&l>=0){let u=e.slice(l,c+1);try{return JSON.parse(u)}catch{l=-1}}}}return null}function Gn(i){let e=String(i||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return jn(e)}}function zn(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(n=>typeof n?.text=="string"?n.text:"").join("");if(r.trim())return r}}}catch{}return i}var ne=class extends Mn{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY))return m.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return Dn("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return m.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,skills:o=null,sessionPath:l=null,nodeName:c=null,timeout:a=600*1e3,signal:u=null}=t,f=r;(!f||f==="auto")&&(f=F.GEMINI);let d=Ft[f]||f,p=String(process.env.GEMINI_API_KEY||"").trim(),g=String(process.env.GOOGLE_API_KEY||"").trim(),y=this._resolveSkillsToMcp(o,{sessionPath:l,workspace:n,nodeName:c}),h=Object.keys(y).length>0,S=new fe(e),w=s&&typeof s.parse=="function",b=null;if(s){let $;try{let L=w?Un(s,{target:"openAi"}):s;$=JSON.stringify(L,null,2)}catch{$="{}"}if(h){S.addSystemInstruction(`Write valid JSON that matches this schema:
85
+ ${$}`,"schema_instruction","append");let L=`zibby-result-${Date.now()}.json`,B=re(n,".zibby","tmp");b=re(B,L),Qt(B,{recursive:!0}),S.addStructuredOutput(s,b)}else S.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
86
86
  ${$}`,"json_instruction","append")}let v=S.build(),N=S.getUserPrompt(),P=S.getStats(),k=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),_=k?` | key: ***${k.slice(-4)}`:" | key: not set";console.log(`
87
87
  \u25C6 Model: ${d||"auto"}${_}
88
88
  `);let C=(await import("chalk")).default;console.log(`
89
- ${C.bold("Prompt sent to LLM:")}`),console.log(C.dim("\u2500".repeat(60))),console.log(C.dim(N)),console.log(C.dim("\u2500".repeat(60)));let M=this._createGeminiConfigDir(n,y),T=["--output-format","json"];d&&d!=="auto"&&T.push("--model",d);let x=Object.keys(y);if(x.length>0){T.push("--approval-mode","yolo");for(let $ of x)T.push("--allowed-mcp-server-names",$);m.info(`[Gemini] Enabling MCP servers: ${x.join(", ")}`)}else o&&o.length>0&&m.warn(`[Gemini] Skills requested but no MCP servers configured: ${o.join(", ")}`);T.push("-p",v);let A={...process.env,GEMINI_CLI_HOME:M};p?(A.GEMINI_API_KEY=p,delete A.GOOGLE_API_KEY):g&&(A.GOOGLE_API_KEY=g,delete A.GEMINI_API_KEY),m.debug(`[Gemini] Command: gemini ${T.slice(0,8).join(" ")}... (${T.length} total args)`),m.debug(`[Gemini] User prompt: ${P.userPromptLength} chars, System instructions: ${P.systemInstructionsLength} chars (${P.instructionCount} blocks), Full: ${P.fullPromptLength} chars`),m.debug(`[Gemini] Config home: ${M}`),m.debug(`[Gemini] GEMINI_CLI_HOME env: ${A.GEMINI_CLI_HOME}`);let R="",E=null;try{R=await new Promise((L,U)=>{let D=Un("gemini",T,{cwd:n,env:A,stdio:["ignore","pipe","pipe"],...u&&{signal:u}}),H="",pe="",it=!1,$e=null,at=!1,Ut=setTimeout(()=>{try{D.kill("SIGTERM")}catch{}},a),Ge=()=>{at||it||(at=!0,$e=setTimeout(()=>{if(!it)try{D.kill("SIGKILL")}catch{}},5e3))};u&&(u.aborted?Ge():u.addEventListener("abort",Ge,{once:!0})),D.stdout.on("data",W=>{H+=W.toString()}),D.stderr.on("data",W=>{pe+=W.toString()}),D.on("error",W=>{if(clearTimeout(Ut),$e&&clearTimeout($e),u&&!u.aborted)try{u.removeEventListener("abort",Ge)}catch{}U(W)}),D.on("close",W=>{if(it=!0,clearTimeout(Ut),$e&&clearTimeout($e),u&&!u.aborted)try{u.removeEventListener("abort",Ge)}catch{}if(at){let Bt=new Error("Aborted via signal");return Bt.name="AbortError",U(Bt)}if(W===0)return L(H.trim());U(new Error(`gemini failed with code ${W}: ${(pe||H).trim()}`))})})}catch($){E=$}finally{try{Fn(M,{recursive:!0,force:!0})}catch{}}let O=zn(R).trim();if(!s){if(E)throw E;return O}if(b){let $=qt(b);if(m.info(`[Gemini] Result file: ${$?"present":"missing"} at ${b}`),$)try{let L=er(b,"utf-8").trim(),U=JSON.parse(L),D=w?s.parse(U):U;return m.info("[Gemini] Structured output recovered from result file"),{raw:O,structured:D}}catch(L){m.warn(`[Gemini] Result file parse/validation failed: ${L.message}`)}else E||m.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let I=null;if(s){let $=new K;$.zodSchema=s,$.processChunk(O),$.flush(),I=$.getResult()}if(m.info(`[Gemini] Raw stdout length: ${R.length} chars`),m.info(`[Gemini] Extracted text length: ${O.length} chars`),m.info(`[Gemini] StreamParser result: ${I?"extracted":"null"}`),I||(O.length<2e3?m.info(`[Gemini] Raw text preview:
89
+ ${C.bold("Prompt sent to LLM:")}`),console.log(C.dim("\u2500".repeat(60))),console.log(C.dim(N)),console.log(C.dim("\u2500".repeat(60)));let M=this._createGeminiConfigDir(n,y),T=["--output-format","json"];d&&d!=="auto"&&T.push("--model",d);let x=Object.keys(y);if(x.length>0){T.push("--approval-mode","yolo");for(let $ of x)T.push("--allowed-mcp-server-names",$);m.info(`[Gemini] Enabling MCP servers: ${x.join(", ")}`)}else o&&o.length>0&&m.warn(`[Gemini] Skills requested but no MCP servers configured: ${o.join(", ")}`);T.push("-p",v);let A={...process.env,GEMINI_CLI_HOME:M};p?(A.GEMINI_API_KEY=p,delete A.GOOGLE_API_KEY):g&&(A.GOOGLE_API_KEY=g,delete A.GEMINI_API_KEY),m.debug(`[Gemini] Command: gemini ${T.slice(0,8).join(" ")}... (${T.length} total args)`),m.debug(`[Gemini] User prompt: ${P.userPromptLength} chars, System instructions: ${P.systemInstructionsLength} chars (${P.instructionCount} blocks), Full: ${P.fullPromptLength} chars`),m.debug(`[Gemini] Config home: ${M}`),m.debug(`[Gemini] GEMINI_CLI_HOME env: ${A.GEMINI_CLI_HOME}`);let R="",E=null;try{R=await new Promise((L,B)=>{let D=Bn("gemini",T,{cwd:n,env:A,stdio:["ignore","pipe","pipe"],...u&&{signal:u}}),H="",pe="",it=!1,$e=null,at=!1,Bt=setTimeout(()=>{try{D.kill("SIGTERM")}catch{}},a),Ge=()=>{at||it||(at=!0,$e=setTimeout(()=>{if(!it)try{D.kill("SIGKILL")}catch{}},5e3))};u&&(u.aborted?Ge():u.addEventListener("abort",Ge,{once:!0})),D.stdout.on("data",W=>{H+=W.toString()}),D.stderr.on("data",W=>{pe+=W.toString()}),D.on("error",W=>{if(clearTimeout(Bt),$e&&clearTimeout($e),u&&!u.aborted)try{u.removeEventListener("abort",Ge)}catch{}B(W)}),D.on("close",W=>{if(it=!0,clearTimeout(Bt),$e&&clearTimeout($e),u&&!u.aborted)try{u.removeEventListener("abort",Ge)}catch{}if(at){let Ut=new Error("Aborted via signal");return Ut.name="AbortError",B(Ut)}if(W===0)return L(H.trim());B(new Error(`gemini failed with code ${W}: ${(pe||H).trim()}`))})})}catch($){E=$}finally{try{Fn(M,{recursive:!0,force:!0})}catch{}}let O=zn(R).trim();if(!s){if(E)throw E;return O}if(b){let $=qt(b);if(m.info(`[Gemini] Result file: ${$?"present":"missing"} at ${b}`),$)try{let L=er(b,"utf-8").trim(),B=JSON.parse(L),D=w?s.parse(B):B;return m.info("[Gemini] Structured output recovered from result file"),{raw:O,structured:D}}catch(L){m.warn(`[Gemini] Result file parse/validation failed: ${L.message}`)}else E||m.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let I=null;if(s){let $=new K;$.zodSchema=s,$.processChunk(O),$.flush(),I=$.getResult()}if(m.info(`[Gemini] Raw stdout length: ${R.length} chars`),m.info(`[Gemini] Extracted text length: ${O.length} chars`),m.info(`[Gemini] StreamParser result: ${I?"extracted":"null"}`),I||(O.length<2e3?m.info(`[Gemini] Raw text preview:
90
90
  ${O}`):m.info(`[Gemini] Raw text preview (first 1000 chars):
91
- ${O.slice(0,1e3)}`),I=Gn(O)),!I)throw E||(m.error("[Gemini] Failed to extract valid JSON from output"),m.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?s.parse(I):I;return{raw:O,structured:B}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=Ln(n);if(!s||typeof s.resolve!="function")continue;let o=s.resolve(t);if(!o)continue;let l=s.cursorKey||s.serverName||n,c={command:o.command};o.args?.length&&(c.args=o.args),o.env&&Object.keys(o.env).length>0&&(c.env=o.env),o.cwd&&(c.cwd=o.cwd),r[l]=c}return r}_createGeminiConfigDir(e,t){let r=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,n=re(e||process.cwd(),".zibby","tmp",`gemini-home-${r}`),s=re(n,".gemini");Qt(s,{recursive:!0});let o=re(s,"settings.json"),l={},c=re(process.env.HOME||"",".gemini","settings.json");if(qt(c))try{l=JSON.parse(er(c,"utf-8"))}catch{l={}}let a={...l,mcpServers:{...l.mcpServers&&typeof l.mcpServers=="object"?l.mcpServers:{},...t||{}}};tr(o,`${JSON.stringify(a,null,2)}
91
+ ${O.slice(0,1e3)}`),I=Gn(O)),!I)throw E||(m.error("[Gemini] Failed to extract valid JSON from output"),m.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=w?s.parse(I):I;return{raw:O,structured:U}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=Ln(n);if(!s||typeof s.resolve!="function")continue;let o=s.resolve(t);if(!o)continue;let l=s.cursorKey||s.serverName||n,c={command:o.command};o.args?.length&&(c.args=o.args),o.env&&Object.keys(o.env).length>0&&(c.env=o.env),o.cwd&&(c.cwd=o.cwd),r[l]=c}return r}_createGeminiConfigDir(e,t){let r=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,n=re(e||process.cwd(),".zibby","tmp",`gemini-home-${r}`),s=re(n,".gemini");Qt(s,{recursive:!0});let o=re(s,"settings.json"),l={},c=re(process.env.HOME||"",".gemini","settings.json");if(qt(c))try{l=JSON.parse(er(c,"utf-8"))}catch{l={}}let a={...l,mcpServers:{...l.mcpServers&&typeof l.mcpServers=="object"?l.mcpServers:{},...t||{}}};tr(o,`${JSON.stringify(a,null,2)}
92
92
  `,"utf-8");let u=re(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{tr(u,`${JSON.stringify(a,null,2)}
93
93
  `,"utf-8")}catch{}return m.debug(`[Gemini] Created isolated config with ${Object.keys(a.mcpServers||{}).length} MCP servers`),m.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(a.mcpServers||{}),null,2)}`),n}};import{AgentStrategy as rs,getSkill as Ve}from"@zibby/agent-workflow";var me=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 se=class extends me{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 Ce=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 Ye(i){return Buffer.byteLength(JSON.stringify(i),"utf8")}function He(i,e){let t=String(i||"");if(t.length<=e)return t;let r=Math.max(0,e-28);return`${t.slice(0,r)}
94
94
 
@@ -103,7 +103,7 @@ ${O.slice(0,1e3)}`),I=Gn(O)),!I)throw E||(m.error("[Gemini] Failed to extract va
103
103
  `);let s=(await import("chalk")).default;console.log(s.bold("Prompt sent to LLM:")),console.log(s.dim("\u2500".repeat(60)));let o=!1;for(let l of e)if(l.role==="system")console.log(s.dim(`[System] ${l.content||""}`));else{o||(console.log(s.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),o=!0);let c=l.role==="user"?"Human":"AI",a=l.content?.length>200?`${l.content.slice(0,200)}...`:l.content||"";console.log(s.dim(`[${c}] ${a}`))}console.log(s.dim("\u2500".repeat(60)))}};var ar=!1;function gt(){ar||(Ne(new oe),Ne(new Q),Ne(new ee),Ne(new te),Ne(new ne),ar=!0)}import{existsSync as Me,readdirSync as yr,statSync as ys}from"fs";import{join as G,relative as St,sep as ke,resolve as ie}from"path";import{appendFileSync as as,readFileSync as ls,existsSync as lr,mkdirSync as cs}from"node:fs";import{join as qe}from"node:path";import{DEFAULT_OUTPUT_BASE as cr}from"@zibby/agent-workflow";var ur="run-index.jsonl";function pr(i,e=cr){let t=qe(i,e);return qe(t,ur)}function Qe(i){if(!i||!i.sessionId)return;let e=i.cwd||process.cwd(),t=i.outputBase||cr,r=qe(e,t);lr(r)||cs(r,{recursive:!0});let n=qe(r,ur),s=`${JSON.stringify(i)}
104
104
  `;as(n,s,"utf8")}function fr(i){if(!i||!lr(i))return[];let e;try{e=ls(i,"utf8")}catch{return[]}let t=[];for(let r of e.split(`
105
105
  `)){let n=r.trim();if(n)try{t.push(JSON.parse(n))}catch{}}return t}import{existsSync as us,mkdirSync as ps,readFileSync as fs,readdirSync as sl,statSync as ol,writeFileSync as ds}from"node:fs";import{join as ms}from"node:path";var gs="zibby-run-state.json";function dr(i){return ms(i,gs)}function ht(i){if(!i||typeof i!="string")return null;let e=dr(i);if(!us(e))return null;try{let t=fs(e,"utf8"),r=JSON.parse(t);return r&&typeof r=="object"?r:null}catch{return null}}function et(i,e){if(!i||typeof i!="string")return;try{ps(i,{recursive:!0})}catch{return}let r={...ht(i)||{v:1},...e,v:1,updatedAt:Date.now()};try{ds(dr(i),`${JSON.stringify(r)}
106
- `,"utf8")}catch(n){console.warn(`[zibby run-state] ${n.message}`)}}function hs(i){return i?.recordKind==="progress"}function mr(i){let e=Number(i)||0;return e<=0?0:e<1e12?e*1e3:e}function gr(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:n,progress:s}=i||{};if(!s)return!1;let o=mr(s.ts);if(t>0&&o>0&&r-o>t)return!1;if(!n)return o>0;let l=mr(n.ts);return o>l}function hr(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 n=Number(t.ts)||0;hs(t)?(!r.progress||n>=(Number(r.progress.ts)||0))&&(r.progress=t):(!r.summary||n>=(Number(r.summary.ts)||0))&&(r.summary=t),e.set(t.sessionId,r)}return e}import{DEFAULT_OUTPUT_BASE as ae,SESSIONS_DIR as bt}from"@zibby/agent-workflow";var yt=Object.freeze(["preflight","execute_live","generate_script"]);function wt(i){let e=process.env.ZIBBY_STUDIO_TEST_CASE_ID;return e!=null&&String(e).trim()!==""?String(e).trim():i!=null?String(i):""}var Ss=[G("generate_script","generated-test.spec.js"),G("generate_script","generated-test.spec.ts"),G("generate_script","playwright.spec.ts"),G("generate_script","test.spec.ts")];function bs(i){let e=[G(i,"execute_live","videos"),G(i,"execute_live"),i];for(let t of e){if(!Me(t))continue;let r;try{r=yr(t)}catch{continue}let n=r.find(s=>s.endsWith(".webm"));if(n)return G(t,n)}return null}function ws(i){let e=[G(i,"execute_live","events.json"),G(i,"events.json")];for(let t of e)if(Me(t))return t;return null}function xs(i){for(let e of Ss){let t=G(i,e);if(Me(t))return t}return null}function _s(i){return!i||!Me(i)?{videoPathAbs:null,eventsPathAbs:null,scriptPathAbs:null}:{videoPathAbs:bs(i),eventsPathAbs:ws(i),scriptPathAbs:xs(i)}}function Sr(i){let e=i.cwd||process.cwd(),t=i.outputBase||ae,s=((i.result||{}).state||{}).sessionPath;if(!s||typeof s!="string")return null;let o=s.split(/[/\\]/).filter(Boolean).pop();if(!o)return null;let{videoPathAbs:l,eventsPathAbs:c,scriptPathAbs:a}=_s(s),u=d=>{if(!d)return null;try{return St(e,d).split(ke).join("/")}catch{return null}},f=null;if(i.specPath)try{let d=ie(e,i.specPath);f=St(e,d).split(ke).join("/")}catch{f=String(i.specPath).split(ke).join("/")}return{v:1,recordKind:"summary",ts:Date.now(),sessionId:o,status:i.status??(i.success?"completed":"failed"),cwd:e,outputBase:t,sessionPathAbs:s,sessionDirRel:u(s),videoPathAbs:l||null,eventsPathAbs:c||null,scriptPathAbs:a||null,videoRel:u(l),eventsRel:u(c),scriptRel:u(a),specRel:f,source:process.env.ZIBBY_RUN_SOURCE||"cli",studioTestCaseId:wt(o)||null,errorMessage:i.errorMessage||null}}function br({cwd:i,config:e,result:t,success:r,specPath:n,errorMessage:s}){try{let o=Sr({cwd:i||process.cwd(),result:t,success:r,outputBase:e?.paths?.output||ae,specPath:n,errorMessage:s});o&&(Qe(o),o.sessionPathAbs&&et(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 Es({sessionPath:i,sessionId:e,cwd:t,outputBase:r=ae}={}){let n=t||process.cwd(),s=r||ae,o=e!=null&&String(e).trim()!==""?String(e).trim():null,l=process.env.ZIBBY_RUN_SOURCE==="studio",c=process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim();if(l&&c)return ie(c);let a=i&&String(i).trim();if(a)return ie(a);let u=process.env.ZIBBY_SESSIONS_ROOT&&String(process.env.ZIBBY_SESSIONS_ROOT).trim();return u&&o?ie(G(u,o)):process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim()?ie(String(process.env.ZIBBY_SESSION_PATH).trim()):ie(G(n,s,bt,o||"invalid"))}function Ts(i){try{let e=i?.currentNode;if(!e||!yt.includes(e))return;let t=i.sessionPath,r=i.sessionId||t&&String(t).split(/[/\\]/).filter(Boolean).pop()||null;if(!r)return;let n=i.cwd||process.cwd(),s=i.outputBase||ae,o=yt.indexOf(e),l=i?.specPath!=null?String(i.specPath).trim():"",c=i?.taskDescription!=null?String(i.taskDescription):"",a=null;if(l)try{let f=ie(n,l);a=St(n,f).split(ke).join("/")}catch{a=l.split(ke).join("/")}let u=Es({sessionPath:t,sessionId:r,cwd:n,outputBase:s});Qe({v:1,recordKind:"progress",ts:Date.now(),sessionId:r,cwd:n,outputBase:s,sessionPathAbs:u,activeNode:e,activeStageIndex:o,specRel:a,taskDescription:c||null,studioTestCaseId:wt(r)||null,source:process.env.ZIBBY_RUN_SOURCE||"cli"}),et(u,{sessionId:r,studioTestCaseId:wt(r)||r,status:"running",activeNode:e,activeStageIndex:o,sessionPathAbs:u,cwd:n,outputBase:s,specPath:a||null,task:c||null,taskDescription:c||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 wr({cwd:i,config:e}={}){let t=i||process.cwd(),r=e?.paths?.output||ae;return n=>{Ts({cwd:n?.cwd||t,outputBase:n?.outputBase||r,sessionPath:n?.sessionPath,sessionId:n?.sessionId,currentNode:n?.currentNode,specPath:n?.specPath,taskDescription:n?.taskDescription})}}function xr(i={}){try{let e=i.cwd||process.cwd(),t=i.config?.paths?.output||i.outputBase||ae,r=pr(e,t),n=fr(r),s=hr(n),o=new Set,l=i.errorMessage||"Run stopped (SIGINT/SIGTERM) before a normal summary was written.",c=(f,d)=>{if(!f||!d||o.has(f))return;o.add(f);let p=Sr({cwd:e,outputBase:t,result:{state:{sessionPath:d}},success:!1,specPath:null,status:"interrupted",errorMessage:l});p&&(Qe(p),et(d,{sessionId:f,studioTestCaseId:p.studioTestCaseId||f,status:"interrupted",activeNode:null,activeStageIndex:null,errorMessage:p.errorMessage||null,runSource:p.source||"cli",cwd:e,outputBase:t,sessionPathAbs:d}))};for(let[f,d]of s){if(!gr(d))continue;let p=d.progress;if(!p)continue;let g=String(f),y=p.sessionPathAbs&&String(p.sessionPathAbs)||G(e,t,bt,g);c(g,y)}let a=G(e,t,bt);if(!Me(a))return;let u;try{u=yr(a)}catch{return}for(let f of u){let d=G(a,f),p;try{p=ys(d)}catch{continue}if(!p.isDirectory())continue;let g=ht(d);!g||g.status!=="running"||c(String(f),d)}}catch(e){console.warn(`[zibby browser-test run-index interrupt] ${e.message}`)}}function tt(i){br(i)}function xt(i){xr(i)}function _r(i){return wr(i)}import{spawn as Os}from"node:child_process";import{mkdirSync as Tr,existsSync as Cs,writeFileSync as Rs}from"node:fs";import{join as vt}from"node:path";import{ContextLoader as Ns,WorkflowGraph as ks,Node as Ms,WorkflowState as Ls,DEFAULT_OUTPUT_BASE as vr,SESSIONS_DIR as Ds,SESSION_INFO_FILE as Us}from"@zibby/agent-workflow";import{exec as vs}from"node:child_process";import{promisify as Is}from"node:util";import{existsSync as $s}from"node:fs";import{join as _t}from"node:path";import{homedir as Et}from"node:os";var Er=Is(vs);async function Tt(){try{return await Er("cursor-agent --version"),"cursor-agent"}catch{let e=[_t(Et(),".local","bin","cursor-agent"),_t(Et(),".cursor","bin","cursor-agent"),_t(Et(),".cursor-agent","bin","cursor-agent")];for(let t of e)if($s(t))try{return await Er(`"${t}" --version`),t}catch{}return null}}async function As(){return await Tt()!==null}function Ps(){return`
106
+ `,"utf8")}catch(n){console.warn(`[zibby run-state] ${n.message}`)}}function hs(i){return i?.recordKind==="progress"}function mr(i){let e=Number(i)||0;return e<=0?0:e<1e12?e*1e3:e}function gr(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:n,progress:s}=i||{};if(!s)return!1;let o=mr(s.ts);if(t>0&&o>0&&r-o>t)return!1;if(!n)return o>0;let l=mr(n.ts);return o>l}function hr(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 n=Number(t.ts)||0;hs(t)?(!r.progress||n>=(Number(r.progress.ts)||0))&&(r.progress=t):(!r.summary||n>=(Number(r.summary.ts)||0))&&(r.summary=t),e.set(t.sessionId,r)}return e}import{DEFAULT_OUTPUT_BASE as ae,SESSIONS_DIR as bt}from"@zibby/agent-workflow";var yt=Object.freeze(["preflight","execute_live","generate_script"]);function wt(i){let e=process.env.ZIBBY_STUDIO_TEST_CASE_ID;return e!=null&&String(e).trim()!==""?String(e).trim():i!=null?String(i):""}var Ss=[G("generate_script","generated-test.spec.js"),G("generate_script","generated-test.spec.ts"),G("generate_script","playwright.spec.ts"),G("generate_script","test.spec.ts")];function bs(i){let e=[G(i,"execute_live","videos"),G(i,"execute_live"),i];for(let t of e){if(!Me(t))continue;let r;try{r=yr(t)}catch{continue}let n=r.find(s=>s.endsWith(".webm"));if(n)return G(t,n)}return null}function ws(i){let e=[G(i,"execute_live","events.json"),G(i,"events.json")];for(let t of e)if(Me(t))return t;return null}function xs(i){for(let e of Ss){let t=G(i,e);if(Me(t))return t}return null}function _s(i){return!i||!Me(i)?{videoPathAbs:null,eventsPathAbs:null,scriptPathAbs:null}:{videoPathAbs:bs(i),eventsPathAbs:ws(i),scriptPathAbs:xs(i)}}function Sr(i){let e=i.cwd||process.cwd(),t=i.outputBase||ae,s=((i.result||{}).state||{}).sessionPath;if(!s||typeof s!="string")return null;let o=s.split(/[/\\]/).filter(Boolean).pop();if(!o)return null;let{videoPathAbs:l,eventsPathAbs:c,scriptPathAbs:a}=_s(s),u=d=>{if(!d)return null;try{return St(e,d).split(ke).join("/")}catch{return null}},f=null;if(i.specPath)try{let d=ie(e,i.specPath);f=St(e,d).split(ke).join("/")}catch{f=String(i.specPath).split(ke).join("/")}return{v:1,recordKind:"summary",ts:Date.now(),sessionId:o,status:i.status??(i.success?"completed":"failed"),cwd:e,outputBase:t,sessionPathAbs:s,sessionDirRel:u(s),videoPathAbs:l||null,eventsPathAbs:c||null,scriptPathAbs:a||null,videoRel:u(l),eventsRel:u(c),scriptRel:u(a),specRel:f,source:process.env.ZIBBY_RUN_SOURCE||"cli",studioTestCaseId:wt(o)||null,errorMessage:i.errorMessage||null}}function br({cwd:i,config:e,result:t,success:r,specPath:n,errorMessage:s}){try{let o=Sr({cwd:i||process.cwd(),result:t,success:r,outputBase:e?.paths?.output||ae,specPath:n,errorMessage:s});o&&(Qe(o),o.sessionPathAbs&&et(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 Es({sessionPath:i,sessionId:e,cwd:t,outputBase:r=ae}={}){let n=t||process.cwd(),s=r||ae,o=e!=null&&String(e).trim()!==""?String(e).trim():null,l=process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true",c=process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim();if(l&&c)return ie(c);let a=i&&String(i).trim();if(a)return ie(a);let u=process.env.ZIBBY_SESSIONS_ROOT&&String(process.env.ZIBBY_SESSIONS_ROOT).trim();return u&&o?ie(G(u,o)):process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim()?ie(String(process.env.ZIBBY_SESSION_PATH).trim()):ie(G(n,s,bt,o||"invalid"))}function Ts(i){try{let e=i?.currentNode;if(!e||!yt.includes(e))return;let t=i.sessionPath,r=i.sessionId||t&&String(t).split(/[/\\]/).filter(Boolean).pop()||null;if(!r)return;let n=i.cwd||process.cwd(),s=i.outputBase||ae,o=yt.indexOf(e),l=i?.specPath!=null?String(i.specPath).trim():"",c=i?.taskDescription!=null?String(i.taskDescription):"",a=null;if(l)try{let f=ie(n,l);a=St(n,f).split(ke).join("/")}catch{a=l.split(ke).join("/")}let u=Es({sessionPath:t,sessionId:r,cwd:n,outputBase:s});Qe({v:1,recordKind:"progress",ts:Date.now(),sessionId:r,cwd:n,outputBase:s,sessionPathAbs:u,activeNode:e,activeStageIndex:o,specRel:a,taskDescription:c||null,studioTestCaseId:wt(r)||null,source:process.env.ZIBBY_RUN_SOURCE||"cli"}),et(u,{sessionId:r,studioTestCaseId:wt(r)||r,status:"running",activeNode:e,activeStageIndex:o,sessionPathAbs:u,cwd:n,outputBase:s,specPath:a||null,task:c||null,taskDescription:c||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 wr({cwd:i,config:e}={}){let t=i||process.cwd(),r=e?.paths?.output||ae;return n=>{Ts({cwd:n?.cwd||t,outputBase:n?.outputBase||r,sessionPath:n?.sessionPath,sessionId:n?.sessionId,currentNode:n?.currentNode,specPath:n?.specPath,taskDescription:n?.taskDescription})}}function xr(i={}){try{let e=i.cwd||process.cwd(),t=i.config?.paths?.output||i.outputBase||ae,r=pr(e,t),n=fr(r),s=hr(n),o=new Set,l=i.errorMessage||"Run stopped (SIGINT/SIGTERM) before a normal summary was written.",c=(f,d)=>{if(!f||!d||o.has(f))return;o.add(f);let p=Sr({cwd:e,outputBase:t,result:{state:{sessionPath:d}},success:!1,specPath:null,status:"interrupted",errorMessage:l});p&&(Qe(p),et(d,{sessionId:f,studioTestCaseId:p.studioTestCaseId||f,status:"interrupted",activeNode:null,activeStageIndex:null,errorMessage:p.errorMessage||null,runSource:p.source||"cli",cwd:e,outputBase:t,sessionPathAbs:d}))};for(let[f,d]of s){if(!gr(d))continue;let p=d.progress;if(!p)continue;let g=String(f),y=p.sessionPathAbs&&String(p.sessionPathAbs)||G(e,t,bt,g);c(g,y)}let a=G(e,t,bt);if(!Me(a))return;let u;try{u=yr(a)}catch{return}for(let f of u){let d=G(a,f),p;try{p=ys(d)}catch{continue}if(!p.isDirectory())continue;let g=ht(d);!g||g.status!=="running"||c(String(f),d)}}catch(e){console.warn(`[zibby browser-test run-index interrupt] ${e.message}`)}}function tt(i){br(i)}function xt(i){xr(i)}function _r(i){return wr(i)}import{spawn as Os}from"node:child_process";import{mkdirSync as Tr,existsSync as Cs,writeFileSync as Rs}from"node:fs";import{join as vt}from"node:path";import{ContextLoader as Ns,WorkflowGraph as ks,Node as Ms,WorkflowState as Ls,DEFAULT_OUTPUT_BASE as vr,SESSIONS_DIR as Ds,SESSION_INFO_FILE as Bs}from"@zibby/agent-workflow";import{exec as vs}from"node:child_process";import{promisify as Is}from"node:util";import{existsSync as $s}from"node:fs";import{join as _t}from"node:path";import{homedir as Et}from"node:os";var Er=Is(vs);async function Tt(){try{return await Er("cursor-agent --version"),"cursor-agent"}catch{let e=[_t(Et(),".local","bin","cursor-agent"),_t(Et(),".cursor","bin","cursor-agent"),_t(Et(),".cursor-agent","bin","cursor-agent")];for(let t of e)if($s(t))try{return await Er(`"${t}" --version`),t}catch{}return null}}async function As(){return await Tt()!==null}function Ps(){return`
107
107
  \u274C cursor-agent CLI not found!
108
108
 
109
109
  To use the Cursor agent, install it from:
@@ -132,11 +132,11 @@ ${JSON.stringify(c,null,2)}
132
132
  `)}catch(a){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${a.message}`)}return{success:!0,output:c,raw:l}}async cleanup(){this.adapter&&this.adapter.isConnected()&&await this.adapter.disconnect()}async executePrompt(e,t=process.cwd(),r=3e5,n=null,s=!0){let o=this.agentCommand;if(o==="cursor-agent"){let l=await Tt();l&&(o=l)}return new Promise((l,c)=>{let a="",u=this.buildArgs(e,s);n&&u.push("--model",n);let f={...process.env},d=Os(o,u,{cwd:t,env:f,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),p=setTimeout(()=>{console.log(`
133
133
  \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),c(new Error(`Agent timed out after ${r/1e3}s. The agent may be stuck or waiting for user input.`))},r),g=0,y=Date.now(),h=setInterval(()=>{if(a.length>g)g=a.length,y=Date.now();else{let v=Date.now()-y;v>1e4&&console.log(`\u23F3 AI agent is thinking... (${Math.floor(v/1e3)}s, ${a.length} bytes so far)`)}},1e4),S=()=>{clearTimeout(p),clearInterval(h),d&&!d.killed&&(d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},2e3))},w=()=>{console.log(`
134
134
 
135
- \u{1F6D1} Interrupted by user (Ctrl+C)`),S(),c(new Error("Interrupted by user"))};process.on("SIGINT",w);let b=new K;d.stdout.on("data",v=>{let N=v.toString();a+=N;let P=b.processChunk(N);P&&(process.stdout.write(P,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),y=Date.now(),g+=P.length)}),d.on("close",v=>{process.off("SIGINT",w),clearTimeout(p),clearInterval(h);let N=b.flush();N&&process.stdout.write(N),a=b.getRawText();let P=b.getResult();v===0?l({raw:a,extracted:P}):c(new Error(`Agent exited with code ${v}`))}),d.on("error",v=>{process.off("SIGINT",w),clearTimeout(p),clearInterval(h),c(new Error(`Failed to spawn agent: ${v.message}`))})})}async runSingleNode(e,t,r){let n=t[e];if(!n)throw new Error(`Unknown node: ${e}. Available nodes: ${Object.keys(t).join(", ")}`);let{cwd:s}=r;if(!s)throw new Error("cwd is required for single node execution");let o=r.sessionPath,l=r.sessionTimestamp,c=r.config||{};if(!o){let h=process.env.CI_JOB_ID||process.env.GITHUB_RUN_ID||process.env.CIRCLE_WORKFLOW_ID||process.env.BUILD_ID||Date.now().toString(),S=c.paths?.sessionPrefix,w=S?`${S}_${h}`:h;l=l||Date.now();let b=c.paths?.output||vr;o=vt(s,b,Ds,w),Cs(o)||Tr(o,{recursive:!0})}let a=c.paths?.output||vr,u=vt(s,a,Us);Tr(vt(s,a),{recursive:!0}),Rs(u,JSON.stringify({sessionPath:o,sessionTimestamp:l||o.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
135
+ \u{1F6D1} Interrupted by user (Ctrl+C)`),S(),c(new Error("Interrupted by user"))};process.on("SIGINT",w);let b=new K;d.stdout.on("data",v=>{let N=v.toString();a+=N;let P=b.processChunk(N);P&&(process.stdout.write(P,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),y=Date.now(),g+=P.length)}),d.on("close",v=>{process.off("SIGINT",w),clearTimeout(p),clearInterval(h);let N=b.flush();N&&process.stdout.write(N),a=b.getRawText();let P=b.getResult();v===0?l({raw:a,extracted:P}):c(new Error(`Agent exited with code ${v}`))}),d.on("error",v=>{process.off("SIGINT",w),clearTimeout(p),clearInterval(h),c(new Error(`Failed to spawn agent: ${v.message}`))})})}async runSingleNode(e,t,r){let n=t[e];if(!n)throw new Error(`Unknown node: ${e}. Available nodes: ${Object.keys(t).join(", ")}`);let{cwd:s}=r;if(!s)throw new Error("cwd is required for single node execution");let o=r.sessionPath,l=r.sessionTimestamp,c=r.config||{};if(!o){let h=process.env.CI_JOB_ID||process.env.GITHUB_RUN_ID||process.env.CIRCLE_WORKFLOW_ID||process.env.BUILD_ID||Date.now().toString(),S=c.paths?.sessionPrefix,w=S?`${S}_${h}`:h;l=l||Date.now();let b=c.paths?.output||vr;o=vt(s,b,Ds,w),Cs(o)||Tr(o,{recursive:!0})}let a=c.paths?.output||vr,u=vt(s,a,Bs);Tr(vt(s,a),{recursive:!0}),Rs(u,JSON.stringify({sessionPath:o,sessionTimestamp:l||o.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
136
136
  ${"=".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)}
137
137
  `);let f=await Ns.loadContext(r.specPath||"",s,r.contextConfig||{}),d=new Ls({...r,sessionPath:o,sessionTimestamp:l,context:f}),g=await new Ms(n).execute(this,d);return console.log(`
138
138
  ${"=".repeat(80)}`),console.log(`\u2705 Node ${e} completed`),console.log(`${"=".repeat(80)}
139
- `),{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 n=e.replace(new RegExp(`^${t}/`),"").replace(/\.[^.]+$/,".spec.js");return`${r}/${n}`.replace(/\/+/g,"/")}};function Bs(i,e={}){let t=new Se(e);return t.buildGraph=function(){let r=new ks;return i(r),r},e.onComplete&&(t.onComplete=e.onComplete),t}import{WorkflowGraph as Zu,resolveWorkflowSession as Wu,generateWorkflowSessionId as Vu,clearInheritedSessionEnvForFreshRun as Xu,shouldTrustInheritedSessionEnv as qu,readStudioPinnedSessionPathFromEnv as Qu,syncProcessEnvToSession as ep}from"@zibby/agent-workflow";import{writeFileSync as Ir,existsSync as Fs,mkdirSync as js}from"node:fs";import{join as It}from"node:path";var $t=class i{static saveTitle(e,t){let r=e.state.sessionPath;if(!r)return;let n=i._findInState(e.state,"title")||i._findInState(e.state,"result");if(!(!n||typeof n!="string"))try{let s=It(r,"title.txt");Ir(s,n,"utf-8"),m.info(`Saved title to session: "${n}"`)}catch(s){console.warn("\u26A0\uFE0F Could not save title file:",s.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,n]of Object.entries(e.state)){if(!n||typeof n!="object")continue;let s=Array.isArray(n.actions)&&n.actions.length>0,o=typeof n.scriptPath=="string"&&n.scriptPath.trim().length>0;if(!(!s&&!o))try{let l=It(t,r);Fs(l)||js(l,{recursive:!0});let c=It(l,"result.json");Ir(c,JSON.stringify(n,null,2),"utf-8"),m.info(`Saved execution data to ${r} folder`),await this.onNodeSaved(l,n)}catch(l){console.warn(`\u26A0\uFE0F Could not save execution data for ${r}:`,l.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),n=r.length>0&&r.every(([,o])=>o.success),s=r.some(([,o])=>o.success===!1);if(n)m.info("Workflow completed successfully."),t&&m.info(`Output: ${t}`);else if(s){let o=r.filter(([,l])=>!l.success).map(([l])=>l);m.info(`Workflow completed with failures in: ${o.join(", ")}`),t&&m.info(`Output: ${t}`)}return n}static handle(e,t,r){return this.saveTitle(e,t),this.saveExecutionData(e),this.logResult(e,r)}};import{z as np}from"zod/v3";import{AgentStrategy as zs}from"@zibby/agent-workflow";var $r=[new oe,new Q,new ee,new te,new ne];function Ar(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");m.debug(`Agent selection: requested=${r}`);let n=$r.find(s=>s.getName()===r);if(!n)throw new Error(`Unknown agent '${r}'. Available: ${$r.map(s=>s.getName()).join(", ")}`);if(m.debug(`Checking if ${r} can handle this environment...`),!n.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 m.debug(`Using agent: ${n.getName()}`),n}async function Gs(i,e={},t={}){try{await import("@zibby/skills")}catch{}let r=Ar(e),n=e.state?.config||t.config||{},s=n.models||{},o=t.nodeName&&s[t.nodeName]||null,l=s.default||null,c=r.name,a=n.agent?.[c]?.model||null,u=o||l||a||t.model||null,f={...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:n},d=f.skills||[],p=i;if(d.length>0&&!t.skipPromptFragments){let{getSkill:y}=await import("@zibby/agent-workflow"),h=d.map(S=>{let w=y(S)?.promptFragment;return typeof w=="function"?w():w}).filter(Boolean);h.length>0&&(p+=`
139
+ `),{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 n=e.replace(new RegExp(`^${t}/`),"").replace(/\.[^.]+$/,".spec.js");return`${r}/${n}`.replace(/\/+/g,"/")}};function Us(i,e={}){let t=new Se(e);return t.buildGraph=function(){let r=new ks;return i(r),r},e.onComplete&&(t.onComplete=e.onComplete),t}import{WorkflowGraph as Zu,resolveWorkflowSession as Wu,generateWorkflowSessionId as Vu,clearInheritedSessionEnvForFreshRun as Xu,shouldTrustInheritedSessionEnv as qu,readPinnedSessionPathFromEnv as Qu,syncProcessEnvToSession as ep}from"@zibby/agent-workflow";import{writeFileSync as Ir,existsSync as Fs,mkdirSync as js}from"node:fs";import{join as It}from"node:path";var $t=class i{static saveTitle(e,t){let r=e.state.sessionPath;if(!r)return;let n=i._findInState(e.state,"title")||i._findInState(e.state,"result");if(!(!n||typeof n!="string"))try{let s=It(r,"title.txt");Ir(s,n,"utf-8"),m.info(`Saved title to session: "${n}"`)}catch(s){console.warn("\u26A0\uFE0F Could not save title file:",s.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,n]of Object.entries(e.state)){if(!n||typeof n!="object")continue;let s=Array.isArray(n.actions)&&n.actions.length>0,o=typeof n.scriptPath=="string"&&n.scriptPath.trim().length>0;if(!(!s&&!o))try{let l=It(t,r);Fs(l)||js(l,{recursive:!0});let c=It(l,"result.json");Ir(c,JSON.stringify(n,null,2),"utf-8"),m.info(`Saved execution data to ${r} folder`),await this.onNodeSaved(l,n)}catch(l){console.warn(`\u26A0\uFE0F Could not save execution data for ${r}:`,l.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),n=r.length>0&&r.every(([,o])=>o.success),s=r.some(([,o])=>o.success===!1);if(n)m.info("Workflow completed successfully."),t&&m.info(`Output: ${t}`);else if(s){let o=r.filter(([,l])=>!l.success).map(([l])=>l);m.info(`Workflow completed with failures in: ${o.join(", ")}`),t&&m.info(`Output: ${t}`)}return n}static handle(e,t,r){return this.saveTitle(e,t),this.saveExecutionData(e),this.logResult(e,r)}};import{z as np}from"zod/v3";import{AgentStrategy as zs}from"@zibby/agent-workflow";var $r=[new oe,new Q,new ee,new te,new ne];function Ar(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");m.debug(`Agent selection: requested=${r}`);let n=$r.find(s=>s.getName()===r);if(!n)throw new Error(`Unknown agent '${r}'. Available: ${$r.map(s=>s.getName()).join(", ")}`);if(m.debug(`Checking if ${r} can handle this environment...`),!n.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 m.debug(`Using agent: ${n.getName()}`),n}async function Gs(i,e={},t={}){try{await import("@zibby/skills")}catch{}let r=Ar(e),n=e.state?.config||t.config||{},s=n.models||{},o=t.nodeName&&s[t.nodeName]||null,l=s.default||null,c=r.name,a=n.agent?.[c]?.model||null,u=o||l||a||t.model||null,f={...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:n},d=f.skills||[],p=i;if(d.length>0&&!t.skipPromptFragments){let{getSkill:y}=await import("@zibby/agent-workflow"),h=d.map(S=>{let w=y(S)?.promptFragment;return typeof w=="function"?w():w}).filter(Boolean);h.length>0&&(p+=`
140
140
 
141
141
  ${h.join(`
142
142
 
@@ -231,7 +231,7 @@ async function showRipple(page, locator) {
231
231
  `.trim()}var De=class{static generate(e,t="element"){let{selectors:r}=e;if(!r||typeof r!="object")return this.generateFallbackSelector(e,t);let n=[];return r.role&&n.push(this.generateRoleSelector(r.role)),r.attributes&&n.push(this.generateAttributeSelector(r.attributes)),r.partialMatch&&n.push(this.generatePartialMatchSelector(r.partialMatch)),r.structure&&n.push(this.generateStructuralSelector(r.structure)),n.length===0?this.generateFallbackSelector(e,t):n.length===1?`const ${t} = ${n[0]};`:`const ${t} = ${n[0]}
232
232
  ${n.slice(1).map(o=>` .or(${o})`).join(`
233
233
  `)};`}static generateRoleSelector(e){let{role:t,name:r}=e;if(!t)return null;if(r){let n=this.escapeRegex(r);return`page.getByRole('${t}', { name: /${n}/i })`}return`page.getByRole('${t}')`}static generateAttributeSelector(e){if(!e||typeof e!="object")return null;let t=Object.entries(e).filter(([n,s])=>s!=null).map(([n,s])=>n==="placeholder"||n==="aria-label"?n==="placeholder"?`page.getByPlaceholder('${this.escapeString(s)}')`:`page.locator('[${n}="${this.escapeString(s)}"]')`:`[${n}="${this.escapeString(s)}"]`);if(e.placeholder)return`page.getByPlaceholder('${this.escapeString(e.placeholder)}')`;let r=t.filter(n=>!n.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,n])=>n!==void 0).map(([r,n])=>{let s=n.replace(/^\^/,"");return`[${r}^="${this.escapeString(s)}"]`});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:n}=e;if(n==="fill"||n==="type")return`const ${t} = page.locator('input').first();`;if(n==="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:n,description:s,selectors:o}=e,l=`element${t}`,c=this.generate(e,l),a=this.generateActionMethod(r,l,n);return`${c}
234
- ${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:n,actual:s,passed:o}=e;return r.toLowerCase().includes("url")?`await expect(page).toHaveURL(/${this.escapeRegex(s)}/);`:r.toLowerCase().includes("visible")?"await expect(page.locator('body')).toBeVisible();":`// ${r}`}};import Ue from"fs/promises";var At=class{static async generateFromEvents(e,t,r,n){try{console.log("[TestPostProcessor] \u{1F3AF} Generating test from events.json (100% accurate)");let{readFileSync:s}=await import("fs"),o=JSON.parse(s(t,"utf-8")),l=o.filter(p=>["navigate","type","fill","click","select_option"].includes(p.type)),c=l.filter(p=>p.type!=="navigate");console.log(`[TestPostProcessor] Found ${l.length} action events, ${r.length} trace actions`);let a=`import { ZibbyRuntime } from '@zibby/core';
234
+ ${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:n,actual:s,passed:o}=e;return r.toLowerCase().includes("url")?`await expect(page).toHaveURL(/${this.escapeRegex(s)}/);`:r.toLowerCase().includes("visible")?"await expect(page.locator('body')).toBeVisible();":`// ${r}`}};import Be from"fs/promises";var At=class{static async generateFromEvents(e,t,r,n){try{console.log("[TestPostProcessor] \u{1F3AF} Generating test from events.json (100% accurate)");let{readFileSync:s}=await import("fs"),o=JSON.parse(s(t,"utf-8")),l=o.filter(p=>["navigate","type","fill","click","select_option"].includes(p.type)),c=l.filter(p=>p.type!=="navigate");console.log(`[TestPostProcessor] Found ${l.length} action events, ${r.length} trace actions`);let a=`import { ZibbyRuntime } from '@zibby/core';
235
235
  import { test, expect } from '@playwright/test';
236
236
 
237
237
  `;a+=`test('${n}', async ({ page }) => {
@@ -246,10 +246,10 @@ import { test, expect } from '@playwright/test';
246
246
  `,u++}else if(p.type==="select_option"){let{element:g,values:y}=p.data.params,h=r[u]?.strategies||[],S={name:g,action:"selectOption",value:Array.isArray(y)?y[0]:y,strategies:h};a+=` await ZibbyRuntime.step(page, ${JSON.stringify(S,null,2)});
247
247
 
248
248
  `,u++}a+=`});
249
- `;let{dirname:f}=await import("path"),{mkdirSync:d}=await import("fs");return d(f(e),{recursive:!0}),await Ue.writeFile(e,a,"utf-8"),console.log(`[TestPostProcessor] \u2705 Generated test with ${o.filter(p=>["type","fill","click","select_option"].includes(p.type)).length} actions`),!0}catch(s){return console.warn("[TestPostProcessor] Failed to generate from events:",s.message),!1}}static async enhanceSelectorsWithTrace(e,t,r){try{console.log("[TestPostProcessor] \u{1F6E1}\uFE0F Applying Zibby Safe Action Wrappers...");let n=await Ue.readFile(e,"utf-8");n.includes("ZibbyRuntime")||(n=`import { ZibbyRuntime } from '@zibby/core';
250
- ${n}`);for(let s=0;s<t.length;s++){let o=t[s],l=`element${s}`,c=new RegExp(`const ${l}\\b\\s*=\\s*page\\.[^;]+;(\\s*await ${l}\\.waitFor\\([^)]*\\);)?\\s*await ${l}\\.(click|fill|type|selectOption|pressSequentially)\\(([^)]*)\\);`,"s"),a=n.match(c);if(!a)continue;let u={name:o.name||`Action ${s}`,action:o.method==="type"?"fill":o.method,value:a[3].trim().replace(/^['"]|['"]$/g,""),strategies:o.strategies||[]},f=`await ZibbyRuntime.step(page, ${JSON.stringify(u,null,2)});`;n=n.replace(a[0],f)}return await Ue.writeFile(e,n,"utf-8"),console.log("[TestPostProcessor] \u2705 Successfully converted test to Resilient Zibby format"),!0}catch(n){return console.warn("[TestPostProcessor] Failed to apply safe wrappers:",n.message),!1}}static async enhanceSelectors(e,t){try{let{actions:r=[]}=t;if(!r.length)return!1;let n=await Ue.readFile(e,"utf-8"),s=this.buildSelectorMap(r);return n=this.replaceSimpleSelectors(n,s),await Ue.writeFile(e,n,"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 n=e[r];if(!n.selectors||n.type==="navigate")continue;let s=`element${r}`,l=De.generate(n,s).match(/= (.+);/s);if(l){let c=l[1].trim(),a=`${n.type}:${this.normalizeDescription(n.description)}`;t.set(a,c),n.selectors.role&&t.set(`role:${n.selectors.role.name}`,c),n.selectors.attributes?.placeholder&&t.set(`placeholder:${n.selectors.attributes.placeholder}`,c)}}return t}static replaceSimpleSelectors(e,t){let r=e,n=[/await page\.(getByRole|getByPlaceholder|getByText|getByLabel|locator)\([^)]+\)\.(fill|click|type)\([^)]*\)/g];for(let s of n)r=r.replace(s,o=>{for(let[l,c]of t.entries())if(o.includes(l.split(":")[1])){let a=o.match(/\.(fill|click|type)\(([^)]*)\)/);if(a){let[,u,f]=a,d="element";return`const ${d} = ${c};
251
- await ${d}.${u}(${f})`}}return o});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as Io,existsSync as Mr,readdirSync as Lr}from"node:fs";import{join as Pt}from"node:path";import{execSync as $o}from"node:child_process";import{tmpdir as Ao}from"node:os";var Be=class{static async parseTraceZip(e){let t;if(e.endsWith(".zip")&&Mr(e)){let r=Pt(Ao(),`trace-${Date.now()}`);$o(`unzip -q "${e}" -d "${r}"`,{stdio:"pipe"});let s=Lr(r).find(o=>o.endsWith(".trace"));if(!s)throw new Error("No .trace file found in zip");t=Pt(r,s)}else if(Mr(e)){let n=Lr(e).find(s=>s.endsWith(".trace"));if(!n)throw new Error("No .trace file found");t=Pt(e,n)}else throw new Error(`Trace not found at ${e}`);try{let n=Io(t,"utf-8").trim().split(`
252
- `),s=[],o=new Map,l=new Map;for(let c of n)try{let a=JSON.parse(c);if(a.type==="snapshot"&&a.snapshot&&a.snapshot.accessibility){let u=new Map;for(let f of a.snapshot.accessibility)f.ref&&u.set(f.ref,f);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&&l.set(a.pageId||"default",u)}}catch{}for(let c of n)try{let a=JSON.parse(c);if(a.type==="before"&&a.params&&a.params.selector){let u=a.method;if(["click","fill","type","selectOption"].includes(u)){let f=a.params.selector,d=a.params.text||a.params.value||"",p=[],g=null,y=null,h=null,S=f.match(/aria-ref=([a-z0-9]+)/i);if(S&&a.snapshotName){let T=S[1],x=o.get(a.snapshotName);if(x&&x.has(T)){let A=x.get(T);g=A.name||null,y=A.role||null,h=A.label||null,console.log(`[TraceParser] \u2705 Found ACTUAL element data: text="${g}", role="${y}"`)}}let w=f.match(/internal:text="([^"]+)"/i),b=f.match(/internal:label="([^"]+)"/i),v=f.match(/internal:placeholder="([^"]+)"/i),N=f.match(/internal:role=([^ ]+)/i),P=f.match(/internal:describe="([^"]+)"/i),k=f.match(/name="([^"]+)"/i);if(w){p.push({type:"text",text:w[1]});let T=w[1].split(" ");T.length>1&&(p.push({type:"text",text:T[0],fuzzy:!0}),p.push({type:"text",text:T[T.length-1],fuzzy:!0}))}if(b&&p.push({type:"label",label:b[1]}),v&&p.push({type:"placeholder",placeholder:v[1]}),g){p.unshift({type:"text",text:g,source:"accessibility-tree"});let T=g.split(" ");T.length>1&&p.push({type:"text",text:T[0],fuzzy:!0,source:"accessibility-tree"})}if(y||N){let T=y||N[1],x=g||(k?k[1]:w?w[1]:null);p.unshift({type:"role",role:T,name:x,source:g?"accessibility-tree":"selector"})}if(h&&p.unshift({type:"label",label:h,source:"accessibility-tree"}),P){let T=P[1],x=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],A=null,R=T;for(let E of x)if(T.toLowerCase().endsWith(` ${E}`)){A=E.replace(" ",""),R=T.substring(0,T.length-E.length-1);break}if(A){p.push({type:"role",role:A,name:R});let E=R.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:E}),p.push({type:"text",text:R});let O=R.split(" ");O.length>1&&(p.push({type:"text",text:O[0],fuzzy:!0}),p.push({type:"text",text:O.slice(0,2).join(" "),fuzzy:!0}))}else{let E=T.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:E}),p.push({type:"text",text:T})}}let _=this.extractDOMStrategies(f,l,w?.[1]||P?.[1],a.pageId);p.push(..._);let C=this.extractStructuralContext(f);(C.parent||C.sibling)&&p.forEach(T=>{["role","text","label","testid"].includes(T.type)&&(C.parent&&(T.parent=C.parent),C.sibling&&(T.sibling=C.sibling))}),p.push({type:"css",value:f});let M=g||w?w[1]:P?P[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${s.length}`;s.push({method:u,name:M,action:u==="type"?"fill":u,value:d,strategies:p,timestamp:a.startTime,actualText:g,actualRole:y,actualAriaLabel:h})}}}catch{}return s}catch(r){throw new Error(`Failed to parse trace: ${r.message}`,{cause:r})}}static extractDOMStrategies(e,t,r,n){let s=[];if(!t||t.size===0||!r)return s;try{let o=t.get(n);if(!o)return s;let l=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${l}`,"i"),a=o.match(c);a&&s.push({type:"testid",value:a[1],priority:"high"});let u=new RegExp(`class=["']([^"']+)["'][^>]*>[^<]*${l}`,"gi"),f=o.matchAll(u);for(let g of f){let y=g[1].split(/\s+/).filter(h=>h&&!h.match(/^(css|jss|makeStyles|MuiBox|MuiStack)-\w+/)&&h.length>2);y.length>0&&(s.push({type:"class",value:y.join("."),priority:"medium"}),y.length===1&&s.push({type:"class",value:y[0],priority:"medium"}))}let d=new RegExp(`id=["']([^"']+)["'][^>]*>[^<]*${l}`,"i"),p=o.match(d);p&&!p[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&s.push({type:"id",value:p[1],priority:"high"})}catch(o){console.warn(`[TraceParser] DOM extraction failed: ${o.message}`)}return s}static extractStructuralContext(e){let t={parent:null,sibling:null},r=e.split(">>").map(o=>o.trim());if(r.length>1){let l=r[r.length-2].replace(/internal:text="[^"]+"\s*/gi,"").replace(/internal:role=\S+\s*/gi,"").replace(/internal:label="[^"]+"\s*/gi,"").trim();l&&(l.match(/^(form|section|nav|header|aside|main|article)\b/)||l.includes("[")||l.match(/[#.]\w/))&&(t.parent=l)}let s=r[r.length-1].match(/([^+~]+)\s*[+~]\s*(.+)/);return s&&(t.sibling=s[1].trim()),t}};var Ot=class{static async step(e,t){let{name:r,action:n,value:s,strategies:o,options:l={timeout:1e4},enrichedData:c}=t;console.log(`[Zibby] \u26A1 Executing step: ${r}`),await this.waitForPageStability(e,l.timeout);let a=await this.findBestMatch(e,o,r);if(!a)throw new Error(`[Zibby] \u274C Failed to find "${r}" using ${o.length} strategies`);c?.position&&await this.verifyPosition(a,c.position),await this.performActionWithRetry(e,a,n,s,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 n,s=new MutationObserver(()=>{clearTimeout(n),n=setTimeout(()=>{s.disconnect(),r()},500)});s.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),n=setTimeout(()=>{s.disconnect(),r()},500)})).catch(()=>{})}catch{}}static async verifyPosition(e,t){try{let r=await e.boundingBox();if(!r)return;let n=Math.abs(r.x-t.x),s=Math.abs(r.y-t.y);(n>50||s>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,n,s=3){for(let o=1;o<=s;o++)try{r==="click"?await t.click():r==="fill"?await t.fill(n||""):r==="type"?await t.pressSequentially(n||""):r==="selectOption"&&await t.selectOption(n||"");return}catch(l){if(o===s)throw l;console.log(`[Zibby] \u26A0\uFE0F Action failed (attempt ${o}/${s}), retrying...`),await new Promise(c=>setTimeout(c,1e3*o))}}static async findBestMatch(e,t,r){let s=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(g,y)=>{try{if(!await g.isVisible({timeout:100}))return null;let S=await this.scoreCandidate(g,a,e);return{element:g,strategy:a,score:S,strategyIdx:u,elIdx:y}}catch{return null}}))).filter(g=>g!==null)}catch{return[]}}),l=(await Promise.all(o)).flat();if(l.length===0)return console.log(`[Zibby] \u274C No visible candidates found for "${r}"`),null;l.sort((a,u)=>u.score-a.score);let c=l[0];return console.log(`[Zibby] \u2705 Found element using ${c.strategy.type} (score: ${c.score.toFixed(2)}, ${l.length} candidates)`),c.element}static async scoreCandidate(e,t,r){let n=0;if(n+={testid:120,id:110,role:100,label:90,class:85,placeholder:85,text:80,css:50}[t.type]||50,t.priority==="high"&&(n+=20),t.priority==="medium"&&(n+=10),t.fuzzy&&(n-=15),t.parent)try{await e.locator("xpath=ancestor::*").first().evaluate((c,a)=>c.matches(a),t.parent)&&(n+=30)}catch{}if(t.sibling)try{await e.evaluate((l,c)=>l.parentElement?.querySelector(c)!==null,t.sibling)&&(n+=20)}catch{}try{let o=await e.boundingBox();o&&o.y<1e3&&(n+=10)}catch{}try{let o=await e.evaluate(l=>{let c=0,a=l;for(;a;)a.tagName==="IFRAME"&&c++,a=a.parentElement;return c});n-=o*5}catch{}return n}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 n=t.value?.replace(/aria-ref=e\d+ >> /g,"")||t.css;r=e.locator(n);break}}return t.parent&&(r=r.filter({has:e.locator(t.parent)})),r}};var Ct=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 n=r.timeout||1e4,s=`[data-zibby-id="${t}"]`,o=Date.now();for(;Date.now()-o<n;){await this.injectStableIds(e);let l=e.locator(s);if(await l.count()>0)try{await l.click({timeout:2e3});return}catch(c){if(c.message.includes("intercepts pointer")){await l.click({force:!0});return}}await e.waitForTimeout(200)}throw new Error(`Element ${s} not found after ${n}ms`)}static async fillWithRetry(e,t,r,n=1e4){let s=`[data-zibby-id="${t}"]`,o=Date.now();for(;Date.now()-o<n;){await this.injectStableIds(e);let l=e.locator(s);if(await l.count()>0){await l.fill(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${s} not found after ${n}ms`)}static async selectWithRetry(e,t,r,n=1e4){let s=`[data-zibby-id="${t}"]`,o=Date.now();for(;Date.now()-o<n;){await this.injectStableIds(e);let l=e.locator(s);if(await l.count()>0){await l.selectOption(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${s} not found after ${n}ms`)}static async injectStableIds(e){try{await e.evaluate(()=>{function t(c){if(c.getAttribute("aria-label"))return c.getAttribute("aria-label").trim();let a=c.getAttribute("aria-labelledby");if(a){let d=document.getElementById(a);if(d)return d.textContent.trim()}if(c.id){let d=document.querySelector(`label[for="${c.id}"]`);if(d)return d.textContent.trim()}let u=c.closest("label");if(u){let d=u.cloneNode(!0);d.querySelectorAll("input, select, textarea").forEach(g=>g.remove());let p=d.textContent.trim();if(p)return p}if(c.placeholder)return c.placeholder;let f=c.tagName.toLowerCase();return f==="button"||f==="a"||c.getAttribute("role")==="button"?(c.textContent||"").trim().slice(0,50):c.title?c.title:f==="input"&&(c.type==="submit"||c.type==="button")&&c.value||""}function r(c){let a=[],u=c.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 y=new URL(u.action,window.location.origin).pathname;a.push(`form[action=${y}]`)}catch{a.push(`form[action=${u.getAttribute("action")}]`)}else{let y=document.querySelectorAll("form"),h=Array.from(y).indexOf(u);a.push(`form:nth(${h})`)}let f=c.closest('header, nav, main, footer, aside, [role="banner"], [role="navigation"], [role="main"], [role="contentinfo"]');if(f){let y=f.tagName.toLowerCase(),h=f.getAttribute("role");a.push(h||y)}let d=c.closest('section, article, [role="region"]');if(d){let y=d.querySelector("h1, h2, h3, h4, h5, h6");y&&a.push(`section:${y.textContent.trim().slice(0,30)}`)}let p=c.closest("fieldset");if(p){let y=p.querySelector("legend");y&&a.push(`fieldset:${y.textContent.trim()}`)}let g=c.closest('dialog, [role="dialog"], [role="alertdialog"]');if(g){let y=g.querySelector('[role="heading"], h1, h2, h3');y?a.push(`dialog:${y.textContent.trim().slice(0,30)}`):a.push("dialog")}return a.join("/")}function n(c){let a=c.tagName.toLowerCase(),u=c.id||"",f=c.name||"",d=c.type||"",p=c.getAttribute("role")||"",g="";if(c.href)try{g=new URL(c.href,window.location.origin).pathname.slice(0,50)}catch{g=c.getAttribute("href")?.slice(0,50)||""}let y=t(c).slice(0,50).replace(/\s+/g," "),h=r(c),S=[a,u,f,d,p,g,y,h].join("|"),w=5381;for(let b=0;b<S.length;b++)w=(w<<5)+w^S.charCodeAt(b);return`zibby-${(w>>>0).toString(36)}`}let s=["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,l=0;document.querySelectorAll(s).forEach(c=>{let a=window.getComputedStyle(c);if(a.display==="none"||a.visibility==="hidden")return;let u=n(c),f=u,d=o.get(f)||0;d>0&&(u=`${f}-${d}`),o.set(f,d+1),c.setAttribute("data-zibby-id",u),l++}),console.log(`[Zibby] Injected ${l} stable IDs`)})}catch{}}};var Po=8,Oo=1,Co=64;function Ro(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 n=Math.floor(r);return n<1?8:Math.min(64,n)}import{readFileSync as ko,writeFileSync as Ur,existsSync as Mo}from"node:fs";import{join as Br}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 No}from"node:fs";import{join as Dr}from"node:path";var le=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=Dr(e,"traces"),r=Dr(e,"trace.zip");if(No(r))try{this.traceData=await Be.parseTraceZip(r),console.log(`[TraceTextEnricher] \u2705 Loaded trace with ${this.traceData.length} actions`)}catch(n){console.log(`[TraceTextEnricher] \u26A0\uFE0F Failed to parse trace: ${n.message}`)}}async enrich(e,t){let r=e.data?.params?.ref,n=e.id;if(r===void 0&&n===void 0||(!this.traceData&&t.sessionPath&&await this.loadTrace(t.sessionPath),!this.traceData))return null;let s=this.traceData[n];if(!s)return console.log(`[TraceTextEnricher] \u26A0\uFE0F No trace action for event ${n}`),null;let o=s.actualText||this._extractTextFromSelector(s.selector),l=s.actualRole,c=s.actualAriaLabel;return o||l||c?(console.log(`[TraceTextEnricher] \u2705 Event ${n}: text="${o}", role="${l}", label="${c}"`),{traceActualText:o,traceActualRole:l,traceActualAriaLabel:c,traceSelector:s.selector,traceStrategies:s.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 n=e.match(/getByText\(['"]([^'"]+)['"]\)/);if(n)return n[1];let s=e.match(/name:\s*['"]([^'"]+)['"]/);return s?s[1]:null}};async function Lo(i){let e=Br(i,"events.json"),t=Br(i,"events-enriched.json");if(!Mo(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(ko(e,"utf-8")),n=new le,s=0,o=0;for(let l of r)try{let c=await n.enrich(l,{sessionPath:i});c&&(l.enrichedData={...l.enrichedData||{},...c},s++)}catch(c){console.log(`[PostProcess] Failed to enrich event ${l.id}: ${c.message}`),o++}return s>0&&(Ur(t,JSON.stringify(r,null,2)),Ur(e,JSON.stringify(r,null,2)),console.log(`[PostProcess] \u2705 Enriched ${s} events (${o} failed)`)),{enriched:s,failed:o}}catch(r){return console.log(`[PostProcess] \u274C Failed to post-process events: ${r.message}`),{enriched:0,failed:0}}}import{spawn as Do}from"node:child_process";import{existsSync as Uo}from"node:fs";import{dirname as Bo,resolve as Fr,relative as Fo}from"node:path";var ot=new Map,Fe=8,jr={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 ${Fe} 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}`,n=(ot.get(r)||0)+1;if(ot.set(r,n),n>Fe)return{success:!1,executionCount:n,maxReached:!0,error:`Maximum ${Fe} executions reached. Stop retrying and return your best result.`};let s=e?.projectRoot||process.cwd(),o=Fr(s,i),l=Fo(s,o);return l.startsWith("..")||Fr(o)!==o&&l.includes("..")?{success:!1,executionCount:n,error:"Path traversal detected: scriptPath must be within the project root."}:Uo(o)?new Promise(c=>{let a=Bo(o),u=Do("npx",["playwright","test",o,"--reporter=line"],{cwd:s,env:{...process.env,FORCE_COLOR:"0"}}),f="",d="";u.stdout.on("data",g=>{f+=g.toString()}),u.stderr.on("data",g=>{d+=g.toString()});let p=setTimeout(()=>{u.kill("SIGTERM"),c({success:!1,executionCount:n,error:"Test timed out after 60 seconds",stdout:f.slice(-2e3),stderr:d.slice(-1e3)})},6e4);u.on("close",g=>{clearTimeout(p);let h=`${f}
249
+ `;let{dirname:f}=await import("path"),{mkdirSync:d}=await import("fs");return d(f(e),{recursive:!0}),await Be.writeFile(e,a,"utf-8"),console.log(`[TestPostProcessor] \u2705 Generated test with ${o.filter(p=>["type","fill","click","select_option"].includes(p.type)).length} actions`),!0}catch(s){return console.warn("[TestPostProcessor] Failed to generate from events:",s.message),!1}}static async enhanceSelectorsWithTrace(e,t,r){try{console.log("[TestPostProcessor] \u{1F6E1}\uFE0F Applying Zibby Safe Action Wrappers...");let n=await Be.readFile(e,"utf-8");n.includes("ZibbyRuntime")||(n=`import { ZibbyRuntime } from '@zibby/core';
250
+ ${n}`);for(let s=0;s<t.length;s++){let o=t[s],l=`element${s}`,c=new RegExp(`const ${l}\\b\\s*=\\s*page\\.[^;]+;(\\s*await ${l}\\.waitFor\\([^)]*\\);)?\\s*await ${l}\\.(click|fill|type|selectOption|pressSequentially)\\(([^)]*)\\);`,"s"),a=n.match(c);if(!a)continue;let u={name:o.name||`Action ${s}`,action:o.method==="type"?"fill":o.method,value:a[3].trim().replace(/^['"]|['"]$/g,""),strategies:o.strategies||[]},f=`await ZibbyRuntime.step(page, ${JSON.stringify(u,null,2)});`;n=n.replace(a[0],f)}return await Be.writeFile(e,n,"utf-8"),console.log("[TestPostProcessor] \u2705 Successfully converted test to Resilient Zibby format"),!0}catch(n){return console.warn("[TestPostProcessor] Failed to apply safe wrappers:",n.message),!1}}static async enhanceSelectors(e,t){try{let{actions:r=[]}=t;if(!r.length)return!1;let n=await Be.readFile(e,"utf-8"),s=this.buildSelectorMap(r);return n=this.replaceSimpleSelectors(n,s),await Be.writeFile(e,n,"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 n=e[r];if(!n.selectors||n.type==="navigate")continue;let s=`element${r}`,l=De.generate(n,s).match(/= (.+);/s);if(l){let c=l[1].trim(),a=`${n.type}:${this.normalizeDescription(n.description)}`;t.set(a,c),n.selectors.role&&t.set(`role:${n.selectors.role.name}`,c),n.selectors.attributes?.placeholder&&t.set(`placeholder:${n.selectors.attributes.placeholder}`,c)}}return t}static replaceSimpleSelectors(e,t){let r=e,n=[/await page\.(getByRole|getByPlaceholder|getByText|getByLabel|locator)\([^)]+\)\.(fill|click|type)\([^)]*\)/g];for(let s of n)r=r.replace(s,o=>{for(let[l,c]of t.entries())if(o.includes(l.split(":")[1])){let a=o.match(/\.(fill|click|type)\(([^)]*)\)/);if(a){let[,u,f]=a,d="element";return`const ${d} = ${c};
251
+ await ${d}.${u}(${f})`}}return o});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as Io,existsSync as Mr,readdirSync as Lr}from"node:fs";import{join as Pt}from"node:path";import{execSync as $o}from"node:child_process";import{tmpdir as Ao}from"node:os";var Ue=class{static async parseTraceZip(e){let t;if(e.endsWith(".zip")&&Mr(e)){let r=Pt(Ao(),`trace-${Date.now()}`);$o(`unzip -q "${e}" -d "${r}"`,{stdio:"pipe"});let s=Lr(r).find(o=>o.endsWith(".trace"));if(!s)throw new Error("No .trace file found in zip");t=Pt(r,s)}else if(Mr(e)){let n=Lr(e).find(s=>s.endsWith(".trace"));if(!n)throw new Error("No .trace file found");t=Pt(e,n)}else throw new Error(`Trace not found at ${e}`);try{let n=Io(t,"utf-8").trim().split(`
252
+ `),s=[],o=new Map,l=new Map;for(let c of n)try{let a=JSON.parse(c);if(a.type==="snapshot"&&a.snapshot&&a.snapshot.accessibility){let u=new Map;for(let f of a.snapshot.accessibility)f.ref&&u.set(f.ref,f);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&&l.set(a.pageId||"default",u)}}catch{}for(let c of n)try{let a=JSON.parse(c);if(a.type==="before"&&a.params&&a.params.selector){let u=a.method;if(["click","fill","type","selectOption"].includes(u)){let f=a.params.selector,d=a.params.text||a.params.value||"",p=[],g=null,y=null,h=null,S=f.match(/aria-ref=([a-z0-9]+)/i);if(S&&a.snapshotName){let T=S[1],x=o.get(a.snapshotName);if(x&&x.has(T)){let A=x.get(T);g=A.name||null,y=A.role||null,h=A.label||null,console.log(`[TraceParser] \u2705 Found ACTUAL element data: text="${g}", role="${y}"`)}}let w=f.match(/internal:text="([^"]+)"/i),b=f.match(/internal:label="([^"]+)"/i),v=f.match(/internal:placeholder="([^"]+)"/i),N=f.match(/internal:role=([^ ]+)/i),P=f.match(/internal:describe="([^"]+)"/i),k=f.match(/name="([^"]+)"/i);if(w){p.push({type:"text",text:w[1]});let T=w[1].split(" ");T.length>1&&(p.push({type:"text",text:T[0],fuzzy:!0}),p.push({type:"text",text:T[T.length-1],fuzzy:!0}))}if(b&&p.push({type:"label",label:b[1]}),v&&p.push({type:"placeholder",placeholder:v[1]}),g){p.unshift({type:"text",text:g,source:"accessibility-tree"});let T=g.split(" ");T.length>1&&p.push({type:"text",text:T[0],fuzzy:!0,source:"accessibility-tree"})}if(y||N){let T=y||N[1],x=g||(k?k[1]:w?w[1]:null);p.unshift({type:"role",role:T,name:x,source:g?"accessibility-tree":"selector"})}if(h&&p.unshift({type:"label",label:h,source:"accessibility-tree"}),P){let T=P[1],x=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],A=null,R=T;for(let E of x)if(T.toLowerCase().endsWith(` ${E}`)){A=E.replace(" ",""),R=T.substring(0,T.length-E.length-1);break}if(A){p.push({type:"role",role:A,name:R});let E=R.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:E}),p.push({type:"text",text:R});let O=R.split(" ");O.length>1&&(p.push({type:"text",text:O[0],fuzzy:!0}),p.push({type:"text",text:O.slice(0,2).join(" "),fuzzy:!0}))}else{let E=T.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:E}),p.push({type:"text",text:T})}}let _=this.extractDOMStrategies(f,l,w?.[1]||P?.[1],a.pageId);p.push(..._);let C=this.extractStructuralContext(f);(C.parent||C.sibling)&&p.forEach(T=>{["role","text","label","testid"].includes(T.type)&&(C.parent&&(T.parent=C.parent),C.sibling&&(T.sibling=C.sibling))}),p.push({type:"css",value:f});let M=g||w?w[1]:P?P[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${s.length}`;s.push({method:u,name:M,action:u==="type"?"fill":u,value:d,strategies:p,timestamp:a.startTime,actualText:g,actualRole:y,actualAriaLabel:h})}}}catch{}return s}catch(r){throw new Error(`Failed to parse trace: ${r.message}`,{cause:r})}}static extractDOMStrategies(e,t,r,n){let s=[];if(!t||t.size===0||!r)return s;try{let o=t.get(n);if(!o)return s;let l=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${l}`,"i"),a=o.match(c);a&&s.push({type:"testid",value:a[1],priority:"high"});let u=new RegExp(`class=["']([^"']+)["'][^>]*>[^<]*${l}`,"gi"),f=o.matchAll(u);for(let g of f){let y=g[1].split(/\s+/).filter(h=>h&&!h.match(/^(css|jss|makeStyles|MuiBox|MuiStack)-\w+/)&&h.length>2);y.length>0&&(s.push({type:"class",value:y.join("."),priority:"medium"}),y.length===1&&s.push({type:"class",value:y[0],priority:"medium"}))}let d=new RegExp(`id=["']([^"']+)["'][^>]*>[^<]*${l}`,"i"),p=o.match(d);p&&!p[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&s.push({type:"id",value:p[1],priority:"high"})}catch(o){console.warn(`[TraceParser] DOM extraction failed: ${o.message}`)}return s}static extractStructuralContext(e){let t={parent:null,sibling:null},r=e.split(">>").map(o=>o.trim());if(r.length>1){let l=r[r.length-2].replace(/internal:text="[^"]+"\s*/gi,"").replace(/internal:role=\S+\s*/gi,"").replace(/internal:label="[^"]+"\s*/gi,"").trim();l&&(l.match(/^(form|section|nav|header|aside|main|article)\b/)||l.includes("[")||l.match(/[#.]\w/))&&(t.parent=l)}let s=r[r.length-1].match(/([^+~]+)\s*[+~]\s*(.+)/);return s&&(t.sibling=s[1].trim()),t}};var Ot=class{static async step(e,t){let{name:r,action:n,value:s,strategies:o,options:l={timeout:1e4},enrichedData:c}=t;console.log(`[Zibby] \u26A1 Executing step: ${r}`),await this.waitForPageStability(e,l.timeout);let a=await this.findBestMatch(e,o,r);if(!a)throw new Error(`[Zibby] \u274C Failed to find "${r}" using ${o.length} strategies`);c?.position&&await this.verifyPosition(a,c.position),await this.performActionWithRetry(e,a,n,s,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 n,s=new MutationObserver(()=>{clearTimeout(n),n=setTimeout(()=>{s.disconnect(),r()},500)});s.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),n=setTimeout(()=>{s.disconnect(),r()},500)})).catch(()=>{})}catch{}}static async verifyPosition(e,t){try{let r=await e.boundingBox();if(!r)return;let n=Math.abs(r.x-t.x),s=Math.abs(r.y-t.y);(n>50||s>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,n,s=3){for(let o=1;o<=s;o++)try{r==="click"?await t.click():r==="fill"?await t.fill(n||""):r==="type"?await t.pressSequentially(n||""):r==="selectOption"&&await t.selectOption(n||"");return}catch(l){if(o===s)throw l;console.log(`[Zibby] \u26A0\uFE0F Action failed (attempt ${o}/${s}), retrying...`),await new Promise(c=>setTimeout(c,1e3*o))}}static async findBestMatch(e,t,r){let s=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(g,y)=>{try{if(!await g.isVisible({timeout:100}))return null;let S=await this.scoreCandidate(g,a,e);return{element:g,strategy:a,score:S,strategyIdx:u,elIdx:y}}catch{return null}}))).filter(g=>g!==null)}catch{return[]}}),l=(await Promise.all(o)).flat();if(l.length===0)return console.log(`[Zibby] \u274C No visible candidates found for "${r}"`),null;l.sort((a,u)=>u.score-a.score);let c=l[0];return console.log(`[Zibby] \u2705 Found element using ${c.strategy.type} (score: ${c.score.toFixed(2)}, ${l.length} candidates)`),c.element}static async scoreCandidate(e,t,r){let n=0;if(n+={testid:120,id:110,role:100,label:90,class:85,placeholder:85,text:80,css:50}[t.type]||50,t.priority==="high"&&(n+=20),t.priority==="medium"&&(n+=10),t.fuzzy&&(n-=15),t.parent)try{await e.locator("xpath=ancestor::*").first().evaluate((c,a)=>c.matches(a),t.parent)&&(n+=30)}catch{}if(t.sibling)try{await e.evaluate((l,c)=>l.parentElement?.querySelector(c)!==null,t.sibling)&&(n+=20)}catch{}try{let o=await e.boundingBox();o&&o.y<1e3&&(n+=10)}catch{}try{let o=await e.evaluate(l=>{let c=0,a=l;for(;a;)a.tagName==="IFRAME"&&c++,a=a.parentElement;return c});n-=o*5}catch{}return n}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 n=t.value?.replace(/aria-ref=e\d+ >> /g,"")||t.css;r=e.locator(n);break}}return t.parent&&(r=r.filter({has:e.locator(t.parent)})),r}};var Ct=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 n=r.timeout||1e4,s=`[data-zibby-id="${t}"]`,o=Date.now();for(;Date.now()-o<n;){await this.injectStableIds(e);let l=e.locator(s);if(await l.count()>0)try{await l.click({timeout:2e3});return}catch(c){if(c.message.includes("intercepts pointer")){await l.click({force:!0});return}}await e.waitForTimeout(200)}throw new Error(`Element ${s} not found after ${n}ms`)}static async fillWithRetry(e,t,r,n=1e4){let s=`[data-zibby-id="${t}"]`,o=Date.now();for(;Date.now()-o<n;){await this.injectStableIds(e);let l=e.locator(s);if(await l.count()>0){await l.fill(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${s} not found after ${n}ms`)}static async selectWithRetry(e,t,r,n=1e4){let s=`[data-zibby-id="${t}"]`,o=Date.now();for(;Date.now()-o<n;){await this.injectStableIds(e);let l=e.locator(s);if(await l.count()>0){await l.selectOption(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${s} not found after ${n}ms`)}static async injectStableIds(e){try{await e.evaluate(()=>{function t(c){if(c.getAttribute("aria-label"))return c.getAttribute("aria-label").trim();let a=c.getAttribute("aria-labelledby");if(a){let d=document.getElementById(a);if(d)return d.textContent.trim()}if(c.id){let d=document.querySelector(`label[for="${c.id}"]`);if(d)return d.textContent.trim()}let u=c.closest("label");if(u){let d=u.cloneNode(!0);d.querySelectorAll("input, select, textarea").forEach(g=>g.remove());let p=d.textContent.trim();if(p)return p}if(c.placeholder)return c.placeholder;let f=c.tagName.toLowerCase();return f==="button"||f==="a"||c.getAttribute("role")==="button"?(c.textContent||"").trim().slice(0,50):c.title?c.title:f==="input"&&(c.type==="submit"||c.type==="button")&&c.value||""}function r(c){let a=[],u=c.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 y=new URL(u.action,window.location.origin).pathname;a.push(`form[action=${y}]`)}catch{a.push(`form[action=${u.getAttribute("action")}]`)}else{let y=document.querySelectorAll("form"),h=Array.from(y).indexOf(u);a.push(`form:nth(${h})`)}let f=c.closest('header, nav, main, footer, aside, [role="banner"], [role="navigation"], [role="main"], [role="contentinfo"]');if(f){let y=f.tagName.toLowerCase(),h=f.getAttribute("role");a.push(h||y)}let d=c.closest('section, article, [role="region"]');if(d){let y=d.querySelector("h1, h2, h3, h4, h5, h6");y&&a.push(`section:${y.textContent.trim().slice(0,30)}`)}let p=c.closest("fieldset");if(p){let y=p.querySelector("legend");y&&a.push(`fieldset:${y.textContent.trim()}`)}let g=c.closest('dialog, [role="dialog"], [role="alertdialog"]');if(g){let y=g.querySelector('[role="heading"], h1, h2, h3');y?a.push(`dialog:${y.textContent.trim().slice(0,30)}`):a.push("dialog")}return a.join("/")}function n(c){let a=c.tagName.toLowerCase(),u=c.id||"",f=c.name||"",d=c.type||"",p=c.getAttribute("role")||"",g="";if(c.href)try{g=new URL(c.href,window.location.origin).pathname.slice(0,50)}catch{g=c.getAttribute("href")?.slice(0,50)||""}let y=t(c).slice(0,50).replace(/\s+/g," "),h=r(c),S=[a,u,f,d,p,g,y,h].join("|"),w=5381;for(let b=0;b<S.length;b++)w=(w<<5)+w^S.charCodeAt(b);return`zibby-${(w>>>0).toString(36)}`}let s=["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,l=0;document.querySelectorAll(s).forEach(c=>{let a=window.getComputedStyle(c);if(a.display==="none"||a.visibility==="hidden")return;let u=n(c),f=u,d=o.get(f)||0;d>0&&(u=`${f}-${d}`),o.set(f,d+1),c.setAttribute("data-zibby-id",u),l++}),console.log(`[Zibby] Injected ${l} stable IDs`)})}catch{}}};var Po=8,Oo=1,Co=64;function Ro(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 n=Math.floor(r);return n<1?8:Math.min(64,n)}import{readFileSync as ko,writeFileSync as Br,existsSync as Mo}from"node:fs";import{join as Ur}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 No}from"node:fs";import{join as Dr}from"node:path";var le=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=Dr(e,"traces"),r=Dr(e,"trace.zip");if(No(r))try{this.traceData=await Ue.parseTraceZip(r),console.log(`[TraceTextEnricher] \u2705 Loaded trace with ${this.traceData.length} actions`)}catch(n){console.log(`[TraceTextEnricher] \u26A0\uFE0F Failed to parse trace: ${n.message}`)}}async enrich(e,t){let r=e.data?.params?.ref,n=e.id;if(r===void 0&&n===void 0||(!this.traceData&&t.sessionPath&&await this.loadTrace(t.sessionPath),!this.traceData))return null;let s=this.traceData[n];if(!s)return console.log(`[TraceTextEnricher] \u26A0\uFE0F No trace action for event ${n}`),null;let o=s.actualText||this._extractTextFromSelector(s.selector),l=s.actualRole,c=s.actualAriaLabel;return o||l||c?(console.log(`[TraceTextEnricher] \u2705 Event ${n}: text="${o}", role="${l}", label="${c}"`),{traceActualText:o,traceActualRole:l,traceActualAriaLabel:c,traceSelector:s.selector,traceStrategies:s.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 n=e.match(/getByText\(['"]([^'"]+)['"]\)/);if(n)return n[1];let s=e.match(/name:\s*['"]([^'"]+)['"]/);return s?s[1]:null}};async function Lo(i){let e=Ur(i,"events.json"),t=Ur(i,"events-enriched.json");if(!Mo(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(ko(e,"utf-8")),n=new le,s=0,o=0;for(let l of r)try{let c=await n.enrich(l,{sessionPath:i});c&&(l.enrichedData={...l.enrichedData||{},...c},s++)}catch(c){console.log(`[PostProcess] Failed to enrich event ${l.id}: ${c.message}`),o++}return s>0&&(Br(t,JSON.stringify(r,null,2)),Br(e,JSON.stringify(r,null,2)),console.log(`[PostProcess] \u2705 Enriched ${s} events (${o} failed)`)),{enriched:s,failed:o}}catch(r){return console.log(`[PostProcess] \u274C Failed to post-process events: ${r.message}`),{enriched:0,failed:0}}}import{spawn as Do}from"node:child_process";import{existsSync as Bo}from"node:fs";import{dirname as Uo,resolve as Fr,relative as Fo}from"node:path";var ot=new Map,Fe=8,jr={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 ${Fe} 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}`,n=(ot.get(r)||0)+1;if(ot.set(r,n),n>Fe)return{success:!1,executionCount:n,maxReached:!0,error:`Maximum ${Fe} executions reached. Stop retrying and return your best result.`};let s=e?.projectRoot||process.cwd(),o=Fr(s,i),l=Fo(s,o);return l.startsWith("..")||Fr(o)!==o&&l.includes("..")?{success:!1,executionCount:n,error:"Path traversal detected: scriptPath must be within the project root."}:Bo(o)?new Promise(c=>{let a=Uo(o),u=Do("npx",["playwright","test",o,"--reporter=line"],{cwd:s,env:{...process.env,FORCE_COLOR:"0"}}),f="",d="";u.stdout.on("data",g=>{f+=g.toString()}),u.stderr.on("data",g=>{d+=g.toString()});let p=setTimeout(()=>{u.kill("SIGTERM"),c({success:!1,executionCount:n,error:"Test timed out after 60 seconds",stdout:f.slice(-2e3),stderr:d.slice(-1e3)})},6e4);u.on("close",g=>{clearTimeout(p);let h=`${f}
253
253
  ${d}`.split(`
254
254
  `),S="",w=null;for(let b=0;b<h.length;b++){let v=h[b];if(v.includes("Error:")||v.includes("error:")||v.includes("\u2718")){S+=`${v}
255
255
  `;for(let N=b+1;N<Math.min(b+5,h.length);N++)S+=`${h[N]}
@@ -319,6 +319,6 @@ ${d}`.split(`
319
319
 
320
320
  This will create .zibby/graph.mjs with your workflow definition.`);await g.initialize(f);let y=!1,h=()=>{if(!y)try{xt({cwd:s||process.cwd(),config:e}),y=!0}catch(S){console.warn("[zibby] run-index interrupt row:",S?.message||S)}};process.on("SIGINT",h),process.on("SIGTERM",h);try{if(e.singleNode){console.log(`
321
321
  \u{1F3AF} Running Single Node: ${e.singleNode} (Framework Mode)
322
- `);let _=g.calculateOutputPath(o||i),C=g.buildGraph(),M={};for(let[A,R]of C.nodes.entries())M[A]=R.config||R;let T={};if(e.sessionId){let A=e.sessionId,R=e.paths?.output||qo;if(A==="last"){let B=Ie(s,R,Wr);if(Hr(B)){let{readdirSync:$,statSync:L}=await import("fs"),U=$(B).filter(D=>L(Ie(B,D)).isDirectory()).map(D=>({name:D,time:L(Ie(B,D)).mtimeMs})).sort((D,H)=>H.time-D.time);U.length>0?(A=U[0].name,console.log(`\u{1F4C2} Using latest session: ${A}`)):console.log(`\u26A0\uFE0F No sessions found in ${B}`)}}let E=Ie(s,R,Wr,A),O=Ie(E,"execute_live"),I=Ie(O,Qo);Hr(I)?(console.log(`\u{1F4C2} Loading session: ${A}`),T={sessionPath:E,execute_live_output:JSON.parse(Yr(I,"utf-8"))}):console.log(`\u26A0\uFE0F Session not found: ${E}`)}let x=await g.runSingleNode(e.singleNode,M,{testSpec:u,outputPath:_,cwd:s||process.cwd(),contextConfig:e.contextConfig,specPath:o||i,config:e,...T});return typeof g.onComplete=="function"&&await g.onComplete(x),tt({cwd:s,config:e,result:x,success:!0,specPath:o||i}),x}let S;typeof e.onPipelineProgress=="function"?S=e.onPipelineProgress:e.runIndex?.pipelineProgress!==!1&&(S=_r({cwd:s||process.cwd(),config:e}));let w=s||process.cwd(),b=l!=null&&String(l).trim()!==""?(()=>{let _=String(l).trim();try{return Xo(_)?Zr(_):Zr(w,_)}catch{return _}})():void 0,v=ri(),N=b??v;ti();let P=ei({cwd:w,config:e,traceFrom:"runTest",initialState:{sessionPath:N,sessionTimestamp:c}}),k;try{k=await g.run(u,{testSpec:u,specPath:o||i,cwd:w,config:e,sessionPath:P.sessionPath,sessionTimestamp:P.sessionTimestamp,...S?{onPipelineProgress:S}:{}})}catch(_){throw typeof _?.message=="string"&&_.message.includes("Interrupted by user")&&xt({cwd:s||process.cwd(),config:e}),y||tt({cwd:s,config:e,result:_?.partialResult||{},success:!1,specPath:o||i,errorMessage:_?.message}),_}return tt({cwd:s,config:e,result:k,success:!0,specPath:o||i}),k}finally{process.off("SIGINT",h),process.off("SIGTERM",h),await g.cleanup()}}function si(i){return i.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function oi(i,e){if(i[e])return i[e];let t=si(e);if(i[t])return i[t];let r=`${t}Workflow`;return i[r]?i[r]:null}async function Ku(i=process.cwd()){try{let{join:e}=await import("path"),{existsSync:t}=await import("fs"),{pathToFileURL:r}=await import("url"),n=e(i,".zibby/graph.mjs");if(!t(n))return{available:[],default:null,error:"No .zibby/graph.mjs found"};let s=await import(r(n).href),o=Object.keys(s).filter(c=>c!=="default"&&typeof s[c]=="function"&&s[c].prototype instanceof Se),l=s.BrowserTestAutomationAgent?"BrowserTestAutomationAgent":s.CursorAgent?"CursorAgent":s.default?"default":o[0]||null;return{available:o,default:l,error:null}}catch(e){return{available:[],default:null,error:e.message}}}async function ii(i,e){try{let{join:t}=await import("path"),{existsSync:r}=await import("fs"),{pathToFileURL:n}=await import("url"),s=t(i,".zibby/graph.mjs");if(!r(s))return{agent:null,error:null};let o=await import(n(s).href),l=e.workflow,c;if(l){if(c=oi(o,l),!c){let u=Object.keys(o).filter(f=>f!=="default"&&typeof o[f]=="function");throw new Error(`Workflow "${l}" not found.
322
+ `);let _=g.calculateOutputPath(o||i),C=g.buildGraph(),M={};for(let[A,R]of C.nodes.entries())M[A]=R.config||R;let T={};if(e.sessionId){let A=e.sessionId,R=e.paths?.output||qo;if(A==="last"){let U=Ie(s,R,Wr);if(Hr(U)){let{readdirSync:$,statSync:L}=await import("fs"),B=$(U).filter(D=>L(Ie(U,D)).isDirectory()).map(D=>({name:D,time:L(Ie(U,D)).mtimeMs})).sort((D,H)=>H.time-D.time);B.length>0?(A=B[0].name,console.log(`\u{1F4C2} Using latest session: ${A}`)):console.log(`\u26A0\uFE0F No sessions found in ${U}`)}}let E=Ie(s,R,Wr,A),O=Ie(E,"execute_live"),I=Ie(O,Qo);Hr(I)?(console.log(`\u{1F4C2} Loading session: ${A}`),T={sessionPath:E,execute_live_output:JSON.parse(Yr(I,"utf-8"))}):console.log(`\u26A0\uFE0F Session not found: ${E}`)}let x=await g.runSingleNode(e.singleNode,M,{testSpec:u,outputPath:_,cwd:s||process.cwd(),contextConfig:e.contextConfig,specPath:o||i,config:e,...T});return typeof g.onComplete=="function"&&await g.onComplete(x),tt({cwd:s,config:e,result:x,success:!0,specPath:o||i}),x}let S;typeof e.onPipelineProgress=="function"?S=e.onPipelineProgress:e.runIndex?.pipelineProgress!==!1&&(S=_r({cwd:s||process.cwd(),config:e}));let w=s||process.cwd(),b=l!=null&&String(l).trim()!==""?(()=>{let _=String(l).trim();try{return Xo(_)?Zr(_):Zr(w,_)}catch{return _}})():void 0,v=ri(),N=b??v;ti();let P=ei({cwd:w,config:e,traceFrom:"runTest",initialState:{sessionPath:N,sessionTimestamp:c}}),k;try{k=await g.run(u,{testSpec:u,specPath:o||i,cwd:w,config:e,sessionPath:P.sessionPath,sessionTimestamp:P.sessionTimestamp,...S?{onPipelineProgress:S}:{}})}catch(_){throw typeof _?.message=="string"&&_.message.includes("Interrupted by user")&&xt({cwd:s||process.cwd(),config:e}),y||tt({cwd:s,config:e,result:_?.partialResult||{},success:!1,specPath:o||i,errorMessage:_?.message}),_}return tt({cwd:s,config:e,result:k,success:!0,specPath:o||i}),k}finally{process.off("SIGINT",h),process.off("SIGTERM",h),await g.cleanup()}}function si(i){return i.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function oi(i,e){if(i[e])return i[e];let t=si(e);if(i[t])return i[t];let r=`${t}Workflow`;return i[r]?i[r]:null}async function Ku(i=process.cwd()){try{let{join:e}=await import("path"),{existsSync:t}=await import("fs"),{pathToFileURL:r}=await import("url"),n=e(i,".zibby/graph.mjs");if(!t(n))return{available:[],default:null,error:"No .zibby/graph.mjs found"};let s=await import(r(n).href),o=Object.keys(s).filter(c=>c!=="default"&&typeof s[c]=="function"&&s[c].prototype instanceof Se),l=s.BrowserTestAutomationAgent?"BrowserTestAutomationAgent":s.CursorAgent?"CursorAgent":s.default?"default":o[0]||null;return{available:o,default:l,error:null}}catch(e){return{available:[],default:null,error:e.message}}}async function ii(i,e){try{let{join:t}=await import("path"),{existsSync:r}=await import("fs"),{pathToFileURL:n}=await import("url"),s=t(i,".zibby/graph.mjs");if(!r(s))return{agent:null,error:null};let o=await import(n(s).href),l=e.workflow,c;if(l){if(c=oi(o,l),!c){let u=Object.keys(o).filter(f=>f!=="default"&&typeof o[f]=="function");throw new Error(`Workflow "${l}" not found.
323
323
  Available workflows: ${u.join(", ")}
324
- Supported formats: QuickSmokeWorkflow, QuickSmoke, quick-smoke`)}let a=Object.keys(o).find(u=>o[u]===c);console.log(`\u2713 Using workflow: ${a} (from --workflow ${l})`)}else{if(c=o.BrowserTestAutomationAgent||o.CursorAgent||o.default,!c){let a=Object.keys(o).filter(u=>u!=="default"&&typeof o[u]=="function"&&o[u].prototype instanceof Se);a.length>0&&(c=o[a[0]],console.log(`\u2713 Using workflow: ${a[0]} (auto-detected)`))}if(!c)return{agent:null,error:"Could not find any WorkflowAgent export in local graph.js"};c.name?.includes("auto-detected")||console.log("\u2713 Using local agent from .zibby/graph.mjs")}return{agent:new c(e),error:null}}catch(t){return{agent:null,error:t.message}}}var Xr=class{constructor(e={}){this.config=e}async run(e){return ni(e.spec||e.specPath,{...this.config,...e})}};export{Qr as AGENT_TYPES,Kl as ALL_TOOLS,ce as AccessibilityEnricher,zs as AgentStrategy,oe as AssistantStrategy,Vs as CHAT_MEMORY_TOOLS,Op as CI_ENV_VARS,en as CORE_LOG_LEVELS,Js as CORE_TOOLS,ee as ClaudeAgentStrategy,te as CodexAgentStrategy,Q as CursorAgentStrategy,Po as DEFAULT_MAX_CONCURRENT_RUNS,F as DEFAULT_MODELS,Tp as DEFAULT_OUTPUT_BASE,ve as DOMEnricher,Pp as EVENTS_FILE,X as EnrichmentPipeline,j as EventEnricher,Ys as GITHUB_TOOLS,ne as GeminiAgentStrategy,Ks as JIRA_TOOLS,z as LOG_LEVELS,Dt as LiveEnrichmentRecorder,ze as Logger,Co as MAX_MAX_CONCURRENT_RUNS,we as MCPRefStrategy,Ws as MEMORY_TOOLS,Oo as MIN_MAX_CONCURRENT_RUNS,Re as McpClientManager,se as OpenAIToolProvider,ue as PageStateEnricher,Ee as PlaywrightJsonVerificationStrategy,Te as PositionEnricher,Ap as RAW_OUTPUT_FILE,$p as RESULT_FILE,kr as RIPPLE_EFFECT_SCRIPT,Zs as RUNNER_TOOLS,$t as ResultHandler,vp as SESSIONS_DIR,Ip as SESSION_INFO_FILE,cp as SKILLS,Xs as SKILL_TOOLS,Hs as SLACK_TOOLS,De as SelectorGenerator,Ct as StableIdRuntime,xe as StableIdStrategy,K as StreamingParser,Xr as TestAutomation,V as TestGenerationStrategy,At as TestPostProcessor,_e as TestVerificationStrategy,me as ToolCallProvider,Be as TraceParser,Se as WorkflowAgent,Zu as WorkflowGraph,Ot as ZibbyRuntime,Le as ZibbyUploader,As as checkCursorAgentInstalled,wo as checkCursorAgentPatched,Xu as clearInheritedSessionEnvForFreshRun,oo as clearTokenCache,ho as cloneRepo,Zo as createCustomPipeline,kt as createDefaultPipeline,Mt as createMinimalPipeline,Cr as createUploader,Vo as enrichRecordedEvents,vo as generateRippleHelperCode,Vu as generateWorkflowSessionId,Ar as getAgentStrategy,mp as getAllSkills,xo as getApprovalKeys,Ps as getCursorAgentInstallInstructions,fp as getSkill,dp as hasSkill,To as injectRippleEffect,Gs as invokeAgent,gp as listSkillIds,Ku as listWorkflows,m as logger,co as organizeVideos,bo as patchCursorAgentForCI,Lo as postProcessEvents,Qu as readStudioPinnedSessionPathFromEnv,gt as registerBuiltInStrategies,pp as registerSkill,jo as resetExecutionCount,so as resolveIntegrationToken,Ro as resolveMaxParallelRuns,Wu as resolveWorkflowSession,jr as runPlaywrightTestTool,ni as runTest,Eo as saveApprovalKeys,qu as shouldTrustInheritedSessionEnv,ep as syncProcessEnvToSession,Jo as testGenerationManager,Ho as testVerificationManager,Y as timeline,Bs as workflow,np as z};
324
+ Supported formats: QuickSmokeWorkflow, QuickSmoke, quick-smoke`)}let a=Object.keys(o).find(u=>o[u]===c);console.log(`\u2713 Using workflow: ${a} (from --workflow ${l})`)}else{if(c=o.BrowserTestAutomationAgent||o.CursorAgent||o.default,!c){let a=Object.keys(o).filter(u=>u!=="default"&&typeof o[u]=="function"&&o[u].prototype instanceof Se);a.length>0&&(c=o[a[0]],console.log(`\u2713 Using workflow: ${a[0]} (auto-detected)`))}if(!c)return{agent:null,error:"Could not find any WorkflowAgent export in local graph.js"};c.name?.includes("auto-detected")||console.log("\u2713 Using local agent from .zibby/graph.mjs")}return{agent:new c(e),error:null}}catch(t){return{agent:null,error:t.message}}}var Xr=class{constructor(e={}){this.config=e}async run(e){return ni(e.spec||e.specPath,{...this.config,...e})}};export{Qr as AGENT_TYPES,Kl as ALL_TOOLS,ce as AccessibilityEnricher,zs as AgentStrategy,oe as AssistantStrategy,Vs as CHAT_MEMORY_TOOLS,Op as CI_ENV_VARS,en as CORE_LOG_LEVELS,Js as CORE_TOOLS,ee as ClaudeAgentStrategy,te as CodexAgentStrategy,Q as CursorAgentStrategy,Po as DEFAULT_MAX_CONCURRENT_RUNS,F as DEFAULT_MODELS,Tp as DEFAULT_OUTPUT_BASE,ve as DOMEnricher,Pp as EVENTS_FILE,X as EnrichmentPipeline,j as EventEnricher,Ys as GITHUB_TOOLS,ne as GeminiAgentStrategy,Ks as JIRA_TOOLS,z as LOG_LEVELS,Dt as LiveEnrichmentRecorder,ze as Logger,Co as MAX_MAX_CONCURRENT_RUNS,we as MCPRefStrategy,Ws as MEMORY_TOOLS,Oo as MIN_MAX_CONCURRENT_RUNS,Re as McpClientManager,se as OpenAIToolProvider,ue as PageStateEnricher,Ee as PlaywrightJsonVerificationStrategy,Te as PositionEnricher,Ap as RAW_OUTPUT_FILE,$p as RESULT_FILE,kr as RIPPLE_EFFECT_SCRIPT,Zs as RUNNER_TOOLS,$t as ResultHandler,vp as SESSIONS_DIR,Ip as SESSION_INFO_FILE,cp as SKILLS,Xs as SKILL_TOOLS,Hs as SLACK_TOOLS,De as SelectorGenerator,Ct as StableIdRuntime,xe as StableIdStrategy,K as StreamingParser,Xr as TestAutomation,V as TestGenerationStrategy,At as TestPostProcessor,_e as TestVerificationStrategy,me as ToolCallProvider,Ue as TraceParser,Se as WorkflowAgent,Zu as WorkflowGraph,Ot as ZibbyRuntime,Le as ZibbyUploader,As as checkCursorAgentInstalled,wo as checkCursorAgentPatched,Xu as clearInheritedSessionEnvForFreshRun,oo as clearTokenCache,ho as cloneRepo,Zo as createCustomPipeline,kt as createDefaultPipeline,Mt as createMinimalPipeline,Cr as createUploader,Vo as enrichRecordedEvents,vo as generateRippleHelperCode,Vu as generateWorkflowSessionId,Ar as getAgentStrategy,mp as getAllSkills,xo as getApprovalKeys,Ps as getCursorAgentInstallInstructions,fp as getSkill,dp as hasSkill,To as injectRippleEffect,Gs as invokeAgent,gp as listSkillIds,Ku as listWorkflows,m as logger,co as organizeVideos,bo as patchCursorAgentForCI,Lo as postProcessEvents,Qu as readPinnedSessionPathFromEnv,gt as registerBuiltInStrategies,pp as registerSkill,jo as resetExecutionCount,so as resolveIntegrationToken,Ro as resolveMaxParallelRuns,Wu as resolveWorkflowSession,jr as runPlaywrightTestTool,ni as runTest,Eo as saveApprovalKeys,qu as shouldTrustInheritedSessionEnv,ep as syncProcessEnvToSession,Jo as testGenerationManager,Ho as testVerificationManager,Y as timeline,Us as workflow,np as z};
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/core",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Core test automation engine with multi-agent and multi-MCP support",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -69,7 +69,7 @@
69
69
  "node": ">=18.0.0"
70
70
  },
71
71
  "dependencies": {
72
- "@zibby/agent-workflow": "^0.2.0",
72
+ "@zibby/agent-workflow": "^0.3.0",
73
73
  "@anthropic-ai/claude-agent-sdk": "^0.2.104",
74
74
  "@anthropic-ai/sdk": "^0.88.0",
75
75
  "@modelcontextprotocol/sdk": "^1.29.0",