@zibby/core 0.5.29 → 0.5.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- var vn=Object.defineProperty;var An=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var On=(o,e)=>()=>(o&&(e=o(o=0)),e);var $n=(o,e)=>{for(var t in e)vn(o,t,{get:e[t],enumerable:!0})};var hr={};$n(hr,{zodToJson:()=>se});import{z as gr}from"zod";import{zodToJsonSchema as ao}from"zod-to-json-schema";function lo(o){if(!o||typeof o!="object")return o;if(Array.isArray(o.type))return o.type.includes("null")||(o.type=[...o.type,"null"]),o;if(typeof o.type=="string")return o.type=[o.type,"null"],o;for(let e of["anyOf","oneOf"])if(Array.isArray(o[e]))return o[e].some(t=>t&&t.type==="null")||(o[e]=[...o[e],{type:"null"}]),o;return{anyOf:[o,{type:"null"}]}}function be(o){if(!o||typeof o!="object")return o;for(let e of["$defs","definitions"])if(o[e]&&typeof o[e]=="object")for(let t of Object.keys(o[e]))o[e][t]=be(o[e][t]);for(let e of["anyOf","oneOf","allOf"])Array.isArray(o[e])&&(o[e]=o[e].map(be));if(o.properties&&typeof o.properties=="object"){o.additionalProperties=!1;let e=Object.keys(o.properties),t=new Set(Array.isArray(o.required)?o.required:[]);for(let r of e){let n=be(o.properties[r]);t.has(r)||(n=lo(n)),o.properties[r]=n}o.required=e}return o.items&&(Array.isArray(o.items)?o.items=o.items.map(be):o.items=be(o.items)),o}function se(o,e={target:"openApi3"}){if(!o)return null;let t=e?.target==="openAi",r=null;if(typeof gr?.toJSONSchema=="function")try{r=gr.toJSONSchema(o)}catch{}if(!r)try{r=ao(o,e)}catch{return null}if(t&&r)try{return be(r)}catch{return r}return r}var Fe=On(()=>{});import{readFileSync as Sn,existsSync as _n}from"node:fs";import{join as Ne,resolve as wn,isAbsolute as Ci}from"node:path";import{DEFAULT_OUTPUT_BASE as Pi,SESSIONS_DIR as xn,RESULT_FILE as ki,resolveWorkflowSession as Ni,clearInheritedSessionEnvForFreshRun as Ri,readPinnedSessionPathFromEnv as Li}from"@zibby/agent-workflow";import{registerStrategy as He}from"@zibby/agent-workflow";import{AgentStrategy as qn,DEFAULT_OUTPUT_BASE as Qn,SESSION_INFO_FILE as eo,STOP_REQUEST_FILE as to,getAllSkills as ro,getSkill as lr}from"@zibby/agent-workflow";import{spawn as no,execSync as ne}from"node:child_process";import{writeFileSync as cr,readFileSync as ur,mkdirSync as pr,existsSync as je,accessSync as fr,constants as dr,unlinkSync as oo}from"node:fs";import{join as Z,resolve as so}from"node:path";import{homedir as Be}from"node:os";import Me from"chalk";var V={debug:0,info:1,warn:2,error:3,silent:4},rt=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return V.debug;if(process.env.ZIBBY_VERBOSE==="true")return V.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in V?V[e]:V.info}_shouldLog(e){return V[e]>=this._level}_formatMessage(e,t,r={}){let n=new Date().toISOString(),i=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(i+=Me.dim(` ${JSON.stringify(r)}`)),i}_getPrefix(e){return{debug:Me.gray("[DEBUG]"),info:Me.cyan("[INFO]"),warn:Me.yellow("[WARN]"),error:Me.red("\u274C [ERROR]")}[e]||""}debug(e,t){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,t))}info(e,t){this._shouldLog("info")&&console.log(this._formatMessage("info",e,t))}warn(e,t){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,t))}error(e,t){this._shouldLog("error")&&console.error(this._formatMessage("error",e,t))}setLevel(e){e in V&&(this._level=V[e])}getLevel(){return Object.keys(V).find(e=>V[e]===this._level)}},p=new rt;var De=[{alias:"auto",canonicalId:"claude-sonnet-4-6",vendor:"claude",label:"Claude \xB7 Sonnet 4.6",family:"claude-sonnet-4",pickerVisible:!0,isDefault:!0},{alias:"opus-4.8",canonicalId:"claude-opus-4-8",vendor:"claude",label:"Claude \xB7 Opus 4.8",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-8",canonicalId:"claude-opus-4-8",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.8"},{alias:"sonnet-4.8",canonicalId:"claude-sonnet-4-8",vendor:"claude",label:"Claude \xB7 Sonnet 4.8",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-8",canonicalId:"claude-sonnet-4-8",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.8"},{alias:"opus-4.7",canonicalId:"claude-opus-4-7",vendor:"claude",label:"Claude \xB7 Opus 4.7",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-7",canonicalId:"claude-opus-4-7",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.7"},{alias:"sonnet-4.7",canonicalId:"claude-sonnet-4-7",vendor:"claude",label:"Claude \xB7 Sonnet 4.7",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-7",canonicalId:"claude-sonnet-4-7",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.7"},{alias:"sonnet-4.6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"auto"},{alias:"sonnet-4-6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"auto"},{alias:"opus-4.6",canonicalId:"claude-opus-4-6",vendor:"claude",label:"Claude \xB7 Opus 4.6",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-6",canonicalId:"claude-opus-4-6",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.6"},{alias:"sonnet-4.5",canonicalId:"claude-sonnet-4-5-20250929",vendor:"claude",label:"Claude \xB7 Sonnet 4.5",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-5",canonicalId:"claude-sonnet-4-5-20250929",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.5"},{alias:"opus-4.5",canonicalId:"claude-opus-4-5-20251101",vendor:"claude",label:"Claude \xB7 Opus 4.5",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-5",canonicalId:"claude-opus-4-5-20251101",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.5"},{alias:"haiku-4.5",canonicalId:"claude-haiku-4-5-20251001",vendor:"claude",label:"Claude \xB7 Haiku 4.5",family:"claude-haiku-4"},{alias:"haiku-4-5",canonicalId:"claude-haiku-4-5-20251001",vendor:"claude",family:"claude-haiku-4",aliasOf:"haiku-4.5"},{alias:"claude-opus-4-8",canonicalId:"claude-opus-4-8",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.8"},{alias:"claude-sonnet-4-8",canonicalId:"claude-sonnet-4-8",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.8"},{alias:"claude-opus-4-7",canonicalId:"claude-opus-4-7",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.7"},{alias:"claude-sonnet-4-7",canonicalId:"claude-sonnet-4-7",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.7"},{alias:"claude-sonnet-4-6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"auto"},{alias:"claude-opus-4-6",canonicalId:"claude-opus-4-6",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.6"},{alias:"claude-sonnet-4-5-20250929",canonicalId:"claude-sonnet-4-5-20250929",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.5"},{alias:"claude-opus-4-5-20251101",canonicalId:"claude-opus-4-5-20251101",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.5"},{alias:"claude-haiku-4-5-20251001",canonicalId:"claude-haiku-4-5-20251001",vendor:"claude",family:"claude-haiku-4",aliasOf:"haiku-4.5"},{alias:"claude-opus-4-20250514",canonicalId:"claude-opus-4-20250514",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.5"},{alias:"auto",canonicalId:"o4-mini",vendor:"codex",label:"Codex \xB7 o4-mini",family:"o4-mini",isDefault:!0},{alias:"o4-mini",canonicalId:"o4-mini",vendor:"codex",label:"Codex \xB7 o4-mini",family:"o4-mini",pickerVisible:!0},{alias:"o3",canonicalId:"o3",vendor:"codex",family:"o3"},{alias:"o3-mini",canonicalId:"o3-mini",vendor:"codex",family:"o3-mini"},{alias:"codex-mini",canonicalId:"codex-mini-latest",vendor:"codex",family:"codex-mini"},{alias:"gpt-4o",canonicalId:"gpt-4o",vendor:"codex",label:"Codex \xB7 GPT-4o",family:"gpt-4o",pickerVisible:!0},{alias:"gpt-4o-mini",canonicalId:"gpt-4o-mini",vendor:"codex",label:"Codex \xB7 GPT-4o mini",family:"gpt-4o-mini",pickerVisible:!0},{alias:"gpt-5.2-codex",canonicalId:"gpt-5.2-codex",vendor:"codex",label:"Codex \xB7 GPT-5.2",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.2",canonicalId:"gpt-5.2",vendor:"codex",label:"Codex \xB7 GPT-5.2 base",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.3",canonicalId:"gpt-5.3",vendor:"codex",label:"Codex \xB7 GPT-5.3",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.3-codex",canonicalId:"gpt-5.3-codex",vendor:"codex",family:"gpt-5"},{alias:"gpt-5.4",canonicalId:"gpt-5.4",vendor:"codex",label:"Codex \xB7 GPT-5.4",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.5",canonicalId:"gpt-5.5",vendor:"codex",label:"Codex \xB7 GPT-5.5",family:"gpt-5",pickerVisible:!0},{alias:"auto",canonicalId:"gemini-3-pro",vendor:"gemini",label:"Gemini \xB7 3 Pro",family:"gemini-3",isDefault:!0},{alias:"gemini-3-pro",canonicalId:"gemini-3-pro",vendor:"gemini",label:"Gemini \xB7 3 Pro",family:"gemini-3",pickerVisible:!0},{alias:"gemini-3-flash",canonicalId:"gemini-3-flash",vendor:"gemini",label:"Gemini \xB7 3 Flash",family:"gemini-3",pickerVisible:!0},{alias:"gemini-2.5-pro",canonicalId:"gemini-2.5-pro",vendor:"gemini",label:"Gemini \xB7 2.5 Pro",family:"gemini-2.5",pickerVisible:!0},{alias:"gemini-2.5-flash",canonicalId:"gemini-2.5-flash",vendor:"gemini",label:"Gemini \xB7 2.5 Flash",family:"gemini-2.5",pickerVisible:!0}];function Ue(o){let e={};for(let t of De)t.vendor===o&&(e[t.alias]=t.canonicalId);return e}function In(o){if(!o||typeof o!="string")return null;let e=o.toLowerCase();for(let t of De)if(t.alias.toLowerCase()===e)return t.family??null;for(let t of De)if(t.canonicalId.toLowerCase()===e)return t.family??null;return null}function er(o){let e=String(o||"").match(/(\d+(?:\.\d+)?)/);return e?parseFloat(e[1]):0}function tr(o){let e=String(o||"").toLowerCase();return/\b(base|mini)\b/.test(e)?0:/\b(opus|pro)\b/.test(e)?2:1}function Cn(o,e){let t=er(e.label)-er(o.label);if(t!==0)return t;let r=tr(e.label)-tr(o.label);return r!==0?r:o.label.localeCompare(e.label)}function Pn(){let o=[],e=new Map;for(let r of De)r.pickerVisible&&(e.has(r.vendor)||(e.set(r.vendor,[]),o.push(r.vendor)),e.get(r.vendor).push({value:`${r.vendor}:${r.alias}`,label:r.label||`${r.vendor}:${r.alias}`,vendor:r.vendor,alias:r.alias,isDefault:!!r.isDefault}));let t=[];for(let r of o)t.push(...e.get(r).sort(Cn));return t}var z={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-3-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"},kn={ASSISTANT:"assistant",CLAUDE:"claude",CURSOR:"cursor",CODEX:"codex",GEMINI:"gemini"},Nn={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error",SILENT:"silent"},nt=Ue("claude"),ot=Ue("codex"),_t=Ue("gemini"),st={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var X=class o{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(e){if(!e)return null;this.buffer+=e;let t=this.buffer.split(`
1
+ var An=Object.defineProperty;var On=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var $n=(o,e)=>()=>(o&&(e=o(o=0)),e);var In=(o,e)=>{for(var t in e)An(o,t,{get:e[t],enumerable:!0})};var yr={};In(yr,{zodToJson:()=>se});import{z as hr}from"zod";import{zodToJsonSchema as lo}from"zod-to-json-schema";function co(o){if(!o||typeof o!="object")return o;if(Array.isArray(o.type))return o.type.includes("null")||(o.type=[...o.type,"null"]),o;if(typeof o.type=="string")return o.type=[o.type,"null"],o;for(let e of["anyOf","oneOf"])if(Array.isArray(o[e]))return o[e].some(t=>t&&t.type==="null")||(o[e]=[...o[e],{type:"null"}]),o;return{anyOf:[o,{type:"null"}]}}function be(o){if(!o||typeof o!="object")return o;for(let e of["$defs","definitions"])if(o[e]&&typeof o[e]=="object")for(let t of Object.keys(o[e]))o[e][t]=be(o[e][t]);for(let e of["anyOf","oneOf","allOf"])Array.isArray(o[e])&&(o[e]=o[e].map(be));if(o.properties&&typeof o.properties=="object"){o.additionalProperties=!1;let e=Object.keys(o.properties),t=new Set(Array.isArray(o.required)?o.required:[]);for(let r of e){let n=be(o.properties[r]);t.has(r)||(n=co(n)),o.properties[r]=n}o.required=e}return o.items&&(Array.isArray(o.items)?o.items=o.items.map(be):o.items=be(o.items)),o}function se(o,e={target:"openApi3"}){if(!o)return null;let t=e?.target==="openAi",r=null;if(typeof hr?.toJSONSchema=="function")try{r=hr.toJSONSchema(o)}catch{}if(!r)try{r=lo(o,e)}catch{return null}if(t&&r)try{return be(r)}catch{return r}return r}var Be=$n(()=>{});import{readFileSync as _n,existsSync as wn}from"node:fs";import{join as ke,resolve as xn,isAbsolute as Pi}from"node:path";import{DEFAULT_OUTPUT_BASE as ki,SESSIONS_DIR as En,RESULT_FILE as Ni,resolveWorkflowSession as Ri,clearInheritedSessionEnvForFreshRun as Li,readPinnedSessionPathFromEnv as Mi}from"@zibby/agent-workflow";import{registerStrategy as Ye}from"@zibby/agent-workflow";import{AgentStrategy as Qn,DEFAULT_OUTPUT_BASE as eo,SESSION_INFO_FILE as to,STOP_REQUEST_FILE as ro,getAllSkills as no,getSkill as cr}from"@zibby/agent-workflow";import{spawn as oo,execSync as ne}from"node:child_process";import{writeFileSync as ur,readFileSync as pr,mkdirSync as fr,existsSync as Ue,accessSync as dr,constants as mr,unlinkSync as so}from"node:fs";import{join as Z,resolve as io}from"node:path";import{homedir as je}from"node:os";import Le from"chalk";var W={debug:0,info:1,warn:2,error:3,silent:4},tt=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return W.debug;if(process.env.ZIBBY_VERBOSE==="true")return W.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in W?W[e]:W.info}_shouldLog(e){return W[e]>=this._level}_formatMessage(e,t,r={}){let n=new Date().toISOString(),i=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(i+=Le.dim(` ${JSON.stringify(r)}`)),i}_getPrefix(e){return{debug:Le.gray("[DEBUG]"),info:Le.cyan("[INFO]"),warn:Le.yellow("[WARN]"),error:Le.red("\u274C [ERROR]")}[e]||""}debug(e,t){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,t))}info(e,t){this._shouldLog("info")&&console.log(this._formatMessage("info",e,t))}warn(e,t){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,t))}error(e,t){this._shouldLog("error")&&console.error(this._formatMessage("error",e,t))}setLevel(e){e in W&&(this._level=W[e])}getLevel(){return Object.keys(W).find(e=>W[e]===this._level)}},p=new tt;var Me=[{alias:"auto",canonicalId:"claude-sonnet-4-6",vendor:"claude",label:"Claude \xB7 Sonnet 4.6",family:"claude-sonnet-4",pickerVisible:!0,isDefault:!0},{alias:"opus-4.8",canonicalId:"claude-opus-4-8",vendor:"claude",label:"Claude \xB7 Opus 4.8",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-8",canonicalId:"claude-opus-4-8",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.8"},{alias:"sonnet-4.8",canonicalId:"claude-sonnet-4-8",vendor:"claude",label:"Claude \xB7 Sonnet 4.8",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-8",canonicalId:"claude-sonnet-4-8",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.8"},{alias:"opus-4.7",canonicalId:"claude-opus-4-7",vendor:"claude",label:"Claude \xB7 Opus 4.7",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-7",canonicalId:"claude-opus-4-7",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.7"},{alias:"sonnet-4.7",canonicalId:"claude-sonnet-4-7",vendor:"claude",label:"Claude \xB7 Sonnet 4.7",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-7",canonicalId:"claude-sonnet-4-7",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.7"},{alias:"sonnet-4.6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"auto"},{alias:"sonnet-4-6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"auto"},{alias:"opus-4.6",canonicalId:"claude-opus-4-6",vendor:"claude",label:"Claude \xB7 Opus 4.6",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-6",canonicalId:"claude-opus-4-6",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.6"},{alias:"sonnet-4.5",canonicalId:"claude-sonnet-4-5-20250929",vendor:"claude",label:"Claude \xB7 Sonnet 4.5",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-5",canonicalId:"claude-sonnet-4-5-20250929",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.5"},{alias:"opus-4.5",canonicalId:"claude-opus-4-5-20251101",vendor:"claude",label:"Claude \xB7 Opus 4.5",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-5",canonicalId:"claude-opus-4-5-20251101",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.5"},{alias:"haiku-4.5",canonicalId:"claude-haiku-4-5-20251001",vendor:"claude",label:"Claude \xB7 Haiku 4.5",family:"claude-haiku-4"},{alias:"haiku-4-5",canonicalId:"claude-haiku-4-5-20251001",vendor:"claude",family:"claude-haiku-4",aliasOf:"haiku-4.5"},{alias:"claude-opus-4-8",canonicalId:"claude-opus-4-8",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.8"},{alias:"claude-sonnet-4-8",canonicalId:"claude-sonnet-4-8",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.8"},{alias:"claude-opus-4-7",canonicalId:"claude-opus-4-7",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.7"},{alias:"claude-sonnet-4-7",canonicalId:"claude-sonnet-4-7",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.7"},{alias:"claude-sonnet-4-6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"auto"},{alias:"claude-opus-4-6",canonicalId:"claude-opus-4-6",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.6"},{alias:"claude-sonnet-4-5-20250929",canonicalId:"claude-sonnet-4-5-20250929",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.5"},{alias:"claude-opus-4-5-20251101",canonicalId:"claude-opus-4-5-20251101",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.5"},{alias:"claude-haiku-4-5-20251001",canonicalId:"claude-haiku-4-5-20251001",vendor:"claude",family:"claude-haiku-4",aliasOf:"haiku-4.5"},{alias:"claude-opus-4-20250514",canonicalId:"claude-opus-4-20250514",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.5"},{alias:"auto",canonicalId:"o4-mini",vendor:"codex",label:"Codex \xB7 o4-mini",family:"o4-mini",isDefault:!0},{alias:"o4-mini",canonicalId:"o4-mini",vendor:"codex",label:"Codex \xB7 o4-mini",family:"o4-mini",pickerVisible:!0},{alias:"o3",canonicalId:"o3",vendor:"codex",family:"o3"},{alias:"o3-mini",canonicalId:"o3-mini",vendor:"codex",family:"o3-mini"},{alias:"codex-mini",canonicalId:"codex-mini-latest",vendor:"codex",family:"codex-mini"},{alias:"gpt-4o",canonicalId:"gpt-4o",vendor:"codex",label:"Codex \xB7 GPT-4o",family:"gpt-4o",pickerVisible:!0},{alias:"gpt-4o-mini",canonicalId:"gpt-4o-mini",vendor:"codex",label:"Codex \xB7 GPT-4o mini",family:"gpt-4o-mini",pickerVisible:!0},{alias:"gpt-5.2-codex",canonicalId:"gpt-5.2-codex",vendor:"codex",label:"Codex \xB7 GPT-5.2",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.2",canonicalId:"gpt-5.2",vendor:"codex",label:"Codex \xB7 GPT-5.2 base",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.3",canonicalId:"gpt-5.3",vendor:"codex",label:"Codex \xB7 GPT-5.3",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.3-codex",canonicalId:"gpt-5.3-codex",vendor:"codex",family:"gpt-5"},{alias:"gpt-5.4",canonicalId:"gpt-5.4",vendor:"codex",label:"Codex \xB7 GPT-5.4",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.5",canonicalId:"gpt-5.5",vendor:"codex",label:"Codex \xB7 GPT-5.5",family:"gpt-5",pickerVisible:!0},{alias:"auto",canonicalId:"gemini-3-pro",vendor:"gemini",label:"Gemini \xB7 3 Pro",family:"gemini-3",isDefault:!0},{alias:"gemini-3-pro",canonicalId:"gemini-3-pro",vendor:"gemini",label:"Gemini \xB7 3 Pro",family:"gemini-3",pickerVisible:!0},{alias:"gemini-3-flash",canonicalId:"gemini-3-flash",vendor:"gemini",label:"Gemini \xB7 3 Flash",family:"gemini-3",pickerVisible:!0},{alias:"gemini-2.5-pro",canonicalId:"gemini-2.5-pro",vendor:"gemini",label:"Gemini \xB7 2.5 Pro",family:"gemini-2.5",pickerVisible:!0},{alias:"gemini-2.5-flash",canonicalId:"gemini-2.5-flash",vendor:"gemini",label:"Gemini \xB7 2.5 Flash",family:"gemini-2.5",pickerVisible:!0}];function De(o){let e={};for(let t of Me)t.vendor===o&&(e[t.alias]=t.canonicalId);return e}function Cn(o){if(!o||typeof o!="string")return null;let e=o.toLowerCase();for(let t of Me)if(t.alias.toLowerCase()===e)return t.family??null;for(let t of Me)if(t.canonicalId.toLowerCase()===e)return t.family??null;return null}function tr(o){let e=String(o||"").match(/(\d+(?:\.\d+)?)/);return e?parseFloat(e[1]):0}function rr(o){let e=String(o||"").toLowerCase();return/\b(base|mini)\b/.test(e)?0:/\b(opus|pro)\b/.test(e)?2:1}function Pn(o,e){let t=tr(e.label)-tr(o.label);if(t!==0)return t;let r=rr(e.label)-rr(o.label);return r!==0?r:o.label.localeCompare(e.label)}function kn(){let o=[],e=new Map;for(let r of Me)r.pickerVisible&&(e.has(r.vendor)||(e.set(r.vendor,[]),o.push(r.vendor)),e.get(r.vendor).push({value:`${r.vendor}:${r.alias}`,label:r.label||`${r.vendor}:${r.alias}`,vendor:r.vendor,alias:r.alias,isDefault:!!r.isDefault}));let t=[];for(let r of o)t.push(...e.get(r).sort(Pn));return t}var z={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-3-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"},Nn={ASSISTANT:"assistant",CLAUDE:"claude",CURSOR:"cursor",CODEX:"codex",GEMINI:"gemini"},Rn={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error",SILENT:"silent"},rt=De("claude"),nt=De("codex"),St=De("gemini"),ot={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var X=class o{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(e){if(!e)return null;this.buffer+=e;let t=this.buffer.split(`
2
2
  `);this.buffer=t.pop()||"";let r="";for(let n of t)if(n.trim())try{let s=JSON.parse(n);this._emitToolCalls(s);let i=this.extractText(s);if(i){if(this.rawText&&i.startsWith(this.rawText)){let c=i.substring(this.rawText.length);this.rawText=i,r+=c}else(!this.rawText.includes(i)||i.length<20)&&(this.rawText+=i,r+=i);this.tryExtractResult(this.rawText)}else this.isValidResult(s)&&(this.rawText+=`${n}
3
3
  `,r+=`${n}
4
- `,this.extractedResult=s)}catch{if(n.includes('"text"')||n.includes('"content"')){let i=n.match(/"text"\s*:\s*"([^"]*)/),c=n.match(/"content"\s*:\s*"([^"]*)/),a=i?i[1]:c?c[1]:null;a&&!this.rawText.includes(a)&&(r+=a,this.rawText+=a)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(i,c)=>{if(!i)return;let a=`${i}:${JSON.stringify(c??{})}`;this._lastToolEmit!==a&&(this._lastToolEmit=a,this.onToolCall(i,c??void 0))},r=i=>{if(i!=null){if(typeof i=="object"&&!Array.isArray(i))return i;if(typeof i=="string")try{return JSON.parse(i)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,r(e.input??e.arguments));return}let i=e.tool_call;if(i&&typeof i=="object"&&!Array.isArray(i)){let c=Object.keys(i);if(c.length===1){let a=c[0],l=i[a],u=l&&typeof l=="object"?l.args??l.input??l:void 0;t(a,r(u))}return}return}if(Array.isArray(e.tool_calls)){for(let i of e.tool_calls)t(i.name,r(i.input??i.arguments));return}let n=e.message??e;if(Array.isArray(n?.tool_calls)){for(let i of n.tool_calls)t(i.name,r(i.input??i.arguments));return}let s=n?.content??e.content;if(Array.isArray(s))for(let i of s)(i.type==="tool_use"||i.type==="tool_call")&&i.name&&t(i.name,r(i.input??i.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return e.type==="thinking"&&e.text||e.text?e.text:e.content&&typeof e.content=="string"?e.content:e.delta?e.delta:null}tryExtractResult(e){if(!e||typeof e!="string")return;let t=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,n;for(;(n=r.exec(e))!==null;){let d=n[1].trim();try{JSON.parse(d),t.push({text:d,source:"markdown"})}catch{}}let s=0,i=0;for(;s<e.length&&(s=e.indexOf("{",s),s!==-1);){let d=0,m=s;for(let f=s;f<e.length;f++)if(e[f]==="{")d++;else if(e[f]==="}"&&(d--,d===0)){m=f,t.push({text:e.substring(s,m+1),source:"brace"}),i++;break}s=m+1}let c=this.extractedResult,a=c?JSON.stringify(c).length:0,l=0,u=-1;for(let d=0;d<t.length;d++){let m=t[d];try{let f=m.text.replace(/,(\s*[}\]])/g,"$1"),g=JSON.parse(f);this.isValidResult(g)&&(l++,a=JSON.stringify(g).length,c=g,u=d)}catch{}}c&&(this.extractedResult=c)}isValidResult(e){if(!e||typeof e!="object"||Array.isArray(e)||e.session_id||e.timestamp_ms||e.type||e.call_id||e.tool_call||e.result&&typeof e.result=="object"&&(e.result.success&&typeof e.result.success=="object"||e.result.error&&typeof e.result.error=="object")||e.args&&typeof e.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(e),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(e,t=null){let r=new o;r.zodSchema=t,r.processChunk(e),r.flush();let n=r.getResult();return!n&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),n}};import{z as rr}from"zod";import{zodToJsonSchema as Rn}from"zod-to-json-schema";function Ln(o){if(!o)return null;if(typeof rr?.toJSONSchema=="function")try{return rr.toJSONSchema(o)}catch{}try{return Rn(o,{target:"openApi3"})}catch{return null}}var it=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=Ln(e):r=e;let n=this._buildExample(r);return`
4
+ `,this.extractedResult=s)}catch{if(n.includes('"text"')||n.includes('"content"')){let i=n.match(/"text"\s*:\s*"([^"]*)/),c=n.match(/"content"\s*:\s*"([^"]*)/),a=i?i[1]:c?c[1]:null;a&&!this.rawText.includes(a)&&(r+=a,this.rawText+=a)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(i,c)=>{if(!i)return;let a=`${i}:${JSON.stringify(c??{})}`;this._lastToolEmit!==a&&(this._lastToolEmit=a,this.onToolCall(i,c??void 0))},r=i=>{if(i!=null){if(typeof i=="object"&&!Array.isArray(i))return i;if(typeof i=="string")try{return JSON.parse(i)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,r(e.input??e.arguments));return}let i=e.tool_call;if(i&&typeof i=="object"&&!Array.isArray(i)){let c=Object.keys(i);if(c.length===1){let a=c[0],l=i[a],u=l&&typeof l=="object"?l.args??l.input??l:void 0;t(a,r(u))}return}return}if(Array.isArray(e.tool_calls)){for(let i of e.tool_calls)t(i.name,r(i.input??i.arguments));return}let n=e.message??e;if(Array.isArray(n?.tool_calls)){for(let i of n.tool_calls)t(i.name,r(i.input??i.arguments));return}let s=n?.content??e.content;if(Array.isArray(s))for(let i of s)(i.type==="tool_use"||i.type==="tool_call")&&i.name&&t(i.name,r(i.input??i.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return e.type==="thinking"&&e.text||e.text?e.text:e.content&&typeof e.content=="string"?e.content:e.delta?e.delta:null}tryExtractResult(e){if(!e||typeof e!="string")return;let t=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,n;for(;(n=r.exec(e))!==null;){let d=n[1].trim();try{JSON.parse(d),t.push({text:d,source:"markdown"})}catch{}}let s=0,i=0;for(;s<e.length&&(s=e.indexOf("{",s),s!==-1);){let d=0,m=s;for(let f=s;f<e.length;f++)if(e[f]==="{")d++;else if(e[f]==="}"&&(d--,d===0)){m=f,t.push({text:e.substring(s,m+1),source:"brace"}),i++;break}s=m+1}let c=this.extractedResult,a=c?JSON.stringify(c).length:0,l=0,u=-1;for(let d=0;d<t.length;d++){let m=t[d];try{let f=m.text.replace(/,(\s*[}\]])/g,"$1"),g=JSON.parse(f);this.isValidResult(g)&&(l++,a=JSON.stringify(g).length,c=g,u=d)}catch{}}c&&(this.extractedResult=c)}isValidResult(e){if(!e||typeof e!="object"||Array.isArray(e)||e.session_id||e.timestamp_ms||e.type||e.call_id||e.tool_call||e.result&&typeof e.result=="object"&&(e.result.success&&typeof e.result.success=="object"||e.result.error&&typeof e.result.error=="object")||e.args&&typeof e.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(e),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(e,t=null){let r=new o;r.zodSchema=t,r.processChunk(e),r.flush();let n=r.getResult();return!n&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),n}};import{z as nr}from"zod";import{zodToJsonSchema as Ln}from"zod-to-json-schema";function Mn(o){if(!o)return null;if(typeof nr?.toJSONSchema=="function")try{return nr.toJSONSchema(o)}catch{}try{return Ln(o,{target:"openApi3"})}catch{return null}}var st=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=Mn(e):r=e;let n=this._buildExample(r);return`
5
5
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
6
6
  \u{1F6A8} MANDATORY: WRITE RESULT TO FILE \u{1F6A8}
7
7
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
@@ -23,7 +23,7 @@ JSON types (strict \u2014 validators reject wrong types):
23
23
 
24
24
  Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(e){if(!e)return{};let t=e.type;if(t==="object"&&e.properties){let r={};for(let[n,s]of Object.entries(e.properties))r[n]=this._buildExample(s);return r}if(t==="array"&&e.items)return[this._buildExample(e.items)];if(e.enum&&Array.isArray(e.enum)&&e.enum.length>0)return`<${e.enum.join("|")}>`;if(t==="string")return"<string>";if(t==="number"||t==="integer")return 0;if(t==="boolean")return!1;if(e.description)return`<${e.description}>`;if(e.nullable||e.oneOf||e.anyOf){let r=e.oneOf?.find(n=>n.type!=="null")||e.anyOf?.find(n=>n.type!=="null");return r?this._buildExample(r):null}return"<value>"}};var ge=class o{constructor(e=""){this.userPrompt=e,this.systemInstructions=[],this.metadata={}}setUserPrompt(e){return this.userPrompt=e,this}appendUserPrompt(e){return this.userPrompt?this.userPrompt+=`
25
25
 
26
- ${e}`:this.userPrompt=e,this}addSkillHints(e){return e&&this.systemInstructions.push({type:"skill_hints",content:e,position:"prepend"}),this}addStructuredOutput(e,t){if(e&&t){let r=it.generateFileOutputInstructions(e,t);this.systemInstructions.push({type:"structured_output",content:r,position:"append"}),this.metadata.structuredOutputPath=t}return this}addExtraInstructions(e){if(e?.trim()){let t=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
26
+ ${e}`:this.userPrompt=e,this}addSkillHints(e){return e&&this.systemInstructions.push({type:"skill_hints",content:e,position:"prepend"}),this}addStructuredOutput(e,t){if(e&&t){let r=st.generateFileOutputInstructions(e,t);this.systemInstructions.push({type:"structured_output",content:r,position:"append"}),this.metadata.structuredOutputPath=t}return this}addExtraInstructions(e){if(e?.trim()){let t=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
27
27
  \u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
28
28
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
29
29
 
@@ -31,15 +31,15 @@ ${e.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:t,p
31
31
 
32
32
  `),position:"append"}),this}addSystemInstruction(e,t="custom",r="append"){return e&&this.systemInstructions.push({type:t,content:e,position:r}),this}getUserPrompt(){return this.userPrompt}getSystemInstructions(){return this.systemInstructions}getMetadata(){return this.metadata}build(){let e=this.systemInstructions.filter(n=>n.position==="prepend").map(n=>n.content),t=this.systemInstructions.filter(n=>n.position==="append").map(n=>n.content);return[...e,this.userPrompt,...t].filter(Boolean).join(`
33
33
 
34
- `)}getStats(){let e=this.userPrompt.length,t=this.build().length;return{userPromptLength:e,fullPromptLength:t,systemInstructionsLength:t-e,instructionCount:this.systemInstructions.length,instructionTypes:this.systemInstructions.map(r=>r.type)}}clone(){let e=new o(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};import Mn from"axios";import{homedir as Dn}from"node:os";import{join as Un}from"node:path";import{existsSync as jn,readFileSync as Bn}from"node:fs";import{toJSONSchema as Fn}from"zod";function Gn(){if(process.env.OPENAI_PROXY_TOKEN)return p.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return p.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let o=Un(Dn(),".zibby","config.json");if(jn(o)){let e=JSON.parse(Bn(o,"utf-8"));if(e.sessionToken)return p.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(o){p.debug(`[Auth] Could not read zibby login session: ${o.message}`)}return null}function Kn(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function he(o){if(!(typeof o!="object"||o===null)){if(Object.keys(o).length===0){o.type="object",o.additionalProperties=!0;return}if(o.type||(o.properties?o.type="object":o.items&&(o.type="array")),o.type==="object")if(o.properties){for(let[e,t]of Object.entries(o.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(o.properties[e]={type:["object","null"]});o.additionalProperties=!1,o.required=Object.keys(o.properties),Object.values(o.properties).forEach(he)}else"additionalProperties"in o||(o.additionalProperties=!0);o.type==="array"&&o.items&&he(o.items),o.anyOf&&o.anyOf.forEach(he),o.oneOf&&o.oneOf.forEach(he),o.allOf&&o.allOf.forEach(he)}}async function nr(o,e){p.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=Gn();if(!t)throw new Error("Authentication required for structured output processing.\n Local development: Run `zibby login`\n CI/CD: Set ZIBBY_USER_TOKEN environment variable (Personal Access Token from UI settings)");let r=Kn();p.info(`\u{1F517} Using OpenAI proxy: ${r}`);let n=Fn(e),s=n;if(n.$ref&&n.definitions){let u=n.$ref.split("/").pop();s=n.definitions[u]||n,p.debug(`Extracted schema from $ref: ${u}`)}delete s.$schema,he(s);let i=4e5,c=o;o.length>i&&(p.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${o.length} chars) exceeds limit, keeping last ${i} chars`),c=`... [truncated early content] ...
34
+ `)}getStats(){let e=this.userPrompt.length,t=this.build().length;return{userPromptLength:e,fullPromptLength:t,systemInstructionsLength:t-e,instructionCount:this.systemInstructions.length,instructionTypes:this.systemInstructions.map(r=>r.type)}}clone(){let e=new o(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};import Dn from"axios";import{homedir as Un}from"node:os";import{join as jn}from"node:path";import{existsSync as Bn,readFileSync as Fn}from"node:fs";import{toJSONSchema as Gn}from"zod";function Kn(){if(process.env.OPENAI_PROXY_TOKEN)return p.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return p.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let o=jn(Un(),".zibby","config.json");if(Bn(o)){let e=JSON.parse(Fn(o,"utf-8"));if(e.sessionToken)return p.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(o){p.debug(`[Auth] Could not read zibby login session: ${o.message}`)}return null}function Jn(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function he(o){if(!(typeof o!="object"||o===null)){if(Object.keys(o).length===0){o.type="object",o.additionalProperties=!0;return}if(o.type||(o.properties?o.type="object":o.items&&(o.type="array")),o.type==="object")if(o.properties){for(let[e,t]of Object.entries(o.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(o.properties[e]={type:["object","null"]});o.additionalProperties=!1,o.required=Object.keys(o.properties),Object.values(o.properties).forEach(he)}else"additionalProperties"in o||(o.additionalProperties=!0);o.type==="array"&&o.items&&he(o.items),o.anyOf&&o.anyOf.forEach(he),o.oneOf&&o.oneOf.forEach(he),o.allOf&&o.allOf.forEach(he)}}async function or(o,e){p.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=Kn();if(!t)throw new Error("Authentication required for structured output processing.\n Local development: Run `zibby login`\n CI/CD: Set ZIBBY_USER_TOKEN environment variable (Personal Access Token from UI settings)");let r=Jn();p.info(`\u{1F517} Using OpenAI proxy: ${r}`);let n=Gn(e),s=n;if(n.$ref&&n.definitions){let u=n.$ref.split("/").pop();s=n.definitions[u]||n,p.debug(`Extracted schema from $ref: ${u}`)}delete s.$schema,he(s);let i=4e5,c=o;o.length>i&&(p.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${o.length} chars) exceeds limit, keeping last ${i} chars`),c=`... [truncated early content] ...
35
35
  ${o.slice(-i)}`);let a=`Extract and format the following information into structured JSON matching the schema.
36
36
 
37
37
  RAW CONTENT:
38
38
  ${c}
39
39
 
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:z.OPENAI_POSTPROCESSING,messages:[{role:"user",content:a}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:s,strict:!0}}};p.info(`\u{1F4E4} Sending to OpenAI proxy: model=${z.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(s.properties||{}).join(", ")}`),p.debug(` Schema size: ${JSON.stringify(s).length} chars`),p.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 Mn.post(r,l,{headers:u,timeout:st.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!m)throw new Error("OpenAI proxy returned empty response");let f=JSON.parse(m);return p.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:f,raw:o}}catch(u){if(u.response){let d=u.response.status,m=u.response.data;throw p.error(`\u274C OpenAI proxy request failed: ${d}`),p.error(` Status: ${d}`),p.error(` Response: ${JSON.stringify(m,null,2)}`),d===401||d===403?new Error(`Authentication failed for OpenAI proxy.
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:z.OPENAI_POSTPROCESSING,messages:[{role:"user",content:a}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:s,strict:!0}}};p.info(`\u{1F4E4} Sending to OpenAI proxy: model=${z.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(s.properties||{}).join(", ")}`),p.debug(` Schema size: ${JSON.stringify(s).length} chars`),p.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 Dn.post(r,l,{headers:u,timeout:ot.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!m)throw new Error("OpenAI proxy returned empty response");let f=JSON.parse(m);return p.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:f,raw:o}}catch(u){if(u.response){let d=u.response.status,m=u.response.data;throw p.error(`\u274C OpenAI proxy request failed: ${d}`),p.error(` Status: ${d}`),p.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 p.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}function H(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,p.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 q,Timeline as ua,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as pa}from"@zibby/agent-workflow";import{copyFileSync as Jn,existsSync as wt,lstatSync as zn,mkdirSync as or,rmSync as Yn,symlinkSync as Hn,unlinkSync as Wn}from"node:fs";import{join as Q}from"node:path";import{homedir as Vn}from"node:os";import{randomBytes as Zn}from"node:crypto";var Xn=["cli-config.json","config.json","auth.json","argv.json"];function sr(o){return!(!o||typeof o!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function ir(o){let e=Q(o||process.cwd(),".zibby","tmp");or(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${Zn(4).toString("hex")}`,r=Q(e,`cursor-agent-home-${t}`),n=Q(r,".cursor");or(n,{recursive:!0});let s=Vn(),i=Q(s,".cursor");if(wt(i))for(let c of Xn){let a=Q(i,c);if(wt(a))try{Jn(a,Q(n,c))}catch{}}if(process.platform==="darwin"){let c=Q(s,"Library");if(wt(c))try{Hn(c,Q(r,"Library"))}catch{}}return r}function ar(o){if(!(!o||typeof o!="string"))try{let e=Q(o,"Library");try{zn(e).isSymbolicLink()&&Wn(e)}catch{}Yn(o,{recursive:!0,force:!0})}catch{}}var oe=class extends qn{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[Z(Be(),".local","bin","cursor-agent"),Z(Be(),".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("/")){fr(r,dr.X_OK);let n=ne(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(n&&n.length>0)return p.debug(`[Cursor] Found agent at: ${r} (version: ${n.trim().slice(0,50)})`),!0}else{let n=ne(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!n)continue;let s=ne(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return p.debug(`[Cursor] Found '${r}' in PATH at ${n} (version: ${s.trim().slice(0,50)})`),!0}}catch{continue}return p.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=st.CURSOR_AGENT_DEFAULT,config:u={},signal:d=null}=t,m=u?.agent?.strictMode||!1,f=t.model??u?.agent?.cursor?.model??z.CURSOR,g=H("CURSOR_API_KEY");try{p.debug(`[Cursor] Invoking (model: ${f}, timeout: ${l/1e3}s, skills: ${JSON.stringify(i)})`);let h=(this._setupMcpConfig(c,r,u,i,a)||{}).isolatedMcpHome??null,b=[Z(Be(),".local","bin","cursor-agent"),Z(Be(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"],w=null;for(let C of b)try{if(C.startsWith("/"))fr(C,dr.X_OK),ne(`"${C}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!ne(`which ${C}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");ne(`${C} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}w=C,p.debug(`[Agent] Using binary: ${C}`);break}catch(_){p.debug(`[Agent] Binary '${C}' check failed: ${_.message}`);continue}if(!w)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 p.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}function H(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,p.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 q,Timeline as pa,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as fa}from"@zibby/agent-workflow";import{copyFileSync as zn,existsSync as _t,lstatSync as Yn,mkdirSync as sr,rmSync as Hn,symlinkSync as Vn,unlinkSync as Wn}from"node:fs";import{join as Q}from"node:path";import{homedir as Zn}from"node:os";import{randomBytes as Xn}from"node:crypto";var qn=["cli-config.json","config.json","auth.json","argv.json"];function ir(o){return!(!o||typeof o!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function ar(o){let e=Q(o||process.cwd(),".zibby","tmp");sr(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${Xn(4).toString("hex")}`,r=Q(e,`cursor-agent-home-${t}`),n=Q(r,".cursor");sr(n,{recursive:!0});let s=Zn(),i=Q(s,".cursor");if(_t(i))for(let c of qn){let a=Q(i,c);if(_t(a))try{zn(a,Q(n,c))}catch{}}if(process.platform==="darwin"){let c=Q(s,"Library");if(_t(c))try{Vn(c,Q(r,"Library"))}catch{}}return r}function lr(o){if(!(!o||typeof o!="string"))try{let e=Q(o,"Library");try{Yn(e).isSymbolicLink()&&Wn(e)}catch{}Hn(o,{recursive:!0,force:!0})}catch{}}var oe=class extends Qn{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[Z(je(),".local","bin","cursor-agent"),Z(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("/")){dr(r,mr.X_OK);let n=ne(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(n&&n.length>0)return p.debug(`[Cursor] Found agent at: ${r} (version: ${n.trim().slice(0,50)})`),!0}else{let n=ne(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!n)continue;let s=ne(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return p.debug(`[Cursor] Found '${r}' in PATH at ${n} (version: ${s.trim().slice(0,50)})`),!0}}catch{continue}return p.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=ot.CURSOR_AGENT_DEFAULT,config:u={},signal:d=null}=t,m=u?.agent?.strictMode||!1,f=t.model??u?.agent?.cursor?.model??z.CURSOR,g=H("CURSOR_API_KEY");try{p.debug(`[Cursor] Invoking (model: ${f}, timeout: ${l/1e3}s, skills: ${JSON.stringify(i)})`);let h=(this._setupMcpConfig(c,r,u,i,a)||{}).isolatedMcpHome??null,b=[Z(je(),".local","bin","cursor-agent"),Z(je(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"],w=null;for(let C of b)try{if(C.startsWith("/"))dr(C,mr.X_OK),ne(`"${C}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!ne(`which ${C}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");ne(`${C} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}w=C,p.debug(`[Agent] Using binary: ${C}`);break}catch(_){p.debug(`[Agent] Binary '${C}' check failed: ${_.message}`);continue}if(!w)throw new Error(`Cursor Agent CLI not found or not working.
43
43
 
44
44
  Checked paths:
45
45
  ${b.map(C=>` - ${C}`).join(`
@@ -51,20 +51,20 @@ 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 E=new ge(e),S=null;if(s){let C=`zibby-result-${Date.now()}.json`;S=Z(r,".zibby","tmp",C);let _=Z(r,".zibby","tmp");je(_)||pr(_,{recursive:!0}),E.addStructuredOutput(s,S)}let $=process.env.CURSOR_API_KEY,P=$?` | key: ***${$.slice(-4)}`:" | key: not set";console.log(`
54
+ Test with: agent --version`);let E=new ge(e),S=null;if(s){let C=`zibby-result-${Date.now()}.json`;S=Z(r,".zibby","tmp",C);let _=Z(r,".zibby","tmp");Ue(_)||fr(_,{recursive:!0}),E.addStructuredOutput(s,S)}let $=process.env.CURSOR_API_KEY,P=$?` | key: ***${$.slice(-4)}`:" | key: not set";console.log(`
55
55
  \u25C6 Model: ${f||"auto"}${P}
56
56
  `);let k=(await import("chalk")).default,T=E.getUserPrompt();console.log(`
57
57
  ${k.bold("Prompt sent to LLM:")}`),console.log(k.dim("\u2500".repeat(60))),console.log(k.dim(T)),console.log(k.dim("\u2500".repeat(60)));let j=E.build(),B=E.getStats(),v=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",f||"auto"];if(process.env.CURSOR_API_KEY&&v.push("--api-key",process.env.CURSOR_API_KEY),v.push(j),p.debug(`[Agent] User prompt: ${B.userPromptLength} chars, System instructions: ${B.systemInstructionsLength} chars (${B.instructionCount} blocks), Full: ${B.fullPromptLength} chars, model: ${f||"auto"}`),p.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${f||"auto"} (from .zibby.config.js agent.cursor.model)
58
- `)}catch{}let O,I=null;try{let C=c||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);O=await this._spawnWithStreaming(w,v,r,l,null,C,h,d)}catch(C){I=C}let N=O?.stdout||"";if(s){let C=typeof s.parse=="function",_=null,R=!!(S&&je(S));if(S&&p.info(`[Agent] Result file: ${R?"present":"missing"} at ${S}`),R)try{let A=ur(S,"utf-8").trim();_=JSON.parse(A),p.info(`[Agent] Parsed JSON from result file OK (${A.length} chars) \u2192 object ready for validation`),I&&p.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(A){p.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${A.message}`)}else if(I)p.warn(`[Agent] Result file missing at ${S} (agent process error \u2014 may still recover if strictMode repairs)`);else throw p.error(`\u274C [Agent] Result file was never created at ${S}`),new Error(`Agent did not write required result file at ${S}`);if(_&&C)try{let A=s.parse(_);return p.info("\u2705 [Agent] Zod validation passed for structured result file"),m&&p.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:N,structured:A}}catch(A){let x=A.issues?A.issues.map(L=>` - ${L.path.join(".")}: ${L.message}`).join(`
58
+ `)}catch{}let O,I=null;try{let C=c||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);O=await this._spawnWithStreaming(w,v,r,l,null,C,h,d)}catch(C){I=C}let N=O?.stdout||"";if(s){let C=typeof s.parse=="function",_=null,R=!!(S&&Ue(S));if(S&&p.info(`[Agent] Result file: ${R?"present":"missing"} at ${S}`),R)try{let A=pr(S,"utf-8").trim();_=JSON.parse(A),p.info(`[Agent] Parsed JSON from result file OK (${A.length} chars) \u2192 object ready for validation`),I&&p.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(A){p.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${A.message}`)}else if(I)p.warn(`[Agent] Result file missing at ${S} (agent process error \u2014 may still recover if strictMode repairs)`);else throw p.error(`\u274C [Agent] Result file was never created at ${S}`),new Error(`Agent did not write required result file at ${S}`);if(_&&C)try{let A=s.parse(_);return p.info("\u2705 [Agent] Zod validation passed for structured result file"),m&&p.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:N,structured:A}}catch(A){let x=A.issues?A.issues.map(L=>` - ${L.path.join(".")}: ${L.message}`).join(`
59
59
  `):A.message?.slice(0,400);if(p.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
60
60
  ${x}`),p.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
61
61
  ${JSON.stringify(_,null,2).slice(0,500)}`),!m)throw new Error(`Agent output failed schema validation:
62
62
  ${x}
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:A})}else{if(_)return p.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),m&&p.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:N,structured:_};R&&p.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(m&&!I){let A=O.parsedText,x=_?JSON.stringify(_):A;p.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${x.length} chars in)`);try{let L=await nr(x,s);if(C){let M=s.parse(L.structured);return p.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:N,structured:M}}return{raw:N,...L}}catch(L){if(p.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${L.message}`),_)return p.warn("[Agent] Using agent's original result file as fallback"),{raw:N,structured:_}}}if(I)throw I;let D=R?_==null?"file existed but JSON.parse failed \u2014 see WARN log above":C?"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 p.error(`\u274C [Agent] No validated structured output: ${D}`),p.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 ${S}. Enable strictMode for proxy fallback.`)}if(I)throw I;return this._extractFinalResult(N)||O?.parsedText||N}finally{g.dispose()}}_extractFinalResult(e){if(!e)return null;let t=e.split(`
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=Z(Be(),".cursor"),a=Z(c,"mcp.json"),l={};if(je(a))try{l=JSON.parse(ur(a,"utf-8"))}catch{}let u=l.mcpServers||{},d=r?.paths?.output||Qn,m=Z(t||process.cwd(),d,eo),f=Array.isArray(n)?n.map(h=>lr(h)).filter(Boolean):[...ro()].map(([,h])=>h),g=new Set;for(let h of f)typeof h.resolve=="function"&&(g.has(h.serverName)||(g.add(h.serverName),this._ensureSkillConfigured(u,h,e,m,s,i)));if(e){let h=lr("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 p.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let y=`${JSON.stringify({mcpServers:u},null,2)}
67
- `;if(sr(e)){let h=ir(t||process.cwd()),b=Z(h,".cursor","mcp.json");return cr(b,y,"utf8"),p.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${h} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:h}}return je(c)||pr(c,{recursive:!0}),cr(a,y,"utf8"),p.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(f=>f.startsWith("--output-dir=")?`--output-dir=${r}`:f);let d=u?.env||{},m=t.sessionEnvKey?{[t.sessionEnvKey]:n}:{};e[a].env={...e[a].env||{},...d,...m},p.debug(`[MCP] Updated ${a} session \u2192 ${r}`);return}if(a)return;let l=t.resolve({sessionPath:r,nodeName:s,headless:i});l&&(e[c]={...l,...t.sessionEnvKey&&{env:{...l.env||{},[t.sessionEnvKey]:n}}},p.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="",f="",g=Date.now(),y=0,h=!1,b=null,w=!1,E=!1,S=null;if(i)try{S=Z(so(String(i)),to)}catch{S=null}let $=!1,P=()=>{$||($=!0,ar(c))},k={...process.env};c&&(k.HOME=c,process.platform==="win32"&&(k.USERPROFILE=c),p.debug(`[Agent] cursor-agent HOME=${c} (isolated MCP config)`));let T=no(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:k,...a&&{signal:a}});p.debug(`[Agent] PID: ${T.pid}`);let j=null,B=()=>{h||E||(h=!0,b="aborted",p.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),j=setTimeout(()=>{if(!E){p.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{T.kill("SIGKILL")}catch{}}},5e3))};a&&(a.aborted?B():a.addEventListener("abort",B,{once:!0})),T.stdin.on("error",_=>{_.code!=="EPIPE"&&p.warn(`[Agent] stdin error: ${_.message}`)}),T.stdout.on("error",_=>{_.code!=="EPIPE"&&p.warn(`[Agent] stdout error: ${_.message}`)}),T.stderr.on("error",_=>{_.code!=="EPIPE"&&p.warn(`[Agent] stderr error: ${_.message}`)}),s?(T.stdin.write(s,_=>{_&&_.code!=="EPIPE"&&p.warn(`[Agent] Failed to write to stdin: ${_.message}`),T.stdin.end()}),p.debug(`[Agent] Prompt also piped to stdin (${s.length} chars)`)):T.stdin.end();let v=null;S&&(v=setInterval(()=>{if(!(h||E))try{if(je(S)){h=!0,b="aborted";try{oo(S)}catch{}p.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),T.kill("SIGTERM"),setTimeout(()=>{T.killed||T.kill("SIGKILL")},2e3)}}catch{}},600));let O=new Set,I=new Date(d).toISOString().replace(/\.\d+Z$/,""),N=setInterval(()=>{let _=Math.round((Date.now()-d)/1e3),R=Math.round((Date.now()-g)/1e3),D=[];try{let x=Math.ceil(_/60)+1,L=ne(`find "${r}" -type f -mmin -${x} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(L)for(let M of L.split(`
65
+ Enable strictMode in .zibby.config.js for automatic repair.`,{cause:A})}else{if(_)return p.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),m&&p.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:N,structured:_};R&&p.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(m&&!I){let A=O.parsedText,x=_?JSON.stringify(_):A;p.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${x.length} chars in)`);try{let L=await or(x,s);if(C){let M=s.parse(L.structured);return p.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:N,structured:M}}return{raw:N,...L}}catch(L){if(p.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${L.message}`),_)return p.warn("[Agent] Using agent's original result file as fallback"),{raw:N,structured:_}}}if(I)throw I;let D=R?_==null?"file existed but JSON.parse failed \u2014 see WARN log above":C?"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 p.error(`\u274C [Agent] No validated structured output: ${D}`),p.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 ${S}. Enable strictMode for proxy fallback.`)}if(I)throw I;return this._extractFinalResult(N)||O?.parsedText||N}finally{g.dispose()}}_extractFinalResult(e){if(!e)return null;let t=e.split(`
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=Z(je(),".cursor"),a=Z(c,"mcp.json"),l={};if(Ue(a))try{l=JSON.parse(pr(a,"utf-8"))}catch{}let u=l.mcpServers||{},d=r?.paths?.output||eo,m=Z(t||process.cwd(),d,to),f=Array.isArray(n)?n.map(h=>cr(h)).filter(Boolean):[...no()].map(([,h])=>h),g=new Set;for(let h of f)typeof h.resolve=="function"&&(g.has(h.serverName)||(g.add(h.serverName),this._ensureSkillConfigured(u,h,e,m,s,i)));if(e){let h=cr("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 p.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let y=`${JSON.stringify({mcpServers:u},null,2)}
67
+ `;if(ir(e)){let h=ar(t||process.cwd()),b=Z(h,".cursor","mcp.json");return ur(b,y,"utf8"),p.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${h} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:h}}return Ue(c)||fr(c,{recursive:!0}),ur(a,y,"utf8"),p.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(f=>f.startsWith("--output-dir=")?`--output-dir=${r}`:f);let d=u?.env||{},m=t.sessionEnvKey?{[t.sessionEnvKey]:n}:{};e[a].env={...e[a].env||{},...d,...m},p.debug(`[MCP] Updated ${a} session \u2192 ${r}`);return}if(a)return;let l=t.resolve({sessionPath:r,nodeName:s,headless:i});l&&(e[c]={...l,...t.sessionEnvKey&&{env:{...l.env||{},[t.sessionEnvKey]:n}}},p.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="",f="",g=Date.now(),y=0,h=!1,b=null,w=!1,E=!1,S=null;if(i)try{S=Z(io(String(i)),ro)}catch{S=null}let $=!1,P=()=>{$||($=!0,lr(c))},k={...process.env};c&&(k.HOME=c,process.platform==="win32"&&(k.USERPROFILE=c),p.debug(`[Agent] cursor-agent HOME=${c} (isolated MCP config)`));let T=oo(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:k,...a&&{signal:a}});p.debug(`[Agent] PID: ${T.pid}`);let j=null,B=()=>{h||E||(h=!0,b="aborted",p.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),j=setTimeout(()=>{if(!E){p.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{T.kill("SIGKILL")}catch{}}},5e3))};a&&(a.aborted?B():a.addEventListener("abort",B,{once:!0})),T.stdin.on("error",_=>{_.code!=="EPIPE"&&p.warn(`[Agent] stdin error: ${_.message}`)}),T.stdout.on("error",_=>{_.code!=="EPIPE"&&p.warn(`[Agent] stdout error: ${_.message}`)}),T.stderr.on("error",_=>{_.code!=="EPIPE"&&p.warn(`[Agent] stderr error: ${_.message}`)}),s?(T.stdin.write(s,_=>{_&&_.code!=="EPIPE"&&p.warn(`[Agent] Failed to write to stdin: ${_.message}`),T.stdin.end()}),p.debug(`[Agent] Prompt also piped to stdin (${s.length} chars)`)):T.stdin.end();let v=null;S&&(v=setInterval(()=>{if(!(h||E))try{if(Ue(S)){h=!0,b="aborted";try{so(S)}catch{}p.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),T.kill("SIGTERM"),setTimeout(()=>{T.killed||T.kill("SIGKILL")},2e3)}}catch{}},600));let O=new Set,I=new Date(d).toISOString().replace(/\.\d+Z$/,""),N=setInterval(()=>{let _=Math.round((Date.now()-d)/1e3),R=Math.round((Date.now()-g)/1e3),D=[];try{let x=Math.ceil(_/60)+1,L=ne(`find "${r}" -type f -mmin -${x} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(L)for(let M of L.split(`
68
68
  `)){let U=M.replace(`${r}/`,"");O.has(U)||(O.add(U),D.push(U))}}catch{}let A="";D.length>0&&(A=` | \u{1F4C1} new: ${D.map(L=>L.split("/").pop()).join(", ")}`),O.size>0&&(A+=` | \u{1F4E6} total: ${O.size} files`),p.debug(`\u{1F493} [Agent] Running for ${_}s | ${y} lines output${A}`),y===0&&_>=30&&O.size===0&&(_<35&&p.warn(`\u26A0\uFE0F [Agent] No output after ${_}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),_>=60&&(h=!0,b=b||"stall",p.error(`\u274C [Agent] No response after ${_}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),T.kill("SIGTERM"),setTimeout(()=>{T.killed||T.kill("SIGKILL")},3e3)))},3e4),F=setTimeout(()=>{h=!0,b=b||"timeout";let _=Math.round((Date.now()-d)/1e3);p.error(`\u23F1\uFE0F [Agent] Timeout after ${_}s \u2014 killing process (PID: ${T.pid})`),m.trim()&&p.warn(`\u{1F4E4} [Agent] Partial output (${m.length} chars) before timeout:
69
69
  ${m.slice(-2e3)}`),T.kill("SIGTERM"),setTimeout(()=>{T.killed||T.kill("SIGKILL")},5e3)},n),C=new X;C.onToolCall=(_,R)=>{let D=_,A=R;if(_==="mcpToolCall"&&R?.name)D=R.name.replace(/^mcp_+[^_]+_+/,""),D.includes("-")&&D.split("-")[0]===D.split("-")[1]&&(D=D.split("-")[0]),A=R.args??R.input??R;else{if(_==="readToolCall"||_==="editToolCall"||_==="writeToolCall")return;(_.startsWith("mcp__")||_.includes("ToolCall"))&&(D=_.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(D.includes("memory")?q.stepMemory(`Tool: ${D}`):q.stepTool(`Tool: ${D}`),A!=null&&typeof A=="object"&&Object.keys(A).length>0&&!E){let L=JSON.stringify(A),M=L.length>100?`${L.substring(0,100)}...`:L;console.log(` Input: ${M}`)}},T.stdout.on("data",_=>{let R=_.toString();m+=R,g=Date.now(),w||(w=!0);let D=C.processChunk(R);D&&!E&&process.stdout.write(D);let A=R.split(`
70
70
  `).filter(x=>x.trim());y+=A.length}),T.stderr.on("data",_=>{let R=_.toString();f+=R,g=Date.now(),w||(w=!0);let D=R.split(`
@@ -75,32 +75,32 @@ Stderr: ${f.slice(-1e3)}`:""}${m.trim()?`
75
75
  Stdout (last 500 chars): ${m.slice(-500)}`:""}`));return}let A=C.getResult(),x=A?JSON.stringify(A,null,2):C.getRawText()||m||"";l({stdout:m||f||"",parsedText:x})}),T.on("error",_=>{if(P(),clearTimeout(F),clearInterval(N),v&&clearInterval(v),j&&clearTimeout(j),a&&!a.aborted)try{a.removeEventListener("abort",B)}catch{}u(new Error(`Cursor Agent spawn error: ${_.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 co,getSkill as yr,NO_INTEGRATION_TOGGLEABLE_SKILL_IDS as uo}from"@zibby/agent-workflow";import{query as po}from"@anthropic-ai/claude-agent-sdk";import io from"node:process";var mr=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","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 ye(o=io.env){let e={},t=new Set(mr);for(let[r,n]of Object.entries(o))t.has(r)||n!==void 0&&(e[r]=n);return e}Fe();import{writeFileSync as xt,mkdirSync as Et,existsSync as Se,readFileSync as Sr}from"fs";import{homedir as _r}from"os";import{join as W}from"path";import{createRequire as fo}from"module";import G from"process";var br=fo(import.meta.url);function mo(){try{if(G.env.CLAUDE_CODE_EXECUTABLE&&Se(G.env.CLAUDE_CODE_EXECUTABLE))return G.env.CLAUDE_CODE_EXECUTABLE;let o=G.platform,e=G.arch,t=`@anthropic-ai/claude-agent-sdk-${o}-${e}`,r=o==="win32"?"claude.exe":"claude";try{let n=br.resolve(`${t}/package.json`),s=W(n,"..",r);if(Se(s))return s}catch{}try{let n=br.resolve("@anthropic-ai/claude-agent-sdk/package.json"),s=W(n,"..");for(let c of[r,W("vendor",r),W("bin",r)]){let a=W(s,c);if(Se(a))return a}let i=W(s,"..",`claude-agent-sdk-${o}-${e}`,r);if(Se(i))return i}catch{}}catch{}return null}var at=mo();at&&p.debug(`Claude native CLI resolved to baked binary: ${at}`);var ie=class extends co{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!G.env.ANTHROPIC_API_KEY||!!G.env.ANTHROPIC_API_KEY_POOL,r=!!G.env.CLAUDE_CODE_OAUTH_TOKEN||!!G.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,n=!!G.env.ANTHROPIC_AUTH_TOKEN||!!G.env.ANTHROPIC_AUTH_TOKEN_POOL,s=t||r||n;return s||p.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=G.cwd(),schema:s=null,images:i=[],skills:c=null,sessionPath:a=null,nodeName:l=null,timeout:u,config:d={},signal:m=null,sessionId:f,resume:g,forkSession:y,sessionStore:h}=t,b=r;(!b||b==="auto")&&(p.debug(`Model is '${b||"undefined"}', using default: ${z.CLAUDE}`),b=z.CLAUDE);let w=nt[b]||b;nt[b]&&b!==w&&p.debug(`Mapped model: ${b} \u2192 ${w}`);let E=[H("ANTHROPIC_API_KEY"),H("CLAUDE_CODE_OAUTH_TOKEN"),H("ANTHROPIC_AUTH_TOKEN")];try{p.debug(`Invoking Claude Agent SDK with model: ${w}, skills: ${JSON.stringify(c)}`);let S=G.env.CLAUDE_CODE_OAUTH_TOKEN,$=G.env.ANTHROPIC_API_KEY,P=G.env.ANTHROPIC_AUTH_TOKEN;G.env.CLAUDE_CODE_CREDENTIALS_JSON?yo(G.env.CLAUDE_CODE_CREDENTIALS_JSON):S&&ho(S,G.env.__ZIBBY_CLAUDE_PLAN);let k=G.env.__ZIBBY_CLAUDE_PLAN,T=k?k.charAt(0).toUpperCase()+k.slice(1):null,j;S?j=T?`Claude ${T} plan \xB7 ***${S.slice(-4)}`:`Subscription \xB7 ***${S.slice(-4)}`:$?j=`API key \xB7 ***${$.slice(-4)}`:P?j=`Bearer \xB7 ***${P.slice(-4)}`:j="NONE \u2014 request will fail";let B=(await import("chalk")).default;console.log(""),console.log(` ${B.cyan("\u25C6")} ${B.bold(w)}`),console.log(` ${B.dim("Auth: ")}${j}`),console.log(` ${B.dim("Workdir: ")}${n}`),console.log(""),console.log(B.bold("Prompt sent to LLM:")),console.log(B.dim("\u2500".repeat(60))),console.log(B.dim(e)),console.log(B.dim("\u2500".repeat(60)));let{allowedTools:v,mcpServers:O}=this._resolveSkills(c,{sessionPath:a,workspace:n,nodeName:l});try{let I={cwd:n,allowedTools:v,settings:{permissions:{allow:["Bash(*)","Read(*)","Write(*)","Edit(*)","MultiEdit(*)","NotebookEdit(*)","Grep(*)","Glob(*)","WebFetch(*)","WebSearch(*)","Task(*)","TodoWrite(*)","Skill(*)"]}},model:w,env:ye(G.env),...at&&{pathToClaudeCodeExecutable:at},...Object.keys(O).length>0&&{mcpServers:O},...f&&{sessionId:f},...g&&{resume:g},...y&&{forkSession:!0},...h&&{sessionStore:h}};if(s){let L=typeof s.parse=="function"?se(s):s;I.outputFormat={type:"json_schema",schema:L},p.debug("Structured output enforced via SDK outputFormat")}p.debug(`Agent SDK options: ${JSON.stringify({cwd:I.cwd,toolCount:v.length,permissionMode:I.permissionMode,model:I.model,hasOutputFormat:!!I.outputFormat})}`);let N="",F=0,C=[];p.debug("Starting Claude Agent SDK query stream");let _;try{_=po({prompt:e,options:I})}catch(x){throw p.error(`Failed to initialize Claude Agent SDK: ${x.message}`),x}let R=null,D=0,A=3;if(m?.aborted){let x=new Error("Aborted via signal");throw x.name="AbortError",x}try{for await(let x of _){if(m?.aborted){let M=new Error("Aborted via signal");throw M.name="AbortError",M}if(C.push(x),x.type==="system"&&x.subtype==="init"){let M=x.mcp_servers||[];if(M.length>0){let U=M.map(K=>`${K.name}=${K.status}${K.error?` (${String(K.error).slice(0,120)})`:""}`).join(", ");p.info(`[mcp] SDK init \u2014 ${M.length} server(s): ${U}`);for(let K of M)K.status!=="connected"&&p.warn(`[mcp] server '${K.name}' did not connect: status=${K.status}`,{name:K.name,status:K.status,error:K.error})}else Object.keys(O||{}).length>0&&p.warn(`[mcp] SDK init returned no mcp_servers despite passing ${Object.keys(O).length} server(s) \u2014 SDK version may not expose this field, or config was dropped`);if(Array.isArray(x.tools)){let U=x.tools.filter(K=>K.startsWith("mcp__"));U.length>0?p.info(`[mcp] tools visible to model: ${U.join(", ")}`):Object.keys(O||{}).length>0&&p.warn("[mcp] no mcp__* tools in model's tool list \u2014 MCP servers configured but tools didn't reach the prompt")}}if(x.type==="error"||x.error){let M=x.error?.message||x.error||x.message||"Unknown API error";try{p.error("SDK error event raw payload",{fullMessage:JSON.stringify(x,null,2)})}catch{}throw new Error(typeof M=="string"?M:JSON.stringify(M))}let L=JSON.stringify(x.message?.content||x.text||"").slice(0,200);if(L===R){if(D++,D>=A){let M=(x.message?.content?.[0]?.text||x.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${D}x repeated): ${M}`)}}else R=L,D=1;if(x.type==="assistant"||x.constructor?.name==="AssistantMessage"){let M=x.message?.content||x.content||[];for(let U of M)if(U.type==="thinking"&&U.thinking)console.log(`${U.thinking.substring(0,200)}${U.thinking.length>200?"...":""}`);else if(U.type==="text"&&U.text)N+=U.text,U.text.length<500?console.log(`${U.text}`):console.log(`${U.text.substring(0,200)}... (${U.text.length} chars)`);else if(U.type==="tool_use"){F++,U.name.includes("memory")?q.stepMemory(`Tool: ${U.name}`):q.stepTool(`Tool: ${U.name}`);let Re=JSON.stringify(U.input).substring(0,100);console.log(` Input: ${Re}${JSON.stringify(U.input).length>100?"...":""}`)}}else if(!(x.type==="user"&&x.tool_use_result)){if(x.type==="result"||x.constructor?.name==="ResultMessage"){let M=x.result||x.text||x.content||N;try{go({message:x,sessionPath:a,nodeName:l,model:b,toolCallCount:F})}catch(U){p.debug(`usage.json write failed: ${U.message}`)}if(s){if(x.structured_output){p.debug("Using SDK native structured_output");let K=typeof s.parse=="function"?s.parse(x.structured_output):x.structured_output;return{raw:M,structured:K}}if(M){let U=this._extractJson(M,s);if(U)return{raw:M,structured:U}}p.warn(`Could not extract structured output \u2014 returning raw text (${(M||"").length} chars)`)}return M||""}}}if(p.warn(`Agent SDK ended without result. Collected ${C.length} messages`),N.length>0)return p.debug("Returning accumulated text from messages"),N;throw new Error("Claude Agent SDK query ended without result")}catch(x){let L={message:x?.message,name:x?.name,code:x?.code,cause:x?.cause?.message||x?.cause,stack:x?.stack?.split(`
78
+ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};import{AgentStrategy as uo,getSkill as br,NO_INTEGRATION_TOGGLEABLE_SKILL_IDS as po}from"@zibby/agent-workflow";import{query as fo}from"@anthropic-ai/claude-agent-sdk";import ao from"node:process";var gr=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","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 ye(o=ao.env){let e={},t=new Set(gr);for(let[r,n]of Object.entries(o))t.has(r)||n!==void 0&&(e[r]=n);return e}Be();import{writeFileSync as wt,mkdirSync as xt,existsSync as Se,readFileSync as _r}from"fs";import{homedir as wr}from"os";import{join as V}from"path";import{createRequire as mo}from"module";import G from"process";var Sr=mo(import.meta.url);function go(){try{if(G.env.CLAUDE_CODE_EXECUTABLE&&Se(G.env.CLAUDE_CODE_EXECUTABLE))return G.env.CLAUDE_CODE_EXECUTABLE;let o=G.platform,e=G.arch,t=`@anthropic-ai/claude-agent-sdk-${o}-${e}`,r=o==="win32"?"claude.exe":"claude";try{let n=Sr.resolve(`${t}/package.json`),s=V(n,"..",r);if(Se(s))return s}catch{}try{let n=Sr.resolve("@anthropic-ai/claude-agent-sdk/package.json"),s=V(n,"..");for(let c of[r,V("vendor",r),V("bin",r)]){let a=V(s,c);if(Se(a))return a}let i=V(s,"..",`claude-agent-sdk-${o}-${e}`,r);if(Se(i))return i}catch{}}catch{}return null}var it=go();it&&p.debug(`Claude native CLI resolved to baked binary: ${it}`);var ie=class extends uo{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!G.env.ANTHROPIC_API_KEY||!!G.env.ANTHROPIC_API_KEY_POOL,r=!!G.env.CLAUDE_CODE_OAUTH_TOKEN||!!G.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,n=!!G.env.ANTHROPIC_AUTH_TOKEN||!!G.env.ANTHROPIC_AUTH_TOKEN_POOL,s=t||r||n;return s||p.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=G.cwd(),schema:s=null,images:i=[],skills:c=null,sessionPath:a=null,nodeName:l=null,timeout:u,config:d={},signal:m=null,sessionId:f,resume:g,forkSession:y,sessionStore:h}=t,b=r;(!b||b==="auto")&&(p.debug(`Model is '${b||"undefined"}', using default: ${z.CLAUDE}`),b=z.CLAUDE);let w=rt[b]||b;rt[b]&&b!==w&&p.debug(`Mapped model: ${b} \u2192 ${w}`);let E=[H("ANTHROPIC_API_KEY"),H("CLAUDE_CODE_OAUTH_TOKEN"),H("ANTHROPIC_AUTH_TOKEN")];try{p.debug(`Invoking Claude Agent SDK with model: ${w}, skills: ${JSON.stringify(c)}`);let S=G.env.CLAUDE_CODE_OAUTH_TOKEN,$=G.env.ANTHROPIC_API_KEY,P=G.env.ANTHROPIC_AUTH_TOKEN;G.env.CLAUDE_CODE_CREDENTIALS_JSON?bo(G.env.CLAUDE_CODE_CREDENTIALS_JSON):S&&yo(S,G.env.__ZIBBY_CLAUDE_PLAN);let k=G.env.__ZIBBY_CLAUDE_PLAN,T=k?k.charAt(0).toUpperCase()+k.slice(1):null,j;S?j=T?`Claude ${T} plan \xB7 ***${S.slice(-4)}`:`Subscription \xB7 ***${S.slice(-4)}`:$?j=`API key \xB7 ***${$.slice(-4)}`:P?j=`Bearer \xB7 ***${P.slice(-4)}`:j="NONE \u2014 request will fail";let B=(await import("chalk")).default;console.log(""),console.log(` ${B.cyan("\u25C6")} ${B.bold(w)}`),console.log(` ${B.dim("Auth: ")}${j}`),console.log(` ${B.dim("Workdir: ")}${n}`),console.log(""),console.log(B.bold("Prompt sent to LLM:")),console.log(B.dim("\u2500".repeat(60))),console.log(B.dim(e)),console.log(B.dim("\u2500".repeat(60)));let{allowedTools:v,mcpServers:O}=this._resolveSkills(c,{sessionPath:a,workspace:n,nodeName:l});try{let I={cwd:n,allowedTools:v,settings:{permissions:{allow:["Bash(*)","Read(*)","Write(*)","Edit(*)","MultiEdit(*)","NotebookEdit(*)","Grep(*)","Glob(*)","WebFetch(*)","WebSearch(*)","Task(*)","TodoWrite(*)","Skill(*)"]}},model:w,env:ye(G.env),...it&&{pathToClaudeCodeExecutable:it},...Object.keys(O).length>0&&{mcpServers:O},...f&&{sessionId:f},...g&&{resume:g},...y&&{forkSession:!0},...h&&{sessionStore:h}};if(s){let L=typeof s.parse=="function"?se(s):s;I.outputFormat={type:"json_schema",schema:L},p.debug("Structured output enforced via SDK outputFormat")}p.debug(`Agent SDK options: ${JSON.stringify({cwd:I.cwd,toolCount:v.length,permissionMode:I.permissionMode,model:I.model,hasOutputFormat:!!I.outputFormat})}`);let N="",F=0,C=[];p.debug("Starting Claude Agent SDK query stream");let _;try{_=fo({prompt:e,options:I})}catch(x){throw p.error(`Failed to initialize Claude Agent SDK: ${x.message}`),x}let R=null,D=0,A=3;if(m?.aborted){let x=new Error("Aborted via signal");throw x.name="AbortError",x}try{for await(let x of _){if(m?.aborted){let M=new Error("Aborted via signal");throw M.name="AbortError",M}if(C.push(x),x.type==="system"&&x.subtype==="init"){let M=x.mcp_servers||[];if(M.length>0){let U=M.map(K=>`${K.name}=${K.status}${K.error?` (${String(K.error).slice(0,120)})`:""}`).join(", ");p.info(`[mcp] SDK init \u2014 ${M.length} server(s): ${U}`);for(let K of M)K.status!=="connected"&&p.warn(`[mcp] server '${K.name}' did not connect: status=${K.status}`,{name:K.name,status:K.status,error:K.error})}else Object.keys(O||{}).length>0&&p.warn(`[mcp] SDK init returned no mcp_servers despite passing ${Object.keys(O).length} server(s) \u2014 SDK version may not expose this field, or config was dropped`);if(Array.isArray(x.tools)){let U=x.tools.filter(K=>K.startsWith("mcp__"));U.length>0?p.info(`[mcp] tools visible to model: ${U.join(", ")}`):Object.keys(O||{}).length>0&&p.warn("[mcp] no mcp__* tools in model's tool list \u2014 MCP servers configured but tools didn't reach the prompt")}}if(x.type==="error"||x.error){let M=x.error?.message||x.error||x.message||"Unknown API error";try{p.error("SDK error event raw payload",{fullMessage:JSON.stringify(x,null,2)})}catch{}throw new Error(typeof M=="string"?M:JSON.stringify(M))}let L=JSON.stringify(x.message?.content||x.text||"").slice(0,200);if(L===R){if(D++,D>=A){let M=(x.message?.content?.[0]?.text||x.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${D}x repeated): ${M}`)}}else R=L,D=1;if(x.type==="assistant"||x.constructor?.name==="AssistantMessage"){let M=x.message?.content||x.content||[];for(let U of M)if(U.type==="thinking"&&U.thinking)console.log(`${U.thinking.substring(0,200)}${U.thinking.length>200?"...":""}`);else if(U.type==="text"&&U.text)N+=U.text,U.text.length<500?console.log(`${U.text}`):console.log(`${U.text.substring(0,200)}... (${U.text.length} chars)`);else if(U.type==="tool_use"){F++,U.name.includes("memory")?q.stepMemory(`Tool: ${U.name}`):q.stepTool(`Tool: ${U.name}`);let Ne=JSON.stringify(U.input).substring(0,100);console.log(` Input: ${Ne}${JSON.stringify(U.input).length>100?"...":""}`)}}else if(!(x.type==="user"&&x.tool_use_result)){if(x.type==="result"||x.constructor?.name==="ResultMessage"){let M=x.result||x.text||x.content||N;try{ho({message:x,sessionPath:a,nodeName:l,model:b,toolCallCount:F})}catch(U){p.debug(`usage.json write failed: ${U.message}`)}if(s){if(x.structured_output){p.debug("Using SDK native structured_output");let K=typeof s.parse=="function"?s.parse(x.structured_output):x.structured_output;return{raw:M,structured:K}}if(M){let U=this._extractJson(M,s);if(U)return{raw:M,structured:U}}p.warn(`Could not extract structured output \u2014 returning raw text (${(M||"").length} chars)`)}return M||""}}}if(p.warn(`Agent SDK ended without result. Collected ${C.length} messages`),N.length>0)return p.debug("Returning accumulated text from messages"),N;throw new Error("Claude Agent SDK query ended without result")}catch(x){let L={message:x?.message,name:x?.name,code:x?.code,cause:x?.cause?.message||x?.cause,stack:x?.stack?.split(`
79
79
  `).slice(0,5).join(`
80
- `),stringified:(()=>{try{return JSON.stringify(x,Object.getOwnPropertyNames(Object(x)))}catch{return String(x)}})()};throw p.error(`Error during query stream: ${x?.message||x}`,L),x}}catch(I){throw p.error("Claude Agent SDK call failed",{message:I?.message,name:I?.name,code:I?.code,cause:I?.cause?.message||I?.cause}),I}}finally{for(let S of E)S.dispose()}}_resolveSkills(e,t){let r=["Read","Write","Edit","Bash","Grep","Glob"];if(e===null)return p.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return p.debug("Default IDE skills for code generation"),{allowedTools:[...r],mcpServers:{}};let n=[...r],s={},i=G.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=yr(u);return d?.meta?.toggleable===!0?!0:d?.meta?.toggleable===void 0&&uo.includes(u)},l=u=>c!==null&&c.size>0&&a(u)&&!c.has(u);for(let u of e){if(l(u)){p.debug(`Skill "${u}" disabled by enabledIntegrations allowlist \u2014 skipping`);continue}let d=yr(u);if(!d){p.warn(`Unknown skill "${u}" \u2014 skipping`);continue}if(d.allowedTools&&n.push(...d.allowedTools),typeof d.resolve=="function"){let m=d.resolve(t);m&&(s[d.serverName]=m,p.debug(`MCP: ${d.serverName} \u2192 ${m.command} ${m.args[0]}`))}}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 go({message:o,sessionPath:e,nodeName:t,model:r,toolCallCount:n}){if(!e||!t)return;let s=o?.usage||o?.message?.usage||{},i=Ge(s.input_tokens,s.inputTokens),c=Ge(s.output_tokens,s.outputTokens),a=Ge(s.cache_read_input_tokens,s.cacheReadInputTokens),l=Ge(s.cache_creation_input_tokens,s.cacheCreationInputTokens),u=Ge(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=W(e,t);try{Et(m,{recursive:!0})}catch{}xt(W(m,"usage.json"),JSON.stringify(d,null,2),"utf-8")}function Ge(...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 ho(o,e){let t=W(_r(),".claude"),r=W(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(Se(r)&&JSON.parse(Sr(r,"utf-8"))?.claudeAiOauth?.accessToken===o)return;Et(t,{recursive:!0}),xt(r,JSON.stringify(n,null,2),"utf-8"),p.debug(`Wrote Claude Code OAuth credentials to ${r}`)}catch(s){p.warn(`Could not write ${r}: ${s.message} \u2014 Claude SDK may fail to authenticate.`)}}function yo(o){let e=W(_r(),".claude"),t=W(e,".credentials.json"),r;try{r=JSON.parse(o)}catch(n){p.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${n.message}`);return}if(!r?.claudeAiOauth?.accessToken){p.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if(Se(t)){let n=JSON.parse(Sr(t,"utf-8"));if(n?.claudeAiOauth?.accessToken===r.claudeAiOauth.accessToken&&n?.claudeAiOauth?.expiresAt===r.claudeAiOauth.expiresAt)return}Et(e,{recursive:!0}),xt(t,JSON.stringify(r,null,2),"utf-8"),p.debug(`Wrote full Claude Code credentials blob to ${t}`)}catch(n){p.warn(`Could not write ${t}: ${n.message} \u2014 Claude SDK may fail to authenticate.`)}}import{AgentStrategy as bo,getSkill as So}from"@zibby/agent-workflow";Fe();import{execSync as Ke}from"node:child_process";import{readFileSync as _o,mkdirSync as Tt,cpSync as wo,existsSync as xo}from"node:fs";import{join as Je}from"node:path";import{homedir as Eo}from"node:os";function vt(o){if(Array.isArray(o))return o.map(vt);if(o&&typeof o=="object"){let e={};for(let[t,r]of Object.entries(o))r!==null&&(e[t]=vt(r));return e}return o}var ae=class extends bo{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 p.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return Ke("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return p.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,skills:i=null,plugins:c=null,sessionPath:a=null,nodeName:l=null,timeout:u,config:d={},signal:m=null}=t,f=[H("OPENAI_API_KEY"),H("CODEX_API_KEY")];try{let{Codex:g}=await import("@openai/codex-sdk"),y=r;(!y||y==="auto")&&(p.debug(`Model is '${y||"undefined"}', using default: ${z.CODEX}`),y=z.CODEX);let h=ot[y]||y;ot[y]&&y!==h&&p.debug(`Mapped model: ${y} \u2192 ${h}`),p.debug(`Invoking Codex SDK with model: ${h}, skills: ${JSON.stringify(i)}`);let b=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;b&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=b);let w=b?` | key: ***${b.slice(-4)}`:" | key: not set";if(console.log(`
80
+ `),stringified:(()=>{try{return JSON.stringify(x,Object.getOwnPropertyNames(Object(x)))}catch{return String(x)}})()};throw p.error(`Error during query stream: ${x?.message||x}`,L),x}}catch(I){throw p.error("Claude Agent SDK call failed",{message:I?.message,name:I?.name,code:I?.code,cause:I?.cause?.message||I?.cause}),I}}finally{for(let S of E)S.dispose()}}_resolveSkills(e,t){let r=["Read","Write","Edit","Bash","Grep","Glob"];if(e===null)return p.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return p.debug("Default IDE skills for code generation"),{allowedTools:[...r],mcpServers:{}};let n=[...r],s={},i=G.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=br(u);return d?.meta?.toggleable===!0?!0:d?.meta?.toggleable===void 0&&po.includes(u)},l=u=>c!==null&&c.size>0&&a(u)&&!c.has(u);for(let u of e){if(l(u)){p.debug(`Skill "${u}" disabled by enabledIntegrations allowlist \u2014 skipping`);continue}let d=br(u);if(!d){p.warn(`Unknown skill "${u}" \u2014 skipping`);continue}if(d.allowedTools&&n.push(...d.allowedTools),typeof d.resolve=="function"){let m=d.resolve(t);m&&(s[d.serverName]=m,p.debug(`MCP: ${d.serverName} \u2192 ${m.command} ${m.args[0]}`))}}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 ho({message:o,sessionPath:e,nodeName:t,model:r,toolCallCount:n}){if(!e||!t)return;let s=o?.usage||o?.message?.usage||{},i=Fe(s.input_tokens,s.inputTokens),c=Fe(s.output_tokens,s.outputTokens),a=Fe(s.cache_read_input_tokens,s.cacheReadInputTokens),l=Fe(s.cache_creation_input_tokens,s.cacheCreationInputTokens),u=Fe(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=V(e,t);try{xt(m,{recursive:!0})}catch{}wt(V(m,"usage.json"),JSON.stringify(d,null,2),"utf-8")}function Fe(...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 yo(o,e){let t=V(wr(),".claude"),r=V(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(Se(r)&&JSON.parse(_r(r,"utf-8"))?.claudeAiOauth?.accessToken===o)return;xt(t,{recursive:!0}),wt(r,JSON.stringify(n,null,2),"utf-8"),p.debug(`Wrote Claude Code OAuth credentials to ${r}`)}catch(s){p.warn(`Could not write ${r}: ${s.message} \u2014 Claude SDK may fail to authenticate.`)}}function bo(o){let e=V(wr(),".claude"),t=V(e,".credentials.json"),r;try{r=JSON.parse(o)}catch(n){p.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${n.message}`);return}if(!r?.claudeAiOauth?.accessToken){p.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if(Se(t)){let n=JSON.parse(_r(t,"utf-8"));if(n?.claudeAiOauth?.accessToken===r.claudeAiOauth.accessToken&&n?.claudeAiOauth?.expiresAt===r.claudeAiOauth.expiresAt)return}xt(e,{recursive:!0}),wt(t,JSON.stringify(r,null,2),"utf-8"),p.debug(`Wrote full Claude Code credentials blob to ${t}`)}catch(n){p.warn(`Could not write ${t}: ${n.message} \u2014 Claude SDK may fail to authenticate.`)}}import{AgentStrategy as So,getSkill as _o}from"@zibby/agent-workflow";Be();import{execSync as Ge}from"node:child_process";import{readFileSync as wo,mkdirSync as Et,cpSync as xo,existsSync as Eo}from"node:fs";import{join as Ke}from"node:path";import{homedir as To}from"node:os";function Tt(o){if(Array.isArray(o))return o.map(Tt);if(o&&typeof o=="object"){let e={};for(let[t,r]of Object.entries(o))r!==null&&(e[t]=Tt(r));return e}return o}var ae=class extends So{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 p.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return Ge("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return p.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,skills:i=null,plugins:c=null,sessionPath:a=null,nodeName:l=null,timeout:u,config:d={},signal:m=null}=t,f=[H("OPENAI_API_KEY"),H("CODEX_API_KEY")];try{let{Codex:g}=await import("@openai/codex-sdk"),y=r;(!y||y==="auto")&&(p.debug(`Model is '${y||"undefined"}', using default: ${z.CODEX}`),y=z.CODEX);let h=nt[y]||y;nt[y]&&y!==h&&p.debug(`Mapped model: ${y} \u2192 ${h}`),p.debug(`Invoking Codex SDK with model: ${h}, skills: ${JSON.stringify(i)}`);let b=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;b&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=b);let w=b?` | key: ***${b.slice(-4)}`:" | key: not set";if(console.log(`
81
81
  \u25C6 Model: ${h}${w}
82
- `),Array.isArray(c)&&c.length>0){let O=this._resolveCodexHome(a);process.env.CODEX_HOME=O;try{Tt(O,{recursive:!0})}catch{}this._ensurePlugins(c,O)}let E=(await import("chalk")).default;console.log(`
83
- ${E.bold("Prompt sent to LLM:")}`),console.log(E.dim("\u2500".repeat(60))),console.log(E.dim(e)),console.log(E.dim("\u2500".repeat(60)));let S=this._resolveSkillsToMcp(i,{sessionPath:a,workspace:n,nodeName:l}),$={};Object.keys(S).length>0&&($.mcp_servers=S,p.debug(`[Codex] MCP servers: ${Object.keys(S).join(", ")}`));let P=this._resolveCodexBin(),k=new g({...P?{codexPathOverride:P}:{},...Object.keys($).length>0&&{config:$},env:ye(process.env)}),T=n;try{T&&Tt(T,{recursive:!0})}catch{}(!T||!xo(T))&&(T=process.cwd());let j=k.startThread({workingDirectory:T,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),B=s&&typeof s.parse=="function",v={};if(s)try{let O=B?se(s,{target:"openAi"}):s;v.outputSchema=O,p.debug("Structured output via SDK outputSchema")}catch(O){p.warn(`[Codex] Schema conversion failed, will extract from text: ${O.message}`)}if(m?.aborted){let O=new Error("Aborted via signal");throw O.name="AbortError",O}try{let{events:O}=await j.runStreamed(e,v),I=0,N="";for await(let F of O){if(m?.aborted){let _=new Error("Aborted via signal");throw _.name="AbortError",_}let C=F.type;if(C==="item.completed"){let _=F.item,R=_?.type;if(R==="mcp_tool_call"){I++;let D=`${_.server}/${_.tool}`;if(q.stepTool(`Tool: ${D}`),_.arguments){let A=JSON.stringify(_.arguments),x=A.length>100?`${A.substring(0,100)}...`:A;console.log(` Input: ${x}`)}}else if(R==="tool_call"||R==="function_call"||R==="command_execution"){I++;let D=_.name||_.tool||_.command||"unknown";q.stepTool(`Tool: ${D}`)}else R==="agent_message"&&(N=_.text||"",N.length<500?console.log(N):console.log(`${N.substring(0,200)}... (${N.length} chars)`))}else C==="turn.completed"?p.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(F.usage||{})}`):p.debug(`[Codex] Event: ${C} ${JSON.stringify(F).slice(0,300)}`)}if(p.debug(`[Codex] Last agent message (${N.length} chars): ${N.slice(0,500)}`),s){if(!N)throw new Error("Codex agent returned no response");let F=JSON.parse(N),C=F;if(B)try{C=s.parse(F)}catch{C=s.parse(vt(F))}return p.debug("\u2705 [Codex] Structured output validated"),{raw:N,structured:C}}return N||""}catch(O){let I=O.message||String(O);throw p.error(`\u274C [Codex] SDK call failed: ${I}`),I.includes("exited with code")&&(v.outputSchema&&p.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."),p.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),p.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),O}}finally{for(let g of f)g.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=So(n);if(!s){p.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={command:i.command};i.args?.length&&(a.args=i.args),a.env={...process.env,...i.env||{}},r[c]=a,p.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)?Je(e,".codex-home"):Je(Eo(),".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 Ke("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){p.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)){p.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);p.info(`[Codex][plugins] installing ${a} from local marketplace ${l}`),console.log(`\u25C6 [Codex] installing plugin ${a} (local, no network)`);try{Ke(`codex plugin marketplace add ${JSON.stringify(l)}`,{env:r,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),Ke(`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 p.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=Je(t,".zibby-mkt",String(e).replace(/[^a-zA-Z0-9]+/g,"_"));try{return Tt(Je(t,".zibby-mkt"),{recursive:!0}),wo(e,r,{recursive:!0}),r}catch(n){return p.warn(`[Codex][plugins] could not copy @-containing marketplace to a safe path: ${n.message}`),e}}_readMarketplaceName(e){let t=Je(e,".agents","plugins","marketplace.json"),r;try{r=JSON.parse(_o(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 Ke("codex plugin list",{env:t,stdio:"pipe",timeout:15e3,encoding:"utf-8"}).split(`
84
- `).some(n=>n.includes(e)&&/installed/.test(n))}catch{return!1}}};import{AgentStrategy as To,getSkill as vo}from"@zibby/agent-workflow";Fe();import{execSync as Ao,spawn as Oo}from"node:child_process";import{existsSync as wr,mkdirSync as xr,readFileSync as Er,rmSync as $o,writeFileSync as Tr}from"node:fs";import{join as le}from"node:path";function Io(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 Co(o){let e=String(o||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return Io(e)}}function Po(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 ce=class extends To{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 p.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return Ao("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return p.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,skills:i=null,sessionPath:c=null,nodeName:a=null,timeout:l=600*1e3,signal:u=null}=t,d=[H("GEMINI_API_KEY"),H("GOOGLE_API_KEY")];try{let m=r;(!m||m==="auto")&&(m=z.GEMINI);let f=_t[m]||m,g=String(process.env.GEMINI_API_KEY||"").trim(),y=String(process.env.GOOGLE_API_KEY||"").trim(),h=this._resolveSkillsToMcp(i,{sessionPath:c,workspace:n,nodeName:a}),b=Object.keys(h).length>0,w=new ge(e),E=s&&typeof s.parse=="function",S=null;if(s){let A;try{let x=E?se(s,{target:"openAi"}):s;A=JSON.stringify(x,null,2)}catch{A="{}"}if(b){w.addSystemInstruction(`Write valid JSON that matches this schema:
85
- ${A}`,"schema_instruction","append");let x=`zibby-result-${Date.now()}.json`,L=le(n,".zibby","tmp");S=le(L,x),xr(L,{recursive:!0}),w.addStructuredOutput(s,S)}else w.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
82
+ `),Array.isArray(c)&&c.length>0){let O=this._resolveCodexHome(a);process.env.CODEX_HOME=O;try{Et(O,{recursive:!0})}catch{}this._ensurePlugins(c,O)}let E=(await import("chalk")).default;console.log(`
83
+ ${E.bold("Prompt sent to LLM:")}`),console.log(E.dim("\u2500".repeat(60))),console.log(E.dim(e)),console.log(E.dim("\u2500".repeat(60)));let S=this._resolveSkillsToMcp(i,{sessionPath:a,workspace:n,nodeName:l}),$={};Object.keys(S).length>0&&($.mcp_servers=S,p.debug(`[Codex] MCP servers: ${Object.keys(S).join(", ")}`));let P=this._resolveCodexBin(),k=new g({...P?{codexPathOverride:P}:{},...Object.keys($).length>0&&{config:$},env:ye(process.env)}),T=n;try{T&&Et(T,{recursive:!0})}catch{}(!T||!Eo(T))&&(T=process.cwd());let j=k.startThread({workingDirectory:T,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),B=s&&typeof s.parse=="function",v={};if(s)try{let O=B?se(s,{target:"openAi"}):s;v.outputSchema=O,p.debug("Structured output via SDK outputSchema")}catch(O){p.warn(`[Codex] Schema conversion failed, will extract from text: ${O.message}`)}if(m?.aborted){let O=new Error("Aborted via signal");throw O.name="AbortError",O}try{let{events:O}=await j.runStreamed(e,v),I=0,N="";for await(let F of O){if(m?.aborted){let _=new Error("Aborted via signal");throw _.name="AbortError",_}let C=F.type;if(C==="item.completed"){let _=F.item,R=_?.type;if(R==="mcp_tool_call"){I++;let D=`${_.server}/${_.tool}`;if(q.stepTool(`Tool: ${D}`),_.arguments){let A=JSON.stringify(_.arguments),x=A.length>100?`${A.substring(0,100)}...`:A;console.log(` Input: ${x}`)}}else if(R==="tool_call"||R==="function_call"||R==="command_execution"){I++;let D=_.name||_.tool||_.command||"unknown";q.stepTool(`Tool: ${D}`)}else R==="agent_message"&&(N=_.text||"",N.length<500?console.log(N):console.log(`${N.substring(0,200)}... (${N.length} chars)`))}else C==="turn.completed"?p.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(F.usage||{})}`):p.debug(`[Codex] Event: ${C} ${JSON.stringify(F).slice(0,300)}`)}if(p.debug(`[Codex] Last agent message (${N.length} chars): ${N.slice(0,500)}`),s){if(!N)throw new Error("Codex agent returned no response");let F=JSON.parse(N),C=F;if(B)try{C=s.parse(F)}catch{C=s.parse(Tt(F))}return p.debug("\u2705 [Codex] Structured output validated"),{raw:N,structured:C}}return N||""}catch(O){let I=O.message||String(O);throw p.error(`\u274C [Codex] SDK call failed: ${I}`),I.includes("exited with code")&&(v.outputSchema&&p.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."),p.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),p.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),O}}finally{for(let g of f)g.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){p.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={command:i.command};i.args?.length&&(a.args=i.args),a.env={...process.env,...i.env||{}},r[c]=a,p.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)?Ke(e,".codex-home"):Ke(To(),".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 Ge("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){p.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)){p.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);p.info(`[Codex][plugins] installing ${a} from local marketplace ${l}`),console.log(`\u25C6 [Codex] installing plugin ${a} (local, no network)`);try{Ge(`codex plugin marketplace add ${JSON.stringify(l)}`,{env:r,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),Ge(`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 p.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=Ke(t,".zibby-mkt",String(e).replace(/[^a-zA-Z0-9]+/g,"_"));try{return Et(Ke(t,".zibby-mkt"),{recursive:!0}),xo(e,r,{recursive:!0}),r}catch(n){return p.warn(`[Codex][plugins] could not copy @-containing marketplace to a safe path: ${n.message}`),e}}_readMarketplaceName(e){let t=Ke(e,".agents","plugins","marketplace.json"),r;try{r=JSON.parse(wo(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 Ge("codex plugin list",{env:t,stdio:"pipe",timeout:15e3,encoding:"utf-8"}).split(`
84
+ `).some(n=>n.includes(e)&&/installed/.test(n))}catch{return!1}}};import{AgentStrategy as vo,getSkill as Ao}from"@zibby/agent-workflow";Be();import{execSync as Oo,spawn as $o}from"node:child_process";import{existsSync as xr,mkdirSync as Er,readFileSync as Tr,rmSync as Io,writeFileSync as vr}from"node:fs";import{join as le}from"node:path";function Co(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 Po(o){let e=String(o||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return Co(e)}}function ko(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 ce=class extends vo{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 p.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return Oo("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return p.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,skills:i=null,sessionPath:c=null,nodeName:a=null,timeout:l=600*1e3,signal:u=null}=t,d=[H("GEMINI_API_KEY"),H("GOOGLE_API_KEY")];try{let m=r;(!m||m==="auto")&&(m=z.GEMINI);let f=St[m]||m,g=String(process.env.GEMINI_API_KEY||"").trim(),y=String(process.env.GOOGLE_API_KEY||"").trim(),h=this._resolveSkillsToMcp(i,{sessionPath:c,workspace:n,nodeName:a}),b=Object.keys(h).length>0,w=new ge(e),E=s&&typeof s.parse=="function",S=null;if(s){let A;try{let x=E?se(s,{target:"openAi"}):s;A=JSON.stringify(x,null,2)}catch{A="{}"}if(b){w.addSystemInstruction(`Write valid JSON that matches this schema:
85
+ ${A}`,"schema_instruction","append");let x=`zibby-result-${Date.now()}.json`,L=le(n,".zibby","tmp");S=le(L,x),Er(L,{recursive:!0}),w.addStructuredOutput(s,S)}else w.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
86
86
  ${A}`,"json_instruction","append")}let $=w.build(),P=w.getUserPrompt(),k=w.getStats(),T=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),j=T?` | key: ***${T.slice(-4)}`:" | key: not set";console.log(`
87
87
  \u25C6 Model: ${f||"auto"}${j}
88
88
  `);let B=(await import("chalk")).default;console.log(`
89
- ${B.bold("Prompt sent to LLM:")}`),console.log(B.dim("\u2500".repeat(60))),console.log(B.dim(P)),console.log(B.dim("\u2500".repeat(60)));let v=this._createGeminiConfigDir(n,h),O=["--output-format","json"];f&&f!=="auto"&&O.push("--model",f);let I=Object.keys(h);if(I.length>0){O.push("--approval-mode","yolo");for(let A of I)O.push("--allowed-mcp-server-names",A);p.info(`[Gemini] Enabling MCP servers: ${I.join(", ")}`)}else i&&i.length>0&&p.warn(`[Gemini] Skills requested but no MCP servers configured: ${i.join(", ")}`);O.push("-p",$);let N={...ye(process.env),GEMINI_CLI_HOME:v};g?(N.GEMINI_API_KEY=g,delete N.GOOGLE_API_KEY):y&&(N.GOOGLE_API_KEY=y,delete N.GEMINI_API_KEY),p.debug(`[Gemini] Command: gemini ${O.slice(0,8).join(" ")}... (${O.length} total args)`),p.debug(`[Gemini] User prompt: ${k.userPromptLength} chars, System instructions: ${k.systemInstructionsLength} chars (${k.instructionCount} blocks), Full: ${k.fullPromptLength} chars`),p.debug(`[Gemini] Config home: ${v}`),p.debug(`[Gemini] GEMINI_CLI_HOME env: ${N.GEMINI_CLI_HOME}`);let F="",C=null;try{F=await new Promise((x,L)=>{let M=Oo("gemini",O,{cwd:n,env:N,stdio:["ignore","pipe","pipe"],...u&&{signal:u}}),U="",K="",Re=!1,Le=null,St=!1,qt=setTimeout(()=>{try{M.kill("SIGTERM")}catch{}},l),tt=()=>{St||Re||(St=!0,Le=setTimeout(()=>{if(!Re)try{M.kill("SIGKILL")}catch{}},5e3))};u&&(u.aborted?tt():u.addEventListener("abort",tt,{once:!0})),M.stdout.on("data",ee=>{U+=ee.toString()}),M.stderr.on("data",ee=>{K+=ee.toString()}),M.on("error",ee=>{if(clearTimeout(qt),Le&&clearTimeout(Le),u&&!u.aborted)try{u.removeEventListener("abort",tt)}catch{}L(ee)}),M.on("close",ee=>{if(Re=!0,clearTimeout(qt),Le&&clearTimeout(Le),u&&!u.aborted)try{u.removeEventListener("abort",tt)}catch{}if(St){let Qt=new Error("Aborted via signal");return Qt.name="AbortError",L(Qt)}if(ee===0)return x(U.trim());L(new Error(`gemini failed with code ${ee}: ${(K||U).trim()}`))})})}catch(A){C=A}finally{try{$o(v,{recursive:!0,force:!0})}catch{}}let _=Po(F).trim();if(!s){if(C)throw C;return _}if(S){let A=wr(S);if(p.info(`[Gemini] Result file: ${A?"present":"missing"} at ${S}`),A)try{let x=Er(S,"utf-8").trim(),L=JSON.parse(x),M=E?s.parse(L):L;return p.info("[Gemini] Structured output recovered from result file"),{raw:_,structured:M}}catch(x){p.warn(`[Gemini] Result file parse/validation failed: ${x.message}`)}else C||p.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let R=null;if(s){let A=new X;A.zodSchema=s,A.processChunk(_),A.flush(),R=A.getResult()}if(p.info(`[Gemini] Raw stdout length: ${F.length} chars`),p.info(`[Gemini] Extracted text length: ${_.length} chars`),p.info(`[Gemini] StreamParser result: ${R?"extracted":"null"}`),R||(_.length<2e3?p.info(`[Gemini] Raw text preview:
89
+ ${B.bold("Prompt sent to LLM:")}`),console.log(B.dim("\u2500".repeat(60))),console.log(B.dim(P)),console.log(B.dim("\u2500".repeat(60)));let v=this._createGeminiConfigDir(n,h),O=["--output-format","json"];f&&f!=="auto"&&O.push("--model",f);let I=Object.keys(h);if(I.length>0){O.push("--approval-mode","yolo");for(let A of I)O.push("--allowed-mcp-server-names",A);p.info(`[Gemini] Enabling MCP servers: ${I.join(", ")}`)}else i&&i.length>0&&p.warn(`[Gemini] Skills requested but no MCP servers configured: ${i.join(", ")}`);O.push("-p",$);let N={...ye(process.env),GEMINI_CLI_HOME:v};g?(N.GEMINI_API_KEY=g,delete N.GOOGLE_API_KEY):y&&(N.GOOGLE_API_KEY=y,delete N.GEMINI_API_KEY),p.debug(`[Gemini] Command: gemini ${O.slice(0,8).join(" ")}... (${O.length} total args)`),p.debug(`[Gemini] User prompt: ${k.userPromptLength} chars, System instructions: ${k.systemInstructionsLength} chars (${k.instructionCount} blocks), Full: ${k.fullPromptLength} chars`),p.debug(`[Gemini] Config home: ${v}`),p.debug(`[Gemini] GEMINI_CLI_HOME env: ${N.GEMINI_CLI_HOME}`);let F="",C=null;try{F=await new Promise((x,L)=>{let M=$o("gemini",O,{cwd:n,env:N,stdio:["ignore","pipe","pipe"],...u&&{signal:u}}),U="",K="",Ne=!1,Re=null,bt=!1,Qt=setTimeout(()=>{try{M.kill("SIGTERM")}catch{}},l),et=()=>{bt||Ne||(bt=!0,Re=setTimeout(()=>{if(!Ne)try{M.kill("SIGKILL")}catch{}},5e3))};u&&(u.aborted?et():u.addEventListener("abort",et,{once:!0})),M.stdout.on("data",ee=>{U+=ee.toString()}),M.stderr.on("data",ee=>{K+=ee.toString()}),M.on("error",ee=>{if(clearTimeout(Qt),Re&&clearTimeout(Re),u&&!u.aborted)try{u.removeEventListener("abort",et)}catch{}L(ee)}),M.on("close",ee=>{if(Ne=!0,clearTimeout(Qt),Re&&clearTimeout(Re),u&&!u.aborted)try{u.removeEventListener("abort",et)}catch{}if(bt){let er=new Error("Aborted via signal");return er.name="AbortError",L(er)}if(ee===0)return x(U.trim());L(new Error(`gemini failed with code ${ee}: ${(K||U).trim()}`))})})}catch(A){C=A}finally{try{Io(v,{recursive:!0,force:!0})}catch{}}let _=ko(F).trim();if(!s){if(C)throw C;return _}if(S){let A=xr(S);if(p.info(`[Gemini] Result file: ${A?"present":"missing"} at ${S}`),A)try{let x=Tr(S,"utf-8").trim(),L=JSON.parse(x),M=E?s.parse(L):L;return p.info("[Gemini] Structured output recovered from result file"),{raw:_,structured:M}}catch(x){p.warn(`[Gemini] Result file parse/validation failed: ${x.message}`)}else C||p.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let R=null;if(s){let A=new X;A.zodSchema=s,A.processChunk(_),A.flush(),R=A.getResult()}if(p.info(`[Gemini] Raw stdout length: ${F.length} chars`),p.info(`[Gemini] Extracted text length: ${_.length} chars`),p.info(`[Gemini] StreamParser result: ${R?"extracted":"null"}`),R||(_.length<2e3?p.info(`[Gemini] Raw text preview:
90
90
  ${_}`):p.info(`[Gemini] Raw text preview (first 1000 chars):
91
- ${_.slice(0,1e3)}`),R=Co(_)),!R)throw C||(p.error("[Gemini] Failed to extract valid JSON from output"),p.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 D=E?s.parse(R):R;return{raw:_,structured:D}}finally{for(let m of d)m.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=vo(n);if(!s||typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let c=s.cursorKey||s.serverName||n,a={command:i.command};i.args?.length&&(a.args=i.args),i.env&&Object.keys(i.env).length>0&&(a.env=i.env),i.cwd&&(a.cwd=i.cwd),r[c]=a}return r}_createGeminiConfigDir(e,t){let r=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,n=le(e||process.cwd(),".zibby","tmp",`gemini-home-${r}`),s=le(n,".gemini");xr(s,{recursive:!0});let i=le(s,"settings.json"),c={},a=le(process.env.HOME||"",".gemini","settings.json");if(wr(a))try{c=JSON.parse(Er(a,"utf-8"))}catch{c={}}let l={...c,mcpServers:{...c.mcpServers&&typeof c.mcpServers=="object"?c.mcpServers:{},...t||{}}};Tr(i,`${JSON.stringify(l,null,2)}
92
- `,"utf-8");let u=le(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{Tr(u,`${JSON.stringify(l,null,2)}
93
- `,"utf-8")}catch{}return p.debug(`[Gemini] Created isolated config with ${Object.keys(l.mcpServers||{}).length} MCP servers`),p.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(l.mcpServers||{}),null,2)}`),n}};import{AgentStrategy as Jo,getSkill as ft}from"@zibby/agent-workflow";var _e=class{formatTools(e){throw new Error("formatTools() must be implemented")}hasToolCalls(e){throw new Error("hasToolCalls() must be implemented")}parseToolCalls(e){throw new Error("parseToolCalls() must be implemented")}getTextContent(e){throw new Error("getTextContent() must be implemented")}buildAssistantMessage(e){throw new Error("buildAssistantMessage() must be implemented")}buildToolResultMessage(e,t){throw new Error("buildToolResultMessage() must be implemented")}injectToolsIntoBody(e,t){throw new Error("injectToolsIntoBody() must be implemented")}};var ue=class extends _e{formatTools(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters||t.input_schema||{type:"object",properties:{}}}}))}hasToolCalls(e){let t=e.choices?.[0]?.message;return!!(t?.tool_calls&&t.tool_calls.length>0)}parseToolCalls(e){return(e.choices?.[0]?.message?.tool_calls||[]).map(r=>({id:r.id,name:r.function.name,args:JSON.parse(r.function.arguments||"{}")}))}getTextContent(e){return e.choices?.[0]?.message?.content||""}buildAssistantMessage(e){return e.choices?.[0]?.message}buildToolResultMessage(e,t){return{role:"tool",tool_call_id:e,content:typeof t=="string"?t:JSON.stringify(t)}}injectToolsIntoBody(e,t){return t.length>0&&(e.tools=t),e}};var ze=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 lt(o){return Buffer.byteLength(JSON.stringify(o),"utf8")}function ct(o,e){let t=String(o||"");if(t.length<=e)return t;let r=Math.max(0,e-28);return`${t.slice(0,r)}
91
+ ${_.slice(0,1e3)}`),R=Po(_)),!R)throw C||(p.error("[Gemini] Failed to extract valid JSON from output"),p.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 D=E?s.parse(R):R;return{raw:_,structured:D}}finally{for(let m of d)m.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=Ao(n);if(!s||typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let c=s.cursorKey||s.serverName||n,a={command:i.command};i.args?.length&&(a.args=i.args),i.env&&Object.keys(i.env).length>0&&(a.env=i.env),i.cwd&&(a.cwd=i.cwd),r[c]=a}return r}_createGeminiConfigDir(e,t){let r=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,n=le(e||process.cwd(),".zibby","tmp",`gemini-home-${r}`),s=le(n,".gemini");Er(s,{recursive:!0});let i=le(s,"settings.json"),c={},a=le(process.env.HOME||"",".gemini","settings.json");if(xr(a))try{c=JSON.parse(Tr(a,"utf-8"))}catch{c={}}let l={...c,mcpServers:{...c.mcpServers&&typeof c.mcpServers=="object"?c.mcpServers:{},...t||{}}};vr(i,`${JSON.stringify(l,null,2)}
92
+ `,"utf-8");let u=le(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{vr(u,`${JSON.stringify(l,null,2)}
93
+ `,"utf-8")}catch{}return p.debug(`[Gemini] Created isolated config with ${Object.keys(l.mcpServers||{}).length} MCP servers`),p.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(l.mcpServers||{}),null,2)}`),n}};import{AgentStrategy as zo,getSkill as pt}from"@zibby/agent-workflow";var _e=class{formatTools(e){throw new Error("formatTools() must be implemented")}hasToolCalls(e){throw new Error("hasToolCalls() must be implemented")}parseToolCalls(e){throw new Error("parseToolCalls() must be implemented")}getTextContent(e){throw new Error("getTextContent() must be implemented")}buildAssistantMessage(e){throw new Error("buildAssistantMessage() must be implemented")}buildToolResultMessage(e,t){throw new Error("buildToolResultMessage() must be implemented")}injectToolsIntoBody(e,t){throw new Error("injectToolsIntoBody() must be implemented")}};var ue=class extends _e{formatTools(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters||t.input_schema||{type:"object",properties:{}}}}))}hasToolCalls(e){let t=e.choices?.[0]?.message;return!!(t?.tool_calls&&t.tool_calls.length>0)}parseToolCalls(e){return(e.choices?.[0]?.message?.tool_calls||[]).map(r=>({id:r.id,name:r.function.name,args:JSON.parse(r.function.arguments||"{}")}))}getTextContent(e){return e.choices?.[0]?.message?.content||""}buildAssistantMessage(e){return e.choices?.[0]?.message}buildToolResultMessage(e,t){return{role:"tool",tool_call_id:e,content:typeof t=="string"?t:JSON.stringify(t)}}injectToolsIntoBody(e,t){return t.length>0&&(e.tools=t),e}};var Je=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 at(o){return Buffer.byteLength(JSON.stringify(o),"utf8")}function lt(o,e){let t=String(o||"");if(t.length<=e)return t;let r=Math.max(0,e-28);return`${t.slice(0,r)}
94
94
 
95
- [truncated for size budget]`}function At(o,e=0){if(!o||typeof o!="object"||e>8)return o;if(Array.isArray(o))return o.map(r=>At(r,e+1));let t={};for(let[r,n]of Object.entries(o))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=At(n,e+1));return t}function ko(o=[]){return o.map(e=>({...e,function:{...e.function,description:ct(e.function?.description||"",180),parameters:At(e.function?.parameters||{type:"object",properties:{}})}}))}function vr(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 Ot(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)?ko(o.tools):o.tools};n.messages.length>0&&n.messages[0]?.role==="system"&&(n.messages[0]={...n.messages[0],content:ct(n.messages[0].content,r)});let s=!1;for(;lt(n)>t&&n.messages.length>2;)n.messages.splice(1,1),s=!0;if(s&&(n.messages=vr(n.messages)),lt(n)>t&&n.messages.length>0&&(n.messages[0]={...n.messages[0],content:ct(n.messages[0].content,6e3)},s=!0),lt(n)>t){let i=n.messages.find(a=>a.role==="system")||n.messages[0],c=n.messages.slice(-2);n.messages=vr([i,...c].filter(Boolean).map((a,l)=>({...a,content:ct(a.content,l===0?4e3:8e3)}))),s=!0}return{body:n,meta:{bytes:lt(n),trimmed:s,maxBytes:t,messageCount:n.messages.length}}}var Ar=o=>Buffer.byteLength(JSON.stringify(o),"utf8"),we=class extends ze{async fetchCompletion(e,t,r={}){let n=Ar(e),{body:s,meta:i}=Ot(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=Ar(n),{body:i,meta:c}=Ot(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,f="",g="",y=new Map;for(;;){let{done:h,value:b}=await d.read();if(h)break;f+=m.decode(b,{stream:!0});let w=f.split(`
96
- `);f=w.pop();for(let E of w){if(!E.startsWith("data: "))continue;let S=E.slice(6).trim();if(S==="[DONE]")continue;let $;try{$=JSON.parse(S)}catch{continue}let P=$.choices?.[0]?.delta;if(P&&(P.content&&(g+=P.content,r.onToken&&r.onToken(P.content)),P.tool_calls))for(let k of P.tool_calls){let T=k.index??0;y.has(T)||y.set(T,{id:"",name:"",args:""});let j=y.get(T);k.id&&(j.id=k.id),k.function?.name&&(j.name=k.function.name),k.function?.arguments!=null&&(j.args+=k.function.arguments)}}}if(y.size>0){let h=[...y.entries()].sort(([b],[w])=>b-w).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 No}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Ro}from"@modelcontextprotocol/sdk/client/stdio.js";var Ye=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;p.debug(`[MCP] Starting ${e}: ${r} ${n.join(" ")}`);let i=new Ro({command:r,args:n,env:{...process.env,...s}}),c=new No({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`);p.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(`
97
- `)||"",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){p.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 Lo,readFileSync as Mo}from"node:fs";import{join as Do}from"node:path";import{homedir as Uo}from"node:os";function jo(){try{let o=Do(Uo(),".zibby","config.json");return Lo(o)?JSON.parse(Mo(o,"utf-8")):{}}catch{return{}}}function ut(o){return String(o||"").replace(/\/v1\/?$/,"")}function Bo(o,e){let t=process.env.OPENAI_PROXY_URL;if(t)return ut(t);if(o==="session")return e.proxyUrl?ut(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 ut(r||"https://api.openai.com")}return ut(t||"")}function $t(){let o=jo(),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=Bo(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 pt(o,e){let t=String(o??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
95
+ [truncated for size budget]`}function vt(o,e=0){if(!o||typeof o!="object"||e>8)return o;if(Array.isArray(o))return o.map(r=>vt(r,e+1));let t={};for(let[r,n]of Object.entries(o))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=vt(n,e+1));return t}function No(o=[]){return o.map(e=>({...e,function:{...e.function,description:lt(e.function?.description||"",180),parameters:vt(e.function?.parameters||{type:"object",properties:{}})}}))}function Ar(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 At(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)?No(o.tools):o.tools};n.messages.length>0&&n.messages[0]?.role==="system"&&(n.messages[0]={...n.messages[0],content:lt(n.messages[0].content,r)});let s=!1;for(;at(n)>t&&n.messages.length>2;)n.messages.splice(1,1),s=!0;if(s&&(n.messages=Ar(n.messages)),at(n)>t&&n.messages.length>0&&(n.messages[0]={...n.messages[0],content:lt(n.messages[0].content,6e3)},s=!0),at(n)>t){let i=n.messages.find(a=>a.role==="system")||n.messages[0],c=n.messages.slice(-2);n.messages=Ar([i,...c].filter(Boolean).map((a,l)=>({...a,content:lt(a.content,l===0?4e3:8e3)}))),s=!0}return{body:n,meta:{bytes:at(n),trimmed:s,maxBytes:t,messageCount:n.messages.length}}}var Or=o=>Buffer.byteLength(JSON.stringify(o),"utf8"),we=class extends Je{async fetchCompletion(e,t,r={}){let n=Or(e),{body:s,meta:i}=At(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=Or(n),{body:i,meta:c}=At(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,f="",g="",y=new Map;for(;;){let{done:h,value:b}=await d.read();if(h)break;f+=m.decode(b,{stream:!0});let w=f.split(`
96
+ `);f=w.pop();for(let E of w){if(!E.startsWith("data: "))continue;let S=E.slice(6).trim();if(S==="[DONE]")continue;let $;try{$=JSON.parse(S)}catch{continue}let P=$.choices?.[0]?.delta;if(P&&(P.content&&(g+=P.content,r.onToken&&r.onToken(P.content)),P.tool_calls))for(let k of P.tool_calls){let T=k.index??0;y.has(T)||y.set(T,{id:"",name:"",args:""});let j=y.get(T);k.id&&(j.id=k.id),k.function?.name&&(j.name=k.function.name),k.function?.arguments!=null&&(j.args+=k.function.arguments)}}}if(y.size>0){let h=[...y.entries()].sort(([b],[w])=>b-w).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 Ro}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Lo}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;p.debug(`[MCP] Starting ${e}: ${r} ${n.join(" ")}`);let i=new Lo({command:r,args:n,env:{...process.env,...s}}),c=new Ro({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`);p.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(`
97
+ `)||"",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){p.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 Mo,readFileSync as Do}from"node:fs";import{join as Uo}from"node:path";import{homedir as jo}from"node:os";function Bo(){try{let o=Uo(jo(),".zibby","config.json");return Mo(o)?JSON.parse(Do(o,"utf-8")):{}}catch{return{}}}function ct(o){return String(o||"").replace(/\/v1\/?$/,"")}function Fo(o,e){let t=process.env.OPENAI_PROXY_URL;if(t)return ct(t);if(o==="session")return e.proxyUrl?ct(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 ct(r||"https://api.openai.com")}return ct(t||"")}function Ot(){let o=Bo(),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=Fo(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 ut(o,e){let t=String(o??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
98
98
 
99
- [tool result truncated for size]`}function Fo(o,e){if(typeof o=="string")return pt(o,e);try{return pt(JSON.stringify(o),e)}catch{return pt(String(o),e)}}function Or(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 Go(o){let e=Array.isArray(o?.messages)?o.messages:[],t=e.find(s=>s.role==="system"),r=e.slice(-4).map(s=>({...s,content:pt(s.content,s.role==="tool"?1200:2500)}));r=Or(r);let n={...o,messages:[t,...r].filter(Boolean)};return delete n.tools,n}async function Ko({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=Go(o);return typeof i=="function"&&i(o,l),{data:e?await s(l,t,r):await n(l,t,r),fallback:l}}}async function $r({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:f,hasToolCalls:g,getTextContent:y,parseToolCalls:h,buildAssistantMessage:b,buildToolResultMessage:w,executeTool:E,onToolCallLog:S,injectTools:$}=a;Array.isArray(o?.messages)&&(o.messages=Or(o.messages));let P=await Ko({body:o,streaming:r,auth:e,options:t,fetchCompletion:d,fetchStreamingCompletion:m,onFallbackLog:f}),k=P?.data||P;if(!g(k))return{done:!0,text:y(k),body:P?.fallback||o};let T=h(k),j=P?.fallback||o;j.messages.push(b(k)),c&&typeof S=="function"&&S(T);let B=await Promise.all(T.map((v,O)=>(typeof t.onToolCall=="function"&&t.onToolCall(v.name,v.args,{round:i,index:O,total:T.length}),E(v,n))));for(let v=0;v<T.length;v++){let I=T[v].name==="get_skill_context"?typeof B[v]=="string"?B[v]:JSON.stringify(B[v]):Fo(B[v],u);j.messages.push(w(T[v].id,I))}return typeof t.onToolCall=="function"&&t.onToolCall(null),$(j,s),{done:!1,body:j}}var zo=z.ASSISTANT,Yo=15,It="get_skill_context";function Ee(o){!o||typeof o!="object"||(o.type==="object"&&o.properties&&(o.required=Object.keys(o.properties),o.additionalProperties=!1,Object.values(o.properties).forEach(Ee)),o.type==="array"&&o.items&&Ee(o.items),o.anyOf&&o.anyOf.forEach(Ee),o.oneOf&&o.oneOf.forEach(Ee),o.allOf&&o.allOf.forEach(Ee))}var Ir={maxBytes:49e3,systemMaxChars:12e3},xe=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Ho=o=>Buffer.byteLength(JSON.stringify(o),"utf8");function dt(o){return Array.isArray(o)?new Set(o.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function Wo(o){return Array.isArray(o)?o.map(e=>String(e||"").trim()).filter(Boolean):[]}var pe=class extends Jo{#e;#t;#r=new Ye;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new ue,this.#t=e.completionProvider||new we):(this.#e=e||new ue,this.#t=new we)}canHandle(e){return $t().ok}async invoke(e,t={}){let r=H("OPENAI_API_KEY");try{let n=t.model&&t.model!=="auto"?t.model:zo,s=$t();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=xe();if(a?await this.#m(i,n,c,s.tokenPreview||"none"):p.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),f=this.#u(t),g={...t,payloadCompaction:f},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 w=0;w<Yo;w++){if(t.signal?.aborted){let S=new Error("Aborted via signal");throw S.name="AbortError",S}let E=await $r({body:b,auth:s,options:g,streaming:h,toolContext:y,activeSkills:d,round:w,verbose:a,dependencies:{fetchCompletion:this.#s.bind(this),fetchStreamingCompletion:this.#l.bind(this),onFallbackLog:(S,$)=>{xe()&&console.log(`413 fallback: messages ${S.messages.length} -> ${$.messages.length}, bytes=${Ho($)}`)},hasToolCalls:S=>this.#e.hasToolCalls(S),getTextContent:S=>this.#e.getTextContent(S),parseToolCalls:S=>this.#e.parseToolCalls(S),buildAssistantMessage:S=>this.#e.buildAssistantMessage(S),buildToolResultMessage:(S,$)=>this.#e.buildToolResultMessage(S,$),executeTool:(S,$)=>this.#a(S,$),onToolCallLog:async S=>{let $=(await import("chalk")).default;console.log($.dim(` ${S.map(P=>`${P.name}(${JSON.stringify(P.args).slice(0,80)})`).join(", ")}`))},injectTools:(S,$)=>this.#o(S,$,u)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(E.done)return E.text;b.messages=E.body.messages,E.body.tools?b.tools=E.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=ft(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(It,t)&&r.push({name:It,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===It){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=ft(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),f=JSON.stringify({skillId:l,description:u.description||"",toolNames:m,promptFragment:d||""});return xe()&&(console.log(`
99
+ [tool result truncated for size]`}function Go(o,e){if(typeof o=="string")return ut(o,e);try{return ut(JSON.stringify(o),e)}catch{return ut(String(o),e)}}function $r(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 Ko(o){let e=Array.isArray(o?.messages)?o.messages:[],t=e.find(s=>s.role==="system"),r=e.slice(-4).map(s=>({...s,content:ut(s.content,s.role==="tool"?1200:2500)}));r=$r(r);let n={...o,messages:[t,...r].filter(Boolean)};return delete n.tools,n}async function Jo({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=Ko(o);return typeof i=="function"&&i(o,l),{data:e?await s(l,t,r):await n(l,t,r),fallback:l}}}async function Ir({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:f,hasToolCalls:g,getTextContent:y,parseToolCalls:h,buildAssistantMessage:b,buildToolResultMessage:w,executeTool:E,onToolCallLog:S,injectTools:$}=a;Array.isArray(o?.messages)&&(o.messages=$r(o.messages));let P=await Jo({body:o,streaming:r,auth:e,options:t,fetchCompletion:d,fetchStreamingCompletion:m,onFallbackLog:f}),k=P?.data||P;if(!g(k))return{done:!0,text:y(k),body:P?.fallback||o};let T=h(k),j=P?.fallback||o;j.messages.push(b(k)),c&&typeof S=="function"&&S(T);let B=await Promise.all(T.map((v,O)=>(typeof t.onToolCall=="function"&&t.onToolCall(v.name,v.args,{round:i,index:O,total:T.length}),E(v,n))));for(let v=0;v<T.length;v++){let I=T[v].name==="get_skill_context"?typeof B[v]=="string"?B[v]:JSON.stringify(B[v]):Go(B[v],u);j.messages.push(w(T[v].id,I))}return typeof t.onToolCall=="function"&&t.onToolCall(null),$(j,s),{done:!1,body:j}}var Yo=z.ASSISTANT,Ho=15,$t="get_skill_context";function Ee(o){!o||typeof o!="object"||(o.type==="object"&&o.properties&&(o.required=Object.keys(o.properties),o.additionalProperties=!1,Object.values(o.properties).forEach(Ee)),o.type==="array"&&o.items&&Ee(o.items),o.anyOf&&o.anyOf.forEach(Ee),o.oneOf&&o.oneOf.forEach(Ee),o.allOf&&o.allOf.forEach(Ee))}var Cr={maxBytes:49e3,systemMaxChars:12e3},xe=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Vo=o=>Buffer.byteLength(JSON.stringify(o),"utf8");function ft(o){return Array.isArray(o)?new Set(o.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function Wo(o){return Array.isArray(o)?o.map(e=>String(e||"").trim()).filter(Boolean):[]}var pe=class extends zo{#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 ue,this.#t=e.completionProvider||new we):(this.#e=e||new ue,this.#t=new we)}canHandle(e){return Ot().ok}async invoke(e,t={}){let r=H("OPENAI_API_KEY");try{let n=t.model&&t.model!=="auto"?t.model:Yo,s=Ot();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=xe();if(a?await this.#m(i,n,c,s.tokenPreview||"none"):p.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),f=this.#u(t),g={...t,payloadCompaction:f},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 w=0;w<Ho;w++){if(t.signal?.aborted){let S=new Error("Aborted via signal");throw S.name="AbortError",S}let E=await Ir({body:b,auth:s,options:g,streaming:h,toolContext:y,activeSkills:d,round:w,verbose:a,dependencies:{fetchCompletion:this.#s.bind(this),fetchStreamingCompletion:this.#l.bind(this),onFallbackLog:(S,$)=>{xe()&&console.log(`413 fallback: messages ${S.messages.length} -> ${$.messages.length}, bytes=${Vo($)}`)},hasToolCalls:S=>this.#e.hasToolCalls(S),getTextContent:S=>this.#e.getTextContent(S),parseToolCalls:S=>this.#e.parseToolCalls(S),buildAssistantMessage:S=>this.#e.buildAssistantMessage(S),buildToolResultMessage:(S,$)=>this.#e.buildToolResultMessage(S,$),executeTool:(S,$)=>this.#a(S,$),onToolCallLog:async S=>{let $=(await import("chalk")).default;console.log($.dim(` ${S.map(P=>`${P.name}(${JSON.stringify(P.args).slice(0,80)})`).join(", ")}`))},injectTools:(S,$)=>this.#o(S,$,u)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(E.done)return E.text;b.messages=E.body.messages,E.body.tools?b.tools=E.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=pt(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($t,t)&&r.push({name:$t,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===$t){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=pt(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),f=JSON.stringify({skillId:l,description:u.description||"",toolNames:m,promptFragment:d||""});return xe()&&(console.log(`
100
100
  \u{1F4D6} get_skill_context("${l}") \u2192 ${f.length} chars (fragment: ${d.length} chars)`),console.log(` tools: [${m.join(", ")}]`),console.log(` fragment preview: ${d.slice(0,200).replace(/\n/g,"\\n")}\u2026
101
- `)),f}let c=s?.get(e.name)||null;if(!c)return`Unknown tool: ${e.name}`;let a=ft(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})=>{xe()&&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})=>{xe()&&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(()=>(Fe(),hr)),i=typeof n.schema?.parse=="function",c=i?s(n.schema,{}):n.schema;delete c.$schema,Ee(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||Ir.maxBytes),systemMaxChars:Number(t.systemMaxChars||Ir.systemMaxChars)}}#p(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:dt(t.allowTools||e.allowTools),denyTools:dt(t.denyTools||e.denyTools),denyPrefixes:Wo(t.denyPrefixes||e.denyToolPrefixes),includeSkills:dt(t.includeSkills||e.includeSkills),excludeSkills:dt(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=ft(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&&xe()){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(`
101
+ `)),f}let c=s?.get(e.name)||null;if(!c)return`Unknown tool: ${e.name}`;let a=pt(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})=>{xe()&&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})=>{xe()&&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(()=>(Be(),yr)),i=typeof n.schema?.parse=="function",c=i?s(n.schema,{}):n.schema;delete c.$schema,Ee(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||Cr.maxBytes),systemMaxChars:Number(t.systemMaxChars||Cr.systemMaxChars)}}#p(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:ft(t.allowTools||e.allowTools),denyTools:ft(t.denyTools||e.denyTools),denyPrefixes:Wo(t.denyPrefixes||e.denyToolPrefixes),includeSkills:ft(t.includeSkills||e.includeSkills),excludeSkills:ft(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=pt(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&&xe()){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(`
102
102
  \u25C6 Model: ${t} | proxy: ${r} | token: ${n||"none"}
103
- `);let s=(await import("chalk")).default;console.log(s.bold("Prompt sent to LLM:")),console.log(s.dim("\u2500".repeat(60)));let i=!1;for(let c of e)if(c.role==="system")console.log(s.dim(`[System] ${c.content||""}`));else{i||(console.log(s.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),i=!0);let a=c.role==="user"?"Human":"AI",l=c.content?.length>200?`${c.content.slice(0,200)}...`:c.content||"";console.log(s.dim(`[${a}] ${l}`))}console.log(s.dim("\u2500".repeat(60)))}};var Cr=!1;function Ct(){Cr||(He(new pe),He(new oe),He(new ie),He(new ae),He(new ce),Cr=!0)}function Pr(o){return null}import{spawn as es}from"node:child_process";import{mkdirSync as Nr,existsSync as ts,writeFileSync as rs}from"node:fs";import{join as Rt}from"node:path";import{ContextLoader as ns,WorkflowGraph as os,Node as ss,WorkflowState as is,DEFAULT_OUTPUT_BASE as Rr,SESSIONS_DIR as as,SESSION_INFO_FILE as ls}from"@zibby/agent-workflow";import{exec as Vo}from"node:child_process";import{promisify as Zo}from"node:util";import{existsSync as Xo}from"node:fs";import{join as Pt}from"node:path";import{homedir as kt}from"node:os";var kr=Zo(Vo);async function Nt(){try{return await kr("cursor-agent --version"),"cursor-agent"}catch{let e=[Pt(kt(),".local","bin","cursor-agent"),Pt(kt(),".cursor","bin","cursor-agent"),Pt(kt(),".cursor-agent","bin","cursor-agent")];for(let t of e)if(Xo(t))try{return await kr(`"${t}" --version`),t}catch{}return null}}async function qo(){return await Nt()!==null}function Qo(){return`
103
+ `);let s=(await import("chalk")).default;console.log(s.bold("Prompt sent to LLM:")),console.log(s.dim("\u2500".repeat(60)));let i=!1;for(let c of e)if(c.role==="system")console.log(s.dim(`[System] ${c.content||""}`));else{i||(console.log(s.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),i=!0);let a=c.role==="user"?"Human":"AI",l=c.content?.length>200?`${c.content.slice(0,200)}...`:c.content||"";console.log(s.dim(`[${a}] ${l}`))}console.log(s.dim("\u2500".repeat(60)))}};var Pr=!1;function It(){Pr||(Ye(new pe),Ye(new oe),Ye(new ie),Ye(new ae),Ye(new ce),Pr=!0)}function kr(o){return null}import{spawn as ts}from"node:child_process";import{mkdirSync as Rr,existsSync as rs,writeFileSync as ns}from"node:fs";import{join as Nt}from"node:path";import{ContextLoader as os,WorkflowGraph as ss,Node as is,WorkflowState as as,DEFAULT_OUTPUT_BASE as Lr,SESSIONS_DIR as ls,SESSION_INFO_FILE as cs}from"@zibby/agent-workflow";import{exec as Zo}from"node:child_process";import{promisify as Xo}from"node:util";import{existsSync as qo}from"node:fs";import{join as Ct}from"node:path";import{homedir as Pt}from"node:os";var Nr=Xo(Zo);async function kt(){try{return await Nr("cursor-agent --version"),"cursor-agent"}catch{let e=[Ct(Pt(),".local","bin","cursor-agent"),Ct(Pt(),".cursor","bin","cursor-agent"),Ct(Pt(),".cursor-agent","bin","cursor-agent")];for(let t of e)if(qo(t))try{return await Nr(`"${t}" --version`),t}catch{}return null}}async function Qo(){return await kt()!==null}function es(){return`
104
104
  \u274C cursor-agent CLI not found!
105
105
 
106
106
  To use the Cursor agent, install it from:
@@ -126,14 +126,14 @@ ${c}
126
126
  `);let a=null;if(n)try{if(a=o.extractJsonFromStream(c),!a)throw new Error("No valid result JSON found in output");console.log(`
127
127
  \u2705 Parsed Output:
128
128
  ${JSON.stringify(a,null,2)}
129
- `)}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 Nt();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=es(i,u,{cwd:t,env:d,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),f=setTimeout(()=>{console.log(`
129
+ `)}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 kt();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=ts(i,u,{cwd:t,env:d,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),f=setTimeout(()=>{console.log(`
130
130
  \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 S=Date.now()-y;S>1e4&&console.log(`\u23F3 AI agent is thinking... (${Math.floor(S/1e3)}s, ${l.length} bytes so far)`)}},1e4),b=()=>{clearTimeout(f),clearInterval(h),m&&!m.killed&&(m.kill("SIGTERM"),setTimeout(()=>{m.killed||m.kill("SIGKILL")},2e3))},w=()=>{console.log(`
131
131
 
132
- \u{1F6D1} Interrupted by user (Ctrl+C)`),b(),a(new Error("Interrupted by user"))};process.on("SIGINT",w);let E=new X;m.stdout.on("data",S=>{let $=S.toString();l+=$;let P=E.processChunk($);P&&(process.stdout.write(P,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),y=Date.now(),g+=P.length)}),m.on("close",S=>{process.off("SIGINT",w),clearTimeout(f),clearInterval(h);let $=E.flush();$&&process.stdout.write($),l=E.getRawText();let P=E.getResult();S===0?c({raw:l,extracted:P}):a(new Error(`Agent exited with code ${S}`))}),m.on("error",S=>{process.off("SIGINT",w),clearTimeout(f),clearInterval(h),a(new Error(`Failed to spawn agent: ${S.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,w=b?`${b}_${h}`:h;c=c||Date.now();let E=a.paths?.output||Rr;i=Rt(s,E,as,w),ts(i)||Nr(i,{recursive:!0})}let l=a.paths?.output||Rr,u=Rt(s,l,ls);Nr(Rt(s,l),{recursive:!0}),rs(u,JSON.stringify({sessionPath:i,sessionTimestamp:c||i.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
132
+ \u{1F6D1} Interrupted by user (Ctrl+C)`),b(),a(new Error("Interrupted by user"))};process.on("SIGINT",w);let E=new X;m.stdout.on("data",S=>{let $=S.toString();l+=$;let P=E.processChunk($);P&&(process.stdout.write(P,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),y=Date.now(),g+=P.length)}),m.on("close",S=>{process.off("SIGINT",w),clearTimeout(f),clearInterval(h);let $=E.flush();$&&process.stdout.write($),l=E.getRawText();let P=E.getResult();S===0?c({raw:l,extracted:P}):a(new Error(`Agent exited with code ${S}`))}),m.on("error",S=>{process.off("SIGINT",w),clearTimeout(f),clearInterval(h),a(new Error(`Failed to spawn agent: ${S.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,w=b?`${b}_${h}`:h;c=c||Date.now();let E=a.paths?.output||Lr;i=Nt(s,E,ls,w),rs(i)||Rr(i,{recursive:!0})}let l=a.paths?.output||Lr,u=Nt(s,l,cs);Rr(Nt(s,l),{recursive:!0}),ns(u,JSON.stringify({sessionPath:i,sessionTimestamp:c||i.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
133
133
  ${"=".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)}
134
- `);let d=await ns.loadContext(r.specPath||"",s,r.contextConfig||{}),m=new is({...r,sessionPath:i,sessionTimestamp:c,context:d}),g=await new ss(n).execute(this,m);return console.log(`
134
+ `);let d=await os.loadContext(r.specPath||"",s,r.contextConfig||{}),m=new as({...r,sessionPath:i,sessionTimestamp:c,context:d}),g=await new is(n).execute(this,m);return console.log(`
135
135
  ${"=".repeat(80)}`),console.log(`\u2705 Node ${e} completed`),console.log(`${"=".repeat(80)}
136
- `),{success:!0,output:g.output,outputPath:r.outputPath,state:g}}calculateOutputPath(e){let{specs:t,generated:r}=this.paths;if(!e)return`${r}/generated-test.spec.js`;let n=e.replace(new RegExp(`^${t}/`),"").replace(/\.[^.]+$/,".spec.js");return`${r}/${n}`.replace(/\/+/g,"/")}};function cs(o,e={}){let t=new Te(e);return t.buildGraph=function(){let r=new os;return o(r),r},e.onComplete&&(t.onComplete=e.onComplete),t}import{WorkflowGraph as lf,resolveWorkflowSession as cf,generateWorkflowSessionId as uf,clearInheritedSessionEnvForFreshRun as pf,shouldTrustInheritedSessionEnv as ff,readPinnedSessionPathFromEnv as df,syncProcessEnvToSession as mf}from"@zibby/agent-workflow";import{writeFileSync as Lr,existsSync as us,mkdirSync as ps}from"node:fs";import{join as Lt}from"node:path";var Mt=class o{static saveTitle(e,t){let r=e.state.sessionPath;if(!r)return;let n=o._findInState(e.state,"title")||o._findInState(e.state,"result");if(!(!n||typeof n!="string"))try{let s=Lt(r,"title.txt");Lr(s,n,"utf-8"),p.info(`Saved title to session: "${n}"`)}catch(s){console.warn("\u26A0\uFE0F Could not save title file:",s.message)}}static _findInState(e,t){for(let[,r]of Object.entries(e))if(r&&typeof r=="object"&&r[t]!==void 0)return r[t]}static async saveExecutionData(e){let t=e.state.sessionPath;if(t)for(let[r,n]of Object.entries(e.state)){if(!n||typeof n!="object")continue;let s=Array.isArray(n.actions)&&n.actions.length>0,i=typeof n.scriptPath=="string"&&n.scriptPath.trim().length>0;if(!(!s&&!i))try{let c=Lt(t,r);us(c)||ps(c,{recursive:!0});let a=Lt(c,"result.json");Lr(a,JSON.stringify(n,null,2),"utf-8"),p.info(`Saved execution data to ${r} folder`),await this.onNodeSaved(c,n)}catch(c){console.warn(`\u26A0\uFE0F Could not save execution data for ${r}:`,c.message)}}}static async onNodeSaved(e,t){}static logResult(e,t){let r=Object.entries(e.state).filter(([,i])=>i&&typeof i=="object"&&i.success!==void 0),n=r.length>0&&r.every(([,i])=>i.success),s=r.some(([,i])=>i.success===!1);if(n)p.info("Workflow completed successfully."),t&&p.info(`Output: ${t}`);else if(s){let i=r.filter(([,c])=>!c.success).map(([c])=>c);p.info(`Workflow completed with failures in: ${i.join(", ")}`),t&&p.info(`Output: ${t}`)}return n}static handle(e,t,r){return this.saveTitle(e,t),this.saveExecutionData(e),this.logResult(e,r)}};import{z as yf}from"zod/v3";import{AgentStrategy as ds}from"@zibby/agent-workflow";var Mr=[new pe,new oe,new ie,new ae,new ce];function Dr(o={}){let{state:e={},preferredAgent:t=null}=o,r=t||e.agentType||process.env.AGENT_TYPE;if(!r)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");p.debug(`Agent selection: requested=${r}`);let n=Mr.find(s=>s.getName()===r);if(!n)throw new Error(`Unknown agent '${r}'. Available: ${Mr.map(s=>s.getName()).join(", ")}`);if(p.debug(`Checking if ${r} can handle this environment...`),!n.canHandle(o)){let i={assistant:"Run `zibby login` to authenticate",claude:"Set ANTHROPIC_API_KEY in .env",cursor:"Install cursor-agent CLI or set CURSOR_API_KEY",codex:"Install codex CLI (npm i -g @openai/codex) and set OPENAI_API_KEY in .env",gemini:"Install gemini CLI (npm i -g @google/gemini-cli) and set GEMINI_API_KEY in .env"}[r]||"Check your environment configuration";throw new Error(`Agent '${r}' is not available. ${i}`)}return p.debug(`Using agent: ${n.getName()}`),n}async function fs(o,e={},t={}){try{await import("@zibby/skills")}catch{}try{await import("@zibby/skills-internal")}catch{}let r=Dr(e),n=e.state?.config||t.config||{},s=n.models||{},i=t.nodeName&&s[t.nodeName]||null,c=s.default||null,a=r.name,l=n.agent?.[a]?.model||null,u=i||c||l||t.model||null,d={...t,model:u,workspace:e.state?.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:n},m=d.skills||[],f=o;if(m.length>0&&!t.skipPromptFragments){let{getSkill:h}=await import("@zibby/agent-workflow"),b=m.map(w=>{let E=h(w)?.promptFragment;return typeof E=="function"?E():E}).filter(Boolean);b.length>0&&(f+=`
136
+ `),{success:!0,output:g.output,outputPath:r.outputPath,state:g}}calculateOutputPath(e){let{specs:t,generated:r}=this.paths;if(!e)return`${r}/generated-test.spec.js`;let n=e.replace(new RegExp(`^${t}/`),"").replace(/\.[^.]+$/,".spec.js");return`${r}/${n}`.replace(/\/+/g,"/")}};function us(o,e={}){let t=new Te(e);return t.buildGraph=function(){let r=new ss;return o(r),r},e.onComplete&&(t.onComplete=e.onComplete),t}import{WorkflowGraph as cf,resolveWorkflowSession as uf,generateWorkflowSessionId as pf,clearInheritedSessionEnvForFreshRun as ff,shouldTrustInheritedSessionEnv as df,readPinnedSessionPathFromEnv as mf,syncProcessEnvToSession as gf}from"@zibby/agent-workflow";import{writeFileSync as Mr,existsSync as ps,mkdirSync as fs}from"node:fs";import{join as Rt}from"node:path";var Lt=class o{static saveTitle(e,t){let r=e.state.sessionPath;if(!r)return;let n=o._findInState(e.state,"title")||o._findInState(e.state,"result");if(!(!n||typeof n!="string"))try{let s=Rt(r,"title.txt");Mr(s,n,"utf-8"),p.info(`Saved title to session: "${n}"`)}catch(s){console.warn("\u26A0\uFE0F Could not save title file:",s.message)}}static _findInState(e,t){for(let[,r]of Object.entries(e))if(r&&typeof r=="object"&&r[t]!==void 0)return r[t]}static async saveExecutionData(e){let t=e.state.sessionPath;if(t)for(let[r,n]of Object.entries(e.state)){if(!n||typeof n!="object")continue;let s=Array.isArray(n.actions)&&n.actions.length>0,i=typeof n.scriptPath=="string"&&n.scriptPath.trim().length>0;if(!(!s&&!i))try{let c=Rt(t,r);ps(c)||fs(c,{recursive:!0});let a=Rt(c,"result.json");Mr(a,JSON.stringify(n,null,2),"utf-8"),p.info(`Saved execution data to ${r} folder`),await this.onNodeSaved(c,n)}catch(c){console.warn(`\u26A0\uFE0F Could not save execution data for ${r}:`,c.message)}}}static async onNodeSaved(e,t){}static logResult(e,t){let r=Object.entries(e.state).filter(([,i])=>i&&typeof i=="object"&&i.success!==void 0),n=r.length>0&&r.every(([,i])=>i.success),s=r.some(([,i])=>i.success===!1);if(n)p.info("Workflow completed successfully."),t&&p.info(`Output: ${t}`);else if(s){let i=r.filter(([,c])=>!c.success).map(([c])=>c);p.info(`Workflow completed with failures in: ${i.join(", ")}`),t&&p.info(`Output: ${t}`)}return n}static handle(e,t,r){return this.saveTitle(e,t),this.saveExecutionData(e),this.logResult(e,r)}};import{z as bf}from"zod/v3";import{AgentStrategy as ms}from"@zibby/agent-workflow";var Dr=[new pe,new oe,new ie,new ae,new ce];function Ur(o={}){let{state:e={},preferredAgent:t=null}=o,r=t||e.agentType||process.env.AGENT_TYPE;if(!r)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");p.debug(`Agent selection: requested=${r}`);let n=Dr.find(s=>s.getName()===r);if(!n)throw new Error(`Unknown agent '${r}'. Available: ${Dr.map(s=>s.getName()).join(", ")}`);if(p.debug(`Checking if ${r} can handle this environment...`),!n.canHandle(o)){let i={assistant:"Run `zibby login` to authenticate",claude:"Set ANTHROPIC_API_KEY in .env",cursor:"Install cursor-agent CLI or set CURSOR_API_KEY",codex:"Install codex CLI (npm i -g @openai/codex) and set OPENAI_API_KEY in .env",gemini:"Install gemini CLI (npm i -g @google/gemini-cli) and set GEMINI_API_KEY in .env"}[r]||"Check your environment configuration";throw new Error(`Agent '${r}' is not available. ${i}`)}return p.debug(`Using agent: ${n.getName()}`),n}async function ds(o,e={},t={}){try{await import("@zibby/skills")}catch{}try{await import("@zibby/skills-internal")}catch{}let r=Ur(e),n=e.state?.config||t.config||{},s=n.models||{},i=t.nodeName&&s[t.nodeName]||null,c=s.default||null,a=r.name,l=n.agent?.[a]?.model||null,u=i||c||l||t.model||null,d={...t,model:u,workspace:e.state?.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:n},m=d.skills||[],f=o;if(m.length>0&&!t.skipPromptFragments){let{getSkill:h}=await import("@zibby/agent-workflow"),b=m.map(w=>{let E=h(w)?.promptFragment;return typeof E=="function"?E():E}).filter(Boolean);b.length>0&&(f+=`
137
137
 
138
138
  ${b.join(`
139
139
 
@@ -150,13 +150,13 @@ ${b.join(`
150
150
 
151
151
  ${y}
152
152
  `),p.debug(`Prompt length: ${f.length} chars`),process.env.STAGE!=="prod"&&p.debug(`Full prompt:
153
- ${f}`),r.invoke(f,d)}import{SKILL_IDS as Ef}from"@zibby/skill-ids";import{registerSkill as vf,getSkill as Af,hasSkill as Of,getAllSkills as $f,listSkillIds as If}from"@zibby/agent-workflow";var ms={READ_FILE:"read_file",WRITE_FILE:"write_file",LIST_DIRECTORY:"list_directory",RUN_COMMAND:"run_command",OPEN_URL:"open_url",WAIT:"wait"},gs={LIST_PROJECTS:"jira_list_projects",SEARCH:"jira_search",GET_ISSUE:"jira_get_issue",CREATE_ISSUE:"jira_create_issue",LIST_SPRINTS:"jira_list_sprints",GET_SPRINT_ISSUES:"jira_get_sprint_issues",GET_COMMENTS:"jira_get_comments",ADD_COMMENT:"jira_add_comment",EDIT_ISSUE:"jira_edit_issue",TRANSITION_ISSUE:"jira_transition_issue"},hs={GET_USER:"github_get_user",LIST_ORGS:"github_list_orgs",LIST_REPOS:"github_list_repos",CLONE:"github_clone",SEARCH_REPOS:"github_search_repos",SEARCH_ISSUES:"github_search_issues",SEARCH_CODE:"github_search_code",GET_PR:"github_get_pr",GET_PR_DIFF:"github_get_pr_diff",LIST_PR_FILES:"github_list_pr_files",LIST_PR_COMMENTS:"github_list_pr_comments",LIST_COMMITS:"github_list_commits",GET_COMMIT:"github_get_commit",GET_FILE:"github_get_file",CREATE_ISSUE:"github_create_issue"},ys={LIST_CHANNELS:"slack_list_channels",POST_MESSAGE:"slack_post_message",REPLY_TO_THREAD:"slack_reply_to_thread",ADD_REACTION:"slack_add_reaction",GET_CHANNEL_HISTORY:"slack_get_channel_history",GET_THREAD_REPLIES:"slack_get_thread_replies",GET_USERS:"slack_get_users",GET_USER_PROFILE:"slack_get_user_profile"},bs={GENERATE:"run_generate",TEST:"run_test",STATUS:"run_status",CANCEL:"run_cancel",WAIT:"run_wait",ARTIFACTS:"run_artifacts",LIST_SPECS:"list_specs"},Ss={GET_TEST_HISTORY:"memory_get_test_history",GET_SELECTORS:"memory_get_selectors",GET_PAGE_MODEL:"memory_get_page_model",GET_NAVIGATION:"memory_get_navigation",SAVE_INSIGHT:"memory_save_insight"},_s={STORE:"memory_store",RECALL:"memory_recall",BRIEF:"memory_brief",END_SESSION:"memory_end_session",TASK_LOG:"task_log",TASK_HISTORY:"task_history"},ws={INSTALL:"install_skill",UNINSTALL:"uninstall_skill",LIST_AVAILABLE:"list_available_skills"},Ic={...ms,...gs,...hs,...ys,...bs,...Ss,..._s,...ws};import{existsSync as xs,readFileSync as Es}from"node:fs";import{homedir as Ts}from"node:os";import{join as vs}from"node:path";var mt=new Map,As={github:"GITHUB_TOKEN",gitlab:"GITLAB_TOKEN",sentry:"SENTRY_AUTH_TOKEN",slack:"SLACK_BOT_TOKEN"};function Os(){let o=process.env.ZIBBY_SELF_HOST;return o!=null&&o!==""&&o!=="0"&&o.toLowerCase()!=="false"}function $s(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let o=vs(Ts(),".zibby","config.json");return xs(o)&&JSON.parse(Es(o,"utf-8")).sessionToken||null}catch{return null}}function Is(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app"}async function Dt(o){if(Os()){let a=As[o];if(a&&process.env[a])return{token:process.env[a]}}let e=Date.now(),t=mt.get(o);if(t&&t.expiresAt>e)return t.data;let r=$s();if(!r)throw new Error("No session token. Run `zibby login` first.");let n=`${Is()}/integrations/token/${o}`,s=await fetch(n,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!s.ok){let a=await s.text().catch(()=>"");throw s.status===404?new Error(`${o} is not connected. Connect it at https://studio.zibby.dev/integrations`):s.status===401||s.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Failed to resolve ${o} token (${s.status}): ${a}`)}let i=await s.json();if(!i||typeof i!="object")throw new Error(`Invalid response from ${o} token endpoint: expected object, got ${typeof i}`);if(o==="jira"){if(!i.token||typeof i.token!="string")throw new Error(`Invalid jira token response: token is ${typeof i.token}, expected string`);if(!i.cloudId)throw new Error("Invalid jira token response: missing cloudId")}else if(o==="github"&&(!i.token||typeof i.token!="string"))throw new Error(`Invalid github token response: token is ${typeof i.token}, expected string`);let c=((i.expiresInSec||3e3)-120)*1e3;return mt.set(o,{data:i,expiresAt:e+c}),i}function Cs(o){o?mt.delete(o):mt.clear()}var Ps=Object.freeze(["github.com","gitlab.com"]);function ve(o){try{return new URL(o).hostname.toLowerCase()}catch{return""}}function Ur(o=process.env){let e=o&&(o.GITLAB_URL||o.GITLAB_INSTANCE_URL)||"";return ve(e)}function gt(o={}){if(o.gitlabHost){let e=String(o.gitlabHost).trim().toLowerCase();return e?e.includes("://")?ve(e):e.replace(/:\d+$/,""):""}return Ur()}function jr(o,e={}){let t=ve(o);if(!t)return!1;if(t==="github.com"||t==="gitlab.com")return!0;let r=gt(e);return!!(r&&t===r)}function Br(o,e={}){if(o==="github.com")return"github";if(o==="gitlab.com")return"gitlab";let t=gt(e);return t&&o===t?"gitlab":null}function Fr(o,e,t={}){if(!o||!e)return o;let r=ve(o);if(!r)return o;if(r==="github.com")return o.replace(/^https:\/\/(?:[^@/]+@)?github\.com(?=[:/]|$)/i,`https://x-access-token:${e}@github.com`);if(r==="gitlab.com")return o.replace(/^https:\/\/(?:[^@/]+@)?gitlab\.com(?=[:/]|$)/i,`https://oauth2:${e}@gitlab.com`);let n=gt(t);if(n&&r===n){let s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^https:\\/\\/(?:[^@/]+@)?${s}(?=[:/]|$)`,"i");return o.replace(i,`https://oauth2:${e}@${n}`)}return o}function Gr(o){return o&&String(o).replace(/^(https:\/\/)[^@/]+@/i,"$1")}function Kr(o,e){let t=o==null?"":String(o);return e&&(t=t.split(e).join("***")),t=t.replace(/(https?:\/\/)(?:x-access-token|oauth2):[^@\s/]+@/gi,"$1"),t=t.replace(/(https?:\/\/)[^@\s/:]+:[^@\s/]+@/gi,"$1"),t}async function ks(o,e,t){try{await o("git",["remote","set-url","origin",Gr(t)],e)}catch(r){console.warn(`\u26A0\uFE0F could not scrub token from origin remote (continuing): ${r?.message||r}`)}}async function Ns({run:o,repoPath:e,repoUrl:t,branch:r,token:n,resolveToken:s=Dt,gitlabHost:i}={}){if(typeof o!="function")throw new Error("securePush: `run` (a spawn wrapper resolving {code,stdout,stderr}) is required");if(!r)throw new Error("securePush: `branch` is required");let c=gt({gitlabHost:i}),a=ve(t),l=jr(t,{gitlabHost:c}),u=n||"";if(!u&&l&&typeof s=="function"){let g=Br(a,{gitlabHost:c});if(g)try{u=(await s(g))?.token||""}catch{}}else!u&&!l&&console.warn(`\u26A0\uFE0F push target host '${a||"(unparseable)"}' is not a trusted VCS host \u2014 refusing to mint a token`);let d=u&&l,m=d?Fr(t,u,{gitlabHost:c}):"origin",f=await o("git",["push",m,r],e);if(!f||f.code!==0){let g=Kr(f&&f.stderr||"",u);throw new Error(`git push failed (exit ${f?f.code:"?"}): ${String(g).slice(-500)}`)}return{code:f.code,stdout:f.stdout,stderr:f.stderr,pushedAuthed:!!d,target:d?"<authed>":"origin"}}import{readdir as Rs,access as Jr,copyFile as Ls,constants as zr}from"fs/promises";import{join as ht,relative as Ms}from"node:path";async function Ds(o={}){let{testResultsDir:e="test-results",testsDir:t="tests",projectRoot:r=process.cwd(),verbose:n=!0}=o;n&&console.log(`\u{1F3A5} Organizing test videos...
154
- `);let s=ht(r,e),i=ht(r,t);try{let c=await Rs(s),a=0;for(let l of c){if(l.startsWith("."))continue;let u=ht(s,l,"video.webm");try{await Jr(u,zr.F_OK)}catch{continue}let d=l.replace(/-chromium$/,"").replace(/-firefox$/,"").replace(/-webkit$/,""),m=await Us(i,d);if(m){let f=m.replace(/\.spec\.(js|ts)$/,".spec.webm");await Ls(u,f),n&&console.log(`\u2705 ${Ms(r,f)}`),a++}else n&&console.log(`\u26A0\uFE0F Could not find test file for: ${l}`)}return n&&(console.log(`
155
- \u{1F3AC} Organized ${a} video(s)`),console.log(`\u{1F4C2} Videos are now next to their test files in ${t}/`)),{movedCount:a,success:!0}}catch(c){return n&&console.error("\u274C Error organizing videos:",c.message),{movedCount:0,success:!1,error:c.message}}}async function Us(o,e){let t=e.split("-");for(let r=t.length;r>0;r--){let s=t.slice(0,r).join("/");for(let i of["js","ts"]){let c=ht(o,`${s}.spec.${i}`);try{return await Jr(c,zr.F_OK),c}catch{}}}return null}var We=class{constructor(e,t={}){this.apiKey=e,this.baseUrl=t.baseUrl||process.env.ZIBBY_API_URL||"https://api-prod.zibby.app",this.enabled=!!e}isEnabled(){return this.enabled}};function Yr(){let o=process.env.ZIBBY_API_KEY;return new We(o)}import{execSync as Wr}from"node:child_process";import{existsSync as js,mkdirSync as Bs}from"node:fs";import{join as Fs}from"node:path";function Hr(o,e,t,r,n="clone"){try{o(`git -C "${e}" remote set-url origin "${t}"`,{stdio:"pipe"})}catch(s){let i=String(s&&s.message||s);r&&(i=i.split(r).join("***")),console.error(`[${n}] WARNING: failed to strip token from .git/config: ${i}`)}}async function Gs(o={}){let{baseDir:e="/workspace/repos",repos:t=null,depth:r=1,branch:n=null}=o,s=process.env.REPOS;if(!s)throw new Error("REPOS environment variable not set. Are you running in a Zibby workflow container?");let i;try{i=JSON.parse(s)}catch(l){throw new Error(`Failed to parse REPOS env var: ${l.message}`,{cause:l})}if(!Array.isArray(i)||i.length===0)throw new Error("No repositories configured for this project");let c=t?i.filter(l=>t.includes(l.name)):i;if(c.length===0)throw new Error(`No matching repositories found. Available: ${i.map(l=>l.name).join(", ")}`);js(e)||Bs(e,{recursive:!0});let a={};return await Promise.all(c.map(async l=>{let u=l.provider||"github",d=u==="gitlab"?process.env.GITLAB_TOKEN:process.env.GITHUB_TOKEN;if(!d){console.error(`${u.toUpperCase()}_TOKEN not set, skipping ${l.name}`),a[l.name]=null;return}let m=l.name.replace(/\//g,"-"),f=Fs(e,m),g=l.cloneUrl||l.url;if(!g){console.error(`Repository "${l.name}" has no clone URL`),a[l.name]=null;return}let y;u==="gitlab"?y=g.replace(/^https:\/\//,`https://oauth2:${d}@`):y=g.replace(/^https:\/\//,`https://x-access-token:${d}@`);let h=["clone"];r>0&&h.push("--depth",r.toString()),n&&h.push("--branch",n),h.push(y,f);let b=`git ${h.join(" ")}`;console.log(`Cloning ${l.name} (${u}) to ${f}...`);try{Wr(b,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),Hr(Wr,f,g,d,`cloneRepo:${l.name}`),console.log(`Repository ${l.name} cloned successfully`),a[l.name]=f}catch(w){let E=w.message.replace(d,"***").replace(y,g);console.error(`Failed to clone ${l.name}: ${E}`),a[l.name]=null}})),a}var Vr=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Ks(o){return typeof o=="string"&&Vr.test(o)}var Zr=Ks;function Js(o){if(!Zr(o))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(o.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(o.slice(9,13),16))>>>8,e&255,(e=parseInt(o.slice(14,18),16))>>>8,e&255,(e=parseInt(o.slice(19,23),16))>>>8,e&255,(e=parseInt(o.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}var Ut=Js;var J=[];for(let o=0;o<256;++o)J.push((o+256).toString(16).slice(1));function Xr(o,e=0){return(J[o[e+0]]+J[o[e+1]]+J[o[e+2]]+J[o[e+3]]+"-"+J[o[e+4]]+J[o[e+5]]+"-"+J[o[e+6]]+J[o[e+7]]+"-"+J[o[e+8]]+J[o[e+9]]+"-"+J[o[e+10]]+J[o[e+11]]+J[o[e+12]]+J[o[e+13]]+J[o[e+14]]+J[o[e+15]]).toLowerCase()}function zs(o){o=unescape(encodeURIComponent(o));let e=new Uint8Array(o.length);for(let t=0;t<o.length;++t)e[t]=o.charCodeAt(t);return e}var qr="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Qr="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function jt(o,e,t,r,n,s){let i=typeof t=="string"?zs(t):t,c=typeof r=="string"?Ut(r):r;if(typeof r=="string"&&(r=Ut(r)),r?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+i.length);if(a.set(c),a.set(i,c.length),a=e(a),a[6]=a[6]&15|o,a[8]=a[8]&63|128,n){if(s=s||0,s<0||s+16>n.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let l=0;l<16;++l)n[s+l]=a[l];return n}return Xr(a)}import{createHash as Ys}from"crypto";function Hs(o){return Array.isArray(o)?o=Buffer.from(o):typeof o=="string"&&(o=Buffer.from(o,"utf8")),Ys("sha1").update(o).digest()}var en=Hs;function Bt(o,e,t,r){return jt(80,en,o,e,t,r)}Bt.DNS=qr;Bt.URL=Qr;var Ft=Bt;var tn="@zibby/core ZibbySessionStore/1",Ve=class{constructor({apiUrl:e,apiKey:t,workflowUuid:r,fetchImpl:n=globalThis.fetch}){if(!e)throw new Error("ZibbySessionStore: apiUrl is required");if(!t)throw new Error("ZibbySessionStore: apiKey is required");if(!r)throw new Error("ZibbySessionStore: workflowUuid is required");this._apiUrl=String(e).replace(/\/+$/,""),this._apiKey=t,this._workflowUuid=r,this._fetch=n}async append(e,t){if(!Array.isArray(t)||t.length===0)return;let r=`${this._apiUrl}/workflows/${encodeURIComponent(this._workflowUuid)}/sessions/${encodeURIComponent(e.sessionId)}/append`,n=await this._fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this._apiKey}`,"Content-Type":"application/json","User-Agent":tn},body:JSON.stringify({entries:t})});if(!n.ok)throw new Error(`ZibbySessionStore.append HTTP ${n.status}`)}async load(e){let t=`${this._apiUrl}/workflows/${encodeURIComponent(this._workflowUuid)}/sessions/${encodeURIComponent(e.sessionId)}`,r;try{r=await this._fetch(t,{method:"GET",headers:{Authorization:`Bearer ${this._apiKey}`,"User-Agent":tn}})}catch{return null}if(r.status===404||!r.ok)return null;let n;try{n=await r.json()}catch{return null}let s=Array.isArray(n?.entries)?n.entries:null;return s&&s.length>0?s:null}};var Ws="6ba7b810-9dad-11d1-80b4-00c04fd430c8",rn=new Set;function Vs(){return(process.env.PROGRESS_API_URL||process.env.ZIBBY_API_BASE||"").replace(/\/executions\/?$/,"").replace(/\/+$/,"")}function nn({namespace:o=Ws}={}){return{id:"session",description:"Persist agent conversation state across invocations (Claude-only in v1)",envKeys:[],tools:[],invokeAgentOptions(e,t){let r=e?.conversationId,n=e?.workflowUuid;if(!r||!n)return null;let s=t?.agentType;if(s&&s!=="claude")return rn.has(s)||(console.warn(`[SKILLS.SESSION] agent type '${s}' does not support native sessions \u2014 node running stateless`),rn.add(s)),null;let i=Ft(`${n}:${r}`,o),c=Vs(),a=process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN,l=null;if(c&&a)try{l=new Ve({apiUrl:c,apiKey:a,workflowUuid:n})}catch(m){console.warn(`[SKILLS.SESSION] failed to build SessionStore: ${m.message}`),l=null}return e.resetConversation?{sessionId:i,resume:i,forkSession:!0,...l&&{sessionStore:l}}:e.hasPriorSession?{resume:i,...l&&{sessionStore:l}}:{sessionId:i,...l&&{sessionStore:l}}}}}import{spawn as on}from"node:child_process";import{readFileSync as Zs,writeFileSync as Xs,existsSync as yt}from"node:fs";import{homedir as sn}from"node:os";import{join as Ae}from"node:path";async function qs(){let o=Ae(sn(),".local/share/cursor-agent/versions");if(!yt(o))throw new Error(`cursor-agent not found at ${o}. Please install cursor-agent first.`);return console.log(`\u{1F527} Patching cursor-agent for CI/CD...
156
- `),new Promise((e,t)=>{let r=Ae(__dirname,"../../scripts/patch-cursor-mcp.py");if(!yt(r)){t(new Error("Patch script not found"));return}let n=on("python3",[r],{stdio:"inherit"});n.on("close",s=>{s===0?e({success:!0}):t(new Error(`Patch failed with code ${s}`))}),n.on("error",s=>{t(s)})})}function Qs(){let o=Ae(sn(),".local/share/cursor-agent/versions");if(!yt(o))return{patched:!1,installed:!1};try{let e=An("fs").readdirSync(o);if(e.length===0)return{patched:!1,installed:!1};let t=e.sort().reverse()[0],r=Ae(o,t,"index.js");return yt(r)?{patched:Zs(r,"utf-8").includes("AUTO-APPROVE MCP TOOLS FOR CI/CD"),installed:!0,path:r}:{patched:!1,installed:!1}}catch(e){return{patched:!1,installed:!1,error:e.message}}}async function ei(o){return console.log(`\u{1F511} Getting MCP approval keys...
157
- `),new Promise((e,t)=>{let r=on("cursor-agent",["mcp","list"],{cwd:o,stdio:"pipe"}),n="";r.stdout.on("data",s=>{n+=s.toString(),process.stdout.write(s)}),r.stderr.on("data",s=>{process.stderr.write(s)}),r.on("close",s=>{if(s===0){let i=ti(n);e({success:!0,keys:i,output:n})}else t(new Error(`Failed to get approval keys (exit code ${s})`))}),r.on("error",s=>{t(s)})})}function ti(o){let e={},t=/🔑 APPROVAL KEY:\s+(\S+)\s+=>\s+(\S+)/g,r;for(;(r=t.exec(o))!==null;)e[r[1]]=r[2];return e}function ri(o,e){let t=Ae(o,".cursor/projects"),r=Ae(t,"mcp-approvals.json");Xs(r,JSON.stringify(e,null,2)),console.log(`
153
+ ${f}`),r.invoke(f,d)}import{SKILL_IDS as Tf}from"@zibby/skill-ids";import{registerSkill as Af,getSkill as Of,hasSkill as $f,getAllSkills as If,listSkillIds as Cf}from"@zibby/agent-workflow";var gs={READ_FILE:"read_file",WRITE_FILE:"write_file",LIST_DIRECTORY:"list_directory",RUN_COMMAND:"run_command",OPEN_URL:"open_url",WAIT:"wait"},hs={LIST_PROJECTS:"jira_list_projects",SEARCH:"jira_search",GET_ISSUE:"jira_get_issue",CREATE_ISSUE:"jira_create_issue",LIST_SPRINTS:"jira_list_sprints",GET_SPRINT_ISSUES:"jira_get_sprint_issues",GET_COMMENTS:"jira_get_comments",ADD_COMMENT:"jira_add_comment",EDIT_ISSUE:"jira_edit_issue",TRANSITION_ISSUE:"jira_transition_issue"},ys={GET_USER:"github_get_user",LIST_ORGS:"github_list_orgs",LIST_REPOS:"github_list_repos",CLONE:"github_clone",SEARCH_REPOS:"github_search_repos",SEARCH_ISSUES:"github_search_issues",SEARCH_CODE:"github_search_code",GET_PR:"github_get_pr",GET_PR_DIFF:"github_get_pr_diff",LIST_PR_FILES:"github_list_pr_files",LIST_PR_COMMENTS:"github_list_pr_comments",LIST_COMMITS:"github_list_commits",GET_COMMIT:"github_get_commit",GET_FILE:"github_get_file",CREATE_ISSUE:"github_create_issue"},bs={LIST_CHANNELS:"slack_list_channels",POST_MESSAGE:"slack_post_message",REPLY_TO_THREAD:"slack_reply_to_thread",ADD_REACTION:"slack_add_reaction",GET_CHANNEL_HISTORY:"slack_get_channel_history",GET_THREAD_REPLIES:"slack_get_thread_replies",GET_USERS:"slack_get_users",GET_USER_PROFILE:"slack_get_user_profile"},Ss={GENERATE:"run_generate",TEST:"run_test",STATUS:"run_status",CANCEL:"run_cancel",WAIT:"run_wait",ARTIFACTS:"run_artifacts",LIST_SPECS:"list_specs"},_s={GET_TEST_HISTORY:"memory_get_test_history",GET_SELECTORS:"memory_get_selectors",GET_PAGE_MODEL:"memory_get_page_model",GET_NAVIGATION:"memory_get_navigation",SAVE_INSIGHT:"memory_save_insight"},ws={STORE:"memory_store",RECALL:"memory_recall",BRIEF:"memory_brief",END_SESSION:"memory_end_session",TASK_LOG:"task_log",TASK_HISTORY:"task_history"},xs={INSTALL:"install_skill",UNINSTALL:"uninstall_skill",LIST_AVAILABLE:"list_available_skills"},Cc={...gs,...hs,...ys,...bs,...Ss,..._s,...ws,...xs};import{existsSync as Es,readFileSync as Ts}from"node:fs";import{homedir as vs}from"node:os";import{join as As}from"node:path";var dt=new Map,Os={github:"GITHUB_TOKEN",gitlab:"GITLAB_TOKEN",sentry:"SENTRY_AUTH_TOKEN",slack:"SLACK_BOT_TOKEN"};function $s(){let o=process.env.ZIBBY_SELF_HOST;return o!=null&&o!==""&&o!=="0"&&o.toLowerCase()!=="false"}function Is(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let o=As(vs(),".zibby","config.json");return Es(o)&&JSON.parse(Ts(o,"utf-8")).sessionToken||null}catch{return null}}function Cs(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app"}async function Mt(o){if($s()){let a=Os[o];if(a&&process.env[a])return{token:process.env[a]}}let e=Date.now(),t=dt.get(o);if(t&&t.expiresAt>e)return t.data;let r=Is();if(!r)throw new Error("No session token. Run `zibby login` first.");let n=`${Cs()}/integrations/token/${o}`,s=await fetch(n,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!s.ok){let a=await s.text().catch(()=>"");throw s.status===404?new Error(`${o} is not connected. Connect it at https://studio.zibby.dev/integrations`):s.status===401||s.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Failed to resolve ${o} token (${s.status}): ${a}`)}let i=await s.json();if(!i||typeof i!="object")throw new Error(`Invalid response from ${o} token endpoint: expected object, got ${typeof i}`);if(o==="jira"){if(!i.token||typeof i.token!="string")throw new Error(`Invalid jira token response: token is ${typeof i.token}, expected string`);if(!i.cloudId)throw new Error("Invalid jira token response: missing cloudId")}else if(o==="github"&&(!i.token||typeof i.token!="string"))throw new Error(`Invalid github token response: token is ${typeof i.token}, expected string`);let c=((i.expiresInSec||3e3)-120)*1e3;return dt.set(o,{data:i,expiresAt:e+c}),i}function Ps(o){o?dt.delete(o):dt.clear()}var ks=Object.freeze(["github.com","gitlab.com"]);function Dt(o){try{return new URL(o).hostname.toLowerCase()}catch{return""}}function Ut(o){if(typeof o!="string"||o===""||/[\\\x00-\x20\x7f]/.test(o))return"";let e;try{e=new URL(o)}catch{return""}return e.protocol!=="https:"?"":e.hostname.toLowerCase()}function jr(o=process.env){let e=o&&(o.GITLAB_URL||o.GITLAB_INSTANCE_URL)||"";return Dt(e)}function mt(o={}){if(o.gitlabHost){let e=String(o.gitlabHost).trim().toLowerCase();return e?e.includes("://")?Dt(e):e.replace(/:\d+$/,""):""}return jr()}function Br(o,e={}){let t=Ut(o);if(!t)return!1;if(t==="github.com"||t==="gitlab.com")return!0;let r=mt(e);return!!(r&&t===r)}function Fr(o,e={}){if(o==="github.com")return"github";if(o==="gitlab.com")return"gitlab";let t=mt(e);return t&&o===t?"gitlab":null}function Gr(o,e,t={}){if(!o||!e)return o;let r=Ut(o);if(!r)return o;if(r==="github.com")return o.replace(/^https:\/\/(?:[^@/]+@)?github\.com(?=[:/]|$)/i,`https://x-access-token:${e}@github.com`);if(r==="gitlab.com")return o.replace(/^https:\/\/(?:[^@/]+@)?gitlab\.com(?=[:/]|$)/i,`https://oauth2:${e}@gitlab.com`);let n=mt(t);if(n&&r===n){let s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^https:\\/\\/(?:[^@/]+@)?${s}(?=[:/]|$)`,"i");return o.replace(i,`https://oauth2:${e}@${n}`)}return o}function Kr(o){return o&&String(o).replace(/^(https:\/\/)[^@/]+@/i,"$1")}function Jr(o,e){let t=o==null?"":String(o);return e&&(t=t.split(e).join("***")),t=t.replace(/(https?:\/\/)(?:x-access-token|oauth2):[^@\s/]+@/gi,"$1"),t=t.replace(/(https?:\/\/)[^@\s/:]+:[^@\s/]+@/gi,"$1"),t}async function Ns(o,e,t){try{await o("git",["remote","set-url","origin",Kr(t)],e)}catch(r){console.warn(`\u26A0\uFE0F could not scrub token from origin remote (continuing): ${r?.message||r}`)}}async function Rs({run:o,repoPath:e,repoUrl:t,branch:r,token:n,resolveToken:s=Mt,gitlabHost:i}={}){if(typeof o!="function")throw new Error("securePush: `run` (a spawn wrapper resolving {code,stdout,stderr}) is required");if(!r)throw new Error("securePush: `branch` is required");let c=mt({gitlabHost:i}),a=Ut(t),l=Br(t,{gitlabHost:c}),u=n||"";if(!u&&l&&typeof s=="function"){let g=Fr(a,{gitlabHost:c});if(g)try{u=(await s(g))?.token||""}catch{}}else!u&&!l&&console.warn(`\u26A0\uFE0F push target host '${a||"(unparseable)"}' is not a trusted VCS host \u2014 refusing to mint a token`);let d=u&&l,m=d?Gr(t,u,{gitlabHost:c}):"origin",f=await o("git",["push",m,r],e);if(!f||f.code!==0){let g=Jr(f&&f.stderr||"",u);throw new Error(`git push failed (exit ${f?f.code:"?"}): ${String(g).slice(-500)}`)}return{code:f.code,stdout:f.stdout,stderr:f.stderr,pushedAuthed:!!d,target:d?"<authed>":"origin"}}import{readdir as Ls,access as zr,copyFile as Ms,constants as Yr}from"fs/promises";import{join as gt,relative as Ds}from"node:path";async function Us(o={}){let{testResultsDir:e="test-results",testsDir:t="tests",projectRoot:r=process.cwd(),verbose:n=!0}=o;n&&console.log(`\u{1F3A5} Organizing test videos...
154
+ `);let s=gt(r,e),i=gt(r,t);try{let c=await Ls(s),a=0;for(let l of c){if(l.startsWith("."))continue;let u=gt(s,l,"video.webm");try{await zr(u,Yr.F_OK)}catch{continue}let d=l.replace(/-chromium$/,"").replace(/-firefox$/,"").replace(/-webkit$/,""),m=await js(i,d);if(m){let f=m.replace(/\.spec\.(js|ts)$/,".spec.webm");await Ms(u,f),n&&console.log(`\u2705 ${Ds(r,f)}`),a++}else n&&console.log(`\u26A0\uFE0F Could not find test file for: ${l}`)}return n&&(console.log(`
155
+ \u{1F3AC} Organized ${a} video(s)`),console.log(`\u{1F4C2} Videos are now next to their test files in ${t}/`)),{movedCount:a,success:!0}}catch(c){return n&&console.error("\u274C Error organizing videos:",c.message),{movedCount:0,success:!1,error:c.message}}}async function js(o,e){let t=e.split("-");for(let r=t.length;r>0;r--){let s=t.slice(0,r).join("/");for(let i of["js","ts"]){let c=gt(o,`${s}.spec.${i}`);try{return await zr(c,Yr.F_OK),c}catch{}}}return null}var He=class{constructor(e,t={}){this.apiKey=e,this.baseUrl=t.baseUrl||process.env.ZIBBY_API_URL||"https://api-prod.zibby.app",this.enabled=!!e}isEnabled(){return this.enabled}};function Hr(){let o=process.env.ZIBBY_API_KEY;return new He(o)}import{execSync as Wr}from"node:child_process";import{existsSync as Bs,mkdirSync as Fs}from"node:fs";import{join as Gs}from"node:path";function Vr(o,e,t,r,n="clone"){try{o(`git -C "${e}" remote set-url origin "${t}"`,{stdio:"pipe"})}catch(s){let i=String(s&&s.message||s);r&&(i=i.split(r).join("***")),console.error(`[${n}] WARNING: failed to strip token from .git/config: ${i}`)}}async function Ks(o={}){let{baseDir:e="/workspace/repos",repos:t=null,depth:r=1,branch:n=null}=o,s=process.env.REPOS;if(!s)throw new Error("REPOS environment variable not set. Are you running in a Zibby workflow container?");let i;try{i=JSON.parse(s)}catch(l){throw new Error(`Failed to parse REPOS env var: ${l.message}`,{cause:l})}if(!Array.isArray(i)||i.length===0)throw new Error("No repositories configured for this project");let c=t?i.filter(l=>t.includes(l.name)):i;if(c.length===0)throw new Error(`No matching repositories found. Available: ${i.map(l=>l.name).join(", ")}`);Bs(e)||Fs(e,{recursive:!0});let a={};return await Promise.all(c.map(async l=>{let u=l.provider||"github",d=u==="gitlab"?process.env.GITLAB_TOKEN:process.env.GITHUB_TOKEN;if(!d){console.error(`${u.toUpperCase()}_TOKEN not set, skipping ${l.name}`),a[l.name]=null;return}let m=l.name.replace(/\//g,"-"),f=Gs(e,m),g=l.cloneUrl||l.url;if(!g){console.error(`Repository "${l.name}" has no clone URL`),a[l.name]=null;return}let y;u==="gitlab"?y=g.replace(/^https:\/\//,`https://oauth2:${d}@`):y=g.replace(/^https:\/\//,`https://x-access-token:${d}@`);let h=["clone"];r>0&&h.push("--depth",r.toString()),n&&h.push("--branch",n),h.push(y,f);let b=`git ${h.join(" ")}`;console.log(`Cloning ${l.name} (${u}) to ${f}...`);try{Wr(b,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),Vr(Wr,f,g,d,`cloneRepo:${l.name}`),console.log(`Repository ${l.name} cloned successfully`),a[l.name]=f}catch(w){let E=w.message.replace(d,"***").replace(y,g);console.error(`Failed to clone ${l.name}: ${E}`),a[l.name]=null}})),a}var Zr=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Js(o){return typeof o=="string"&&Zr.test(o)}var Xr=Js;function zs(o){if(!Xr(o))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(o.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(o.slice(9,13),16))>>>8,e&255,(e=parseInt(o.slice(14,18),16))>>>8,e&255,(e=parseInt(o.slice(19,23),16))>>>8,e&255,(e=parseInt(o.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}var jt=zs;var J=[];for(let o=0;o<256;++o)J.push((o+256).toString(16).slice(1));function qr(o,e=0){return(J[o[e+0]]+J[o[e+1]]+J[o[e+2]]+J[o[e+3]]+"-"+J[o[e+4]]+J[o[e+5]]+"-"+J[o[e+6]]+J[o[e+7]]+"-"+J[o[e+8]]+J[o[e+9]]+"-"+J[o[e+10]]+J[o[e+11]]+J[o[e+12]]+J[o[e+13]]+J[o[e+14]]+J[o[e+15]]).toLowerCase()}function Ys(o){o=unescape(encodeURIComponent(o));let e=new Uint8Array(o.length);for(let t=0;t<o.length;++t)e[t]=o.charCodeAt(t);return e}var Qr="6ba7b810-9dad-11d1-80b4-00c04fd430c8",en="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Bt(o,e,t,r,n,s){let i=typeof t=="string"?Ys(t):t,c=typeof r=="string"?jt(r):r;if(typeof r=="string"&&(r=jt(r)),r?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+i.length);if(a.set(c),a.set(i,c.length),a=e(a),a[6]=a[6]&15|o,a[8]=a[8]&63|128,n){if(s=s||0,s<0||s+16>n.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let l=0;l<16;++l)n[s+l]=a[l];return n}return qr(a)}import{createHash as Hs}from"crypto";function Vs(o){return Array.isArray(o)?o=Buffer.from(o):typeof o=="string"&&(o=Buffer.from(o,"utf8")),Hs("sha1").update(o).digest()}var tn=Vs;function Ft(o,e,t,r){return Bt(80,tn,o,e,t,r)}Ft.DNS=Qr;Ft.URL=en;var Gt=Ft;var rn="@zibby/core ZibbySessionStore/1",Ve=class{constructor({apiUrl:e,apiKey:t,workflowUuid:r,fetchImpl:n=globalThis.fetch}){if(!e)throw new Error("ZibbySessionStore: apiUrl is required");if(!t)throw new Error("ZibbySessionStore: apiKey is required");if(!r)throw new Error("ZibbySessionStore: workflowUuid is required");this._apiUrl=String(e).replace(/\/+$/,""),this._apiKey=t,this._workflowUuid=r,this._fetch=n}async append(e,t){if(!Array.isArray(t)||t.length===0)return;let r=`${this._apiUrl}/workflows/${encodeURIComponent(this._workflowUuid)}/sessions/${encodeURIComponent(e.sessionId)}/append`,n=await this._fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this._apiKey}`,"Content-Type":"application/json","User-Agent":rn},body:JSON.stringify({entries:t})});if(!n.ok)throw new Error(`ZibbySessionStore.append HTTP ${n.status}`)}async load(e){let t=`${this._apiUrl}/workflows/${encodeURIComponent(this._workflowUuid)}/sessions/${encodeURIComponent(e.sessionId)}`,r;try{r=await this._fetch(t,{method:"GET",headers:{Authorization:`Bearer ${this._apiKey}`,"User-Agent":rn}})}catch{return null}if(r.status===404||!r.ok)return null;let n;try{n=await r.json()}catch{return null}let s=Array.isArray(n?.entries)?n.entries:null;return s&&s.length>0?s:null}};var Ws="6ba7b810-9dad-11d1-80b4-00c04fd430c8",nn=new Set;function Zs(){return(process.env.PROGRESS_API_URL||process.env.ZIBBY_API_BASE||"").replace(/\/executions\/?$/,"").replace(/\/+$/,"")}function on({namespace:o=Ws}={}){return{id:"session",description:"Persist agent conversation state across invocations (Claude-only in v1)",envKeys:[],tools:[],invokeAgentOptions(e,t){let r=e?.conversationId,n=e?.workflowUuid;if(!r||!n)return null;let s=t?.agentType;if(s&&s!=="claude")return nn.has(s)||(console.warn(`[SKILLS.SESSION] agent type '${s}' does not support native sessions \u2014 node running stateless`),nn.add(s)),null;let i=Gt(`${n}:${r}`,o),c=Zs(),a=process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN,l=null;if(c&&a)try{l=new Ve({apiUrl:c,apiKey:a,workflowUuid:n})}catch(m){console.warn(`[SKILLS.SESSION] failed to build SessionStore: ${m.message}`),l=null}return e.resetConversation?{sessionId:i,resume:i,forkSession:!0,...l&&{sessionStore:l}}:e.hasPriorSession?{resume:i,...l&&{sessionStore:l}}:{sessionId:i,...l&&{sessionStore:l}}}}}import{spawn as sn}from"node:child_process";import{readFileSync as Xs,writeFileSync as qs,existsSync as ht}from"node:fs";import{homedir as an}from"node:os";import{join as ve}from"node:path";async function Qs(){let o=ve(an(),".local/share/cursor-agent/versions");if(!ht(o))throw new Error(`cursor-agent not found at ${o}. Please install cursor-agent first.`);return console.log(`\u{1F527} Patching cursor-agent for CI/CD...
156
+ `),new Promise((e,t)=>{let r=ve(__dirname,"../../scripts/patch-cursor-mcp.py");if(!ht(r)){t(new Error("Patch script not found"));return}let n=sn("python3",[r],{stdio:"inherit"});n.on("close",s=>{s===0?e({success:!0}):t(new Error(`Patch failed with code ${s}`))}),n.on("error",s=>{t(s)})})}function ei(){let o=ve(an(),".local/share/cursor-agent/versions");if(!ht(o))return{patched:!1,installed:!1};try{let e=On("fs").readdirSync(o);if(e.length===0)return{patched:!1,installed:!1};let t=e.sort().reverse()[0],r=ve(o,t,"index.js");return ht(r)?{patched:Xs(r,"utf-8").includes("AUTO-APPROVE MCP TOOLS FOR CI/CD"),installed:!0,path:r}:{patched:!1,installed:!1}}catch(e){return{patched:!1,installed:!1,error:e.message}}}async function ti(o){return console.log(`\u{1F511} Getting MCP approval keys...
157
+ `),new Promise((e,t)=>{let r=sn("cursor-agent",["mcp","list"],{cwd:o,stdio:"pipe"}),n="";r.stdout.on("data",s=>{n+=s.toString(),process.stdout.write(s)}),r.stderr.on("data",s=>{process.stderr.write(s)}),r.on("close",s=>{if(s===0){let i=ri(n);e({success:!0,keys:i,output:n})}else t(new Error(`Failed to get approval keys (exit code ${s})`))}),r.on("error",s=>{t(s)})})}function ri(o){let e={},t=/🔑 APPROVAL KEY:\s+(\S+)\s+=>\s+(\S+)/g,r;for(;(r=t.exec(o))!==null;)e[r[1]]=r[2];return e}function ni(o,e){let t=ve(o,".cursor/projects"),r=ve(t,"mcp-approvals.json");qs(r,JSON.stringify(e,null,2)),console.log(`
158
158
  \u2705 Saved approval keys to: ${r}
159
- `)}import{DEFAULT_OUTPUT_BASE as Gf,SESSIONS_DIR as Kf,SESSION_INFO_FILE as Jf,RESULT_FILE as zf,RAW_OUTPUT_FILE as Yf,EVENTS_FILE as Hf,CI_ENV_VARS as Wf}from"@zibby/agent-workflow";var an=`
159
+ `)}import{DEFAULT_OUTPUT_BASE as Kf,SESSIONS_DIR as Jf,SESSION_INFO_FILE as zf,RESULT_FILE as Yf,RAW_OUTPUT_FILE as Hf,EVENTS_FILE as Vf,CI_ENV_VARS as Wf}from"@zibby/agent-workflow";var ln=`
160
160
  const style = document.createElement('style');
161
161
  style.textContent = \`
162
162
  @keyframes zibby-ripple {
@@ -217,7 +217,7 @@ ${f}`),r.invoke(f,d)}import{SKILL_IDS as Ef}from"@zibby/skill-ids";import{regist
217
217
  setTimeout(() => ripple.remove(), 600);
218
218
  }
219
219
  };
220
- `;function ni(o){return o.addInitScript(an)}function oi(){return`
220
+ `;function oi(o){return o.addInitScript(ln)}function si(){return`
221
221
  async function showRipple(page, locator) {
222
222
  const box = await locator.boundingBox().catch(() => null);
223
223
  if (box) {
@@ -230,10 +230,10 @@ async function showRipple(page, locator) {
230
230
  }, { x, y }).catch(() => {});
231
231
  }
232
232
  }
233
- `.trim()}var Ze=class{static generate(e,t="element"){let{selectors:r}=e;if(!r||typeof r!="object")return this.generateFallbackSelector(e,t);let n=[];return r.role&&n.push(this.generateRoleSelector(r.role)),r.attributes&&n.push(this.generateAttributeSelector(r.attributes)),r.partialMatch&&n.push(this.generatePartialMatchSelector(r.partialMatch)),r.structure&&n.push(this.generateStructuralSelector(r.structure)),n.length===0?this.generateFallbackSelector(e,t):n.length===1?`const ${t} = ${n[0]};`:`const ${t} = ${n[0]}
233
+ `.trim()}var We=class{static generate(e,t="element"){let{selectors:r}=e;if(!r||typeof r!="object")return this.generateFallbackSelector(e,t);let n=[];return r.role&&n.push(this.generateRoleSelector(r.role)),r.attributes&&n.push(this.generateAttributeSelector(r.attributes)),r.partialMatch&&n.push(this.generatePartialMatchSelector(r.partialMatch)),r.structure&&n.push(this.generateStructuralSelector(r.structure)),n.length===0?this.generateFallbackSelector(e,t):n.length===1?`const ${t} = ${n[0]};`:`const ${t} = ${n[0]}
234
234
  ${n.slice(1).map(i=>` .or(${i})`).join(`
235
235
  `)};`}static generateRoleSelector(e){let{role:t,name:r}=e;if(!t)return null;if(r){let n=this.escapeRegex(r);return`page.getByRole('${t}', { name: /${n}/i })`}return`page.getByRole('${t}')`}static generateAttributeSelector(e){if(!e||typeof e!="object")return null;let t=Object.entries(e).filter(([n,s])=>s!=null).map(([n,s])=>n==="placeholder"||n==="aria-label"?n==="placeholder"?`page.getByPlaceholder('${this.escapeString(s)}')`:`page.locator('[${n}="${this.escapeString(s)}"]')`:`[${n}="${this.escapeString(s)}"]`);if(e.placeholder)return`page.getByPlaceholder('${this.escapeString(e.placeholder)}')`;let r=t.filter(n=>!n.startsWith("page.")).join("");return r?`page.locator('${r}')`:null}static generatePartialMatchSelector(e){if(!e||typeof e!="object")return null;let t=Object.entries(e).filter(([r,n])=>n!==void 0).map(([r,n])=>{let s=n.replace(/^\^/,"");return`[${r}^="${this.escapeString(s)}"]`});return t.length>0?`page.locator('${t.join("")}')`:null}static generateStructuralSelector(e){return!e||typeof e!="string"?null:`page.locator('${this.escapeString(e)}')`}static generateFallbackSelector(e,t){let{description:r,type:n}=e;if(n==="fill"||n==="type")return`const ${t} = page.locator('input').first();`;if(n==="click"){if(r.toLowerCase().includes("button"))return`const ${t} = page.locator('button').first();`;if(r.toLowerCase().includes("link"))return`const ${t} = page.locator('a').first();`}return`const ${t} = page.locator('body');`}static escapeString(e){return typeof e!="string"?String(e):e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/"/g,'\\"')}static escapeRegex(e){return typeof e!="string"?String(e):e.replace(/[.*+?^${}()[\]\\]/g,"\\$&")}static generateActionCode(e,t){let{type:r,value:n,description:s,selectors:i}=e,c=`element${t}`,a=this.generate(e,c),l=this.generateActionMethod(r,c,n);return`${a}
236
- ${l}`}static generateActionMethod(e,t,r){switch(e){case"fill":case"type":return`await ${t}.fill('${this.escapeString(r||"")}');`;case"click":return`await ${t}.click();`;case"navigate":return`await page.goto('${this.escapeString(r||"")}');`;case"wait":return`await page.waitForTimeout(${parseInt(r)||2e3});`;default:return`// Unknown action type: ${e}`}}static generateAssertionCode(e,t){let{description:r,expected:n,actual:s,passed:i}=e;return r.toLowerCase().includes("url")?`await expect(page).toHaveURL(/${this.escapeRegex(s)}/);`:r.toLowerCase().includes("visible")?"await expect(page.locator('body')).toBeVisible();":`// ${r}`}};import Xe from"fs/promises";var Gt=class{static async generateFromEvents(e,t,r,n){try{console.log("[TestPostProcessor] \u{1F3AF} Generating test from events.json (100% accurate)");let{readFileSync:s}=await import("fs"),i=JSON.parse(s(t,"utf-8")),c=i.filter(f=>["navigate","type","fill","click","select_option"].includes(f.type)),a=c.filter(f=>f.type!=="navigate");console.log(`[TestPostProcessor] Found ${c.length} action events, ${r.length} trace actions`);let l=`import { ZibbyRuntime } from '@zibby/core';
236
+ ${l}`}static generateActionMethod(e,t,r){switch(e){case"fill":case"type":return`await ${t}.fill('${this.escapeString(r||"")}');`;case"click":return`await ${t}.click();`;case"navigate":return`await page.goto('${this.escapeString(r||"")}');`;case"wait":return`await page.waitForTimeout(${parseInt(r)||2e3});`;default:return`// Unknown action type: ${e}`}}static generateAssertionCode(e,t){let{description:r,expected:n,actual:s,passed:i}=e;return r.toLowerCase().includes("url")?`await expect(page).toHaveURL(/${this.escapeRegex(s)}/);`:r.toLowerCase().includes("visible")?"await expect(page.locator('body')).toBeVisible();":`// ${r}`}};import Ze from"fs/promises";var Kt=class{static async generateFromEvents(e,t,r,n){try{console.log("[TestPostProcessor] \u{1F3AF} Generating test from events.json (100% accurate)");let{readFileSync:s}=await import("fs"),i=JSON.parse(s(t,"utf-8")),c=i.filter(f=>["navigate","type","fill","click","select_option"].includes(f.type)),a=c.filter(f=>f.type!=="navigate");console.log(`[TestPostProcessor] Found ${c.length} action events, ${r.length} trace actions`);let l=`import { ZibbyRuntime } from '@zibby/core';
237
237
  import { test, expect } from '@playwright/test';
238
238
 
239
239
  `;l+=`test('${n}', async ({ page }) => {
@@ -248,14 +248,14 @@ import { test, expect } from '@playwright/test';
248
248
  `,u++}else if(f.type==="select_option"){let{element:g,values:y}=f.data.params,h=r[u]?.strategies||[],b={name:g,action:"selectOption",value:Array.isArray(y)?y[0]:y,strategies:h};l+=` await ZibbyRuntime.step(page, ${JSON.stringify(b,null,2)});
249
249
 
250
250
  `,u++}l+=`});
251
- `;let{dirname:d}=await import("path"),{mkdirSync:m}=await import("fs");return m(d(e),{recursive:!0}),await Xe.writeFile(e,l,"utf-8"),console.log(`[TestPostProcessor] \u2705 Generated test with ${i.filter(f=>["type","fill","click","select_option"].includes(f.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 Xe.readFile(e,"utf-8");n.includes("ZibbyRuntime")||(n=`import { ZibbyRuntime } from '@zibby/core';
252
- ${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 Xe.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 Xe.readFile(e,"utf-8"),s=this.buildSelectorMap(r);return n=this.replaceSimpleSelectors(n,s),await Xe.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=Ze.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};
253
- await ${m}.${u}(${d})`}}return i});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as si,existsSync as ln,readdirSync as cn}from"node:fs";import{join as Kt}from"node:path";import{execSync as ii}from"node:child_process";import{tmpdir as ai}from"node:os";var qe=class{static async parseTraceZip(e){let t;if(e.endsWith(".zip")&&ln(e)){let r=Kt(ai(),`trace-${Date.now()}`);ii(`unzip -q "${e}" -d "${r}"`,{stdio:"pipe"});let s=cn(r).find(i=>i.endsWith(".trace"));if(!s)throw new Error("No .trace file found in zip");t=Kt(r,s)}else if(ln(e)){let n=cn(e).find(s=>s.endsWith(".trace"));if(!n)throw new Error("No .trace file found");t=Kt(e,n)}else throw new Error(`Trace not found at ${e}`);try{let n=si(t,"utf-8").trim().split(`
254
- `),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||"",f=[],g=null,y=null,h=null,b=d.match(/aria-ref=([a-z0-9]+)/i);if(b&&l.snapshotName){let v=b[1],O=i.get(l.snapshotName);if(O&&O.has(v)){let I=O.get(v);g=I.name||null,y=I.role||null,h=I.label||null,console.log(`[TraceParser] \u2705 Found ACTUAL element data: text="${g}", role="${y}"`)}}let w=d.match(/internal:text="([^"]+)"/i),E=d.match(/internal:label="([^"]+)"/i),S=d.match(/internal:placeholder="([^"]+)"/i),$=d.match(/internal:role=([^ ]+)/i),P=d.match(/internal:describe="([^"]+)"/i),k=d.match(/name="([^"]+)"/i);if(w){f.push({type:"text",text:w[1]});let v=w[1].split(" ");v.length>1&&(f.push({type:"text",text:v[0],fuzzy:!0}),f.push({type:"text",text:v[v.length-1],fuzzy:!0}))}if(E&&f.push({type:"label",label:E[1]}),S&&f.push({type:"placeholder",placeholder:S[1]}),g){f.unshift({type:"text",text:g,source:"accessibility-tree"});let v=g.split(" ");v.length>1&&f.push({type:"text",text:v[0],fuzzy:!0,source:"accessibility-tree"})}if(y||$){let v=y||$[1],O=g||(k?k[1]:w?w[1]:null);f.unshift({type:"role",role:v,name:O,source:g?"accessibility-tree":"selector"})}if(h&&f.unshift({type:"label",label:h,source:"accessibility-tree"}),P){let v=P[1],O=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],I=null,N=v;for(let F of O)if(v.toLowerCase().endsWith(` ${F}`)){I=F.replace(" ",""),N=v.substring(0,v.length-F.length-1);break}if(I){f.push({type:"role",role:I,name:N});let F=N.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:F}),f.push({type:"text",text:N});let C=N.split(" ");C.length>1&&(f.push({type:"text",text:C[0],fuzzy:!0}),f.push({type:"text",text:C.slice(0,2).join(" "),fuzzy:!0}))}else{let F=v.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:F}),f.push({type:"text",text:v})}}let T=this.extractDOMStrategies(d,c,w?.[1]||P?.[1],l.pageId);f.push(...T);let j=this.extractStructuralContext(d);(j.parent||j.sibling)&&f.forEach(v=>{["role","text","label","testid"].includes(v.type)&&(j.parent&&(v.parent=j.parent),j.sibling&&(v.sibling=j.sibling))}),f.push({type:"css",value:d});let B=g||w?w[1]:P?P[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${s.length}`;s.push({method:u,name:B,action:u==="type"?"fill":u,value:m,strategies:f,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"),f=i.match(m);f&&!f[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&s.push({type:"id",value:f[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 Jt=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 zt=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 f=m.textContent.trim();if(f)return f}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 f=a.closest("fieldset");if(f){let y=f.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||"",f=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,f,g,y,h].join("|"),w=5381;for(let E=0;E<b.length;E++)w=(w<<5)+w^b.charCodeAt(E);return`zibby-${(w>>>0).toString(36)}`}let s=["button","a","input","select","textarea","label[for]",'[role="button"]','[role="link"]','[role="textbox"]','[role="checkbox"]','[role="radio"]','[role="combobox"]','[role="menuitem"]','[role="tab"]','[role="option"]','[role="switch"]','[role="slider"]',"[onclick]","[data-action]"].join(", "),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 li=8,ci=1,ui=64;function pi(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 di,writeFileSync as pn,existsSync as mi}from"node:fs";import{join as fn}from"node:path";var Y=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 fi}from"node:fs";import{join as un}from"node:path";var fe=class extends Y{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=un(e,"traces"),r=un(e,"trace.zip");if(fi(r))try{this.traceData=await qe.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 gi(o){let e=fn(o,"events.json"),t=fn(o,"events-enriched.json");if(!mi(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(di(e,"utf-8")),n=new fe,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&&(pn(t,JSON.stringify(r,null,2)),pn(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 hi}from"node:child_process";import{existsSync as yi}from"node:fs";import{dirname as bi,resolve as dn,relative as Si}from"node:path";var bt=new Map,Qe=8,mn={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 ${Qe} 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=(bt.get(r)||0)+1;if(bt.set(r,n),n>Qe)return{success:!1,executionCount:n,maxReached:!0,error:`Maximum ${Qe} executions reached. Stop retrying and return your best result.`};let s=e?.projectRoot||process.cwd(),i=dn(s,o),c=Si(s,i);return c.startsWith("..")||dn(i)!==i&&c.includes("..")?{success:!1,executionCount:n,error:"Path traversal detected: scriptPath must be within the project root."}:yi(i)?new Promise(a=>{let l=bi(i),u=hi("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 f=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(f);let h=`${d}
251
+ `;let{dirname:d}=await import("path"),{mkdirSync:m}=await import("fs");return m(d(e),{recursive:!0}),await Ze.writeFile(e,l,"utf-8"),console.log(`[TestPostProcessor] \u2705 Generated test with ${i.filter(f=>["type","fill","click","select_option"].includes(f.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 Ze.readFile(e,"utf-8");n.includes("ZibbyRuntime")||(n=`import { ZibbyRuntime } from '@zibby/core';
252
+ ${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 Ze.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 Ze.readFile(e,"utf-8"),s=this.buildSelectorMap(r);return n=this.replaceSimpleSelectors(n,s),await Ze.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=We.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};
253
+ await ${m}.${u}(${d})`}}return i});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as ii,existsSync as cn,readdirSync as un}from"node:fs";import{join as Jt}from"node:path";import{execSync as ai}from"node:child_process";import{tmpdir as li}from"node:os";var Xe=class{static async parseTraceZip(e){let t;if(e.endsWith(".zip")&&cn(e)){let r=Jt(li(),`trace-${Date.now()}`);ai(`unzip -q "${e}" -d "${r}"`,{stdio:"pipe"});let s=un(r).find(i=>i.endsWith(".trace"));if(!s)throw new Error("No .trace file found in zip");t=Jt(r,s)}else if(cn(e)){let n=un(e).find(s=>s.endsWith(".trace"));if(!n)throw new Error("No .trace file found");t=Jt(e,n)}else throw new Error(`Trace not found at ${e}`);try{let n=ii(t,"utf-8").trim().split(`
254
+ `),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||"",f=[],g=null,y=null,h=null,b=d.match(/aria-ref=([a-z0-9]+)/i);if(b&&l.snapshotName){let v=b[1],O=i.get(l.snapshotName);if(O&&O.has(v)){let I=O.get(v);g=I.name||null,y=I.role||null,h=I.label||null,console.log(`[TraceParser] \u2705 Found ACTUAL element data: text="${g}", role="${y}"`)}}let w=d.match(/internal:text="([^"]+)"/i),E=d.match(/internal:label="([^"]+)"/i),S=d.match(/internal:placeholder="([^"]+)"/i),$=d.match(/internal:role=([^ ]+)/i),P=d.match(/internal:describe="([^"]+)"/i),k=d.match(/name="([^"]+)"/i);if(w){f.push({type:"text",text:w[1]});let v=w[1].split(" ");v.length>1&&(f.push({type:"text",text:v[0],fuzzy:!0}),f.push({type:"text",text:v[v.length-1],fuzzy:!0}))}if(E&&f.push({type:"label",label:E[1]}),S&&f.push({type:"placeholder",placeholder:S[1]}),g){f.unshift({type:"text",text:g,source:"accessibility-tree"});let v=g.split(" ");v.length>1&&f.push({type:"text",text:v[0],fuzzy:!0,source:"accessibility-tree"})}if(y||$){let v=y||$[1],O=g||(k?k[1]:w?w[1]:null);f.unshift({type:"role",role:v,name:O,source:g?"accessibility-tree":"selector"})}if(h&&f.unshift({type:"label",label:h,source:"accessibility-tree"}),P){let v=P[1],O=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],I=null,N=v;for(let F of O)if(v.toLowerCase().endsWith(` ${F}`)){I=F.replace(" ",""),N=v.substring(0,v.length-F.length-1);break}if(I){f.push({type:"role",role:I,name:N});let F=N.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:F}),f.push({type:"text",text:N});let C=N.split(" ");C.length>1&&(f.push({type:"text",text:C[0],fuzzy:!0}),f.push({type:"text",text:C.slice(0,2).join(" "),fuzzy:!0}))}else{let F=v.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:F}),f.push({type:"text",text:v})}}let T=this.extractDOMStrategies(d,c,w?.[1]||P?.[1],l.pageId);f.push(...T);let j=this.extractStructuralContext(d);(j.parent||j.sibling)&&f.forEach(v=>{["role","text","label","testid"].includes(v.type)&&(j.parent&&(v.parent=j.parent),j.sibling&&(v.sibling=j.sibling))}),f.push({type:"css",value:d});let B=g||w?w[1]:P?P[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${s.length}`;s.push({method:u,name:B,action:u==="type"?"fill":u,value:m,strategies:f,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"),f=i.match(m);f&&!f[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&s.push({type:"id",value:f[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 zt=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 Yt=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 f=m.textContent.trim();if(f)return f}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 f=a.closest("fieldset");if(f){let y=f.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||"",f=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,f,g,y,h].join("|"),w=5381;for(let E=0;E<b.length;E++)w=(w<<5)+w^b.charCodeAt(E);return`zibby-${(w>>>0).toString(36)}`}let s=["button","a","input","select","textarea","label[for]",'[role="button"]','[role="link"]','[role="textbox"]','[role="checkbox"]','[role="radio"]','[role="combobox"]','[role="menuitem"]','[role="tab"]','[role="option"]','[role="switch"]','[role="slider"]',"[onclick]","[data-action]"].join(", "),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 ci=8,ui=1,pi=64;function fi(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 mi,writeFileSync as fn,existsSync as gi}from"node:fs";import{join as dn}from"node:path";var Y=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 di}from"node:fs";import{join as pn}from"node:path";var fe=class extends Y{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=pn(e,"traces"),r=pn(e,"trace.zip");if(di(r))try{this.traceData=await Xe.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 hi(o){let e=dn(o,"events.json"),t=dn(o,"events-enriched.json");if(!gi(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(mi(e,"utf-8")),n=new fe,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&&(fn(t,JSON.stringify(r,null,2)),fn(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 yi}from"node:child_process";import{existsSync as bi}from"node:fs";import{dirname as Si,resolve as mn,relative as _i}from"node:path";var yt=new Map,qe=8,gn={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 ${qe} 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=(yt.get(r)||0)+1;if(yt.set(r,n),n>qe)return{success:!1,executionCount:n,maxReached:!0,error:`Maximum ${qe} executions reached. Stop retrying and return your best result.`};let s=e?.projectRoot||process.cwd(),i=mn(s,o),c=_i(s,i);return c.startsWith("..")||mn(i)!==i&&c.includes("..")?{success:!1,executionCount:n,error:"Path traversal detected: scriptPath must be within the project root."}:bi(i)?new Promise(a=>{let l=Si(i),u=yi("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 f=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(f);let h=`${d}
255
255
  ${m}`.split(`
256
256
  `),b="",w=null;for(let E=0;E<h.length;E++){let S=h[E];if(S.includes("Error:")||S.includes("error:")||S.includes("\u2718")){b+=`${S}
257
257
  `;for(let $=E+1;$<Math.min(E+5,h.length);$++)b+=`${h[$]}
258
- `}if(S.includes("at ")&&S.includes(".spec.")){let $=S.match(/:(\d+):\d+/);$&&(w=parseInt($[1]))}}a(g===0?{success:!0,executionCount:n,message:"All tests passed!",output:d.slice(-500)}:{success:!1,executionCount:n,remainingAttempts:Qe-n,error:b.slice(0,1500)||"Test failed (see output)",failedAtLine:w,stdout:d.slice(-1500),stderr:m.slice(-500),hint:n<Qe?"Fix the error and run again.":"Last attempt - make your best fix."})}),u.on("error",g=>{clearTimeout(f),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 bt.keys())e.startsWith(`${o}:`)&&bt.delete(e)}};function _i(o){mn.resetCount(o)}var te=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 gn,writeFileSync as wi}from"node:fs";var Oe=class extends te{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(gn(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(gn(s,"utf-8")).filter(u=>["navigate","type","fill","click","select_option"].includes(u.type)),l=`import { test, expect } from '@playwright/test';
258
+ `}if(S.includes("at ")&&S.includes(".spec.")){let $=S.match(/:(\d+):\d+/);$&&(w=parseInt($[1]))}}a(g===0?{success:!0,executionCount:n,message:"All tests passed!",output:d.slice(-500)}:{success:!1,executionCount:n,remainingAttempts:qe-n,error:b.slice(0,1500)||"Test failed (see output)",failedAtLine:w,stdout:d.slice(-1500),stderr:m.slice(-500),hint:n<qe?"Fix the error and run again.":"Last attempt - make your best fix."})}),u.on("error",g=>{clearTimeout(f),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 yt.keys())e.startsWith(`${o}:`)&&yt.delete(e)}};function wi(o){gn.resetCount(o)}var te=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 hn,writeFileSync as xi}from"node:fs";var Ae=class extends te{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(hn(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(hn(s,"utf-8")).filter(u=>["navigate","type","fill","click","select_option"].includes(u.type)),l=`import { test, expect } from '@playwright/test';
259
259
  `;l+=`import { ZibbyRuntime } from '@zibby/core';
260
260
 
261
261
  `,l+=`test('${i}', async ({ page }) => {
@@ -295,7 +295,7 @@ ${m}`.split(`
295
295
  `,l+=` });
296
296
 
297
297
  `}}return l+=`});
298
- `,wi(t,l),console.log(`[MCPRefStrategy] \u2705 Generated test with ${a.length} actions using MCP descriptions`),{success:!0,testPath:t,method:"MCP Reference Replay (1:1)",actionsGenerated:a.length}}_extractRole(e){let t=e.toLowerCase();return t.includes("button")?"button":t.includes("textbox")?"textbox":t.includes("link")?"link":t.includes("checkbox")?"checkbox":t.includes("radio")?"radio":t.includes("combobox")?"combobox":t.includes("heading")?"heading":"button"}_extractName(e){return e.replace(/\s+(button|textbox|link|checkbox|radio|combobox)$/i,"").trim()}_escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}};import{readFileSync as hn,writeFileSync as xi}from"node:fs";var $e=class extends te{constructor(){super("stable-id","Stable ID Injection (Experimental)",300)}canGenerate(e){let t=e.eventsPath||`${e.sessionPath}/execute_live/events.json`;try{return JSON.parse(hn(t,"utf-8")).some(s=>s.stableId||s.data?.stableId)?(console.log("[StableIdStrategy] \u2705 Stable IDs available"),!0):(console.log("[StableIdStrategy] \u274C No stable IDs found in events"),!1)}catch(r){return console.log("[StableIdStrategy] \u274C Failed to read events:",r.message),!1}}getName(){return"Stable ID Injection (Experimental)"}getPriority(){return 300}async generate(e){let{testFilePath:t,sessionPath:r,state:n}=e,s=`${r}/execute_live/events.json`,i=n?.title||"Generated Test";console.log("[StableIdStrategy] \u{1F3AF} Generating test using stable IDs"),console.log(`[StableIdStrategy] events: ${s}`),console.log(`[StableIdStrategy] output: ${t}`);let a=JSON.parse(hn(s,"utf-8")).filter(m=>["navigate","type","fill","click","select_option","select"].includes(m.type)),l=`import { test, expect } from '@playwright/test';
298
+ `,xi(t,l),console.log(`[MCPRefStrategy] \u2705 Generated test with ${a.length} actions using MCP descriptions`),{success:!0,testPath:t,method:"MCP Reference Replay (1:1)",actionsGenerated:a.length}}_extractRole(e){let t=e.toLowerCase();return t.includes("button")?"button":t.includes("textbox")?"textbox":t.includes("link")?"link":t.includes("checkbox")?"checkbox":t.includes("radio")?"radio":t.includes("combobox")?"combobox":t.includes("heading")?"heading":"button"}_extractName(e){return e.replace(/\s+(button|textbox|link|checkbox|radio|combobox)$/i,"").trim()}_escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}};import{readFileSync as yn,writeFileSync as Ei}from"node:fs";var Oe=class extends te{constructor(){super("stable-id","Stable ID Injection (Experimental)",300)}canGenerate(e){let t=e.eventsPath||`${e.sessionPath}/execute_live/events.json`;try{return JSON.parse(yn(t,"utf-8")).some(s=>s.stableId||s.data?.stableId)?(console.log("[StableIdStrategy] \u2705 Stable IDs available"),!0):(console.log("[StableIdStrategy] \u274C No stable IDs found in events"),!1)}catch(r){return console.log("[StableIdStrategy] \u274C Failed to read events:",r.message),!1}}getName(){return"Stable ID Injection (Experimental)"}getPriority(){return 300}async generate(e){let{testFilePath:t,sessionPath:r,state:n}=e,s=`${r}/execute_live/events.json`,i=n?.title||"Generated Test";console.log("[StableIdStrategy] \u{1F3AF} Generating test using stable IDs"),console.log(`[StableIdStrategy] events: ${s}`),console.log(`[StableIdStrategy] output: ${t}`);let a=JSON.parse(yn(s,"utf-8")).filter(m=>["navigate","type","fill","click","select_option","select"].includes(m.type)),l=`import { test, expect } from '@playwright/test';
299
299
  `;l+=`import { StableIdRuntime } from '@zibby/core';
300
300
 
301
301
  `,l+=`test('${i}', async ({ page }) => {
@@ -310,17 +310,17 @@ ${m}`.split(`
310
310
  `}else if(f.type==="select_option"||f.type==="select"){u=!1;let h=f.data?.values||f.data?.params?.values,b=Array.isArray(h)?h[0]:h||"";g?l+=` await StableIdRuntime.selectWithRetry(page, '${g}', '${this._escapeString(b)}');
311
311
  `:l+=` await page.locator('select').selectOption('${this._escapeString(b)}');
312
312
  `}}return l+=`});
313
- `,xi(t,l),console.log(`[StableIdStrategy] \u2705 Generated test with ${a.length} actions using stable IDs`),{success:!0,testPath:t,method:"Stable ID Injection (Experimental)",actionsGenerated:a.length}}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}_generateSemanticSelector(e){let t=e.toLowerCase(),r="locator",n=e;return t.includes("button")?(r="button",n=e.replace(/\s*button\s*/gi,"").trim()):t.includes("link")?(r="link",n=e.replace(/\s*link\s*/gi,"").trim()):t.includes("textbox")?(r="textbox",n=e.replace(/\s*textbox\s*/gi,"").trim()):t.includes("checkbox")?(r="checkbox",n=e.replace(/\s*checkbox\s*/gi,"").trim()):(t.includes("combobox")||t.includes("dropdown")||t.includes("select"))&&(r="combobox",n=e.replace(/\s*(combobox|dropdown|select)\s*/gi,"").trim()),r!=="locator"&&n?`page.getByRole('${r}', { name: '${this._escapeString(n)}' })`:`page.getByText('${this._escapeString(e)}')`}};var Yt=class{constructor(){this.strategies=[new $e,new Oe],this.strategies.sort((e,t)=>t.getPriority()-e.getPriority())}registerStrategy(e){this.strategies.push(e),this.strategies.sort((t,r)=>r.getPriority()-t.getPriority())}async generate(e){console.log(`
313
+ `,Ei(t,l),console.log(`[StableIdStrategy] \u2705 Generated test with ${a.length} actions using stable IDs`),{success:!0,testPath:t,method:"Stable ID Injection (Experimental)",actionsGenerated:a.length}}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}_generateSemanticSelector(e){let t=e.toLowerCase(),r="locator",n=e;return t.includes("button")?(r="button",n=e.replace(/\s*button\s*/gi,"").trim()):t.includes("link")?(r="link",n=e.replace(/\s*link\s*/gi,"").trim()):t.includes("textbox")?(r="textbox",n=e.replace(/\s*textbox\s*/gi,"").trim()):t.includes("checkbox")?(r="checkbox",n=e.replace(/\s*checkbox\s*/gi,"").trim()):(t.includes("combobox")||t.includes("dropdown")||t.includes("select"))&&(r="combobox",n=e.replace(/\s*(combobox|dropdown|select)\s*/gi,"").trim()),r!=="locator"&&n?`page.getByRole('${r}', { name: '${this._escapeString(n)}' })`:`page.getByText('${this._escapeString(e)}')`}};var Ht=class{constructor(){this.strategies=[new Oe,new Ae],this.strategies.sort((e,t)=>t.getPriority()-e.getPriority())}registerStrategy(e){this.strategies.push(e),this.strategies.sort((t,r)=>r.getPriority()-t.getPriority())}async generate(e){console.log(`
314
314
  \u{1F4CB} Available generation strategies (${this.strategies.length}):`),this.strategies.forEach(t=>{let r=t.canGenerate(e);console.log(` ${r?"\u2713":"\u2717"} ${t.getName()} (priority: ${t.getPriority()})`)});for(let t of this.strategies)if(t.canGenerate(e))return console.log(`
315
- \u{1F3AF} Selected: ${t.getName()}`),t.generate(e);throw new Error("No generation strategy available for this context")}getStrategy(e){return this.strategies.find(t=>t.getName().includes(e))||null}},Ei=new Yt;var Ie=class{async verify(e){throw new Error("TestVerificationStrategy.verify() must be implemented")}canVerify(e){throw new Error("TestVerificationStrategy.canVerify() must be implemented")}getName(){throw new Error("TestVerificationStrategy.getName() must be implemented")}getPriority(){return 0}};import{execSync as Ti}from"node:child_process";import{existsSync as vi}from"node:fs";var Ce=class extends Ie{getName(){return"Playwright JSON Reporter"}getPriority(){return 100}canVerify(e){let{testFilePath:t}=e;return vi(t)}async verify(e){let{testFilePath:t,cwd:r,timeout:n=3e4}=e;try{console.log(`\u{1F9EA} Running test: ${t}`);let s=`npx playwright test ${t} --reporter=json --timeout=${n}`,i=Ti(s,{cwd:r,encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:n+1e4}),a=JSON.parse(i).stats||{};return{success:a.unexpected===0,passed:a.expected||0,failed:a.unexpected||0,error:null,errorDetails:null}}catch(s){let i=s.stdout||s.stderr||s.message;try{let c=JSON.parse(i),a=c.stats||{},l="Test execution failed";if(c.suites&&c.suites.length>0){let d=c.suites[0];if(d.specs&&d.specs.length>0){let m=d.specs[0];if(m.tests&&m.tests.length>0){let f=m.tests[0];if(f.results&&f.results.length>0){let g=f.results[0];g.error&&(l=g.error.message||l)}}}}let u=l.includes("Executable doesn't exist")||l.includes("browserType.launch")||l.includes("Please run the following command")||l.includes("npx playwright install")||i.includes("Executable doesn't exist")||i.includes("npx playwright install");return{success:!1,passed:a.expected||0,failed:a.unexpected||0,error:l,errorDetails:l,isEnvironmentError:u}}catch{let a=i.match(/Error: (.+)/),l=a?a[1]:"Test execution failed",u=l.includes("Executable doesn't exist")||l.includes("browserType.launch")||l.includes("Please run the following command")||l.includes("npx playwright install")||i.includes("Executable doesn't exist")||i.includes("npx playwright install");return{success:!1,passed:0,failed:1,error:l,errorDetails:l,isEnvironmentError:u}}}}};var Ht=class{constructor(){this.strategies=[new Ce],this.strategies.sort((e,t)=>t.getPriority()-e.getPriority())}registerStrategy(e){this.strategies.push(e),this.strategies.sort((t,r)=>r.getPriority()-t.getPriority())}async verify(e){console.log(`
315
+ \u{1F3AF} Selected: ${t.getName()}`),t.generate(e);throw new Error("No generation strategy available for this context")}getStrategy(e){return this.strategies.find(t=>t.getName().includes(e))||null}},Ti=new Ht;var $e=class{async verify(e){throw new Error("TestVerificationStrategy.verify() must be implemented")}canVerify(e){throw new Error("TestVerificationStrategy.canVerify() must be implemented")}getName(){throw new Error("TestVerificationStrategy.getName() must be implemented")}getPriority(){return 0}};import{execSync as vi}from"node:child_process";import{existsSync as Ai}from"node:fs";var Ie=class extends $e{getName(){return"Playwright JSON Reporter"}getPriority(){return 100}canVerify(e){let{testFilePath:t}=e;return Ai(t)}async verify(e){let{testFilePath:t,cwd:r,timeout:n=3e4}=e;try{console.log(`\u{1F9EA} Running test: ${t}`);let s=`npx playwright test ${t} --reporter=json --timeout=${n}`,i=vi(s,{cwd:r,encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:n+1e4}),a=JSON.parse(i).stats||{};return{success:a.unexpected===0,passed:a.expected||0,failed:a.unexpected||0,error:null,errorDetails:null}}catch(s){let i=s.stdout||s.stderr||s.message;try{let c=JSON.parse(i),a=c.stats||{},l="Test execution failed";if(c.suites&&c.suites.length>0){let d=c.suites[0];if(d.specs&&d.specs.length>0){let m=d.specs[0];if(m.tests&&m.tests.length>0){let f=m.tests[0];if(f.results&&f.results.length>0){let g=f.results[0];g.error&&(l=g.error.message||l)}}}}let u=l.includes("Executable doesn't exist")||l.includes("browserType.launch")||l.includes("Please run the following command")||l.includes("npx playwright install")||i.includes("Executable doesn't exist")||i.includes("npx playwright install");return{success:!1,passed:a.expected||0,failed:a.unexpected||0,error:l,errorDetails:l,isEnvironmentError:u}}catch{let a=i.match(/Error: (.+)/),l=a?a[1]:"Test execution failed",u=l.includes("Executable doesn't exist")||l.includes("browserType.launch")||l.includes("Please run the following command")||l.includes("npx playwright install")||i.includes("Executable doesn't exist")||i.includes("npx playwright install");return{success:!1,passed:0,failed:1,error:l,errorDetails:l,isEnvironmentError:u}}}}};var Vt=class{constructor(){this.strategies=[new Ie],this.strategies.sort((e,t)=>t.getPriority()-e.getPriority())}registerStrategy(e){this.strategies.push(e),this.strategies.sort((t,r)=>r.getPriority()-t.getPriority())}async verify(e){console.log(`
316
316
  \u{1F4CB} Available verification strategies (${this.strategies.length}):`),this.strategies.forEach(t=>{let r=t.canVerify(e);console.log(` ${r?"\u2713":"\u2717"} ${t.getName()} (priority: ${t.getPriority()})`)});for(let t of this.strategies)if(t.canVerify(e))return console.log(`
317
- \u{1F3AF} Selected: ${t.getName()}`),t.verify(e);throw new Error("No verification strategy available for this context")}getStrategy(e){return this.strategies.find(t=>t.getName().includes(e))||null}},Ai=new Ht;var re=class{constructor(e={}){this.enrichers=[],this.config=e,this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}register(e){return this.enrichers.push(e),this.enrichers.sort((t,r)=>r.getPriority()-t.getPriority()),this}unregister(e){return this.enrichers=this.enrichers.filter(t=>t.getName()!==e),this}get(e){return this.enrichers.find(t=>t.getName()===e)}setEnabled(e,t){let r=this.get(e);return r&&(r.enabled=t),this}async enrich(e,t){this.stats.totalEvents++;let r={...e},n=[],s=[],i=[];for(let c of this.enrichers)try{if(!c.canEnrich(t)){s.push(c.getName());continue}let a=Date.now(),l=await c.enrich(e,t),u=Date.now()-a;l?(Object.assign(r,l),n.push({name:c.getName(),duration:u})):s.push(c.getName())}catch(a){console.warn(`[EnrichmentPipeline] ${c.getName()} failed:`,a.message),i.push(c.getName()),this.stats.errors[c.getName()]=(this.stats.errors[c.getName()]||0)+1}return r._enrichment={version:"1.0",timestamp:new Date().toISOString(),enrichers:{run:n,skipped:s,failed:i}},n.length>0?this.stats.enrichedEvents++:this.stats.skippedEvents++,r}async enrichBatch(e,t){let r=[];for(let n of e){let s=await this.enrich(n,t);r.push(s)}return r}getStats(){return{...this.stats,enrichers:this.enrichers.map(e=>({name:e.getName(),enabled:e.enabled,priority:e.getPriority(),errors:this.stats.errors[e.getName()]||0}))}}resetStats(){this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}logStatus(){console.log(`
317
+ \u{1F3AF} Selected: ${t.getName()}`),t.verify(e);throw new Error("No verification strategy available for this context")}getStrategy(e){return this.strategies.find(t=>t.getName().includes(e))||null}},Oi=new Vt;var re=class{constructor(e={}){this.enrichers=[],this.config=e,this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}register(e){return this.enrichers.push(e),this.enrichers.sort((t,r)=>r.getPriority()-t.getPriority()),this}unregister(e){return this.enrichers=this.enrichers.filter(t=>t.getName()!==e),this}get(e){return this.enrichers.find(t=>t.getName()===e)}setEnabled(e,t){let r=this.get(e);return r&&(r.enabled=t),this}async enrich(e,t){this.stats.totalEvents++;let r={...e},n=[],s=[],i=[];for(let c of this.enrichers)try{if(!c.canEnrich(t)){s.push(c.getName());continue}let a=Date.now(),l=await c.enrich(e,t),u=Date.now()-a;l?(Object.assign(r,l),n.push({name:c.getName(),duration:u})):s.push(c.getName())}catch(a){console.warn(`[EnrichmentPipeline] ${c.getName()} failed:`,a.message),i.push(c.getName()),this.stats.errors[c.getName()]=(this.stats.errors[c.getName()]||0)+1}return r._enrichment={version:"1.0",timestamp:new Date().toISOString(),enrichers:{run:n,skipped:s,failed:i}},n.length>0?this.stats.enrichedEvents++:this.stats.skippedEvents++,r}async enrichBatch(e,t){let r=[];for(let n of e){let s=await this.enrich(n,t);r.push(s)}return r}getStats(){return{...this.stats,enrichers:this.enrichers.map(e=>({name:e.getName(),enabled:e.enabled,priority:e.getPriority(),errors:this.stats.errors[e.getName()]||0}))}}resetStats(){this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}logStatus(){console.log(`
318
318
  \u{1F4CA} Enrichment Pipeline Status:`),console.log(` Total events: ${this.stats.totalEvents}`),console.log(` Enriched: ${this.stats.enrichedEvents}`),console.log(` Skipped: ${this.stats.skippedEvents}`),console.log(`
319
- Registered enrichers (${this.enrichers.length}):`);for(let e of this.enrichers){let t=e.enabled?"\u2713":"\u2717",r=this.stats.errors[e.getName()]||0,n=r>0?` (${r} errors)`:"";console.log(` ${t} ${e.getName()} (priority: ${e.getPriority()})${n}`)}console.log()}};var Pe=class extends Y{getName(){return"PositionEnricher"}getPriority(){return 90}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:n}=t,s=await n.boundingBox();if(!s)return null;let i=await r.evaluate(()=>({scrollX:window.scrollX,scrollY:window.scrollY,width:window.innerWidth,height:window.innerHeight})),c=s.y>=i.scrollY&&s.y+s.height<=i.scrollY+i.height&&s.x>=0&&s.x+s.width<=i.width;return{position:{boundingBox:s,viewport:i,inViewport:c,centerPoint:{x:Math.round(s.x+s.width/2),y:Math.round(s.y+s.height/2)}}}}catch(r){return this.handleError(r,e)}}};import yn from"node:crypto";var de=class extends Y{getName(){return"AccessibilityEnricher"}getPriority(){return 100}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:n}=t,s=await r.accessibility.snapshot(),i=await this.findAxNode(n,s);if(!i)return null;let c=await this.getAxContext(i,s),a=this.hashAxSubtree(i),l=this.hashAxPath(c.path);return{accessibility:{role:i.role,name:i.name||"",level:c.level,parent:c.parent,siblings:c.siblings,axTreeHash:a,axPathHash:l}}}catch(r){return this.handleError(r,e)}}async findAxNode(e,t){let r=await e.evaluate(n=>({role:n.getAttribute("role")||n.tagName.toLowerCase(),name:n.getAttribute("aria-label")||n.textContent?.trim()||"",tagName:n.tagName.toLowerCase()}));return this.searchAxTree(t,r)}searchAxTree(e,t){if(!e)return null;if(e.role===t.role&&(e.name||"").includes(t.name.substring(0,20)))return e;if(e.children)for(let r of e.children){let n=this.searchAxTree(r,t);if(n)return n}return null}getAxContext(e,t){let r={level:0,parent:null,siblings:[],path:[]},n=this.findParent(e,t);return n&&(r.parent={role:n.role,name:n.name},r.siblings=(n.children||[]).filter(s=>s!==e).map(s=>({role:s.role,name:s.name})).slice(0,3)),r.level=this.calculateLevel(e,t),r.path=this.buildPath(e,t),r}findParent(e,t,r=t){if(!r||!r.children)return null;if(r.children.includes(e))return r;for(let n of r.children){let s=this.findParent(e,t,n);if(s)return s}return null}calculateLevel(e,t,r=t,n=0){if(r===e)return n;if(r.children)for(let s of r.children){let i=this.calculateLevel(e,t,s,n+1);if(i>=0)return i}return-1}buildPath(e,t,r=t,n=[]){if(r===e)return[...n,{role:r.role,name:r.name}];if(r.children)for(let s of r.children){let i=this.buildPath(e,t,s,[...n,{role:r.role,name:r.name}]);if(i)return i}return null}hashAxSubtree(e){let t=JSON.stringify({role:e.role,name:e.name,children:(e.children||[]).map(r=>({role:r.role,name:r.name}))});return yn.createHash("md5").update(t).digest("hex").substring(0,12)}hashAxPath(e){let t=e.map(r=>`${r.role}:${r.name}`).join("/");return yn.createHash("md5").update(t).digest("hex").substring(0,12)}};var me=class extends Y{constructor(e={}){super(e),this.pendingRequests=new Set,this.setupNetworkTracking=!1}getName(){return"PageStateEnricher"}getPriority(){return 95}canEnrich(e){return this.enabled&&e.page}async setupTracking(e){this.setupNetworkTracking||(e.on("request",t=>{["document","xhr","fetch"].includes(t.resourceType())&&this.pendingRequests.add(t.url())}),e.on("requestfinished",t=>{this.pendingRequests.delete(t.url())}),e.on("requestfailed",t=>{this.pendingRequests.delete(t.url())}),this.setupNetworkTracking=!0)}async enrich(e,t){try{let{page:r}=t;await this.setupTracking(r);let n=await r.evaluate(()=>({readyState:document.readyState,domContentLoaded:document.readyState!=="loading",loadComplete:document.readyState==="complete",url:document.location.href})),s=await this.checkDOMStability(r);return{page:{networkIdle:this.pendingRequests.size===0,pendingRequests:this.pendingRequests.size,domStable:s,...n}}}catch(r){return this.handleError(r,e)}}async checkDOMStability(e,t=500){try{return await e.evaluate(n=>new Promise(s=>{let i,c=0,a=new MutationObserver(()=>{c++,clearTimeout(i),i=setTimeout(()=>{a.disconnect(),s(c===0)},n)});a.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),i=setTimeout(()=>{a.disconnect(),s(!0)},n)}),t)}catch{return!1}}reset(){this.pendingRequests.clear(),this.setupNetworkTracking=!1}};var ke=class extends Y{getName(){return"DOMEnricher"}getPriority(){return 85}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{element:r}=t,n=await r.evaluate(s=>{let i=f=>{let g=[],y=f;for(;y&&y!==document.body;){let h=y.tagName.toLowerCase(),b=y.parentElement;if(b){let w=Array.from(b.children).filter(E=>E.tagName===y.tagName);if(w.length>1){let E=w.indexOf(y)+1;h+=`:nth-child(${E})`}}g.unshift(h),y=y.parentElement}return`body > ${g.join(" > ")}`},c=f=>{let g=[],y=f;for(;y&&y!==document.body;){let h=1,b=y.previousSibling;for(;b;)b.nodeType===1&&b.tagName===y.tagName&&h++,b=b.previousSibling;let w=y.tagName.toLowerCase();g.unshift(`${w}[${h}]`),y=y.parentElement}return`/html/body/${g.join("/")}`},a={};for(let f of s.attributes)a[f.name]=f.value;let l=window.getComputedStyle(s),u={display:l.display,visibility:l.visibility,opacity:l.opacity,pointerEvents:l.pointerEvents},d=0,m=s.parentElement;for(;m;)d++,m=m.parentElement;return{path:i(s),xpath:c(s),depth:d,parent:s.parentElement?s.parentElement.tagName.toLowerCase():null,tagName:s.tagName.toLowerCase(),attributes:a,state:{visible:l.display!=="none"&&l.visibility!=="hidden",enabled:!s.disabled,focused:document.activeElement===s,...u}}});return{dom:{path:n.path,xpath:n.xpath,depth:n.depth,parent:n.parent,selector:this.buildSmartSelector(n)},attributes:n.attributes,state:n.state}}catch(r){return this.handleError(r,e)}}buildSmartSelector(e){let t=e.tagName;if(e.attributes.id)return`#${e.attributes.id}`;if(e.attributes["data-test-id"])return`[data-test-id="${e.attributes["data-test-id"]}"]`;if(e.attributes.class){let r=e.attributes.class.split(" ").filter(n=>n&&!n.match(/^(active|focus|hover|disabled)/));r.length>0&&(t+=`.${r.slice(0,2).join(".")}`)}return e.parent&&(t=`${e.parent} > ${t}`),t}};var et=class extends Y{constructor(e={}){super(e),this.priority=200}getName(){return"MCPRef"}getPriority(){return this.priority}async enrich(e,t){let r=e.data?.params?.ref,n=e.data?.params?.element;if(!r&&!n)return null;let s=null,i=null,c=null;if(t?.element)try{let a=await t.element.evaluate(l=>({text:l.textContent?.trim()||"",innerText:l.innerText?.trim()||"",value:l.value||"",label:l.getAttribute("aria-label")||l.getAttribute("label")||"",role:l.getAttribute("role")||l.tagName.toLowerCase(),placeholder:l.getAttribute("placeholder")||"",title:l.getAttribute("title")||""}));s=a.text||a.innerText||a.value||a.placeholder,i=a.role,c=a.label||a.title,console.log(`[MCPRefEnricher] \u2705 Captured actual text: "${s}" (AI said: "${n}")`)}catch(a){console.log(`[MCPRefEnricher] \u26A0\uFE0F Could not extract actual text: ${a.message}`)}return{mcpRef:r,mcpElement:n,actualText:s,actualRole:i,actualLabel:c,recordedSelector:s||n}}};function Wt(o={}){let e=new re(o);return o.enableMCPRef!==!1&&e.register(new et(o)),o.enableTraceText!==!1&&e.register(new fe(o)),o.enableAccessibility!==!1&&e.register(new de(o)),o.enablePageState!==!1&&e.register(new me(o)),o.enablePosition!==!1&&e.register(new Pe(o)),o.enableDOM!==!1&&e.register(new ke(o)),e}function Vt(o={}){let e=new re(o);return e.register(new de(o)),e.register(new me(o)),e}function Oi(o,e={}){let t=new re(e);for(let r of o)t.register(r);return t}import{readFileSync as $i,writeFileSync as Zt}from"node:fs";import{join as bn}from"node:path";async function Ii(o,e={}){let t=bn(o,"events.json"),r=bn(o,"trace.zip");try{let n=JSON.parse($i(t,"utf-8")),s=n.map(c=>({...c,_enrichmentNote:"Full enrichment requires live Playwright access. Use EnrichmentPipeline during test execution."})),i=`${t}.backup`;return Zt(i,JSON.stringify(n,null,2)),Zt(t,JSON.stringify(s,null,2)),{enrichedCount:s.length,skippedCount:0,errors:[]}}catch(n){return console.error("[EnrichmentIntegration] Failed to enrich events:",n.message),{enrichedCount:0,skippedCount:0,errors:[n.message]}}}var Xt=class{constructor(e={}){this.pipeline=e.minimal?Vt(e):Wt(e),this.events=[],this.config=e}async recordEvent(e,t,r){let n={id:this.events.length,type:e,timestamp:new Date().toISOString(),data:t},s=await this.pipeline.enrich(n,{...r,event:n});return this.events.push(s),s}saveEvents(e){Zt(e,JSON.stringify(this.events,null,2)),console.log(`[LiveEnrichment] Saved ${this.events.length} enriched events to ${e}`),this.pipeline.logStatus()}getStats(){return this.pipeline.getStats()}};Ct();var En=o=>{o?.message?.includes("Connection closed")||o?.message?.includes("MCP error -32000")||o?.code===-32e3||console.error("Unhandled rejection:",o)};process.listeners("unhandledRejection").includes(En)||process.on("unhandledRejection",En);async function Mi(o,e={}){let{agent:t,mcp:r,headless:n,cwd:s=process.cwd(),specPath:i,sessionPath:c,sessionTimestamp:a,...l}=e,u=Sn(o,"utf-8"),d=null,{agent:m,error:f}=await ji(s,l),g=m;if(!g&&e.fallbackAgentModule){let b=e.fallbackAgentModule,w=b.BrowserTestAutomationAgent||b.default;w&&(g=new w(l))}if(!g&&f&&console.warn(`\u26A0\uFE0F Failed to load local agent: ${f}`),!g)throw new Error(`No agent found. Please run:
319
+ Registered enrichers (${this.enrichers.length}):`);for(let e of this.enrichers){let t=e.enabled?"\u2713":"\u2717",r=this.stats.errors[e.getName()]||0,n=r>0?` (${r} errors)`:"";console.log(` ${t} ${e.getName()} (priority: ${e.getPriority()})${n}`)}console.log()}};var Ce=class extends Y{getName(){return"PositionEnricher"}getPriority(){return 90}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:n}=t,s=await n.boundingBox();if(!s)return null;let i=await r.evaluate(()=>({scrollX:window.scrollX,scrollY:window.scrollY,width:window.innerWidth,height:window.innerHeight})),c=s.y>=i.scrollY&&s.y+s.height<=i.scrollY+i.height&&s.x>=0&&s.x+s.width<=i.width;return{position:{boundingBox:s,viewport:i,inViewport:c,centerPoint:{x:Math.round(s.x+s.width/2),y:Math.round(s.y+s.height/2)}}}}catch(r){return this.handleError(r,e)}}};import bn from"node:crypto";var de=class extends Y{getName(){return"AccessibilityEnricher"}getPriority(){return 100}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:n}=t,s=await r.accessibility.snapshot(),i=await this.findAxNode(n,s);if(!i)return null;let c=await this.getAxContext(i,s),a=this.hashAxSubtree(i),l=this.hashAxPath(c.path);return{accessibility:{role:i.role,name:i.name||"",level:c.level,parent:c.parent,siblings:c.siblings,axTreeHash:a,axPathHash:l}}}catch(r){return this.handleError(r,e)}}async findAxNode(e,t){let r=await e.evaluate(n=>({role:n.getAttribute("role")||n.tagName.toLowerCase(),name:n.getAttribute("aria-label")||n.textContent?.trim()||"",tagName:n.tagName.toLowerCase()}));return this.searchAxTree(t,r)}searchAxTree(e,t){if(!e)return null;if(e.role===t.role&&(e.name||"").includes(t.name.substring(0,20)))return e;if(e.children)for(let r of e.children){let n=this.searchAxTree(r,t);if(n)return n}return null}getAxContext(e,t){let r={level:0,parent:null,siblings:[],path:[]},n=this.findParent(e,t);return n&&(r.parent={role:n.role,name:n.name},r.siblings=(n.children||[]).filter(s=>s!==e).map(s=>({role:s.role,name:s.name})).slice(0,3)),r.level=this.calculateLevel(e,t),r.path=this.buildPath(e,t),r}findParent(e,t,r=t){if(!r||!r.children)return null;if(r.children.includes(e))return r;for(let n of r.children){let s=this.findParent(e,t,n);if(s)return s}return null}calculateLevel(e,t,r=t,n=0){if(r===e)return n;if(r.children)for(let s of r.children){let i=this.calculateLevel(e,t,s,n+1);if(i>=0)return i}return-1}buildPath(e,t,r=t,n=[]){if(r===e)return[...n,{role:r.role,name:r.name}];if(r.children)for(let s of r.children){let i=this.buildPath(e,t,s,[...n,{role:r.role,name:r.name}]);if(i)return i}return null}hashAxSubtree(e){let t=JSON.stringify({role:e.role,name:e.name,children:(e.children||[]).map(r=>({role:r.role,name:r.name}))});return bn.createHash("md5").update(t).digest("hex").substring(0,12)}hashAxPath(e){let t=e.map(r=>`${r.role}:${r.name}`).join("/");return bn.createHash("md5").update(t).digest("hex").substring(0,12)}};var me=class extends Y{constructor(e={}){super(e),this.pendingRequests=new Set,this.setupNetworkTracking=!1}getName(){return"PageStateEnricher"}getPriority(){return 95}canEnrich(e){return this.enabled&&e.page}async setupTracking(e){this.setupNetworkTracking||(e.on("request",t=>{["document","xhr","fetch"].includes(t.resourceType())&&this.pendingRequests.add(t.url())}),e.on("requestfinished",t=>{this.pendingRequests.delete(t.url())}),e.on("requestfailed",t=>{this.pendingRequests.delete(t.url())}),this.setupNetworkTracking=!0)}async enrich(e,t){try{let{page:r}=t;await this.setupTracking(r);let n=await r.evaluate(()=>({readyState:document.readyState,domContentLoaded:document.readyState!=="loading",loadComplete:document.readyState==="complete",url:document.location.href})),s=await this.checkDOMStability(r);return{page:{networkIdle:this.pendingRequests.size===0,pendingRequests:this.pendingRequests.size,domStable:s,...n}}}catch(r){return this.handleError(r,e)}}async checkDOMStability(e,t=500){try{return await e.evaluate(n=>new Promise(s=>{let i,c=0,a=new MutationObserver(()=>{c++,clearTimeout(i),i=setTimeout(()=>{a.disconnect(),s(c===0)},n)});a.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),i=setTimeout(()=>{a.disconnect(),s(!0)},n)}),t)}catch{return!1}}reset(){this.pendingRequests.clear(),this.setupNetworkTracking=!1}};var Pe=class extends Y{getName(){return"DOMEnricher"}getPriority(){return 85}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{element:r}=t,n=await r.evaluate(s=>{let i=f=>{let g=[],y=f;for(;y&&y!==document.body;){let h=y.tagName.toLowerCase(),b=y.parentElement;if(b){let w=Array.from(b.children).filter(E=>E.tagName===y.tagName);if(w.length>1){let E=w.indexOf(y)+1;h+=`:nth-child(${E})`}}g.unshift(h),y=y.parentElement}return`body > ${g.join(" > ")}`},c=f=>{let g=[],y=f;for(;y&&y!==document.body;){let h=1,b=y.previousSibling;for(;b;)b.nodeType===1&&b.tagName===y.tagName&&h++,b=b.previousSibling;let w=y.tagName.toLowerCase();g.unshift(`${w}[${h}]`),y=y.parentElement}return`/html/body/${g.join("/")}`},a={};for(let f of s.attributes)a[f.name]=f.value;let l=window.getComputedStyle(s),u={display:l.display,visibility:l.visibility,opacity:l.opacity,pointerEvents:l.pointerEvents},d=0,m=s.parentElement;for(;m;)d++,m=m.parentElement;return{path:i(s),xpath:c(s),depth:d,parent:s.parentElement?s.parentElement.tagName.toLowerCase():null,tagName:s.tagName.toLowerCase(),attributes:a,state:{visible:l.display!=="none"&&l.visibility!=="hidden",enabled:!s.disabled,focused:document.activeElement===s,...u}}});return{dom:{path:n.path,xpath:n.xpath,depth:n.depth,parent:n.parent,selector:this.buildSmartSelector(n)},attributes:n.attributes,state:n.state}}catch(r){return this.handleError(r,e)}}buildSmartSelector(e){let t=e.tagName;if(e.attributes.id)return`#${e.attributes.id}`;if(e.attributes["data-test-id"])return`[data-test-id="${e.attributes["data-test-id"]}"]`;if(e.attributes.class){let r=e.attributes.class.split(" ").filter(n=>n&&!n.match(/^(active|focus|hover|disabled)/));r.length>0&&(t+=`.${r.slice(0,2).join(".")}`)}return e.parent&&(t=`${e.parent} > ${t}`),t}};var Qe=class extends Y{constructor(e={}){super(e),this.priority=200}getName(){return"MCPRef"}getPriority(){return this.priority}async enrich(e,t){let r=e.data?.params?.ref,n=e.data?.params?.element;if(!r&&!n)return null;let s=null,i=null,c=null;if(t?.element)try{let a=await t.element.evaluate(l=>({text:l.textContent?.trim()||"",innerText:l.innerText?.trim()||"",value:l.value||"",label:l.getAttribute("aria-label")||l.getAttribute("label")||"",role:l.getAttribute("role")||l.tagName.toLowerCase(),placeholder:l.getAttribute("placeholder")||"",title:l.getAttribute("title")||""}));s=a.text||a.innerText||a.value||a.placeholder,i=a.role,c=a.label||a.title,console.log(`[MCPRefEnricher] \u2705 Captured actual text: "${s}" (AI said: "${n}")`)}catch(a){console.log(`[MCPRefEnricher] \u26A0\uFE0F Could not extract actual text: ${a.message}`)}return{mcpRef:r,mcpElement:n,actualText:s,actualRole:i,actualLabel:c,recordedSelector:s||n}}};function Wt(o={}){let e=new re(o);return o.enableMCPRef!==!1&&e.register(new Qe(o)),o.enableTraceText!==!1&&e.register(new fe(o)),o.enableAccessibility!==!1&&e.register(new de(o)),o.enablePageState!==!1&&e.register(new me(o)),o.enablePosition!==!1&&e.register(new Ce(o)),o.enableDOM!==!1&&e.register(new Pe(o)),e}function Zt(o={}){let e=new re(o);return e.register(new de(o)),e.register(new me(o)),e}function $i(o,e={}){let t=new re(e);for(let r of o)t.register(r);return t}import{readFileSync as Ii,writeFileSync as Xt}from"node:fs";import{join as Sn}from"node:path";async function Ci(o,e={}){let t=Sn(o,"events.json"),r=Sn(o,"trace.zip");try{let n=JSON.parse(Ii(t,"utf-8")),s=n.map(c=>({...c,_enrichmentNote:"Full enrichment requires live Playwright access. Use EnrichmentPipeline during test execution."})),i=`${t}.backup`;return Xt(i,JSON.stringify(n,null,2)),Xt(t,JSON.stringify(s,null,2)),{enrichedCount:s.length,skippedCount:0,errors:[]}}catch(n){return console.error("[EnrichmentIntegration] Failed to enrich events:",n.message),{enrichedCount:0,skippedCount:0,errors:[n.message]}}}var qt=class{constructor(e={}){this.pipeline=e.minimal?Zt(e):Wt(e),this.events=[],this.config=e}async recordEvent(e,t,r){let n={id:this.events.length,type:e,timestamp:new Date().toISOString(),data:t},s=await this.pipeline.enrich(n,{...r,event:n});return this.events.push(s),s}saveEvents(e){Xt(e,JSON.stringify(this.events,null,2)),console.log(`[LiveEnrichment] Saved ${this.events.length} enriched events to ${e}`),this.pipeline.logStatus()}getStats(){return this.pipeline.getStats()}};It();var Tn=o=>{o?.message?.includes("Connection closed")||o?.message?.includes("MCP error -32000")||o?.code===-32e3||console.error("Unhandled rejection:",o)};process.listeners("unhandledRejection").includes(Tn)||process.on("unhandledRejection",Tn);async function Di(o,e={}){let{agent:t,mcp:r,headless:n,cwd:s=process.cwd(),specPath:i,sessionPath:c,sessionTimestamp:a,...l}=e,u=_n(o,"utf-8"),d=null,{agent:m,error:f}=await Bi(s,l),g=m;if(!g&&e.fallbackAgentModule){let b=e.fallbackAgentModule,w=b.BrowserTestAutomationAgent||b.default;w&&(g=new w(l))}if(!g&&f&&console.warn(`\u26A0\uFE0F Failed to load local agent: ${f}`),!g)throw new Error(`No agent found. Please run:
320
320
  zibby init
321
321
 
322
322
  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(`
323
323
  \u{1F3AF} Running Single Node: ${e.singleNode} (Framework Mode)
324
- `);let T=g.calculateOutputPath(i||o),j=g.buildGraph(),B={};for(let[I,N]of j.nodes.entries())B[I]=N.config||N;let v={};if(e.sessionId){let I=e.sessionId,N=e.paths?.output||Pi;if(I==="last"){let R=Ne(s,N,xn);if(_n(R)){let{readdirSync:D,statSync:A}=await import("fs"),x=D(R).filter(L=>A(Ne(R,L)).isDirectory()).map(L=>({name:L,time:A(Ne(R,L)).mtimeMs})).sort((L,M)=>M.time-L.time);x.length>0?(I=x[0].name,console.log(`\u{1F4C2} Using latest session: ${I}`)):console.log(`\u26A0\uFE0F No sessions found in ${R}`)}}let F=Ne(s,N,xn,I),C=Ne(F,"execute_live"),_=Ne(C,ki);_n(_)?(console.log(`\u{1F4C2} Loading session: ${I}`),v={sessionPath:F,execute_live_output:JSON.parse(Sn(_,"utf-8"))}):console.log(`\u26A0\uFE0F Session not found: ${F}`)}let O=await g.runSingleNode(e.singleNode,B,{testSpec:u,outputPath:T,cwd:s||process.cwd(),contextConfig:e.contextConfig,specPath:i||o,config:e,...v});return typeof g.onComplete=="function"&&await g.onComplete(O),O}let b;typeof e.onPipelineProgress=="function"?b=e.onPipelineProgress:e.runIndex?.pipelineProgress!==!1&&(b=Pr({cwd:s||process.cwd(),config:e}));let w=s||process.cwd(),E=c!=null&&String(c).trim()!==""?(()=>{let T=String(c).trim();try{return Ci(T)?wn(T):wn(w,T)}catch{return T}})():void 0,S=Li(),$=E??S;Ri();let P=Ni({cwd:w,config:e,traceFrom:"runTest",initialState:{sessionPath:$,sessionTimestamp:a}}),k;try{k=await g.run(u,{testSpec:u,specPath:i||o,cwd:w,config:e,sessionPath:P.sessionPath,sessionTimestamp:P.sessionTimestamp,...b?{onPipelineProgress:b}:{}})}catch(T){throw typeof T?.message=="string"&&T.message.includes("Interrupted by user")&&(s||process.cwd(),void 0),y||(T?.partialResult,T?.message,void 0),T}return k}finally{process.off("SIGINT",h),process.off("SIGTERM",h),await g.cleanup()}}function Di(o){return o.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function Ui(o,e){if(o[e])return o[e];let t=Di(e);if(o[t])return o[t];let r=`${t}Workflow`;return o[r]?o[r]:null}async function of(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 Te),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 ji(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=Ui(i,c),!a){let u=Object.keys(i).filter(d=>d!=="default"&&typeof i[d]=="function");throw new Error(`Workflow "${c}" not found.
324
+ `);let T=g.calculateOutputPath(i||o),j=g.buildGraph(),B={};for(let[I,N]of j.nodes.entries())B[I]=N.config||N;let v={};if(e.sessionId){let I=e.sessionId,N=e.paths?.output||ki;if(I==="last"){let R=ke(s,N,En);if(wn(R)){let{readdirSync:D,statSync:A}=await import("fs"),x=D(R).filter(L=>A(ke(R,L)).isDirectory()).map(L=>({name:L,time:A(ke(R,L)).mtimeMs})).sort((L,M)=>M.time-L.time);x.length>0?(I=x[0].name,console.log(`\u{1F4C2} Using latest session: ${I}`)):console.log(`\u26A0\uFE0F No sessions found in ${R}`)}}let F=ke(s,N,En,I),C=ke(F,"execute_live"),_=ke(C,Ni);wn(_)?(console.log(`\u{1F4C2} Loading session: ${I}`),v={sessionPath:F,execute_live_output:JSON.parse(_n(_,"utf-8"))}):console.log(`\u26A0\uFE0F Session not found: ${F}`)}let O=await g.runSingleNode(e.singleNode,B,{testSpec:u,outputPath:T,cwd:s||process.cwd(),contextConfig:e.contextConfig,specPath:i||o,config:e,...v});return typeof g.onComplete=="function"&&await g.onComplete(O),O}let b;typeof e.onPipelineProgress=="function"?b=e.onPipelineProgress:e.runIndex?.pipelineProgress!==!1&&(b=kr({cwd:s||process.cwd(),config:e}));let w=s||process.cwd(),E=c!=null&&String(c).trim()!==""?(()=>{let T=String(c).trim();try{return Pi(T)?xn(T):xn(w,T)}catch{return T}})():void 0,S=Mi(),$=E??S;Li();let P=Ri({cwd:w,config:e,traceFrom:"runTest",initialState:{sessionPath:$,sessionTimestamp:a}}),k;try{k=await g.run(u,{testSpec:u,specPath:i||o,cwd:w,config:e,sessionPath:P.sessionPath,sessionTimestamp:P.sessionTimestamp,...b?{onPipelineProgress:b}:{}})}catch(T){throw typeof T?.message=="string"&&T.message.includes("Interrupted by user")&&(s||process.cwd(),void 0),y||(T?.partialResult,T?.message,void 0),T}return k}finally{process.off("SIGINT",h),process.off("SIGTERM",h),await g.cleanup()}}function Ui(o){return o.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function ji(o,e){if(o[e])return o[e];let t=Ui(e);if(o[t])return o[t];let r=`${t}Workflow`;return o[r]?o[r]:null}async function sf(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 Te),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 Bi(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=ji(i,c),!a){let u=Object.keys(i).filter(d=>d!=="default"&&typeof i[d]=="function");throw new Error(`Workflow "${c}" not found.
325
325
  Available workflows: ${u.join(", ")}
326
- 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 Te);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 Tn=class{constructor(e={}){this.config=e}async run(e){return Mi(e.spec||e.specPath,{...this.config,...e})}};export{kn as AGENT_TYPES,Ic as ALL_TOOLS,de as AccessibilityEnricher,ds as AgentStrategy,pe as AssistantStrategy,_s as CHAT_MEMORY_TOOLS,Wf as CI_ENV_VARS,nt as CLAUDE_MODEL_MAP,ot as CODEX_MODEL_MAP,Nn as CORE_LOG_LEVELS,ms as CORE_TOOLS,ie as ClaudeAgentStrategy,ae as CodexAgentStrategy,oe as CursorAgentStrategy,li as DEFAULT_MAX_CONCURRENT_RUNS,z as DEFAULT_MODELS,Gf as DEFAULT_OUTPUT_BASE,ke as DOMEnricher,Hf as EVENTS_FILE,re as EnrichmentPipeline,Y as EventEnricher,_t as GEMINI_MODEL_MAP,hs as GITHUB_TOOLS,ce as GeminiAgentStrategy,gs as JIRA_TOOLS,V as LOG_LEVELS,Xt as LiveEnrichmentRecorder,rt as Logger,ui as MAX_MAX_CONCURRENT_RUNS,Oe as MCPRefStrategy,Ss as MEMORY_TOOLS,ci as MIN_MAX_CONCURRENT_RUNS,De as MODEL_REGISTRY,Ye as McpClientManager,ue as OpenAIToolProvider,me as PageStateEnricher,Ce as PlaywrightJsonVerificationStrategy,Pe as PositionEnricher,Yf as RAW_OUTPUT_FILE,zf as RESULT_FILE,an as RIPPLE_EFFECT_SCRIPT,bs as RUNNER_TOOLS,Mt as ResultHandler,Kf as SESSIONS_DIR,Jf as SESSION_INFO_FILE,Ef as SKILLS,ws as SKILL_TOOLS,ys as SLACK_TOOLS,Ze as SelectorGenerator,zt as StableIdRuntime,$e as StableIdStrategy,X as StreamingParser,Ps as TRUSTED_VCS_HOSTS,Tn as TestAutomation,te as TestGenerationStrategy,Gt as TestPostProcessor,Ie as TestVerificationStrategy,_e as ToolCallProvider,qe as TraceParser,Te as WorkflowAgent,lf as WorkflowGraph,Jt as ZibbyRuntime,We as ZibbyUploader,Fr as authedUrl,Ue as buildVendorModelMap,qo as checkCursorAgentInstalled,Qs as checkCursorAgentPatched,pf as clearInheritedSessionEnvForFreshRun,Cs as clearTokenCache,Gs as cloneRepo,Oi as createCustomPipeline,Wt as createDefaultPipeline,Vt as createMinimalPipeline,Yr as createUploader,Ii as enrichRecordedEvents,oi as generateRippleHelperCode,uf as generateWorkflowSessionId,Dr as getAgentStrategy,$f as getAllSkills,ei as getApprovalKeys,Qo as getCursorAgentInstallInstructions,Pn as getPickerModels,Af as getSkill,Of as hasSkill,ve as hostnameOf,ni as injectRippleEffect,fs as invokeAgent,jr as isTrustedVcsHost,If as listSkillIds,of as listWorkflows,p as logger,Ds as organizeVideos,qs as patchCursorAgentForCI,H as pickFromPool,gi as postProcessEvents,Br as providerForHost,df as readPinnedSessionPathFromEnv,Kr as redactGitSecrets,Ct as registerBuiltInStrategies,vf as registerSkill,_i as resetExecutionCount,Dt as resolveIntegrationToken,pi as resolveMaxParallelRuns,In as resolveModelFamily,cf as resolveWorkflowSession,mn as runPlaywrightTestTool,Mi as runTest,ri as saveApprovalKeys,ks as scrubRemoteToTokenless,Ns as securePush,Ur as selfHostGitlabHost,nn as sessionSkill,ff as shouldTrustInheritedSessionEnv,mf as syncProcessEnvToSession,Ei as testGenerationManager,Ai as testVerificationManager,q as timeline,Gr as tokenlessUrl,cs as workflow,yf as z};
326
+ 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 Te);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 vn=class{constructor(e={}){this.config=e}async run(e){return Di(e.spec||e.specPath,{...this.config,...e})}};export{Nn as AGENT_TYPES,Cc as ALL_TOOLS,de as AccessibilityEnricher,ms as AgentStrategy,pe as AssistantStrategy,ws as CHAT_MEMORY_TOOLS,Wf as CI_ENV_VARS,rt as CLAUDE_MODEL_MAP,nt as CODEX_MODEL_MAP,Rn as CORE_LOG_LEVELS,gs as CORE_TOOLS,ie as ClaudeAgentStrategy,ae as CodexAgentStrategy,oe as CursorAgentStrategy,ci as DEFAULT_MAX_CONCURRENT_RUNS,z as DEFAULT_MODELS,Kf as DEFAULT_OUTPUT_BASE,Pe as DOMEnricher,Vf as EVENTS_FILE,re as EnrichmentPipeline,Y as EventEnricher,St as GEMINI_MODEL_MAP,ys as GITHUB_TOOLS,ce as GeminiAgentStrategy,hs as JIRA_TOOLS,W as LOG_LEVELS,qt as LiveEnrichmentRecorder,tt as Logger,pi as MAX_MAX_CONCURRENT_RUNS,Ae as MCPRefStrategy,_s as MEMORY_TOOLS,ui as MIN_MAX_CONCURRENT_RUNS,Me as MODEL_REGISTRY,ze as McpClientManager,ue as OpenAIToolProvider,me as PageStateEnricher,Ie as PlaywrightJsonVerificationStrategy,Ce as PositionEnricher,Hf as RAW_OUTPUT_FILE,Yf as RESULT_FILE,ln as RIPPLE_EFFECT_SCRIPT,Ss as RUNNER_TOOLS,Lt as ResultHandler,Jf as SESSIONS_DIR,zf as SESSION_INFO_FILE,Tf as SKILLS,xs as SKILL_TOOLS,bs as SLACK_TOOLS,We as SelectorGenerator,Yt as StableIdRuntime,Oe as StableIdStrategy,X as StreamingParser,ks as TRUSTED_VCS_HOSTS,vn as TestAutomation,te as TestGenerationStrategy,Kt as TestPostProcessor,$e as TestVerificationStrategy,_e as ToolCallProvider,Xe as TraceParser,Te as WorkflowAgent,cf as WorkflowGraph,zt as ZibbyRuntime,He as ZibbyUploader,Gr as authedUrl,De as buildVendorModelMap,Qo as checkCursorAgentInstalled,ei as checkCursorAgentPatched,ff as clearInheritedSessionEnvForFreshRun,Ps as clearTokenCache,Ks as cloneRepo,$i as createCustomPipeline,Wt as createDefaultPipeline,Zt as createMinimalPipeline,Hr as createUploader,Ci as enrichRecordedEvents,si as generateRippleHelperCode,pf as generateWorkflowSessionId,Ur as getAgentStrategy,If as getAllSkills,ti as getApprovalKeys,es as getCursorAgentInstallInstructions,kn as getPickerModels,Of as getSkill,$f as hasSkill,Dt as hostnameOf,oi as injectRippleEffect,ds as invokeAgent,Br as isTrustedVcsHost,Cf as listSkillIds,sf as listWorkflows,p as logger,Us as organizeVideos,Qs as patchCursorAgentForCI,H as pickFromPool,hi as postProcessEvents,Fr as providerForHost,mf as readPinnedSessionPathFromEnv,Jr as redactGitSecrets,It as registerBuiltInStrategies,Af as registerSkill,wi as resetExecutionCount,Mt as resolveIntegrationToken,fi as resolveMaxParallelRuns,Cn as resolveModelFamily,uf as resolveWorkflowSession,gn as runPlaywrightTestTool,Di as runTest,ni as saveApprovalKeys,Ns as scrubRemoteToTokenless,Rs as securePush,jr as selfHostGitlabHost,on as sessionSkill,df as shouldTrustInheritedSessionEnv,gf as syncProcessEnvToSession,Ti as testGenerationManager,Oi as testVerificationManager,q as timeline,Kr as tokenlessUrl,us as workflow,bf as z};
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/core",
3
- "version": "0.5.29",
3
+ "version": "0.5.30",
4
4
  "description": "Core test automation engine with multi-agent and multi-MCP support",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -1 +1 @@
1
- import{existsSync as E,readFileSync as _}from"node:fs";import{homedir as m}from"node:os";import{join as y}from"node:path";var b=new Map,$={github:"GITHUB_TOKEN",gitlab:"GITLAB_TOKEN",sentry:"SENTRY_AUTH_TOKEN",slack:"SLACK_BOT_TOKEN"};function x(){let t=process.env.ZIBBY_SELF_HOST;return t!=null&&t!==""&&t!=="0"&&t.toLowerCase()!=="false"}function I(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let t=y(m(),".zibby","config.json");return E(t)&&JSON.parse(_(t,"utf-8")).sessionToken||null}catch{return null}}function k(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app"}async function w(t){if(x()){let a=$[t];if(a&&process.env[a])return{token:process.env[a]}}let n=Date.now(),e=b.get(t);if(e&&e.expiresAt>n)return e.data;let r=I();if(!r)throw new Error("No session token. Run `zibby login` first.");let c=`${k()}/integrations/token/${t}`,s=await fetch(c,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!s.ok){let a=await s.text().catch(()=>"");throw s.status===404?new Error(`${t} is not connected. Connect it at https://studio.zibby.dev/integrations`):s.status===401||s.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Failed to resolve ${t} token (${s.status}): ${a}`)}let o=await s.json();if(!o||typeof o!="object")throw new Error(`Invalid response from ${t} token endpoint: expected object, got ${typeof o}`);if(t==="jira"){if(!o.token||typeof o.token!="string")throw new Error(`Invalid jira token response: token is ${typeof o.token}, expected string`);if(!o.cloudId)throw new Error("Invalid jira token response: missing cloudId")}else if(t==="github"&&(!o.token||typeof o.token!="string"))throw new Error(`Invalid github token response: token is ${typeof o.token}, expected string`);let f=((o.expiresInSec||3e3)-120)*1e3;return b.set(t,{data:o,expiresAt:n+f}),o}var U=Object.freeze(["github.com","gitlab.com"]);function p(t){try{return new URL(t).hostname.toLowerCase()}catch{return""}}function A(t=process.env){let n=t&&(t.GITLAB_URL||t.GITLAB_INSTANCE_URL)||"";return p(n)}function h(t={}){if(t.gitlabHost){let n=String(t.gitlabHost).trim().toLowerCase();return n?n.includes("://")?p(n):n.replace(/:\d+$/,""):""}return A()}function O(t,n={}){let e=p(t);if(!e)return!1;if(e==="github.com"||e==="gitlab.com")return!0;let r=h(n);return!!(r&&e===r)}function S(t,n={}){if(t==="github.com")return"github";if(t==="gitlab.com")return"gitlab";let e=h(n);return e&&t===e?"gitlab":null}function v(t,n,e={}){if(!t||!n)return t;let r=p(t);if(!r)return t;if(r==="github.com")return t.replace(/^https:\/\/(?:[^@/]+@)?github\.com(?=[:/]|$)/i,`https://x-access-token:${n}@github.com`);if(r==="gitlab.com")return t.replace(/^https:\/\/(?:[^@/]+@)?gitlab\.com(?=[:/]|$)/i,`https://oauth2:${n}@gitlab.com`);let c=h(e);if(c&&r===c){let s=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`^https:\\/\\/(?:[^@/]+@)?${s}(?=[:/]|$)`,"i");return t.replace(o,`https://oauth2:${n}@${c}`)}return t}function B(t){return t&&String(t).replace(/^(https:\/\/)[^@/]+@/i,"$1")}function C(t,n){let e=t==null?"":String(t);return n&&(e=e.split(n).join("***")),e=e.replace(/(https?:\/\/)(?:x-access-token|oauth2):[^@\s/]+@/gi,"$1"),e=e.replace(/(https?:\/\/)[^@\s/:]+:[^@\s/]+@/gi,"$1"),e}async function K(t,n,e){try{await t("git",["remote","set-url","origin",B(e)],n)}catch(r){console.warn(`\u26A0\uFE0F could not scrub token from origin remote (continuing): ${r?.message||r}`)}}async function P({run:t,repoPath:n,repoUrl:e,branch:r,token:c,resolveToken:s=w,gitlabHost:o}={}){if(typeof t!="function")throw new Error("securePush: `run` (a spawn wrapper resolving {code,stdout,stderr}) is required");if(!r)throw new Error("securePush: `branch` is required");let f=h({gitlabHost:o}),a=p(e),g=O(e,{gitlabHost:f}),u=c||"";if(!u&&g&&typeof s=="function"){let l=S(a,{gitlabHost:f});if(l)try{u=(await s(l))?.token||""}catch{}}else!u&&!g&&console.warn(`\u26A0\uFE0F push target host '${a||"(unparseable)"}' is not a trusted VCS host \u2014 refusing to mint a token`);let d=u&&g,T=d?v(e,u,{gitlabHost:f}):"origin",i=await t("git",["push",T,r],n);if(!i||i.code!==0){let l=C(i&&i.stderr||"",u);throw new Error(`git push failed (exit ${i?i.code:"?"}): ${String(l).slice(-500)}`)}return{code:i.code,stdout:i.stdout,stderr:i.stderr,pushedAuthed:!!d,target:d?"<authed>":"origin"}}export{U as TRUSTED_VCS_HOSTS,v as authedUrl,p as hostnameOf,O as isTrustedVcsHost,S as providerForHost,C as redactGitSecrets,K as scrubRemoteToTokenless,P as securePush,A as selfHostGitlabHost,B as tokenlessUrl};
1
+ import{existsSync as E,readFileSync as _}from"node:fs";import{homedir as y}from"node:os";import{join as x}from"node:path";var w=new Map,$={github:"GITHUB_TOKEN",gitlab:"GITLAB_TOKEN",sentry:"SENTRY_AUTH_TOKEN",slack:"SLACK_BOT_TOKEN"};function I(){let t=process.env.ZIBBY_SELF_HOST;return t!=null&&t!==""&&t!=="0"&&t.toLowerCase()!=="false"}function k(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let t=x(y(),".zibby","config.json");return E(t)&&JSON.parse(_(t,"utf-8")).sessionToken||null}catch{return null}}function A(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app"}async function b(t){if(I()){let a=$[t];if(a&&process.env[a])return{token:process.env[a]}}let e=Date.now(),n=w.get(t);if(n&&n.expiresAt>e)return n.data;let r=k();if(!r)throw new Error("No session token. Run `zibby login` first.");let c=`${A()}/integrations/token/${t}`,s=await fetch(c,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!s.ok){let a=await s.text().catch(()=>"");throw s.status===404?new Error(`${t} is not connected. Connect it at https://studio.zibby.dev/integrations`):s.status===401||s.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Failed to resolve ${t} token (${s.status}): ${a}`)}let o=await s.json();if(!o||typeof o!="object")throw new Error(`Invalid response from ${t} token endpoint: expected object, got ${typeof o}`);if(t==="jira"){if(!o.token||typeof o.token!="string")throw new Error(`Invalid jira token response: token is ${typeof o.token}, expected string`);if(!o.cloudId)throw new Error("Invalid jira token response: missing cloudId")}else if(t==="github"&&(!o.token||typeof o.token!="string"))throw new Error(`Invalid github token response: token is ${typeof o.token}, expected string`);let f=((o.expiresInSec||3e3)-120)*1e3;return w.set(t,{data:o,expiresAt:e+f}),o}var K=Object.freeze(["github.com","gitlab.com"]);function m(t){try{return new URL(t).hostname.toLowerCase()}catch{return""}}function d(t){if(typeof t!="string"||t===""||/[\\\x00-\x20\x7f]/.test(t))return"";let e;try{e=new URL(t)}catch{return""}return e.protocol!=="https:"?"":e.hostname.toLowerCase()}function O(t=process.env){let e=t&&(t.GITLAB_URL||t.GITLAB_INSTANCE_URL)||"";return m(e)}function l(t={}){if(t.gitlabHost){let e=String(t.gitlabHost).trim().toLowerCase();return e?e.includes("://")?m(e):e.replace(/:\d+$/,""):""}return O()}function S(t,e={}){let n=d(t);if(!n)return!1;if(n==="github.com"||n==="gitlab.com")return!0;let r=l(e);return!!(r&&n===r)}function v(t,e={}){if(t==="github.com")return"github";if(t==="gitlab.com")return"gitlab";let n=l(e);return n&&t===n?"gitlab":null}function B(t,e,n={}){if(!t||!e)return t;let r=d(t);if(!r)return t;if(r==="github.com")return t.replace(/^https:\/\/(?:[^@/]+@)?github\.com(?=[:/]|$)/i,`https://x-access-token:${e}@github.com`);if(r==="gitlab.com")return t.replace(/^https:\/\/(?:[^@/]+@)?gitlab\.com(?=[:/]|$)/i,`https://oauth2:${e}@gitlab.com`);let c=l(n);if(c&&r===c){let s=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`^https:\\/\\/(?:[^@/]+@)?${s}(?=[:/]|$)`,"i");return t.replace(o,`https://oauth2:${e}@${c}`)}return t}function C(t){return t&&String(t).replace(/^(https:\/\/)[^@/]+@/i,"$1")}function N(t,e){let n=t==null?"":String(t);return e&&(n=n.split(e).join("***")),n=n.replace(/(https?:\/\/)(?:x-access-token|oauth2):[^@\s/]+@/gi,"$1"),n=n.replace(/(https?:\/\/)[^@\s/:]+:[^@\s/]+@/gi,"$1"),n}async function P(t,e,n){try{await t("git",["remote","set-url","origin",C(n)],e)}catch(r){console.warn(`\u26A0\uFE0F could not scrub token from origin remote (continuing): ${r?.message||r}`)}}async function G({run:t,repoPath:e,repoUrl:n,branch:r,token:c,resolveToken:s=b,gitlabHost:o}={}){if(typeof t!="function")throw new Error("securePush: `run` (a spawn wrapper resolving {code,stdout,stderr}) is required");if(!r)throw new Error("securePush: `branch` is required");let f=l({gitlabHost:o}),a=d(n),h=S(n,{gitlabHost:f}),u=c||"";if(!u&&h&&typeof s=="function"){let p=v(a,{gitlabHost:f});if(p)try{u=(await s(p))?.token||""}catch{}}else!u&&!h&&console.warn(`\u26A0\uFE0F push target host '${a||"(unparseable)"}' is not a trusted VCS host \u2014 refusing to mint a token`);let g=u&&h,T=g?B(n,u,{gitlabHost:f}):"origin",i=await t("git",["push",T,r],e);if(!i||i.code!==0){let p=N(i&&i.stderr||"",u);throw new Error(`git push failed (exit ${i?i.code:"?"}): ${String(p).slice(-500)}`)}return{code:i.code,stdout:i.stdout,stderr:i.stderr,pushedAuthed:!!g,target:g?"<authed>":"origin"}}export{K as TRUSTED_VCS_HOSTS,B as authedUrl,m as hostnameOf,S as isTrustedVcsHost,v as providerForHost,N as redactGitSecrets,d as safeVcsHostname,P as scrubRemoteToTokenless,G as securePush,O as selfHostGitlabHost,C as tokenlessUrl};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/core",
3
- "version": "0.5.29",
3
+ "version": "0.5.30",
4
4
  "description": "Core test automation engine with multi-agent and multi-MCP support",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",