@zibby/core 0.5.37 → 0.5.38

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
@@ -39,10 +39,10 @@ ${c}
39
39
 
40
40
  Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,l={model:se.OPENAI_POSTPROCESSING,messages:[{role:"user",content:a}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:s,strict:!0}}};f.info(`\u{1F4E4} Sending to OpenAI proxy: model=${se.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(s.properties||{}).join(", ")}`),f.debug(` Schema size: ${JSON.stringify(s).length} chars`),f.debug(` Prompt size: ${a.length} chars`);try{let u={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(u["x-proxy-token"]=t,u["x-execution-id"]=process.env.EXECUTION_ID||""):(u.Authorization=`Bearer ${t}`,u["x-api-key"]=process.env.ZIBBY_API_KEY||"",u["x-execution-id"]=process.env.EXECUTION_ID||"");let m=(await Jn.post(r,l,{headers:u,timeout:ct.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!m)throw new Error("OpenAI proxy returned empty response");let p=JSON.parse(m);return f.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:p,raw:o}}catch(u){if(u.response){let d=u.response.status,m=u.response.data;throw f.error(`\u274C OpenAI proxy request failed: ${d}`),f.error(` Status: ${d}`),f.error(` Response: ${JSON.stringify(m,null,2)}`),d===401||d===403?new Error(`Authentication failed for OpenAI proxy.
41
41
  Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
42
- Response: ${JSON.stringify(m)}`,{cause:u}):new Error(`Failed to format Cursor output: ${m?.error?.message||"Unknown error"}`,{cause:u})}throw f.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}function V(o){let e=`${o}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let r=t.split(/[,\n]+/).map(i=>i.trim()).filter(Boolean);if(r.length===0)return{picked:null,count:0,dispose:()=>{}};let n=r[Math.floor(Math.random()*r.length)],s=process.env[o];return process.env[o]=n,f.debug(`[auth-pool] ${o}: picked 1 of ${r.length} from pool (***${n.slice(-4)})`),{picked:n,count:r.length,dispose(){s===void 0?delete process.env[o]:process.env[o]=s}}}import{timeline as re,Timeline as Sa,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as _a}from"@zibby/agent-workflow";import{copyFileSync as Xn,existsSync as $t,lstatSync as Qn,mkdirSync as fr,rmSync as eo,symlinkSync as to,unlinkSync as ro}from"node:fs";import{join as ne}from"node:path";import{homedir as no}from"node:os";import{randomBytes as oo}from"node:crypto";var so=["cli-config.json","config.json","auth.json","argv.json"];function dr(o){return!(!o||typeof o!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function mr(o){let e=ne(o||process.cwd(),".zibby","tmp");fr(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${oo(4).toString("hex")}`,r=ne(e,`cursor-agent-home-${t}`),n=ne(r,".cursor");fr(n,{recursive:!0});let s=no(),i=ne(s,".cursor");if($t(i))for(let c of so){let a=ne(i,c);if($t(a))try{Xn(a,ne(n,c))}catch{}}if(process.platform==="darwin"){let c=ne(s,"Library");if($t(c))try{to(c,ne(r,"Library"))}catch{}}return r}function gr(o){if(!(!o||typeof o!="string"))try{let e=ne(o,"Library");try{Qn(e).isSymbolicLink()&&ro(e)}catch{}eo(o,{recursive:!0,force:!0})}catch{}}var ue=class extends io{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[ee(Je(),".local","bin","cursor-agent"),ee(Je(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"];for(let r of t)try{if(r.startsWith("/")){_r(r,wr.X_OK);let n=ce(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(n&&n.length>0)return f.debug(`[Cursor] Found agent at: ${r} (version: ${n.trim().slice(0,50)})`),!0}else{let n=ce(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!n)continue;let s=ce(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return f.debug(`[Cursor] Found '${r}' in PATH at ${n} (version: ${s.trim().slice(0,50)})`),!0}}catch{continue}return f.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:r=process.cwd(),print:n=!1,schema:s=null,skills:i=null,sessionPath:c=null,nodeName:a=null,timeout:l=ct.CURSOR_AGENT_DEFAULT,config:u={},signal:d=null}=t,m=u?.agent?.strictMode||!1,p=t.model??u?.agent?.cursor?.model??se.CURSOR,g=V("CURSOR_API_KEY");try{f.debug(`[Cursor] Invoking (model: ${p}, timeout: ${l/1e3}s, skills: ${JSON.stringify(i)})`);let h=(this._setupMcpConfig(c,r,u,i,a)||{}).isolatedMcpHome??null,b=[ee(Je(),".local","bin","cursor-agent"),ee(Je(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"],S=null;for(let v of b)try{if(v.startsWith("/"))_r(v,wr.X_OK),ce(`"${v}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!ce(`which ${v}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");ce(`${v} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}S=v,f.debug(`[Agent] Using binary: ${v}`);break}catch(w){f.debug(`[Agent] Binary '${v}' check failed: ${w.message}`);continue}if(!S)throw new Error(`Cursor Agent CLI not found or not working.
42
+ Response: ${JSON.stringify(m)}`,{cause:u}):new Error(`Failed to format Cursor output: ${m?.error?.message||"Unknown error"}`,{cause:u})}throw f.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}function V(o){let e=`${o}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let r=t.split(/[,\n]+/).map(i=>i.trim()).filter(Boolean);if(r.length===0)return{picked:null,count:0,dispose:()=>{}};let n=r[Math.floor(Math.random()*r.length)],s=process.env[o];return process.env[o]=n,f.debug(`[auth-pool] ${o}: picked 1 of ${r.length} from pool (***${n.slice(-4)})`),{picked:n,count:r.length,dispose(){s===void 0?delete process.env[o]:process.env[o]=s}}}import{timeline as re,Timeline as Sa,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as _a}from"@zibby/agent-workflow";import{copyFileSync as Xn,existsSync as $t,lstatSync as Qn,mkdirSync as fr,rmSync as eo,symlinkSync as to,unlinkSync as ro}from"node:fs";import{join as ne}from"node:path";import{homedir as no}from"node:os";import{randomBytes as oo}from"node:crypto";var so=["cli-config.json","config.json","auth.json","argv.json"];function dr(o){return!(!o||typeof o!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function mr(o){let e=ne(o||process.cwd(),".zibby","tmp");fr(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${oo(4).toString("hex")}`,r=ne(e,`cursor-agent-home-${t}`),n=ne(r,".cursor");fr(n,{recursive:!0});let s=no(),i=ne(s,".cursor");if($t(i))for(let c of so){let a=ne(i,c);if($t(a))try{Xn(a,ne(n,c))}catch{}}if(process.platform==="darwin"){let c=ne(s,"Library");if($t(c))try{to(c,ne(r,"Library"))}catch{}}return r}function gr(o){if(!(!o||typeof o!="string"))try{let e=ne(o,"Library");try{Qn(e).isSymbolicLink()&&ro(e)}catch{}eo(o,{recursive:!0,force:!0})}catch{}}var ue=class extends io{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[ee(Je(),".local","bin","cursor-agent"),ee(Je(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"];for(let r of t)try{if(r.startsWith("/")){_r(r,wr.X_OK);let n=ce(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(n&&n.length>0)return f.debug(`[Cursor] Found agent at: ${r} (version: ${n.trim().slice(0,50)})`),!0}else{let n=ce(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!n)continue;let s=ce(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return f.debug(`[Cursor] Found '${r}' in PATH at ${n} (version: ${s.trim().slice(0,50)})`),!0}}catch{continue}return f.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:r=process.cwd(),print:n=!1,schema:s=null,skills:i=null,sessionPath:c=null,nodeName:a=null,timeout:l=ct.CURSOR_AGENT_DEFAULT,config:u={},signal:d=null}=t,m=u?.agent?.strictMode||!1,p=t.model??u?.agent?.cursor?.model??se.CURSOR,g=V("CURSOR_API_KEY");try{f.debug(`[Cursor] Invoking (model: ${p}, timeout: ${l/1e3}s, skills: ${JSON.stringify(i)})`);let h=(this._setupMcpConfig(c,r,u,i,a)||{}).isolatedMcpHome??null,b=[ee(Je(),".local","bin","cursor-agent"),ee(Je(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"],S=null;for(let $ of b)try{if($.startsWith("/"))_r($,wr.X_OK),ce(`"${$}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!ce(`which ${$}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");ce(`${$} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}S=$,f.debug(`[Agent] Using binary: ${$}`);break}catch(w){f.debug(`[Agent] Binary '${$}' check failed: ${w.message}`);continue}if(!S)throw new Error(`Cursor Agent CLI not found or not working.
43
43
 
44
44
  Checked paths:
45
- ${b.map(v=>` - ${v}`).join(`
45
+ ${b.map($=>` - ${$}`).join(`
46
46
  `)}
47
47
 
48
48
  Install cursor-agent:
@@ -51,67 +51,67 @@ Install cursor-agent:
51
51
  Then add to PATH:
52
52
  echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
53
53
 
54
- Test with: agent --version`);let x=new Ee(e),_=null;if(s){let v=`zibby-result-${Date.now()}.json`;_=ee(r,".zibby","tmp",v);let w=ee(r,".zibby","tmp");Ke(w)||Sr(w,{recursive:!0}),x.addStructuredOutput(s,_)}let C=process.env.CURSOR_API_KEY,k=C?` | key: ***${C.slice(-4)}`:" | key: not set";console.log(`
54
+ Test with: agent --version`);let x=new Ee(e),_=null;if(s){let $=`zibby-result-${Date.now()}.json`;_=ee(r,".zibby","tmp",$);let w=ee(r,".zibby","tmp");Ke(w)||Sr(w,{recursive:!0}),x.addStructuredOutput(s,_)}let I=process.env.CURSOR_API_KEY,k=I?` | key: ***${I.slice(-4)}`:" | key: not set";console.log(`
55
55
  \u25C6 Model: ${p||"auto"}${k}
56
- `);let N=(await import("chalk")).default,I=x.getUserPrompt();console.log(`
57
- ${N.bold("Prompt sent to LLM:")}`),console.log(N.dim("\u2500".repeat(60))),console.log(N.dim(I)),console.log(N.dim("\u2500".repeat(60)));let M=x.build(),F=x.getStats(),P=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",p||"auto"];if(process.env.CURSOR_API_KEY&&P.push("--api-key",process.env.CURSOR_API_KEY),P.push(M),f.debug(`[Agent] User prompt: ${F.userPromptLength} chars, System instructions: ${F.systemInstructionsLength} chars (${F.instructionCount} blocks), Full: ${F.fullPromptLength} chars, model: ${p||"auto"}`),f.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 D,U=null;try{let v=c||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);D=await this._spawnWithStreaming(S,P,r,l,null,v,h,d)}catch(v){U=v}let E=D?.stdout||"";if(s){let v=typeof s.parse=="function",w=null,R=!!(_&&Ke(_));if(_&&f.info(`[Agent] Result file: ${R?"present":"missing"} at ${_}`),R)try{let O=br(_,"utf-8").trim();w=JSON.parse(O),f.info(`[Agent] Parsed JSON from result file OK (${O.length} chars) \u2192 object ready for validation`),U&&f.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(O){f.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${O.message}`)}else if(U)f.warn(`[Agent] Result file missing at ${_} (agent process error \u2014 may still recover if strictMode repairs)`);else throw f.error(`\u274C [Agent] Result file was never created at ${_}`),new Error(`Agent did not write required result file at ${_}`);if(w&&v)try{let O=s.parse(w);return f.info("\u2705 [Agent] Zod validation passed for structured result file"),m&&f.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:E,structured:O}}catch(O){let G=O.issues?O.issues.map(A=>` - ${A.path.join(".")}: ${A.message}`).join(`
56
+ `);let N=(await import("chalk")).default,C=x.getUserPrompt();console.log(`
57
+ ${N.bold("Prompt sent to LLM:")}`),console.log(N.dim("\u2500".repeat(60))),console.log(N.dim(C)),console.log(N.dim("\u2500".repeat(60)));let M=x.build(),F=x.getStats(),P=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",p||"auto"];if(process.env.CURSOR_API_KEY&&P.push("--api-key",process.env.CURSOR_API_KEY),P.push(M),f.debug(`[Agent] User prompt: ${F.userPromptLength} chars, System instructions: ${F.systemInstructionsLength} chars (${F.instructionCount} blocks), Full: ${F.fullPromptLength} chars, model: ${p||"auto"}`),f.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 D,U=null;try{let $=c||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);D=await this._spawnWithStreaming(S,P,r,l,null,$,h,d)}catch($){U=$}let E=D?.stdout||"";if(s){let $=typeof s.parse=="function",w=null,R=!!(_&&Ke(_));if(_&&f.info(`[Agent] Result file: ${R?"present":"missing"} at ${_}`),R)try{let O=br(_,"utf-8").trim();w=JSON.parse(O),f.info(`[Agent] Parsed JSON from result file OK (${O.length} chars) \u2192 object ready for validation`),U&&f.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(O){f.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${O.message}`)}else if(U)f.warn(`[Agent] Result file missing at ${_} (agent process error \u2014 may still recover if strictMode repairs)`);else throw f.error(`\u274C [Agent] Result file was never created at ${_}`),new Error(`Agent did not write required result file at ${_}`);if(w&&$)try{let O=s.parse(w);return f.info("\u2705 [Agent] Zod validation passed for structured result file"),m&&f.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:E,structured:O}}catch(O){let G=O.issues?O.issues.map(v=>` - ${v.path.join(".")}: ${v.message}`).join(`
59
59
  `):O.message?.slice(0,400);if(f.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
60
60
  ${G}`),f.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
61
61
  ${JSON.stringify(w,null,2).slice(0,500)}`),!m)throw new Error(`Agent output failed schema validation:
62
62
  ${G}
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:O})}else{if(w)return f.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),m&&f.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:E,structured:w};R&&f.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(m&&!U){let O=D.parsedText,G=w?JSON.stringify(w):O;f.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${G.length} chars in)`);try{let A=await pr(G,s);if(v){let B=s.parse(A.structured);return f.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:E,structured:B}}return{raw:E,...A}}catch(A){if(f.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${A.message}`),w)return f.warn("[Agent] Using agent's original result file as fallback"),{raw:E,structured:w}}}if(U)throw U;let L=R?w==null?"file existed but JSON.parse failed \u2014 see WARN log above":v?"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 f.error(`\u274C [Agent] No validated structured output: ${L}`),f.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 ${_}. Enable strictMode for proxy fallback.`)}if(U)throw U;return this._extractFinalResult(E)||D?.parsedText||E}finally{g.dispose()}}_extractFinalResult(e){if(!e)return null;let t=e.split(`
65
+ Enable strictMode in .zibby.config.js for automatic repair.`,{cause:O})}else{if(w)return f.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),m&&f.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:E,structured:w};R&&f.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(m&&!U){let O=D.parsedText,G=w?JSON.stringify(w):O;f.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${G.length} chars in)`);try{let v=await pr(G,s);if($){let B=s.parse(v.structured);return f.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:E,structured:B}}return{raw:E,...v}}catch(v){if(f.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${v.message}`),w)return f.warn("[Agent] Using agent's original result file as fallback"),{raw:E,structured:w}}}if(U)throw U;let L=R?w==null?"file existed but JSON.parse failed \u2014 see WARN log above":$?"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 f.error(`\u274C [Agent] No validated structured output: ${L}`),f.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 ${_}. Enable strictMode for proxy fallback.`)}if(U)throw U;return this._extractFinalResult(E)||D?.parsedText||E}finally{g.dispose()}}_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 i=JSON.parse(s);if(i.type==="assistant"&&i.message?.content){let c=i.message.content;if(Array.isArray(c)){let a=c.filter(l=>l.type==="text"&&l.text).map(l=>l.text).join("");a&&(r=a)}else typeof c=="string"&&c&&(r=c)}}catch{}}return r?.trim()||null}_setupMcpConfig(e,t,r,n=null,s=null){let i=r?.headless,c=ee(Je(),".cursor"),a=ee(c,"mcp.json"),l={};if(Ke(a))try{l=JSON.parse(br(a,"utf-8"))}catch{}let u=l.mcpServers||{},d=r?.paths?.output||ao,m=ee(t||process.cwd(),d,lo),p=Array.isArray(n)?n.map(h=>hr(h)).filter(Boolean):[...uo()].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,m,s,i)));if(e){let h=hr("browser");h&&typeof h.resolve=="function"&&!g.has(h.serverName)&&this._ensureSkillConfigured(u,h,e,m,"execute_live",i)}if(Object.keys(u).length===0)return f.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let y=`${JSON.stringify({mcpServers:u},null,2)}
67
- `;if(dr(e)){let h=mr(t||process.cwd()),b=ee(h,".cursor","mcp.json");return yr(b,y,"utf8"),f.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${h} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:h}}return Ke(c)||Sr(c,{recursive:!0}),yr(a,y,"utf8"),f.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,n,s=null,i){let c=t.cursorKey||t.serverName,a=e[c]?c:e[t.serverName]?t.serverName:null;if(a&&r){let u=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:s,headless:i}):null;u?.args?e[a].args=u.args:e[a].args=(e[a].args||[]).map(p=>p.startsWith("--output-dir=")?`--output-dir=${r}`:p);let d=u?.env||{},m=t.sessionEnvKey?{[t.sessionEnvKey]:n}:{};e[a].env={...e[a].env||{},...d,...m},f.debug(`[MCP] Updated ${a} session \u2192 ${r}`);return}if(a)return;let l=t.resolve({sessionPath:r,nodeName:s,headless:i});if(l){if(pt(l)){e[c]=Q("cursor",l),f.debug(`[MCP] ${c} \u2192 ${ft(l)}`);return}e[c]={...l,...t.sessionEnvKey&&{env:{...l.env||{},[t.sessionEnvKey]:n}}},f.debug(`[MCP] Configured ${c}`)}}_spawnWithStreaming(e,t,r,n,s=null,i=null,c=null,a=null){return new Promise((l,u)=>{let d=Date.now(),m="",p="",g=Date.now(),y=0,h=!1,b=null,S=!1,x=!1,_=null;if(i)try{_=ee(mo(String(i)),co)}catch{_=null}let C=!1,k=()=>{C||(C=!0,gr(c))},N={...process.env};c&&(N.HOME=c,process.platform==="win32"&&(N.USERPROFILE=c),f.debug(`[Agent] cursor-agent HOME=${c} (isolated MCP config)`));let I=po(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:N,...a&&{signal:a}});f.debug(`[Agent] PID: ${I.pid}`);let M=null,F=()=>{h||x||(h=!0,b="aborted",f.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),M=setTimeout(()=>{if(!x){f.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{I.kill("SIGKILL")}catch{}}},5e3))};a&&(a.aborted?F():a.addEventListener("abort",F,{once:!0})),I.stdin.on("error",w=>{w.code!=="EPIPE"&&f.warn(`[Agent] stdin error: ${w.message}`)}),I.stdout.on("error",w=>{w.code!=="EPIPE"&&f.warn(`[Agent] stdout error: ${w.message}`)}),I.stderr.on("error",w=>{w.code!=="EPIPE"&&f.warn(`[Agent] stderr error: ${w.message}`)}),s?(I.stdin.write(s,w=>{w&&w.code!=="EPIPE"&&f.warn(`[Agent] Failed to write to stdin: ${w.message}`),I.stdin.end()}),f.debug(`[Agent] Prompt also piped to stdin (${s.length} chars)`)):I.stdin.end();let P=null;_&&(P=setInterval(()=>{if(!(h||x))try{if(Ke(_)){h=!0,b="aborted";try{fo(_)}catch{}f.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),I.kill("SIGTERM"),setTimeout(()=>{I.killed||I.kill("SIGKILL")},2e3)}}catch{}},600));let D=new Set,U=new Date(d).toISOString().replace(/\.\d+Z$/,""),E=setInterval(()=>{let w=Math.round((Date.now()-d)/1e3),R=Math.round((Date.now()-g)/1e3),L=[];try{let G=Math.ceil(w/60)+1,A=ce(`find "${r}" -type f -mmin -${G} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(A)for(let B of A.split(`
68
- `)){let H=B.replace(`${r}/`,"");D.has(H)||(D.add(H),L.push(H))}}catch{}let O="";L.length>0&&(O=` | \u{1F4C1} new: ${L.map(A=>A.split("/").pop()).join(", ")}`),D.size>0&&(O+=` | \u{1F4E6} total: ${D.size} files`),f.debug(`\u{1F493} [Agent] Running for ${w}s | ${y} lines output${O}`),y===0&&w>=30&&D.size===0&&(w<35&&f.warn(`\u26A0\uFE0F [Agent] No output after ${w}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),w>=60&&(h=!0,b=b||"stall",f.error(`\u274C [Agent] No response after ${w}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),I.kill("SIGTERM"),setTimeout(()=>{I.killed||I.kill("SIGKILL")},3e3)))},3e4),$=setTimeout(()=>{h=!0,b=b||"timeout";let w=Math.round((Date.now()-d)/1e3);f.error(`\u23F1\uFE0F [Agent] Timeout after ${w}s \u2014 killing process (PID: ${I.pid})`),m.trim()&&f.warn(`\u{1F4E4} [Agent] Partial output (${m.length} chars) before timeout:
69
- ${m.slice(-2e3)}`),I.kill("SIGTERM"),setTimeout(()=>{I.killed||I.kill("SIGKILL")},5e3)},n),v=new te;v.onToolCall=(w,R)=>{let L=w,O=R;if(w==="mcpToolCall"&&R?.name)L=R.name.replace(/^mcp_+[^_]+_+/,""),L.includes("-")&&L.split("-")[0]===L.split("-")[1]&&(L=L.split("-")[0]),O=R.args??R.input??R;else{if(w==="readToolCall"||w==="editToolCall"||w==="writeToolCall")return;(w.startsWith("mcp__")||w.includes("ToolCall"))&&(L=w.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(L.includes("memory")?re.stepMemory(`Tool: ${L}`):re.stepTool(`Tool: ${L}`),O!=null&&typeof O=="object"&&Object.keys(O).length>0&&!x){let A=JSON.stringify(O),B=A.length>100?`${A.substring(0,100)}...`:A;console.log(` Input: ${B}`)}},I.stdout.on("data",w=>{let R=w.toString();m+=R,g=Date.now(),S||(S=!0);let L=v.processChunk(R);L&&!x&&process.stdout.write(L);let O=R.split(`
70
- `).filter(G=>G.trim());y+=O.length}),I.stderr.on("data",w=>{let R=w.toString();p+=R,g=Date.now(),S||(S=!0);let L=R.split(`
71
- `).filter(O=>O.trim());for(let O of L)f.warn(`\u26A0\uFE0F [Agent stderr] ${O}`)}),I.on("close",(w,R)=>{if(x=!0,k(),clearTimeout($),clearInterval(E),P&&clearInterval(P),M&&clearTimeout(M),a&&!a.aborted)try{a.removeEventListener("abort",F)}catch{}v.flush();let L=Math.round((Date.now()-d)/1e3);if(f.debug(`[Agent] Exited: code=${w}, signal=${R}, elapsed=${L}s, output=${m.length} chars`),h){if(b==="aborted"){let A=new Error("Aborted via signal");A.name="AbortError",u(A);return}u(new Error(`Cursor Agent timed out after ${L}s (limit: ${n/1e3}s). ${y} lines produced. Last output ${Math.round((Date.now()-g)/1e3)}s ago. ${m.trim()?`
67
+ `;if(dr(e)){let h=mr(t||process.cwd()),b=ee(h,".cursor","mcp.json");return yr(b,y,"utf8"),f.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${h} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:h}}return Ke(c)||Sr(c,{recursive:!0}),yr(a,y,"utf8"),f.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,n,s=null,i){let c=t.cursorKey||t.serverName,a=e[c]?c:e[t.serverName]?t.serverName:null;if(a&&r){let u=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:s,headless:i}):null;u?.args?e[a].args=u.args:e[a].args=(e[a].args||[]).map(p=>p.startsWith("--output-dir=")?`--output-dir=${r}`:p);let d=u?.env||{},m=t.sessionEnvKey?{[t.sessionEnvKey]:n}:{};e[a].env={...e[a].env||{},...d,...m},f.debug(`[MCP] Updated ${a} session \u2192 ${r}`);return}if(a)return;let l=t.resolve({sessionPath:r,nodeName:s,headless:i});if(l){if(pt(l)){e[c]=Q("cursor",l),f.debug(`[MCP] ${c} \u2192 ${ft(l)}`);return}e[c]={...l,...t.sessionEnvKey&&{env:{...l.env||{},[t.sessionEnvKey]:n}}},f.debug(`[MCP] Configured ${c}`)}}_spawnWithStreaming(e,t,r,n,s=null,i=null,c=null,a=null){return new Promise((l,u)=>{let d=Date.now(),m="",p="",g=Date.now(),y=0,h=!1,b=null,S=!1,x=!1,_=null;if(i)try{_=ee(mo(String(i)),co)}catch{_=null}let I=!1,k=()=>{I||(I=!0,gr(c))},N={...process.env};c&&(N.HOME=c,process.platform==="win32"&&(N.USERPROFILE=c),f.debug(`[Agent] cursor-agent HOME=${c} (isolated MCP config)`));let C=po(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:N,...a&&{signal:a}});f.debug(`[Agent] PID: ${C.pid}`);let M=null,F=()=>{h||x||(h=!0,b="aborted",f.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),M=setTimeout(()=>{if(!x){f.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{C.kill("SIGKILL")}catch{}}},5e3))};a&&(a.aborted?F():a.addEventListener("abort",F,{once:!0})),C.stdin.on("error",w=>{w.code!=="EPIPE"&&f.warn(`[Agent] stdin error: ${w.message}`)}),C.stdout.on("error",w=>{w.code!=="EPIPE"&&f.warn(`[Agent] stdout error: ${w.message}`)}),C.stderr.on("error",w=>{w.code!=="EPIPE"&&f.warn(`[Agent] stderr error: ${w.message}`)}),s?(C.stdin.write(s,w=>{w&&w.code!=="EPIPE"&&f.warn(`[Agent] Failed to write to stdin: ${w.message}`),C.stdin.end()}),f.debug(`[Agent] Prompt also piped to stdin (${s.length} chars)`)):C.stdin.end();let P=null;_&&(P=setInterval(()=>{if(!(h||x))try{if(Ke(_)){h=!0,b="aborted";try{fo(_)}catch{}f.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),C.kill("SIGTERM"),setTimeout(()=>{C.killed||C.kill("SIGKILL")},2e3)}}catch{}},600));let D=new Set,U=new Date(d).toISOString().replace(/\.\d+Z$/,""),E=setInterval(()=>{let w=Math.round((Date.now()-d)/1e3),R=Math.round((Date.now()-g)/1e3),L=[];try{let G=Math.ceil(w/60)+1,v=ce(`find "${r}" -type f -mmin -${G} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(v)for(let B of v.split(`
68
+ `)){let H=B.replace(`${r}/`,"");D.has(H)||(D.add(H),L.push(H))}}catch{}let O="";L.length>0&&(O=` | \u{1F4C1} new: ${L.map(v=>v.split("/").pop()).join(", ")}`),D.size>0&&(O+=` | \u{1F4E6} total: ${D.size} files`),f.debug(`\u{1F493} [Agent] Running for ${w}s | ${y} lines output${O}`),y===0&&w>=30&&D.size===0&&(w<35&&f.warn(`\u26A0\uFE0F [Agent] No output after ${w}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),w>=60&&(h=!0,b=b||"stall",f.error(`\u274C [Agent] No response after ${w}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),C.kill("SIGTERM"),setTimeout(()=>{C.killed||C.kill("SIGKILL")},3e3)))},3e4),A=setTimeout(()=>{h=!0,b=b||"timeout";let w=Math.round((Date.now()-d)/1e3);f.error(`\u23F1\uFE0F [Agent] Timeout after ${w}s \u2014 killing process (PID: ${C.pid})`),m.trim()&&f.warn(`\u{1F4E4} [Agent] Partial output (${m.length} chars) before timeout:
69
+ ${m.slice(-2e3)}`),C.kill("SIGTERM"),setTimeout(()=>{C.killed||C.kill("SIGKILL")},5e3)},n),$=new te;$.onToolCall=(w,R)=>{let L=w,O=R;if(w==="mcpToolCall"&&R?.name)L=R.name.replace(/^mcp_+[^_]+_+/,""),L.includes("-")&&L.split("-")[0]===L.split("-")[1]&&(L=L.split("-")[0]),O=R.args??R.input??R;else{if(w==="readToolCall"||w==="editToolCall"||w==="writeToolCall")return;(w.startsWith("mcp__")||w.includes("ToolCall"))&&(L=w.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(L.includes("memory")?re.stepMemory(`Tool: ${L}`):re.stepTool(`Tool: ${L}`),O!=null&&typeof O=="object"&&Object.keys(O).length>0&&!x){let v=JSON.stringify(O),B=v.length>100?`${v.substring(0,100)}...`:v;console.log(` Input: ${B}`)}},C.stdout.on("data",w=>{let R=w.toString();m+=R,g=Date.now(),S||(S=!0);let L=$.processChunk(R);L&&!x&&process.stdout.write(L);let O=R.split(`
70
+ `).filter(G=>G.trim());y+=O.length}),C.stderr.on("data",w=>{let R=w.toString();p+=R,g=Date.now(),S||(S=!0);let L=R.split(`
71
+ `).filter(O=>O.trim());for(let O of L)f.warn(`\u26A0\uFE0F [Agent stderr] ${O}`)}),C.on("close",(w,R)=>{if(x=!0,k(),clearTimeout(A),clearInterval(E),P&&clearInterval(P),M&&clearTimeout(M),a&&!a.aborted)try{a.removeEventListener("abort",F)}catch{}$.flush();let L=Math.round((Date.now()-d)/1e3);if(f.debug(`[Agent] Exited: code=${w}, signal=${R}, elapsed=${L}s, output=${m.length} chars`),h){if(b==="aborted"){let v=new Error("Aborted via signal");v.name="AbortError",u(v);return}u(new Error(`Cursor Agent timed out after ${L}s (limit: ${n/1e3}s). ${y} lines produced. Last output ${Math.round((Date.now()-g)/1e3)}s ago. ${m.trim()?`
72
72
  Partial output (last 500 chars):
73
73
  ${m.slice(-500)}`:"No output captured."}`));return}if(w!==0){u(new Error(`Cursor Agent failed: exit code ${w}, signal ${a}. ${p.trim()?`
74
74
  Stderr: ${p.slice(-1e3)}`:""}${m.trim()?`
75
- Stdout (last 500 chars): ${m.slice(-500)}`:""}`));return}let O=v.getResult(),G=O?JSON.stringify(O,null,2):v.getRawText()||m||"";l({stdout:m||p||"",parsedText:G})}),I.on("error",w=>{if(k(),clearTimeout($),clearInterval(E),P&&clearInterval(P),M&&clearTimeout(M),a&&!a.aborted)try{a.removeEventListener("abort",F)}catch{}u(new Error(`Cursor Agent spawn error: ${w.message}
75
+ Stdout (last 500 chars): ${m.slice(-500)}`:""}`));return}let O=$.getResult(),G=O?JSON.stringify(O,null,2):$.getRawText()||m||"";l({stdout:m||p||"",parsedText:G})}),C.on("error",w=>{if(k(),clearTimeout(A),clearInterval(E),P&&clearInterval(P),M&&clearTimeout(M),a&&!a.aborted)try{a.removeEventListener("abort",F)}catch{}u(new Error(`Cursor Agent spawn error: ${w.message}
76
76
  Binary: ${e}
77
77
  This usually means the binary is not in PATH. Try:
78
- echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};import{AgentStrategy as bo,getSkill as vr,NO_INTEGRATION_TOGGLEABLE_SKILL_IDS as So}from"@zibby/agent-workflow";import{query as _o}from"@anthropic-ai/claude-agent-sdk";import go from"node:process";var xr=Object.freeze(["GITHUB_TOKEN","GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","ATLASSIAN_ACCESS_TOKEN","JIRA_API_TOKEN","JIRA_EMAIL","SENTRY_AUTH_TOKEN","SLACK_BOT_TOKEN","DISCORD_BOT_TOKEN","ZIBBY_CHAT_SLACK_TOKEN","ZIBBY_CHAT_LARK_APP_SECRET","ZIBBY_CHAT_DISCORD_INTERACTION_TOKEN","LINEAR_API_KEY","LINEAR_OAUTH_TOKEN","PLANE_API_KEY","PLANE_OAUTH_TOKEN","ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_MEMORY_AWS_ACCESS_KEY_ID","ZIBBY_MEMORY_AWS_SECRET_ACCESS_KEY","ZIBBY_MEMORY_AWS_SESSION_TOKEN"]);function ve(o=go.env){let e={},t=new Set(xr);for(let[r,n]of Object.entries(o))t.has(r)||n!==void 0&&(e[r]=n);return e}ze();import{writeFileSync as Ot,mkdirSync as It,existsSync as $e,readFileSync as $r}from"fs";import{homedir as Or}from"os";import{join as q}from"path";function dt(o){if(!o||typeof o!="object")return null;let e=(...n)=>{for(let s of n){if(s==null||s==="")continue;let i=Number(s);if(Number.isFinite(i))return i}return null},t=e(o.input_tokens,o.inputTokens,o.prompt_tokens,o.promptTokens),r=e(o.output_tokens,o.outputTokens,o.completion_tokens,o.completionTokens);return t==null&&r==null?null:{input:t||0,output:r||0}}import{createRequire as wo}from"module";import z from"process";var Ar=wo(import.meta.url);function xo(){try{if(z.env.CLAUDE_CODE_EXECUTABLE&&$e(z.env.CLAUDE_CODE_EXECUTABLE))return z.env.CLAUDE_CODE_EXECUTABLE;let o=z.platform,e=z.arch,t=`@anthropic-ai/claude-agent-sdk-${o}-${e}`,r=o==="win32"?"claude.exe":"claude";try{let n=Ar.resolve(`${t}/package.json`),s=q(n,"..",r);if($e(s))return s}catch{}try{let n=Ar.resolve("@anthropic-ai/claude-agent-sdk/package.json"),s=q(n,"..");for(let c of[r,q("vendor",r),q("bin",r)]){let a=q(s,c);if($e(a))return a}let i=q(s,"..",`claude-agent-sdk-${o}-${e}`,r);if($e(i))return i}catch{}}catch{}return null}var mt=xo();mt&&f.debug(`Claude native CLI resolved to baked binary: ${mt}`);var fe=class extends bo{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!z.env.ANTHROPIC_API_KEY||!!z.env.ANTHROPIC_API_KEY_POOL,r=!!z.env.CLAUDE_CODE_OAUTH_TOKEN||!!z.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,n=!!z.env.ANTHROPIC_AUTH_TOKEN||!!z.env.ANTHROPIC_AUTH_TOKEN_POOL,s=t||r||n;return s||f.debug("ClaudeAgentStrategy: no credentials. Set one of ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_AUTH_TOKEN (or a *_POOL variant for multi-token rotation)."),s}async invoke(e,t={}){let{model:r,workspace:n=z.cwd(),schema:s=null,images:i=[],skills:c=null,sessionPath:a=null,nodeName:l=null,timeout:u,config:d={},activityLog:m=!1,signal:p=null,sessionId:g,resume:y,forkSession:h,sessionStore:b}=t,S=xe("claude",r),x=at[S]||S;at[S]&&S!==x&&f.debug(`Mapped model: ${S} \u2192 ${x}`);let _=[V("ANTHROPIC_API_KEY"),V("CLAUDE_CODE_OAUTH_TOKEN"),V("ANTHROPIC_AUTH_TOKEN")];try{f.debug(`Invoking Claude Agent SDK with model: ${x}, skills: ${JSON.stringify(c)}`);let C=($,v)=>{let w=String($??"");return w.length>v?`${w.slice(0,v)}\u2026`:w},k=($,v)=>{try{console.log(JSON.stringify({mode:$,...v}))}catch{}},N=z.env.CLAUDE_CODE_OAUTH_TOKEN,I=z.env.ANTHROPIC_API_KEY,M=z.env.ANTHROPIC_AUTH_TOKEN;z.env.CLAUDE_CODE_CREDENTIALS_JSON?vo(z.env.CLAUDE_CODE_CREDENTIALS_JSON):N&&To(N,z.env.__ZIBBY_CLAUDE_PLAN);let F=z.env.__ZIBBY_CLAUDE_PLAN,P=F?F.charAt(0).toUpperCase()+F.slice(1):null,D;if(N?D=P?`Claude ${P} plan \xB7 ***${N.slice(-4)}`:`Subscription \xB7 ***${N.slice(-4)}`:I?D=`API key \xB7 ***${I.slice(-4)}`:M?D=`Bearer \xB7 ***${M.slice(-4)}`:D="NONE \u2014 request will fail",!m){let $=(await import("chalk")).default;console.log(""),console.log(` ${$.cyan("\u25C6")} ${$.bold(x)}`),console.log(` ${$.dim("Auth: ")}${D}`),console.log(` ${$.dim("Workdir: ")}${n}`),console.log(""),console.log($.bold("Prompt sent to LLM:")),console.log($.dim("\u2500".repeat(60))),console.log($.dim(e)),console.log($.dim("\u2500".repeat(60)))}let{allowedTools:U,mcpServers:E}=this._resolveSkills(c,{sessionPath:a,workspace:n,nodeName:l});for(let $ of t.extraMcpServers||[])if($&&$.serverName&&$.def){let v=Q("claude",$.def);v&&(E[$.serverName]=v)}try{let $={cwd:n,allowedTools:U,settings:{permissions:{allow:["Bash(*)","Read(*)","Write(*)","Edit(*)","MultiEdit(*)","NotebookEdit(*)","Grep(*)","Glob(*)","WebFetch(*)","WebSearch(*)","Task(*)","TodoWrite(*)","Skill(*)"]}},model:x,env:ve(z.env),...mt&&{pathToClaudeCodeExecutable:mt},...Object.keys(E).length>0&&{mcpServers:E},...g&&{sessionId:g},...y&&{resume:y},...h&&{forkSession:!0},...b&&{sessionStore:b}};if(s){let Z=typeof s.parse=="function"?pe(s):s;$.outputFormat={type:"json_schema",schema:Z},f.debug("Structured output enforced via SDK outputFormat")}f.debug(`Agent SDK options: ${JSON.stringify({cwd:$.cwd,toolCount:U.length,permissionMode:$.permissionMode,model:$.model,hasOutputFormat:!!$.outputFormat})}`);let v="",w=0,R=[];f.debug("Starting Claude Agent SDK query stream");let L=e,O=Array.isArray(i)?i.filter(T=>T&&typeof T.path=="string"&&T.path.startsWith("/")):[];if(O.length){let T=O.map((Z,K)=>` ${K+1}. ${Z.path}${Z.name?` (${Z.name})`:""}`).join(`
78
+ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};import{AgentStrategy as bo,getSkill as vr,NO_INTEGRATION_TOGGLEABLE_SKILL_IDS as So}from"@zibby/agent-workflow";import{query as _o}from"@anthropic-ai/claude-agent-sdk";import go from"node:process";var xr=Object.freeze(["GITHUB_TOKEN","GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","ATLASSIAN_ACCESS_TOKEN","JIRA_API_TOKEN","JIRA_EMAIL","SENTRY_AUTH_TOKEN","SLACK_BOT_TOKEN","DISCORD_BOT_TOKEN","ZIBBY_CHAT_SLACK_TOKEN","ZIBBY_CHAT_LARK_APP_SECRET","ZIBBY_CHAT_DISCORD_INTERACTION_TOKEN","LINEAR_API_KEY","LINEAR_OAUTH_TOKEN","PLANE_API_KEY","PLANE_OAUTH_TOKEN","ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_MEMORY_AWS_ACCESS_KEY_ID","ZIBBY_MEMORY_AWS_SECRET_ACCESS_KEY","ZIBBY_MEMORY_AWS_SESSION_TOKEN"]);function ve(o=go.env){let e={},t=new Set(xr);for(let[r,n]of Object.entries(o))t.has(r)||n!==void 0&&(e[r]=n);return e}ze();import{writeFileSync as Ot,mkdirSync as It,existsSync as $e,readFileSync as $r}from"fs";import{homedir as Or}from"os";import{join as q}from"path";function dt(o){if(!o||typeof o!="object")return null;let e=(...n)=>{for(let s of n){if(s==null||s==="")continue;let i=Number(s);if(Number.isFinite(i))return i}return null},t=e(o.input_tokens,o.inputTokens,o.prompt_tokens,o.promptTokens),r=e(o.output_tokens,o.outputTokens,o.completion_tokens,o.completionTokens);return t==null&&r==null?null:{input:t||0,output:r||0}}import{createRequire as wo}from"module";import z from"process";var Ar=wo(import.meta.url);function xo(){try{if(z.env.CLAUDE_CODE_EXECUTABLE&&$e(z.env.CLAUDE_CODE_EXECUTABLE))return z.env.CLAUDE_CODE_EXECUTABLE;let o=z.platform,e=z.arch,t=`@anthropic-ai/claude-agent-sdk-${o}-${e}`,r=o==="win32"?"claude.exe":"claude";try{let n=Ar.resolve(`${t}/package.json`),s=q(n,"..",r);if($e(s))return s}catch{}try{let n=Ar.resolve("@anthropic-ai/claude-agent-sdk/package.json"),s=q(n,"..");for(let c of[r,q("vendor",r),q("bin",r)]){let a=q(s,c);if($e(a))return a}let i=q(s,"..",`claude-agent-sdk-${o}-${e}`,r);if($e(i))return i}catch{}}catch{}return null}var mt=xo();mt&&f.debug(`Claude native CLI resolved to baked binary: ${mt}`);var fe=class extends bo{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!z.env.ANTHROPIC_API_KEY||!!z.env.ANTHROPIC_API_KEY_POOL,r=!!z.env.CLAUDE_CODE_OAUTH_TOKEN||!!z.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,n=!!z.env.ANTHROPIC_AUTH_TOKEN||!!z.env.ANTHROPIC_AUTH_TOKEN_POOL,s=t||r||n;return s||f.debug("ClaudeAgentStrategy: no credentials. Set one of ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_AUTH_TOKEN (or a *_POOL variant for multi-token rotation)."),s}async invoke(e,t={}){let{model:r,workspace:n=z.cwd(),schema:s=null,images:i=[],skills:c=null,sessionPath:a=null,nodeName:l=null,timeout:u,config:d={},activityLog:m=!1,signal:p=null,sessionId:g,resume:y,forkSession:h,sessionStore:b}=t,S=xe("claude",r),x=at[S]||S;at[S]&&S!==x&&f.debug(`Mapped model: ${S} \u2192 ${x}`);let _=[V("ANTHROPIC_API_KEY"),V("CLAUDE_CODE_OAUTH_TOKEN"),V("ANTHROPIC_AUTH_TOKEN")];try{f.debug(`Invoking Claude Agent SDK with model: ${x}, skills: ${JSON.stringify(c)}`);let I=(A,$)=>{let w=String(A??"");return w.length>$?`${w.slice(0,$)}\u2026`:w},k=(A,$)=>{try{console.log(JSON.stringify({mode:A,...$}))}catch{}},N=z.env.CLAUDE_CODE_OAUTH_TOKEN,C=z.env.ANTHROPIC_API_KEY,M=z.env.ANTHROPIC_AUTH_TOKEN;z.env.CLAUDE_CODE_CREDENTIALS_JSON?vo(z.env.CLAUDE_CODE_CREDENTIALS_JSON):N&&To(N,z.env.__ZIBBY_CLAUDE_PLAN);let F=z.env.__ZIBBY_CLAUDE_PLAN,P=F?F.charAt(0).toUpperCase()+F.slice(1):null,D;if(N?D=P?`Claude ${P} plan \xB7 ***${N.slice(-4)}`:`Subscription \xB7 ***${N.slice(-4)}`:C?D=`API key \xB7 ***${C.slice(-4)}`:M?D=`Bearer \xB7 ***${M.slice(-4)}`:D="NONE \u2014 request will fail",!m){let A=(await import("chalk")).default;console.log(""),console.log(` ${A.cyan("\u25C6")} ${A.bold(x)}`),console.log(` ${A.dim("Auth: ")}${D}`),console.log(` ${A.dim("Workdir: ")}${n}`),console.log(""),console.log(A.bold("Prompt sent to LLM:")),console.log(A.dim("\u2500".repeat(60))),console.log(A.dim(e)),console.log(A.dim("\u2500".repeat(60)))}let{allowedTools:U,mcpServers:E}=this._resolveSkills(c,{sessionPath:a,workspace:n,nodeName:l});for(let A of t.extraMcpServers||[])if(A&&A.serverName&&A.def){if(Object.prototype.hasOwnProperty.call(E,A.serverName)){console.warn(`[custom-mcp] skip "${A.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let $=Q("claude",A.def);$&&(E[A.serverName]=$)}try{let A={cwd:n,allowedTools:U,settings:{permissions:{allow:["Bash(*)","Read(*)","Write(*)","Edit(*)","MultiEdit(*)","NotebookEdit(*)","Grep(*)","Glob(*)","WebFetch(*)","WebSearch(*)","Task(*)","TodoWrite(*)","Skill(*)"]}},model:x,env:ve(z.env),...mt&&{pathToClaudeCodeExecutable:mt},...Object.keys(E).length>0&&{mcpServers:E},...g&&{sessionId:g},...y&&{resume:y},...h&&{forkSession:!0},...b&&{sessionStore:b}};if(s){let Z=typeof s.parse=="function"?pe(s):s;A.outputFormat={type:"json_schema",schema:Z},f.debug("Structured output enforced via SDK outputFormat")}f.debug(`Agent SDK options: ${JSON.stringify({cwd:A.cwd,toolCount:U.length,permissionMode:A.permissionMode,model:A.model,hasOutputFormat:!!A.outputFormat})}`);let $="",w=0,R=[];f.debug("Starting Claude Agent SDK query stream");let L=e,O=Array.isArray(i)?i.filter(T=>T&&typeof T.path=="string"&&T.path.startsWith("/")):[];if(O.length){let T=O.map((Z,K)=>` ${K+1}. ${Z.path}${Z.name?` (${Z.name})`:""}`).join(`
79
79
  `);L=`${e}
80
80
 
81
81
  # Attached image files \u2014 VIEW THESE
82
82
  The user attached ${O.length} image(s), saved locally. Use the Read tool on each path to SEE the image, then use what it shows to answer:
83
- ${T}`}let G;try{G=_o({prompt:L,options:$})}catch(T){throw f.error(`Failed to initialize Claude Agent SDK: ${T.message}`),T}let A=null,B=0,H=3;if(p?.aborted){let T=new Error("Aborted via signal");throw T.name="AbortError",T}try{for await(let T of G){if(p?.aborted){let K=new Error("Aborted via signal");throw K.name="AbortError",K}if(R.push(T),T.type==="system"&&T.subtype==="init"){let K=T.mcp_servers||[];if(K.length>0){let j=K.map(J=>`${J.name}=${J.status}${J.error?` (${String(J.error).slice(0,120)})`:""}`).join(", ");f.info(`[mcp] SDK init \u2014 ${K.length} server(s): ${j}`);for(let J of K)J.status!=="connected"&&f.warn(`[mcp] server '${J.name}' did not connect: status=${J.status}`,{name:J.name,status:J.status,error:J.error})}else Object.keys(E||{}).length>0&&f.warn(`[mcp] SDK init returned no mcp_servers despite passing ${Object.keys(E).length} server(s) \u2014 SDK version may not expose this field, or config was dropped`);if(Array.isArray(T.tools)){let j=T.tools.filter(J=>J.startsWith("mcp__"));j.length>0?f.info(`[mcp] tools visible to model: ${j.join(", ")}`):Object.keys(E||{}).length>0&&f.warn("[mcp] no mcp__* tools in model's tool list \u2014 MCP servers configured but tools didn't reach the prompt")}}if(T.type==="error"||T.error){let K=T.error?.message||T.error||T.message||"Unknown API error";try{f.error("SDK error event raw payload",{fullMessage:JSON.stringify(T,null,2)})}catch{}throw new Error(typeof K=="string"?K:JSON.stringify(K))}let Z=JSON.stringify(T.message?.content||T.text||"").slice(0,200);if(Z===A){if(B++,B>=H){let K=(T.message?.content?.[0]?.text||T.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${B}x repeated): ${K}`)}}else A=Z,B=1;if(T.type==="assistant"||T.constructor?.name==="AssistantMessage"){let K=T.message?.content||T.content||[];for(let j of K)if(j.type==="thinking"&&j.thinking)m?k("turn:thinking",{text:C(j.thinking,600)}):console.log(`${j.thinking.substring(0,200)}${j.thinking.length>200?"...":""}`);else if(j.type==="text"&&j.text)v+=j.text,m||(j.text.length<500?console.log(`${j.text}`):console.log(`${j.text.substring(0,200)}... (${j.text.length} chars)`));else if(j.type==="tool_use")if(w++,j.name.includes("memory")?re.stepMemory(`Tool: ${j.name}`):re.stepTool(`Tool: ${j.name}`),m)k("turn:tool",{name:j.name});else{let le=JSON.stringify(j.input).substring(0,100);console.log(` Input: ${le}${JSON.stringify(j.input).length>100?"...":""}`)}}else if(!(T.type==="user"&&T.tool_use_result)){if(T.type==="result"||T.constructor?.name==="ResultMessage"){let K=T.result||T.text||T.content||v;try{Eo({message:T,sessionPath:a,nodeName:l,model:S,toolCallCount:w})}catch(J){f.debug(`usage.json write failed: ${J.message}`)}let j=dt(T?.usage||T?.message?.usage);if(s){if(T.structured_output){f.debug("Using SDK native structured_output");let le=typeof s.parse=="function"?s.parse(T.structured_output):T.structured_output;return{raw:K,structured:le,...j?{usage:j}:{}}}if(K){let J=this._extractJson(K,s);if(J)return{raw:K,structured:J,...j?{usage:j}:{}}}f.warn(`Could not extract structured output \u2014 returning raw text (${(K||"").length} chars)`)}return K||""}}}if(f.warn(`Agent SDK ended without result. Collected ${R.length} messages`),v.length>0)return f.debug("Returning accumulated text from messages"),v;throw new Error("Claude Agent SDK query ended without result")}catch(T){let Z={message:T?.message,name:T?.name,code:T?.code,cause:T?.cause?.message||T?.cause,stack:T?.stack?.split(`
83
+ ${T}`}let G;try{G=_o({prompt:L,options:A})}catch(T){throw f.error(`Failed to initialize Claude Agent SDK: ${T.message}`),T}let v=null,B=0,H=3;if(p?.aborted){let T=new Error("Aborted via signal");throw T.name="AbortError",T}try{for await(let T of G){if(p?.aborted){let K=new Error("Aborted via signal");throw K.name="AbortError",K}if(R.push(T),T.type==="system"&&T.subtype==="init"){let K=T.mcp_servers||[];if(K.length>0){let j=K.map(J=>`${J.name}=${J.status}${J.error?` (${String(J.error).slice(0,120)})`:""}`).join(", ");f.info(`[mcp] SDK init \u2014 ${K.length} server(s): ${j}`);for(let J of K)J.status!=="connected"&&f.warn(`[mcp] server '${J.name}' did not connect: status=${J.status}`,{name:J.name,status:J.status,error:J.error})}else Object.keys(E||{}).length>0&&f.warn(`[mcp] SDK init returned no mcp_servers despite passing ${Object.keys(E).length} server(s) \u2014 SDK version may not expose this field, or config was dropped`);if(Array.isArray(T.tools)){let j=T.tools.filter(J=>J.startsWith("mcp__"));j.length>0?f.info(`[mcp] tools visible to model: ${j.join(", ")}`):Object.keys(E||{}).length>0&&f.warn("[mcp] no mcp__* tools in model's tool list \u2014 MCP servers configured but tools didn't reach the prompt")}}if(T.type==="error"||T.error){let K=T.error?.message||T.error||T.message||"Unknown API error";try{f.error("SDK error event raw payload",{fullMessage:JSON.stringify(T,null,2)})}catch{}throw new Error(typeof K=="string"?K:JSON.stringify(K))}let Z=JSON.stringify(T.message?.content||T.text||"").slice(0,200);if(Z===v){if(B++,B>=H){let K=(T.message?.content?.[0]?.text||T.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${B}x repeated): ${K}`)}}else v=Z,B=1;if(T.type==="assistant"||T.constructor?.name==="AssistantMessage"){let K=T.message?.content||T.content||[];for(let j of K)if(j.type==="thinking"&&j.thinking)m?k("turn:thinking",{text:I(j.thinking,600)}):console.log(`${j.thinking.substring(0,200)}${j.thinking.length>200?"...":""}`);else if(j.type==="text"&&j.text)$+=j.text,m||(j.text.length<500?console.log(`${j.text}`):console.log(`${j.text.substring(0,200)}... (${j.text.length} chars)`));else if(j.type==="tool_use")if(w++,j.name.includes("memory")?re.stepMemory(`Tool: ${j.name}`):re.stepTool(`Tool: ${j.name}`),m)k("turn:tool",{name:j.name});else{let le=JSON.stringify(j.input).substring(0,100);console.log(` Input: ${le}${JSON.stringify(j.input).length>100?"...":""}`)}}else if(!(T.type==="user"&&T.tool_use_result)){if(T.type==="result"||T.constructor?.name==="ResultMessage"){let K=T.result||T.text||T.content||$;try{Eo({message:T,sessionPath:a,nodeName:l,model:S,toolCallCount:w})}catch(J){f.debug(`usage.json write failed: ${J.message}`)}let j=dt(T?.usage||T?.message?.usage);if(s){if(T.structured_output){f.debug("Using SDK native structured_output");let le=typeof s.parse=="function"?s.parse(T.structured_output):T.structured_output;return{raw:K,structured:le,...j?{usage:j}:{}}}if(K){let J=this._extractJson(K,s);if(J)return{raw:K,structured:J,...j?{usage:j}:{}}}f.warn(`Could not extract structured output \u2014 returning raw text (${(K||"").length} chars)`)}return K||""}}}if(f.warn(`Agent SDK ended without result. Collected ${R.length} messages`),$.length>0)return f.debug("Returning accumulated text from messages"),$;throw new Error("Claude Agent SDK query ended without result")}catch(T){let Z={message:T?.message,name:T?.name,code:T?.code,cause:T?.cause?.message||T?.cause,stack:T?.stack?.split(`
84
84
  `).slice(0,5).join(`
85
- `),stringified:(()=>{try{return JSON.stringify(T,Object.getOwnPropertyNames(Object(T)))}catch{return String(T)}})()};throw f.error(`Error during query stream: ${T?.message||T}`,Z),T}}catch($){throw f.error("Claude Agent SDK call failed",{message:$?.message,name:$?.name,code:$?.code,cause:$?.cause?.message||$?.cause}),$}}finally{for(let C of _)C.dispose()}}_resolveSkills(e,t){let r=["Read","Write","Edit","Bash","Grep","Glob"];if(e===null)return f.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return f.debug("Default IDE skills for code generation"),{allowedTools:[...r],mcpServers:{}};let n=[...r],s={},i=z.env.WORKFLOW_ENABLED_INTEGRATIONS,c=typeof i=="string"&&i.trim()!==""?new Set(i.split(",").map(u=>u.trim()).filter(Boolean)):null,a=u=>{let d=vr(u);return d?.meta?.toggleable===!0?!0:d?.meta?.toggleable===void 0&&So.includes(u)},l=u=>c!==null&&c.size>0&&a(u)&&!c.has(u);for(let u of e){if(l(u)){f.debug(`Skill "${u}" disabled by enabledIntegrations allowlist \u2014 skipping`);continue}let d=vr(u);if(!d){f.warn(`Unknown skill "${u}" \u2014 skipping`);continue}if(d.allowedTools&&n.push(...d.allowedTools),typeof d.resolve=="function"){let m=d.resolve(t),p=Q("claude",m);p&&(s[d.serverName]=p,f.debug(`MCP: ${d.serverName} \u2192 ${ft(m)}`))}}return{allowedTools:n,mcpServers:s}}_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 i=JSON.parse(s);if(typeof i!="object"||i===null)continue;return typeof t.parse=="function"?t.parse(i):i}catch{}return null}};function Eo({message:o,sessionPath:e,nodeName:t,model:r,toolCallCount:n}){if(!e||!t)return;let s=o?.usage||o?.message?.usage||{},i=He(s.input_tokens,s.inputTokens),c=He(s.output_tokens,s.outputTokens),a=He(s.cache_read_input_tokens,s.cacheReadInputTokens),l=He(s.cache_creation_input_tokens,s.cacheCreationInputTokens),u=He(o?.duration_ms,o?.durationMs),d={model:r||null,input_tokens:i,output_tokens:c,cache_read_tokens:a,cache_creation_tokens:l,tool_call_count:typeof n=="number"?n:null,duration_ms:u,captured_at:new Date().toISOString()},m=q(e,t);try{It(m,{recursive:!0})}catch{}Ot(q(m,"usage.json"),JSON.stringify(d,null,2),"utf-8")}function He(...o){for(let e of o){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e)))return Number(e)}return null}function To(o,e){let t=q(Or(),".claude"),r=q(t,".credentials.json"),n={claudeAiOauth:{accessToken:o,refreshToken:"",expiresAt:Date.now()+365*24*60*60*1e3,scopes:["user:inference","user:profile"],...e?{subscriptionType:String(e).toLowerCase()}:{}}};try{if($e(r)&&JSON.parse($r(r,"utf-8"))?.claudeAiOauth?.accessToken===o)return;It(t,{recursive:!0}),Ot(r,JSON.stringify(n,null,2),"utf-8"),f.debug(`Wrote Claude Code OAuth credentials to ${r}`)}catch(s){f.warn(`Could not write ${r}: ${s.message} \u2014 Claude SDK may fail to authenticate.`)}}function vo(o){let e=q(Or(),".claude"),t=q(e,".credentials.json"),r;try{r=JSON.parse(o)}catch(n){f.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${n.message}`);return}if(!r?.claudeAiOauth?.accessToken){f.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if($e(t)){let n=JSON.parse($r(t,"utf-8"));if(n?.claudeAiOauth?.accessToken===r.claudeAiOauth.accessToken&&n?.claudeAiOauth?.expiresAt===r.claudeAiOauth.expiresAt)return}It(e,{recursive:!0}),Ot(t,JSON.stringify(r,null,2),"utf-8"),f.debug(`Wrote full Claude Code credentials blob to ${t}`)}catch(n){f.warn(`Could not write ${t}: ${n.message} \u2014 Claude SDK may fail to authenticate.`)}}import{AgentStrategy as Ao,getSkill as $o}from"@zibby/agent-workflow";ze();import{execSync as Ye}from"node:child_process";import{readFileSync as Oo,mkdirSync as Ct,cpSync as Io,existsSync as Co}from"node:fs";import{join as We}from"node:path";import{homedir as Po}from"node:os";function Pt(o){if(Array.isArray(o))return o.map(Pt);if(o&&typeof o=="object"){let e={};for(let[t,r]of Object.entries(o))r!==null&&(e[t]=Pt(r));return e}return o}var de=class extends Ao{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY_POOL||process.env.CODEX_API_KEY||process.env.CODEX_API_KEY_POOL))return f.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return Ye("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return f.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,images:i=[],skills:c=null,plugins:a=null,sessionPath:l=null,nodeName:u=null,timeout:d,config:m={},signal:p=null}=t,g=[V("OPENAI_API_KEY"),V("CODEX_API_KEY")];try{let{Codex:y}=await import("@openai/codex-sdk"),h=xe("codex",r),b=lt[h]||h;lt[h]&&h!==b&&f.debug(`Mapped model: ${h} \u2192 ${b}`),f.debug(`Invoking Codex SDK with model: ${b}, skills: ${JSON.stringify(c)}`);let S=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;S&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=S);let x=S?` | key: ***${S.slice(-4)}`:" | key: not set";if(console.log(`
85
+ `),stringified:(()=>{try{return JSON.stringify(T,Object.getOwnPropertyNames(Object(T)))}catch{return String(T)}})()};throw f.error(`Error during query stream: ${T?.message||T}`,Z),T}}catch(A){throw f.error("Claude Agent SDK call failed",{message:A?.message,name:A?.name,code:A?.code,cause:A?.cause?.message||A?.cause}),A}}finally{for(let I of _)I.dispose()}}_resolveSkills(e,t){let r=["Read","Write","Edit","Bash","Grep","Glob"];if(e===null)return f.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return f.debug("Default IDE skills for code generation"),{allowedTools:[...r],mcpServers:{}};let n=[...r],s={},i=z.env.WORKFLOW_ENABLED_INTEGRATIONS,c=typeof i=="string"&&i.trim()!==""?new Set(i.split(",").map(u=>u.trim()).filter(Boolean)):null,a=u=>{let d=vr(u);return d?.meta?.toggleable===!0?!0:d?.meta?.toggleable===void 0&&So.includes(u)},l=u=>c!==null&&c.size>0&&a(u)&&!c.has(u);for(let u of e){if(l(u)){f.debug(`Skill "${u}" disabled by enabledIntegrations allowlist \u2014 skipping`);continue}let d=vr(u);if(!d){f.warn(`Unknown skill "${u}" \u2014 skipping`);continue}if(d.allowedTools&&n.push(...d.allowedTools),typeof d.resolve=="function"){let m=d.resolve(t),p=Q("claude",m);p&&(s[d.serverName]=p,f.debug(`MCP: ${d.serverName} \u2192 ${ft(m)}`))}}return{allowedTools:n,mcpServers:s}}_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 i=JSON.parse(s);if(typeof i!="object"||i===null)continue;return typeof t.parse=="function"?t.parse(i):i}catch{}return null}};function Eo({message:o,sessionPath:e,nodeName:t,model:r,toolCallCount:n}){if(!e||!t)return;let s=o?.usage||o?.message?.usage||{},i=He(s.input_tokens,s.inputTokens),c=He(s.output_tokens,s.outputTokens),a=He(s.cache_read_input_tokens,s.cacheReadInputTokens),l=He(s.cache_creation_input_tokens,s.cacheCreationInputTokens),u=He(o?.duration_ms,o?.durationMs),d={model:r||null,input_tokens:i,output_tokens:c,cache_read_tokens:a,cache_creation_tokens:l,tool_call_count:typeof n=="number"?n:null,duration_ms:u,captured_at:new Date().toISOString()},m=q(e,t);try{It(m,{recursive:!0})}catch{}Ot(q(m,"usage.json"),JSON.stringify(d,null,2),"utf-8")}function He(...o){for(let e of o){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e)))return Number(e)}return null}function To(o,e){let t=q(Or(),".claude"),r=q(t,".credentials.json"),n={claudeAiOauth:{accessToken:o,refreshToken:"",expiresAt:Date.now()+365*24*60*60*1e3,scopes:["user:inference","user:profile"],...e?{subscriptionType:String(e).toLowerCase()}:{}}};try{if($e(r)&&JSON.parse($r(r,"utf-8"))?.claudeAiOauth?.accessToken===o)return;It(t,{recursive:!0}),Ot(r,JSON.stringify(n,null,2),"utf-8"),f.debug(`Wrote Claude Code OAuth credentials to ${r}`)}catch(s){f.warn(`Could not write ${r}: ${s.message} \u2014 Claude SDK may fail to authenticate.`)}}function vo(o){let e=q(Or(),".claude"),t=q(e,".credentials.json"),r;try{r=JSON.parse(o)}catch(n){f.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${n.message}`);return}if(!r?.claudeAiOauth?.accessToken){f.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if($e(t)){let n=JSON.parse($r(t,"utf-8"));if(n?.claudeAiOauth?.accessToken===r.claudeAiOauth.accessToken&&n?.claudeAiOauth?.expiresAt===r.claudeAiOauth.expiresAt)return}It(e,{recursive:!0}),Ot(t,JSON.stringify(r,null,2),"utf-8"),f.debug(`Wrote full Claude Code credentials blob to ${t}`)}catch(n){f.warn(`Could not write ${t}: ${n.message} \u2014 Claude SDK may fail to authenticate.`)}}import{AgentStrategy as Ao,getSkill as $o}from"@zibby/agent-workflow";ze();import{execSync as Ye}from"node:child_process";import{readFileSync as Oo,mkdirSync as Ct,cpSync as Io,existsSync as Co}from"node:fs";import{join as We}from"node:path";import{homedir as Po}from"node:os";function Pt(o){if(Array.isArray(o))return o.map(Pt);if(o&&typeof o=="object"){let e={};for(let[t,r]of Object.entries(o))r!==null&&(e[t]=Pt(r));return e}return o}var de=class extends Ao{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY_POOL||process.env.CODEX_API_KEY||process.env.CODEX_API_KEY_POOL))return f.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return Ye("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return f.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,images:i=[],skills:c=null,plugins:a=null,sessionPath:l=null,nodeName:u=null,timeout:d,config:m={},signal:p=null}=t,g=[V("OPENAI_API_KEY"),V("CODEX_API_KEY")];try{let{Codex:y}=await import("@openai/codex-sdk"),h=xe("codex",r),b=lt[h]||h;lt[h]&&h!==b&&f.debug(`Mapped model: ${h} \u2192 ${b}`),f.debug(`Invoking Codex SDK with model: ${b}, skills: ${JSON.stringify(c)}`);let S=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;S&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=S);let x=S?` | key: ***${S.slice(-4)}`:" | key: not set";if(console.log(`
86
86
  \u25C6 Model: ${b}${x}
87
87
  `),Array.isArray(a)&&a.length>0){let E=this._resolveCodexHome(l);process.env.CODEX_HOME=E;try{Ct(E,{recursive:!0})}catch{}this._ensurePlugins(a,E)}let _=(await import("chalk")).default;console.log(`
88
- ${_.bold("Prompt sent to LLM:")}`),console.log(_.dim("\u2500".repeat(60))),console.log(_.dim(e)),console.log(_.dim("\u2500".repeat(60)));let C=this._resolveSkillsToMcp(c,{sessionPath:l,workspace:n,nodeName:u});for(let E of t.extraMcpServers||[])if(E&&E.serverName&&E.def){let $=Q("codex",E.def);$&&(C[E.serverName]=$)}let k={};Object.keys(C).length>0&&(k.mcp_servers=C,Object.values(C).some(E=>E&&typeof E.url=="string")&&(k.experimental_use_rmcp_client=!0),f.debug(`[Codex] MCP servers: ${Object.keys(C).join(", ")}`));let N=this._resolveCodexBin(),I=new y({...N?{codexPathOverride:N}:{},...Object.keys(k).length>0&&{config:k},env:ve(process.env)}),M=n;try{M&&Ct(M,{recursive:!0})}catch{}(!M||!Co(M))&&(M=process.cwd());let F=I.startThread({workingDirectory:M,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),P=s&&typeof s.parse=="function",D={};if(s)try{let E=P?pe(s,{target:"openAi"}):s;D.outputSchema=E,f.debug("Structured output via SDK outputSchema")}catch(E){f.warn(`[Codex] Schema conversion failed, will extract from text: ${E.message}`)}let U=Array.isArray(i)?i.filter(E=>E&&typeof E.path=="string"&&E.path.startsWith("/")):[];if(U.length&&(e=`${e}
88
+ ${_.bold("Prompt sent to LLM:")}`),console.log(_.dim("\u2500".repeat(60))),console.log(_.dim(e)),console.log(_.dim("\u2500".repeat(60)));let I=this._resolveSkillsToMcp(c,{sessionPath:l,workspace:n,nodeName:u});for(let E of t.extraMcpServers||[])if(E&&E.serverName&&E.def){if(Object.prototype.hasOwnProperty.call(I,E.serverName)){console.warn(`[custom-mcp] skip "${E.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let A=Q("codex",E.def);A&&(I[E.serverName]=A)}let k={};Object.keys(I).length>0&&(k.mcp_servers=I,Object.values(I).some(E=>E&&typeof E.url=="string")&&(k.experimental_use_rmcp_client=!0),f.debug(`[Codex] MCP servers: ${Object.keys(I).join(", ")}`));let N=this._resolveCodexBin(),C=new y({...N?{codexPathOverride:N}:{},...Object.keys(k).length>0&&{config:k},env:ve(process.env)}),M=n;try{M&&Ct(M,{recursive:!0})}catch{}(!M||!Co(M))&&(M=process.cwd());let F=C.startThread({workingDirectory:M,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),P=s&&typeof s.parse=="function",D={};if(s)try{let E=P?pe(s,{target:"openAi"}):s;D.outputSchema=E,f.debug("Structured output via SDK outputSchema")}catch(E){f.warn(`[Codex] Schema conversion failed, will extract from text: ${E.message}`)}let U=Array.isArray(i)?i.filter(E=>E&&typeof E.path=="string"&&E.path.startsWith("/")):[];if(U.length&&(e=`${e}
89
89
 
90
90
  # Attached image files \u2014 VIEW THESE
91
91
  The user attached ${U.length} image(s), saved locally. Read each path to SEE the image, then use what it shows to answer:
92
- ${U.map((E,$)=>` ${$+1}. ${E.path}${E.name?` (${E.name})`:""}`).join(`
93
- `)}`),p?.aborted){let E=new Error("Aborted via signal");throw E.name="AbortError",E}try{let{events:E}=await F.runStreamed(e,D),$=0,v="",w=null;for await(let R of E){if(p?.aborted){let O=new Error("Aborted via signal");throw O.name="AbortError",O}let L=R.type;if(L==="item.completed"){let O=R.item,G=O?.type;if(G==="mcp_tool_call"){$++;let A=`${O.server}/${O.tool}`;if(re.stepTool(`Tool: ${A}`),O.arguments){let B=JSON.stringify(O.arguments),H=B.length>100?`${B.substring(0,100)}...`:B;console.log(` Input: ${H}`)}}else if(G==="tool_call"||G==="function_call"||G==="command_execution"){$++;let A=O.name||O.tool||O.command||"unknown";re.stepTool(`Tool: ${A}`)}else G==="agent_message"&&(v=O.text||"",v.length<500?console.log(v):console.log(`${v.substring(0,200)}... (${v.length} chars)`))}else L==="turn.completed"?(f.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(R.usage||{})}`),R.usage&&(w=R.usage)):f.debug(`[Codex] Event: ${L} ${JSON.stringify(R).slice(0,300)}`)}if(f.debug(`[Codex] Last agent message (${v.length} chars): ${v.slice(0,500)}`),s){if(!v)throw new Error("Codex agent returned no response");let R=JSON.parse(v),L=R;if(P)try{L=s.parse(R)}catch{L=s.parse(Pt(R))}f.debug("\u2705 [Codex] Structured output validated");let O=dt(w);return{raw:v,structured:L,...O?{usage:O}:{}}}return v||""}catch(E){let $=E.message||String(E);throw f.error(`\u274C [Codex] SDK call failed: ${$}`),$.includes("exited with code")&&(D.outputSchema&&f.error("\u{1F4A1} [Codex] An outputSchema was sent \u2014 an OpenAI strict-mode-invalid schema (a property missing from `required`) makes codex exit 1 here."),f.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),f.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),E}}finally{for(let y of g)y.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=$o(n);if(!s){f.warn(`[Codex] Unknown skill "${n}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let c=s.serverName||n,a=Q("codex",i,{processEnv:process.env});a&&(r[c]=a,f.debug(`[Codex] MCP: ${c} \u2192 ${i.command} ${(i.args||[]).join(" ")}`))}return r}_resolveCodexHome(e){return process.env.CODEX_HOME?process.env.CODEX_HOME:e&&!this._isTempPath(e)?We(e,".codex-home"):We(Po(),".codex")}_isTempPath(e){let t=String(process.env.TMPDIR||"/tmp").replace(/\/+$/,""),r=String(e||"");return r==="/tmp"||r.startsWith("/tmp/")||r===t||r.startsWith(t+"/")}_resolveCodexBin(){if(process.env.CODEX_BIN)return process.env.CODEX_BIN;try{return Ye("command -v codex",{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}_ensurePlugins(e,t){let r={...process.env,CODEX_HOME:t};for(let n of e){let s=typeof n=="string"?n:n?.name,i=n&&typeof n=="object"?n.marketplacePath:null;if(!s||!i){f.warn(`[Codex][plugins] skipping malformed plugin declaration: ${JSON.stringify(n)} (need { name, marketplacePath })`);continue}let c=this._readMarketplaceName(i),a=`${s}@${c}`;if(this._isPluginInstalled(a,r)){f.info(`[Codex][plugins] ${a} already installed \u2014 skipping (idempotent)`),console.log(`\u25C6 [Codex] plugin ${a} already installed \u2014 skip`);continue}let l=this._safeMarketplacePath(i,t);f.info(`[Codex][plugins] installing ${a} from local marketplace ${l}`),console.log(`\u25C6 [Codex] installing plugin ${a} (local, no network)`);try{Ye(`codex plugin marketplace add ${JSON.stringify(l)}`,{env:r,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),Ye(`codex plugin add ${JSON.stringify(a)}`,{env:r,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),console.log(`\u25C6 [Codex] plugin ${a} installed`)}catch(u){let d=u.stderr&&u.stderr.toString()||u.message||String(u);throw f.error(`[Codex][plugins] failed to install ${a}: ${d}`),new Error(`Codex plugin install failed for ${a}: ${d}`)}}}_safeMarketplacePath(e,t){if(!String(e).includes("@"))return e;let r=We(t,".zibby-mkt",String(e).replace(/[^a-zA-Z0-9]+/g,"_"));try{return Ct(We(t,".zibby-mkt"),{recursive:!0}),Io(e,r,{recursive:!0}),r}catch(n){return f.warn(`[Codex][plugins] could not copy @-containing marketplace to a safe path: ${n.message}`),e}}_readMarketplaceName(e){let t=We(e,".agents","plugins","marketplace.json"),r;try{r=JSON.parse(Oo(t,"utf-8"))}catch(n){throw new Error(`Codex plugin marketplace manifest missing/unreadable at ${t}: ${n.message}`)}if(!r?.name||typeof r.name!="string")throw new Error(`Codex plugin marketplace manifest at ${t} has no string "name"`);return r.name}_isPluginInstalled(e,t){try{return Ye("codex plugin list",{env:t,stdio:"pipe",timeout:15e3,encoding:"utf-8"}).split(`
94
- `).some(n=>n.includes(e)&&/installed/.test(n))}catch{return!1}}};import{AgentStrategy as ko,getSkill as No}from"@zibby/agent-workflow";ze();import{execSync as Ro,spawn as Lo}from"node:child_process";import{existsSync as Ir,mkdirSync as Cr,readFileSync as Pr,rmSync as Mo,writeFileSync as kr}from"node:fs";import{join as me}from"node:path";function Do(o){if(!o)return null;let e=String(o),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,i=!1,c=-1;for(let a=r;a<e.length;a++){let l=e[a];if(s){i?i=!1:l==="\\"?i=!0:l==='"'&&(s=!1);continue}if(l==='"'){s=!0;continue}if(l==="{"){n===0&&(c=a),n+=1;continue}if(l==="}"){if(n===0)continue;if(n-=1,n===0&&c>=0){let u=e.slice(c,a+1);try{return JSON.parse(u)}catch{c=-1}}}}return null}function Uo(o){let e=String(o||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return Do(e)}}function jo(o){try{let e=JSON.parse(o);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 o}var ge=class extends ko{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GEMINI_API_KEY_POOL||process.env.GOOGLE_API_KEY||process.env.GOOGLE_API_KEY_POOL))return f.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return Ro("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return f.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,images:i=[],skills:c=null,sessionPath:a=null,nodeName:l=null,timeout:u=600*1e3,signal:d=null}=t,m=[V("GEMINI_API_KEY"),V("GOOGLE_API_KEY")];try{let p=xe("gemini",r),g=At[p]||p,y=String(process.env.GEMINI_API_KEY||"").trim(),h=String(process.env.GOOGLE_API_KEY||"").trim(),b=this._resolveSkillsToMcp(c,{sessionPath:a,workspace:n,nodeName:l});for(let A of t.extraMcpServers||[])if(A&&A.serverName&&A.def){let B=Q("gemini",A.def);B&&(b[A.serverName]=B)}let S=Object.keys(b).length>0,x=new Ee(e),_=s&&typeof s.parse=="function",C=null;if(s){let A;try{let B=_?pe(s,{target:"openAi"}):s;A=JSON.stringify(B,null,2)}catch{A="{}"}if(S){x.addSystemInstruction(`Write valid JSON that matches this schema:
95
- ${A}`,"schema_instruction","append");let B=`zibby-result-${Date.now()}.json`,H=me(n,".zibby","tmp");C=me(H,B),Cr(H,{recursive:!0}),x.addStructuredOutput(s,C)}else x.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
96
- ${A}`,"json_instruction","append")}let k=x.build(),N=Array.isArray(i)?i.filter(A=>A&&typeof A.path=="string"&&A.path.startsWith("/")):[];N.length&&(k+=`
92
+ ${U.map((E,A)=>` ${A+1}. ${E.path}${E.name?` (${E.name})`:""}`).join(`
93
+ `)}`),p?.aborted){let E=new Error("Aborted via signal");throw E.name="AbortError",E}try{let{events:E}=await F.runStreamed(e,D),A=0,$="",w=null;for await(let R of E){if(p?.aborted){let O=new Error("Aborted via signal");throw O.name="AbortError",O}let L=R.type;if(L==="item.completed"){let O=R.item,G=O?.type;if(G==="mcp_tool_call"){A++;let v=`${O.server}/${O.tool}`;if(re.stepTool(`Tool: ${v}`),O.arguments){let B=JSON.stringify(O.arguments),H=B.length>100?`${B.substring(0,100)}...`:B;console.log(` Input: ${H}`)}}else if(G==="tool_call"||G==="function_call"||G==="command_execution"){A++;let v=O.name||O.tool||O.command||"unknown";re.stepTool(`Tool: ${v}`)}else G==="agent_message"&&($=O.text||"",$.length<500?console.log($):console.log(`${$.substring(0,200)}... (${$.length} chars)`))}else L==="turn.completed"?(f.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(R.usage||{})}`),R.usage&&(w=R.usage)):f.debug(`[Codex] Event: ${L} ${JSON.stringify(R).slice(0,300)}`)}if(f.debug(`[Codex] Last agent message (${$.length} chars): ${$.slice(0,500)}`),s){if(!$)throw new Error("Codex agent returned no response");let R=JSON.parse($),L=R;if(P)try{L=s.parse(R)}catch{L=s.parse(Pt(R))}f.debug("\u2705 [Codex] Structured output validated");let O=dt(w);return{raw:$,structured:L,...O?{usage:O}:{}}}return $||""}catch(E){let A=E.message||String(E);throw f.error(`\u274C [Codex] SDK call failed: ${A}`),A.includes("exited with code")&&(D.outputSchema&&f.error("\u{1F4A1} [Codex] An outputSchema was sent \u2014 an OpenAI strict-mode-invalid schema (a property missing from `required`) makes codex exit 1 here."),f.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),f.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),E}}finally{for(let y of g)y.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=$o(n);if(!s){f.warn(`[Codex] Unknown skill "${n}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let c=s.serverName||n,a=Q("codex",i,{processEnv:process.env});a&&(r[c]=a,f.debug(`[Codex] MCP: ${c} \u2192 ${i.command} ${(i.args||[]).join(" ")}`))}return r}_resolveCodexHome(e){return process.env.CODEX_HOME?process.env.CODEX_HOME:e&&!this._isTempPath(e)?We(e,".codex-home"):We(Po(),".codex")}_isTempPath(e){let t=String(process.env.TMPDIR||"/tmp").replace(/\/+$/,""),r=String(e||"");return r==="/tmp"||r.startsWith("/tmp/")||r===t||r.startsWith(t+"/")}_resolveCodexBin(){if(process.env.CODEX_BIN)return process.env.CODEX_BIN;try{return Ye("command -v codex",{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}_ensurePlugins(e,t){let r={...process.env,CODEX_HOME:t};for(let n of e){let s=typeof n=="string"?n:n?.name,i=n&&typeof n=="object"?n.marketplacePath:null;if(!s||!i){f.warn(`[Codex][plugins] skipping malformed plugin declaration: ${JSON.stringify(n)} (need { name, marketplacePath })`);continue}let c=this._readMarketplaceName(i),a=`${s}@${c}`;if(this._isPluginInstalled(a,r)){f.info(`[Codex][plugins] ${a} already installed \u2014 skipping (idempotent)`),console.log(`\u25C6 [Codex] plugin ${a} already installed \u2014 skip`);continue}let l=this._safeMarketplacePath(i,t);f.info(`[Codex][plugins] installing ${a} from local marketplace ${l}`),console.log(`\u25C6 [Codex] installing plugin ${a} (local, no network)`);try{Ye(`codex plugin marketplace add ${JSON.stringify(l)}`,{env:r,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),Ye(`codex plugin add ${JSON.stringify(a)}`,{env:r,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),console.log(`\u25C6 [Codex] plugin ${a} installed`)}catch(u){let d=u.stderr&&u.stderr.toString()||u.message||String(u);throw f.error(`[Codex][plugins] failed to install ${a}: ${d}`),new Error(`Codex plugin install failed for ${a}: ${d}`)}}}_safeMarketplacePath(e,t){if(!String(e).includes("@"))return e;let r=We(t,".zibby-mkt",String(e).replace(/[^a-zA-Z0-9]+/g,"_"));try{return Ct(We(t,".zibby-mkt"),{recursive:!0}),Io(e,r,{recursive:!0}),r}catch(n){return f.warn(`[Codex][plugins] could not copy @-containing marketplace to a safe path: ${n.message}`),e}}_readMarketplaceName(e){let t=We(e,".agents","plugins","marketplace.json"),r;try{r=JSON.parse(Oo(t,"utf-8"))}catch(n){throw new Error(`Codex plugin marketplace manifest missing/unreadable at ${t}: ${n.message}`)}if(!r?.name||typeof r.name!="string")throw new Error(`Codex plugin marketplace manifest at ${t} has no string "name"`);return r.name}_isPluginInstalled(e,t){try{return Ye("codex plugin list",{env:t,stdio:"pipe",timeout:15e3,encoding:"utf-8"}).split(`
94
+ `).some(n=>n.includes(e)&&/installed/.test(n))}catch{return!1}}};import{AgentStrategy as ko,getSkill as No}from"@zibby/agent-workflow";ze();import{execSync as Ro,spawn as Lo}from"node:child_process";import{existsSync as Ir,mkdirSync as Cr,readFileSync as Pr,rmSync as Mo,writeFileSync as kr}from"node:fs";import{join as me}from"node:path";function Do(o){if(!o)return null;let e=String(o),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,i=!1,c=-1;for(let a=r;a<e.length;a++){let l=e[a];if(s){i?i=!1:l==="\\"?i=!0:l==='"'&&(s=!1);continue}if(l==='"'){s=!0;continue}if(l==="{"){n===0&&(c=a),n+=1;continue}if(l==="}"){if(n===0)continue;if(n-=1,n===0&&c>=0){let u=e.slice(c,a+1);try{return JSON.parse(u)}catch{c=-1}}}}return null}function Uo(o){let e=String(o||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return Do(e)}}function jo(o){try{let e=JSON.parse(o);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 o}var ge=class extends ko{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GEMINI_API_KEY_POOL||process.env.GOOGLE_API_KEY||process.env.GOOGLE_API_KEY_POOL))return f.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return Ro("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return f.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,images:i=[],skills:c=null,sessionPath:a=null,nodeName:l=null,timeout:u=600*1e3,signal:d=null}=t,m=[V("GEMINI_API_KEY"),V("GOOGLE_API_KEY")];try{let p=xe("gemini",r),g=At[p]||p,y=String(process.env.GEMINI_API_KEY||"").trim(),h=String(process.env.GOOGLE_API_KEY||"").trim(),b=this._resolveSkillsToMcp(c,{sessionPath:a,workspace:n,nodeName:l});for(let v of t.extraMcpServers||[])if(v&&v.serverName&&v.def){if(Object.prototype.hasOwnProperty.call(b,v.serverName)){console.warn(`[custom-mcp] skip "${v.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let B=Q("gemini",v.def);B&&(b[v.serverName]=B)}let S=Object.keys(b).length>0,x=new Ee(e),_=s&&typeof s.parse=="function",I=null;if(s){let v;try{let B=_?pe(s,{target:"openAi"}):s;v=JSON.stringify(B,null,2)}catch{v="{}"}if(S){x.addSystemInstruction(`Write valid JSON that matches this schema:
95
+ ${v}`,"schema_instruction","append");let B=`zibby-result-${Date.now()}.json`,H=me(n,".zibby","tmp");I=me(H,B),Cr(H,{recursive:!0}),x.addStructuredOutput(s,I)}else x.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
96
+ ${v}`,"json_instruction","append")}let k=x.build(),N=Array.isArray(i)?i.filter(v=>v&&typeof v.path=="string"&&v.path.startsWith("/")):[];N.length&&(k+=`
97
97
 
98
98
  # Attached image files \u2014 VIEW THESE
99
99
  The user attached ${N.length} image(s), saved locally. Read each path to SEE the image, then use what it shows to answer:
100
- ${N.map((A,B)=>` ${B+1}. ${A.path}${A.name?` (${A.name})`:""}`).join(`
101
- `)}`);let I=x.getUserPrompt(),M=x.getStats(),F=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),P=F?` | key: ***${F.slice(-4)}`:" | key: not set";console.log(`
100
+ ${N.map((v,B)=>` ${B+1}. ${v.path}${v.name?` (${v.name})`:""}`).join(`
101
+ `)}`);let C=x.getUserPrompt(),M=x.getStats(),F=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),P=F?` | key: ***${F.slice(-4)}`:" | key: not set";console.log(`
102
102
  \u25C6 Model: ${g||"auto"}${P}
103
103
  `);let D=(await import("chalk")).default;console.log(`
104
- ${D.bold("Prompt sent to LLM:")}`),console.log(D.dim("\u2500".repeat(60))),console.log(D.dim(I)),console.log(D.dim("\u2500".repeat(60)));let U=this._createGeminiConfigDir(n,b),E=["--output-format","json"];g&&g!=="auto"&&E.push("--model",g);let $=Object.keys(b);if($.length>0){E.push("--approval-mode","yolo");for(let A of $)E.push("--allowed-mcp-server-names",A);f.info(`[Gemini] Enabling MCP servers: ${$.join(", ")}`)}else c&&c.length>0&&f.warn(`[Gemini] Skills requested but no MCP servers configured: ${c.join(", ")}`);E.push("-p",k);let v={...ve(process.env),GEMINI_CLI_HOME:U};y?(v.GEMINI_API_KEY=y,delete v.GOOGLE_API_KEY):h&&(v.GOOGLE_API_KEY=h,delete v.GEMINI_API_KEY),f.debug(`[Gemini] Command: gemini ${E.slice(0,8).join(" ")}... (${E.length} total args)`),f.debug(`[Gemini] User prompt: ${M.userPromptLength} chars, System instructions: ${M.systemInstructionsLength} chars (${M.instructionCount} blocks), Full: ${M.fullPromptLength} chars`),f.debug(`[Gemini] Config home: ${U}`),f.debug(`[Gemini] GEMINI_CLI_HOME env: ${v.GEMINI_CLI_HOME}`);let w="",R=null;try{w=await new Promise((B,H)=>{let T=Lo("gemini",E,{cwd:n,env:v,stdio:["ignore","pipe","pipe"],...d&&{signal:d}}),Z="",K="",j=!1,J=null,le=!1,ir=setTimeout(()=>{try{T.kill("SIGTERM")}catch{}},u),st=()=>{le||j||(le=!0,J=setTimeout(()=>{if(!j)try{T.kill("SIGKILL")}catch{}},5e3))};d&&(d.aborted?st():d.addEventListener("abort",st,{once:!0})),T.stdout.on("data",oe=>{Z+=oe.toString()}),T.stderr.on("data",oe=>{K+=oe.toString()}),T.on("error",oe=>{if(clearTimeout(ir),J&&clearTimeout(J),d&&!d.aborted)try{d.removeEventListener("abort",st)}catch{}H(oe)}),T.on("close",oe=>{if(j=!0,clearTimeout(ir),J&&clearTimeout(J),d&&!d.aborted)try{d.removeEventListener("abort",st)}catch{}if(le){let ar=new Error("Aborted via signal");return ar.name="AbortError",H(ar)}if(oe===0)return B(Z.trim());H(new Error(`gemini failed with code ${oe}: ${(K||Z).trim()}`))})})}catch(A){R=A}finally{try{Mo(U,{recursive:!0,force:!0})}catch{}}let L=jo(w).trim();if(!s){if(R)throw R;return L}if(C){let A=Ir(C);if(f.info(`[Gemini] Result file: ${A?"present":"missing"} at ${C}`),A)try{let B=Pr(C,"utf-8").trim(),H=JSON.parse(B),T=_?s.parse(H):H;return f.info("[Gemini] Structured output recovered from result file"),{raw:L,structured:T}}catch(B){f.warn(`[Gemini] Result file parse/validation failed: ${B.message}`)}else R||f.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let O=null;if(s){let A=new te;A.zodSchema=s,A.processChunk(L),A.flush(),O=A.getResult()}if(f.info(`[Gemini] Raw stdout length: ${w.length} chars`),f.info(`[Gemini] Extracted text length: ${L.length} chars`),f.info(`[Gemini] StreamParser result: ${O?"extracted":"null"}`),O||(L.length<2e3?f.info(`[Gemini] Raw text preview:
104
+ ${D.bold("Prompt sent to LLM:")}`),console.log(D.dim("\u2500".repeat(60))),console.log(D.dim(C)),console.log(D.dim("\u2500".repeat(60)));let U=this._createGeminiConfigDir(n,b),E=["--output-format","json"];g&&g!=="auto"&&E.push("--model",g);let A=Object.keys(b);if(A.length>0){E.push("--approval-mode","yolo");for(let v of A)E.push("--allowed-mcp-server-names",v);f.info(`[Gemini] Enabling MCP servers: ${A.join(", ")}`)}else c&&c.length>0&&f.warn(`[Gemini] Skills requested but no MCP servers configured: ${c.join(", ")}`);E.push("-p",k);let $={...ve(process.env),GEMINI_CLI_HOME:U};y?($.GEMINI_API_KEY=y,delete $.GOOGLE_API_KEY):h&&($.GOOGLE_API_KEY=h,delete $.GEMINI_API_KEY),f.debug(`[Gemini] Command: gemini ${E.slice(0,8).join(" ")}... (${E.length} total args)`),f.debug(`[Gemini] User prompt: ${M.userPromptLength} chars, System instructions: ${M.systemInstructionsLength} chars (${M.instructionCount} blocks), Full: ${M.fullPromptLength} chars`),f.debug(`[Gemini] Config home: ${U}`),f.debug(`[Gemini] GEMINI_CLI_HOME env: ${$.GEMINI_CLI_HOME}`);let w="",R=null;try{w=await new Promise((B,H)=>{let T=Lo("gemini",E,{cwd:n,env:$,stdio:["ignore","pipe","pipe"],...d&&{signal:d}}),Z="",K="",j=!1,J=null,le=!1,ir=setTimeout(()=>{try{T.kill("SIGTERM")}catch{}},u),st=()=>{le||j||(le=!0,J=setTimeout(()=>{if(!j)try{T.kill("SIGKILL")}catch{}},5e3))};d&&(d.aborted?st():d.addEventListener("abort",st,{once:!0})),T.stdout.on("data",oe=>{Z+=oe.toString()}),T.stderr.on("data",oe=>{K+=oe.toString()}),T.on("error",oe=>{if(clearTimeout(ir),J&&clearTimeout(J),d&&!d.aborted)try{d.removeEventListener("abort",st)}catch{}H(oe)}),T.on("close",oe=>{if(j=!0,clearTimeout(ir),J&&clearTimeout(J),d&&!d.aborted)try{d.removeEventListener("abort",st)}catch{}if(le){let ar=new Error("Aborted via signal");return ar.name="AbortError",H(ar)}if(oe===0)return B(Z.trim());H(new Error(`gemini failed with code ${oe}: ${(K||Z).trim()}`))})})}catch(v){R=v}finally{try{Mo(U,{recursive:!0,force:!0})}catch{}}let L=jo(w).trim();if(!s){if(R)throw R;return L}if(I){let v=Ir(I);if(f.info(`[Gemini] Result file: ${v?"present":"missing"} at ${I}`),v)try{let B=Pr(I,"utf-8").trim(),H=JSON.parse(B),T=_?s.parse(H):H;return f.info("[Gemini] Structured output recovered from result file"),{raw:L,structured:T}}catch(B){f.warn(`[Gemini] Result file parse/validation failed: ${B.message}`)}else R||f.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let O=null;if(s){let v=new te;v.zodSchema=s,v.processChunk(L),v.flush(),O=v.getResult()}if(f.info(`[Gemini] Raw stdout length: ${w.length} chars`),f.info(`[Gemini] Extracted text length: ${L.length} chars`),f.info(`[Gemini] StreamParser result: ${O?"extracted":"null"}`),O||(L.length<2e3?f.info(`[Gemini] Raw text preview:
105
105
  ${L}`):f.info(`[Gemini] Raw text preview (first 1000 chars):
106
106
  ${L.slice(0,1e3)}`),O=Uo(L)),!O)throw R||(f.error("[Gemini] Failed to extract valid JSON from output"),f.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 G=_?s.parse(O):O;return{raw:L,structured:G}}finally{for(let p of m)p.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=No(n);if(!s||typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let c=s.cursorKey||s.serverName||n,a=Q("gemini",i);a&&(r[c]=a)}return r}_createGeminiConfigDir(e,t){let r=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,n=me(e||process.cwd(),".zibby","tmp",`gemini-home-${r}`),s=me(n,".gemini");Cr(s,{recursive:!0});let i=me(s,"settings.json"),c={},a=me(process.env.HOME||"",".gemini","settings.json");if(Ir(a))try{c=JSON.parse(Pr(a,"utf-8"))}catch{c={}}let l={...c,mcpServers:{...c.mcpServers&&typeof c.mcpServers=="object"?c.mcpServers:{},...t||{}}};kr(i,`${JSON.stringify(l,null,2)}
107
107
  `,"utf-8");let u=me(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{kr(u,`${JSON.stringify(l,null,2)}
108
108
  `,"utf-8")}catch{}return f.debug(`[Gemini] Created isolated config with ${Object.keys(l.mcpServers||{}).length} MCP servers`),f.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(l.mcpServers||{}),null,2)}`),n}};import{AgentStrategy as Xo,getSkill as St}from"@zibby/agent-workflow";var Oe=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 he=class extends Oe{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 Ve=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 gt(o){return Buffer.byteLength(JSON.stringify(o),"utf8")}function ht(o,e){let t=String(o||"");if(t.length<=e)return t;let r=Math.max(0,e-28);return`${t.slice(0,r)}
109
109
 
110
110
  [truncated for size budget]`}function kt(o,e=0){if(!o||typeof o!="object"||e>8)return o;if(Array.isArray(o))return o.map(r=>kt(r,e+1));let t={};for(let[r,n]of Object.entries(o))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=kt(n,e+1));return t}function Bo(o=[]){return o.map(e=>({...e,function:{...e.function,description:ht(e.function?.description||"",180),parameters:kt(e.function?.parameters||{type:"object",properties:{}})}}))}function Nr(o){let e=new Set;for(let n of o)if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let s of n.tool_calls)e.add(s.id);let t=o.filter(n=>n.role==="tool"?e.has(n.tool_call_id):!0),r=new Set;for(let n of t)n.role==="tool"&&r.add(n.tool_call_id);return t.map(n=>{if(n.role!=="assistant"||!Array.isArray(n.tool_calls)||n.tool_calls.every(a=>r.has(a.id)))return n;let{tool_calls:i,...c}=n;return{...c,content:c.content||""}})}function Nt(o,e={}){let t=e.maxBytes||49e3,r=e.systemMaxChars||12e3,n={...o,messages:Array.isArray(o.messages)?[...o.messages]:[],tools:Array.isArray(o.tools)?Bo(o.tools):o.tools};n.messages.length>0&&n.messages[0]?.role==="system"&&(n.messages[0]={...n.messages[0],content:ht(n.messages[0].content,r)});let s=!1;for(;gt(n)>t&&n.messages.length>2;)n.messages.splice(1,1),s=!0;if(s&&(n.messages=Nr(n.messages)),gt(n)>t&&n.messages.length>0&&(n.messages[0]={...n.messages[0],content:ht(n.messages[0].content,6e3)},s=!0),gt(n)>t){let i=n.messages.find(a=>a.role==="system")||n.messages[0],c=n.messages.slice(-2);n.messages=Nr([i,...c].filter(Boolean).map((a,l)=>({...a,content:ht(a.content,l===0?4e3:8e3)}))),s=!0}return{body:n,meta:{bytes:gt(n),trimmed:s,maxBytes:t,messageCount:n.messages.length}}}var Rr=o=>Buffer.byteLength(JSON.stringify(o),"utf8"),Ie=class extends Ve{async fetchCompletion(e,t,r={}){let n=Rr(e),{body:s,meta:i}=Nt(e,r.payloadCompaction);r.onBudget?.({streaming:!1,beforeBytes:n,meta:i});let c=this.#e(r),a=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,l=await fetch(a,{method:"POST",headers:t.headers,body:JSON.stringify(s),signal:c});if(!l.ok){let u=await l.text();throw l.status===401||l.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${l.status}: ${u}`)}return l.json()}async fetchStreamingCompletion(e,t,r={}){let n={...e,stream:!0},s=Rr(n),{body:i,meta:c}=Nt(n,r.payloadCompaction);r.onBudget?.({streaming:!0,beforeBytes:s,meta:c});let a=this.#e(r),l=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,u=await fetch(l,{method:"POST",headers:t.headers,body:JSON.stringify(i),signal:a});if(!u.ok){let h=await u.text();throw u.status===401||u.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${u.status}: ${h}`)}let d=u.body.getReader(),m=new TextDecoder,p="",g="",y=new Map;for(;;){let{done:h,value:b}=await d.read();if(h)break;p+=m.decode(b,{stream:!0});let S=p.split(`
111
- `);p=S.pop();for(let x of S){if(!x.startsWith("data: "))continue;let _=x.slice(6).trim();if(_==="[DONE]")continue;let C;try{C=JSON.parse(_)}catch{continue}let k=C.choices?.[0]?.delta;if(k&&(k.content&&(g+=k.content,r.onToken&&r.onToken(k.content)),k.tool_calls))for(let N of k.tool_calls){let I=N.index??0;y.has(I)||y.set(I,{id:"",name:"",args:""});let M=y.get(I);N.id&&(M.id=N.id),N.function?.name&&(M.name=N.function.name),N.function?.arguments!=null&&(M.args+=N.function.arguments)}}}if(y.size>0){let h=[...y.entries()].sort(([b],[S])=>b-S).map(([,b])=>({id:b.id,type:"function",function:{name:b.name,arguments:b.args}}));return{choices:[{message:{role:"assistant",content:g||null,tool_calls:h}}]}}return{choices:[{message:{role:"assistant",content:g}}]}}#e(e={}){let t=[e.signal,e.timeout?AbortSignal.timeout(e.timeout):null].filter(Boolean);return t.length>1?AbortSignal.any(t):t[0]||void 0}};import{Client as Fo}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Go}from"@modelcontextprotocol/sdk/client/stdio.js";var Ze=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:r,args:n=[],env:s={}}=t;f.debug(`[MCP] Starting ${e}: ${r} ${n.join(" ")}`);let i=new Go({command:r,args:n,env:{...process.env,...s}}),c=new Fo({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await c.connect(i);let a={client:c,transport:i,serverConfig:t};return this.#e.set(e,a),a}async callTool(e,t,r={}){let n=this.#e.get(e);if(!n)throw new Error(`MCP server "${e}" not running`);f.debug(`[MCP] ${e}.${t}(${JSON.stringify(r).slice(0,200)})`);let s=await n.client.callTool({name:t,arguments:r});return{text:s.content?.filter(c=>c.type==="text").map(c=>c.text).join(`
111
+ `);p=S.pop();for(let x of S){if(!x.startsWith("data: "))continue;let _=x.slice(6).trim();if(_==="[DONE]")continue;let I;try{I=JSON.parse(_)}catch{continue}let k=I.choices?.[0]?.delta;if(k&&(k.content&&(g+=k.content,r.onToken&&r.onToken(k.content)),k.tool_calls))for(let N of k.tool_calls){let C=N.index??0;y.has(C)||y.set(C,{id:"",name:"",args:""});let M=y.get(C);N.id&&(M.id=N.id),N.function?.name&&(M.name=N.function.name),N.function?.arguments!=null&&(M.args+=N.function.arguments)}}}if(y.size>0){let h=[...y.entries()].sort(([b],[S])=>b-S).map(([,b])=>({id:b.id,type:"function",function:{name:b.name,arguments:b.args}}));return{choices:[{message:{role:"assistant",content:g||null,tool_calls:h}}]}}return{choices:[{message:{role:"assistant",content:g}}]}}#e(e={}){let t=[e.signal,e.timeout?AbortSignal.timeout(e.timeout):null].filter(Boolean);return t.length>1?AbortSignal.any(t):t[0]||void 0}};import{Client as Fo}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Go}from"@modelcontextprotocol/sdk/client/stdio.js";var Ze=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:r,args:n=[],env:s={}}=t;f.debug(`[MCP] Starting ${e}: ${r} ${n.join(" ")}`);let i=new Go({command:r,args:n,env:{...process.env,...s}}),c=new Fo({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await c.connect(i);let a={client:c,transport:i,serverConfig:t};return this.#e.set(e,a),a}async callTool(e,t,r={}){let n=this.#e.get(e);if(!n)throw new Error(`MCP server "${e}" not running`);f.debug(`[MCP] ${e}.${t}(${JSON.stringify(r).slice(0,200)})`);let s=await n.client.callTool({name:t,arguments:r});return{text:s.content?.filter(c=>c.type==="text").map(c=>c.text).join(`
112
112
  `)||"",isError:s.isError||!1}}isRunning(e){return this.#e.has(e)}async stopServer(e){let t=this.#e.get(e);if(t){try{await t.client.close()}catch(r){f.debug(`[MCP] Error closing ${e}: ${r.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}};import{existsSync as Ko,readFileSync as Jo}from"node:fs";import{join as zo}from"node:path";import{homedir as Ho}from"node:os";function Yo(){try{let o=zo(Ho(),".zibby","config.json");return Ko(o)?JSON.parse(Jo(o,"utf-8")):{}}catch{return{}}}function yt(o){return String(o||"").replace(/\/v1\/?$/,"")}function Wo(o,e){let t=process.env.OPENAI_PROXY_URL;if(t)return yt(t);if(o==="session")return e.proxyUrl?yt(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(o==="byok"){let r=process.env.OPENAI_BASE_URL;return yt(r||"https://api.openai.com")}return yt(t||"")}function Rt(){let o=Yo(),e=process.env.ZIBBY_USER_TOKEN||o.sessionToken||null,t=process.env.OPENAI_API_KEY||null,r=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),n=process.env.OPENAI_PROXY_NO_AUTH==="true",s=process.env.OPENAI_PROXY_URL,i="session";r==="byok"||r==="local"||r==="session"?i=r:e?i="session":t?i="byok":s&&n&&(i="local");let c=Wo(i,o),a={"Content-Type":"application/json"};if(i==="session"){if(!e)return{ok:!1,mode:i,reason:"missing_session_token"};a.Authorization=`Bearer ${e}`}else if(i==="byok"){if(!t)return{ok:!1,mode:i,reason:"missing_openai_api_key"};a.Authorization=`Bearer ${t}`}else if(i==="local"){if(!c)return{ok:!1,mode:i,reason:"missing_openai_proxy_url"};!n&&t&&(a.Authorization=`Bearer ${t}`)}return c?{ok:!0,mode:i,baseUrl:c,headers:a,tokenPreview:a.Authorization?`***${a.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:i,reason:"missing_base_url"}}function bt(o,e){let t=String(o??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
113
113
 
114
- [tool result truncated for size]`}function Vo(o,e){if(typeof o=="string")return bt(o,e);try{return bt(JSON.stringify(o),e)}catch{return bt(String(o),e)}}function Lr(o){let e=new Set;for(let n of o)if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let s of n.tool_calls)e.add(s.id);let t=o.filter(n=>n.role==="tool"?e.has(n.tool_call_id):!0),r=new Set;for(let n of t)n.role==="tool"&&r.add(n.tool_call_id);return t.map(n=>{if(n.role!=="assistant"||!Array.isArray(n.tool_calls)||n.tool_calls.every(a=>r.has(a.id)))return n;let{tool_calls:i,...c}=n;return{...c,content:c.content||""}})}function Zo(o){let e=Array.isArray(o?.messages)?o.messages:[],t=e.find(s=>s.role==="system"),r=e.slice(-4).map(s=>({...s,content:bt(s.content,s.role==="tool"?1200:2500)}));r=Lr(r);let n={...o,messages:[t,...r].filter(Boolean)};return delete n.tools,n}async function qo({body:o,streaming:e,auth:t,options:r,fetchCompletion:n,fetchStreamingCompletion:s,onFallbackLog:i}){try{return e?await s(o,t,r):await n(o,t,r)}catch(c){let a=String(c?.message||c||"");if(!/proxy error 413|payload too large/i.test(a))throw c;let l=Zo(o);return typeof i=="function"&&i(o,l),{data:e?await s(l,t,r):await n(l,t,r),fallback:l}}}async function Mr({body:o,auth:e,options:t,streaming:r,toolContext:n,activeSkills:s,round:i,verbose:c,dependencies:a,config:l={}}){let u=l.maxToolResultChars||3e3,{fetchCompletion:d,fetchStreamingCompletion:m,onFallbackLog:p,hasToolCalls:g,getTextContent:y,parseToolCalls:h,buildAssistantMessage:b,buildToolResultMessage:S,executeTool:x,onToolCallLog:_,injectTools:C}=a;Array.isArray(o?.messages)&&(o.messages=Lr(o.messages));let k=await qo({body:o,streaming:r,auth:e,options:t,fetchCompletion:d,fetchStreamingCompletion:m,onFallbackLog:p}),N=k?.data||k;if(!g(N))return{done:!0,text:y(N),body:k?.fallback||o};let I=h(N),M=k?.fallback||o;M.messages.push(b(N)),c&&typeof _=="function"&&_(I);let F=await Promise.all(I.map((P,D)=>(typeof t.onToolCall=="function"&&t.onToolCall(P.name,P.args,{round:i,index:D,total:I.length}),x(P,n))));for(let P=0;P<I.length;P++){let U=I[P].name==="get_skill_context"?typeof F[P]=="string"?F[P]:JSON.stringify(F[P]):Vo(F[P],u);M.messages.push(S(I[P].id,U))}return typeof t.onToolCall=="function"&&t.onToolCall(null),C(M,s),{done:!1,body:M}}var Qo=se.ASSISTANT,es=15,Lt="get_skill_context";function Pe(o){!o||typeof o!="object"||(o.type==="object"&&o.properties&&(o.required=Object.keys(o.properties),o.additionalProperties=!1,Object.values(o.properties).forEach(Pe)),o.type==="array"&&o.items&&Pe(o.items),o.anyOf&&o.anyOf.forEach(Pe),o.oneOf&&o.oneOf.forEach(Pe),o.allOf&&o.allOf.forEach(Pe))}var Dr={maxBytes:49e3,systemMaxChars:12e3},Ce=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",ts=o=>Buffer.byteLength(JSON.stringify(o),"utf8");function _t(o){return Array.isArray(o)?new Set(o.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function rs(o){return Array.isArray(o)?o.map(e=>String(e||"").trim()).filter(Boolean):[]}var ye=class extends Xo{#e;#t;#r=new Ze;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new he,this.#t=e.completionProvider||new Ie):(this.#e=e||new he,this.#t=new Ie)}canHandle(e){return Rt().ok}async invoke(e,t={}){let r=V("OPENAI_API_KEY");try{let n=t.model&&t.model!=="auto"?t.model:Qo,s=Rt();if(!s.ok)throw s.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):s.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):s.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${s.reason}).`);let i=t.messages||[{role:"user",content:e}],c=s.baseUrl,a=Ce();if(a?await this.#m(i,n,c,s.tokenPreview||"none"):f.debug(`[Assistant] ${c} | model: ${n} | messages: ${i.length}`),t.schema)return this.#c(n,i,s,t);let l=t.activeSkills||[],u=this.#p(t),d=this.#f(l,u),m=this.#d(d),p=this.#u(t),g={...t,payloadCompaction:p},y={activeSkills:d,options:g,executionRegistry:m,capabilityPolicy:u},h=!!t.stream,b={model:n,messages:[...i],stream:!1};this.#o(b,d,u);for(let S=0;S<es;S++){if(t.signal?.aborted){let _=new Error("Aborted via signal");throw _.name="AbortError",_}let x=await Mr({body:b,auth:s,options:g,streaming:h,toolContext:y,activeSkills:d,round:S,verbose:a,dependencies:{fetchCompletion:this.#s.bind(this),fetchStreamingCompletion:this.#l.bind(this),onFallbackLog:(_,C)=>{Ce()&&console.log(`413 fallback: messages ${_.messages.length} -> ${C.messages.length}, bytes=${ts(C)}`)},hasToolCalls:_=>this.#e.hasToolCalls(_),getTextContent:_=>this.#e.getTextContent(_),parseToolCalls:_=>this.#e.parseToolCalls(_),buildAssistantMessage:_=>this.#e.buildAssistantMessage(_),buildToolResultMessage:(_,C)=>this.#e.buildToolResultMessage(_,C),executeTool:(_,C)=>this.#a(_,C),onToolCallLog:async _=>{let C=(await import("chalk")).default;console.log(C.dim(` ${_.map(k=>`${k.name}(${JSON.stringify(k.args).slice(0,80)})`).join(", ")}`))},injectTools:(_,C)=>this.#o(_,C,u)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(x.done)return x.text;b.messages=x.body.messages,x.body.tools?b.tools=x.body.tools:delete b.tools}return"I hit my tool-calling limit for this turn. Please try again."}finally{r.dispose()}}async cleanup(){await this.#r.stopAll()}#o(e,t,r=null){let n=this.#i(t,r),s=this.#e.formatTools(n);this.#e.injectToolsIntoBody(e,s)}#i(e,t=null){let r=[],n=new Set;for(let s of e){let i=St(s);if(i?.tools?.length)for(let c of i.tools)this.#n(c.name,t)&&(n.has(c.name)||(n.add(c.name),r.push({name:c.name,description:c.description,parameters:c.parameters||c.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#n(Lt,t)&&r.push({name:Lt,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),r}async#a(e,t){let{activeSkills:r,options:n,executionRegistry:s,capabilityPolicy:i}=t;if(!this.#n(e.name,i))return`Tool "${e.name}" blocked by policy`;if(e.name===Lt){let l=String(e.args?.skillId||"").trim();if(!l)return JSON.stringify({error:"skillId is required"});if(!r.includes(l))return JSON.stringify({error:`Skill "${l}" is not active`,activeSkills:r});let u=St(l);if(!u)return JSON.stringify({error:`Skill "${l}" not found`});let d=typeof u.promptFragment=="function"?u.promptFragment():u.promptFragment||"",m=(u.tools||[]).map(g=>g.name),p=JSON.stringify({skillId:l,description:u.description||"",toolNames:m,promptFragment:d||""});return Ce()&&(console.log(`
114
+ [tool result truncated for size]`}function Vo(o,e){if(typeof o=="string")return bt(o,e);try{return bt(JSON.stringify(o),e)}catch{return bt(String(o),e)}}function Lr(o){let e=new Set;for(let n of o)if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let s of n.tool_calls)e.add(s.id);let t=o.filter(n=>n.role==="tool"?e.has(n.tool_call_id):!0),r=new Set;for(let n of t)n.role==="tool"&&r.add(n.tool_call_id);return t.map(n=>{if(n.role!=="assistant"||!Array.isArray(n.tool_calls)||n.tool_calls.every(a=>r.has(a.id)))return n;let{tool_calls:i,...c}=n;return{...c,content:c.content||""}})}function Zo(o){let e=Array.isArray(o?.messages)?o.messages:[],t=e.find(s=>s.role==="system"),r=e.slice(-4).map(s=>({...s,content:bt(s.content,s.role==="tool"?1200:2500)}));r=Lr(r);let n={...o,messages:[t,...r].filter(Boolean)};return delete n.tools,n}async function qo({body:o,streaming:e,auth:t,options:r,fetchCompletion:n,fetchStreamingCompletion:s,onFallbackLog:i}){try{return e?await s(o,t,r):await n(o,t,r)}catch(c){let a=String(c?.message||c||"");if(!/proxy error 413|payload too large/i.test(a))throw c;let l=Zo(o);return typeof i=="function"&&i(o,l),{data:e?await s(l,t,r):await n(l,t,r),fallback:l}}}async function Mr({body:o,auth:e,options:t,streaming:r,toolContext:n,activeSkills:s,round:i,verbose:c,dependencies:a,config:l={}}){let u=l.maxToolResultChars||3e3,{fetchCompletion:d,fetchStreamingCompletion:m,onFallbackLog:p,hasToolCalls:g,getTextContent:y,parseToolCalls:h,buildAssistantMessage:b,buildToolResultMessage:S,executeTool:x,onToolCallLog:_,injectTools:I}=a;Array.isArray(o?.messages)&&(o.messages=Lr(o.messages));let k=await qo({body:o,streaming:r,auth:e,options:t,fetchCompletion:d,fetchStreamingCompletion:m,onFallbackLog:p}),N=k?.data||k;if(!g(N))return{done:!0,text:y(N),body:k?.fallback||o};let C=h(N),M=k?.fallback||o;M.messages.push(b(N)),c&&typeof _=="function"&&_(C);let F=await Promise.all(C.map((P,D)=>(typeof t.onToolCall=="function"&&t.onToolCall(P.name,P.args,{round:i,index:D,total:C.length}),x(P,n))));for(let P=0;P<C.length;P++){let U=C[P].name==="get_skill_context"?typeof F[P]=="string"?F[P]:JSON.stringify(F[P]):Vo(F[P],u);M.messages.push(S(C[P].id,U))}return typeof t.onToolCall=="function"&&t.onToolCall(null),I(M,s),{done:!1,body:M}}var Qo=se.ASSISTANT,es=15,Lt="get_skill_context";function Pe(o){!o||typeof o!="object"||(o.type==="object"&&o.properties&&(o.required=Object.keys(o.properties),o.additionalProperties=!1,Object.values(o.properties).forEach(Pe)),o.type==="array"&&o.items&&Pe(o.items),o.anyOf&&o.anyOf.forEach(Pe),o.oneOf&&o.oneOf.forEach(Pe),o.allOf&&o.allOf.forEach(Pe))}var Dr={maxBytes:49e3,systemMaxChars:12e3},Ce=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",ts=o=>Buffer.byteLength(JSON.stringify(o),"utf8");function _t(o){return Array.isArray(o)?new Set(o.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function rs(o){return Array.isArray(o)?o.map(e=>String(e||"").trim()).filter(Boolean):[]}var ye=class extends Xo{#e;#t;#r=new Ze;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new he,this.#t=e.completionProvider||new Ie):(this.#e=e||new he,this.#t=new Ie)}canHandle(e){return Rt().ok}async invoke(e,t={}){let r=V("OPENAI_API_KEY");try{let n=t.model&&t.model!=="auto"?t.model:Qo,s=Rt();if(!s.ok)throw s.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):s.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):s.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${s.reason}).`);let i=t.messages||[{role:"user",content:e}],c=s.baseUrl,a=Ce();if(a?await this.#m(i,n,c,s.tokenPreview||"none"):f.debug(`[Assistant] ${c} | model: ${n} | messages: ${i.length}`),t.schema)return this.#c(n,i,s,t);let l=t.activeSkills||[],u=this.#p(t),d=this.#f(l,u),m=this.#d(d),p=this.#u(t),g={...t,payloadCompaction:p},y={activeSkills:d,options:g,executionRegistry:m,capabilityPolicy:u},h=!!t.stream,b={model:n,messages:[...i],stream:!1};this.#o(b,d,u);for(let S=0;S<es;S++){if(t.signal?.aborted){let _=new Error("Aborted via signal");throw _.name="AbortError",_}let x=await Mr({body:b,auth:s,options:g,streaming:h,toolContext:y,activeSkills:d,round:S,verbose:a,dependencies:{fetchCompletion:this.#s.bind(this),fetchStreamingCompletion:this.#l.bind(this),onFallbackLog:(_,I)=>{Ce()&&console.log(`413 fallback: messages ${_.messages.length} -> ${I.messages.length}, bytes=${ts(I)}`)},hasToolCalls:_=>this.#e.hasToolCalls(_),getTextContent:_=>this.#e.getTextContent(_),parseToolCalls:_=>this.#e.parseToolCalls(_),buildAssistantMessage:_=>this.#e.buildAssistantMessage(_),buildToolResultMessage:(_,I)=>this.#e.buildToolResultMessage(_,I),executeTool:(_,I)=>this.#a(_,I),onToolCallLog:async _=>{let I=(await import("chalk")).default;console.log(I.dim(` ${_.map(k=>`${k.name}(${JSON.stringify(k.args).slice(0,80)})`).join(", ")}`))},injectTools:(_,I)=>this.#o(_,I,u)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(x.done)return x.text;b.messages=x.body.messages,x.body.tools?b.tools=x.body.tools:delete b.tools}return"I hit my tool-calling limit for this turn. Please try again."}finally{r.dispose()}}async cleanup(){await this.#r.stopAll()}#o(e,t,r=null){let n=this.#i(t,r),s=this.#e.formatTools(n);this.#e.injectToolsIntoBody(e,s)}#i(e,t=null){let r=[],n=new Set;for(let s of e){let i=St(s);if(i?.tools?.length)for(let c of i.tools)this.#n(c.name,t)&&(n.has(c.name)||(n.add(c.name),r.push({name:c.name,description:c.description,parameters:c.parameters||c.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#n(Lt,t)&&r.push({name:Lt,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),r}async#a(e,t){let{activeSkills:r,options:n,executionRegistry:s,capabilityPolicy:i}=t;if(!this.#n(e.name,i))return`Tool "${e.name}" blocked by policy`;if(e.name===Lt){let l=String(e.args?.skillId||"").trim();if(!l)return JSON.stringify({error:"skillId is required"});if(!r.includes(l))return JSON.stringify({error:`Skill "${l}" is not active`,activeSkills:r});let u=St(l);if(!u)return JSON.stringify({error:`Skill "${l}" not found`});let d=typeof u.promptFragment=="function"?u.promptFragment():u.promptFragment||"",m=(u.tools||[]).map(g=>g.name),p=JSON.stringify({skillId:l,description:u.description||"",toolNames:m,promptFragment:d||""});return Ce()&&(console.log(`
115
115
  \u{1F4D6} get_skill_context("${l}") \u2192 ${p.length} chars (fragment: ${d.length} chars)`),console.log(` tools: [${m.join(", ")}]`),console.log(` fragment preview: ${d.slice(0,200).replace(/\n/g,"\\n")}\u2026
116
116
  `)),p}let c=s?.get(e.name)||null;if(!c)return`Unknown tool: ${e.name}`;let a=St(c.skillId);if(!a)return`Skill "${c.skillId}" not found for tool "${e.name}"`;if(c.mode==="handler")try{return a.handleToolCall(e.name,e.args,t)}catch(l){return`Error in ${e.name}: ${l.message}`}if(c.mode==="mcp")try{if(!this.#r.isRunning(a.serverName)){let u=a.resolve(n);if(!u)return`Skill "${c.skillId}" is not available (cannot start server)`;await this.#r.ensureServer(a.serverName,u)}let l=await this.#r.callTool(a.serverName,e.name,e.args);return l.text||(l.isError?"Tool call failed":"Done")}catch(l){return`MCP error (${a.serverName}): ${l.message}`}return`Skill "${c.skillId}" owns tool "${e.name}" but has no execution mode`}async#l(e,t,r){return this.#t.fetchStreamingCompletion(e,t,{...r,onBudget:({beforeBytes:n,meta:s})=>{Ce()&&console.log(`payload bytes (stream) before=${n} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#s(e,t,r){return this.#t.fetchCompletion(e,t,{...r,onBudget:({beforeBytes:n,meta:s})=>{Ce()&&console.log(`payload bytes before=${n} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#c(e,t,r,n){let{zodToJson:s}=await Promise.resolve().then(()=>(ze(),Tr)),i=typeof n.schema?.parse=="function",c=i?s(n.schema,{}):n.schema;delete c.$schema,Pe(c);let a={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:c,strict:!0}}},l=await this.#s(a,r,n),u=this.#e.getTextContent(l),d=JSON.parse(u),m=i?n.schema.parse(d):d;return{raw:u,structured:m}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||Dr.maxBytes),systemMaxChars:Number(t.systemMaxChars||Dr.systemMaxChars)}}#p(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:_t(t.allowTools||e.allowTools),denyTools:_t(t.denyTools||e.denyTools),denyPrefixes:rs(t.denyPrefixes||e.denyToolPrefixes),includeSkills:_t(t.includeSkills||e.includeSkills),excludeSkills:_t(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#f(e,t){let r=t?.includeSkills||new Set,n=t?.excludeSkills||new Set;return r.size===0&&n.size===0?e:e.filter(s=>!(r.size>0&&!r.has(s)||n.has(s)))}#n(e,t){let r=String(e||"").trim();if(!r)return!1;let n=t?.allowTools;if(n&&n.size>0&&!n.has(r))return!1;let s=t?.denyTools;return!(s&&s.has(r)||(t?.denyPrefixes||[]).some(c=>r.startsWith(c)))}#d(e){let t=new Map,r=[];for(let n of e){let s=St(n);if(!s?.tools?.length)continue;let i=typeof s.handleToolCall=="function"?"handler":s.serverName&&typeof s.resolve=="function"?"mcp":null;if(i)for(let c of s.tools){let a=String(c?.name||"").trim();if(a){if(t.has(a)){r.push({tool:a,winner:t.get(a).skillId,skipped:n});continue}t.set(a,{skillId:n,mode:i})}}}if(r.length>0&&Ce()){let n=r.slice(0,5).map(s=>`${s.tool}:${s.winner}>${s.skipped}`).join(", ");console.log(`tool registry collisions: ${n}${r.length>5?" ...":""}`)}return t}async#m(e,t,r,n){console.log(`
117
117
  \u25C6 Model: ${t} | proxy: ${r} | token: ${n||"none"}
@@ -144,7 +144,7 @@ ${JSON.stringify(a,null,2)}
144
144
  `)}catch(l){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${l.message}`)}return{success:!0,output:a,raw:c}}async cleanup(){this.adapter&&this.adapter.isConnected()&&await this.adapter.disconnect()}async executePrompt(e,t=process.cwd(),r=3e5,n=null,s=!0){let i=this.agentCommand;if(i==="cursor-agent"){let c=await jt();c&&(i=c)}return new Promise((c,a)=>{let l="",u=this.buildArgs(e,s);n&&u.push("--model",n);let d={...process.env},m=ls(i,u,{cwd:t,env:d,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),p=setTimeout(()=>{console.log(`
145
145
  \u23F1\uFE0F Timeout reached (${r/1e3}s) - killing agent...`),m.kill("SIGTERM"),setTimeout(()=>{m.killed||(console.log("\u26A0\uFE0F Forcing kill (SIGKILL)..."),m.kill("SIGKILL"))},2e3),a(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(l.length>g)g=l.length,y=Date.now();else{let _=Date.now()-y;_>1e4&&console.log(`\u23F3 AI agent is thinking... (${Math.floor(_/1e3)}s, ${l.length} bytes so far)`)}},1e4),b=()=>{clearTimeout(p),clearInterval(h),m&&!m.killed&&(m.kill("SIGTERM"),setTimeout(()=>{m.killed||m.kill("SIGKILL")},2e3))},S=()=>{console.log(`
146
146
 
147
- \u{1F6D1} Interrupted by user (Ctrl+C)`),b(),a(new Error("Interrupted by user"))};process.on("SIGINT",S);let x=new te;m.stdout.on("data",_=>{let C=_.toString();l+=C;let k=x.processChunk(C);k&&(process.stdout.write(k,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),y=Date.now(),g+=k.length)}),m.on("close",_=>{process.off("SIGINT",S),clearTimeout(p),clearInterval(h);let C=x.flush();C&&process.stdout.write(C),l=x.getRawText();let k=x.getResult();_===0?c({raw:l,extracted:k}):a(new Error(`Agent exited with code ${_}`))}),m.on("error",_=>{process.off("SIGINT",S),clearTimeout(p),clearInterval(h),a(new Error(`Failed to spawn agent: ${_.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 i=r.sessionPath,c=r.sessionTimestamp,a=r.config||{};if(!i){let h=process.env.CI_JOB_ID||process.env.GITHUB_RUN_ID||process.env.CIRCLE_WORKFLOW_ID||process.env.BUILD_ID||Date.now().toString(),b=a.paths?.sessionPrefix,S=b?`${b}_${h}`:h;c=c||Date.now();let x=a.paths?.output||Gr;i=Bt(s,x,gs,S),cs(i)||Fr(i,{recursive:!0})}let l=a.paths?.output||Gr,u=Bt(s,l,hs);Fr(Bt(s,l),{recursive:!0}),us(u,JSON.stringify({sessionPath:i,sessionTimestamp:c||i.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
147
+ \u{1F6D1} Interrupted by user (Ctrl+C)`),b(),a(new Error("Interrupted by user"))};process.on("SIGINT",S);let x=new te;m.stdout.on("data",_=>{let I=_.toString();l+=I;let k=x.processChunk(I);k&&(process.stdout.write(k,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),y=Date.now(),g+=k.length)}),m.on("close",_=>{process.off("SIGINT",S),clearTimeout(p),clearInterval(h);let I=x.flush();I&&process.stdout.write(I),l=x.getRawText();let k=x.getResult();_===0?c({raw:l,extracted:k}):a(new Error(`Agent exited with code ${_}`))}),m.on("error",_=>{process.off("SIGINT",S),clearTimeout(p),clearInterval(h),a(new Error(`Failed to spawn agent: ${_.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 i=r.sessionPath,c=r.sessionTimestamp,a=r.config||{};if(!i){let h=process.env.CI_JOB_ID||process.env.GITHUB_RUN_ID||process.env.CIRCLE_WORKFLOW_ID||process.env.BUILD_ID||Date.now().toString(),b=a.paths?.sessionPrefix,S=b?`${b}_${h}`:h;c=c||Date.now();let x=a.paths?.output||Gr;i=Bt(s,x,gs,S),cs(i)||Fr(i,{recursive:!0})}let l=a.paths?.output||Gr,u=Bt(s,l,hs);Fr(Bt(s,l),{recursive:!0}),us(u,JSON.stringify({sessionPath:i,sessionTimestamp:c||i.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
148
148
  ${"=".repeat(80)}`),console.log(`\u{1F3AF} SINGLE NODE EXECUTION: ${e}`),console.log(`\u{1F4C1} Session: ${i.split("/").pop()}${r.sessionPath?" (reusing)":""}`),console.log(`${"=".repeat(80)}
149
149
  `);let d=await ps.loadContext(r.specPath||"",s,r.contextConfig||{}),m=new ms({...r,sessionPath:i,sessionTimestamp:c,context:d}),g=await new ds(n).execute(this,m);return console.log(`
150
150
  ${"=".repeat(80)}`),console.log(`\u2705 Node ${e} completed`),console.log(`${"=".repeat(80)}
@@ -152,8 +152,8 @@ ${"=".repeat(80)}`),console.log(`\u2705 Node ${e} completed`),console.log(`${"="
152
152
 
153
153
  ${b.join(`
154
154
 
155
- `)}`)}let g=e.state?._currentNodeConfig?.stores;if(Array.isArray(g)&&g.length>0&&typeof g[0]=="object"){let h=g.length<=8,b=g.map(S=>{let x=S?.id??S?.storeId??"",_=S?.name??x,C=S?.type?` \xB7 ${S.type}`:"",k=(S?.description||"").toString().replace(/\s+/g," ").trim(),N=`- ${_} \xB7 ${k||"(no description)"}${C}${x?` (id: ${x})`:""}`;if(h&&S?.schema&&typeof S.schema=="object"){let I=S.schema.properties&&typeof S.schema.properties=="object"?Object.keys(S.schema.properties):Object.keys(S.schema);I.length&&(N+=`
156
- fields: ${I.join(", ")}`)}return N});p+=`
155
+ `)}`)}let g=e.state?._currentNodeConfig?.stores;if(Array.isArray(g)&&g.length>0&&typeof g[0]=="object"){let h=g.length<=8,b=g.map(S=>{let x=S?.id??S?.storeId??"",_=S?.name??x,I=S?.type?` \xB7 ${S.type}`:"",k=(S?.description||"").toString().replace(/\s+/g," ").trim(),N=`- ${_} \xB7 ${k||"(no description)"}${I}${x?` (id: ${x})`:""}`;if(h&&S?.schema&&typeof S.schema=="object"){let C=S.schema.properties&&typeof S.schema.properties=="object"?Object.keys(S.schema.properties):Object.keys(S.schema);C.length&&(N+=`
156
+ fields: ${C.join(", ")}`)}return N});p+=`
157
157
 
158
158
  AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
159
159
  ${b.join(`
@@ -266,24 +266,24 @@ import { test, expect } from '@playwright/test';
266
266
  `;let{dirname:d}=await import("path"),{mkdirSync:m}=await import("fs");return m(d(e),{recursive:!0}),await tt.writeFile(e,l,"utf-8"),console.log(`[TestPostProcessor] \u2705 Generated test with ${i.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 tt.readFile(e,"utf-8");n.includes("ZibbyRuntime")||(n=`import { ZibbyRuntime } from '@zibby/core';
267
267
  ${n}`);for(let s=0;s<t.length;s++){let i=t[s],c=`element${s}`,a=new RegExp(`const ${c}\\b\\s*=\\s*page\\.[^;]+;(\\s*await ${c}\\.waitFor\\([^)]*\\);)?\\s*await ${c}\\.(click|fill|type|selectOption|pressSequentially)\\(([^)]*)\\);`,"s"),l=n.match(a);if(!l)continue;let u={name:i.name||`Action ${s}`,action:i.method==="type"?"fill":i.method,value:l[3].trim().replace(/^['"]|['"]$/g,""),strategies:i.strategies||[]},d=`await ZibbyRuntime.step(page, ${JSON.stringify(u,null,2)});`;n=n.replace(l[0],d)}return await tt.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 tt.readFile(e,"utf-8"),s=this.buildSelectorMap(r);return n=this.replaceSimpleSelectors(n,s),await tt.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}`,c=et.generate(n,s).match(/= (.+);/s);if(c){let a=c[1].trim(),l=`${n.type}:${this.normalizeDescription(n.description)}`;t.set(l,a),n.selectors.role&&t.set(`role:${n.selectors.role.name}`,a),n.selectors.attributes?.placeholder&&t.set(`placeholder:${n.selectors.attributes.placeholder}`,a)}}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,i=>{for(let[c,a]of t.entries())if(i.includes(c.split(":")[1])){let l=i.match(/\.(fill|click|type)\(([^)]*)\)/);if(l){let[,u,d]=l,m="element";return`const ${m} = ${a};
268
268
  await ${m}.${u}(${d})`}}return i});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as di,existsSync as hn,readdirSync as yn}from"node:fs";import{join as qt}from"node:path";import{execSync as mi}from"node:child_process";import{tmpdir as gi}from"node:os";var rt=class{static async parseTraceZip(e){let t;if(e.endsWith(".zip")&&hn(e)){let r=qt(gi(),`trace-${Date.now()}`);mi(`unzip -q "${e}" -d "${r}"`,{stdio:"pipe"});let s=yn(r).find(i=>i.endsWith(".trace"));if(!s)throw new Error("No .trace file found in zip");t=qt(r,s)}else if(hn(e)){let n=yn(e).find(s=>s.endsWith(".trace"));if(!n)throw new Error("No .trace file found");t=qt(e,n)}else throw new Error(`Trace not found at ${e}`);try{let n=di(t,"utf-8").trim().split(`
269
- `),s=[],i=new Map,c=new Map;for(let a of n)try{let l=JSON.parse(a);if(l.type==="snapshot"&&l.snapshot&&l.snapshot.accessibility){let u=new Map;for(let d of l.snapshot.accessibility)d.ref&&u.set(d.ref,d);i.set(l.snapshotName,u)}if(l.type==="frame-snapshot"&&l.snapshot){let u=Buffer.from(l.snapshot.html||"","base64").toString("utf-8");u&&u.length>100&&c.set(l.pageId||"default",u)}}catch{}for(let a of n)try{let l=JSON.parse(a);if(l.type==="before"&&l.params&&l.params.selector){let u=l.method;if(["click","fill","type","selectOption"].includes(u)){let d=l.params.selector,m=l.params.text||l.params.value||"",p=[],g=null,y=null,h=null,b=d.match(/aria-ref=([a-z0-9]+)/i);if(b&&l.snapshotName){let P=b[1],D=i.get(l.snapshotName);if(D&&D.has(P)){let U=D.get(P);g=U.name||null,y=U.role||null,h=U.label||null,console.log(`[TraceParser] \u2705 Found ACTUAL element data: text="${g}", role="${y}"`)}}let S=d.match(/internal:text="([^"]+)"/i),x=d.match(/internal:label="([^"]+)"/i),_=d.match(/internal:placeholder="([^"]+)"/i),C=d.match(/internal:role=([^ ]+)/i),k=d.match(/internal:describe="([^"]+)"/i),N=d.match(/name="([^"]+)"/i);if(S){p.push({type:"text",text:S[1]});let P=S[1].split(" ");P.length>1&&(p.push({type:"text",text:P[0],fuzzy:!0}),p.push({type:"text",text:P[P.length-1],fuzzy:!0}))}if(x&&p.push({type:"label",label:x[1]}),_&&p.push({type:"placeholder",placeholder:_[1]}),g){p.unshift({type:"text",text:g,source:"accessibility-tree"});let P=g.split(" ");P.length>1&&p.push({type:"text",text:P[0],fuzzy:!0,source:"accessibility-tree"})}if(y||C){let P=y||C[1],D=g||(N?N[1]:S?S[1]:null);p.unshift({type:"role",role:P,name:D,source:g?"accessibility-tree":"selector"})}if(h&&p.unshift({type:"label",label:h,source:"accessibility-tree"}),k){let P=k[1],D=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],U=null,E=P;for(let $ of D)if(P.toLowerCase().endsWith(` ${$}`)){U=$.replace(" ",""),E=P.substring(0,P.length-$.length-1);break}if(U){p.push({type:"role",role:U,name:E});let $=E.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:$}),p.push({type:"text",text:E});let v=E.split(" ");v.length>1&&(p.push({type:"text",text:v[0],fuzzy:!0}),p.push({type:"text",text:v.slice(0,2).join(" "),fuzzy:!0}))}else{let $=P.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:$}),p.push({type:"text",text:P})}}let I=this.extractDOMStrategies(d,c,S?.[1]||k?.[1],l.pageId);p.push(...I);let M=this.extractStructuralContext(d);(M.parent||M.sibling)&&p.forEach(P=>{["role","text","label","testid"].includes(P.type)&&(M.parent&&(P.parent=M.parent),M.sibling&&(P.sibling=M.sibling))}),p.push({type:"css",value:d});let F=g||S?S[1]:k?k[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${s.length}`;s.push({method:u,name:F,action:u==="type"?"fill":u,value:m,strategies:p,timestamp:l.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 i=t.get(n);if(!i)return s;let c=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),l=i.match(a);l&&s.push({type:"testid",value:l[1],priority:"high"});let u=new RegExp(`class=["']([^"']+)["'][^>]*>[^<]*${c}`,"gi"),d=i.matchAll(u);for(let g of d){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 m=new RegExp(`id=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),p=i.match(m);p&&!p[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&s.push({type:"id",value:p[1],priority:"high"})}catch(i){console.warn(`[TraceParser] DOM extraction failed: ${i.message}`)}return s}static extractStructuralContext(e){let t={parent:null,sibling:null},r=e.split(">>").map(i=>i.trim());if(r.length>1){let c=r[r.length-2].replace(/internal:text="[^"]+"\s*/gi,"").replace(/internal:role=\S+\s*/gi,"").replace(/internal:label="[^"]+"\s*/gi,"").trim();c&&(c.match(/^(form|section|nav|header|aside|main|article)\b/)||c.includes("[")||c.match(/[#.]\w/))&&(t.parent=c)}let s=r[r.length-1].match(/([^+~]+)\s*[+~]\s*(.+)/);return s&&(t.sibling=s[1].trim()),t}};var Xt=class{static async step(e,t){let{name:r,action:n,value:s,strategies:i,options:c={timeout:1e4},enrichedData:a}=t;console.log(`[Zibby] \u26A1 Executing step: ${r}`),await this.waitForPageStability(e,c.timeout);let l=await this.findBestMatch(e,i,r);if(!l)throw new Error(`[Zibby] \u274C Failed to find "${r}" using ${i.length} strategies`);a?.position&&await this.verifyPosition(l,a.position),await this.performActionWithRetry(e,l,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(i=>setTimeout(i,500)))}catch{}}static async performActionWithRetry(e,t,r,n,s=3){for(let i=1;i<=s;i++)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(c){if(i===s)throw c;console.log(`[Zibby] \u26A0\uFE0F Action failed (attempt ${i}/${s}), retrying...`),await new Promise(a=>setTimeout(a,1e3*i))}}static async findBestMatch(e,t,r){let s=Date.now(),i=t.map(async(l,u)=>{try{let m=await this.getLocator(e,l).all();return m.length===0?[]:(await Promise.all(m.map(async(g,y)=>{try{if(!await g.isVisible({timeout:100}))return null;let b=await this.scoreCandidate(g,l,e);return{element:g,strategy:l,score:b,strategyIdx:u,elIdx:y}}catch{return null}}))).filter(g=>g!==null)}catch{return[]}}),c=(await Promise.all(i)).flat();if(c.length===0)return console.log(`[Zibby] \u274C No visible candidates found for "${r}"`),null;c.sort((l,u)=>u.score-l.score);let a=c[0];return console.log(`[Zibby] \u2705 Found element using ${a.strategy.type} (score: ${a.score.toFixed(2)}, ${c.length} candidates)`),a.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((a,l)=>a.matches(l),t.parent)&&(n+=30)}catch{}if(t.sibling)try{await e.evaluate((c,a)=>c.parentElement?.querySelector(a)!==null,t.sibling)&&(n+=20)}catch{}try{let i=await e.boundingBox();i&&i.y<1e3&&(n+=10)}catch{}try{let i=await e.evaluate(c=>{let a=0,l=c;for(;l;)l.tagName==="IFRAME"&&a++,l=l.parentElement;return a});n-=i*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 Qt=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}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let c=e.locator(s);if(await c.count()>0)try{await c.click({timeout:2e3});return}catch(a){if(a.message.includes("intercepts pointer")){await c.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}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let c=e.locator(s);if(await c.count()>0){await c.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}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let c=e.locator(s);if(await c.count()>0){await c.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(a){if(a.getAttribute("aria-label"))return a.getAttribute("aria-label").trim();let l=a.getAttribute("aria-labelledby");if(l){let m=document.getElementById(l);if(m)return m.textContent.trim()}if(a.id){let m=document.querySelector(`label[for="${a.id}"]`);if(m)return m.textContent.trim()}let u=a.closest("label");if(u){let m=u.cloneNode(!0);m.querySelectorAll("input, select, textarea").forEach(g=>g.remove());let p=m.textContent.trim();if(p)return p}if(a.placeholder)return a.placeholder;let d=a.tagName.toLowerCase();return d==="button"||d==="a"||a.getAttribute("role")==="button"?(a.textContent||"").trim().slice(0,50):a.title?a.title:d==="input"&&(a.type==="submit"||a.type==="button")&&a.value||""}function r(a){let l=[],u=a.closest("form");if(u)if(u.id)l.push(`form#${u.id}`);else if(u.name)l.push(`form[name=${u.name}]`);else if(u.action)try{let y=new URL(u.action,window.location.origin).pathname;l.push(`form[action=${y}]`)}catch{l.push(`form[action=${u.getAttribute("action")}]`)}else{let y=document.querySelectorAll("form"),h=Array.from(y).indexOf(u);l.push(`form:nth(${h})`)}let d=a.closest('header, nav, main, footer, aside, [role="banner"], [role="navigation"], [role="main"], [role="contentinfo"]');if(d){let y=d.tagName.toLowerCase(),h=d.getAttribute("role");l.push(h||y)}let m=a.closest('section, article, [role="region"]');if(m){let y=m.querySelector("h1, h2, h3, h4, h5, h6");y&&l.push(`section:${y.textContent.trim().slice(0,30)}`)}let p=a.closest("fieldset");if(p){let y=p.querySelector("legend");y&&l.push(`fieldset:${y.textContent.trim()}`)}let g=a.closest('dialog, [role="dialog"], [role="alertdialog"]');if(g){let y=g.querySelector('[role="heading"], h1, h2, h3');y?l.push(`dialog:${y.textContent.trim().slice(0,30)}`):l.push("dialog")}return l.join("/")}function n(a){let l=a.tagName.toLowerCase(),u=a.id||"",d=a.name||"",m=a.type||"",p=a.getAttribute("role")||"",g="";if(a.href)try{g=new URL(a.href,window.location.origin).pathname.slice(0,50)}catch{g=a.getAttribute("href")?.slice(0,50)||""}let y=t(a).slice(0,50).replace(/\s+/g," "),h=r(a),b=[l,u,d,m,p,g,y,h].join("|"),S=5381;for(let x=0;x<b.length;x++)S=(S<<5)+S^b.charCodeAt(x);return`zibby-${(S>>>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(", "),i=new Map,c=0;document.querySelectorAll(s).forEach(a=>{let l=window.getComputedStyle(a);if(l.display==="none"||l.visibility==="hidden")return;let u=n(a),d=u,m=i.get(d)||0;m>0&&(u=`${d}-${m}`),i.set(d,m+1),a.setAttribute("data-zibby-id",u),c++}),console.log(`[Zibby] Injected ${c} stable IDs`)})}catch{}}};var hi=8,yi=1,bi=64;function Si(o){if(!o||typeof o!="object")return 8;let e=o.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 wi,writeFileSync as Sn,existsSync as xi}from"node:fs";import{join as _n}from"node:path";var W=class{constructor(e={}){this.config=e,this.enabled=e.enabled!==!1,this.priority=e.priority||50}getName(){throw new Error("EventEnricher.getName() must be implemented")}canEnrich(e){return this.enabled}async enrich(e,t){throw new Error("EventEnricher.enrich() must be implemented")}handleError(e,t){return console.warn(`[${this.getName()}] Enrichment failed for event ${t.type}:`,e.message),null}};import{existsSync as _i}from"node:fs";import{join as bn}from"node:path";var be=class extends W{constructor(e={}){super(e),this.priority=190,this.traceData=null}getName(){return"TraceText"}getPriority(){return this.priority}async loadTrace(e){if(this.traceData)return;let t=bn(e,"traces"),r=bn(e,"trace.zip");if(_i(r))try{this.traceData=await rt.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 i=s.actualText||this._extractTextFromSelector(s.selector),c=s.actualRole,a=s.actualAriaLabel;return i||c||a?(console.log(`[TraceTextEnricher] \u2705 Event ${n}: text="${i}", role="${c}", label="${a}"`),{traceActualText:i,traceActualRole:c,traceActualAriaLabel:a,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 Ei(o){let e=_n(o,"events.json"),t=_n(o,"events-enriched.json");if(!xi(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(wi(e,"utf-8")),n=new be,s=0,i=0;for(let c of r)try{let a=await n.enrich(c,{sessionPath:o});a&&(c.enrichedData={...c.enrichedData||{},...a},s++)}catch(a){console.log(`[PostProcess] Failed to enrich event ${c.id}: ${a.message}`),i++}return s>0&&(Sn(t,JSON.stringify(r,null,2)),Sn(e,JSON.stringify(r,null,2)),console.log(`[PostProcess] \u2705 Enriched ${s} events (${i} failed)`)),{enriched:s,failed:i}}catch(r){return console.log(`[PostProcess] \u274C Failed to post-process events: ${r.message}`),{enriched:0,failed:0}}}import{spawn as Ti}from"node:child_process";import{existsSync as vi}from"node:fs";import{dirname as Ai,resolve as wn,relative as $i}from"node:path";var vt=new Map,nt=8,xn={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 ${nt} 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:o},e){let r=`${e?.sessionId||"default"}:${o}`,n=(vt.get(r)||0)+1;if(vt.set(r,n),n>nt)return{success:!1,executionCount:n,maxReached:!0,error:`Maximum ${nt} executions reached. Stop retrying and return your best result.`};let s=e?.projectRoot||process.cwd(),i=wn(s,o),c=$i(s,i);return c.startsWith("..")||wn(i)!==i&&c.includes("..")?{success:!1,executionCount:n,error:"Path traversal detected: scriptPath must be within the project root."}:vi(i)?new Promise(a=>{let l=Ai(i),u=Ti("npx",["playwright","test",i,"--reporter=line"],{cwd:s,env:{...process.env,FORCE_COLOR:"0"}}),d="",m="";u.stdout.on("data",g=>{d+=g.toString()}),u.stderr.on("data",g=>{m+=g.toString()});let p=setTimeout(()=>{u.kill("SIGTERM"),a({success:!1,executionCount:n,error:"Test timed out after 60 seconds",stdout:d.slice(-2e3),stderr:m.slice(-1e3)})},6e4);u.on("close",g=>{clearTimeout(p);let h=`${d}
269
+ `),s=[],i=new Map,c=new Map;for(let a of n)try{let l=JSON.parse(a);if(l.type==="snapshot"&&l.snapshot&&l.snapshot.accessibility){let u=new Map;for(let d of l.snapshot.accessibility)d.ref&&u.set(d.ref,d);i.set(l.snapshotName,u)}if(l.type==="frame-snapshot"&&l.snapshot){let u=Buffer.from(l.snapshot.html||"","base64").toString("utf-8");u&&u.length>100&&c.set(l.pageId||"default",u)}}catch{}for(let a of n)try{let l=JSON.parse(a);if(l.type==="before"&&l.params&&l.params.selector){let u=l.method;if(["click","fill","type","selectOption"].includes(u)){let d=l.params.selector,m=l.params.text||l.params.value||"",p=[],g=null,y=null,h=null,b=d.match(/aria-ref=([a-z0-9]+)/i);if(b&&l.snapshotName){let P=b[1],D=i.get(l.snapshotName);if(D&&D.has(P)){let U=D.get(P);g=U.name||null,y=U.role||null,h=U.label||null,console.log(`[TraceParser] \u2705 Found ACTUAL element data: text="${g}", role="${y}"`)}}let S=d.match(/internal:text="([^"]+)"/i),x=d.match(/internal:label="([^"]+)"/i),_=d.match(/internal:placeholder="([^"]+)"/i),I=d.match(/internal:role=([^ ]+)/i),k=d.match(/internal:describe="([^"]+)"/i),N=d.match(/name="([^"]+)"/i);if(S){p.push({type:"text",text:S[1]});let P=S[1].split(" ");P.length>1&&(p.push({type:"text",text:P[0],fuzzy:!0}),p.push({type:"text",text:P[P.length-1],fuzzy:!0}))}if(x&&p.push({type:"label",label:x[1]}),_&&p.push({type:"placeholder",placeholder:_[1]}),g){p.unshift({type:"text",text:g,source:"accessibility-tree"});let P=g.split(" ");P.length>1&&p.push({type:"text",text:P[0],fuzzy:!0,source:"accessibility-tree"})}if(y||I){let P=y||I[1],D=g||(N?N[1]:S?S[1]:null);p.unshift({type:"role",role:P,name:D,source:g?"accessibility-tree":"selector"})}if(h&&p.unshift({type:"label",label:h,source:"accessibility-tree"}),k){let P=k[1],D=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],U=null,E=P;for(let A of D)if(P.toLowerCase().endsWith(` ${A}`)){U=A.replace(" ",""),E=P.substring(0,P.length-A.length-1);break}if(U){p.push({type:"role",role:U,name:E});let A=E.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:A}),p.push({type:"text",text:E});let $=E.split(" ");$.length>1&&(p.push({type:"text",text:$[0],fuzzy:!0}),p.push({type:"text",text:$.slice(0,2).join(" "),fuzzy:!0}))}else{let A=P.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:A}),p.push({type:"text",text:P})}}let C=this.extractDOMStrategies(d,c,S?.[1]||k?.[1],l.pageId);p.push(...C);let M=this.extractStructuralContext(d);(M.parent||M.sibling)&&p.forEach(P=>{["role","text","label","testid"].includes(P.type)&&(M.parent&&(P.parent=M.parent),M.sibling&&(P.sibling=M.sibling))}),p.push({type:"css",value:d});let F=g||S?S[1]:k?k[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${s.length}`;s.push({method:u,name:F,action:u==="type"?"fill":u,value:m,strategies:p,timestamp:l.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 i=t.get(n);if(!i)return s;let c=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),l=i.match(a);l&&s.push({type:"testid",value:l[1],priority:"high"});let u=new RegExp(`class=["']([^"']+)["'][^>]*>[^<]*${c}`,"gi"),d=i.matchAll(u);for(let g of d){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 m=new RegExp(`id=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),p=i.match(m);p&&!p[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&s.push({type:"id",value:p[1],priority:"high"})}catch(i){console.warn(`[TraceParser] DOM extraction failed: ${i.message}`)}return s}static extractStructuralContext(e){let t={parent:null,sibling:null},r=e.split(">>").map(i=>i.trim());if(r.length>1){let c=r[r.length-2].replace(/internal:text="[^"]+"\s*/gi,"").replace(/internal:role=\S+\s*/gi,"").replace(/internal:label="[^"]+"\s*/gi,"").trim();c&&(c.match(/^(form|section|nav|header|aside|main|article)\b/)||c.includes("[")||c.match(/[#.]\w/))&&(t.parent=c)}let s=r[r.length-1].match(/([^+~]+)\s*[+~]\s*(.+)/);return s&&(t.sibling=s[1].trim()),t}};var Xt=class{static async step(e,t){let{name:r,action:n,value:s,strategies:i,options:c={timeout:1e4},enrichedData:a}=t;console.log(`[Zibby] \u26A1 Executing step: ${r}`),await this.waitForPageStability(e,c.timeout);let l=await this.findBestMatch(e,i,r);if(!l)throw new Error(`[Zibby] \u274C Failed to find "${r}" using ${i.length} strategies`);a?.position&&await this.verifyPosition(l,a.position),await this.performActionWithRetry(e,l,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(i=>setTimeout(i,500)))}catch{}}static async performActionWithRetry(e,t,r,n,s=3){for(let i=1;i<=s;i++)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(c){if(i===s)throw c;console.log(`[Zibby] \u26A0\uFE0F Action failed (attempt ${i}/${s}), retrying...`),await new Promise(a=>setTimeout(a,1e3*i))}}static async findBestMatch(e,t,r){let s=Date.now(),i=t.map(async(l,u)=>{try{let m=await this.getLocator(e,l).all();return m.length===0?[]:(await Promise.all(m.map(async(g,y)=>{try{if(!await g.isVisible({timeout:100}))return null;let b=await this.scoreCandidate(g,l,e);return{element:g,strategy:l,score:b,strategyIdx:u,elIdx:y}}catch{return null}}))).filter(g=>g!==null)}catch{return[]}}),c=(await Promise.all(i)).flat();if(c.length===0)return console.log(`[Zibby] \u274C No visible candidates found for "${r}"`),null;c.sort((l,u)=>u.score-l.score);let a=c[0];return console.log(`[Zibby] \u2705 Found element using ${a.strategy.type} (score: ${a.score.toFixed(2)}, ${c.length} candidates)`),a.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((a,l)=>a.matches(l),t.parent)&&(n+=30)}catch{}if(t.sibling)try{await e.evaluate((c,a)=>c.parentElement?.querySelector(a)!==null,t.sibling)&&(n+=20)}catch{}try{let i=await e.boundingBox();i&&i.y<1e3&&(n+=10)}catch{}try{let i=await e.evaluate(c=>{let a=0,l=c;for(;l;)l.tagName==="IFRAME"&&a++,l=l.parentElement;return a});n-=i*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 Qt=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}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let c=e.locator(s);if(await c.count()>0)try{await c.click({timeout:2e3});return}catch(a){if(a.message.includes("intercepts pointer")){await c.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}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let c=e.locator(s);if(await c.count()>0){await c.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}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let c=e.locator(s);if(await c.count()>0){await c.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(a){if(a.getAttribute("aria-label"))return a.getAttribute("aria-label").trim();let l=a.getAttribute("aria-labelledby");if(l){let m=document.getElementById(l);if(m)return m.textContent.trim()}if(a.id){let m=document.querySelector(`label[for="${a.id}"]`);if(m)return m.textContent.trim()}let u=a.closest("label");if(u){let m=u.cloneNode(!0);m.querySelectorAll("input, select, textarea").forEach(g=>g.remove());let p=m.textContent.trim();if(p)return p}if(a.placeholder)return a.placeholder;let d=a.tagName.toLowerCase();return d==="button"||d==="a"||a.getAttribute("role")==="button"?(a.textContent||"").trim().slice(0,50):a.title?a.title:d==="input"&&(a.type==="submit"||a.type==="button")&&a.value||""}function r(a){let l=[],u=a.closest("form");if(u)if(u.id)l.push(`form#${u.id}`);else if(u.name)l.push(`form[name=${u.name}]`);else if(u.action)try{let y=new URL(u.action,window.location.origin).pathname;l.push(`form[action=${y}]`)}catch{l.push(`form[action=${u.getAttribute("action")}]`)}else{let y=document.querySelectorAll("form"),h=Array.from(y).indexOf(u);l.push(`form:nth(${h})`)}let d=a.closest('header, nav, main, footer, aside, [role="banner"], [role="navigation"], [role="main"], [role="contentinfo"]');if(d){let y=d.tagName.toLowerCase(),h=d.getAttribute("role");l.push(h||y)}let m=a.closest('section, article, [role="region"]');if(m){let y=m.querySelector("h1, h2, h3, h4, h5, h6");y&&l.push(`section:${y.textContent.trim().slice(0,30)}`)}let p=a.closest("fieldset");if(p){let y=p.querySelector("legend");y&&l.push(`fieldset:${y.textContent.trim()}`)}let g=a.closest('dialog, [role="dialog"], [role="alertdialog"]');if(g){let y=g.querySelector('[role="heading"], h1, h2, h3');y?l.push(`dialog:${y.textContent.trim().slice(0,30)}`):l.push("dialog")}return l.join("/")}function n(a){let l=a.tagName.toLowerCase(),u=a.id||"",d=a.name||"",m=a.type||"",p=a.getAttribute("role")||"",g="";if(a.href)try{g=new URL(a.href,window.location.origin).pathname.slice(0,50)}catch{g=a.getAttribute("href")?.slice(0,50)||""}let y=t(a).slice(0,50).replace(/\s+/g," "),h=r(a),b=[l,u,d,m,p,g,y,h].join("|"),S=5381;for(let x=0;x<b.length;x++)S=(S<<5)+S^b.charCodeAt(x);return`zibby-${(S>>>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(", "),i=new Map,c=0;document.querySelectorAll(s).forEach(a=>{let l=window.getComputedStyle(a);if(l.display==="none"||l.visibility==="hidden")return;let u=n(a),d=u,m=i.get(d)||0;m>0&&(u=`${d}-${m}`),i.set(d,m+1),a.setAttribute("data-zibby-id",u),c++}),console.log(`[Zibby] Injected ${c} stable IDs`)})}catch{}}};var hi=8,yi=1,bi=64;function Si(o){if(!o||typeof o!="object")return 8;let e=o.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 wi,writeFileSync as Sn,existsSync as xi}from"node:fs";import{join as _n}from"node:path";var W=class{constructor(e={}){this.config=e,this.enabled=e.enabled!==!1,this.priority=e.priority||50}getName(){throw new Error("EventEnricher.getName() must be implemented")}canEnrich(e){return this.enabled}async enrich(e,t){throw new Error("EventEnricher.enrich() must be implemented")}handleError(e,t){return console.warn(`[${this.getName()}] Enrichment failed for event ${t.type}:`,e.message),null}};import{existsSync as _i}from"node:fs";import{join as bn}from"node:path";var be=class extends W{constructor(e={}){super(e),this.priority=190,this.traceData=null}getName(){return"TraceText"}getPriority(){return this.priority}async loadTrace(e){if(this.traceData)return;let t=bn(e,"traces"),r=bn(e,"trace.zip");if(_i(r))try{this.traceData=await rt.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 i=s.actualText||this._extractTextFromSelector(s.selector),c=s.actualRole,a=s.actualAriaLabel;return i||c||a?(console.log(`[TraceTextEnricher] \u2705 Event ${n}: text="${i}", role="${c}", label="${a}"`),{traceActualText:i,traceActualRole:c,traceActualAriaLabel:a,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 Ei(o){let e=_n(o,"events.json"),t=_n(o,"events-enriched.json");if(!xi(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(wi(e,"utf-8")),n=new be,s=0,i=0;for(let c of r)try{let a=await n.enrich(c,{sessionPath:o});a&&(c.enrichedData={...c.enrichedData||{},...a},s++)}catch(a){console.log(`[PostProcess] Failed to enrich event ${c.id}: ${a.message}`),i++}return s>0&&(Sn(t,JSON.stringify(r,null,2)),Sn(e,JSON.stringify(r,null,2)),console.log(`[PostProcess] \u2705 Enriched ${s} events (${i} failed)`)),{enriched:s,failed:i}}catch(r){return console.log(`[PostProcess] \u274C Failed to post-process events: ${r.message}`),{enriched:0,failed:0}}}import{spawn as Ti}from"node:child_process";import{existsSync as vi}from"node:fs";import{dirname as Ai,resolve as wn,relative as $i}from"node:path";var vt=new Map,nt=8,xn={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 ${nt} 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:o},e){let r=`${e?.sessionId||"default"}:${o}`,n=(vt.get(r)||0)+1;if(vt.set(r,n),n>nt)return{success:!1,executionCount:n,maxReached:!0,error:`Maximum ${nt} executions reached. Stop retrying and return your best result.`};let s=e?.projectRoot||process.cwd(),i=wn(s,o),c=$i(s,i);return c.startsWith("..")||wn(i)!==i&&c.includes("..")?{success:!1,executionCount:n,error:"Path traversal detected: scriptPath must be within the project root."}:vi(i)?new Promise(a=>{let l=Ai(i),u=Ti("npx",["playwright","test",i,"--reporter=line"],{cwd:s,env:{...process.env,FORCE_COLOR:"0"}}),d="",m="";u.stdout.on("data",g=>{d+=g.toString()}),u.stderr.on("data",g=>{m+=g.toString()});let p=setTimeout(()=>{u.kill("SIGTERM"),a({success:!1,executionCount:n,error:"Test timed out after 60 seconds",stdout:d.slice(-2e3),stderr:m.slice(-1e3)})},6e4);u.on("close",g=>{clearTimeout(p);let h=`${d}
270
270
  ${m}`.split(`
271
271
  `),b="",S=null;for(let x=0;x<h.length;x++){let _=h[x];if(_.includes("Error:")||_.includes("error:")||_.includes("\u2718")){b+=`${_}
272
- `;for(let C=x+1;C<Math.min(x+5,h.length);C++)b+=`${h[C]}
273
- `}if(_.includes("at ")&&_.includes(".spec.")){let C=_.match(/:(\d+):\d+/);C&&(S=parseInt(C[1]))}}a(g===0?{success:!0,executionCount:n,message:"All tests passed!",output:d.slice(-500)}:{success:!1,executionCount:n,remainingAttempts:nt-n,error:b.slice(0,1500)||"Test failed (see output)",failedAtLine:S,stdout:d.slice(-1500),stderr:m.slice(-500),hint:n<nt?"Fix the error and run again.":"Last attempt - make your best fix."})}),u.on("error",g=>{clearTimeout(p),a({success:!1,executionCount:n,error:`Failed to run test: ${g.message}`})})}):{success:!1,executionCount:n,error:`Test file not found: ${i}. Make sure you wrote the file first using the write tool.`}},resetCount(o){for(let e of vt.keys())e.startsWith(`${o}:`)&&vt.delete(e)}};function Oi(o){xn.resetCount(o)}var ie=class{async generate(e){throw new Error("TestGenerationStrategy.generate() must be implemented")}canGenerate(e){throw new Error("TestGenerationStrategy.canGenerate() must be implemented")}getName(){throw new Error("TestGenerationStrategy.getName() must be implemented")}getPriority(){return 0}};import{readFileSync as En,writeFileSync as Ii}from"node:fs";var Re=class extends ie{constructor(){super("mcp-ref","MCP Reference Replay (Exact 1:1)",200)}canGenerate(e){let t=e.eventsPath||`${e.sessionPath}/execute_live/events.json`;try{return JSON.parse(En(t,"utf-8")).some(s=>s.data?.params?.element)?(console.log("[MCPRefStrategy] \u2705 MCP element descriptions available"),!0):(console.log("[MCPRefStrategy] \u274C No MCP element descriptions found in events"),!1)}catch(r){return console.log("[MCPRefStrategy] \u274C Failed to read events:",r.message),!1}}getName(){return"MCP Reference Replay (Exact 1:1)"}getPriority(){return 200}async generate(e){let{testFilePath:t,sessionPath:r,state:n}=e,s=`${r}/execute_live/events.json`,i=n?.title||"Generated Test";console.log("[MCPRefStrategy] \u{1F3AF} Generating test using MCP element descriptions (1:1 replay)"),console.log(`[MCPRefStrategy] events: ${s}`),console.log(`[MCPRefStrategy] output: ${t}`);let a=JSON.parse(En(s,"utf-8")).filter(u=>["navigate","type","fill","click","select_option"].includes(u.type)),l=`import { test, expect } from '@playwright/test';
272
+ `;for(let I=x+1;I<Math.min(x+5,h.length);I++)b+=`${h[I]}
273
+ `}if(_.includes("at ")&&_.includes(".spec.")){let I=_.match(/:(\d+):\d+/);I&&(S=parseInt(I[1]))}}a(g===0?{success:!0,executionCount:n,message:"All tests passed!",output:d.slice(-500)}:{success:!1,executionCount:n,remainingAttempts:nt-n,error:b.slice(0,1500)||"Test failed (see output)",failedAtLine:S,stdout:d.slice(-1500),stderr:m.slice(-500),hint:n<nt?"Fix the error and run again.":"Last attempt - make your best fix."})}),u.on("error",g=>{clearTimeout(p),a({success:!1,executionCount:n,error:`Failed to run test: ${g.message}`})})}):{success:!1,executionCount:n,error:`Test file not found: ${i}. Make sure you wrote the file first using the write tool.`}},resetCount(o){for(let e of vt.keys())e.startsWith(`${o}:`)&&vt.delete(e)}};function Oi(o){xn.resetCount(o)}var ie=class{async generate(e){throw new Error("TestGenerationStrategy.generate() must be implemented")}canGenerate(e){throw new Error("TestGenerationStrategy.canGenerate() must be implemented")}getName(){throw new Error("TestGenerationStrategy.getName() must be implemented")}getPriority(){return 0}};import{readFileSync as En,writeFileSync as Ii}from"node:fs";var Re=class extends ie{constructor(){super("mcp-ref","MCP Reference Replay (Exact 1:1)",200)}canGenerate(e){let t=e.eventsPath||`${e.sessionPath}/execute_live/events.json`;try{return JSON.parse(En(t,"utf-8")).some(s=>s.data?.params?.element)?(console.log("[MCPRefStrategy] \u2705 MCP element descriptions available"),!0):(console.log("[MCPRefStrategy] \u274C No MCP element descriptions found in events"),!1)}catch(r){return console.log("[MCPRefStrategy] \u274C Failed to read events:",r.message),!1}}getName(){return"MCP Reference Replay (Exact 1:1)"}getPriority(){return 200}async generate(e){let{testFilePath:t,sessionPath:r,state:n}=e,s=`${r}/execute_live/events.json`,i=n?.title||"Generated Test";console.log("[MCPRefStrategy] \u{1F3AF} Generating test using MCP element descriptions (1:1 replay)"),console.log(`[MCPRefStrategy] events: ${s}`),console.log(`[MCPRefStrategy] output: ${t}`);let a=JSON.parse(En(s,"utf-8")).filter(u=>["navigate","type","fill","click","select_option"].includes(u.type)),l=`import { test, expect } from '@playwright/test';
274
274
  `;l+=`import { ZibbyRuntime } from '@zibby/core';
275
275
 
276
276
  `,l+=`test('${i}', async ({ page }) => {
277
277
  `,l+=` const timestamp = Date.now();
278
278
 
279
- `;for(let u of a){let d=u.data?.params?.element||"element",m=u.data?.params?.ref,p=u.enrichedData?.traceActualText,g=u.enrichedData?.traceActualRole,y=u.enrichedData?.traceActualAriaLabel,h=u.enrichedData?.actualText,b=p||h,S=g||u.enrichedData?.actualRole,x=b||d,_=b||this._extractName(d),C=S||this._extractRole(d),k=p?" [accessibility-tree]":h?" [live]":" [AI]";if(u.type==="navigate")l+=` await page.goto('${u.data.params.url}');
279
+ `;for(let u of a){let d=u.data?.params?.element||"element",m=u.data?.params?.ref,p=u.enrichedData?.traceActualText,g=u.enrichedData?.traceActualRole,y=u.enrichedData?.traceActualAriaLabel,h=u.enrichedData?.actualText,b=p||h,S=g||u.enrichedData?.actualRole,x=b||d,_=b||this._extractName(d),I=S||this._extractRole(d),k=p?" [accessibility-tree]":h?" [live]":" [AI]";if(u.type==="navigate")l+=` await page.goto('${u.data.params.url}');
280
280
 
281
281
  `;else if(u.type==="click")l+=` // ${d}${b?` (actual: "${b}")${k}`:""}
282
282
  `,l+=` await ZibbyRuntime.step(page, {
283
283
  `,l+=` name: '${this._escapeString(d)}',
284
284
  `,l+=` action: 'click',
285
285
  `,l+=` strategies: [
286
- `,l+=` { type: 'role', role: '${C}', name: '${this._escapeString(_)}' },
286
+ `,l+=` { type: 'role', role: '${I}', name: '${this._escapeString(_)}' },
287
287
  `,l+=` { type: 'text', text: '${this._escapeString(_)}' }
288
288
  `,l+=` ]
289
289
  `,l+=` });
@@ -294,16 +294,16 @@ ${m}`.split(`
294
294
  `,l+=` action: 'fill',
295
295
  `,l+=` value: '${this._escapeString(N)}',
296
296
  `,l+=` strategies: [
297
- `,l+=` { type: 'role', role: '${C}', name: '${this._escapeString(_)}' },
297
+ `,l+=` { type: 'role', role: '${I}', name: '${this._escapeString(_)}' },
298
298
  `,l+=` { type: 'attributes', placeholder: '${this._escapeString(_)}' }
299
299
  `,l+=` ]
300
300
  `,l+=` });
301
301
 
302
- `}else if(u.type==="select_option"){let N=u.data.params.values,I=Array.isArray(N)?N[0]:N;l+=` // ${d}${b?` (actual: "${b}")${k}`:""}
302
+ `}else if(u.type==="select_option"){let N=u.data.params.values,C=Array.isArray(N)?N[0]:N;l+=` // ${d}${b?` (actual: "${b}")${k}`:""}
303
303
  `,l+=` await ZibbyRuntime.step(page, {
304
304
  `,l+=` name: '${this._escapeString(d)}',
305
305
  `,l+=` action: 'select',
306
- `,l+=` value: '${this._escapeString(I)}',
306
+ `,l+=` value: '${this._escapeString(C)}',
307
307
  `,l+=` strategies: [
308
308
  `,l+=` { type: 'role', role: 'combobox', name: '${this._escapeString(_)}' }
309
309
  `,l+=` ]
@@ -336,6 +336,6 @@ ${m}`.split(`
336
336
 
337
337
  This will create .zibby/graph.mjs with your workflow definition.`);await g.initialize(d);let y=!1,h=()=>{if(!y)try{s||process.cwd(),y=!0}catch(b){console.warn("[zibby] run-index interrupt row:",b?.message||b)}};process.on("SIGINT",h),process.on("SIGTERM",h);try{if(e.singleNode){console.log(`
338
338
  \u{1F3AF} Running Single Node: ${e.singleNode} (Framework Mode)
339
- `);let I=g.calculateOutputPath(i||o),M=g.buildGraph(),F={};for(let[U,E]of M.nodes.entries())F[U]=E.config||E;let P={};if(e.sessionId){let U=e.sessionId,E=e.paths?.output||ji;if(U==="last"){let R=Be(s,E,Cn);if(On(R)){let{readdirSync:L,statSync:O}=await import("fs"),G=L(R).filter(A=>O(Be(R,A)).isDirectory()).map(A=>({name:A,time:O(Be(R,A)).mtimeMs})).sort((A,B)=>B.time-A.time);G.length>0?(U=G[0].name,console.log(`\u{1F4C2} Using latest session: ${U}`)):console.log(`\u26A0\uFE0F No sessions found in ${R}`)}}let $=Be(s,E,Cn,U),v=Be($,"execute_live"),w=Be(v,Bi);On(w)?(console.log(`\u{1F4C2} Loading session: ${U}`),P={sessionPath:$,execute_live_output:JSON.parse($n(w,"utf-8"))}):console.log(`\u26A0\uFE0F Session not found: ${$}`)}let D=await g.runSingleNode(e.singleNode,F,{testSpec:u,outputPath:I,cwd:s||process.cwd(),contextConfig:e.contextConfig,specPath:i||o,config:e,...P});return typeof g.onComplete=="function"&&await g.onComplete(D),D}let b;typeof e.onPipelineProgress=="function"?b=e.onPipelineProgress:e.runIndex?.pipelineProgress!==!1&&(b=jr({cwd:s||process.cwd(),config:e}));let S=s||process.cwd(),x=c!=null&&String(c).trim()!==""?(()=>{let I=String(c).trim();try{return Ui(I)?In(I):In(S,I)}catch{return I}})():void 0,_=Ki(),C=x??_;Gi();let k=Fi({cwd:S,config:e,traceFrom:"runTest",initialState:{sessionPath:C,sessionTimestamp:a}}),N;try{N=await g.run(u,{testSpec:u,specPath:i||o,cwd:S,config:e,sessionPath:k.sessionPath,sessionTimestamp:k.sessionTimestamp,...b?{onPipelineProgress:b}:{}})}catch(I){throw typeof I?.message=="string"&&I.message.includes("Interrupted by user")&&(s||process.cwd(),void 0),y||(I?.partialResult,I?.message,void 0),I}return N}finally{process.off("SIGINT",h),process.off("SIGTERM",h),await g.cleanup()}}function zi(o){return o.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function Hi(o,e){if(o[e])return o[e];let t=zi(e);if(o[t])return o[t];let r=`${t}Workflow`;return o[r]?o[r]:null}async function $f(o=process.cwd()){try{let{join:e}=await import("path"),{existsSync:t}=await import("fs"),{pathToFileURL:r}=await import("url"),n=e(o,".zibby/graph.mjs");if(!t(n))return{available:[],default:null,error:"No .zibby/graph.mjs found"};let s=await import(r(n).href),i=Object.keys(s).filter(a=>a!=="default"&&typeof s[a]=="function"&&s[a].prototype instanceof ke),c=s.BrowserTestAutomationAgent?"BrowserTestAutomationAgent":s.CursorAgent?"CursorAgent":s.default?"default":i[0]||null;return{available:i,default:c,error:null}}catch(e){return{available:[],default:null,error:e.message}}}async function Yi(o,e){try{let{join:t}=await import("path"),{existsSync:r}=await import("fs"),{pathToFileURL:n}=await import("url"),s=t(o,".zibby/graph.mjs");if(!r(s))return{agent:null,error:null};let i=await import(n(s).href),c=e.workflow,a;if(c){if(a=Hi(i,c),!a){let u=Object.keys(i).filter(d=>d!=="default"&&typeof i[d]=="function");throw new Error(`Workflow "${c}" not found.
339
+ `);let C=g.calculateOutputPath(i||o),M=g.buildGraph(),F={};for(let[U,E]of M.nodes.entries())F[U]=E.config||E;let P={};if(e.sessionId){let U=e.sessionId,E=e.paths?.output||ji;if(U==="last"){let R=Be(s,E,Cn);if(On(R)){let{readdirSync:L,statSync:O}=await import("fs"),G=L(R).filter(v=>O(Be(R,v)).isDirectory()).map(v=>({name:v,time:O(Be(R,v)).mtimeMs})).sort((v,B)=>B.time-v.time);G.length>0?(U=G[0].name,console.log(`\u{1F4C2} Using latest session: ${U}`)):console.log(`\u26A0\uFE0F No sessions found in ${R}`)}}let A=Be(s,E,Cn,U),$=Be(A,"execute_live"),w=Be($,Bi);On(w)?(console.log(`\u{1F4C2} Loading session: ${U}`),P={sessionPath:A,execute_live_output:JSON.parse($n(w,"utf-8"))}):console.log(`\u26A0\uFE0F Session not found: ${A}`)}let D=await g.runSingleNode(e.singleNode,F,{testSpec:u,outputPath:C,cwd:s||process.cwd(),contextConfig:e.contextConfig,specPath:i||o,config:e,...P});return typeof g.onComplete=="function"&&await g.onComplete(D),D}let b;typeof e.onPipelineProgress=="function"?b=e.onPipelineProgress:e.runIndex?.pipelineProgress!==!1&&(b=jr({cwd:s||process.cwd(),config:e}));let S=s||process.cwd(),x=c!=null&&String(c).trim()!==""?(()=>{let C=String(c).trim();try{return Ui(C)?In(C):In(S,C)}catch{return C}})():void 0,_=Ki(),I=x??_;Gi();let k=Fi({cwd:S,config:e,traceFrom:"runTest",initialState:{sessionPath:I,sessionTimestamp:a}}),N;try{N=await g.run(u,{testSpec:u,specPath:i||o,cwd:S,config:e,sessionPath:k.sessionPath,sessionTimestamp:k.sessionTimestamp,...b?{onPipelineProgress:b}:{}})}catch(C){throw typeof C?.message=="string"&&C.message.includes("Interrupted by user")&&(s||process.cwd(),void 0),y||(C?.partialResult,C?.message,void 0),C}return N}finally{process.off("SIGINT",h),process.off("SIGTERM",h),await g.cleanup()}}function zi(o){return o.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function Hi(o,e){if(o[e])return o[e];let t=zi(e);if(o[t])return o[t];let r=`${t}Workflow`;return o[r]?o[r]:null}async function $f(o=process.cwd()){try{let{join:e}=await import("path"),{existsSync:t}=await import("fs"),{pathToFileURL:r}=await import("url"),n=e(o,".zibby/graph.mjs");if(!t(n))return{available:[],default:null,error:"No .zibby/graph.mjs found"};let s=await import(r(n).href),i=Object.keys(s).filter(a=>a!=="default"&&typeof s[a]=="function"&&s[a].prototype instanceof ke),c=s.BrowserTestAutomationAgent?"BrowserTestAutomationAgent":s.CursorAgent?"CursorAgent":s.default?"default":i[0]||null;return{available:i,default:c,error:null}}catch(e){return{available:[],default:null,error:e.message}}}async function Yi(o,e){try{let{join:t}=await import("path"),{existsSync:r}=await import("fs"),{pathToFileURL:n}=await import("url"),s=t(o,".zibby/graph.mjs");if(!r(s))return{agent:null,error:null};let i=await import(n(s).href),c=e.workflow,a;if(c){if(a=Hi(i,c),!a){let u=Object.keys(i).filter(d=>d!=="default"&&typeof i[d]=="function");throw new Error(`Workflow "${c}" not found.
340
340
  Available workflows: ${u.join(", ")}
341
341
  Supported formats: QuickSmokeWorkflow, QuickSmoke, quick-smoke`)}let l=Object.keys(i).find(u=>i[u]===a);console.log(`\u2713 Using workflow: ${l} (from --workflow ${c})`)}else{if(a=i.BrowserTestAutomationAgent||i.CursorAgent||i.default,!a){let l=Object.keys(i).filter(u=>u!=="default"&&typeof i[u]=="function"&&i[u].prototype instanceof ke);l.length>0&&(a=i[l[0]],console.log(`\u2713 Using workflow: ${l[0]} (auto-detected)`))}if(!a)return{agent:null,error:"Could not find any WorkflowAgent export in local graph.js"};a.name?.includes("auto-detected")||console.log("\u2713 Using local agent from .zibby/graph.mjs")}return{agent:new a(e),error:null}}catch(t){return{agent:null,error:t.message}}}var kn=class{constructor(e={}){this.config=e}async run(e){return Ji(e.spec||e.specPath,{...this.config,...e})}};export{Bn as AGENT_TYPES,qc as ALL_TOOLS,Se as AccessibilityEnricher,ws as AgentStrategy,ye as AssistantStrategy,Os as CHAT_MEMORY_TOOLS,hd as CI_ENV_VARS,at as CLAUDE_MODEL_MAP,lt as CODEX_MODEL_MAP,Fn as CORE_LOG_LEVELS,xs as CORE_TOOLS,fe as ClaudeAgentStrategy,de as CodexAgentStrategy,ue as CursorAgentStrategy,hi as DEFAULT_MAX_CONCURRENT_RUNS,se as DEFAULT_MODELS,ud as DEFAULT_OUTPUT_BASE,je as DOMEnricher,gd as EVENTS_FILE,ae as EnrichmentPipeline,W as EventEnricher,At as GEMINI_MODEL_MAP,Ts as GITHUB_TOOLS,ge as GeminiAgentStrategy,Es as JIRA_TOOLS,X as LOG_LEVELS,sr as LiveEnrichmentRecorder,it as Logger,bi as MAX_MAX_CONCURRENT_RUNS,Re as MCPRefStrategy,$s as MEMORY_TOOLS,yi as MIN_MAX_CONCURRENT_RUNS,we as MODEL_REGISTRY,Ze as McpClientManager,he as OpenAIToolProvider,_e as PageStateEnricher,De as PlaywrightJsonVerificationStrategy,Ue as PositionEnricher,md as RAW_OUTPUT_FILE,dd as RESULT_FILE,gn as RIPPLE_EFFECT_SCRIPT,As as RUNNER_TOOLS,Gt as ResultHandler,pd as SESSIONS_DIR,fd as SESSION_INFO_FILE,zf as SKILLS,Is as SKILL_TOOLS,vs as SLACK_TOOLS,et as SelectorGenerator,Qt as StableIdRuntime,Le as StableIdStrategy,te as StreamingParser,js as TRUSTED_VCS_HOSTS,kn as TestAutomation,ie as TestGenerationStrategy,Zt as TestPostProcessor,Me as TestVerificationStrategy,Oe as ToolCallProvider,rt as TraceParser,ke as WorkflowAgent,Cf as WorkflowGraph,Xt as ZibbyRuntime,Xe as ZibbyUploader,Vr as authedUrl,Ge as buildVendorModelMap,is as checkCursorAgentInstalled,ai as checkCursorAgentPatched,Nf as clearInheritedSessionEnvForFreshRun,Us as clearTokenCache,Zs as cloneRepo,Li as createCustomPipeline,rr as createDefaultPipeline,nr as createMinimalPipeline,en as createUploader,Di as enrichRecordedEvents,fi as generateRippleHelperCode,kf as generateWorkflowSessionId,zr as getAgentStrategy,Zf as getAllSkills,li as getApprovalKeys,as as getCursorAgentInstallInstructions,jn as getPickerModels,Wf as getSkill,Vf as hasSkill,Jt as hostnameOf,pi as injectRippleEffect,_s as invokeAgent,Yr as isTrustedVcsHost,qf as listSkillIds,$f as listWorkflows,f as logger,zs as organizeVideos,ii as patchCursorAgentForCI,V as pickFromPool,Ei as postProcessEvents,Wr as providerForHost,Lf as readPinnedSessionPathFromEnv,qr as redactGitSecrets,Mt as registerBuiltInStrategies,Yf as registerSkill,Oi as resetExecutionCount,Kt as resolveIntegrationToken,Si as resolveMaxParallelRuns,Dn as resolveModelFamily,Pf as resolveWorkflowSession,xn as runPlaywrightTestTool,Ji as runTest,ui as saveApprovalKeys,Bs as scrubRemoteToTokenless,Fs as securePush,Hr as selfHostGitlabHost,fn as sessionSkill,Rf as shouldTrustInheritedSessionEnv,Mf as syncProcessEnvToSession,Pi as testGenerationManager,Ri as testVerificationManager,re as timeline,Zr as tokenlessUrl,ys as workflow,jf as z};