@zibby/core 0.5.48 → 0.5.49

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,20 +1,20 @@
1
- var Jn=Object.defineProperty;var Yn=(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 pr=(o,e,t)=>()=>{if(t)throw t[0];try{return o&&(e=o(o=0)),e}catch(r){throw t=[r],r}};var fr=(o,e)=>{for(var t in e)Jn(o,t,{get:e[t],enumerable:!0})};var gr={};fr(gr,{zodToJson:()=>ue});import{z as mr}from"zod";import{zodToJsonSchema as Zn}from"zod-to-json-schema";function Vn(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 Ee(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]=Ee(o[e][t]);for(let e of["anyOf","oneOf","allOf"])Array.isArray(o[e])&&(o[e]=o[e].map(Ee));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=Ee(o.properties[r]);t.has(r)||(n=Vn(n)),o.properties[r]=n}o.required=e}return o.items&&(Array.isArray(o.items)?o.items=o.items.map(Ee):o.items=Ee(o.items)),o}function ue(o,e={target:"openApi3"}){if(!o)return null;let t=e?.target==="openAi",r=null;if(typeof mr?.toJSONSchema=="function")try{r=mr.toJSONSchema(o)}catch{}if(!r)try{r=Zn(o,e)}catch{return null}if(t&&r)try{return Ee(r)}catch{return r}return r}var Ke=pr(()=>{});var tn={};fr(tn,{clearConnectedCache:()=>Ls,clearTokenCache:()=>en,getConnectedIntegrations:()=>Rs,resolveIntegrationToken:()=>At});import{existsSync as Cs,readFileSync as ks}from"node:fs";import{homedir as Ps}from"node:os";import{join as Ns}from"node:path";function qr(){let o=process.env.ZIBBY_SELF_HOST;return o!=null&&o!==""&&o!=="0"&&o.toLowerCase()!=="false"}function Xr(){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=Ns(Ps(),".zibby","config.json");return Cs(o)&&JSON.parse(ks(o,"utf-8")).sessionToken||null}catch{return null}}function Qr(){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 At(o){if(qr()){let l=Wr[o];if(l&&process.env[l])return{token:process.env[l]}}let e=Date.now(),t=Tt.get(o);if(t&&t.expiresAt>e)return t.data;let r=Xr();if(!r)throw new Error("Missing session credential: neither PROJECT_API_TOKEN nor ZIBBY_USER_TOKEN is set in this process env (and no ~/.zibby/config.json session). If this is an MCP skill child, the spawning skill must forward them \u2014 check the skill's envKeys / resolve() env (see @zibby/skills backend-session-env-contract). Interactive CLI: run `zibby login`.");let n=`${Qr()}/integrations/token/${o}`,s=await fetch(n,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!s.ok){let l=await s.text().catch(()=>"");if(s.status===404){let a="";try{a=String(JSON.parse(l)?.error||"").trim()}catch{}throw new Error(a||`${o} is not connected. Connect it at https://studio.zibby.dev/integrations`)}throw 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}): ${l}`)}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 Tt.set(o,{data:i,expiresAt:e+c}),i}function en(o){o?Tt.delete(o):Tt.clear()}function Vr(o){let e=process.env.WORKFLOW_ENABLED_INTEGRATIONS;if(typeof e!="string"||e.trim()==="")return o;let t=new Set(e.split(",").map(n=>n.trim()).filter(Boolean));if(t.size===0)return o;let r={};for(let[n,s]of Object.entries(o))t.has(n)&&(r[n]=s);return r}async function Rs(){let o=Date.now();if(Re&&Re.expiresAt>o)return Re.data;if(qr()){let t={};for(let[n,s]of Object.entries(Wr))t[n]=!!process.env[s];let r=Vr(t);return Re={data:r,expiresAt:o+6e4},r}let e=Xr();if(!e)return{};try{let t=await fetch(`${Qr()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!t.ok)return{};let r=await t.json(),n={};if(r&&typeof r=="object")for(let[i,c]of Object.entries(r))c&&typeof c=="object"&&"connected"in c&&(n[i]=!!c.connected);let s=Vr(n);return Re={data:s,expiresAt:o+6e4},s}catch{return{}}}function Ls(){Re=null}var Tt,Wr,Re,vt=pr(()=>{Tt=new Map,Wr={github:"GITHUB_TOKEN",gitlab:"GITLAB_TOKEN",sentry:"SENTRY_AUTH_TOKEN",slack:"SLACK_BOT_TOKEN"};Re=null});import{readFileSync as jn,existsSync as Bn}from"node:fs";import{join as Ge,resolve as Fn,isAbsolute as Ji}from"node:path";import{DEFAULT_OUTPUT_BASE as Yi,SESSIONS_DIR as Gn,RESULT_FILE as Hi,resolveWorkflowSession as Zi,clearInheritedSessionEnvForFreshRun as Vi,readPinnedSessionPathFromEnv as Wi}from"@zibby/agent-workflow";import{registerStrategy as xt}from"@zibby/agent-workflow";import{AgentStrategy as to,getSkill as br,NO_INTEGRATION_TOGGLEABLE_SKILL_IDS as ro}from"@zibby/agent-workflow";import{query as no}from"@anthropic-ai/claude-agent-sdk";import Hn from"node:process";var dr=Object.freeze(["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_INSTANCES","ATLASSIAN_ACCESS_TOKEN","JIRA_API_TOKEN","JIRA_EMAIL","SENTRY_AUTH_TOKEN","SLACK_BOT_TOKEN","DISCORD_BOT_TOKEN","ZIBBY_CHAT_SLACK_TOKEN","ZIBBY_CHAT_LARK_APP_SECRET","ZIBBY_CHAT_DISCORD_INTERACTION_TOKEN","LINEAR_API_KEY","LINEAR_OAUTH_TOKEN","PLANE_API_KEY","PLANE_OAUTH_TOKEN","ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_MEMORY_AWS_ACCESS_KEY_ID","ZIBBY_MEMORY_AWS_SECRET_ACCESS_KEY","ZIBBY_MEMORY_AWS_SESSION_TOKEN"]);function xe(o=Hn.env){let e={},t=new Set(dr);for(let[r,n]of Object.entries(o))t.has(r)||n!==void 0&&(e[r]=n);return e}function at(o){return!!o&&(o.transport==="http"||typeof o.url=="string"&&!o.command)}function ee(o,e,{processEnv:t}={}){if(!e)return null;if(at(e)){let n=String(e.url||"").trim();if(!n)return null;let s=e.headers&&typeof e.headers=="object"?e.headers:void 0;switch(o){case"claude":return{type:"http",url:n,...s&&{headers:s}};case"codex":return{url:n,...s&&{http_headers:s}};case"gemini":return{url:n,type:"http",...s&&{headers:s}};case"cursor":return{url:n,...s&&{headers:s}};default:return{type:"http",url:n,...s&&{headers:s}}}}let r={command:e.command};return e.args?.length&&(r.args=e.args),e.cwd&&(r.cwd=e.cwd),t?r.env={...t,...e.env||{}}:e.env&&Object.keys(e.env).length&&(r.env=e.env),r}function lt(o){return at(o)?`http \u2192 ${String(o.url||"").replace(/\?.*$/,"")}`:`${o?.command||"?"} ${(o?.args||[]).join(" ")}`.trim()}Ke();import{writeFileSync as Pt,mkdirSync as Nt,existsSync as ve,readFileSync as _r}from"fs";import{homedir as wr}from"os";import{join as X}from"path";import ze from"chalk";var te={debug:0,info:1,warn:2,error:3,silent:4},ct=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return te.debug;if(process.env.ZIBBY_VERBOSE==="true")return te.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in te?te[e]:te.info}_shouldLog(e){return te[e]>=this._level}_formatMessage(e,t,r={}){let n=new Date().toISOString(),i=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(i+=ze.dim(` ${JSON.stringify(r)}`)),i}_getPrefix(e){return{debug:ze.gray("[DEBUG]"),info:ze.cyan("[INFO]"),warn:ze.yellow("[WARN]"),error:ze.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 te&&(this._level=te[e])}getLevel(){return Object.keys(te).find(e=>te[e]===this._level)}},f=new ct;import{timeline as ne,Timeline as pa,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as fa}from"@zibby/agent-workflow";var Te=[{alias:"auto",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",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:"opus-5",canonicalId:"claude-opus-5",vendor:"claude",label:"Claude \xB7 Opus 5",family:"claude-opus-5",pickerVisible:!0},{alias:"claude-opus-5",canonicalId:"claude-opus-5",vendor:"claude",family:"claude-opus-5",aliasOf:"opus-5"},{alias:"sonnet-5",canonicalId:"claude-sonnet-5",vendor:"claude",label:"Claude \xB7 Sonnet 5",family:"claude-sonnet-5",pickerVisible:!0},{alias:"claude-sonnet-5",canonicalId:"claude-sonnet-5",vendor:"claude",family:"claude-sonnet-5",aliasOf:"sonnet-5"},{alias:"fable-5",canonicalId:"claude-fable-5",vendor:"claude",label:"Claude \xB7 Fable 5",family:"claude-fable-5",pickerVisible:!0},{alias:"claude-fable-5",canonicalId:"claude-fable-5",vendor:"claude",family:"claude-fable-5",aliasOf:"fable-5"},{alias:"sonnet-4.8",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4"},{alias:"sonnet-4-8",canonicalId:"claude-sonnet-4-6",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-6",vendor:"claude",family:"claude-sonnet-4"},{alias:"sonnet-4-7",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.7"},{alias:"sonnet-4.6",canonicalId:"claude-sonnet-4-6",vendor:"claude",label:"Claude \xB7 Sonnet 4.6",family:"claude-sonnet-4",pickerVisible:!0,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-6",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-6",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:"gpt-5.6-luna",vendor:"codex",family:"gpt-5",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"},{alias:"gpt-5.5",canonicalId:"gpt-5.5",vendor:"codex",label:"Codex \xB7 GPT-5.5",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.6-luna",canonicalId:"gpt-5.6-luna",vendor:"codex",label:"Codex \xB7 GPT-5.6 Luna",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.6-terra",canonicalId:"gpt-5.6-terra",vendor:"codex",label:"Codex \xB7 GPT-5.6 Terra",family:"gpt-5",pickerVisible:!0},{alias:"auto",canonicalId:"gemini-3-pro",vendor:"gemini",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 Je(o){let e={};for(let t of Te)t.vendor===o&&(e[t.alias]=t.canonicalId);return e}function Wn(o){if(!o||typeof o!="string")return null;let e=o.toLowerCase();for(let t of Te)if(t.alias.toLowerCase()===e)return t.family??null;for(let t of Te)if(t.canonicalId.toLowerCase()===e)return t.family??null;return null}function hr(o){let e=String(o||"").match(/(\d+(?:\.\d+)?)/);return e?parseFloat(e[1]):0}function yr(o){let e=String(o||"").toLowerCase();return/\b(base|mini)\b/.test(e)?0:/\b(opus|pro)\b/.test(e)?2:1}function qn(o,e){let t=hr(e.label)-hr(o.label);if(t!==0)return t;let r=yr(e.label)-yr(o.label);return r!==0?r:o.label.localeCompare(e.label)}function Xn(){let o=[],e=new Map;for(let r of Te)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(qn));return t}function Ae(o,e){let t=typeof e=="string"?e.trim():"";if(t&&t!=="auto")return t;if(t==="auto"&&Te.some(r=>r.vendor===o&&r.isDefault))return"auto";throw new Error(`[${o}] No model reached this LLM call: the node passed none, no config sets one, and the run carries none (MODEL env unset). Refusing to silently substitute a vendor default \u2014 pick a model on the agent (deploy modal / MODEL cell) or pass options.model explicitly.`)}var ae={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"},Qn={ASSISTANT:"assistant",CLAUDE:"claude",CURSOR:"cursor",CODEX:"codex",GEMINI:"gemini"},eo={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error",SILENT:"silent"},ut=Je("claude"),pt=Je("codex"),kt=Je("gemini"),ft={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};function q(o){let e=`${o}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let r=t.split(/[,\n]+/).map(i=>i.trim()).filter(Boolean);if(r.length===0)return{picked:null,count:0,dispose:()=>{}};let n=r[Math.floor(Math.random()*r.length)],s=process.env[o];return process.env[o]=n,f.debug(`[auth-pool] ${o}: picked 1 of ${r.length} from pool (***${n.slice(-4)})`),{picked:n,count:r.length,dispose(){s===void 0?delete process.env[o]:process.env[o]=s}}}function dt(o){if(!o||typeof o!="object")return null;let e=(...n)=>{for(let s of n){if(s==null||s==="")continue;let i=Number(s);if(Number.isFinite(i))return i}return null},t=e(o.input_tokens,o.inputTokens,o.prompt_tokens,o.promptTokens),r=e(o.output_tokens,o.outputTokens,o.completion_tokens,o.completionTokens);return t==null&&r==null?null:{input:t||0,output:r||0}}import{createRequire as oo}from"module";import J from"process";var Sr=oo(import.meta.url);function so(){try{if(J.env.CLAUDE_CODE_EXECUTABLE&&ve(J.env.CLAUDE_CODE_EXECUTABLE))return J.env.CLAUDE_CODE_EXECUTABLE;let o=J.platform,e=J.arch,t=`@anthropic-ai/claude-agent-sdk-${o}-${e}`,r=o==="win32"?"claude.exe":"claude";try{let n=Sr.resolve(`${t}/package.json`),s=X(n,"..",r);if(ve(s))return s}catch{}try{let n=Sr.resolve("@anthropic-ai/claude-agent-sdk/package.json"),s=X(n,"..");for(let c of[r,X("vendor",r),X("bin",r)]){let l=X(s,c);if(ve(l))return l}let i=X(s,"..",`claude-agent-sdk-${o}-${e}`,r);if(ve(i))return i}catch{}}catch{}return null}var mt=so();mt&&f.debug(`Claude native CLI resolved to baked binary: ${mt}`);var pe=class extends to{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!J.env.ANTHROPIC_API_KEY||!!J.env.ANTHROPIC_API_KEY_POOL,r=!!J.env.CLAUDE_CODE_OAUTH_TOKEN||!!J.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,n=!!J.env.ANTHROPIC_AUTH_TOKEN||!!J.env.ANTHROPIC_AUTH_TOKEN_POOL,s=t||r||n;return s||f.debug("ClaudeAgentStrategy: no credentials. Set one of ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_AUTH_TOKEN (or a *_POOL variant for multi-token rotation)."),s}async invoke(e,t={}){let{model:r,workspace:n=J.cwd(),schema:s=null,images:i=[],skills:c=null,sessionPath:l=null,nodeName:a=null,timeout:u,config:d={},activityLog:m=!1,signal:p=null,sessionId:g,resume:y,forkSession:h,sessionStore:b}=t,w=Ae("claude",r),E=ut[w]||w;ut[w]&&w!==E&&f.debug(`Mapped model: ${w} \u2192 ${E}`);let S=[q("ANTHROPIC_API_KEY"),q("CLAUDE_CODE_OAUTH_TOKEN"),q("ANTHROPIC_AUTH_TOKEN")];try{f.debug(`Invoking Claude Agent SDK with model: ${E}, skills: ${JSON.stringify(c)}`);let v=(_,I)=>{let T=String(_??"");return T.length>I?`${T.slice(0,I)}\u2026`:T},k=(_,I)=>{try{console.log(JSON.stringify({mode:_,...I}))}catch{}},R=/secret|token|password|passwd|credential|authorization|bearer|api[-_]?key|private[-_]?key|access[-_]?key/i,C=(_,I=0)=>{if(_==null||I>6||typeof _!="object")return _;let T=Array.isArray(_)?[]:{};for(let[B,$]of Object.entries(_)){let F=R.test(B)||B==="value"&&typeof _.key=="string";T[B]=F&&typeof $=="string"&&$?"[redacted]":C($,I+1)}return T},L=_=>{try{if(_==null)return"";let I=C(_),T=typeof I=="string"?I:JSON.stringify(I);return v(String(T).slice(0,4e3).replace(/(bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,"$1[redacted]").replace(/(https?:\/\/[^/\s:@"']+):[^@/\s"']+@/gi,"$1:[redacted]@").replace(/([?&](?:token|api[-_]?key|apikey|secret|access[-_]?token|auth|key)=)[^&"'\s]+/gi,"$1[redacted]").replace(/sk-[A-Za-z0-9_-]{8,}/g,"sk-[redacted]").replace(/xox[bpoas]-[A-Za-z0-9-]{6,}/g,"xoxb-[redacted]").replace(/zby_[A-Za-z0-9_-]{12,}/g,"zby_[redacted]").replace(/gh[pousr]_[A-Za-z0-9]{20,}/g,"gh_[redacted]").replace(/glpat-[A-Za-z0-9_-]{16,}/g,"glpat-[redacted]").replace(/\bmcp_(?!_)[A-Za-z0-9-]{12,}/g,"mcp_[redacted]").replace(/ntn_[A-Za-z0-9]{10,}/g,"ntn_[redacted]").replace(/figd_[A-Za-z0-9_-]{10,}/g,"figd_[redacted]").replace(/sntrys_[A-Za-z0-9+/=._-]{10,}/g,"sntrys_[redacted]").replace(/ya29\.[A-Za-z0-9_-]{10,}/g,"ya29.[redacted]").replace(/AKIA[0-9A-Z]{16}/g,"AKIA[redacted]").replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*/g,"[redacted-private-key]").replace(/eyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,"eyJ[redacted-jwt]"),300)}catch{return""}},K=J.env.CLAUDE_CODE_OAUTH_TOKEN,P=J.env.ANTHROPIC_API_KEY,D=J.env.ANTHROPIC_AUTH_TOKEN;J.env.CLAUDE_CODE_CREDENTIALS_JSON?lo(J.env.CLAUDE_CODE_CREDENTIALS_JSON):K&&ao(K,J.env.__ZIBBY_CLAUDE_PLAN);let M=J.env.__ZIBBY_CLAUDE_PLAN,O=M?M.charAt(0).toUpperCase()+M.slice(1):null,j;if(K?j=O?`Claude ${O} plan \xB7 ***${K.slice(-4)}`:`Subscription \xB7 ***${K.slice(-4)}`:P?j=`API key \xB7 ***${P.slice(-4)}`:D?j=`Bearer \xB7 ***${D.slice(-4)}`:j="NONE \u2014 request will fail",!m){let _=(await import("chalk")).default;console.log(""),console.log(` ${_.cyan("\u25C6")} ${_.bold(E)}`),console.log(` ${_.dim("Auth: ")}${j}`),console.log(` ${_.dim("Workdir: ")}${n}`),console.log(""),console.log(_.bold("Prompt sent to LLM:")),console.log(_.dim("\u2500".repeat(60))),console.log(_.dim(e)),console.log(_.dim("\u2500".repeat(60)))}let{allowedTools:N,mcpServers:x}=this._resolveSkills(c,{sessionPath:l,workspace:n,nodeName:a});for(let _ of t.extraMcpServers||[])if(_&&_.serverName&&_.def){if(Object.prototype.hasOwnProperty.call(x,_.serverName)){console.warn(`[custom-mcp] skip "${_.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let I=ee("claude",_.def);I&&(x[_.serverName]=I,N.push(`mcp__${_.serverName}__*`))}try{let _={cwd:n,allowedTools:N,...Array.isArray(t.disallowedTools)&&t.disallowedTools.length?{disallowedTools:t.disallowedTools}:{},settings:{permissions:{allow:["Bash(*)","Read(*)","Write(*)","Edit(*)","MultiEdit(*)","NotebookEdit(*)","Grep(*)","Glob(*)","WebFetch(*)","WebSearch(*)","Task(*)","TodoWrite(*)","Skill(*)"]}},model:E,env:xe(J.env),...mt&&{pathToClaudeCodeExecutable:mt},...Object.keys(x).length>0&&{mcpServers:x},...g&&{sessionId:g},...y&&{resume:y},...h&&{forkSession:!0},...b&&{sessionStore:b}};if(s){let V=typeof s.parse=="function"?ue(s):s;_.outputFormat={type:"json_schema",schema:V},f.debug("Structured output enforced via SDK outputFormat")}f.debug(`Agent SDK options: ${JSON.stringify({cwd:_.cwd,toolCount:N.length,permissionMode:_.permissionMode,model:_.model,hasOutputFormat:!!_.outputFormat})}`);let I="",T=0,B=[];f.debug("Starting Claude Agent SDK query stream");let $=e,F=Array.isArray(i)?i.filter(A=>A&&typeof A.path=="string"&&A.path.startsWith("/")):[];if(F.length){let A=F.map((V,G)=>` ${G+1}. ${V.path}${V.name?` (${V.name})`:""}`).join(`
2
- `);$=`${e}
1
+ var Jn=Object.defineProperty;var Yn=(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 pr=(o,e,t)=>()=>{if(t)throw t[0];try{return o&&(e=o(o=0)),e}catch(r){throw t=[r],r}};var fr=(o,e)=>{for(var t in e)Jn(o,t,{get:e[t],enumerable:!0})};var gr={};fr(gr,{zodToJson:()=>ue});import{z as mr}from"zod";import{zodToJsonSchema as qn}from"zod-to-json-schema";function Xn(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 Ee(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]=Ee(o[e][t]);for(let e of["anyOf","oneOf","allOf"])Array.isArray(o[e])&&(o[e]=o[e].map(Ee));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=Ee(o.properties[r]);t.has(r)||(n=Xn(n)),o.properties[r]=n}o.required=e}return o.items&&(Array.isArray(o.items)?o.items=o.items.map(Ee):o.items=Ee(o.items)),o}function ue(o,e={target:"openApi3"}){if(!o)return null;let t=e?.target==="openAi",r=null;if(typeof mr?.toJSONSchema=="function")try{r=mr.toJSONSchema(o)}catch{}if(!r)try{r=qn(o,e)}catch{return null}if(t&&r)try{return Ee(r)}catch{return r}return r}var Ke=pr(()=>{});var tn={};fr(tn,{clearConnectedCache:()=>Us,clearTokenCache:()=>en,getConnectedIntegrations:()=>Ds,resolveIntegrationToken:()=>At});import{existsSync as Ns,readFileSync as Rs}from"node:fs";import{homedir as Ls}from"node:os";import{join as Ms}from"node:path";function qr(){let o=process.env.ZIBBY_SELF_HOST;return o!=null&&o!==""&&o!=="0"&&o.toLowerCase()!=="false"}function Xr(){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=Ms(Ls(),".zibby","config.json");return Ns(o)&&JSON.parse(Rs(o,"utf-8")).sessionToken||null}catch{return null}}function Qr(){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 At(o){if(qr()){let l=Vr[o];if(l&&process.env[l])return{token:process.env[l]}}let e=Date.now(),t=Tt.get(o);if(t&&t.expiresAt>e)return t.data;let r=Xr();if(!r)throw new Error("Missing session credential: neither PROJECT_API_TOKEN nor ZIBBY_USER_TOKEN is set in this process env (and no ~/.zibby/config.json session). If this is an MCP skill child, the spawning skill must forward them \u2014 check the skill's envKeys / resolve() env (see @zibby/skills backend-session-env-contract). Interactive CLI: run `zibby login`.");let n=`${Qr()}/integrations/token/${o}`,s=await fetch(n,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!s.ok){let l=await s.text().catch(()=>"");if(s.status===404){let a="";try{a=String(JSON.parse(l)?.error||"").trim()}catch{}throw new Error(a||`${o} is not connected. Connect it at https://studio.zibby.dev/integrations`)}throw 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}): ${l}`)}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 Tt.set(o,{data:i,expiresAt:e+c}),i}function en(o){o?Tt.delete(o):Tt.clear()}function Wr(o){let e=process.env.WORKFLOW_ENABLED_INTEGRATIONS;if(typeof e!="string"||e.trim()==="")return o;let t=new Set(e.split(",").map(n=>n.trim()).filter(Boolean));if(t.size===0)return o;let r={};for(let[n,s]of Object.entries(o))t.has(n)&&(r[n]=s);return r}async function Ds(){let o=Date.now();if(Re&&Re.expiresAt>o)return Re.data;if(qr()){let t={};for(let[n,s]of Object.entries(Vr))t[n]=!!process.env[s];let r=Wr(t);return Re={data:r,expiresAt:o+6e4},r}let e=Xr();if(!e)return{};try{let t=await fetch(`${Qr()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!t.ok)return{};let r=await t.json(),n={};if(r&&typeof r=="object")for(let[i,c]of Object.entries(r))c&&typeof c=="object"&&"connected"in c&&(n[i]=!!c.connected);let s=Wr(n);return Re={data:s,expiresAt:o+6e4},s}catch{return{}}}function Us(){Re=null}var Tt,Vr,Re,vt=pr(()=>{Tt=new Map,Vr={github:"GITHUB_TOKEN",gitlab:"GITLAB_TOKEN",sentry:"SENTRY_AUTH_TOKEN",slack:"SLACK_BOT_TOKEN"};Re=null});import{readFileSync as jn,existsSync as Bn}from"node:fs";import{join as Ge,resolve as Fn,isAbsolute as Zi}from"node:path";import{DEFAULT_OUTPUT_BASE as Wi,SESSIONS_DIR as Gn,RESULT_FILE as Vi,resolveWorkflowSession as qi,clearInheritedSessionEnvForFreshRun as Xi,readPinnedSessionPathFromEnv as Qi}from"@zibby/agent-workflow";import{registerStrategy as xt}from"@zibby/agent-workflow";import{AgentStrategy as oo,getSkill as br,NO_INTEGRATION_TOGGLEABLE_SKILL_IDS as so}from"@zibby/agent-workflow";import{query as io}from"@anthropic-ai/claude-agent-sdk";import Hn from"node:process";var dr=Object.freeze(["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_INSTANCES","ATLASSIAN_ACCESS_TOKEN","JIRA_API_TOKEN","JIRA_EMAIL","SENTRY_AUTH_TOKEN","SLACK_BOT_TOKEN","DISCORD_BOT_TOKEN","ZIBBY_CHAT_SLACK_TOKEN","ZIBBY_CHAT_LARK_APP_SECRET","ZIBBY_CHAT_DISCORD_INTERACTION_TOKEN","LINEAR_API_KEY","LINEAR_OAUTH_TOKEN","PLANE_API_KEY","PLANE_OAUTH_TOKEN","ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_MEMORY_AWS_ACCESS_KEY_ID","ZIBBY_MEMORY_AWS_SECRET_ACCESS_KEY","ZIBBY_MEMORY_AWS_SESSION_TOKEN"]);function xe(o=Hn.env){let e={},t=new Set(dr);for(let[r,n]of Object.entries(o))t.has(r)||n!==void 0&&(e[r]=n);return e}function at(o){return!!o&&(o.transport==="http"||typeof o.url=="string"&&!o.command)}var Zn=new Set(["claude"]);function Wn(){let o=String(process.env.MCP_ALWAYS_LOAD??"").trim().toLowerCase();return!(o==="0"||o==="false"||o==="off")}function Vn(o,e){return Zn.has(o)?Wn()?typeof e.alwaysLoad=="boolean"?{alwaysLoad:e.alwaysLoad}:{}:{}:{}}function ee(o,e,{processEnv:t}={}){if(!e)return null;let r=Vn(o,e);if(at(e)){let s=String(e.url||"").trim();if(!s)return null;let i=e.headers&&typeof e.headers=="object"?e.headers:void 0;switch(o){case"claude":return{type:"http",url:s,...i&&{headers:i},...r};case"codex":return{url:s,...i&&{http_headers:i}};case"gemini":return{url:s,type:"http",...i&&{headers:i}};case"cursor":return{url:s,...i&&{headers:i}};default:return{type:"http",url:s,...i&&{headers:i},...r}}}let n={command:e.command};return e.args?.length&&(n.args=e.args),e.cwd&&(n.cwd=e.cwd),t?n.env={...t,...e.env||{}}:e.env&&Object.keys(e.env).length&&(n.env=e.env),{...n,...r}}function lt(o){return at(o)?`http \u2192 ${String(o.url||"").replace(/\?.*$/,"")}`:`${o?.command||"?"} ${(o?.args||[]).join(" ")}`.trim()}Ke();import{writeFileSync as Pt,mkdirSync as Nt,existsSync as ve,readFileSync as _r}from"fs";import{homedir as wr}from"os";import{join as X}from"path";import ze from"chalk";var te={debug:0,info:1,warn:2,error:3,silent:4},ct=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return te.debug;if(process.env.ZIBBY_VERBOSE==="true")return te.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in te?te[e]:te.info}_shouldLog(e){return te[e]>=this._level}_formatMessage(e,t,r={}){let n=new Date().toISOString(),i=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(i+=ze.dim(` ${JSON.stringify(r)}`)),i}_getPrefix(e){return{debug:ze.gray("[DEBUG]"),info:ze.cyan("[INFO]"),warn:ze.yellow("[WARN]"),error:ze.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 te&&(this._level=te[e])}getLevel(){return Object.keys(te).find(e=>te[e]===this._level)}},f=new ct;import{timeline as ne,Timeline as ma,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as ga}from"@zibby/agent-workflow";var Te=[{alias:"auto",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",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:"opus-5",canonicalId:"claude-opus-5",vendor:"claude",label:"Claude \xB7 Opus 5",family:"claude-opus-5",pickerVisible:!0},{alias:"claude-opus-5",canonicalId:"claude-opus-5",vendor:"claude",family:"claude-opus-5",aliasOf:"opus-5"},{alias:"sonnet-5",canonicalId:"claude-sonnet-5",vendor:"claude",label:"Claude \xB7 Sonnet 5",family:"claude-sonnet-5",pickerVisible:!0},{alias:"claude-sonnet-5",canonicalId:"claude-sonnet-5",vendor:"claude",family:"claude-sonnet-5",aliasOf:"sonnet-5"},{alias:"fable-5",canonicalId:"claude-fable-5",vendor:"claude",label:"Claude \xB7 Fable 5",family:"claude-fable-5",pickerVisible:!0},{alias:"claude-fable-5",canonicalId:"claude-fable-5",vendor:"claude",family:"claude-fable-5",aliasOf:"fable-5"},{alias:"sonnet-4.8",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4"},{alias:"sonnet-4-8",canonicalId:"claude-sonnet-4-6",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-6",vendor:"claude",family:"claude-sonnet-4"},{alias:"sonnet-4-7",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.7"},{alias:"sonnet-4.6",canonicalId:"claude-sonnet-4-6",vendor:"claude",label:"Claude \xB7 Sonnet 4.6",family:"claude-sonnet-4",pickerVisible:!0,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-6",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-6",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:"gpt-5.6-luna",vendor:"codex",family:"gpt-5",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"},{alias:"gpt-5.5",canonicalId:"gpt-5.5",vendor:"codex",label:"Codex \xB7 GPT-5.5",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.6-luna",canonicalId:"gpt-5.6-luna",vendor:"codex",label:"Codex \xB7 GPT-5.6 Luna",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.6-terra",canonicalId:"gpt-5.6-terra",vendor:"codex",label:"Codex \xB7 GPT-5.6 Terra",family:"gpt-5",pickerVisible:!0},{alias:"auto",canonicalId:"gemini-3-pro",vendor:"gemini",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 Je(o){let e={};for(let t of Te)t.vendor===o&&(e[t.alias]=t.canonicalId);return e}function Qn(o){if(!o||typeof o!="string")return null;let e=o.toLowerCase();for(let t of Te)if(t.alias.toLowerCase()===e)return t.family??null;for(let t of Te)if(t.canonicalId.toLowerCase()===e)return t.family??null;return null}function hr(o){let e=String(o||"").match(/(\d+(?:\.\d+)?)/);return e?parseFloat(e[1]):0}function yr(o){let e=String(o||"").toLowerCase();return/\b(base|mini)\b/.test(e)?0:/\b(opus|pro)\b/.test(e)?2:1}function eo(o,e){let t=hr(e.label)-hr(o.label);if(t!==0)return t;let r=yr(e.label)-yr(o.label);return r!==0?r:o.label.localeCompare(e.label)}function to(){let o=[],e=new Map;for(let r of Te)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(eo));return t}function Ae(o,e){let t=typeof e=="string"?e.trim():"";if(t&&t!=="auto")return t;if(t==="auto"&&Te.some(r=>r.vendor===o&&r.isDefault))return"auto";throw new Error(`[${o}] No model reached this LLM call: the node passed none, no config sets one, and the run carries none (MODEL env unset). Refusing to silently substitute a vendor default \u2014 pick a model on the agent (deploy modal / MODEL cell) or pass options.model explicitly.`)}var ae={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"},ro={ASSISTANT:"assistant",CLAUDE:"claude",CURSOR:"cursor",CODEX:"codex",GEMINI:"gemini"},no={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error",SILENT:"silent"},ut=Je("claude"),pt=Je("codex"),kt=Je("gemini"),ft={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};function q(o){let e=`${o}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let r=t.split(/[,\n]+/).map(i=>i.trim()).filter(Boolean);if(r.length===0)return{picked:null,count:0,dispose:()=>{}};let n=r[Math.floor(Math.random()*r.length)],s=process.env[o];return process.env[o]=n,f.debug(`[auth-pool] ${o}: picked 1 of ${r.length} from pool (***${n.slice(-4)})`),{picked:n,count:r.length,dispose(){s===void 0?delete process.env[o]:process.env[o]=s}}}function dt(o){if(!o||typeof o!="object")return null;let e=(...n)=>{for(let s of n){if(s==null||s==="")continue;let i=Number(s);if(Number.isFinite(i))return i}return null},t=e(o.input_tokens,o.inputTokens,o.prompt_tokens,o.promptTokens),r=e(o.output_tokens,o.outputTokens,o.completion_tokens,o.completionTokens);return t==null&&r==null?null:{input:t||0,output:r||0}}import{createRequire as ao}from"module";import J from"process";var Sr=ao(import.meta.url);function lo(){try{if(J.env.CLAUDE_CODE_EXECUTABLE&&ve(J.env.CLAUDE_CODE_EXECUTABLE))return J.env.CLAUDE_CODE_EXECUTABLE;let o=J.platform,e=J.arch,t=`@anthropic-ai/claude-agent-sdk-${o}-${e}`,r=o==="win32"?"claude.exe":"claude";try{let n=Sr.resolve(`${t}/package.json`),s=X(n,"..",r);if(ve(s))return s}catch{}try{let n=Sr.resolve("@anthropic-ai/claude-agent-sdk/package.json"),s=X(n,"..");for(let c of[r,X("vendor",r),X("bin",r)]){let l=X(s,c);if(ve(l))return l}let i=X(s,"..",`claude-agent-sdk-${o}-${e}`,r);if(ve(i))return i}catch{}}catch{}return null}var mt=lo();mt&&f.debug(`Claude native CLI resolved to baked binary: ${mt}`);var pe=class extends oo{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!J.env.ANTHROPIC_API_KEY||!!J.env.ANTHROPIC_API_KEY_POOL,r=!!J.env.CLAUDE_CODE_OAUTH_TOKEN||!!J.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,n=!!J.env.ANTHROPIC_AUTH_TOKEN||!!J.env.ANTHROPIC_AUTH_TOKEN_POOL,s=t||r||n;return s||f.debug("ClaudeAgentStrategy: no credentials. Set one of ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_AUTH_TOKEN (or a *_POOL variant for multi-token rotation)."),s}async invoke(e,t={}){let{model:r,workspace:n=J.cwd(),schema:s=null,images:i=[],skills:c=null,sessionPath:l=null,nodeName:a=null,timeout:u,config:d={},activityLog:m=!1,signal:p=null,sessionId:g,resume:y,forkSession:h,sessionStore:b}=t,w=Ae("claude",r),E=ut[w]||w;ut[w]&&w!==E&&f.debug(`Mapped model: ${w} \u2192 ${E}`);let S=[q("ANTHROPIC_API_KEY"),q("CLAUDE_CODE_OAUTH_TOKEN"),q("ANTHROPIC_AUTH_TOKEN")];try{f.debug(`Invoking Claude Agent SDK with model: ${E}, skills: ${JSON.stringify(c)}`);let v=(_,I)=>{let T=String(_??"");return T.length>I?`${T.slice(0,I)}\u2026`:T},k=(_,I)=>{try{console.log(JSON.stringify({mode:_,...I}))}catch{}},R=/secret|token|password|passwd|credential|authorization|bearer|api[-_]?key|private[-_]?key|access[-_]?key/i,C=(_,I=0)=>{if(_==null||I>6||typeof _!="object")return _;let T=Array.isArray(_)?[]:{};for(let[B,O]of Object.entries(_)){let F=R.test(B)||B==="value"&&typeof _.key=="string";T[B]=F&&typeof O=="string"&&O?"[redacted]":C(O,I+1)}return T},L=_=>{try{if(_==null)return"";let I=C(_),T=typeof I=="string"?I:JSON.stringify(I);return v(String(T).slice(0,4e3).replace(/(bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,"$1[redacted]").replace(/(https?:\/\/[^/\s:@"']+):[^@/\s"']+@/gi,"$1:[redacted]@").replace(/([?&](?:token|api[-_]?key|apikey|secret|access[-_]?token|auth|key)=)[^&"'\s]+/gi,"$1[redacted]").replace(/sk-[A-Za-z0-9_-]{8,}/g,"sk-[redacted]").replace(/xox[bpoas]-[A-Za-z0-9-]{6,}/g,"xoxb-[redacted]").replace(/zby_[A-Za-z0-9_-]{12,}/g,"zby_[redacted]").replace(/gh[pousr]_[A-Za-z0-9]{20,}/g,"gh_[redacted]").replace(/glpat-[A-Za-z0-9_-]{16,}/g,"glpat-[redacted]").replace(/\bmcp_(?!_)[A-Za-z0-9-]{12,}/g,"mcp_[redacted]").replace(/ntn_[A-Za-z0-9]{10,}/g,"ntn_[redacted]").replace(/figd_[A-Za-z0-9_-]{10,}/g,"figd_[redacted]").replace(/sntrys_[A-Za-z0-9+/=._-]{10,}/g,"sntrys_[redacted]").replace(/ya29\.[A-Za-z0-9_-]{10,}/g,"ya29.[redacted]").replace(/AKIA[0-9A-Z]{16}/g,"AKIA[redacted]").replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*/g,"[redacted-private-key]").replace(/eyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,"eyJ[redacted-jwt]"),300)}catch{return""}},K=J.env.CLAUDE_CODE_OAUTH_TOKEN,P=J.env.ANTHROPIC_API_KEY,D=J.env.ANTHROPIC_AUTH_TOKEN;J.env.CLAUDE_CODE_CREDENTIALS_JSON?po(J.env.CLAUDE_CODE_CREDENTIALS_JSON):K&&uo(K,J.env.__ZIBBY_CLAUDE_PLAN);let M=J.env.__ZIBBY_CLAUDE_PLAN,$=M?M.charAt(0).toUpperCase()+M.slice(1):null,j;if(K?j=$?`Claude ${$} plan \xB7 ***${K.slice(-4)}`:`Subscription \xB7 ***${K.slice(-4)}`:P?j=`API key \xB7 ***${P.slice(-4)}`:D?j=`Bearer \xB7 ***${D.slice(-4)}`:j="NONE \u2014 request will fail",!m){let _=(await import("chalk")).default;console.log(""),console.log(` ${_.cyan("\u25C6")} ${_.bold(E)}`),console.log(` ${_.dim("Auth: ")}${j}`),console.log(` ${_.dim("Workdir: ")}${n}`),console.log(""),console.log(_.bold("Prompt sent to LLM:")),console.log(_.dim("\u2500".repeat(60))),console.log(_.dim(e)),console.log(_.dim("\u2500".repeat(60)))}let{allowedTools:N,mcpServers:x}=this._resolveSkills(c,{sessionPath:l,workspace:n,nodeName:a});for(let _ of t.extraMcpServers||[])if(_&&_.serverName&&_.def){if(Object.prototype.hasOwnProperty.call(x,_.serverName)){console.warn(`[custom-mcp] skip "${_.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let I=ee("claude",_.def);I&&(x[_.serverName]=I,N.push(`mcp__${_.serverName}__*`))}try{let _={cwd:n,allowedTools:N,...Array.isArray(t.disallowedTools)&&t.disallowedTools.length?{disallowedTools:t.disallowedTools}:{},settings:{permissions:{allow:["Bash(*)","Read(*)","Write(*)","Edit(*)","MultiEdit(*)","NotebookEdit(*)","Grep(*)","Glob(*)","WebFetch(*)","WebSearch(*)","Task(*)","TodoWrite(*)","Skill(*)"]}},model:E,env:xe(J.env),...mt&&{pathToClaudeCodeExecutable:mt},...Object.keys(x).length>0&&{mcpServers:x},...g&&{sessionId:g},...y&&{resume:y},...h&&{forkSession:!0},...b&&{sessionStore:b}};if(s){let W=typeof s.parse=="function"?ue(s):s;_.outputFormat={type:"json_schema",schema:W},f.debug("Structured output enforced via SDK outputFormat")}f.debug(`Agent SDK options: ${JSON.stringify({cwd:_.cwd,toolCount:N.length,permissionMode:_.permissionMode,model:_.model,hasOutputFormat:!!_.outputFormat})}`);let I="",T=0,B=[];f.debug("Starting Claude Agent SDK query stream");let O=e,F=Array.isArray(i)?i.filter(A=>A&&typeof A.path=="string"&&A.path.startsWith("/")):[];if(F.length){let A=F.map((W,G)=>` ${G+1}. ${W.path}${W.name?` (${W.name})`:""}`).join(`
2
+ `);O=`${e}
3
3
 
4
4
  # Attached image files \u2014 VIEW THESE
5
5
  The user attached ${F.length} image(s), saved locally. Use the Read tool on each path to SEE the image, then use what it shows to answer:
6
- ${A}`}let Y;try{Y=no({prompt:$,options:_})}catch(A){throw f.error(`Failed to initialize Claude Agent SDK: ${A.message}`),A}let Q=null,ie=0,it=3;if(p?.aborted){let A=new Error("Aborted via signal");throw A.name="AbortError",A}try{for await(let A of Y){if(p?.aborted){let G=new Error("Aborted via signal");throw G.name="AbortError",G}if(B.push(A),A.type==="system"&&A.subtype==="init"){let G=A.mcp_servers||[];if(G.length>0){let U=G.map(z=>`${z.name}=${z.status}${z.error?` (${String(z.error).slice(0,120)})`:""}`).join(", ");f.info(`[mcp] SDK init \u2014 ${G.length} server(s): ${U}`);for(let z of G)z.status!=="connected"&&f.warn(`[mcp] server '${z.name}' did not connect: status=${z.status}`,{name:z.name,status:z.status,error:z.error})}else Object.keys(x||{}).length>0&&f.warn(`[mcp] SDK init returned no mcp_servers despite passing ${Object.keys(x).length} server(s) \u2014 SDK version may not expose this field, or config was dropped`);if(Array.isArray(A.tools)){let U=A.tools.filter(z=>z.startsWith("mcp__"));U.length>0?f.info(`[mcp] tools visible to model: ${U.join(", ")}`):Object.keys(x||{}).length>0&&f.warn("[mcp] no mcp__* tools in model's tool list \u2014 MCP servers configured but tools didn't reach the prompt")}}if(A.type==="system"&&A.subtype==="api_retry"){let G=Number(A.attempt)||0,U=Number(A.max_retries)||0,z=A.error_status!=null?String(A.error_status):"?",H=typeof A.error=="string"?A.error:"error",we=Number.isFinite(A.retry_delay_ms)?Math.round(A.retry_delay_ms):null,ur=`upstream ${z} (${H}) \u2014 SDK retry ${G}/${U}`+(we!=null?` in ${we}ms`:"");m&&k("turn:retry",{status:z,kind:H,attempt:G,maxRetries:U,delayMs:we,detail:ur}),f.warn(`[claude] transient ${ur}`);continue}if(A.type==="error"||A.error){let G=A.error?.message||A.error||A.message||"Unknown API error";try{f.error("SDK error event raw payload",{fullMessage:JSON.stringify(A,null,2)})}catch{}throw new Error(typeof G=="string"?G:JSON.stringify(G))}let V=JSON.stringify(A.message?.content||A.text||"").slice(0,200);if(V===Q){if(ie++,ie>=it){let G=(A.message?.content?.[0]?.text||A.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${ie}x repeated): ${G}`)}}else Q=V,ie=1;if(A.type==="assistant"||A.constructor?.name==="AssistantMessage"){let G=A.message?.content||A.content||[];for(let U of G)if(U.type==="thinking"&&U.thinking)m?k("turn:thinking",{text:v(U.thinking,600)}):console.log(`${U.thinking.substring(0,200)}${U.thinking.length>200?"...":""}`);else if(U.type==="text"&&U.text)I+=U.text,m||(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")if(T++,U.name.includes("memory")?ne.stepMemory(`Tool: ${U.name}`):ne.stepTool(`Tool: ${U.name}`),m){let H=L(U.input);k("turn:tool",{name:U.name,...H?{input:H}:{}})}else{let H=JSON.stringify(U.input).substring(0,100);console.log(` Input: ${H}${JSON.stringify(U.input).length>100?"...":""}`)}}else if(!(A.type==="user"&&A.tool_use_result)){if(A.type==="result"||A.constructor?.name==="ResultMessage"){let G=A.result||A.text||A.content||I;try{io({message:A,sessionPath:l,nodeName:a,model:w,toolCallCount:T})}catch(z){f.debug(`usage.json write failed: ${z.message}`)}let U=dt(A?.usage||A?.message?.usage);if(s){if(A.structured_output){f.debug("Using SDK native structured_output");let H=typeof s.parse=="function"?s.parse(A.structured_output):A.structured_output;return{raw:G,structured:H,...U?{usage:U}:{},toolUseCount:T}}if(G){let z=this._extractJson(G,s);if(z)return{raw:G,structured:z,...U?{usage:U}:{},toolUseCount:T}}f.warn(`Could not extract structured output \u2014 returning raw text (${(G||"").length} chars)`)}return G||""}}}if(f.warn(`Agent SDK ended without result. Collected ${B.length} messages`),I.length>0)return f.debug("Returning accumulated text from messages"),I;throw new Error("Claude Agent SDK query ended without result")}catch(A){let V={message:A?.message,name:A?.name,code:A?.code,cause:A?.cause?.message||A?.cause,stack:A?.stack?.split(`
6
+ ${A}`}let Y;try{Y=io({prompt:O,options:_})}catch(A){throw f.error(`Failed to initialize Claude Agent SDK: ${A.message}`),A}let Q=null,ie=0,it=3;if(p?.aborted){let A=new Error("Aborted via signal");throw A.name="AbortError",A}try{for await(let A of Y){if(p?.aborted){let G=new Error("Aborted via signal");throw G.name="AbortError",G}if(B.push(A),A.type==="system"&&A.subtype==="init"){let G=A.mcp_servers||[];if(G.length>0){let U=G.map(z=>`${z.name}=${z.status}${z.error?` (${String(z.error).slice(0,120)})`:""}`).join(", ");f.info(`[mcp] SDK init \u2014 ${G.length} server(s): ${U}`);for(let z of G)z.status!=="connected"&&f.warn(`[mcp] server '${z.name}' did not connect: status=${z.status}`,{name:z.name,status:z.status,error:z.error})}else Object.keys(x||{}).length>0&&f.warn(`[mcp] SDK init returned no mcp_servers despite passing ${Object.keys(x).length} server(s) \u2014 SDK version may not expose this field, or config was dropped`);if(Array.isArray(A.tools)){let U=A.tools.filter(z=>z.startsWith("mcp__"));U.length>0?f.info(`[mcp] tools visible to model: ${U.join(", ")}`):Object.keys(x||{}).length>0&&f.warn("[mcp] no mcp__* tools in model's tool list \u2014 MCP servers configured but tools didn't reach the prompt")}}if(A.type==="system"&&A.subtype==="api_retry"){let G=Number(A.attempt)||0,U=Number(A.max_retries)||0,z=A.error_status!=null?String(A.error_status):"?",H=typeof A.error=="string"?A.error:"error",we=Number.isFinite(A.retry_delay_ms)?Math.round(A.retry_delay_ms):null,ur=`upstream ${z} (${H}) \u2014 SDK retry ${G}/${U}`+(we!=null?` in ${we}ms`:"");m&&k("turn:retry",{status:z,kind:H,attempt:G,maxRetries:U,delayMs:we,detail:ur}),f.warn(`[claude] transient ${ur}`);continue}if(A.type==="error"||A.error){let G=A.error?.message||A.error||A.message||"Unknown API error";try{f.error("SDK error event raw payload",{fullMessage:JSON.stringify(A,null,2)})}catch{}throw new Error(typeof G=="string"?G:JSON.stringify(G))}let W=JSON.stringify(A.message?.content||A.text||"").slice(0,200);if(W===Q){if(ie++,ie>=it){let G=(A.message?.content?.[0]?.text||A.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${ie}x repeated): ${G}`)}}else Q=W,ie=1;if(A.type==="assistant"||A.constructor?.name==="AssistantMessage"){let G=A.message?.content||A.content||[];for(let U of G)if(U.type==="thinking"&&U.thinking)m?k("turn:thinking",{text:v(U.thinking,600)}):console.log(`${U.thinking.substring(0,200)}${U.thinking.length>200?"...":""}`);else if(U.type==="text"&&U.text)I+=U.text,m||(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")if(T++,U.name.includes("memory")?ne.stepMemory(`Tool: ${U.name}`):ne.stepTool(`Tool: ${U.name}`),m){let H=L(U.input);k("turn:tool",{name:U.name,...H?{input:H}:{}})}else{let H=JSON.stringify(U.input).substring(0,100);console.log(` Input: ${H}${JSON.stringify(U.input).length>100?"...":""}`)}}else if(!(A.type==="user"&&A.tool_use_result)){if(A.type==="result"||A.constructor?.name==="ResultMessage"){let G=A.result||A.text||A.content||I;try{co({message:A,sessionPath:l,nodeName:a,model:w,toolCallCount:T})}catch(z){f.debug(`usage.json write failed: ${z.message}`)}let U=dt(A?.usage||A?.message?.usage);if(s){if(A.structured_output){f.debug("Using SDK native structured_output");let H=typeof s.parse=="function"?s.parse(A.structured_output):A.structured_output;return{raw:G,structured:H,...U?{usage:U}:{},toolUseCount:T}}if(G){let z=this._extractJson(G,s);if(z)return{raw:G,structured:z,...U?{usage:U}:{},toolUseCount:T}}f.warn(`Could not extract structured output \u2014 returning raw text (${(G||"").length} chars)`)}return G||""}}}if(f.warn(`Agent SDK ended without result. Collected ${B.length} messages`),I.length>0)return f.debug("Returning accumulated text from messages"),I;throw new Error("Claude Agent SDK query ended without result")}catch(A){let W={message:A?.message,name:A?.name,code:A?.code,cause:A?.cause?.message||A?.cause,stack:A?.stack?.split(`
7
7
  `).slice(0,5).join(`
8
- `),stringified:(()=>{try{return JSON.stringify(A,Object.getOwnPropertyNames(Object(A)))}catch{return String(A)}})()};throw f.error(`Error during query stream: ${A?.message||A}`,V),A}}catch(_){throw f.error("Claude Agent SDK call failed",{message:_?.message,name:_?.name,code:_?.code,cause:_?.cause?.message||_?.cause}),_}}finally{for(let v of S)v.dispose()}}_resolveSkills(e,t){let r=["Read","Write","Edit","Bash","Grep","Glob"];if(e===null)return f.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return f.debug("Default IDE skills for code generation"),{allowedTools:[...r],mcpServers:{}};let n=[...r],s={},i=J.env.WORKFLOW_ENABLED_INTEGRATIONS,c=typeof i=="string"&&i.trim()!==""?new Set(i.split(",").map(u=>u.trim()).filter(Boolean)):null,l=u=>{let d=br(u);return d?.meta?.toggleable===!0?!0:d?.meta?.toggleable===void 0&&ro.includes(u)},a=u=>c!==null&&c.size>0&&l(u)&&!c.has(u);for(let u of e){if(a(u)){f.debug(`Skill "${u}" disabled by enabledIntegrations allowlist \u2014 skipping`);continue}let d=br(u);if(!d){f.warn(`Unknown skill "${u}" \u2014 skipping`);continue}if(d.allowedTools&&n.push(...d.allowedTools),typeof d.resolve=="function"){let m=d.resolve(t),p=ee("claude",m);p&&(s[d.serverName]=p,f.debug(`MCP: ${d.serverName} \u2192 ${lt(m)}`))}}return{allowedTools:n,mcpServers:s}}_extractJson(e,t){let r=[()=>{if(e.includes("===JSON_START===")){let n=e.indexOf("===JSON_START===")+16,s=e.indexOf("===JSON_END===");return e.substring(n,s).trim()}},()=>e.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!e.startsWith("{"))return e.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>e.trim(),()=>{let n=e.indexOf("{"),s=e.lastIndexOf("}");if(n!==-1&&s>n)return e.substring(n,s+1)}];for(let n of r)try{let s=n();if(!s)continue;let i=JSON.parse(s);if(typeof i!="object"||i===null)continue;return typeof t.parse=="function"?t.parse(i):i}catch{}return null}};function io({message:o,sessionPath:e,nodeName:t,model:r,toolCallCount:n}){if(!e||!t)return;let s=o?.usage||o?.message?.usage||{},i=Ye(s.input_tokens,s.inputTokens),c=Ye(s.output_tokens,s.outputTokens),l=Ye(s.cache_read_input_tokens,s.cacheReadInputTokens),a=Ye(s.cache_creation_input_tokens,s.cacheCreationInputTokens),u=Ye(o?.duration_ms,o?.durationMs),d={model:r||null,input_tokens:i,output_tokens:c,cache_read_tokens:l,cache_creation_tokens:a,tool_call_count:typeof n=="number"?n:null,duration_ms:u,captured_at:new Date().toISOString()},m=X(e,t);try{Nt(m,{recursive:!0})}catch{}Pt(X(m,"usage.json"),JSON.stringify(d,null,2),"utf-8")}function Ye(...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 ao(o,e){let t=X(wr(),".claude"),r=X(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(ve(r)&&JSON.parse(_r(r,"utf-8"))?.claudeAiOauth?.accessToken===o)return;Nt(t,{recursive:!0}),Pt(r,JSON.stringify(n,null,2),"utf-8"),f.debug(`Wrote Claude Code OAuth credentials to ${r}`)}catch(s){f.warn(`Could not write ${r}: ${s.message} \u2014 Claude SDK may fail to authenticate.`)}}function lo(o){let e=X(wr(),".claude"),t=X(e,".credentials.json"),r;try{r=JSON.parse(o)}catch(n){f.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${n.message}`);return}if(!r?.claudeAiOauth?.accessToken){f.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if(ve(t)){let n=JSON.parse(_r(t,"utf-8"));if(n?.claudeAiOauth?.accessToken===r.claudeAiOauth.accessToken&&n?.claudeAiOauth?.expiresAt===r.claudeAiOauth.expiresAt)return}Nt(e,{recursive:!0}),Pt(t,JSON.stringify(r,null,2),"utf-8"),f.debug(`Wrote full Claude Code credentials blob to ${t}`)}catch(n){f.warn(`Could not write ${t}: ${n.message} \u2014 Claude SDK may fail to authenticate.`)}}import{AgentStrategy as co,getSkill as uo}from"@zibby/agent-workflow";Ke();import{execSync as He}from"node:child_process";import{readFileSync as po,mkdirSync as Rt,cpSync as fo,existsSync as mo}from"node:fs";import{join as Ze}from"node:path";import{homedir as go}from"node:os";function Lt(o){if(Array.isArray(o))return o.map(Lt);if(o&&typeof o=="object"){let e={};for(let[t,r]of Object.entries(o))r!==null&&(e[t]=Lt(r));return e}return o}var fe=class extends co{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY_POOL||process.env.CODEX_API_KEY||process.env.CODEX_API_KEY_POOL))return f.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return He("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return f.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,images:i=[],skills:c=null,plugins:l=null,sessionPath:a=null,nodeName:u=null,timeout:d,config:m={},signal:p=null}=t,g=[q("OPENAI_API_KEY"),q("CODEX_API_KEY")];try{let{Codex:y}=await import("@openai/codex-sdk"),h=Ae("codex",r),b=pt[h]||h;pt[h]&&h!==b&&f.debug(`Mapped model: ${h} \u2192 ${b}`),f.debug(`Invoking Codex SDK with model: ${b}, skills: ${JSON.stringify(c)}`);let w=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;w&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=w);let E=w?` | key: ***${w.slice(-4)}`:" | key: not set";if(console.log(`
8
+ `),stringified:(()=>{try{return JSON.stringify(A,Object.getOwnPropertyNames(Object(A)))}catch{return String(A)}})()};throw f.error(`Error during query stream: ${A?.message||A}`,W),A}}catch(_){throw f.error("Claude Agent SDK call failed",{message:_?.message,name:_?.name,code:_?.code,cause:_?.cause?.message||_?.cause}),_}}finally{for(let v of S)v.dispose()}}_resolveSkills(e,t){let r=["Read","Write","Edit","Bash","Grep","Glob"];if(e===null)return f.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return f.debug("Default IDE skills for code generation"),{allowedTools:[...r],mcpServers:{}};let n=[...r],s={},i=J.env.WORKFLOW_ENABLED_INTEGRATIONS,c=typeof i=="string"&&i.trim()!==""?new Set(i.split(",").map(u=>u.trim()).filter(Boolean)):null,l=u=>{let d=br(u);return d?.meta?.toggleable===!0?!0:d?.meta?.toggleable===void 0&&so.includes(u)},a=u=>c!==null&&c.size>0&&l(u)&&!c.has(u);for(let u of e){if(a(u)){f.debug(`Skill "${u}" disabled by enabledIntegrations allowlist \u2014 skipping`);continue}let d=br(u);if(!d){f.warn(`Unknown skill "${u}" \u2014 skipping`);continue}if(d.allowedTools&&n.push(...d.allowedTools),typeof d.resolve=="function"){let m=d.resolve(t),p=ee("claude",m);p&&(s[d.serverName]=p,f.debug(`MCP: ${d.serverName} \u2192 ${lt(m)}`))}}return{allowedTools:n,mcpServers:s}}_extractJson(e,t){let r=[()=>{if(e.includes("===JSON_START===")){let n=e.indexOf("===JSON_START===")+16,s=e.indexOf("===JSON_END===");return e.substring(n,s).trim()}},()=>e.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!e.startsWith("{"))return e.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>e.trim(),()=>{let n=e.indexOf("{"),s=e.lastIndexOf("}");if(n!==-1&&s>n)return e.substring(n,s+1)}];for(let n of r)try{let s=n();if(!s)continue;let i=JSON.parse(s);if(typeof i!="object"||i===null)continue;return typeof t.parse=="function"?t.parse(i):i}catch{}return null}};function co({message:o,sessionPath:e,nodeName:t,model:r,toolCallCount:n}){if(!e||!t)return;let s=o?.usage||o?.message?.usage||{},i=Ye(s.input_tokens,s.inputTokens),c=Ye(s.output_tokens,s.outputTokens),l=Ye(s.cache_read_input_tokens,s.cacheReadInputTokens),a=Ye(s.cache_creation_input_tokens,s.cacheCreationInputTokens),u=Ye(o?.duration_ms,o?.durationMs),d={model:r||null,input_tokens:i,output_tokens:c,cache_read_tokens:l,cache_creation_tokens:a,tool_call_count:typeof n=="number"?n:null,duration_ms:u,captured_at:new Date().toISOString()},m=X(e,t);try{Nt(m,{recursive:!0})}catch{}Pt(X(m,"usage.json"),JSON.stringify(d,null,2),"utf-8")}function Ye(...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 uo(o,e){let t=X(wr(),".claude"),r=X(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(ve(r)&&JSON.parse(_r(r,"utf-8"))?.claudeAiOauth?.accessToken===o)return;Nt(t,{recursive:!0}),Pt(r,JSON.stringify(n,null,2),"utf-8"),f.debug(`Wrote Claude Code OAuth credentials to ${r}`)}catch(s){f.warn(`Could not write ${r}: ${s.message} \u2014 Claude SDK may fail to authenticate.`)}}function po(o){let e=X(wr(),".claude"),t=X(e,".credentials.json"),r;try{r=JSON.parse(o)}catch(n){f.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${n.message}`);return}if(!r?.claudeAiOauth?.accessToken){f.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if(ve(t)){let n=JSON.parse(_r(t,"utf-8"));if(n?.claudeAiOauth?.accessToken===r.claudeAiOauth.accessToken&&n?.claudeAiOauth?.expiresAt===r.claudeAiOauth.expiresAt)return}Nt(e,{recursive:!0}),Pt(t,JSON.stringify(r,null,2),"utf-8"),f.debug(`Wrote full Claude Code credentials blob to ${t}`)}catch(n){f.warn(`Could not write ${t}: ${n.message} \u2014 Claude SDK may fail to authenticate.`)}}import{AgentStrategy as fo,getSkill as mo}from"@zibby/agent-workflow";Ke();import{execSync as He}from"node:child_process";import{readFileSync as go,mkdirSync as Rt,cpSync as ho,existsSync as yo}from"node:fs";import{join as Ze}from"node:path";import{homedir as bo}from"node:os";function Lt(o){if(Array.isArray(o))return o.map(Lt);if(o&&typeof o=="object"){let e={};for(let[t,r]of Object.entries(o))r!==null&&(e[t]=Lt(r));return e}return o}var fe=class extends fo{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY_POOL||process.env.CODEX_API_KEY||process.env.CODEX_API_KEY_POOL))return f.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return He("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return f.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,images:i=[],skills:c=null,plugins:l=null,sessionPath:a=null,nodeName:u=null,timeout:d,config:m={},signal:p=null}=t,g=[q("OPENAI_API_KEY"),q("CODEX_API_KEY")];try{let{Codex:y}=await import("@openai/codex-sdk"),h=Ae("codex",r),b=pt[h]||h;pt[h]&&h!==b&&f.debug(`Mapped model: ${h} \u2192 ${b}`),f.debug(`Invoking Codex SDK with model: ${b}, skills: ${JSON.stringify(c)}`);let w=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;w&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=w);let E=w?` | key: ***${w.slice(-4)}`:" | key: not set";if(console.log(`
9
9
  \u25C6 Model: ${b}${E}
10
- `),Array.isArray(l)&&l.length>0){let O=this._resolveCodexHome(a);process.env.CODEX_HOME=O;try{Rt(O,{recursive:!0})}catch{}this._ensurePlugins(l,O)}let S=(await import("chalk")).default;console.log(`
11
- ${S.bold("Prompt sent to LLM:")}`),console.log(S.dim("\u2500".repeat(60))),console.log(S.dim(e)),console.log(S.dim("\u2500".repeat(60)));let v=this._resolveSkillsToMcp(c,{sessionPath:a,workspace:n,nodeName:u});for(let O of t.extraMcpServers||[])if(O&&O.serverName&&O.def){if(Object.prototype.hasOwnProperty.call(v,O.serverName)){console.warn(`[custom-mcp] skip "${O.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let j=ee("codex",O.def);j&&(v[O.serverName]=j)}let k={};Object.keys(v).length>0&&(k.mcp_servers=v,Object.values(v).some(O=>O&&typeof O.url=="string")&&(k.experimental_use_rmcp_client=!0),f.debug(`[Codex] MCP servers: ${Object.keys(v).join(", ")}`));let R=this._resolveCodexBin(),C=new y({...R?{codexPathOverride:R}:{},...Object.keys(k).length>0&&{config:k},env:xe(process.env)}),L=n;try{L&&Rt(L,{recursive:!0})}catch{}(!L||!mo(L))&&(L=process.cwd());let K=C.startThread({workingDirectory:L,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),P=s&&typeof s.parse=="function",D={};if(s)try{let O=P?ue(s,{target:"openAi"}):s;D.outputSchema=O,f.debug("Structured output via SDK outputSchema")}catch(O){f.warn(`[Codex] Schema conversion failed, will extract from text: ${O.message}`)}let M=Array.isArray(i)?i.filter(O=>O&&typeof O.path=="string"&&O.path.startsWith("/")):[];if(M.length&&(e=`${e}
10
+ `),Array.isArray(l)&&l.length>0){let $=this._resolveCodexHome(a);process.env.CODEX_HOME=$;try{Rt($,{recursive:!0})}catch{}this._ensurePlugins(l,$)}let S=(await import("chalk")).default;console.log(`
11
+ ${S.bold("Prompt sent to LLM:")}`),console.log(S.dim("\u2500".repeat(60))),console.log(S.dim(e)),console.log(S.dim("\u2500".repeat(60)));let v=this._resolveSkillsToMcp(c,{sessionPath:a,workspace:n,nodeName:u});for(let $ of t.extraMcpServers||[])if($&&$.serverName&&$.def){if(Object.prototype.hasOwnProperty.call(v,$.serverName)){console.warn(`[custom-mcp] skip "${$.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let j=ee("codex",$.def);j&&(v[$.serverName]=j)}let k={};Object.keys(v).length>0&&(k.mcp_servers=v,Object.values(v).some($=>$&&typeof $.url=="string")&&(k.experimental_use_rmcp_client=!0),f.debug(`[Codex] MCP servers: ${Object.keys(v).join(", ")}`));let R=this._resolveCodexBin(),C=new y({...R?{codexPathOverride:R}:{},...Object.keys(k).length>0&&{config:k},env:xe(process.env)}),L=n;try{L&&Rt(L,{recursive:!0})}catch{}(!L||!yo(L))&&(L=process.cwd());let K=C.startThread({workingDirectory:L,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),P=s&&typeof s.parse=="function",D={};if(s)try{let $=P?ue(s,{target:"openAi"}):s;D.outputSchema=$,f.debug("Structured output via SDK outputSchema")}catch($){f.warn(`[Codex] Schema conversion failed, will extract from text: ${$.message}`)}let M=Array.isArray(i)?i.filter($=>$&&typeof $.path=="string"&&$.path.startsWith("/")):[];if(M.length&&(e=`${e}
12
12
 
13
13
  # Attached image files \u2014 VIEW THESE
14
14
  The user attached ${M.length} image(s), saved locally. Read each path to SEE the image, then use what it shows to answer:
15
- ${M.map((O,j)=>` ${j+1}. ${O.path}${O.name?` (${O.name})`:""}`).join(`
16
- `)}`),p?.aborted){let O=new Error("Aborted via signal");throw O.name="AbortError",O}try{let{events:O}=await K.runStreamed(e,D),j=0,N="",x=null;for await(let _ of O){if(p?.aborted){let T=new Error("Aborted via signal");throw T.name="AbortError",T}let I=_.type;if(I==="item.completed"){let T=_.item,B=T?.type;if(B==="mcp_tool_call"){j++;let $=`${T.server}/${T.tool}`;if(ne.stepTool(`Tool: ${$}`),T.arguments){let F=JSON.stringify(T.arguments),Y=F.length>100?`${F.substring(0,100)}...`:F;console.log(` Input: ${Y}`)}}else if(B==="tool_call"||B==="function_call"||B==="command_execution"){j++;let $=T.name||T.tool||T.command||"unknown";ne.stepTool(`Tool: ${$}`)}else B==="agent_message"&&(N=T.text||"",N.length<500?console.log(N):console.log(`${N.substring(0,200)}... (${N.length} chars)`))}else I==="turn.completed"?(f.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(_.usage||{})}`),_.usage&&(x=_.usage)):f.debug(`[Codex] Event: ${I} ${JSON.stringify(_).slice(0,300)}`)}if(f.debug(`[Codex] Last agent message (${N.length} chars): ${N.slice(0,500)}`),s){if(!N)throw new Error("Codex agent returned no response");let _=JSON.parse(N),I=_;if(P)try{I=s.parse(_)}catch{I=s.parse(Lt(_))}f.debug("\u2705 [Codex] Structured output validated");let T=dt(x);return{raw:N,structured:I,...T?{usage:T}:{}}}return N||""}catch(O){let j=O.message||String(O);throw f.error(`\u274C [Codex] SDK call failed: ${j}`),j.includes("exited with code")&&(D.outputSchema&&f.error("\u{1F4A1} [Codex] An outputSchema was sent \u2014 an OpenAI strict-mode-invalid schema (a property missing from `required`) makes codex exit 1 here."),f.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),f.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),O}}finally{for(let y of g)y.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=uo(n);if(!s){f.warn(`[Codex] Unknown skill "${n}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let c=s.serverName||n,l=ee("codex",i,{processEnv:process.env});l&&(r[c]=l,f.debug(`[Codex] MCP: ${c} \u2192 ${i.command} ${(i.args||[]).join(" ")}`))}return r}_resolveCodexHome(e){return process.env.CODEX_HOME?process.env.CODEX_HOME:e&&!this._isTempPath(e)?Ze(e,".codex-home"):Ze(go(),".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 He("command -v codex",{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}_ensurePlugins(e,t){let r={...process.env,CODEX_HOME:t};for(let n of e){let s=typeof n=="string"?n:n?.name,i=n&&typeof n=="object"?n.marketplacePath:null;if(!s||!i){f.warn(`[Codex][plugins] skipping malformed plugin declaration: ${JSON.stringify(n)} (need { name, marketplacePath })`);continue}let c=this._readMarketplaceName(i),l=`${s}@${c}`;if(this._isPluginInstalled(l,r)){f.info(`[Codex][plugins] ${l} already installed \u2014 skipping (idempotent)`),console.log(`\u25C6 [Codex] plugin ${l} already installed \u2014 skip`);continue}let a=this._safeMarketplacePath(i,t);f.info(`[Codex][plugins] installing ${l} from local marketplace ${a}`),console.log(`\u25C6 [Codex] installing plugin ${l} (local, no network)`);try{He(`codex plugin marketplace add ${JSON.stringify(a)}`,{env:r,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),He(`codex plugin add ${JSON.stringify(l)}`,{env:r,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),console.log(`\u25C6 [Codex] plugin ${l} installed`)}catch(u){let d=u.stderr&&u.stderr.toString()||u.message||String(u);throw f.error(`[Codex][plugins] failed to install ${l}: ${d}`),new Error(`Codex plugin install failed for ${l}: ${d}`)}}}_safeMarketplacePath(e,t){if(!String(e).includes("@"))return e;let r=Ze(t,".zibby-mkt",String(e).replace(/[^a-zA-Z0-9]+/g,"_"));try{return Rt(Ze(t,".zibby-mkt"),{recursive:!0}),fo(e,r,{recursive:!0}),r}catch(n){return f.warn(`[Codex][plugins] could not copy @-containing marketplace to a safe path: ${n.message}`),e}}_readMarketplaceName(e){let t=Ze(e,".agents","plugins","marketplace.json"),r;try{r=JSON.parse(po(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 He("codex plugin list",{env:t,stdio:"pipe",timeout:15e3,encoding:"utf-8"}).split(`
17
- `).some(n=>n.includes(e)&&/installed/.test(n))}catch{return!1}}};import{AgentStrategy as bo,getSkill as So}from"@zibby/agent-workflow";Ke();import{execSync as _o,spawn as wo}from"node:child_process";import{existsSync as Er,mkdirSync as Tr,readFileSync as Ar,rmSync as xo,writeFileSync as vr}from"node:fs";import{join as de}from"node:path";import{z as xr}from"zod";import{zodToJsonSchema as ho}from"zod-to-json-schema";function yo(o){if(!o)return null;if(typeof xr?.toJSONSchema=="function")try{return xr.toJSONSchema(o)}catch{}try{return ho(o,{target:"openApi3"})}catch{return null}}var gt=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=yo(e):r=e;let n=this._buildExample(r);return`
15
+ ${M.map(($,j)=>` ${j+1}. ${$.path}${$.name?` (${$.name})`:""}`).join(`
16
+ `)}`),p?.aborted){let $=new Error("Aborted via signal");throw $.name="AbortError",$}try{let{events:$}=await K.runStreamed(e,D),j=0,N="",x=null;for await(let _ of $){if(p?.aborted){let T=new Error("Aborted via signal");throw T.name="AbortError",T}let I=_.type;if(I==="item.completed"){let T=_.item,B=T?.type;if(B==="mcp_tool_call"){j++;let O=`${T.server}/${T.tool}`;if(ne.stepTool(`Tool: ${O}`),T.arguments){let F=JSON.stringify(T.arguments),Y=F.length>100?`${F.substring(0,100)}...`:F;console.log(` Input: ${Y}`)}}else if(B==="tool_call"||B==="function_call"||B==="command_execution"){j++;let O=T.name||T.tool||T.command||"unknown";ne.stepTool(`Tool: ${O}`)}else B==="agent_message"&&(N=T.text||"",N.length<500?console.log(N):console.log(`${N.substring(0,200)}... (${N.length} chars)`))}else I==="turn.completed"?(f.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(_.usage||{})}`),_.usage&&(x=_.usage)):f.debug(`[Codex] Event: ${I} ${JSON.stringify(_).slice(0,300)}`)}if(f.debug(`[Codex] Last agent message (${N.length} chars): ${N.slice(0,500)}`),s){if(!N)throw new Error("Codex agent returned no response");let _=JSON.parse(N),I=_;if(P)try{I=s.parse(_)}catch{I=s.parse(Lt(_))}f.debug("\u2705 [Codex] Structured output validated");let T=dt(x);return{raw:N,structured:I,...T?{usage:T}:{}}}return N||""}catch($){let j=$.message||String($);throw f.error(`\u274C [Codex] SDK call failed: ${j}`),j.includes("exited with code")&&(D.outputSchema&&f.error("\u{1F4A1} [Codex] An outputSchema was sent \u2014 an OpenAI strict-mode-invalid schema (a property missing from `required`) makes codex exit 1 here."),f.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),f.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),$}}finally{for(let y of g)y.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=mo(n);if(!s){f.warn(`[Codex] Unknown skill "${n}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let c=s.serverName||n,l=ee("codex",i,{processEnv:process.env});l&&(r[c]=l,f.debug(`[Codex] MCP: ${c} \u2192 ${i.command} ${(i.args||[]).join(" ")}`))}return r}_resolveCodexHome(e){return process.env.CODEX_HOME?process.env.CODEX_HOME:e&&!this._isTempPath(e)?Ze(e,".codex-home"):Ze(bo(),".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 He("command -v codex",{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}_ensurePlugins(e,t){let r={...process.env,CODEX_HOME:t};for(let n of e){let s=typeof n=="string"?n:n?.name,i=n&&typeof n=="object"?n.marketplacePath:null;if(!s||!i){f.warn(`[Codex][plugins] skipping malformed plugin declaration: ${JSON.stringify(n)} (need { name, marketplacePath })`);continue}let c=this._readMarketplaceName(i),l=`${s}@${c}`;if(this._isPluginInstalled(l,r)){f.info(`[Codex][plugins] ${l} already installed \u2014 skipping (idempotent)`),console.log(`\u25C6 [Codex] plugin ${l} already installed \u2014 skip`);continue}let a=this._safeMarketplacePath(i,t);f.info(`[Codex][plugins] installing ${l} from local marketplace ${a}`),console.log(`\u25C6 [Codex] installing plugin ${l} (local, no network)`);try{He(`codex plugin marketplace add ${JSON.stringify(a)}`,{env:r,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),He(`codex plugin add ${JSON.stringify(l)}`,{env:r,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),console.log(`\u25C6 [Codex] plugin ${l} installed`)}catch(u){let d=u.stderr&&u.stderr.toString()||u.message||String(u);throw f.error(`[Codex][plugins] failed to install ${l}: ${d}`),new Error(`Codex plugin install failed for ${l}: ${d}`)}}}_safeMarketplacePath(e,t){if(!String(e).includes("@"))return e;let r=Ze(t,".zibby-mkt",String(e).replace(/[^a-zA-Z0-9]+/g,"_"));try{return Rt(Ze(t,".zibby-mkt"),{recursive:!0}),ho(e,r,{recursive:!0}),r}catch(n){return f.warn(`[Codex][plugins] could not copy @-containing marketplace to a safe path: ${n.message}`),e}}_readMarketplaceName(e){let t=Ze(e,".agents","plugins","marketplace.json"),r;try{r=JSON.parse(go(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 He("codex plugin list",{env:t,stdio:"pipe",timeout:15e3,encoding:"utf-8"}).split(`
17
+ `).some(n=>n.includes(e)&&/installed/.test(n))}catch{return!1}}};import{AgentStrategy as wo,getSkill as xo}from"@zibby/agent-workflow";Ke();import{execSync as Eo,spawn as To}from"node:child_process";import{existsSync as Er,mkdirSync as Tr,readFileSync as Ar,rmSync as Ao,writeFileSync as vr}from"node:fs";import{join as de}from"node:path";import{z as xr}from"zod";import{zodToJsonSchema as So}from"zod-to-json-schema";function _o(o){if(!o)return null;if(typeof xr?.toJSONSchema=="function")try{return xr.toJSONSchema(o)}catch{}try{return So(o,{target:"openApi3"})}catch{return null}}var gt=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=_o(e):r=e;let n=this._buildExample(r);return`
18
18
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
19
19
  \u{1F6A8} MANDATORY: WRITE RESULT TO FILE \u{1F6A8}
20
20
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
@@ -34,7 +34,7 @@ JSON types (strict \u2014 validators reject wrong types):
34
34
  - Use true/false without quotes for booleans.
35
35
  - Use unquoted null where a field may be null.
36
36
 
37
- Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(e){if(!e)return{};let t=e.type;if(t==="object"&&e.properties){let r={};for(let[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 $e=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+=`
37
+ Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(e){if(!e)return{};let t=e.type;if(t==="object"&&e.properties){let r={};for(let[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 Oe=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+=`
38
38
 
39
39
  ${e}`:this.userPrompt=e,this}addSkillHints(e){return e&&this.systemInstructions.push({type:"skill_hints",content:e,position:"prepend"}),this}addStructuredOutput(e,t){if(e&&t){let r=gt.generateFileOutputInstructions(e,t);this.systemInstructions.push({type:"structured_output",content:r,position:"append"}),this.metadata.structuredOutputPath=t}return this}addExtraInstructions(e){if(e?.trim()){let t=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
40
40
  \u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
@@ -47,31 +47,31 @@ ${e.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:t,p
47
47
  `)}getStats(){let e=this.userPrompt.length,t=this.build().length;return{userPromptLength:e,fullPromptLength:t,systemInstructionsLength:t-e,instructionCount:this.systemInstructions.length,instructionTypes:this.systemInstructions.map(r=>r.type)}}clone(){let e=new o(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};var oe=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(`
48
48
  `);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}
49
49
  `,r+=`${n}
50
- `,this.extractedResult=s)}catch{if(n.includes('"text"')||n.includes('"content"')){let i=n.match(/"text"\s*:\s*"([^"]*)/),c=n.match(/"content"\s*:\s*"([^"]*)/),l=i?i[1]:c?c[1]:null;l&&!this.rawText.includes(l)&&(r+=l,this.rawText+=l)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(i,c)=>{if(!i)return;let l=`${i}:${JSON.stringify(c??{})}`;this._lastToolEmit!==l&&(this._lastToolEmit=l,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 l=c[0],a=i[l],u=a&&typeof a=="object"?a.args??a.input??a:void 0;t(l,r(u))}return}return}if(Array.isArray(e.tool_calls)){for(let 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 p=s;p<e.length;p++)if(e[p]==="{")d++;else if(e[p]==="}"&&(d--,d===0)){m=p,t.push({text:e.substring(s,m+1),source:"brace"}),i++;break}s=m+1}let c=this.extractedResult,l=c?JSON.stringify(c).length:0,a=0,u=-1;for(let d=0;d<t.length;d++){let m=t[d];try{let p=m.text.replace(/,(\s*[}\]])/g,"$1"),g=JSON.parse(p);this.isValidResult(g)&&(a++,l=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}};function Eo(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 l=r;l<e.length;l++){let a=e[l];if(s){i?i=!1:a==="\\"?i=!0:a==='"'&&(s=!1);continue}if(a==='"'){s=!0;continue}if(a==="{"){n===0&&(c=l),n+=1;continue}if(a==="}"){if(n===0)continue;if(n-=1,n===0&&c>=0){let u=e.slice(c,l+1);try{return JSON.parse(u)}catch{c=-1}}}}return null}function To(o){let e=String(o||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return Eo(e)}}function Ao(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 me=class extends bo{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GEMINI_API_KEY_POOL||process.env.GOOGLE_API_KEY||process.env.GOOGLE_API_KEY_POOL))return f.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return _o("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return f.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,images:i=[],skills:c=null,sessionPath:l=null,nodeName:a=null,timeout:u=600*1e3,signal:d=null}=t,m=[q("GEMINI_API_KEY"),q("GOOGLE_API_KEY")];try{let p=Ae("gemini",r),g=kt[p]||p,y=String(process.env.GEMINI_API_KEY||"").trim(),h=String(process.env.GOOGLE_API_KEY||"").trim(),b=this._resolveSkillsToMcp(c,{sessionPath:l,workspace:n,nodeName:a});for(let $ of t.extraMcpServers||[])if($&&$.serverName&&$.def){if(Object.prototype.hasOwnProperty.call(b,$.serverName)){console.warn(`[custom-mcp] skip "${$.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let F=ee("gemini",$.def);F&&(b[$.serverName]=F)}let w=Object.keys(b).length>0,E=new $e(e),S=s&&typeof s.parse=="function",v=null;if(s){let $;try{let F=S?ue(s,{target:"openAi"}):s;$=JSON.stringify(F,null,2)}catch{$="{}"}if(w){E.addSystemInstruction(`Write valid JSON that matches this schema:
51
- ${$}`,"schema_instruction","append");let F=`zibby-result-${Date.now()}.json`,Y=de(n,".zibby","tmp");v=de(Y,F),Tr(Y,{recursive:!0}),E.addStructuredOutput(s,v)}else E.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
52
- ${$}`,"json_instruction","append")}let k=E.build(),R=Array.isArray(i)?i.filter($=>$&&typeof $.path=="string"&&$.path.startsWith("/")):[];R.length&&(k+=`
50
+ `,this.extractedResult=s)}catch{if(n.includes('"text"')||n.includes('"content"')){let i=n.match(/"text"\s*:\s*"([^"]*)/),c=n.match(/"content"\s*:\s*"([^"]*)/),l=i?i[1]:c?c[1]:null;l&&!this.rawText.includes(l)&&(r+=l,this.rawText+=l)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(i,c)=>{if(!i)return;let l=`${i}:${JSON.stringify(c??{})}`;this._lastToolEmit!==l&&(this._lastToolEmit=l,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 l=c[0],a=i[l],u=a&&typeof a=="object"?a.args??a.input??a:void 0;t(l,r(u))}return}return}if(Array.isArray(e.tool_calls)){for(let 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 p=s;p<e.length;p++)if(e[p]==="{")d++;else if(e[p]==="}"&&(d--,d===0)){m=p,t.push({text:e.substring(s,m+1),source:"brace"}),i++;break}s=m+1}let c=this.extractedResult,l=c?JSON.stringify(c).length:0,a=0,u=-1;for(let d=0;d<t.length;d++){let m=t[d];try{let p=m.text.replace(/,(\s*[}\]])/g,"$1"),g=JSON.parse(p);this.isValidResult(g)&&(a++,l=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}};function vo(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 l=r;l<e.length;l++){let a=e[l];if(s){i?i=!1:a==="\\"?i=!0:a==='"'&&(s=!1);continue}if(a==='"'){s=!0;continue}if(a==="{"){n===0&&(c=l),n+=1;continue}if(a==="}"){if(n===0)continue;if(n-=1,n===0&&c>=0){let u=e.slice(c,l+1);try{return JSON.parse(u)}catch{c=-1}}}}return null}function Oo(o){let e=String(o||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return vo(e)}}function $o(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 me=class extends wo{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GEMINI_API_KEY_POOL||process.env.GOOGLE_API_KEY||process.env.GOOGLE_API_KEY_POOL))return f.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return Eo("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return f.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,images:i=[],skills:c=null,sessionPath:l=null,nodeName:a=null,timeout:u=600*1e3,signal:d=null}=t,m=[q("GEMINI_API_KEY"),q("GOOGLE_API_KEY")];try{let p=Ae("gemini",r),g=kt[p]||p,y=String(process.env.GEMINI_API_KEY||"").trim(),h=String(process.env.GOOGLE_API_KEY||"").trim(),b=this._resolveSkillsToMcp(c,{sessionPath:l,workspace:n,nodeName:a});for(let O of t.extraMcpServers||[])if(O&&O.serverName&&O.def){if(Object.prototype.hasOwnProperty.call(b,O.serverName)){console.warn(`[custom-mcp] skip "${O.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let F=ee("gemini",O.def);F&&(b[O.serverName]=F)}let w=Object.keys(b).length>0,E=new Oe(e),S=s&&typeof s.parse=="function",v=null;if(s){let O;try{let F=S?ue(s,{target:"openAi"}):s;O=JSON.stringify(F,null,2)}catch{O="{}"}if(w){E.addSystemInstruction(`Write valid JSON that matches this schema:
51
+ ${O}`,"schema_instruction","append");let F=`zibby-result-${Date.now()}.json`,Y=de(n,".zibby","tmp");v=de(Y,F),Tr(Y,{recursive:!0}),E.addStructuredOutput(s,v)}else E.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
52
+ ${O}`,"json_instruction","append")}let k=E.build(),R=Array.isArray(i)?i.filter(O=>O&&typeof O.path=="string"&&O.path.startsWith("/")):[];R.length&&(k+=`
53
53
 
54
54
  # Attached image files \u2014 VIEW THESE
55
55
  The user attached ${R.length} image(s), saved locally. Read each path to SEE the image, then use what it shows to answer:
56
- ${R.map(($,F)=>` ${F+1}. ${$.path}${$.name?` (${$.name})`:""}`).join(`
56
+ ${R.map((O,F)=>` ${F+1}. ${O.path}${O.name?` (${O.name})`:""}`).join(`
57
57
  `)}`);let C=E.getUserPrompt(),L=E.getStats(),K=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),P=K?` | key: ***${K.slice(-4)}`:" | key: not set";console.log(`
58
58
  \u25C6 Model: ${g||"auto"}${P}
59
59
  `);let D=(await import("chalk")).default;console.log(`
60
- ${D.bold("Prompt sent to LLM:")}`),console.log(D.dim("\u2500".repeat(60))),console.log(D.dim(C)),console.log(D.dim("\u2500".repeat(60)));let M=this._createGeminiConfigDir(n,b),O=["--output-format","json"];g&&g!=="auto"&&O.push("--model",g);let j=Object.keys(b);if(j.length>0){O.push("--approval-mode","yolo");for(let $ of j)O.push("--allowed-mcp-server-names",$);f.info(`[Gemini] Enabling MCP servers: ${j.join(", ")}`)}else c&&c.length>0&&f.warn(`[Gemini] Skills requested but no MCP servers configured: ${c.join(", ")}`);O.push("-p",k);let N={...xe(process.env),GEMINI_CLI_HOME:M};y?(N.GEMINI_API_KEY=y,delete N.GOOGLE_API_KEY):h&&(N.GOOGLE_API_KEY=h,delete N.GEMINI_API_KEY),f.debug(`[Gemini] Command: gemini ${O.slice(0,8).join(" ")}... (${O.length} total args)`),f.debug(`[Gemini] User prompt: ${L.userPromptLength} chars, System instructions: ${L.systemInstructionsLength} chars (${L.instructionCount} blocks), Full: ${L.fullPromptLength} chars`),f.debug(`[Gemini] Config home: ${M}`),f.debug(`[Gemini] GEMINI_CLI_HOME env: ${N.GEMINI_CLI_HOME}`);let x="",_=null;try{x=await new Promise((F,Y)=>{let Q=wo("gemini",O,{cwd:n,env:N,stdio:["ignore","pipe","pipe"],...d&&{signal:d}}),ie="",it="",A=!1,V=null,G=!1,U=setTimeout(()=>{try{Q.kill("SIGTERM")}catch{}},u),z=()=>{G||A||(G=!0,V=setTimeout(()=>{if(!A)try{Q.kill("SIGKILL")}catch{}},5e3))};d&&(d.aborted?z():d.addEventListener("abort",z,{once:!0})),Q.stdout.on("data",H=>{ie+=H.toString()}),Q.stderr.on("data",H=>{it+=H.toString()}),Q.on("error",H=>{if(clearTimeout(U),V&&clearTimeout(V),d&&!d.aborted)try{d.removeEventListener("abort",z)}catch{}Y(H)}),Q.on("close",H=>{if(A=!0,clearTimeout(U),V&&clearTimeout(V),d&&!d.aborted)try{d.removeEventListener("abort",z)}catch{}if(G){let we=new Error("Aborted via signal");return we.name="AbortError",Y(we)}if(H===0)return F(ie.trim());Y(new Error(`gemini failed with code ${H}: ${(it||ie).trim()}`))})})}catch($){_=$}finally{try{xo(M,{recursive:!0,force:!0})}catch{}}let I=Ao(x).trim();if(!s){if(_)throw _;return I}if(v){let $=Er(v);if(f.info(`[Gemini] Result file: ${$?"present":"missing"} at ${v}`),$)try{let F=Ar(v,"utf-8").trim(),Y=JSON.parse(F),Q=S?s.parse(Y):Y;return f.info("[Gemini] Structured output recovered from result file"),{raw:I,structured:Q}}catch(F){f.warn(`[Gemini] Result file parse/validation failed: ${F.message}`)}else _||f.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let T=null;if(s){let $=new oe;$.zodSchema=s,$.processChunk(I),$.flush(),T=$.getResult()}if(f.info(`[Gemini] Raw stdout length: ${x.length} chars`),f.info(`[Gemini] Extracted text length: ${I.length} chars`),f.info(`[Gemini] StreamParser result: ${T?"extracted":"null"}`),T||(I.length<2e3?f.info(`[Gemini] Raw text preview:
60
+ ${D.bold("Prompt sent to LLM:")}`),console.log(D.dim("\u2500".repeat(60))),console.log(D.dim(C)),console.log(D.dim("\u2500".repeat(60)));let M=this._createGeminiConfigDir(n,b),$=["--output-format","json"];g&&g!=="auto"&&$.push("--model",g);let j=Object.keys(b);if(j.length>0){$.push("--approval-mode","yolo");for(let O of j)$.push("--allowed-mcp-server-names",O);f.info(`[Gemini] Enabling MCP servers: ${j.join(", ")}`)}else c&&c.length>0&&f.warn(`[Gemini] Skills requested but no MCP servers configured: ${c.join(", ")}`);$.push("-p",k);let N={...xe(process.env),GEMINI_CLI_HOME:M};y?(N.GEMINI_API_KEY=y,delete N.GOOGLE_API_KEY):h&&(N.GOOGLE_API_KEY=h,delete N.GEMINI_API_KEY),f.debug(`[Gemini] Command: gemini ${$.slice(0,8).join(" ")}... (${$.length} total args)`),f.debug(`[Gemini] User prompt: ${L.userPromptLength} chars, System instructions: ${L.systemInstructionsLength} chars (${L.instructionCount} blocks), Full: ${L.fullPromptLength} chars`),f.debug(`[Gemini] Config home: ${M}`),f.debug(`[Gemini] GEMINI_CLI_HOME env: ${N.GEMINI_CLI_HOME}`);let x="",_=null;try{x=await new Promise((F,Y)=>{let Q=To("gemini",$,{cwd:n,env:N,stdio:["ignore","pipe","pipe"],...d&&{signal:d}}),ie="",it="",A=!1,W=null,G=!1,U=setTimeout(()=>{try{Q.kill("SIGTERM")}catch{}},u),z=()=>{G||A||(G=!0,W=setTimeout(()=>{if(!A)try{Q.kill("SIGKILL")}catch{}},5e3))};d&&(d.aborted?z():d.addEventListener("abort",z,{once:!0})),Q.stdout.on("data",H=>{ie+=H.toString()}),Q.stderr.on("data",H=>{it+=H.toString()}),Q.on("error",H=>{if(clearTimeout(U),W&&clearTimeout(W),d&&!d.aborted)try{d.removeEventListener("abort",z)}catch{}Y(H)}),Q.on("close",H=>{if(A=!0,clearTimeout(U),W&&clearTimeout(W),d&&!d.aborted)try{d.removeEventListener("abort",z)}catch{}if(G){let we=new Error("Aborted via signal");return we.name="AbortError",Y(we)}if(H===0)return F(ie.trim());Y(new Error(`gemini failed with code ${H}: ${(it||ie).trim()}`))})})}catch(O){_=O}finally{try{Ao(M,{recursive:!0,force:!0})}catch{}}let I=$o(x).trim();if(!s){if(_)throw _;return I}if(v){let O=Er(v);if(f.info(`[Gemini] Result file: ${O?"present":"missing"} at ${v}`),O)try{let F=Ar(v,"utf-8").trim(),Y=JSON.parse(F),Q=S?s.parse(Y):Y;return f.info("[Gemini] Structured output recovered from result file"),{raw:I,structured:Q}}catch(F){f.warn(`[Gemini] Result file parse/validation failed: ${F.message}`)}else _||f.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let T=null;if(s){let O=new oe;O.zodSchema=s,O.processChunk(I),O.flush(),T=O.getResult()}if(f.info(`[Gemini] Raw stdout length: ${x.length} chars`),f.info(`[Gemini] Extracted text length: ${I.length} chars`),f.info(`[Gemini] StreamParser result: ${T?"extracted":"null"}`),T||(I.length<2e3?f.info(`[Gemini] Raw text preview:
61
61
  ${I}`):f.info(`[Gemini] Raw text preview (first 1000 chars):
62
- ${I.slice(0,1e3)}`),T=To(I)),!T)throw _||(f.error("[Gemini] Failed to extract valid JSON from output"),f.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error("Gemini did not return valid JSON for structured output. Enable strictMode for proxy fallback."));let B=S?s.parse(T):T;return{raw:I,structured:B}}finally{for(let p of m)p.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=So(n);if(!s||typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let c=s.cursorKey||s.serverName||n,l=ee("gemini",i);l&&(r[c]=l)}return r}_createGeminiConfigDir(e,t){let r=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,n=de(e||process.cwd(),".zibby","tmp",`gemini-home-${r}`),s=de(n,".gemini");Tr(s,{recursive:!0});let i=de(s,"settings.json"),c={},l=de(process.env.HOME||"",".gemini","settings.json");if(Er(l))try{c=JSON.parse(Ar(l,"utf-8"))}catch{c={}}let a={...c,mcpServers:{...c.mcpServers&&typeof c.mcpServers=="object"?c.mcpServers:{},...t||{}}};vr(i,`${JSON.stringify(a,null,2)}
62
+ ${I.slice(0,1e3)}`),T=Oo(I)),!T)throw _||(f.error("[Gemini] Failed to extract valid JSON from output"),f.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error("Gemini did not return valid JSON for structured output. Enable strictMode for proxy fallback."));let B=S?s.parse(T):T;return{raw:I,structured:B}}finally{for(let p of m)p.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=xo(n);if(!s||typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let c=s.cursorKey||s.serverName||n,l=ee("gemini",i);l&&(r[c]=l)}return r}_createGeminiConfigDir(e,t){let r=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,n=de(e||process.cwd(),".zibby","tmp",`gemini-home-${r}`),s=de(n,".gemini");Tr(s,{recursive:!0});let i=de(s,"settings.json"),c={},l=de(process.env.HOME||"",".gemini","settings.json");if(Er(l))try{c=JSON.parse(Ar(l,"utf-8"))}catch{c={}}let a={...c,mcpServers:{...c.mcpServers&&typeof c.mcpServers=="object"?c.mcpServers:{},...t||{}}};vr(i,`${JSON.stringify(a,null,2)}
63
63
  `,"utf-8");let u=de(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{vr(u,`${JSON.stringify(a,null,2)}
64
- `,"utf-8")}catch{}return f.debug(`[Gemini] Created isolated config with ${Object.keys(a.mcpServers||{}).length} MCP servers`),f.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(a.mcpServers||{}),null,2)}`),n}};import{AgentStrategy as Uo,getSkill as _t}from"@zibby/agent-workflow";var Oe=class{formatTools(e){throw new Error("formatTools() must be implemented")}hasToolCalls(e){throw new Error("hasToolCalls() must be implemented")}parseToolCalls(e){throw new Error("parseToolCalls() must be implemented")}getTextContent(e){throw new Error("getTextContent() must be implemented")}buildAssistantMessage(e){throw new Error("buildAssistantMessage() must be implemented")}buildToolResultMessage(e,t){throw new Error("buildToolResultMessage() must be implemented")}injectToolsIntoBody(e,t){throw new Error("injectToolsIntoBody() must be implemented")}};var ge=class extends Oe{formatTools(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters||t.input_schema||{type:"object",properties:{}}}}))}hasToolCalls(e){let t=e.choices?.[0]?.message;return!!(t?.tool_calls&&t.tool_calls.length>0)}parseToolCalls(e){return(e.choices?.[0]?.message?.tool_calls||[]).map(r=>({id:r.id,name:r.function.name,args:JSON.parse(r.function.arguments||"{}")}))}getTextContent(e){return e.choices?.[0]?.message?.content||""}buildAssistantMessage(e){return e.choices?.[0]?.message}buildToolResultMessage(e,t){return{role:"tool",tool_call_id:e,content:typeof t=="string"?t:JSON.stringify(t)}}injectToolsIntoBody(e,t){return t.length>0&&(e.tools=t),e}};var Ve=class{async fetchCompletion(e,t,r={}){throw new Error("fetchCompletion() must be implemented")}async fetchStreamingCompletion(e,t,r={}){throw new Error("fetchStreamingCompletion() must be implemented")}};function ht(o){return Buffer.byteLength(JSON.stringify(o),"utf8")}function yt(o,e){let t=String(o||"");if(t.length<=e)return t;let r=Math.max(0,e-28);return`${t.slice(0,r)}
64
+ `,"utf-8")}catch{}return f.debug(`[Gemini] Created isolated config with ${Object.keys(a.mcpServers||{}).length} MCP servers`),f.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(a.mcpServers||{}),null,2)}`),n}};import{AgentStrategy as Fo,getSkill as _t}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 ge=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 We=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 ht(o){return Buffer.byteLength(JSON.stringify(o),"utf8")}function yt(o,e){let t=String(o||"");if(t.length<=e)return t;let r=Math.max(0,e-28);return`${t.slice(0,r)}
65
65
 
66
- [truncated for size budget]`}function Mt(o,e=0){if(!o||typeof o!="object"||e>8)return o;if(Array.isArray(o))return o.map(r=>Mt(r,e+1));let t={};for(let[r,n]of Object.entries(o))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=Mt(n,e+1));return t}function vo(o=[]){return o.map(e=>({...e,function:{...e.function,description:yt(e.function?.description||"",180),parameters:Mt(e.function?.parameters||{type:"object",properties:{}})}}))}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(l=>r.has(l.id)))return n;let{tool_calls:i,...c}=n;return{...c,content:c.content||""}})}function Dt(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)?vo(o.tools):o.tools};n.messages.length>0&&n.messages[0]?.role==="system"&&(n.messages[0]={...n.messages[0],content:yt(n.messages[0].content,r)});let s=!1;for(;ht(n)>t&&n.messages.length>2;)n.messages.splice(1,1),s=!0;if(s&&(n.messages=$r(n.messages)),ht(n)>t&&n.messages.length>0&&(n.messages[0]={...n.messages[0],content:yt(n.messages[0].content,6e3)},s=!0),ht(n)>t){let i=n.messages.find(l=>l.role==="system")||n.messages[0],c=n.messages.slice(-2);n.messages=$r([i,...c].filter(Boolean).map((l,a)=>({...l,content:yt(l.content,a===0?4e3:8e3)}))),s=!0}return{body:n,meta:{bytes:ht(n),trimmed:s,maxBytes:t,messageCount:n.messages.length}}}var Or=o=>Buffer.byteLength(JSON.stringify(o),"utf8"),Ie=class extends Ve{async fetchCompletion(e,t,r={}){let n=Or(e),{body:s,meta:i}=Dt(e,r.payloadCompaction);r.onBudget?.({streaming:!1,beforeBytes:n,meta:i});let c=this.#e(r),l=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,a=await fetch(l,{method:"POST",headers:t.headers,body:JSON.stringify(s),signal:c});if(!a.ok){let u=await a.text();throw a.status===401||a.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${a.status}: ${u}`)}return a.json()}async fetchStreamingCompletion(e,t,r={}){let n={...e,stream:!0},s=Or(n),{body:i,meta:c}=Dt(n,r.payloadCompaction);r.onBudget?.({streaming:!0,beforeBytes:s,meta:c});let l=this.#e(r),a=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,u=await fetch(a,{method:"POST",headers:t.headers,body:JSON.stringify(i),signal:l});if(!u.ok){let h=await u.text();throw u.status===401||u.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${u.status}: ${h}`)}let d=u.body.getReader(),m=new TextDecoder,p="",g="",y=new Map;for(;;){let{done:h,value:b}=await d.read();if(h)break;p+=m.decode(b,{stream:!0});let w=p.split(`
67
- `);p=w.pop();for(let E of w){if(!E.startsWith("data: "))continue;let S=E.slice(6).trim();if(S==="[DONE]")continue;let v;try{v=JSON.parse(S)}catch{continue}let k=v.choices?.[0]?.delta;if(k&&(k.content&&(g+=k.content,r.onToken&&r.onToken(k.content)),k.tool_calls))for(let R of k.tool_calls){let C=R.index??0;y.has(C)||y.set(C,{id:"",name:"",args:""});let L=y.get(C);R.id&&(L.id=R.id),R.function?.name&&(L.name=R.function.name),R.function?.arguments!=null&&(L.args+=R.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 $o}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Oo}from"@modelcontextprotocol/sdk/client/stdio.js";var We=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:r,args:n=[],env:s={}}=t;f.debug(`[MCP] Starting ${e}: ${r} ${n.join(" ")}`);let i=new Oo({command:r,args:n,env:{...process.env,...s}}),c=new $o({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await c.connect(i);let l={client:c,transport:i,serverConfig:t};return this.#e.set(e,l),l}async callTool(e,t,r={}){let n=this.#e.get(e);if(!n)throw new Error(`MCP server "${e}" not running`);f.debug(`[MCP] ${e}.${t}(${JSON.stringify(r).slice(0,200)})`);let s=await n.client.callTool({name:t,arguments:r});return{text:s.content?.filter(c=>c.type==="text").map(c=>c.text).join(`
68
- `)||"",isError:s.isError||!1}}isRunning(e){return this.#e.has(e)}async stopServer(e){let t=this.#e.get(e);if(t){try{await t.client.close()}catch(r){f.debug(`[MCP] Error closing ${e}: ${r.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}};import{existsSync as Io,readFileSync as Co}from"node:fs";import{join as ko}from"node:path";import{homedir as Po}from"node:os";function No(){try{let o=ko(Po(),".zibby","config.json");return Io(o)?JSON.parse(Co(o,"utf-8")):{}}catch{return{}}}function bt(o){return String(o||"").replace(/\/v1\/?$/,"")}function Ro(o,e){let t=process.env.OPENAI_PROXY_URL;if(t)return bt(t);if(o==="session")return e.proxyUrl?bt(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 bt(r||"https://api.openai.com")}return bt(t||"")}function Ut(){let o=No(),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=Ro(i,o),l={"Content-Type":"application/json"};if(i==="session"){if(!e)return{ok:!1,mode:i,reason:"missing_session_token"};l.Authorization=`Bearer ${e}`}else if(i==="byok"){if(!t)return{ok:!1,mode:i,reason:"missing_openai_api_key"};l.Authorization=`Bearer ${t}`}else if(i==="local"){if(!c)return{ok:!1,mode:i,reason:"missing_openai_proxy_url"};!n&&t&&(l.Authorization=`Bearer ${t}`)}return c?{ok:!0,mode:i,baseUrl:c,headers:l,tokenPreview:l.Authorization?`***${l.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:i,reason:"missing_base_url"}}function St(o,e){let t=String(o??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
66
+ [truncated for size budget]`}function Mt(o,e=0){if(!o||typeof o!="object"||e>8)return o;if(Array.isArray(o))return o.map(r=>Mt(r,e+1));let t={};for(let[r,n]of Object.entries(o))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=Mt(n,e+1));return t}function Io(o=[]){return o.map(e=>({...e,function:{...e.function,description:yt(e.function?.description||"",180),parameters:Mt(e.function?.parameters||{type:"object",properties:{}})}}))}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(l=>r.has(l.id)))return n;let{tool_calls:i,...c}=n;return{...c,content:c.content||""}})}function Dt(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)?Io(o.tools):o.tools};n.messages.length>0&&n.messages[0]?.role==="system"&&(n.messages[0]={...n.messages[0],content:yt(n.messages[0].content,r)});let s=!1;for(;ht(n)>t&&n.messages.length>2;)n.messages.splice(1,1),s=!0;if(s&&(n.messages=Or(n.messages)),ht(n)>t&&n.messages.length>0&&(n.messages[0]={...n.messages[0],content:yt(n.messages[0].content,6e3)},s=!0),ht(n)>t){let i=n.messages.find(l=>l.role==="system")||n.messages[0],c=n.messages.slice(-2);n.messages=Or([i,...c].filter(Boolean).map((l,a)=>({...l,content:yt(l.content,a===0?4e3:8e3)}))),s=!0}return{body:n,meta:{bytes:ht(n),trimmed:s,maxBytes:t,messageCount:n.messages.length}}}var $r=o=>Buffer.byteLength(JSON.stringify(o),"utf8"),Ie=class extends We{async fetchCompletion(e,t,r={}){let n=$r(e),{body:s,meta:i}=Dt(e,r.payloadCompaction);r.onBudget?.({streaming:!1,beforeBytes:n,meta:i});let c=this.#e(r),l=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,a=await fetch(l,{method:"POST",headers:t.headers,body:JSON.stringify(s),signal:c});if(!a.ok){let u=await a.text();throw a.status===401||a.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${a.status}: ${u}`)}return a.json()}async fetchStreamingCompletion(e,t,r={}){let n={...e,stream:!0},s=$r(n),{body:i,meta:c}=Dt(n,r.payloadCompaction);r.onBudget?.({streaming:!0,beforeBytes:s,meta:c});let l=this.#e(r),a=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,u=await fetch(a,{method:"POST",headers:t.headers,body:JSON.stringify(i),signal:l});if(!u.ok){let h=await u.text();throw u.status===401||u.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${u.status}: ${h}`)}let d=u.body.getReader(),m=new TextDecoder,p="",g="",y=new Map;for(;;){let{done:h,value:b}=await d.read();if(h)break;p+=m.decode(b,{stream:!0});let w=p.split(`
67
+ `);p=w.pop();for(let E of w){if(!E.startsWith("data: "))continue;let S=E.slice(6).trim();if(S==="[DONE]")continue;let v;try{v=JSON.parse(S)}catch{continue}let k=v.choices?.[0]?.delta;if(k&&(k.content&&(g+=k.content,r.onToken&&r.onToken(k.content)),k.tool_calls))for(let R of k.tool_calls){let C=R.index??0;y.has(C)||y.set(C,{id:"",name:"",args:""});let L=y.get(C);R.id&&(L.id=R.id),R.function?.name&&(L.name=R.function.name),R.function?.arguments!=null&&(L.args+=R.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 Co}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as ko}from"@modelcontextprotocol/sdk/client/stdio.js";var Ve=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:r,args:n=[],env:s={}}=t;f.debug(`[MCP] Starting ${e}: ${r} ${n.join(" ")}`);let i=new ko({command:r,args:n,env:{...process.env,...s}}),c=new Co({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await c.connect(i);let l={client:c,transport:i,serverConfig:t};return this.#e.set(e,l),l}async callTool(e,t,r={}){let n=this.#e.get(e);if(!n)throw new Error(`MCP server "${e}" not running`);f.debug(`[MCP] ${e}.${t}(${JSON.stringify(r).slice(0,200)})`);let s=await n.client.callTool({name:t,arguments:r});return{text:s.content?.filter(c=>c.type==="text").map(c=>c.text).join(`
68
+ `)||"",isError:s.isError||!1}}isRunning(e){return this.#e.has(e)}async stopServer(e){let t=this.#e.get(e);if(t){try{await t.client.close()}catch(r){f.debug(`[MCP] Error closing ${e}: ${r.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}};import{existsSync as Po,readFileSync as No}from"node:fs";import{join as Ro}from"node:path";import{homedir as Lo}from"node:os";function Mo(){try{let o=Ro(Lo(),".zibby","config.json");return Po(o)?JSON.parse(No(o,"utf-8")):{}}catch{return{}}}function bt(o){return String(o||"").replace(/\/v1\/?$/,"")}function Do(o,e){let t=process.env.OPENAI_PROXY_URL;if(t)return bt(t);if(o==="session")return e.proxyUrl?bt(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 bt(r||"https://api.openai.com")}return bt(t||"")}function Ut(){let o=Mo(),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=Do(i,o),l={"Content-Type":"application/json"};if(i==="session"){if(!e)return{ok:!1,mode:i,reason:"missing_session_token"};l.Authorization=`Bearer ${e}`}else if(i==="byok"){if(!t)return{ok:!1,mode:i,reason:"missing_openai_api_key"};l.Authorization=`Bearer ${t}`}else if(i==="local"){if(!c)return{ok:!1,mode:i,reason:"missing_openai_proxy_url"};!n&&t&&(l.Authorization=`Bearer ${t}`)}return c?{ok:!0,mode:i,baseUrl:c,headers:l,tokenPreview:l.Authorization?`***${l.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:i,reason:"missing_base_url"}}function St(o,e){let t=String(o??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
69
69
 
70
- [tool result truncated for size]`}function Lo(o,e){if(typeof o=="string")return St(o,e);try{return St(JSON.stringify(o),e)}catch{return St(String(o),e)}}function Ir(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(l=>r.has(l.id)))return n;let{tool_calls:i,...c}=n;return{...c,content:c.content||""}})}function Mo(o){let e=Array.isArray(o?.messages)?o.messages:[],t=e.find(s=>s.role==="system"),r=e.slice(-4).map(s=>({...s,content:St(s.content,s.role==="tool"?1200:2500)}));r=Ir(r);let n={...o,messages:[t,...r].filter(Boolean)};return delete n.tools,n}async function Do({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 l=String(c?.message||c||"");if(!/proxy error 413|payload too large/i.test(l))throw c;let a=Mo(o);return typeof i=="function"&&i(o,a),{data:e?await s(a,t,r):await n(a,t,r),fallback:a}}}async function Cr({body:o,auth:e,options:t,streaming:r,toolContext:n,activeSkills:s,round:i,verbose:c,dependencies:l,config:a={}}){let u=a.maxToolResultChars||3e3,{fetchCompletion:d,fetchStreamingCompletion:m,onFallbackLog:p,hasToolCalls:g,getTextContent:y,parseToolCalls:h,buildAssistantMessage:b,buildToolResultMessage:w,executeTool:E,onToolCallLog:S,injectTools:v}=l;Array.isArray(o?.messages)&&(o.messages=Ir(o.messages));let k=await Do({body:o,streaming:r,auth:e,options:t,fetchCompletion:d,fetchStreamingCompletion:m,onFallbackLog:p}),R=k?.data||k;if(!g(R))return{done:!0,text:y(R),body:k?.fallback||o};let C=h(R),L=k?.fallback||o;L.messages.push(b(R)),c&&typeof S=="function"&&S(C);let K=await Promise.all(C.map((P,D)=>(typeof t.onToolCall=="function"&&t.onToolCall(P.name,P.args,{round:i,index:D,total:C.length}),E(P,n))));for(let P=0;P<C.length;P++){let M=C[P].name==="get_skill_context"?typeof K[P]=="string"?K[P]:JSON.stringify(K[P]):Lo(K[P],u);L.messages.push(w(C[P].id,M))}return typeof t.onToolCall=="function"&&t.onToolCall(null),v(L,s),{done:!1,body:L}}var jo=ae.ASSISTANT,Bo=15,jt="get_skill_context";function ke(o){!o||typeof o!="object"||(o.type==="object"&&o.properties&&(o.required=Object.keys(o.properties),o.additionalProperties=!1,Object.values(o.properties).forEach(ke)),o.type==="array"&&o.items&&ke(o.items),o.anyOf&&o.anyOf.forEach(ke),o.oneOf&&o.oneOf.forEach(ke),o.allOf&&o.allOf.forEach(ke))}var kr={maxBytes:49e3,systemMaxChars:12e3},Ce=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Fo=o=>Buffer.byteLength(JSON.stringify(o),"utf8");function wt(o){return Array.isArray(o)?new Set(o.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function Go(o){return Array.isArray(o)?o.map(e=>String(e||"").trim()).filter(Boolean):[]}var he=class extends Uo{#e;#t;#r=new We;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new ge,this.#t=e.completionProvider||new Ie):(this.#e=e||new ge,this.#t=new Ie)}canHandle(e){return Ut().ok}async invoke(e,t={}){let r=q("OPENAI_API_KEY");try{let n=t.model&&t.model!=="auto"?t.model:jo,s=Ut();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,l=Ce();if(l?await this.#m(i,n,c,s.tokenPreview||"none"):f.debug(`[Assistant] ${c} | model: ${n} | messages: ${i.length}`),t.schema)return this.#c(n,i,s,t);let a=t.activeSkills||[],u=this.#p(t),d=this.#f(a,u),m=this.#d(d),p=this.#u(t),g={...t,payloadCompaction:p},y={activeSkills:d,options:g,executionRegistry:m,capabilityPolicy:u},h=!!t.stream,b={model:n,messages:[...i],stream:!1};this.#o(b,d,u);for(let w=0;w<Bo;w++){if(t.signal?.aborted){let S=new Error("Aborted via signal");throw S.name="AbortError",S}let E=await Cr({body:b,auth:s,options:g,streaming:h,toolContext:y,activeSkills:d,round:w,verbose:l,dependencies:{fetchCompletion:this.#s.bind(this),fetchStreamingCompletion:this.#l.bind(this),onFallbackLog:(S,v)=>{Ce()&&console.log(`413 fallback: messages ${S.messages.length} -> ${v.messages.length}, bytes=${Fo(v)}`)},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,v)=>this.#e.buildToolResultMessage(S,v),executeTool:(S,v)=>this.#a(S,v),onToolCallLog:async S=>{let v=(await import("chalk")).default;console.log(v.dim(` ${S.map(k=>`${k.name}(${JSON.stringify(k.args).slice(0,80)})`).join(", ")}`))},injectTools:(S,v)=>this.#o(S,v,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=_t(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(jt,t)&&r.push({name:jt,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===jt){let a=String(e.args?.skillId||"").trim();if(!a)return JSON.stringify({error:"skillId is required"});if(!r.includes(a))return JSON.stringify({error:`Skill "${a}" is not active`,activeSkills:r});let u=_t(a);if(!u)return JSON.stringify({error:`Skill "${a}" not found`});let d=typeof u.promptFragment=="function"?u.promptFragment():u.promptFragment||"",m=(u.tools||[]).map(g=>g.name),p=JSON.stringify({skillId:a,description:u.description||"",toolNames:m,promptFragment:d||""});return Ce()&&(console.log(`
70
+ [tool result truncated for size]`}function Uo(o,e){if(typeof o=="string")return St(o,e);try{return St(JSON.stringify(o),e)}catch{return St(String(o),e)}}function Ir(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(l=>r.has(l.id)))return n;let{tool_calls:i,...c}=n;return{...c,content:c.content||""}})}function jo(o){let e=Array.isArray(o?.messages)?o.messages:[],t=e.find(s=>s.role==="system"),r=e.slice(-4).map(s=>({...s,content:St(s.content,s.role==="tool"?1200:2500)}));r=Ir(r);let n={...o,messages:[t,...r].filter(Boolean)};return delete n.tools,n}async function Bo({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 l=String(c?.message||c||"");if(!/proxy error 413|payload too large/i.test(l))throw c;let a=jo(o);return typeof i=="function"&&i(o,a),{data:e?await s(a,t,r):await n(a,t,r),fallback:a}}}async function Cr({body:o,auth:e,options:t,streaming:r,toolContext:n,activeSkills:s,round:i,verbose:c,dependencies:l,config:a={}}){let u=a.maxToolResultChars||3e3,{fetchCompletion:d,fetchStreamingCompletion:m,onFallbackLog:p,hasToolCalls:g,getTextContent:y,parseToolCalls:h,buildAssistantMessage:b,buildToolResultMessage:w,executeTool:E,onToolCallLog:S,injectTools:v}=l;Array.isArray(o?.messages)&&(o.messages=Ir(o.messages));let k=await Bo({body:o,streaming:r,auth:e,options:t,fetchCompletion:d,fetchStreamingCompletion:m,onFallbackLog:p}),R=k?.data||k;if(!g(R))return{done:!0,text:y(R),body:k?.fallback||o};let C=h(R),L=k?.fallback||o;L.messages.push(b(R)),c&&typeof S=="function"&&S(C);let K=await Promise.all(C.map((P,D)=>(typeof t.onToolCall=="function"&&t.onToolCall(P.name,P.args,{round:i,index:D,total:C.length}),E(P,n))));for(let P=0;P<C.length;P++){let M=C[P].name==="get_skill_context"?typeof K[P]=="string"?K[P]:JSON.stringify(K[P]):Uo(K[P],u);L.messages.push(w(C[P].id,M))}return typeof t.onToolCall=="function"&&t.onToolCall(null),v(L,s),{done:!1,body:L}}var Go=ae.ASSISTANT,Ko=15,jt="get_skill_context";function ke(o){!o||typeof o!="object"||(o.type==="object"&&o.properties&&(o.required=Object.keys(o.properties),o.additionalProperties=!1,Object.values(o.properties).forEach(ke)),o.type==="array"&&o.items&&ke(o.items),o.anyOf&&o.anyOf.forEach(ke),o.oneOf&&o.oneOf.forEach(ke),o.allOf&&o.allOf.forEach(ke))}var kr={maxBytes:49e3,systemMaxChars:12e3},Ce=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",zo=o=>Buffer.byteLength(JSON.stringify(o),"utf8");function wt(o){return Array.isArray(o)?new Set(o.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function Jo(o){return Array.isArray(o)?o.map(e=>String(e||"").trim()).filter(Boolean):[]}var he=class extends Fo{#e;#t;#r=new Ve;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new ge,this.#t=e.completionProvider||new Ie):(this.#e=e||new ge,this.#t=new Ie)}canHandle(e){return Ut().ok}async invoke(e,t={}){let r=q("OPENAI_API_KEY");try{let n=t.model&&t.model!=="auto"?t.model:Go,s=Ut();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,l=Ce();if(l?await this.#m(i,n,c,s.tokenPreview||"none"):f.debug(`[Assistant] ${c} | model: ${n} | messages: ${i.length}`),t.schema)return this.#c(n,i,s,t);let a=t.activeSkills||[],u=this.#p(t),d=this.#f(a,u),m=this.#d(d),p=this.#u(t),g={...t,payloadCompaction:p},y={activeSkills:d,options:g,executionRegistry:m,capabilityPolicy:u},h=!!t.stream,b={model:n,messages:[...i],stream:!1};this.#o(b,d,u);for(let w=0;w<Ko;w++){if(t.signal?.aborted){let S=new Error("Aborted via signal");throw S.name="AbortError",S}let E=await Cr({body:b,auth:s,options:g,streaming:h,toolContext:y,activeSkills:d,round:w,verbose:l,dependencies:{fetchCompletion:this.#s.bind(this),fetchStreamingCompletion:this.#l.bind(this),onFallbackLog:(S,v)=>{Ce()&&console.log(`413 fallback: messages ${S.messages.length} -> ${v.messages.length}, bytes=${zo(v)}`)},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,v)=>this.#e.buildToolResultMessage(S,v),executeTool:(S,v)=>this.#a(S,v),onToolCallLog:async S=>{let v=(await import("chalk")).default;console.log(v.dim(` ${S.map(k=>`${k.name}(${JSON.stringify(k.args).slice(0,80)})`).join(", ")}`))},injectTools:(S,v)=>this.#o(S,v,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=_t(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(jt,t)&&r.push({name:jt,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===jt){let a=String(e.args?.skillId||"").trim();if(!a)return JSON.stringify({error:"skillId is required"});if(!r.includes(a))return JSON.stringify({error:`Skill "${a}" is not active`,activeSkills:r});let u=_t(a);if(!u)return JSON.stringify({error:`Skill "${a}" not found`});let d=typeof u.promptFragment=="function"?u.promptFragment():u.promptFragment||"",m=(u.tools||[]).map(g=>g.name),p=JSON.stringify({skillId:a,description:u.description||"",toolNames:m,promptFragment:d||""});return Ce()&&(console.log(`
71
71
  \u{1F4D6} get_skill_context("${a}") \u2192 ${p.length} chars (fragment: ${d.length} chars)`),console.log(` tools: [${m.join(", ")}]`),console.log(` fragment preview: ${d.slice(0,200).replace(/\n/g,"\\n")}\u2026
72
- `)),p}let c=s?.get(e.name)||null;if(!c)return`Unknown tool: ${e.name}`;let l=_t(c.skillId);if(!l)return`Skill "${c.skillId}" not found for tool "${e.name}"`;if(c.mode==="handler")try{return l.handleToolCall(e.name,e.args,t)}catch(a){return`Error in ${e.name}: ${a.message}`}if(c.mode==="mcp")try{if(!this.#r.isRunning(l.serverName)){let u=l.resolve(n);if(!u)return`Skill "${c.skillId}" is not available (cannot start server)`;await this.#r.ensureServer(l.serverName,u)}let a=await this.#r.callTool(l.serverName,e.name,e.args);return a.text||(a.isError?"Tool call failed":"Done")}catch(a){return`MCP error (${l.serverName}): ${a.message}`}return`Skill "${c.skillId}" owns tool "${e.name}" but has no execution mode`}async#l(e,t,r){return this.#t.fetchStreamingCompletion(e,t,{...r,onBudget:({beforeBytes:n,meta:s})=>{Ce()&&console.log(`payload bytes (stream) before=${n} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#s(e,t,r){return this.#t.fetchCompletion(e,t,{...r,onBudget:({beforeBytes:n,meta:s})=>{Ce()&&console.log(`payload bytes before=${n} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#c(e,t,r,n){let{zodToJson:s}=await Promise.resolve().then(()=>(Ke(),gr)),i=typeof n.schema?.parse=="function",c=i?s(n.schema,{}):n.schema;delete c.$schema,ke(c);let l={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:c,strict:!0}}},a=await this.#s(l,r,n),u=this.#e.getTextContent(a),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||kr.maxBytes),systemMaxChars:Number(t.systemMaxChars||kr.systemMaxChars)}}#p(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:wt(t.allowTools||e.allowTools),denyTools:wt(t.denyTools||e.denyTools),denyPrefixes:Go(t.denyPrefixes||e.denyToolPrefixes),includeSkills:wt(t.includeSkills||e.includeSkills),excludeSkills:wt(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=_t(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 l=String(c?.name||"").trim();if(l){if(t.has(l)){r.push({tool:l,winner:t.get(l).skillId,skipped:n});continue}t.set(l,{skillId:n,mode:i})}}}if(r.length>0&&Ce()){let n=r.slice(0,5).map(s=>`${s.tool}:${s.winner}>${s.skipped}`).join(", ");console.log(`tool registry collisions: ${n}${r.length>5?" ...":""}`)}return t}async#m(e,t,r,n){console.log(`
72
+ `)),p}let c=s?.get(e.name)||null;if(!c)return`Unknown tool: ${e.name}`;let l=_t(c.skillId);if(!l)return`Skill "${c.skillId}" not found for tool "${e.name}"`;if(c.mode==="handler")try{return l.handleToolCall(e.name,e.args,t)}catch(a){return`Error in ${e.name}: ${a.message}`}if(c.mode==="mcp")try{if(!this.#r.isRunning(l.serverName)){let u=l.resolve(n);if(!u)return`Skill "${c.skillId}" is not available (cannot start server)`;await this.#r.ensureServer(l.serverName,u)}let a=await this.#r.callTool(l.serverName,e.name,e.args);return a.text||(a.isError?"Tool call failed":"Done")}catch(a){return`MCP error (${l.serverName}): ${a.message}`}return`Skill "${c.skillId}" owns tool "${e.name}" but has no execution mode`}async#l(e,t,r){return this.#t.fetchStreamingCompletion(e,t,{...r,onBudget:({beforeBytes:n,meta:s})=>{Ce()&&console.log(`payload bytes (stream) before=${n} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#s(e,t,r){return this.#t.fetchCompletion(e,t,{...r,onBudget:({beforeBytes:n,meta:s})=>{Ce()&&console.log(`payload bytes before=${n} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#c(e,t,r,n){let{zodToJson:s}=await Promise.resolve().then(()=>(Ke(),gr)),i=typeof n.schema?.parse=="function",c=i?s(n.schema,{}):n.schema;delete c.$schema,ke(c);let l={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:c,strict:!0}}},a=await this.#s(l,r,n),u=this.#e.getTextContent(a),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||kr.maxBytes),systemMaxChars:Number(t.systemMaxChars||kr.systemMaxChars)}}#p(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:wt(t.allowTools||e.allowTools),denyTools:wt(t.denyTools||e.denyTools),denyPrefixes:Jo(t.denyPrefixes||e.denyToolPrefixes),includeSkills:wt(t.includeSkills||e.includeSkills),excludeSkills:wt(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=_t(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 l=String(c?.name||"").trim();if(l){if(t.has(l)){r.push({tool:l,winner:t.get(l).skillId,skipped:n});continue}t.set(l,{skillId:n,mode:i})}}}if(r.length>0&&Ce()){let n=r.slice(0,5).map(s=>`${s.tool}:${s.winner}>${s.skipped}`).join(", ");console.log(`tool registry collisions: ${n}${r.length>5?" ...":""}`)}return t}async#m(e,t,r,n){console.log(`
73
73
  \u25C6 Model: ${t} | proxy: ${r} | token: ${n||"none"}
74
- `);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 l=c.role==="user"?"Human":"AI",a=c.content?.length>200?`${c.content.slice(0,200)}...`:c.content||"";console.log(s.dim(`[${l}] ${a}`))}console.log(s.dim("\u2500".repeat(60)))}};var Pr=!1;function Bt(){Pr||(xt(new he),xt(new pe),xt(new fe),xt(new me),Pr=!0)}function Nr(o){return null}import{spawn as Zo}from"node:child_process";import{mkdirSync as Lr,existsSync as Vo,writeFileSync as Wo}from"node:fs";import{join as zt}from"node:path";import{ContextLoader as qo,WorkflowGraph as Xo,Node as Qo,WorkflowState as es,DEFAULT_OUTPUT_BASE as Mr,SESSIONS_DIR as ts,SESSION_INFO_FILE as rs}from"@zibby/agent-workflow";import{exec as Ko}from"node:child_process";import{promisify as zo}from"node:util";import{existsSync as Jo}from"node:fs";import{join as Ft}from"node:path";import{homedir as Gt}from"node:os";var Rr=zo(Ko);async function Kt(){try{return await Rr("cursor-agent --version"),"cursor-agent"}catch{let e=[Ft(Gt(),".local","bin","cursor-agent"),Ft(Gt(),".cursor","bin","cursor-agent"),Ft(Gt(),".cursor-agent","bin","cursor-agent")];for(let t of e)if(Jo(t))try{return await Rr(`"${t}" --version`),t}catch{}return null}}async function Yo(){return await Kt()!==null}function Ho(){return`
74
+ `);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 l=c.role==="user"?"Human":"AI",a=c.content?.length>200?`${c.content.slice(0,200)}...`:c.content||"";console.log(s.dim(`[${l}] ${a}`))}console.log(s.dim("\u2500".repeat(60)))}};var Pr=!1;function Bt(){Pr||(xt(new he),xt(new pe),xt(new fe),xt(new me),Pr=!0)}function Nr(o){return null}import{spawn as qo}from"node:child_process";import{mkdirSync as Lr,existsSync as Xo,writeFileSync as Qo}from"node:fs";import{join as zt}from"node:path";import{ContextLoader as es,WorkflowGraph as ts,Node as rs,WorkflowState as ns,DEFAULT_OUTPUT_BASE as Mr,SESSIONS_DIR as os,SESSION_INFO_FILE as ss}from"@zibby/agent-workflow";import{exec as Yo}from"node:child_process";import{promisify as Ho}from"node:util";import{existsSync as Zo}from"node:fs";import{join as Ft}from"node:path";import{homedir as Gt}from"node:os";var Rr=Ho(Yo);async function Kt(){try{return await Rr("cursor-agent --version"),"cursor-agent"}catch{let e=[Ft(Gt(),".local","bin","cursor-agent"),Ft(Gt(),".cursor","bin","cursor-agent"),Ft(Gt(),".cursor-agent","bin","cursor-agent")];for(let t of e)if(Zo(t))try{return await Rr(`"${t}" --version`),t}catch{}return null}}async function Wo(){return await Kt()!==null}function Vo(){return`
75
75
  \u274C cursor-agent CLI not found!
76
76
 
77
77
  To use the Cursor agent, install it from:
@@ -97,22 +97,22 @@ ${c}
97
97
  `);let l=null;if(n)try{if(l=o.extractJsonFromStream(c),!l)throw new Error("No valid result JSON found in output");console.log(`
98
98
  \u2705 Parsed Output:
99
99
  ${JSON.stringify(l,null,2)}
100
- `)}catch(a){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${a.message}`)}return{success:!0,output:l,raw:c}}async cleanup(){this.adapter&&this.adapter.isConnected()&&await this.adapter.disconnect()}async executePrompt(e,t=process.cwd(),r=3e5,n=null,s=!0){let i=this.agentCommand;if(i==="cursor-agent"){let c=await Kt();c&&(i=c)}return new Promise((c,l)=>{let a="",u=this.buildArgs(e,s);n&&u.push("--model",n);let d={...process.env},m=Zo(i,u,{cwd:t,env:d,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),p=setTimeout(()=>{console.log(`
100
+ `)}catch(a){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${a.message}`)}return{success:!0,output:l,raw:c}}async cleanup(){this.adapter&&this.adapter.isConnected()&&await this.adapter.disconnect()}async executePrompt(e,t=process.cwd(),r=3e5,n=null,s=!0){let i=this.agentCommand;if(i==="cursor-agent"){let c=await Kt();c&&(i=c)}return new Promise((c,l)=>{let a="",u=this.buildArgs(e,s);n&&u.push("--model",n);let d={...process.env},m=qo(i,u,{cwd:t,env:d,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),p=setTimeout(()=>{console.log(`
101
101
  \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),l(new Error(`Agent timed out after ${r/1e3}s. The agent may be stuck or waiting for user input.`))},r),g=0,y=Date.now(),h=setInterval(()=>{if(a.length>g)g=a.length,y=Date.now();else{let S=Date.now()-y;S>1e4&&console.log(`\u23F3 AI agent is thinking... (${Math.floor(S/1e3)}s, ${a.length} bytes so far)`)}},1e4),b=()=>{clearTimeout(p),clearInterval(h),m&&!m.killed&&(m.kill("SIGTERM"),setTimeout(()=>{m.killed||m.kill("SIGKILL")},2e3))},w=()=>{console.log(`
102
102
 
103
- \u{1F6D1} Interrupted by user (Ctrl+C)`),b(),l(new Error("Interrupted by user"))};process.on("SIGINT",w);let E=new oe;m.stdout.on("data",S=>{let v=S.toString();a+=v;let k=E.processChunk(v);k&&(process.stdout.write(k,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),y=Date.now(),g+=k.length)}),m.on("close",S=>{process.off("SIGINT",w),clearTimeout(p),clearInterval(h);let v=E.flush();v&&process.stdout.write(v),a=E.getRawText();let k=E.getResult();S===0?c({raw:a,extracted:k}):l(new Error(`Agent exited with code ${S}`))}),m.on("error",S=>{process.off("SIGINT",w),clearTimeout(p),clearInterval(h),l(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,l=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=l.paths?.sessionPrefix,w=b?`${b}_${h}`:h;c=c||Date.now();let E=l.paths?.output||Mr;i=zt(s,E,ts,w),Vo(i)||Lr(i,{recursive:!0})}let a=l.paths?.output||Mr,u=zt(s,a,rs);Lr(zt(s,a),{recursive:!0}),Wo(u,JSON.stringify({sessionPath:i,sessionTimestamp:c||i.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
103
+ \u{1F6D1} Interrupted by user (Ctrl+C)`),b(),l(new Error("Interrupted by user"))};process.on("SIGINT",w);let E=new oe;m.stdout.on("data",S=>{let v=S.toString();a+=v;let k=E.processChunk(v);k&&(process.stdout.write(k,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),y=Date.now(),g+=k.length)}),m.on("close",S=>{process.off("SIGINT",w),clearTimeout(p),clearInterval(h);let v=E.flush();v&&process.stdout.write(v),a=E.getRawText();let k=E.getResult();S===0?c({raw:a,extracted:k}):l(new Error(`Agent exited with code ${S}`))}),m.on("error",S=>{process.off("SIGINT",w),clearTimeout(p),clearInterval(h),l(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,l=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=l.paths?.sessionPrefix,w=b?`${b}_${h}`:h;c=c||Date.now();let E=l.paths?.output||Mr;i=zt(s,E,os,w),Xo(i)||Lr(i,{recursive:!0})}let a=l.paths?.output||Mr,u=zt(s,a,ss);Lr(zt(s,a),{recursive:!0}),Qo(u,JSON.stringify({sessionPath:i,sessionTimestamp:c||i.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
104
104
  ${"=".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)}
105
- `);let d=await qo.loadContext(r.specPath||"",s,r.contextConfig||{}),m=new es({...r,sessionPath:i,sessionTimestamp:c,context:d}),g=await new Qo(n).execute(this,m);return console.log(`
105
+ `);let d=await es.loadContext(r.specPath||"",s,r.contextConfig||{}),m=new ns({...r,sessionPath:i,sessionTimestamp:c,context:d}),g=await new rs(n).execute(this,m);return console.log(`
106
106
  ${"=".repeat(80)}`),console.log(`\u2705 Node ${e} completed`),console.log(`${"=".repeat(80)}
107
- `),{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 ns(o,e={}){let t=new Pe(e);return t.buildGraph=function(){let r=new Xo;return o(r),r},e.onComplete&&(t.onComplete=e.onComplete),t}import{WorkflowGraph as Lf,resolveWorkflowSession as Mf,generateWorkflowSessionId as Df,clearInheritedSessionEnvForFreshRun as Uf,shouldTrustInheritedSessionEnv as jf,readPinnedSessionPathFromEnv as Bf,syncProcessEnvToSession as Ff}from"@zibby/agent-workflow";import{writeFileSync as Dr,existsSync as os,mkdirSync as ss}from"node:fs";import{join as Jt}from"node:path";var Yt=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=Jt(r,"title.txt");Dr(s,n,"utf-8"),f.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=Jt(t,r);os(c)||ss(c,{recursive:!0});let l=Jt(c,"result.json");Dr(l,JSON.stringify(n,null,2),"utf-8"),f.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)f.info("Workflow completed successfully."),t&&f.info(`Output: ${t}`);else if(s){let i=r.filter(([,c])=>!c.success).map(([c])=>c);f.info(`Workflow completed with failures in: ${i.join(", ")}`),t&&f.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 zf}from"zod/v3";import{AgentStrategy as xs,DEFAULT_OUTPUT_BASE as Es,SESSION_INFO_FILE as Ts,STOP_REQUEST_FILE as As,getAllSkills as vs,getSkill as Kr}from"@zibby/agent-workflow";import{spawn as $s,execSync as ye}from"node:child_process";import{writeFileSync as zr,readFileSync as Jr,mkdirSync as Yr,existsSync as qe,accessSync as Hr,constants as Zr,unlinkSync as Os}from"node:fs";import{join as re,resolve as Is}from"node:path";import{homedir as Xe}from"node:os";import is from"axios";import{homedir as as}from"node:os";import{join as ls}from"node:path";import{existsSync as cs,readFileSync as us}from"node:fs";import{toJSONSchema as ps}from"zod";function fs(){if(process.env.OPENAI_PROXY_TOKEN)return f.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return f.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let o=ls(as(),".zibby","config.json");if(cs(o)){let e=JSON.parse(us(o,"utf-8"));if(e.sessionToken)return f.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(o){f.debug(`[Auth] Could not read zibby login session: ${o.message}`)}return null}function ds(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function Ne(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(Ne)}else"additionalProperties"in o||(o.additionalProperties=!0);o.type==="array"&&o.items&&Ne(o.items),o.anyOf&&o.anyOf.forEach(Ne),o.oneOf&&o.oneOf.forEach(Ne),o.allOf&&o.allOf.forEach(Ne)}}async function Ur(o,e){f.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=fs();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=ds();f.info(`\u{1F517} Using OpenAI proxy: ${r}`);let n=ps(e),s=n;if(n.$ref&&n.definitions){let u=n.$ref.split("/").pop();s=n.definitions[u]||n,f.debug(`Extracted schema from $ref: ${u}`)}delete s.$schema,Ne(s);let i=4e5,c=o;o.length>i&&(f.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${o.length} chars) exceeds limit, keeping last ${i} chars`),c=`... [truncated early content] ...
107
+ `),{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 is(o,e={}){let t=new Pe(e);return t.buildGraph=function(){let r=new ts;return o(r),r},e.onComplete&&(t.onComplete=e.onComplete),t}import{WorkflowGraph as Uf,resolveWorkflowSession as jf,generateWorkflowSessionId as Bf,clearInheritedSessionEnvForFreshRun as Ff,shouldTrustInheritedSessionEnv as Gf,readPinnedSessionPathFromEnv as Kf,syncProcessEnvToSession as zf}from"@zibby/agent-workflow";import{writeFileSync as Dr,existsSync as as,mkdirSync as ls}from"node:fs";import{join as Jt}from"node:path";var Yt=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=Jt(r,"title.txt");Dr(s,n,"utf-8"),f.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=Jt(t,r);as(c)||ls(c,{recursive:!0});let l=Jt(c,"result.json");Dr(l,JSON.stringify(n,null,2),"utf-8"),f.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)f.info("Workflow completed successfully."),t&&f.info(`Output: ${t}`);else if(s){let i=r.filter(([,c])=>!c.success).map(([c])=>c);f.info(`Workflow completed with failures in: ${i.join(", ")}`),t&&f.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 Hf}from"zod/v3";import{AgentStrategy as As,DEFAULT_OUTPUT_BASE as vs,SESSION_INFO_FILE as Os,STOP_REQUEST_FILE as $s,getAllSkills as Is,getSkill as Kr}from"@zibby/agent-workflow";import{spawn as Cs,execSync as ye}from"node:child_process";import{writeFileSync as zr,readFileSync as Jr,mkdirSync as Yr,existsSync as qe,accessSync as Hr,constants as Zr,unlinkSync as ks}from"node:fs";import{join as re,resolve as Ps}from"node:path";import{homedir as Xe}from"node:os";import cs from"axios";import{homedir as us}from"node:os";import{join as ps}from"node:path";import{existsSync as fs,readFileSync as ds}from"node:fs";import{toJSONSchema as ms}from"zod";function gs(){if(process.env.OPENAI_PROXY_TOKEN)return f.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return f.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let o=ps(us(),".zibby","config.json");if(fs(o)){let e=JSON.parse(ds(o,"utf-8"));if(e.sessionToken)return f.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(o){f.debug(`[Auth] Could not read zibby login session: ${o.message}`)}return null}function hs(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function Ne(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(Ne)}else"additionalProperties"in o||(o.additionalProperties=!0);o.type==="array"&&o.items&&Ne(o.items),o.anyOf&&o.anyOf.forEach(Ne),o.oneOf&&o.oneOf.forEach(Ne),o.allOf&&o.allOf.forEach(Ne)}}async function Ur(o,e){f.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=gs();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=hs();f.info(`\u{1F517} Using OpenAI proxy: ${r}`);let n=ms(e),s=n;if(n.$ref&&n.definitions){let u=n.$ref.split("/").pop();s=n.definitions[u]||n,f.debug(`Extracted schema from $ref: ${u}`)}delete s.$schema,Ne(s);let i=4e5,c=o;o.length>i&&(f.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${o.length} chars) exceeds limit, keeping last ${i} chars`),c=`... [truncated early content] ...
108
108
  ${o.slice(-i)}`);let l=`Extract and format the following information into structured JSON matching the schema.
109
109
 
110
110
  RAW CONTENT:
111
111
  ${c}
112
112
 
113
- Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,a={model:ae.OPENAI_POSTPROCESSING,messages:[{role:"user",content:l}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:s,strict:!0}}};f.info(`\u{1F4E4} Sending to OpenAI proxy: model=${ae.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(s.properties||{}).join(", ")}`),f.debug(` Schema size: ${JSON.stringify(s).length} chars`),f.debug(` Prompt size: ${l.length} chars`);try{let u={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(u["x-proxy-token"]=t,u["x-execution-id"]=process.env.EXECUTION_ID||""):(u.Authorization=`Bearer ${t}`,u["x-api-key"]=process.env.ZIBBY_API_KEY||"",u["x-execution-id"]=process.env.EXECUTION_ID||"");let m=(await is.post(r,a,{headers:u,timeout:ft.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!m)throw new Error("OpenAI proxy returned empty response");let p=JSON.parse(m);return f.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:p,raw:o}}catch(u){if(u.response){let d=u.response.status,m=u.response.data;throw f.error(`\u274C OpenAI proxy request failed: ${d}`),f.error(` Status: ${d}`),f.error(` Response: ${JSON.stringify(m,null,2)}`),d===401||d===403?new Error(`Authentication failed for OpenAI proxy.
113
+ Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,a={model:ae.OPENAI_POSTPROCESSING,messages:[{role:"user",content:l}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:s,strict:!0}}};f.info(`\u{1F4E4} Sending to OpenAI proxy: model=${ae.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(s.properties||{}).join(", ")}`),f.debug(` Schema size: ${JSON.stringify(s).length} chars`),f.debug(` Prompt size: ${l.length} chars`);try{let u={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(u["x-proxy-token"]=t,u["x-execution-id"]=process.env.EXECUTION_ID||""):(u.Authorization=`Bearer ${t}`,u["x-api-key"]=process.env.ZIBBY_API_KEY||"",u["x-execution-id"]=process.env.EXECUTION_ID||"");let m=(await cs.post(r,a,{headers:u,timeout:ft.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!m)throw new Error("OpenAI proxy returned empty response");let p=JSON.parse(m);return f.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:p,raw:o}}catch(u){if(u.response){let d=u.response.status,m=u.response.data;throw f.error(`\u274C OpenAI proxy request failed: ${d}`),f.error(` Status: ${d}`),f.error(` Response: ${JSON.stringify(m,null,2)}`),d===401||d===403?new Error(`Authentication failed for OpenAI proxy.
114
114
  Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
115
- Response: ${JSON.stringify(m)}`,{cause:u}):new Error(`Failed to format Cursor output: ${m?.error?.message||"Unknown error"}`,{cause:u})}throw f.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}import{copyFileSync as ms,existsSync as Ht,lstatSync as gs,mkdirSync as jr,rmSync as hs,symlinkSync as ys,unlinkSync as bs}from"node:fs";import{join as se}from"node:path";import{homedir as Ss}from"node:os";import{randomBytes as _s}from"node:crypto";var ws=["cli-config.json","config.json","auth.json","argv.json"];function Br(o){return!(!o||typeof o!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function Fr(o){let e=se(o||process.cwd(),".zibby","tmp");jr(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${_s(4).toString("hex")}`,r=se(e,`cursor-agent-home-${t}`),n=se(r,".cursor");jr(n,{recursive:!0});let s=Ss(),i=se(s,".cursor");if(Ht(i))for(let c of ws){let l=se(i,c);if(Ht(l))try{ms(l,se(n,c))}catch{}}if(process.platform==="darwin"){let c=se(s,"Library");if(Ht(c))try{ys(c,se(r,"Library"))}catch{}}return r}function Gr(o){if(!(!o||typeof o!="string"))try{let e=se(o,"Library");try{gs(e).isSymbolicLink()&&bs(e)}catch{}hs(o,{recursive:!0,force:!0})}catch{}}var Et=class extends xs{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[re(Xe(),".local","bin","cursor-agent"),re(Xe(),".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("/")){Hr(r,Zr.X_OK);let n=ye(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(n&&n.length>0)return f.debug(`[Cursor] Found agent at: ${r} (version: ${n.trim().slice(0,50)})`),!0}else{let n=ye(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!n)continue;let s=ye(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return f.debug(`[Cursor] Found '${r}' in PATH at ${n} (version: ${s.trim().slice(0,50)})`),!0}}catch{continue}return f.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:r=process.cwd(),print:n=!1,schema:s=null,skills:i=null,sessionPath:c=null,nodeName:l=null,timeout:a=ft.CURSOR_AGENT_DEFAULT,config:u={},signal:d=null}=t,m=u?.agent?.strictMode||!1,p=t.model??u?.agent?.cursor?.model??ae.CURSOR,g=q("CURSOR_API_KEY");try{f.debug(`[Cursor] Invoking (model: ${p}, timeout: ${a/1e3}s, skills: ${JSON.stringify(i)})`);let h=(this._setupMcpConfig(c,r,u,i,l)||{}).isolatedMcpHome??null,b=[re(Xe(),".local","bin","cursor-agent"),re(Xe(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"],w=null;for(let N of b)try{if(N.startsWith("/"))Hr(N,Zr.X_OK),ye(`"${N}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!ye(`which ${N}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");ye(`${N} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}w=N,f.debug(`[Agent] Using binary: ${N}`);break}catch(x){f.debug(`[Agent] Binary '${N}' check failed: ${x.message}`);continue}if(!w)throw new Error(`Cursor Agent CLI not found or not working.
115
+ Response: ${JSON.stringify(m)}`,{cause:u}):new Error(`Failed to format Cursor output: ${m?.error?.message||"Unknown error"}`,{cause:u})}throw f.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}import{copyFileSync as ys,existsSync as Ht,lstatSync as bs,mkdirSync as jr,rmSync as Ss,symlinkSync as _s,unlinkSync as ws}from"node:fs";import{join as se}from"node:path";import{homedir as xs}from"node:os";import{randomBytes as Es}from"node:crypto";var Ts=["cli-config.json","config.json","auth.json","argv.json"];function Br(o){return!(!o||typeof o!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function Fr(o){let e=se(o||process.cwd(),".zibby","tmp");jr(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${Es(4).toString("hex")}`,r=se(e,`cursor-agent-home-${t}`),n=se(r,".cursor");jr(n,{recursive:!0});let s=xs(),i=se(s,".cursor");if(Ht(i))for(let c of Ts){let l=se(i,c);if(Ht(l))try{ys(l,se(n,c))}catch{}}if(process.platform==="darwin"){let c=se(s,"Library");if(Ht(c))try{_s(c,se(r,"Library"))}catch{}}return r}function Gr(o){if(!(!o||typeof o!="string"))try{let e=se(o,"Library");try{bs(e).isSymbolicLink()&&ws(e)}catch{}Ss(o,{recursive:!0,force:!0})}catch{}}var Et=class extends As{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[re(Xe(),".local","bin","cursor-agent"),re(Xe(),".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("/")){Hr(r,Zr.X_OK);let n=ye(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(n&&n.length>0)return f.debug(`[Cursor] Found agent at: ${r} (version: ${n.trim().slice(0,50)})`),!0}else{let n=ye(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!n)continue;let s=ye(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return f.debug(`[Cursor] Found '${r}' in PATH at ${n} (version: ${s.trim().slice(0,50)})`),!0}}catch{continue}return f.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:r=process.cwd(),print:n=!1,schema:s=null,skills:i=null,sessionPath:c=null,nodeName:l=null,timeout:a=ft.CURSOR_AGENT_DEFAULT,config:u={},signal:d=null}=t,m=u?.agent?.strictMode||!1,p=t.model??u?.agent?.cursor?.model??ae.CURSOR,g=q("CURSOR_API_KEY");try{f.debug(`[Cursor] Invoking (model: ${p}, timeout: ${a/1e3}s, skills: ${JSON.stringify(i)})`);let h=(this._setupMcpConfig(c,r,u,i,l)||{}).isolatedMcpHome??null,b=[re(Xe(),".local","bin","cursor-agent"),re(Xe(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"],w=null;for(let N of b)try{if(N.startsWith("/"))Hr(N,Zr.X_OK),ye(`"${N}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!ye(`which ${N}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");ye(`${N} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}w=N,f.debug(`[Agent] Using binary: ${N}`);break}catch(x){f.debug(`[Agent] Binary '${N}' check failed: ${x.message}`);continue}if(!w)throw new Error(`Cursor Agent CLI not found or not working.
116
116
 
117
117
  Checked paths:
118
118
  ${b.map(N=>` - ${N}`).join(`
@@ -124,31 +124,31 @@ Install cursor-agent:
124
124
  Then add to PATH:
125
125
  echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
126
126
 
127
- Test with: agent --version`);let E=new $e(e),S=null;if(s){let N=`zibby-result-${Date.now()}.json`;S=re(r,".zibby","tmp",N);let x=re(r,".zibby","tmp");qe(x)||Yr(x,{recursive:!0}),E.addStructuredOutput(s,S)}let v=process.env.CURSOR_API_KEY,k=v?` | key: ***${v.slice(-4)}`:" | key: not set";console.log(`
127
+ Test with: agent --version`);let E=new Oe(e),S=null;if(s){let N=`zibby-result-${Date.now()}.json`;S=re(r,".zibby","tmp",N);let x=re(r,".zibby","tmp");qe(x)||Yr(x,{recursive:!0}),E.addStructuredOutput(s,S)}let v=process.env.CURSOR_API_KEY,k=v?` | key: ***${v.slice(-4)}`:" | key: not set";console.log(`
128
128
  \u25C6 Model: ${p||"auto"}${k}
129
129
  `);let R=(await import("chalk")).default,C=E.getUserPrompt();console.log(`
130
130
  ${R.bold("Prompt sent to LLM:")}`),console.log(R.dim("\u2500".repeat(60))),console.log(R.dim(C)),console.log(R.dim("\u2500".repeat(60)));let L=E.build(),K=E.getStats(),P=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",p||"auto"];if(process.env.CURSOR_API_KEY&&P.push("--api-key",process.env.CURSOR_API_KEY),P.push(L),f.debug(`[Agent] User prompt: ${K.userPromptLength} chars, System instructions: ${K.systemInstructionsLength} chars (${K.instructionCount} blocks), Full: ${K.fullPromptLength} chars, model: ${p||"auto"}`),f.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${p||"auto"} (from .zibby.config.js agent.cursor.model)
131
- `)}catch{}let D,M=null;try{let N=c||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);D=await this._spawnWithStreaming(w,P,r,a,null,N,h,d)}catch(N){M=N}let O=D?.stdout||"";if(s){let N=typeof s.parse=="function",x=null,_=!!(S&&qe(S));if(S&&f.info(`[Agent] Result file: ${_?"present":"missing"} at ${S}`),_)try{let T=Jr(S,"utf-8").trim();x=JSON.parse(T),f.info(`[Agent] Parsed JSON from result file OK (${T.length} chars) \u2192 object ready for validation`),M&&f.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(T){f.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${T.message}`)}else if(M)f.warn(`[Agent] Result file missing at ${S} (agent process error \u2014 may still recover if strictMode repairs)`);else throw f.error(`\u274C [Agent] Result file was never created at ${S}`),new Error(`Agent did not write required result file at ${S}`);if(x&&N)try{let T=s.parse(x);return f.info("\u2705 [Agent] Zod validation passed for structured result file"),m&&f.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:O,structured:T}}catch(T){let B=T.issues?T.issues.map($=>` - ${$.path.join(".")}: ${$.message}`).join(`
131
+ `)}catch{}let D,M=null;try{let N=c||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);D=await this._spawnWithStreaming(w,P,r,a,null,N,h,d)}catch(N){M=N}let $=D?.stdout||"";if(s){let N=typeof s.parse=="function",x=null,_=!!(S&&qe(S));if(S&&f.info(`[Agent] Result file: ${_?"present":"missing"} at ${S}`),_)try{let T=Jr(S,"utf-8").trim();x=JSON.parse(T),f.info(`[Agent] Parsed JSON from result file OK (${T.length} chars) \u2192 object ready for validation`),M&&f.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(T){f.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${T.message}`)}else if(M)f.warn(`[Agent] Result file missing at ${S} (agent process error \u2014 may still recover if strictMode repairs)`);else throw f.error(`\u274C [Agent] Result file was never created at ${S}`),new Error(`Agent did not write required result file at ${S}`);if(x&&N)try{let T=s.parse(x);return f.info("\u2705 [Agent] Zod validation passed for structured result file"),m&&f.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:$,structured:T}}catch(T){let B=T.issues?T.issues.map(O=>` - ${O.path.join(".")}: ${O.message}`).join(`
132
132
  `):T.message?.slice(0,400);if(f.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
133
133
  ${B}`),f.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
134
134
  ${JSON.stringify(x,null,2).slice(0,500)}`),!m)throw new Error(`Agent output failed schema validation:
135
135
  ${B}
136
136
 
137
137
  The agent wrote invalid data that doesn't match the required outputSchema.
138
- Enable strictMode in .zibby.config.js for automatic repair.`,{cause:T})}else{if(x)return f.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),m&&f.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:O,structured:x};_&&f.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(m&&!M){let T=D.parsedText,B=x?JSON.stringify(x):T;f.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${B.length} chars in)`);try{let $=await Ur(B,s);if(N){let F=s.parse($.structured);return f.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:O,structured:F}}return{raw:O,...$}}catch($){if(f.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${$.message}`),x)return f.warn("[Agent] Using agent's original result file as fallback"),{raw:O,structured:x}}}if(M)throw M;let I=_?x==null?"file existed but JSON.parse failed \u2014 see WARN log above":N?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw f.error(`\u274C [Agent] No validated structured output: ${I}`),f.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error(`Agent did not produce a valid result file at ${S}. Enable strictMode for proxy fallback.`)}if(M)throw M;return this._extractFinalResult(O)||D?.parsedText||O}finally{g.dispose()}}_extractFinalResult(e){if(!e)return null;let t=e.split(`
139
- `),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 l=c.filter(a=>a.type==="text"&&a.text).map(a=>a.text).join("");l&&(r=l)}else typeof c=="string"&&c&&(r=c)}}catch{}}return r?.trim()||null}_setupMcpConfig(e,t,r,n=null,s=null){let i=r?.headless,c=re(Xe(),".cursor"),l=re(c,"mcp.json"),a={};if(qe(l))try{a=JSON.parse(Jr(l,"utf-8"))}catch{}let u=a.mcpServers||{},d=r?.paths?.output||Es,m=re(t||process.cwd(),d,Ts),p=Array.isArray(n)?n.map(h=>Kr(h)).filter(Boolean):[...vs()].map(([,h])=>h),g=new Set;for(let h of p)typeof h.resolve=="function"&&(g.has(h.serverName)||(g.add(h.serverName),this._ensureSkillConfigured(u,h,e,m,s,i)));if(e){let h=Kr("browser");h&&typeof h.resolve=="function"&&!g.has(h.serverName)&&this._ensureSkillConfigured(u,h,e,m,"execute_live",i)}if(Object.keys(u).length===0)return f.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let y=`${JSON.stringify({mcpServers:u},null,2)}
140
- `;if(Br(e)){let h=Fr(t||process.cwd()),b=re(h,".cursor","mcp.json");return zr(b,y,"utf8"),f.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${h} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:h}}return qe(c)||Yr(c,{recursive:!0}),zr(l,y,"utf8"),f.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,n,s=null,i){let c=t.cursorKey||t.serverName,l=e[c]?c:e[t.serverName]?t.serverName:null;if(l&&r){let u=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:s,headless:i}):null;u?.args?e[l].args=u.args:e[l].args=(e[l].args||[]).map(p=>p.startsWith("--output-dir=")?`--output-dir=${r}`:p);let d=u?.env||{},m=t.sessionEnvKey?{[t.sessionEnvKey]:n}:{};e[l].env={...e[l].env||{},...d,...m},f.debug(`[MCP] Updated ${l} session \u2192 ${r}`);return}if(l)return;let a=t.resolve({sessionPath:r,nodeName:s,headless:i});if(a){if(at(a)){e[c]=ee("cursor",a),f.debug(`[MCP] ${c} \u2192 ${lt(a)}`);return}e[c]={...a,...t.sessionEnvKey&&{env:{...a.env||{},[t.sessionEnvKey]:n}}},f.debug(`[MCP] Configured ${c}`)}}_spawnWithStreaming(e,t,r,n,s=null,i=null,c=null,l=null){return new Promise((a,u)=>{let d=Date.now(),m="",p="",g=Date.now(),y=0,h=!1,b=null,w=!1,E=!1,S=null;if(i)try{S=re(Is(String(i)),As)}catch{S=null}let v=!1,k=()=>{v||(v=!0,Gr(c))},R={...process.env};c&&(R.HOME=c,process.platform==="win32"&&(R.USERPROFILE=c),f.debug(`[Agent] cursor-agent HOME=${c} (isolated MCP config)`));let C=$s(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:R,...l&&{signal:l}});f.debug(`[Agent] PID: ${C.pid}`);let L=null,K=()=>{h||E||(h=!0,b="aborted",f.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),L=setTimeout(()=>{if(!E){f.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{C.kill("SIGKILL")}catch{}}},5e3))};l&&(l.aborted?K():l.addEventListener("abort",K,{once:!0})),C.stdin.on("error",x=>{x.code!=="EPIPE"&&f.warn(`[Agent] stdin error: ${x.message}`)}),C.stdout.on("error",x=>{x.code!=="EPIPE"&&f.warn(`[Agent] stdout error: ${x.message}`)}),C.stderr.on("error",x=>{x.code!=="EPIPE"&&f.warn(`[Agent] stderr error: ${x.message}`)}),s?(C.stdin.write(s,x=>{x&&x.code!=="EPIPE"&&f.warn(`[Agent] Failed to write to stdin: ${x.message}`),C.stdin.end()}),f.debug(`[Agent] Prompt also piped to stdin (${s.length} chars)`)):C.stdin.end();let P=null;S&&(P=setInterval(()=>{if(!(h||E))try{if(qe(S)){h=!0,b="aborted";try{Os(S)}catch{}f.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),C.kill("SIGTERM"),setTimeout(()=>{C.killed||C.kill("SIGKILL")},2e3)}}catch{}},600));let D=new Set,M=new Date(d).toISOString().replace(/\.\d+Z$/,""),O=setInterval(()=>{let x=Math.round((Date.now()-d)/1e3),_=Math.round((Date.now()-g)/1e3),I=[];try{let B=Math.ceil(x/60)+1,$=ye(`find "${r}" -type f -mmin -${B} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if($)for(let F of $.split(`
141
- `)){let Y=F.replace(`${r}/`,"");D.has(Y)||(D.add(Y),I.push(Y))}}catch{}let T="";I.length>0&&(T=` | \u{1F4C1} new: ${I.map($=>$.split("/").pop()).join(", ")}`),D.size>0&&(T+=` | \u{1F4E6} total: ${D.size} files`),f.debug(`\u{1F493} [Agent] Running for ${x}s | ${y} lines output${T}`),y===0&&x>=30&&D.size===0&&(x<35&&f.warn(`\u26A0\uFE0F [Agent] No output after ${x}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),x>=60&&(h=!0,b=b||"stall",f.error(`\u274C [Agent] No response after ${x}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),C.kill("SIGTERM"),setTimeout(()=>{C.killed||C.kill("SIGKILL")},3e3)))},3e4),j=setTimeout(()=>{h=!0,b=b||"timeout";let x=Math.round((Date.now()-d)/1e3);f.error(`\u23F1\uFE0F [Agent] Timeout after ${x}s \u2014 killing process (PID: ${C.pid})`),m.trim()&&f.warn(`\u{1F4E4} [Agent] Partial output (${m.length} chars) before timeout:
142
- ${m.slice(-2e3)}`),C.kill("SIGTERM"),setTimeout(()=>{C.killed||C.kill("SIGKILL")},5e3)},n),N=new oe;N.onToolCall=(x,_)=>{let I=x,T=_;if(x==="mcpToolCall"&&_?.name)I=_.name.replace(/^mcp_+[^_]+_+/,""),I.includes("-")&&I.split("-")[0]===I.split("-")[1]&&(I=I.split("-")[0]),T=_.args??_.input??_;else{if(x==="readToolCall"||x==="editToolCall"||x==="writeToolCall")return;(x.startsWith("mcp__")||x.includes("ToolCall"))&&(I=x.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(I.includes("memory")?ne.stepMemory(`Tool: ${I}`):ne.stepTool(`Tool: ${I}`),T!=null&&typeof T=="object"&&Object.keys(T).length>0&&!E){let $=JSON.stringify(T),F=$.length>100?`${$.substring(0,100)}...`:$;console.log(` Input: ${F}`)}},C.stdout.on("data",x=>{let _=x.toString();m+=_,g=Date.now(),w||(w=!0);let I=N.processChunk(_);I&&!E&&process.stdout.write(I);let T=_.split(`
138
+ Enable strictMode in .zibby.config.js for automatic repair.`,{cause:T})}else{if(x)return f.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),m&&f.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:$,structured:x};_&&f.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(m&&!M){let T=D.parsedText,B=x?JSON.stringify(x):T;f.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${B.length} chars in)`);try{let O=await Ur(B,s);if(N){let F=s.parse(O.structured);return f.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:$,structured:F}}return{raw:$,...O}}catch(O){if(f.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${O.message}`),x)return f.warn("[Agent] Using agent's original result file as fallback"),{raw:$,structured:x}}}if(M)throw M;let I=_?x==null?"file existed but JSON.parse failed \u2014 see WARN log above":N?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw f.error(`\u274C [Agent] No validated structured output: ${I}`),f.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error(`Agent did not produce a valid result file at ${S}. Enable strictMode for proxy fallback.`)}if(M)throw M;return this._extractFinalResult($)||D?.parsedText||$}finally{g.dispose()}}_extractFinalResult(e){if(!e)return null;let t=e.split(`
139
+ `),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 l=c.filter(a=>a.type==="text"&&a.text).map(a=>a.text).join("");l&&(r=l)}else typeof c=="string"&&c&&(r=c)}}catch{}}return r?.trim()||null}_setupMcpConfig(e,t,r,n=null,s=null){let i=r?.headless,c=re(Xe(),".cursor"),l=re(c,"mcp.json"),a={};if(qe(l))try{a=JSON.parse(Jr(l,"utf-8"))}catch{}let u=a.mcpServers||{},d=r?.paths?.output||vs,m=re(t||process.cwd(),d,Os),p=Array.isArray(n)?n.map(h=>Kr(h)).filter(Boolean):[...Is()].map(([,h])=>h),g=new Set;for(let h of p)typeof h.resolve=="function"&&(g.has(h.serverName)||(g.add(h.serverName),this._ensureSkillConfigured(u,h,e,m,s,i)));if(e){let h=Kr("browser");h&&typeof h.resolve=="function"&&!g.has(h.serverName)&&this._ensureSkillConfigured(u,h,e,m,"execute_live",i)}if(Object.keys(u).length===0)return f.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let y=`${JSON.stringify({mcpServers:u},null,2)}
140
+ `;if(Br(e)){let h=Fr(t||process.cwd()),b=re(h,".cursor","mcp.json");return zr(b,y,"utf8"),f.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${h} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:h}}return qe(c)||Yr(c,{recursive:!0}),zr(l,y,"utf8"),f.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,n,s=null,i){let c=t.cursorKey||t.serverName,l=e[c]?c:e[t.serverName]?t.serverName:null;if(l&&r){let u=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:s,headless:i}):null;u?.args?e[l].args=u.args:e[l].args=(e[l].args||[]).map(p=>p.startsWith("--output-dir=")?`--output-dir=${r}`:p);let d=u?.env||{},m=t.sessionEnvKey?{[t.sessionEnvKey]:n}:{};e[l].env={...e[l].env||{},...d,...m},f.debug(`[MCP] Updated ${l} session \u2192 ${r}`);return}if(l)return;let a=t.resolve({sessionPath:r,nodeName:s,headless:i});if(a){if(at(a)){e[c]=ee("cursor",a),f.debug(`[MCP] ${c} \u2192 ${lt(a)}`);return}e[c]={...a,...t.sessionEnvKey&&{env:{...a.env||{},[t.sessionEnvKey]:n}}},f.debug(`[MCP] Configured ${c}`)}}_spawnWithStreaming(e,t,r,n,s=null,i=null,c=null,l=null){return new Promise((a,u)=>{let d=Date.now(),m="",p="",g=Date.now(),y=0,h=!1,b=null,w=!1,E=!1,S=null;if(i)try{S=re(Ps(String(i)),$s)}catch{S=null}let v=!1,k=()=>{v||(v=!0,Gr(c))},R={...process.env};c&&(R.HOME=c,process.platform==="win32"&&(R.USERPROFILE=c),f.debug(`[Agent] cursor-agent HOME=${c} (isolated MCP config)`));let C=Cs(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:R,...l&&{signal:l}});f.debug(`[Agent] PID: ${C.pid}`);let L=null,K=()=>{h||E||(h=!0,b="aborted",f.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),L=setTimeout(()=>{if(!E){f.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{C.kill("SIGKILL")}catch{}}},5e3))};l&&(l.aborted?K():l.addEventListener("abort",K,{once:!0})),C.stdin.on("error",x=>{x.code!=="EPIPE"&&f.warn(`[Agent] stdin error: ${x.message}`)}),C.stdout.on("error",x=>{x.code!=="EPIPE"&&f.warn(`[Agent] stdout error: ${x.message}`)}),C.stderr.on("error",x=>{x.code!=="EPIPE"&&f.warn(`[Agent] stderr error: ${x.message}`)}),s?(C.stdin.write(s,x=>{x&&x.code!=="EPIPE"&&f.warn(`[Agent] Failed to write to stdin: ${x.message}`),C.stdin.end()}),f.debug(`[Agent] Prompt also piped to stdin (${s.length} chars)`)):C.stdin.end();let P=null;S&&(P=setInterval(()=>{if(!(h||E))try{if(qe(S)){h=!0,b="aborted";try{ks(S)}catch{}f.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),C.kill("SIGTERM"),setTimeout(()=>{C.killed||C.kill("SIGKILL")},2e3)}}catch{}},600));let D=new Set,M=new Date(d).toISOString().replace(/\.\d+Z$/,""),$=setInterval(()=>{let x=Math.round((Date.now()-d)/1e3),_=Math.round((Date.now()-g)/1e3),I=[];try{let B=Math.ceil(x/60)+1,O=ye(`find "${r}" -type f -mmin -${B} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(O)for(let F of O.split(`
141
+ `)){let Y=F.replace(`${r}/`,"");D.has(Y)||(D.add(Y),I.push(Y))}}catch{}let T="";I.length>0&&(T=` | \u{1F4C1} new: ${I.map(O=>O.split("/").pop()).join(", ")}`),D.size>0&&(T+=` | \u{1F4E6} total: ${D.size} files`),f.debug(`\u{1F493} [Agent] Running for ${x}s | ${y} lines output${T}`),y===0&&x>=30&&D.size===0&&(x<35&&f.warn(`\u26A0\uFE0F [Agent] No output after ${x}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),x>=60&&(h=!0,b=b||"stall",f.error(`\u274C [Agent] No response after ${x}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),C.kill("SIGTERM"),setTimeout(()=>{C.killed||C.kill("SIGKILL")},3e3)))},3e4),j=setTimeout(()=>{h=!0,b=b||"timeout";let x=Math.round((Date.now()-d)/1e3);f.error(`\u23F1\uFE0F [Agent] Timeout after ${x}s \u2014 killing process (PID: ${C.pid})`),m.trim()&&f.warn(`\u{1F4E4} [Agent] Partial output (${m.length} chars) before timeout:
142
+ ${m.slice(-2e3)}`),C.kill("SIGTERM"),setTimeout(()=>{C.killed||C.kill("SIGKILL")},5e3)},n),N=new oe;N.onToolCall=(x,_)=>{let I=x,T=_;if(x==="mcpToolCall"&&_?.name)I=_.name.replace(/^mcp_+[^_]+_+/,""),I.includes("-")&&I.split("-")[0]===I.split("-")[1]&&(I=I.split("-")[0]),T=_.args??_.input??_;else{if(x==="readToolCall"||x==="editToolCall"||x==="writeToolCall")return;(x.startsWith("mcp__")||x.includes("ToolCall"))&&(I=x.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(I.includes("memory")?ne.stepMemory(`Tool: ${I}`):ne.stepTool(`Tool: ${I}`),T!=null&&typeof T=="object"&&Object.keys(T).length>0&&!E){let O=JSON.stringify(T),F=O.length>100?`${O.substring(0,100)}...`:O;console.log(` Input: ${F}`)}},C.stdout.on("data",x=>{let _=x.toString();m+=_,g=Date.now(),w||(w=!0);let I=N.processChunk(_);I&&!E&&process.stdout.write(I);let T=_.split(`
143
143
  `).filter(B=>B.trim());y+=T.length}),C.stderr.on("data",x=>{let _=x.toString();p+=_,g=Date.now(),w||(w=!0);let I=_.split(`
144
- `).filter(T=>T.trim());for(let T of I)f.warn(`\u26A0\uFE0F [Agent stderr] ${T}`)}),C.on("close",(x,_)=>{if(E=!0,k(),clearTimeout(j),clearInterval(O),P&&clearInterval(P),L&&clearTimeout(L),l&&!l.aborted)try{l.removeEventListener("abort",K)}catch{}N.flush();let I=Math.round((Date.now()-d)/1e3);if(f.debug(`[Agent] Exited: code=${x}, signal=${_}, elapsed=${I}s, output=${m.length} chars`),h){if(b==="aborted"){let $=new Error("Aborted via signal");$.name="AbortError",u($);return}u(new Error(`Cursor Agent timed out after ${I}s (limit: ${n/1e3}s). ${y} lines produced. Last output ${Math.round((Date.now()-g)/1e3)}s ago. ${m.trim()?`
144
+ `).filter(T=>T.trim());for(let T of I)f.warn(`\u26A0\uFE0F [Agent stderr] ${T}`)}),C.on("close",(x,_)=>{if(E=!0,k(),clearTimeout(j),clearInterval($),P&&clearInterval(P),L&&clearTimeout(L),l&&!l.aborted)try{l.removeEventListener("abort",K)}catch{}N.flush();let I=Math.round((Date.now()-d)/1e3);if(f.debug(`[Agent] Exited: code=${x}, signal=${_}, elapsed=${I}s, output=${m.length} chars`),h){if(b==="aborted"){let O=new Error("Aborted via signal");O.name="AbortError",u(O);return}u(new Error(`Cursor Agent timed out after ${I}s (limit: ${n/1e3}s). ${y} lines produced. Last output ${Math.round((Date.now()-g)/1e3)}s ago. ${m.trim()?`
145
145
  Partial output (last 500 chars):
146
146
  ${m.slice(-500)}`:"No output captured."}`));return}if(x!==0){u(new Error(`Cursor Agent failed: exit code ${x}, signal ${l}. ${p.trim()?`
147
147
  Stderr: ${p.slice(-1e3)}`:""}${m.trim()?`
148
- Stdout (last 500 chars): ${m.slice(-500)}`:""}`));return}let T=N.getResult(),B=T?JSON.stringify(T,null,2):N.getRawText()||m||"";a({stdout:m||p||"",parsedText:B})}),C.on("error",x=>{if(k(),clearTimeout(j),clearInterval(O),P&&clearInterval(P),L&&clearTimeout(L),l&&!l.aborted)try{l.removeEventListener("abort",K)}catch{}u(new Error(`Cursor Agent spawn error: ${x.message}
148
+ Stdout (last 500 chars): ${m.slice(-500)}`:""}`));return}let T=N.getResult(),B=T?JSON.stringify(T,null,2):N.getRawText()||m||"";a({stdout:m||p||"",parsedText:B})}),C.on("error",x=>{if(k(),clearTimeout(j),clearInterval($),P&&clearInterval(P),L&&clearTimeout(L),l&&!l.aborted)try{l.removeEventListener("abort",K)}catch{}u(new Error(`Cursor Agent spawn error: ${x.message}
149
149
  Binary: ${e}
150
150
  This usually means the binary is not in PATH. Try:
151
- echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};import{AgentStrategy as Ds}from"@zibby/agent-workflow";var rn=[new he,new pe,new fe,new me];function nn(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");f.debug(`Agent selection: requested=${r}`);let n=rn.find(s=>s.getName()===r);if(!n)throw new Error(`Unknown agent '${r}'. Available: ${rn.map(s=>s.getName()).join(", ")}`);if(f.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 f.debug(`Using agent: ${n.getName()}`),n}async function Ms(o,e={},t={}){try{await import("@zibby/skills")}catch{}try{await import("@zibby/skills-internal")}catch{}let r=nn(e),n=e.state?.config||t.config||{},s=n.models||{},i=t.nodeName&&s[t.nodeName]||null,c=s.default||null,l=r.name,a=n.agent?.[l]?.model||null,u=i||c||a||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||[],p=o;if(m.length>0&&!t.skipPromptFragments){let{getSkill:h}=await import("@zibby/agent-workflow"),b=null;try{let{getConnectedIntegrations:S}=await Promise.resolve().then(()=>(vt(),tn));b=await S()}catch{b=null}let w=S=>{let v=S&&S.requiresIntegration;return!v||!b?!0:(Array.isArray(v)?v:[v]).some(R=>b[R]===!0)},E=m.map(S=>{let v=h(S);if(!w(v))return null;let k=v?.promptFragment;return typeof k=="function"?k():k}).filter(Boolean);E.length>0&&(p+=`
151
+ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};import{AgentStrategy as Bs}from"@zibby/agent-workflow";var rn=[new he,new pe,new fe,new me];function nn(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");f.debug(`Agent selection: requested=${r}`);let n=rn.find(s=>s.getName()===r);if(!n)throw new Error(`Unknown agent '${r}'. Available: ${rn.map(s=>s.getName()).join(", ")}`);if(f.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 f.debug(`Using agent: ${n.getName()}`),n}async function js(o,e={},t={}){try{await import("@zibby/skills")}catch{}try{await import("@zibby/skills-internal")}catch{}let r=nn(e),n=e.state?.config||t.config||{},s=n.models||{},i=t.nodeName&&s[t.nodeName]||null,c=s.default||null,l=r.name,a=n.agent?.[l]?.model||null,u=i||c||a||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||[],p=o;if(m.length>0&&!t.skipPromptFragments){let{getSkill:h}=await import("@zibby/agent-workflow"),b=null;try{let{getConnectedIntegrations:S}=await Promise.resolve().then(()=>(vt(),tn));b=await S()}catch{b=null}let w=S=>{let v=S&&S.requiresIntegration;return!v||!b?!0:(Array.isArray(v)?v:[v]).some(R=>b[R]===!0)},E=m.map(S=>{let v=h(S);if(!w(v))return null;let k=v?.promptFragment;return typeof k=="function"?k():k}).filter(Boolean);E.length>0&&(p+=`
152
152
 
153
153
  ${E.join(`
154
154
 
@@ -165,13 +165,13 @@ ${b.join(`
165
165
 
166
166
  ${y}
167
167
  `),f.debug(`Prompt length: ${p.length} chars`),process.env.STAGE!=="prod"&&f.debug(`Full prompt:
168
- ${p}`),r.invoke(p,d)}import{SKILL_IDS as Wf}from"@zibby/skill-ids";import{registerSkill as Xf,getSkill as Qf,hasSkill as ed,getAllSkills as td,listSkillIds as rd}from"@zibby/agent-workflow";var Us={READ_FILE:"read_file",WRITE_FILE:"write_file",LIST_DIRECTORY:"list_directory",RUN_COMMAND:"run_command",OPEN_URL:"open_url",WAIT:"wait"},js={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"},Bs={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"},Fs={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"},Gs={GENERATE:"run_generate",TEST:"run_test",STATUS:"run_status",CANCEL:"run_cancel",WAIT:"run_wait",ARTIFACTS:"run_artifacts",LIST_SPECS:"list_specs"},Ks={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"},zs={STORE:"memory_store",RECALL:"memory_recall",BRIEF:"memory_brief",END_SESSION:"memory_end_session",TASK_LOG:"task_log",TASK_HISTORY:"task_history"},Js={INSTALL:"install_skill",UNINSTALL:"uninstall_skill",LIST_AVAILABLE:"list_available_skills"},iu={...Us,...js,...Bs,...Fs,...Gs,...Ks,...zs,...Js};vt();vt();var Ys=Object.freeze(["github.com","gitlab.com"]);function Zt(o){try{return new URL(o).hostname.toLowerCase()}catch{return""}}function Vt(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 on(o=process.env){let e=o&&(o.GITLAB_URL||o.GITLAB_INSTANCE_URL)||"";return Zt(e)}function $t(o={}){if(o.gitlabHost){let e=String(o.gitlabHost).trim().toLowerCase();return e?e.includes("://")?Zt(e):e.replace(/:\d+$/,""):""}return on()}function sn(o,e={}){let t=Vt(o);if(!t)return!1;if(t==="github.com"||t==="gitlab.com")return!0;let r=$t(e);return!!(r&&t===r)}function an(o,e={}){if(o==="github.com")return"github";if(o==="gitlab.com")return"gitlab";let t=$t(e);return t&&o===t?"gitlab":null}function ln(o,e,t={}){if(!o||!e)return o;let r=Vt(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=$t(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 cn(o){return o&&String(o).replace(/^(https:\/\/)[^@/]+@/i,"$1")}function un(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 Hs(o,e,t){try{await o("git",["remote","set-url","origin",cn(t)],e)}catch(r){console.warn(`\u26A0\uFE0F could not scrub token from origin remote (continuing): ${r?.message||r}`)}}async function Zs({run:o,repoPath:e,repoUrl:t,branch:r,token:n,resolveToken:s=At,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=$t({gitlabHost:i}),l=Vt(t),a=sn(t,{gitlabHost:c}),u=n||"";if(!u&&a&&typeof s=="function"){let g=an(l,{gitlabHost:c});if(g)try{u=(await s(g))?.token||""}catch{}}else!u&&!a&&console.warn(`\u26A0\uFE0F push target host '${l||"(unparseable)"}' is not a trusted VCS host \u2014 refusing to mint a token`);let d=u&&a,m=d?ln(t,u,{gitlabHost:c}):"origin",p=await o("git",["push",m,r],e);if(!p||p.code!==0){let g=un(p&&p.stderr||"",u);throw new Error(`git push failed (exit ${p?p.code:"?"}): ${String(g).slice(-500)}`)}return{code:p.code,stdout:p.stdout,stderr:p.stderr,pushedAuthed:!!d,target:d?"<authed>":"origin"}}import{readdir as Vs,access as pn,copyFile as Ws,constants as fn}from"fs/promises";import{join as Ot,relative as qs}from"node:path";async function Xs(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...
169
- `);let s=Ot(r,e),i=Ot(r,t);try{let c=await Vs(s),l=0;for(let a of c){if(a.startsWith("."))continue;let u=Ot(s,a,"video.webm");try{await pn(u,fn.F_OK)}catch{continue}let d=a.replace(/-chromium$/,"").replace(/-firefox$/,"").replace(/-webkit$/,""),m=await Qs(i,d);if(m){let p=m.replace(/\.spec\.(js|ts)$/,".spec.webm");await Ws(u,p),n&&console.log(`\u2705 ${qs(r,p)}`),l++}else n&&console.log(`\u26A0\uFE0F Could not find test file for: ${a}`)}return n&&(console.log(`
170
- \u{1F3AC} Organized ${l} video(s)`),console.log(`\u{1F4C2} Videos are now next to their test files in ${t}/`)),{movedCount:l,success:!0}}catch(c){return n&&console.error("\u274C Error organizing videos:",c.message),{movedCount:0,success:!1,error:c.message}}}async function Qs(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=Ot(o,`${s}.spec.${i}`);try{return await pn(c,fn.F_OK),c}catch{}}}return null}var Qe=class{constructor(e,t={}){this.apiKey=e,this.baseUrl=t.baseUrl||process.env.ZIBBY_API_URL||"https://api-prod.zibby.app",this.enabled=!!e}isEnabled(){return this.enabled}};function dn(){let o=process.env.ZIBBY_API_KEY;return new Qe(o)}import{execSync as gn}from"node:child_process";import{existsSync as ei,mkdirSync as ti}from"node:fs";import{join as ri}from"node:path";function mn(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 ni(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(a){throw new Error(`Failed to parse REPOS env var: ${a.message}`,{cause:a})}if(!Array.isArray(i)||i.length===0)throw new Error("No repositories configured for this project");let c=t?i.filter(a=>t.includes(a.name)):i;if(c.length===0)throw new Error(`No matching repositories found. Available: ${i.map(a=>a.name).join(", ")}`);ei(e)||ti(e,{recursive:!0});let l={};return await Promise.all(c.map(async a=>{let u=a.provider||"github",d=u==="gitlab"?process.env.GITLAB_TOKEN:process.env.GITHUB_TOKEN;if(!d){console.error(`${u.toUpperCase()}_TOKEN not set, skipping ${a.name}`),l[a.name]=null;return}let m=a.name.replace(/\//g,"-"),p=ri(e,m),g=a.cloneUrl||a.url;if(!g){console.error(`Repository "${a.name}" has no clone URL`),l[a.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,p);let b=`git ${h.join(" ")}`;console.log(`Cloning ${a.name} (${u}) to ${p}...`);try{gn(b,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),mn(gn,p,g,d,`cloneRepo:${a.name}`),console.log(`Repository ${a.name} cloned successfully`),l[a.name]=p}catch(w){let E=w.message.replace(d,"***").replace(y,g);console.error(`Failed to clone ${a.name}: ${E}`),l[a.name]=null}})),l}var hn=/^(?:[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 oi(o){return typeof o=="string"&&hn.test(o)}var yn=oi;function si(o){if(!yn(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 Wt=si;var Z=[];for(let o=0;o<256;++o)Z.push((o+256).toString(16).slice(1));function bn(o,e=0){return(Z[o[e+0]]+Z[o[e+1]]+Z[o[e+2]]+Z[o[e+3]]+"-"+Z[o[e+4]]+Z[o[e+5]]+"-"+Z[o[e+6]]+Z[o[e+7]]+"-"+Z[o[e+8]]+Z[o[e+9]]+"-"+Z[o[e+10]]+Z[o[e+11]]+Z[o[e+12]]+Z[o[e+13]]+Z[o[e+14]]+Z[o[e+15]]).toLowerCase()}function ii(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 Sn="6ba7b810-9dad-11d1-80b4-00c04fd430c8",_n="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function qt(o,e,t,r,n,s){let i=typeof t=="string"?ii(t):t,c=typeof r=="string"?Wt(r):r;if(typeof r=="string"&&(r=Wt(r)),r?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+i.length);if(l.set(c),l.set(i,c.length),l=e(l),l[6]=l[6]&15|o,l[8]=l[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 a=0;a<16;++a)n[s+a]=l[a];return n}return bn(l)}import{createHash as ai}from"crypto";function li(o){return Array.isArray(o)?o=Buffer.from(o):typeof o=="string"&&(o=Buffer.from(o,"utf8")),ai("sha1").update(o).digest()}var wn=li;function Xt(o,e,t,r){return qt(80,wn,o,e,t,r)}Xt.DNS=Sn;Xt.URL=_n;var Qt=Xt;var xn="@zibby/core ZibbySessionStore/1",et=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":xn},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":xn}})}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 ci="6ba7b810-9dad-11d1-80b4-00c04fd430c8",En=new Set;function ui(){return(process.env.PROGRESS_API_URL||process.env.ZIBBY_API_BASE||"").replace(/\/executions\/?$/,"").replace(/\/+$/,"")}function Tn({namespace:o=ci}={}){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 En.has(s)||(console.warn(`[SKILLS.SESSION] agent type '${s}' does not support native sessions \u2014 node running stateless`),En.add(s)),null;let i=Qt(`${n}:${r}`,o),c=ui(),l=process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN,a=null;if(c&&l)try{a=new et({apiUrl:c,apiKey:l,workflowUuid:n})}catch(m){console.warn(`[SKILLS.SESSION] failed to build SessionStore: ${m.message}`),a=null}return e.resetConversation?{sessionId:i,resume:i,forkSession:!0,...a&&{sessionStore:a}}:e.hasPriorSession?{resume:i,...a&&{sessionStore:a}}:{sessionId:i,...a&&{sessionStore:a}}}}}import{spawn as An}from"node:child_process";import{readFileSync as pi,writeFileSync as fi,existsSync as It}from"node:fs";import{homedir as vn}from"node:os";import{join as Le}from"node:path";async function di(){let o=Le(vn(),".local/share/cursor-agent/versions");if(!It(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...
171
- `),new Promise((e,t)=>{let r=Le(__dirname,"../../scripts/patch-cursor-mcp.py");if(!It(r)){t(new Error("Patch script not found"));return}let n=An("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 mi(){let o=Le(vn(),".local/share/cursor-agent/versions");if(!It(o))return{patched:!1,installed:!1};try{let e=Yn("fs").readdirSync(o);if(e.length===0)return{patched:!1,installed:!1};let t=e.sort().reverse()[0],r=Le(o,t,"index.js");return It(r)?{patched:pi(r,"utf-8").includes("AUTO-APPROVE MCP TOOLS FOR CI/CD"),installed:!0,path:r}:{patched:!1,installed:!1}}catch(e){return{patched:!1,installed:!1,error:e.message}}}async function gi(o){return console.log(`\u{1F511} Getting MCP approval keys...
172
- `),new Promise((e,t)=>{let r=An("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=hi(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 hi(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 yi(o,e){let t=Le(o,".cursor/projects"),r=Le(t,"mcp-approvals.json");fi(r,JSON.stringify(e,null,2)),console.log(`
168
+ ${p}`),r.invoke(p,d)}import{SKILL_IDS as Qf}from"@zibby/skill-ids";import{registerSkill as td,getSkill as rd,hasSkill as nd,getAllSkills as od,listSkillIds as sd}from"@zibby/agent-workflow";var Fs={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"},Ks={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"},zs={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"},Js={GENERATE:"run_generate",TEST:"run_test",STATUS:"run_status",CANCEL:"run_cancel",WAIT:"run_wait",ARTIFACTS:"run_artifacts",LIST_SPECS:"list_specs"},Ys={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"},Hs={STORE:"memory_store",RECALL:"memory_recall",BRIEF:"memory_brief",END_SESSION:"memory_end_session",TASK_LOG:"task_log",TASK_HISTORY:"task_history"},Zs={INSTALL:"install_skill",UNINSTALL:"uninstall_skill",LIST_AVAILABLE:"list_available_skills"},cu={...Fs,...Gs,...Ks,...zs,...Js,...Ys,...Hs,...Zs};vt();vt();var Ws=Object.freeze(["github.com","gitlab.com"]);function Zt(o){try{return new URL(o).hostname.toLowerCase()}catch{return""}}function Wt(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 on(o=process.env){let e=o&&(o.GITLAB_URL||o.GITLAB_INSTANCE_URL)||"";return Zt(e)}function Ot(o={}){if(o.gitlabHost){let e=String(o.gitlabHost).trim().toLowerCase();return e?e.includes("://")?Zt(e):e.replace(/:\d+$/,""):""}return on()}function sn(o,e={}){let t=Wt(o);if(!t)return!1;if(t==="github.com"||t==="gitlab.com")return!0;let r=Ot(e);return!!(r&&t===r)}function an(o,e={}){if(o==="github.com")return"github";if(o==="gitlab.com")return"gitlab";let t=Ot(e);return t&&o===t?"gitlab":null}function ln(o,e,t={}){if(!o||!e)return o;let r=Wt(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=Ot(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 cn(o){return o&&String(o).replace(/^(https:\/\/)[^@/]+@/i,"$1")}function un(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 Vs(o,e,t){try{await o("git",["remote","set-url","origin",cn(t)],e)}catch(r){console.warn(`\u26A0\uFE0F could not scrub token from origin remote (continuing): ${r?.message||r}`)}}async function qs({run:o,repoPath:e,repoUrl:t,branch:r,token:n,resolveToken:s=At,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=Ot({gitlabHost:i}),l=Wt(t),a=sn(t,{gitlabHost:c}),u=n||"";if(!u&&a&&typeof s=="function"){let g=an(l,{gitlabHost:c});if(g)try{u=(await s(g))?.token||""}catch{}}else!u&&!a&&console.warn(`\u26A0\uFE0F push target host '${l||"(unparseable)"}' is not a trusted VCS host \u2014 refusing to mint a token`);let d=u&&a,m=d?ln(t,u,{gitlabHost:c}):"origin",p=await o("git",["push",m,r],e);if(!p||p.code!==0){let g=un(p&&p.stderr||"",u);throw new Error(`git push failed (exit ${p?p.code:"?"}): ${String(g).slice(-500)}`)}return{code:p.code,stdout:p.stdout,stderr:p.stderr,pushedAuthed:!!d,target:d?"<authed>":"origin"}}import{readdir as Xs,access as pn,copyFile as Qs,constants as fn}from"fs/promises";import{join as $t,relative as ei}from"node:path";async function ti(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...
169
+ `);let s=$t(r,e),i=$t(r,t);try{let c=await Xs(s),l=0;for(let a of c){if(a.startsWith("."))continue;let u=$t(s,a,"video.webm");try{await pn(u,fn.F_OK)}catch{continue}let d=a.replace(/-chromium$/,"").replace(/-firefox$/,"").replace(/-webkit$/,""),m=await ri(i,d);if(m){let p=m.replace(/\.spec\.(js|ts)$/,".spec.webm");await Qs(u,p),n&&console.log(`\u2705 ${ei(r,p)}`),l++}else n&&console.log(`\u26A0\uFE0F Could not find test file for: ${a}`)}return n&&(console.log(`
170
+ \u{1F3AC} Organized ${l} video(s)`),console.log(`\u{1F4C2} Videos are now next to their test files in ${t}/`)),{movedCount:l,success:!0}}catch(c){return n&&console.error("\u274C Error organizing videos:",c.message),{movedCount:0,success:!1,error:c.message}}}async function ri(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=$t(o,`${s}.spec.${i}`);try{return await pn(c,fn.F_OK),c}catch{}}}return null}var Qe=class{constructor(e,t={}){this.apiKey=e,this.baseUrl=t.baseUrl||process.env.ZIBBY_API_URL||"https://api-prod.zibby.app",this.enabled=!!e}isEnabled(){return this.enabled}};function dn(){let o=process.env.ZIBBY_API_KEY;return new Qe(o)}import{execSync as gn}from"node:child_process";import{existsSync as ni,mkdirSync as oi}from"node:fs";import{join as si}from"node:path";function mn(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 ii(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(a){throw new Error(`Failed to parse REPOS env var: ${a.message}`,{cause:a})}if(!Array.isArray(i)||i.length===0)throw new Error("No repositories configured for this project");let c=t?i.filter(a=>t.includes(a.name)):i;if(c.length===0)throw new Error(`No matching repositories found. Available: ${i.map(a=>a.name).join(", ")}`);ni(e)||oi(e,{recursive:!0});let l={};return await Promise.all(c.map(async a=>{let u=a.provider||"github",d=u==="gitlab"?process.env.GITLAB_TOKEN:process.env.GITHUB_TOKEN;if(!d){console.error(`${u.toUpperCase()}_TOKEN not set, skipping ${a.name}`),l[a.name]=null;return}let m=a.name.replace(/\//g,"-"),p=si(e,m),g=a.cloneUrl||a.url;if(!g){console.error(`Repository "${a.name}" has no clone URL`),l[a.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,p);let b=`git ${h.join(" ")}`;console.log(`Cloning ${a.name} (${u}) to ${p}...`);try{gn(b,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),mn(gn,p,g,d,`cloneRepo:${a.name}`),console.log(`Repository ${a.name} cloned successfully`),l[a.name]=p}catch(w){let E=w.message.replace(d,"***").replace(y,g);console.error(`Failed to clone ${a.name}: ${E}`),l[a.name]=null}})),l}var hn=/^(?:[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 ai(o){return typeof o=="string"&&hn.test(o)}var yn=ai;function li(o){if(!yn(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 Vt=li;var Z=[];for(let o=0;o<256;++o)Z.push((o+256).toString(16).slice(1));function bn(o,e=0){return(Z[o[e+0]]+Z[o[e+1]]+Z[o[e+2]]+Z[o[e+3]]+"-"+Z[o[e+4]]+Z[o[e+5]]+"-"+Z[o[e+6]]+Z[o[e+7]]+"-"+Z[o[e+8]]+Z[o[e+9]]+"-"+Z[o[e+10]]+Z[o[e+11]]+Z[o[e+12]]+Z[o[e+13]]+Z[o[e+14]]+Z[o[e+15]]).toLowerCase()}function ci(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 Sn="6ba7b810-9dad-11d1-80b4-00c04fd430c8",_n="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function qt(o,e,t,r,n,s){let i=typeof t=="string"?ci(t):t,c=typeof r=="string"?Vt(r):r;if(typeof r=="string"&&(r=Vt(r)),r?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+i.length);if(l.set(c),l.set(i,c.length),l=e(l),l[6]=l[6]&15|o,l[8]=l[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 a=0;a<16;++a)n[s+a]=l[a];return n}return bn(l)}import{createHash as ui}from"crypto";function pi(o){return Array.isArray(o)?o=Buffer.from(o):typeof o=="string"&&(o=Buffer.from(o,"utf8")),ui("sha1").update(o).digest()}var wn=pi;function Xt(o,e,t,r){return qt(80,wn,o,e,t,r)}Xt.DNS=Sn;Xt.URL=_n;var Qt=Xt;var xn="@zibby/core ZibbySessionStore/1",et=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":xn},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":xn}})}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 fi="6ba7b810-9dad-11d1-80b4-00c04fd430c8",En=new Set;function di(){return(process.env.PROGRESS_API_URL||process.env.ZIBBY_API_BASE||"").replace(/\/executions\/?$/,"").replace(/\/+$/,"")}function Tn({namespace:o=fi}={}){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 En.has(s)||(console.warn(`[SKILLS.SESSION] agent type '${s}' does not support native sessions \u2014 node running stateless`),En.add(s)),null;let i=Qt(`${n}:${r}`,o),c=di(),l=process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN,a=null;if(c&&l)try{a=new et({apiUrl:c,apiKey:l,workflowUuid:n})}catch(m){console.warn(`[SKILLS.SESSION] failed to build SessionStore: ${m.message}`),a=null}return e.resetConversation?{sessionId:i,resume:i,forkSession:!0,...a&&{sessionStore:a}}:e.hasPriorSession?{resume:i,...a&&{sessionStore:a}}:{sessionId:i,...a&&{sessionStore:a}}}}}import{spawn as An}from"node:child_process";import{readFileSync as mi,writeFileSync as gi,existsSync as It}from"node:fs";import{homedir as vn}from"node:os";import{join as Le}from"node:path";async function hi(){let o=Le(vn(),".local/share/cursor-agent/versions");if(!It(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...
171
+ `),new Promise((e,t)=>{let r=Le(__dirname,"../../scripts/patch-cursor-mcp.py");if(!It(r)){t(new Error("Patch script not found"));return}let n=An("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 yi(){let o=Le(vn(),".local/share/cursor-agent/versions");if(!It(o))return{patched:!1,installed:!1};try{let e=Yn("fs").readdirSync(o);if(e.length===0)return{patched:!1,installed:!1};let t=e.sort().reverse()[0],r=Le(o,t,"index.js");return It(r)?{patched:mi(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 bi(o){return console.log(`\u{1F511} Getting MCP approval keys...
172
+ `),new Promise((e,t)=>{let r=An("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=Si(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 Si(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 _i(o,e){let t=Le(o,".cursor/projects"),r=Le(t,"mcp-approvals.json");gi(r,JSON.stringify(e,null,2)),console.log(`
173
173
  \u2705 Saved approval keys to: ${r}
174
- `)}import{DEFAULT_OUTPUT_BASE as gd,SESSIONS_DIR as hd,SESSION_INFO_FILE as yd,RESULT_FILE as bd,RAW_OUTPUT_FILE as Sd,EVENTS_FILE as _d,CI_ENV_VARS as wd}from"@zibby/agent-workflow";var $n=`
174
+ `)}import{DEFAULT_OUTPUT_BASE as bd,SESSIONS_DIR as Sd,SESSION_INFO_FILE as _d,RESULT_FILE as wd,RAW_OUTPUT_FILE as xd,EVENTS_FILE as Ed,CI_ENV_VARS as Td}from"@zibby/agent-workflow";var On=`
175
175
  const style = document.createElement('style');
176
176
  style.textContent = \`
177
177
  @keyframes zibby-ripple {
@@ -232,7 +232,7 @@ ${p}`),r.invoke(p,d)}import{SKILL_IDS as Wf}from"@zibby/skill-ids";import{regist
232
232
  setTimeout(() => ripple.remove(), 600);
233
233
  }
234
234
  };
235
- `;function bi(o){return o.addInitScript($n)}function Si(){return`
235
+ `;function wi(o){return o.addInitScript(On)}function xi(){return`
236
236
  async function showRipple(page, locator) {
237
237
  const box = await locator.boundingBox().catch(() => null);
238
238
  if (box) {
@@ -265,12 +265,12 @@ import { test, expect } from '@playwright/test';
265
265
  `,u++}a+=`});
266
266
  `;let{dirname:d}=await import("path"),{mkdirSync:m}=await import("fs");return m(d(e),{recursive:!0}),await rt.writeFile(e,a,"utf-8"),console.log(`[TestPostProcessor] \u2705 Generated test with ${i.filter(p=>["type","fill","click","select_option"].includes(p.type)).length} actions`),!0}catch(s){return console.warn("[TestPostProcessor] Failed to generate from events:",s.message),!1}}static async enhanceSelectorsWithTrace(e,t,r){try{console.log("[TestPostProcessor] \u{1F6E1}\uFE0F Applying Zibby Safe Action Wrappers...");let n=await rt.readFile(e,"utf-8");n.includes("ZibbyRuntime")||(n=`import { ZibbyRuntime } from '@zibby/core';
267
267
  ${n}`);for(let s=0;s<t.length;s++){let i=t[s],c=`element${s}`,l=new RegExp(`const ${c}\\b\\s*=\\s*page\\.[^;]+;(\\s*await ${c}\\.waitFor\\([^)]*\\);)?\\s*await ${c}\\.(click|fill|type|selectOption|pressSequentially)\\(([^)]*)\\);`,"s"),a=n.match(l);if(!a)continue;let u={name:i.name||`Action ${s}`,action:i.method==="type"?"fill":i.method,value:a[3].trim().replace(/^['"]|['"]$/g,""),strategies:i.strategies||[]},d=`await ZibbyRuntime.step(page, ${JSON.stringify(u,null,2)});`;n=n.replace(a[0],d)}return await rt.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 rt.readFile(e,"utf-8"),s=this.buildSelectorMap(r);return n=this.replaceSimpleSelectors(n,s),await rt.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=tt.generate(n,s).match(/= (.+);/s);if(c){let l=c[1].trim(),a=`${n.type}:${this.normalizeDescription(n.description)}`;t.set(a,l),n.selectors.role&&t.set(`role:${n.selectors.role.name}`,l),n.selectors.attributes?.placeholder&&t.set(`placeholder:${n.selectors.attributes.placeholder}`,l)}}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,l]of t.entries())if(i.includes(c.split(":")[1])){let a=i.match(/\.(fill|click|type)\(([^)]*)\)/);if(a){let[,u,d]=a,m="element";return`const ${m} = ${l};
268
- await ${m}.${u}(${d})`}}return i});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as _i,existsSync as On,readdirSync as In}from"node:fs";import{join as tr}from"node:path";import{execSync as wi}from"node:child_process";import{tmpdir as xi}from"node:os";var nt=class{static async parseTraceZip(e){let t;if(e.endsWith(".zip")&&On(e)){let r=tr(xi(),`trace-${Date.now()}`);wi(`unzip -q "${e}" -d "${r}"`,{stdio:"pipe"});let s=In(r).find(i=>i.endsWith(".trace"));if(!s)throw new Error("No .trace file found in zip");t=tr(r,s)}else if(On(e)){let n=In(e).find(s=>s.endsWith(".trace"));if(!n)throw new Error("No .trace file found");t=tr(e,n)}else throw new Error(`Trace not found at ${e}`);try{let n=_i(t,"utf-8").trim().split(`
269
- `),s=[],i=new Map,c=new Map;for(let l of n)try{let a=JSON.parse(l);if(a.type==="snapshot"&&a.snapshot&&a.snapshot.accessibility){let u=new Map;for(let d of a.snapshot.accessibility)d.ref&&u.set(d.ref,d);i.set(a.snapshotName,u)}if(a.type==="frame-snapshot"&&a.snapshot){let u=Buffer.from(a.snapshot.html||"","base64").toString("utf-8");u&&u.length>100&&c.set(a.pageId||"default",u)}}catch{}for(let l of n)try{let a=JSON.parse(l);if(a.type==="before"&&a.params&&a.params.selector){let u=a.method;if(["click","fill","type","selectOption"].includes(u)){let d=a.params.selector,m=a.params.text||a.params.value||"",p=[],g=null,y=null,h=null,b=d.match(/aria-ref=([a-z0-9]+)/i);if(b&&a.snapshotName){let P=b[1],D=i.get(a.snapshotName);if(D&&D.has(P)){let M=D.get(P);g=M.name||null,y=M.role||null,h=M.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),v=d.match(/internal:role=([^ ]+)/i),k=d.match(/internal:describe="([^"]+)"/i),R=d.match(/name="([^"]+)"/i);if(w){p.push({type:"text",text:w[1]});let P=w[1].split(" ");P.length>1&&(p.push({type:"text",text:P[0],fuzzy:!0}),p.push({type:"text",text:P[P.length-1],fuzzy:!0}))}if(E&&p.push({type:"label",label:E[1]}),S&&p.push({type:"placeholder",placeholder:S[1]}),g){p.unshift({type:"text",text:g,source:"accessibility-tree"});let P=g.split(" ");P.length>1&&p.push({type:"text",text:P[0],fuzzy:!0,source:"accessibility-tree"})}if(y||v){let P=y||v[1],D=g||(R?R[1]:w?w[1]:null);p.unshift({type:"role",role:P,name:D,source:g?"accessibility-tree":"selector"})}if(h&&p.unshift({type:"label",label:h,source:"accessibility-tree"}),k){let P=k[1],D=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],M=null,O=P;for(let j of D)if(P.toLowerCase().endsWith(` ${j}`)){M=j.replace(" ",""),O=P.substring(0,P.length-j.length-1);break}if(M){p.push({type:"role",role:M,name:O});let j=O.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:j}),p.push({type:"text",text:O});let N=O.split(" ");N.length>1&&(p.push({type:"text",text:N[0],fuzzy:!0}),p.push({type:"text",text:N.slice(0,2).join(" "),fuzzy:!0}))}else{let j=P.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:j}),p.push({type:"text",text:P})}}let C=this.extractDOMStrategies(d,c,w?.[1]||k?.[1],a.pageId);p.push(...C);let L=this.extractStructuralContext(d);(L.parent||L.sibling)&&p.forEach(P=>{["role","text","label","testid"].includes(P.type)&&(L.parent&&(P.parent=L.parent),L.sibling&&(P.sibling=L.sibling))}),p.push({type:"css",value:d});let K=g||w?w[1]:k?k[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${s.length}`;s.push({method:u,name:K,action:u==="type"?"fill":u,value:m,strategies:p,timestamp:a.startTime,actualText:g,actualRole:y,actualAriaLabel:h})}}}catch{}return s}catch(r){throw new Error(`Failed to parse trace: ${r.message}`,{cause:r})}}static extractDOMStrategies(e,t,r,n){let s=[];if(!t||t.size===0||!r)return s;try{let i=t.get(n);if(!i)return s;let c=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),a=i.match(l);a&&s.push({type:"testid",value:a[1],priority:"high"});let u=new RegExp(`class=["']([^"']+)["'][^>]*>[^<]*${c}`,"gi"),d=i.matchAll(u);for(let g of d){let y=g[1].split(/\s+/).filter(h=>h&&!h.match(/^(css|jss|makeStyles|MuiBox|MuiStack)-\w+/)&&h.length>2);y.length>0&&(s.push({type:"class",value:y.join("."),priority:"medium"}),y.length===1&&s.push({type:"class",value:y[0],priority:"medium"}))}let m=new RegExp(`id=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),p=i.match(m);p&&!p[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&s.push({type:"id",value:p[1],priority:"high"})}catch(i){console.warn(`[TraceParser] DOM extraction failed: ${i.message}`)}return s}static extractStructuralContext(e){let t={parent:null,sibling:null},r=e.split(">>").map(i=>i.trim());if(r.length>1){let c=r[r.length-2].replace(/internal:text="[^"]+"\s*/gi,"").replace(/internal:role=\S+\s*/gi,"").replace(/internal:label="[^"]+"\s*/gi,"").trim();c&&(c.match(/^(form|section|nav|header|aside|main|article)\b/)||c.includes("[")||c.match(/[#.]\w/))&&(t.parent=c)}let s=r[r.length-1].match(/([^+~]+)\s*[+~]\s*(.+)/);return s&&(t.sibling=s[1].trim()),t}};var rr=class{static async step(e,t){let{name:r,action:n,value:s,strategies:i,options:c={timeout:1e4},enrichedData:l}=t;console.log(`[Zibby] \u26A1 Executing step: ${r}`),await this.waitForPageStability(e,c.timeout);let a=await this.findBestMatch(e,i,r);if(!a)throw new Error(`[Zibby] \u274C Failed to find "${r}" using ${i.length} strategies`);l?.position&&await this.verifyPosition(a,l.position),await this.performActionWithRetry(e,a,n,s,3),console.log(`[Zibby] \u2728 Step "${r}" completed.`)}static async waitForPageStability(e,t=1e4){try{await e.waitForLoadState("networkidle",{timeout:3e3}).catch(()=>{}),await e.evaluate(()=>new Promise(r=>{let n,s=new MutationObserver(()=>{clearTimeout(n),n=setTimeout(()=>{s.disconnect(),r()},500)});s.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),n=setTimeout(()=>{s.disconnect(),r()},500)})).catch(()=>{})}catch{}}static async verifyPosition(e,t){try{let r=await e.boundingBox();if(!r)return;let n=Math.abs(r.x-t.x),s=Math.abs(r.y-t.y);(n>50||s>50)&&(console.log(`[Zibby] \u26A0\uFE0F Element moved: expected (${t.x}, ${t.y}), got (${r.x}, ${r.y})`),await new Promise(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(l=>setTimeout(l,1e3*i))}}static async findBestMatch(e,t,r){let s=Date.now(),i=t.map(async(a,u)=>{try{let m=await this.getLocator(e,a).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,a,e);return{element:g,strategy:a,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((a,u)=>u.score-a.score);let l=c[0];return console.log(`[Zibby] \u2705 Found element using ${l.strategy.type} (score: ${l.score.toFixed(2)}, ${c.length} candidates)`),l.element}static async scoreCandidate(e,t,r){let 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((l,a)=>l.matches(a),t.parent)&&(n+=30)}catch{}if(t.sibling)try{await e.evaluate((c,l)=>c.parentElement?.querySelector(l)!==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 l=0,a=c;for(;a;)a.tagName==="IFRAME"&&l++,a=a.parentElement;return l});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 nr=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(l){if(l.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(l){if(l.getAttribute("aria-label"))return l.getAttribute("aria-label").trim();let a=l.getAttribute("aria-labelledby");if(a){let m=document.getElementById(a);if(m)return m.textContent.trim()}if(l.id){let m=document.querySelector(`label[for="${l.id}"]`);if(m)return m.textContent.trim()}let u=l.closest("label");if(u){let m=u.cloneNode(!0);m.querySelectorAll("input, select, textarea").forEach(g=>g.remove());let p=m.textContent.trim();if(p)return p}if(l.placeholder)return l.placeholder;let d=l.tagName.toLowerCase();return d==="button"||d==="a"||l.getAttribute("role")==="button"?(l.textContent||"").trim().slice(0,50):l.title?l.title:d==="input"&&(l.type==="submit"||l.type==="button")&&l.value||""}function r(l){let a=[],u=l.closest("form");if(u)if(u.id)a.push(`form#${u.id}`);else if(u.name)a.push(`form[name=${u.name}]`);else if(u.action)try{let y=new URL(u.action,window.location.origin).pathname;a.push(`form[action=${y}]`)}catch{a.push(`form[action=${u.getAttribute("action")}]`)}else{let y=document.querySelectorAll("form"),h=Array.from(y).indexOf(u);a.push(`form:nth(${h})`)}let d=l.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");a.push(h||y)}let m=l.closest('section, article, [role="region"]');if(m){let y=m.querySelector("h1, h2, h3, h4, h5, h6");y&&a.push(`section:${y.textContent.trim().slice(0,30)}`)}let p=l.closest("fieldset");if(p){let y=p.querySelector("legend");y&&a.push(`fieldset:${y.textContent.trim()}`)}let g=l.closest('dialog, [role="dialog"], [role="alertdialog"]');if(g){let y=g.querySelector('[role="heading"], h1, h2, h3');y?a.push(`dialog:${y.textContent.trim().slice(0,30)}`):a.push("dialog")}return a.join("/")}function n(l){let a=l.tagName.toLowerCase(),u=l.id||"",d=l.name||"",m=l.type||"",p=l.getAttribute("role")||"",g="";if(l.href)try{g=new URL(l.href,window.location.origin).pathname.slice(0,50)}catch{g=l.getAttribute("href")?.slice(0,50)||""}let y=t(l).slice(0,50).replace(/\s+/g," "),h=r(l),b=[a,u,d,m,p,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(l=>{let a=window.getComputedStyle(l);if(a.display==="none"||a.visibility==="hidden")return;let u=n(l),d=u,m=i.get(d)||0;m>0&&(u=`${d}-${m}`),i.set(d,m+1),l.setAttribute("data-zibby-id",u),c++}),console.log(`[Zibby] Injected ${c} stable IDs`)})}catch{}}};var Ei=8,Ti=1,Ai=64;function vi(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 Oi,writeFileSync as kn,existsSync as Ii}from"node:fs";import{join as Pn}from"node:path";var W=class{constructor(e={}){this.config=e,this.enabled=e.enabled!==!1,this.priority=e.priority||50}getName(){throw new Error("EventEnricher.getName() must be implemented")}canEnrich(e){return this.enabled}async enrich(e,t){throw new Error("EventEnricher.enrich() must be implemented")}handleError(e,t){return console.warn(`[${this.getName()}] Enrichment failed for event ${t.type}:`,e.message),null}};import{existsSync as $i}from"node:fs";import{join as Cn}from"node:path";var be=class extends W{constructor(e={}){super(e),this.priority=190,this.traceData=null}getName(){return"TraceText"}getPriority(){return this.priority}async loadTrace(e){if(this.traceData)return;let t=Cn(e,"traces"),r=Cn(e,"trace.zip");if($i(r))try{this.traceData=await nt.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,l=s.actualAriaLabel;return i||c||l?(console.log(`[TraceTextEnricher] \u2705 Event ${n}: text="${i}", role="${c}", label="${l}"`),{traceActualText:i,traceActualRole:c,traceActualAriaLabel:l,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 Ci(o){let e=Pn(o,"events.json"),t=Pn(o,"events-enriched.json");if(!Ii(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(Oi(e,"utf-8")),n=new be,s=0,i=0;for(let c of r)try{let l=await n.enrich(c,{sessionPath:o});l&&(c.enrichedData={...c.enrichedData||{},...l},s++)}catch(l){console.log(`[PostProcess] Failed to enrich event ${c.id}: ${l.message}`),i++}return s>0&&(kn(t,JSON.stringify(r,null,2)),kn(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 ki}from"node:child_process";import{existsSync as Pi}from"node:fs";import{dirname as Ni,resolve as Nn,relative as Ri}from"node:path";var Ct=new Map,ot=8,Rn={name:"run_playwright_test",description:`Run a Playwright test file and return results. Use this after writing a test to verify it works. If it fails, fix the issues and run again. Maximum ${ot} attempts per session.`,inputSchema:{type:"object",properties:{scriptPath:{type:"string",description:"Path to the Playwright test file (e.g., tests/login.spec.js)"}},required:["scriptPath"]},async execute({scriptPath:o},e){let r=`${e?.sessionId||"default"}:${o}`,n=(Ct.get(r)||0)+1;if(Ct.set(r,n),n>ot)return{success:!1,executionCount:n,maxReached:!0,error:`Maximum ${ot} executions reached. Stop retrying and return your best result.`};let s=e?.projectRoot||process.cwd(),i=Nn(s,o),c=Ri(s,i);return c.startsWith("..")||Nn(i)!==i&&c.includes("..")?{success:!1,executionCount:n,error:"Path traversal detected: scriptPath must be within the project root."}:Pi(i)?new Promise(l=>{let a=Ni(i),u=ki("npx",["playwright","test",i,"--reporter=line"],{cwd:s,env:{...process.env,FORCE_COLOR:"0"}}),d="",m="";u.stdout.on("data",g=>{d+=g.toString()}),u.stderr.on("data",g=>{m+=g.toString()});let p=setTimeout(()=>{u.kill("SIGTERM"),l({success:!1,executionCount:n,error:"Test timed out after 60 seconds",stdout:d.slice(-2e3),stderr:m.slice(-1e3)})},6e4);u.on("close",g=>{clearTimeout(p);let h=`${d}
268
+ await ${m}.${u}(${d})`}}return i});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as Ei,existsSync as $n,readdirSync as In}from"node:fs";import{join as tr}from"node:path";import{execSync as Ti}from"node:child_process";import{tmpdir as Ai}from"node:os";var nt=class{static async parseTraceZip(e){let t;if(e.endsWith(".zip")&&$n(e)){let r=tr(Ai(),`trace-${Date.now()}`);Ti(`unzip -q "${e}" -d "${r}"`,{stdio:"pipe"});let s=In(r).find(i=>i.endsWith(".trace"));if(!s)throw new Error("No .trace file found in zip");t=tr(r,s)}else if($n(e)){let n=In(e).find(s=>s.endsWith(".trace"));if(!n)throw new Error("No .trace file found");t=tr(e,n)}else throw new Error(`Trace not found at ${e}`);try{let n=Ei(t,"utf-8").trim().split(`
269
+ `),s=[],i=new Map,c=new Map;for(let l of n)try{let a=JSON.parse(l);if(a.type==="snapshot"&&a.snapshot&&a.snapshot.accessibility){let u=new Map;for(let d of a.snapshot.accessibility)d.ref&&u.set(d.ref,d);i.set(a.snapshotName,u)}if(a.type==="frame-snapshot"&&a.snapshot){let u=Buffer.from(a.snapshot.html||"","base64").toString("utf-8");u&&u.length>100&&c.set(a.pageId||"default",u)}}catch{}for(let l of n)try{let a=JSON.parse(l);if(a.type==="before"&&a.params&&a.params.selector){let u=a.method;if(["click","fill","type","selectOption"].includes(u)){let d=a.params.selector,m=a.params.text||a.params.value||"",p=[],g=null,y=null,h=null,b=d.match(/aria-ref=([a-z0-9]+)/i);if(b&&a.snapshotName){let P=b[1],D=i.get(a.snapshotName);if(D&&D.has(P)){let M=D.get(P);g=M.name||null,y=M.role||null,h=M.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),v=d.match(/internal:role=([^ ]+)/i),k=d.match(/internal:describe="([^"]+)"/i),R=d.match(/name="([^"]+)"/i);if(w){p.push({type:"text",text:w[1]});let P=w[1].split(" ");P.length>1&&(p.push({type:"text",text:P[0],fuzzy:!0}),p.push({type:"text",text:P[P.length-1],fuzzy:!0}))}if(E&&p.push({type:"label",label:E[1]}),S&&p.push({type:"placeholder",placeholder:S[1]}),g){p.unshift({type:"text",text:g,source:"accessibility-tree"});let P=g.split(" ");P.length>1&&p.push({type:"text",text:P[0],fuzzy:!0,source:"accessibility-tree"})}if(y||v){let P=y||v[1],D=g||(R?R[1]:w?w[1]:null);p.unshift({type:"role",role:P,name:D,source:g?"accessibility-tree":"selector"})}if(h&&p.unshift({type:"label",label:h,source:"accessibility-tree"}),k){let P=k[1],D=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],M=null,$=P;for(let j of D)if(P.toLowerCase().endsWith(` ${j}`)){M=j.replace(" ",""),$=P.substring(0,P.length-j.length-1);break}if(M){p.push({type:"role",role:M,name:$});let j=$.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:j}),p.push({type:"text",text:$});let N=$.split(" ");N.length>1&&(p.push({type:"text",text:N[0],fuzzy:!0}),p.push({type:"text",text:N.slice(0,2).join(" "),fuzzy:!0}))}else{let j=P.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:j}),p.push({type:"text",text:P})}}let C=this.extractDOMStrategies(d,c,w?.[1]||k?.[1],a.pageId);p.push(...C);let L=this.extractStructuralContext(d);(L.parent||L.sibling)&&p.forEach(P=>{["role","text","label","testid"].includes(P.type)&&(L.parent&&(P.parent=L.parent),L.sibling&&(P.sibling=L.sibling))}),p.push({type:"css",value:d});let K=g||w?w[1]:k?k[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${s.length}`;s.push({method:u,name:K,action:u==="type"?"fill":u,value:m,strategies:p,timestamp:a.startTime,actualText:g,actualRole:y,actualAriaLabel:h})}}}catch{}return s}catch(r){throw new Error(`Failed to parse trace: ${r.message}`,{cause:r})}}static extractDOMStrategies(e,t,r,n){let s=[];if(!t||t.size===0||!r)return s;try{let i=t.get(n);if(!i)return s;let c=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),a=i.match(l);a&&s.push({type:"testid",value:a[1],priority:"high"});let u=new RegExp(`class=["']([^"']+)["'][^>]*>[^<]*${c}`,"gi"),d=i.matchAll(u);for(let g of d){let y=g[1].split(/\s+/).filter(h=>h&&!h.match(/^(css|jss|makeStyles|MuiBox|MuiStack)-\w+/)&&h.length>2);y.length>0&&(s.push({type:"class",value:y.join("."),priority:"medium"}),y.length===1&&s.push({type:"class",value:y[0],priority:"medium"}))}let m=new RegExp(`id=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),p=i.match(m);p&&!p[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&s.push({type:"id",value:p[1],priority:"high"})}catch(i){console.warn(`[TraceParser] DOM extraction failed: ${i.message}`)}return s}static extractStructuralContext(e){let t={parent:null,sibling:null},r=e.split(">>").map(i=>i.trim());if(r.length>1){let c=r[r.length-2].replace(/internal:text="[^"]+"\s*/gi,"").replace(/internal:role=\S+\s*/gi,"").replace(/internal:label="[^"]+"\s*/gi,"").trim();c&&(c.match(/^(form|section|nav|header|aside|main|article)\b/)||c.includes("[")||c.match(/[#.]\w/))&&(t.parent=c)}let s=r[r.length-1].match(/([^+~]+)\s*[+~]\s*(.+)/);return s&&(t.sibling=s[1].trim()),t}};var rr=class{static async step(e,t){let{name:r,action:n,value:s,strategies:i,options:c={timeout:1e4},enrichedData:l}=t;console.log(`[Zibby] \u26A1 Executing step: ${r}`),await this.waitForPageStability(e,c.timeout);let a=await this.findBestMatch(e,i,r);if(!a)throw new Error(`[Zibby] \u274C Failed to find "${r}" using ${i.length} strategies`);l?.position&&await this.verifyPosition(a,l.position),await this.performActionWithRetry(e,a,n,s,3),console.log(`[Zibby] \u2728 Step "${r}" completed.`)}static async waitForPageStability(e,t=1e4){try{await e.waitForLoadState("networkidle",{timeout:3e3}).catch(()=>{}),await e.evaluate(()=>new Promise(r=>{let n,s=new MutationObserver(()=>{clearTimeout(n),n=setTimeout(()=>{s.disconnect(),r()},500)});s.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),n=setTimeout(()=>{s.disconnect(),r()},500)})).catch(()=>{})}catch{}}static async verifyPosition(e,t){try{let r=await e.boundingBox();if(!r)return;let n=Math.abs(r.x-t.x),s=Math.abs(r.y-t.y);(n>50||s>50)&&(console.log(`[Zibby] \u26A0\uFE0F Element moved: expected (${t.x}, ${t.y}), got (${r.x}, ${r.y})`),await new Promise(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(l=>setTimeout(l,1e3*i))}}static async findBestMatch(e,t,r){let s=Date.now(),i=t.map(async(a,u)=>{try{let m=await this.getLocator(e,a).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,a,e);return{element:g,strategy:a,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((a,u)=>u.score-a.score);let l=c[0];return console.log(`[Zibby] \u2705 Found element using ${l.strategy.type} (score: ${l.score.toFixed(2)}, ${c.length} candidates)`),l.element}static async scoreCandidate(e,t,r){let 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((l,a)=>l.matches(a),t.parent)&&(n+=30)}catch{}if(t.sibling)try{await e.evaluate((c,l)=>c.parentElement?.querySelector(l)!==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 l=0,a=c;for(;a;)a.tagName==="IFRAME"&&l++,a=a.parentElement;return l});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 nr=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(l){if(l.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(l){if(l.getAttribute("aria-label"))return l.getAttribute("aria-label").trim();let a=l.getAttribute("aria-labelledby");if(a){let m=document.getElementById(a);if(m)return m.textContent.trim()}if(l.id){let m=document.querySelector(`label[for="${l.id}"]`);if(m)return m.textContent.trim()}let u=l.closest("label");if(u){let m=u.cloneNode(!0);m.querySelectorAll("input, select, textarea").forEach(g=>g.remove());let p=m.textContent.trim();if(p)return p}if(l.placeholder)return l.placeholder;let d=l.tagName.toLowerCase();return d==="button"||d==="a"||l.getAttribute("role")==="button"?(l.textContent||"").trim().slice(0,50):l.title?l.title:d==="input"&&(l.type==="submit"||l.type==="button")&&l.value||""}function r(l){let a=[],u=l.closest("form");if(u)if(u.id)a.push(`form#${u.id}`);else if(u.name)a.push(`form[name=${u.name}]`);else if(u.action)try{let y=new URL(u.action,window.location.origin).pathname;a.push(`form[action=${y}]`)}catch{a.push(`form[action=${u.getAttribute("action")}]`)}else{let y=document.querySelectorAll("form"),h=Array.from(y).indexOf(u);a.push(`form:nth(${h})`)}let d=l.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");a.push(h||y)}let m=l.closest('section, article, [role="region"]');if(m){let y=m.querySelector("h1, h2, h3, h4, h5, h6");y&&a.push(`section:${y.textContent.trim().slice(0,30)}`)}let p=l.closest("fieldset");if(p){let y=p.querySelector("legend");y&&a.push(`fieldset:${y.textContent.trim()}`)}let g=l.closest('dialog, [role="dialog"], [role="alertdialog"]');if(g){let y=g.querySelector('[role="heading"], h1, h2, h3');y?a.push(`dialog:${y.textContent.trim().slice(0,30)}`):a.push("dialog")}return a.join("/")}function n(l){let a=l.tagName.toLowerCase(),u=l.id||"",d=l.name||"",m=l.type||"",p=l.getAttribute("role")||"",g="";if(l.href)try{g=new URL(l.href,window.location.origin).pathname.slice(0,50)}catch{g=l.getAttribute("href")?.slice(0,50)||""}let y=t(l).slice(0,50).replace(/\s+/g," "),h=r(l),b=[a,u,d,m,p,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(l=>{let a=window.getComputedStyle(l);if(a.display==="none"||a.visibility==="hidden")return;let u=n(l),d=u,m=i.get(d)||0;m>0&&(u=`${d}-${m}`),i.set(d,m+1),l.setAttribute("data-zibby-id",u),c++}),console.log(`[Zibby] Injected ${c} stable IDs`)})}catch{}}};var vi=8,Oi=1,$i=64;function Ii(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 ki,writeFileSync as kn,existsSync as Pi}from"node:fs";import{join as Pn}from"node:path";var V=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 Ci}from"node:fs";import{join as Cn}from"node:path";var be=class extends V{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=Cn(e,"traces"),r=Cn(e,"trace.zip");if(Ci(r))try{this.traceData=await nt.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,l=s.actualAriaLabel;return i||c||l?(console.log(`[TraceTextEnricher] \u2705 Event ${n}: text="${i}", role="${c}", label="${l}"`),{traceActualText:i,traceActualRole:c,traceActualAriaLabel:l,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 Ni(o){let e=Pn(o,"events.json"),t=Pn(o,"events-enriched.json");if(!Pi(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(ki(e,"utf-8")),n=new be,s=0,i=0;for(let c of r)try{let l=await n.enrich(c,{sessionPath:o});l&&(c.enrichedData={...c.enrichedData||{},...l},s++)}catch(l){console.log(`[PostProcess] Failed to enrich event ${c.id}: ${l.message}`),i++}return s>0&&(kn(t,JSON.stringify(r,null,2)),kn(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 Ri}from"node:child_process";import{existsSync as Li}from"node:fs";import{dirname as Mi,resolve as Nn,relative as Di}from"node:path";var Ct=new Map,ot=8,Rn={name:"run_playwright_test",description:`Run a Playwright test file and return results. Use this after writing a test to verify it works. If it fails, fix the issues and run again. Maximum ${ot} attempts per session.`,inputSchema:{type:"object",properties:{scriptPath:{type:"string",description:"Path to the Playwright test file (e.g., tests/login.spec.js)"}},required:["scriptPath"]},async execute({scriptPath:o},e){let r=`${e?.sessionId||"default"}:${o}`,n=(Ct.get(r)||0)+1;if(Ct.set(r,n),n>ot)return{success:!1,executionCount:n,maxReached:!0,error:`Maximum ${ot} executions reached. Stop retrying and return your best result.`};let s=e?.projectRoot||process.cwd(),i=Nn(s,o),c=Di(s,i);return c.startsWith("..")||Nn(i)!==i&&c.includes("..")?{success:!1,executionCount:n,error:"Path traversal detected: scriptPath must be within the project root."}:Li(i)?new Promise(l=>{let a=Mi(i),u=Ri("npx",["playwright","test",i,"--reporter=line"],{cwd:s,env:{...process.env,FORCE_COLOR:"0"}}),d="",m="";u.stdout.on("data",g=>{d+=g.toString()}),u.stderr.on("data",g=>{m+=g.toString()});let p=setTimeout(()=>{u.kill("SIGTERM"),l({success:!1,executionCount:n,error:"Test timed out after 60 seconds",stdout:d.slice(-2e3),stderr:m.slice(-1e3)})},6e4);u.on("close",g=>{clearTimeout(p);let h=`${d}
270
270
  ${m}`.split(`
271
271
  `),b="",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}
272
272
  `;for(let v=E+1;v<Math.min(E+5,h.length);v++)b+=`${h[v]}
273
- `}if(S.includes("at ")&&S.includes(".spec.")){let v=S.match(/:(\d+):\d+/);v&&(w=parseInt(v[1]))}}l(g===0?{success:!0,executionCount:n,message:"All tests passed!",output:d.slice(-500)}:{success:!1,executionCount:n,remainingAttempts:ot-n,error:b.slice(0,1500)||"Test failed (see output)",failedAtLine:w,stdout:d.slice(-1500),stderr:m.slice(-500),hint:n<ot?"Fix the error and run again.":"Last attempt - make your best fix."})}),u.on("error",g=>{clearTimeout(p),l({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 Ct.keys())e.startsWith(`${o}:`)&&Ct.delete(e)}};function Li(o){Rn.resetCount(o)}var le=class{async generate(e){throw new Error("TestGenerationStrategy.generate() must be implemented")}canGenerate(e){throw new Error("TestGenerationStrategy.canGenerate() must be implemented")}getName(){throw new Error("TestGenerationStrategy.getName() must be implemented")}getPriority(){return 0}};import{readFileSync as Ln,writeFileSync as Mi}from"node:fs";var Me=class extends le{constructor(){super("mcp-ref","MCP Reference Replay (Exact 1:1)",200)}canGenerate(e){let t=e.eventsPath||`${e.sessionPath}/execute_live/events.json`;try{return JSON.parse(Ln(t,"utf-8")).some(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 l=JSON.parse(Ln(s,"utf-8")).filter(u=>["navigate","type","fill","click","select_option"].includes(u.type)),a=`import { test, expect } from '@playwright/test';
273
+ `}if(S.includes("at ")&&S.includes(".spec.")){let v=S.match(/:(\d+):\d+/);v&&(w=parseInt(v[1]))}}l(g===0?{success:!0,executionCount:n,message:"All tests passed!",output:d.slice(-500)}:{success:!1,executionCount:n,remainingAttempts:ot-n,error:b.slice(0,1500)||"Test failed (see output)",failedAtLine:w,stdout:d.slice(-1500),stderr:m.slice(-500),hint:n<ot?"Fix the error and run again.":"Last attempt - make your best fix."})}),u.on("error",g=>{clearTimeout(p),l({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 Ct.keys())e.startsWith(`${o}:`)&&Ct.delete(e)}};function Ui(o){Rn.resetCount(o)}var le=class{async generate(e){throw new Error("TestGenerationStrategy.generate() must be implemented")}canGenerate(e){throw new Error("TestGenerationStrategy.canGenerate() must be implemented")}getName(){throw new Error("TestGenerationStrategy.getName() must be implemented")}getPriority(){return 0}};import{readFileSync as Ln,writeFileSync as ji}from"node:fs";var Me=class extends le{constructor(){super("mcp-ref","MCP Reference Replay (Exact 1:1)",200)}canGenerate(e){let t=e.eventsPath||`${e.sessionPath}/execute_live/events.json`;try{return JSON.parse(Ln(t,"utf-8")).some(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 l=JSON.parse(Ln(s,"utf-8")).filter(u=>["navigate","type","fill","click","select_option"].includes(u.type)),a=`import { test, expect } from '@playwright/test';
274
274
  `;a+=`import { ZibbyRuntime } from '@zibby/core';
275
275
 
276
276
  `,a+=`test('${i}', async ({ page }) => {
@@ -310,7 +310,7 @@ ${m}`.split(`
310
310
  `,a+=` });
311
311
 
312
312
  `}}return a+=`});
313
- `,Mi(t,a),console.log(`[MCPRefStrategy] \u2705 Generated test with ${l.length} actions using MCP descriptions`),{success:!0,testPath:t,method:"MCP Reference Replay (1:1)",actionsGenerated:l.length}}_extractRole(e){let t=e.toLowerCase();return t.includes("button")?"button":t.includes("textbox")?"textbox":t.includes("link")?"link":t.includes("checkbox")?"checkbox":t.includes("radio")?"radio":t.includes("combobox")?"combobox":t.includes("heading")?"heading":"button"}_extractName(e){return e.replace(/\s+(button|textbox|link|checkbox|radio|combobox)$/i,"").trim()}_escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}};import{readFileSync as Mn,writeFileSync as Di}from"node:fs";var De=class extends le{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(Mn(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 l=JSON.parse(Mn(s,"utf-8")).filter(m=>["navigate","type","fill","click","select_option","select"].includes(m.type)),a=`import { test, expect } from '@playwright/test';
313
+ `,ji(t,a),console.log(`[MCPRefStrategy] \u2705 Generated test with ${l.length} actions using MCP descriptions`),{success:!0,testPath:t,method:"MCP Reference Replay (1:1)",actionsGenerated:l.length}}_extractRole(e){let t=e.toLowerCase();return t.includes("button")?"button":t.includes("textbox")?"textbox":t.includes("link")?"link":t.includes("checkbox")?"checkbox":t.includes("radio")?"radio":t.includes("combobox")?"combobox":t.includes("heading")?"heading":"button"}_extractName(e){return e.replace(/\s+(button|textbox|link|checkbox|radio|combobox)$/i,"").trim()}_escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}};import{readFileSync as Mn,writeFileSync as Bi}from"node:fs";var De=class extends le{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(Mn(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 l=JSON.parse(Mn(s,"utf-8")).filter(m=>["navigate","type","fill","click","select_option","select"].includes(m.type)),a=`import { test, expect } from '@playwright/test';
314
314
  `;a+=`import { StableIdRuntime } from '@zibby/core';
315
315
 
316
316
  `,a+=`test('${i}', async ({ page }) => {
@@ -325,17 +325,17 @@ ${m}`.split(`
325
325
  `}else if(p.type==="select_option"||p.type==="select"){u=!1;let h=p.data?.values||p.data?.params?.values,b=Array.isArray(h)?h[0]:h||"";g?a+=` await StableIdRuntime.selectWithRetry(page, '${g}', '${this._escapeString(b)}');
326
326
  `:a+=` await page.locator('select').selectOption('${this._escapeString(b)}');
327
327
  `}}return a+=`});
328
- `,Di(t,a),console.log(`[StableIdStrategy] \u2705 Generated test with ${l.length} actions using stable IDs`),{success:!0,testPath:t,method:"Stable ID Injection (Experimental)",actionsGenerated:l.length}}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}_generateSemanticSelector(e){let t=e.toLowerCase(),r="locator",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 or=class{constructor(){this.strategies=[new De,new Me],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(`
328
+ `,Bi(t,a),console.log(`[StableIdStrategy] \u2705 Generated test with ${l.length} actions using stable IDs`),{success:!0,testPath:t,method:"Stable ID Injection (Experimental)",actionsGenerated:l.length}}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}_generateSemanticSelector(e){let t=e.toLowerCase(),r="locator",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 or=class{constructor(){this.strategies=[new De,new Me],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(`
329
329
  \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(`
330
- \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}},Ui=new or;var Ue=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 ji}from"node:child_process";import{existsSync as Bi}from"node:fs";var je=class extends Ue{getName(){return"Playwright JSON Reporter"}getPriority(){return 100}canVerify(e){let{testFilePath:t}=e;return Bi(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=ji(s,{cwd:r,encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:n+1e4}),l=JSON.parse(i).stats||{};return{success:l.unexpected===0,passed:l.expected||0,failed:l.unexpected||0,error:null,errorDetails:null}}catch(s){let i=s.stdout||s.stderr||s.message;try{let c=JSON.parse(i),l=c.stats||{},a="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 p=m.tests[0];if(p.results&&p.results.length>0){let g=p.results[0];g.error&&(a=g.error.message||a)}}}}let u=a.includes("Executable doesn't exist")||a.includes("browserType.launch")||a.includes("Please run the following command")||a.includes("npx playwright install")||i.includes("Executable doesn't exist")||i.includes("npx playwright install");return{success:!1,passed:l.expected||0,failed:l.unexpected||0,error:a,errorDetails:a,isEnvironmentError:u}}catch{let l=i.match(/Error: (.+)/),a=l?l[1]:"Test execution failed",u=a.includes("Executable doesn't exist")||a.includes("browserType.launch")||a.includes("Please run the following command")||a.includes("npx playwright install")||i.includes("Executable doesn't exist")||i.includes("npx playwright install");return{success:!1,passed:0,failed:1,error:a,errorDetails:a,isEnvironmentError:u}}}}};var sr=class{constructor(){this.strategies=[new je],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(`
330
+ \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}},Fi=new or;var Ue=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 Gi}from"node:child_process";import{existsSync as Ki}from"node:fs";var je=class extends Ue{getName(){return"Playwright JSON Reporter"}getPriority(){return 100}canVerify(e){let{testFilePath:t}=e;return Ki(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=Gi(s,{cwd:r,encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:n+1e4}),l=JSON.parse(i).stats||{};return{success:l.unexpected===0,passed:l.expected||0,failed:l.unexpected||0,error:null,errorDetails:null}}catch(s){let i=s.stdout||s.stderr||s.message;try{let c=JSON.parse(i),l=c.stats||{},a="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 p=m.tests[0];if(p.results&&p.results.length>0){let g=p.results[0];g.error&&(a=g.error.message||a)}}}}let u=a.includes("Executable doesn't exist")||a.includes("browserType.launch")||a.includes("Please run the following command")||a.includes("npx playwright install")||i.includes("Executable doesn't exist")||i.includes("npx playwright install");return{success:!1,passed:l.expected||0,failed:l.unexpected||0,error:a,errorDetails:a,isEnvironmentError:u}}catch{let l=i.match(/Error: (.+)/),a=l?l[1]:"Test execution failed",u=a.includes("Executable doesn't exist")||a.includes("browserType.launch")||a.includes("Please run the following command")||a.includes("npx playwright install")||i.includes("Executable doesn't exist")||i.includes("npx playwright install");return{success:!1,passed:0,failed:1,error:a,errorDetails:a,isEnvironmentError:u}}}}};var sr=class{constructor(){this.strategies=[new je],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(`
331
331
  \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(`
332
- \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}},Fi=new sr;var ce=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 l=Date.now(),a=await c.enrich(e,t),u=Date.now()-l;a?(Object.assign(r,a),n.push({name:c.getName(),duration:u})):s.push(c.getName())}catch(l){console.warn(`[EnrichmentPipeline] ${c.getName()} failed:`,l.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(`
332
+ \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}},zi=new sr;var ce=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 l=Date.now(),a=await c.enrich(e,t),u=Date.now()-l;a?(Object.assign(r,a),n.push({name:c.getName(),duration:u})):s.push(c.getName())}catch(l){console.warn(`[EnrichmentPipeline] ${c.getName()} failed:`,l.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(`
333
333
  \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(`
334
- 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 Be=class extends W{getName(){return"PositionEnricher"}getPriority(){return 90}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element: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 Dn from"node:crypto";var Se=class extends W{getName(){return"AccessibilityEnricher"}getPriority(){return 100}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:n}=t,s=await r.accessibility.snapshot(),i=await this.findAxNode(n,s);if(!i)return null;let c=await this.getAxContext(i,s),l=this.hashAxSubtree(i),a=this.hashAxPath(c.path);return{accessibility:{role:i.role,name:i.name||"",level:c.level,parent:c.parent,siblings:c.siblings,axTreeHash:l,axPathHash:a}}}catch(r){return this.handleError(r,e)}}async findAxNode(e,t){let r=await e.evaluate(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 Dn.createHash("md5").update(t).digest("hex").substring(0,12)}hashAxPath(e){let t=e.map(r=>`${r.role}:${r.name}`).join("/");return Dn.createHash("md5").update(t).digest("hex").substring(0,12)}};var _e=class extends W{constructor(e={}){super(e),this.pendingRequests=new Set,this.setupNetworkTracking=!1}getName(){return"PageStateEnricher"}getPriority(){return 95}canEnrich(e){return this.enabled&&e.page}async setupTracking(e){this.setupNetworkTracking||(e.on("request",t=>{["document","xhr","fetch"].includes(t.resourceType())&&this.pendingRequests.add(t.url())}),e.on("requestfinished",t=>{this.pendingRequests.delete(t.url())}),e.on("requestfailed",t=>{this.pendingRequests.delete(t.url())}),this.setupNetworkTracking=!0)}async enrich(e,t){try{let{page:r}=t;await this.setupTracking(r);let 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,l=new MutationObserver(()=>{c++,clearTimeout(i),i=setTimeout(()=>{l.disconnect(),s(c===0)},n)});l.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),i=setTimeout(()=>{l.disconnect(),s(!0)},n)}),t)}catch{return!1}}reset(){this.pendingRequests.clear(),this.setupNetworkTracking=!1}};var Fe=class extends W{getName(){return"DOMEnricher"}getPriority(){return 85}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{element:r}=t,n=await r.evaluate(s=>{let i=p=>{let g=[],y=p;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=p=>{let g=[],y=p;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("/")}`},l={};for(let p of s.attributes)l[p.name]=p.value;let a=window.getComputedStyle(s),u={display:a.display,visibility:a.visibility,opacity:a.opacity,pointerEvents:a.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:l,state:{visible:a.display!=="none"&&a.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 st=class extends W{constructor(e={}){super(e),this.priority=200}getName(){return"MCPRef"}getPriority(){return this.priority}async enrich(e,t){let r=e.data?.params?.ref,n=e.data?.params?.element;if(!r&&!n)return null;let s=null,i=null,c=null;if(t?.element)try{let l=await t.element.evaluate(a=>({text:a.textContent?.trim()||"",innerText:a.innerText?.trim()||"",value:a.value||"",label:a.getAttribute("aria-label")||a.getAttribute("label")||"",role:a.getAttribute("role")||a.tagName.toLowerCase(),placeholder:a.getAttribute("placeholder")||"",title:a.getAttribute("title")||""}));s=l.text||l.innerText||l.value||l.placeholder,i=l.role,c=l.label||l.title,console.log(`[MCPRefEnricher] \u2705 Captured actual text: "${s}" (AI said: "${n}")`)}catch(l){console.log(`[MCPRefEnricher] \u26A0\uFE0F Could not extract actual text: ${l.message}`)}return{mcpRef:r,mcpElement:n,actualText:s,actualRole:i,actualLabel:c,recordedSelector:s||n}}};function ir(o={}){let e=new ce(o);return o.enableMCPRef!==!1&&e.register(new st(o)),o.enableTraceText!==!1&&e.register(new be(o)),o.enableAccessibility!==!1&&e.register(new Se(o)),o.enablePageState!==!1&&e.register(new _e(o)),o.enablePosition!==!1&&e.register(new Be(o)),o.enableDOM!==!1&&e.register(new Fe(o)),e}function ar(o={}){let e=new ce(o);return e.register(new Se(o)),e.register(new _e(o)),e}function Gi(o,e={}){let t=new ce(e);for(let r of o)t.register(r);return t}import{readFileSync as Ki,writeFileSync as lr}from"node:fs";import{join as Un}from"node:path";async function zi(o,e={}){let t=Un(o,"events.json"),r=Un(o,"trace.zip");try{let n=JSON.parse(Ki(t,"utf-8")),s=n.map(c=>({...c,_enrichmentNote:"Full enrichment requires live Playwright access. Use EnrichmentPipeline during test execution."})),i=`${t}.backup`;return lr(i,JSON.stringify(n,null,2)),lr(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 cr=class{constructor(e={}){this.pipeline=e.minimal?ar(e):ir(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){lr(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()}};Bt();var Kn=o=>{o?.message?.includes("Connection closed")||o?.message?.includes("MCP error -32000")||o?.code===-32e3||console.error("Unhandled rejection:",o)};process.listeners("unhandledRejection").includes(Kn)||process.on("unhandledRejection",Kn);async function qi(o,e={}){let{agent:t,mcp:r,headless:n,cwd:s=process.cwd(),specPath:i,sessionPath:c,sessionTimestamp:l,...a}=e,u=jn(o,"utf-8"),d=null,{agent:m,error:p}=await ea(s,a),g=m;if(!g&&e.fallbackAgentModule){let b=e.fallbackAgentModule,w=b.BrowserTestAutomationAgent||b.default;w&&(g=new w(a))}if(!g&&p&&console.warn(`\u26A0\uFE0F Failed to load local agent: ${p}`),!g)throw new Error(`No agent found. Please run:
334
+ 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 Be=class extends V{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 Dn from"node:crypto";var Se=class extends V{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),l=this.hashAxSubtree(i),a=this.hashAxPath(c.path);return{accessibility:{role:i.role,name:i.name||"",level:c.level,parent:c.parent,siblings:c.siblings,axTreeHash:l,axPathHash:a}}}catch(r){return this.handleError(r,e)}}async findAxNode(e,t){let r=await e.evaluate(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 Dn.createHash("md5").update(t).digest("hex").substring(0,12)}hashAxPath(e){let t=e.map(r=>`${r.role}:${r.name}`).join("/");return Dn.createHash("md5").update(t).digest("hex").substring(0,12)}};var _e=class extends V{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,l=new MutationObserver(()=>{c++,clearTimeout(i),i=setTimeout(()=>{l.disconnect(),s(c===0)},n)});l.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),i=setTimeout(()=>{l.disconnect(),s(!0)},n)}),t)}catch{return!1}}reset(){this.pendingRequests.clear(),this.setupNetworkTracking=!1}};var Fe=class extends V{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=p=>{let g=[],y=p;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=p=>{let g=[],y=p;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("/")}`},l={};for(let p of s.attributes)l[p.name]=p.value;let a=window.getComputedStyle(s),u={display:a.display,visibility:a.visibility,opacity:a.opacity,pointerEvents:a.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:l,state:{visible:a.display!=="none"&&a.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 st=class extends V{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 l=await t.element.evaluate(a=>({text:a.textContent?.trim()||"",innerText:a.innerText?.trim()||"",value:a.value||"",label:a.getAttribute("aria-label")||a.getAttribute("label")||"",role:a.getAttribute("role")||a.tagName.toLowerCase(),placeholder:a.getAttribute("placeholder")||"",title:a.getAttribute("title")||""}));s=l.text||l.innerText||l.value||l.placeholder,i=l.role,c=l.label||l.title,console.log(`[MCPRefEnricher] \u2705 Captured actual text: "${s}" (AI said: "${n}")`)}catch(l){console.log(`[MCPRefEnricher] \u26A0\uFE0F Could not extract actual text: ${l.message}`)}return{mcpRef:r,mcpElement:n,actualText:s,actualRole:i,actualLabel:c,recordedSelector:s||n}}};function ir(o={}){let e=new ce(o);return o.enableMCPRef!==!1&&e.register(new st(o)),o.enableTraceText!==!1&&e.register(new be(o)),o.enableAccessibility!==!1&&e.register(new Se(o)),o.enablePageState!==!1&&e.register(new _e(o)),o.enablePosition!==!1&&e.register(new Be(o)),o.enableDOM!==!1&&e.register(new Fe(o)),e}function ar(o={}){let e=new ce(o);return e.register(new Se(o)),e.register(new _e(o)),e}function Ji(o,e={}){let t=new ce(e);for(let r of o)t.register(r);return t}import{readFileSync as Yi,writeFileSync as lr}from"node:fs";import{join as Un}from"node:path";async function Hi(o,e={}){let t=Un(o,"events.json"),r=Un(o,"trace.zip");try{let n=JSON.parse(Yi(t,"utf-8")),s=n.map(c=>({...c,_enrichmentNote:"Full enrichment requires live Playwright access. Use EnrichmentPipeline during test execution."})),i=`${t}.backup`;return lr(i,JSON.stringify(n,null,2)),lr(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 cr=class{constructor(e={}){this.pipeline=e.minimal?ar(e):ir(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){lr(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()}};Bt();var Kn=o=>{o?.message?.includes("Connection closed")||o?.message?.includes("MCP error -32000")||o?.code===-32e3||console.error("Unhandled rejection:",o)};process.listeners("unhandledRejection").includes(Kn)||process.on("unhandledRejection",Kn);async function ea(o,e={}){let{agent:t,mcp:r,headless:n,cwd:s=process.cwd(),specPath:i,sessionPath:c,sessionTimestamp:l,...a}=e,u=jn(o,"utf-8"),d=null,{agent:m,error:p}=await na(s,a),g=m;if(!g&&e.fallbackAgentModule){let b=e.fallbackAgentModule,w=b.BrowserTestAutomationAgent||b.default;w&&(g=new w(a))}if(!g&&p&&console.warn(`\u26A0\uFE0F Failed to load local agent: ${p}`),!g)throw new Error(`No agent found. Please run:
335
335
  zibby init
336
336
 
337
337
  This will create .zibby/graph.mjs with your workflow definition.`);await g.initialize(d);let y=!1,h=()=>{if(!y)try{s||process.cwd(),y=!0}catch(b){console.warn("[zibby] run-index interrupt row:",b?.message||b)}};process.on("SIGINT",h),process.on("SIGTERM",h);try{if(e.singleNode){console.log(`
338
338
  \u{1F3AF} Running Single Node: ${e.singleNode} (Framework Mode)
339
- `);let C=g.calculateOutputPath(i||o),L=g.buildGraph(),K={};for(let[M,O]of L.nodes.entries())K[M]=O.config||O;let P={};if(e.sessionId){let M=e.sessionId,O=e.paths?.output||Yi;if(M==="last"){let _=Ge(s,O,Gn);if(Bn(_)){let{readdirSync:I,statSync:T}=await import("fs"),B=I(_).filter($=>T(Ge(_,$)).isDirectory()).map($=>({name:$,time:T(Ge(_,$)).mtimeMs})).sort(($,F)=>F.time-$.time);B.length>0?(M=B[0].name,console.log(`\u{1F4C2} Using latest session: ${M}`)):console.log(`\u26A0\uFE0F No sessions found in ${_}`)}}let j=Ge(s,O,Gn,M),N=Ge(j,"execute_live"),x=Ge(N,Hi);Bn(x)?(console.log(`\u{1F4C2} Loading session: ${M}`),P={sessionPath:j,execute_live_output:JSON.parse(jn(x,"utf-8"))}):console.log(`\u26A0\uFE0F Session not found: ${j}`)}let D=await g.runSingleNode(e.singleNode,K,{testSpec:u,outputPath:C,cwd:s||process.cwd(),contextConfig:e.contextConfig,specPath:i||o,config:e,...P});return typeof g.onComplete=="function"&&await g.onComplete(D),D}let b;typeof e.onPipelineProgress=="function"?b=e.onPipelineProgress:e.runIndex?.pipelineProgress!==!1&&(b=Nr({cwd:s||process.cwd(),config:e}));let w=s||process.cwd(),E=c!=null&&String(c).trim()!==""?(()=>{let C=String(c).trim();try{return Ji(C)?Fn(C):Fn(w,C)}catch{return C}})():void 0,S=Wi(),v=E??S;Vi();let k=Zi({cwd:w,config:e,traceFrom:"runTest",initialState:{sessionPath:v,sessionTimestamp:l}}),R;try{R=await g.run(u,{testSpec:u,specPath:i||o,cwd:w,config:e,sessionPath:k.sessionPath,sessionTimestamp:k.sessionTimestamp,...b?{onPipelineProgress:b}:{}})}catch(C){throw typeof C?.message=="string"&&C.message.includes("Interrupted by user")&&(s||process.cwd(),void 0),y||(C?.partialResult,C?.message,void 0),C}return R}finally{process.off("SIGINT",h),process.off("SIGTERM",h),await g.cleanup()}}function Xi(o){return o.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function Qi(o,e){if(o[e])return o[e];let t=Xi(e);if(o[t])return o[t];let r=`${t}Workflow`;return o[r]?o[r]:null}async function Pf(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(l=>l!=="default"&&typeof s[l]=="function"&&s[l].prototype instanceof Pe),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 ea(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,l;if(c){if(l=Qi(i,c),!l){let u=Object.keys(i).filter(d=>d!=="default"&&typeof i[d]=="function");throw new Error(`Workflow "${c}" not found.
339
+ `);let C=g.calculateOutputPath(i||o),L=g.buildGraph(),K={};for(let[M,$]of L.nodes.entries())K[M]=$.config||$;let P={};if(e.sessionId){let M=e.sessionId,$=e.paths?.output||Wi;if(M==="last"){let _=Ge(s,$,Gn);if(Bn(_)){let{readdirSync:I,statSync:T}=await import("fs"),B=I(_).filter(O=>T(Ge(_,O)).isDirectory()).map(O=>({name:O,time:T(Ge(_,O)).mtimeMs})).sort((O,F)=>F.time-O.time);B.length>0?(M=B[0].name,console.log(`\u{1F4C2} Using latest session: ${M}`)):console.log(`\u26A0\uFE0F No sessions found in ${_}`)}}let j=Ge(s,$,Gn,M),N=Ge(j,"execute_live"),x=Ge(N,Vi);Bn(x)?(console.log(`\u{1F4C2} Loading session: ${M}`),P={sessionPath:j,execute_live_output:JSON.parse(jn(x,"utf-8"))}):console.log(`\u26A0\uFE0F Session not found: ${j}`)}let D=await g.runSingleNode(e.singleNode,K,{testSpec:u,outputPath:C,cwd:s||process.cwd(),contextConfig:e.contextConfig,specPath:i||o,config:e,...P});return typeof g.onComplete=="function"&&await g.onComplete(D),D}let b;typeof e.onPipelineProgress=="function"?b=e.onPipelineProgress:e.runIndex?.pipelineProgress!==!1&&(b=Nr({cwd:s||process.cwd(),config:e}));let w=s||process.cwd(),E=c!=null&&String(c).trim()!==""?(()=>{let C=String(c).trim();try{return Zi(C)?Fn(C):Fn(w,C)}catch{return C}})():void 0,S=Qi(),v=E??S;Xi();let k=qi({cwd:w,config:e,traceFrom:"runTest",initialState:{sessionPath:v,sessionTimestamp:l}}),R;try{R=await g.run(u,{testSpec:u,specPath:i||o,cwd:w,config:e,sessionPath:k.sessionPath,sessionTimestamp:k.sessionTimestamp,...b?{onPipelineProgress:b}:{}})}catch(C){throw typeof C?.message=="string"&&C.message.includes("Interrupted by user")&&(s||process.cwd(),void 0),y||(C?.partialResult,C?.message,void 0),C}return R}finally{process.off("SIGINT",h),process.off("SIGTERM",h),await g.cleanup()}}function ta(o){return o.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function ra(o,e){if(o[e])return o[e];let t=ta(e);if(o[t])return o[t];let r=`${t}Workflow`;return o[r]?o[r]:null}async function Lf(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(l=>l!=="default"&&typeof s[l]=="function"&&s[l].prototype instanceof Pe),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 na(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,l;if(c){if(l=ra(i,c),!l){let u=Object.keys(i).filter(d=>d!=="default"&&typeof i[d]=="function");throw new Error(`Workflow "${c}" not found.
340
340
  Available workflows: ${u.join(", ")}
341
- Supported formats: QuickSmokeWorkflow, QuickSmoke, quick-smoke`)}let a=Object.keys(i).find(u=>i[u]===l);console.log(`\u2713 Using workflow: ${a} (from --workflow ${c})`)}else{if(l=i.BrowserTestAutomationAgent||i.CursorAgent||i.default,!l){let a=Object.keys(i).filter(u=>u!=="default"&&typeof i[u]=="function"&&i[u].prototype instanceof Pe);a.length>0&&(l=i[a[0]],console.log(`\u2713 Using workflow: ${a[0]} (auto-detected)`))}if(!l)return{agent:null,error:"Could not find any WorkflowAgent export in local graph.js"};l.name?.includes("auto-detected")||console.log("\u2713 Using local agent from .zibby/graph.mjs")}return{agent:new l(e),error:null}}catch(t){return{agent:null,error:t.message}}}var zn=class{constructor(e={}){this.config=e}async run(e){return qi(e.spec||e.specPath,{...this.config,...e})}};export{Qn as AGENT_TYPES,iu as ALL_TOOLS,Se as AccessibilityEnricher,Ds as AgentStrategy,he as AssistantStrategy,zs as CHAT_MEMORY_TOOLS,wd as CI_ENV_VARS,ut as CLAUDE_MODEL_MAP,pt as CODEX_MODEL_MAP,eo as CORE_LOG_LEVELS,Us as CORE_TOOLS,pe as ClaudeAgentStrategy,fe as CodexAgentStrategy,Et as CursorAgentStrategy,Ei as DEFAULT_MAX_CONCURRENT_RUNS,ae as DEFAULT_MODELS,gd as DEFAULT_OUTPUT_BASE,Fe as DOMEnricher,_d as EVENTS_FILE,ce as EnrichmentPipeline,W as EventEnricher,kt as GEMINI_MODEL_MAP,Bs as GITHUB_TOOLS,me as GeminiAgentStrategy,js as JIRA_TOOLS,te as LOG_LEVELS,cr as LiveEnrichmentRecorder,ct as Logger,Ai as MAX_MAX_CONCURRENT_RUNS,Me as MCPRefStrategy,Ks as MEMORY_TOOLS,Ti as MIN_MAX_CONCURRENT_RUNS,Te as MODEL_REGISTRY,We as McpClientManager,ge as OpenAIToolProvider,_e as PageStateEnricher,je as PlaywrightJsonVerificationStrategy,Be as PositionEnricher,Sd as RAW_OUTPUT_FILE,bd as RESULT_FILE,$n as RIPPLE_EFFECT_SCRIPT,Gs as RUNNER_TOOLS,Yt as ResultHandler,hd as SESSIONS_DIR,yd as SESSION_INFO_FILE,Wf as SKILLS,Js as SKILL_TOOLS,Fs as SLACK_TOOLS,tt as SelectorGenerator,nr as StableIdRuntime,De as StableIdStrategy,oe as StreamingParser,Ys as TRUSTED_VCS_HOSTS,zn as TestAutomation,le as TestGenerationStrategy,er as TestPostProcessor,Ue as TestVerificationStrategy,Oe as ToolCallProvider,nt as TraceParser,Pe as WorkflowAgent,Lf as WorkflowGraph,rr as ZibbyRuntime,Qe as ZibbyUploader,ln as authedUrl,Je as buildVendorModelMap,Yo as checkCursorAgentInstalled,mi as checkCursorAgentPatched,Uf as clearInheritedSessionEnvForFreshRun,en as clearTokenCache,ni as cloneRepo,Gi as createCustomPipeline,ir as createDefaultPipeline,ar as createMinimalPipeline,dn as createUploader,zi as enrichRecordedEvents,Si as generateRippleHelperCode,Df as generateWorkflowSessionId,nn as getAgentStrategy,td as getAllSkills,gi as getApprovalKeys,Ho as getCursorAgentInstallInstructions,Xn as getPickerModels,Qf as getSkill,ed as hasSkill,Zt as hostnameOf,bi as injectRippleEffect,Ms as invokeAgent,sn as isTrustedVcsHost,rd as listSkillIds,Pf as listWorkflows,f as logger,Xs as organizeVideos,di as patchCursorAgentForCI,q as pickFromPool,Ci as postProcessEvents,an as providerForHost,Bf as readPinnedSessionPathFromEnv,un as redactGitSecrets,Bt as registerBuiltInStrategies,Xf as registerSkill,Li as resetExecutionCount,At as resolveIntegrationToken,vi as resolveMaxParallelRuns,Wn as resolveModelFamily,Mf as resolveWorkflowSession,Rn as runPlaywrightTestTool,qi as runTest,yi as saveApprovalKeys,Hs as scrubRemoteToTokenless,Zs as securePush,on as selfHostGitlabHost,Tn as sessionSkill,jf as shouldTrustInheritedSessionEnv,Ff as syncProcessEnvToSession,Ui as testGenerationManager,Fi as testVerificationManager,ne as timeline,cn as tokenlessUrl,ns as workflow,zf as z};
341
+ Supported formats: QuickSmokeWorkflow, QuickSmoke, quick-smoke`)}let a=Object.keys(i).find(u=>i[u]===l);console.log(`\u2713 Using workflow: ${a} (from --workflow ${c})`)}else{if(l=i.BrowserTestAutomationAgent||i.CursorAgent||i.default,!l){let a=Object.keys(i).filter(u=>u!=="default"&&typeof i[u]=="function"&&i[u].prototype instanceof Pe);a.length>0&&(l=i[a[0]],console.log(`\u2713 Using workflow: ${a[0]} (auto-detected)`))}if(!l)return{agent:null,error:"Could not find any WorkflowAgent export in local graph.js"};l.name?.includes("auto-detected")||console.log("\u2713 Using local agent from .zibby/graph.mjs")}return{agent:new l(e),error:null}}catch(t){return{agent:null,error:t.message}}}var zn=class{constructor(e={}){this.config=e}async run(e){return ea(e.spec||e.specPath,{...this.config,...e})}};export{ro as AGENT_TYPES,cu as ALL_TOOLS,Se as AccessibilityEnricher,Bs as AgentStrategy,he as AssistantStrategy,Hs as CHAT_MEMORY_TOOLS,Td as CI_ENV_VARS,ut as CLAUDE_MODEL_MAP,pt as CODEX_MODEL_MAP,no as CORE_LOG_LEVELS,Fs as CORE_TOOLS,pe as ClaudeAgentStrategy,fe as CodexAgentStrategy,Et as CursorAgentStrategy,vi as DEFAULT_MAX_CONCURRENT_RUNS,ae as DEFAULT_MODELS,bd as DEFAULT_OUTPUT_BASE,Fe as DOMEnricher,Ed as EVENTS_FILE,ce as EnrichmentPipeline,V as EventEnricher,kt as GEMINI_MODEL_MAP,Ks as GITHUB_TOOLS,me as GeminiAgentStrategy,Gs as JIRA_TOOLS,te as LOG_LEVELS,cr as LiveEnrichmentRecorder,ct as Logger,$i as MAX_MAX_CONCURRENT_RUNS,Me as MCPRefStrategy,Ys as MEMORY_TOOLS,Oi as MIN_MAX_CONCURRENT_RUNS,Te as MODEL_REGISTRY,Ve as McpClientManager,ge as OpenAIToolProvider,_e as PageStateEnricher,je as PlaywrightJsonVerificationStrategy,Be as PositionEnricher,xd as RAW_OUTPUT_FILE,wd as RESULT_FILE,On as RIPPLE_EFFECT_SCRIPT,Js as RUNNER_TOOLS,Yt as ResultHandler,Sd as SESSIONS_DIR,_d as SESSION_INFO_FILE,Qf as SKILLS,Zs as SKILL_TOOLS,zs as SLACK_TOOLS,tt as SelectorGenerator,nr as StableIdRuntime,De as StableIdStrategy,oe as StreamingParser,Ws as TRUSTED_VCS_HOSTS,zn as TestAutomation,le as TestGenerationStrategy,er as TestPostProcessor,Ue as TestVerificationStrategy,$e as ToolCallProvider,nt as TraceParser,Pe as WorkflowAgent,Uf as WorkflowGraph,rr as ZibbyRuntime,Qe as ZibbyUploader,ln as authedUrl,Je as buildVendorModelMap,Wo as checkCursorAgentInstalled,yi as checkCursorAgentPatched,Ff as clearInheritedSessionEnvForFreshRun,en as clearTokenCache,ii as cloneRepo,Ji as createCustomPipeline,ir as createDefaultPipeline,ar as createMinimalPipeline,dn as createUploader,Hi as enrichRecordedEvents,xi as generateRippleHelperCode,Bf as generateWorkflowSessionId,nn as getAgentStrategy,od as getAllSkills,bi as getApprovalKeys,Vo as getCursorAgentInstallInstructions,to as getPickerModels,rd as getSkill,nd as hasSkill,Zt as hostnameOf,wi as injectRippleEffect,js as invokeAgent,sn as isTrustedVcsHost,sd as listSkillIds,Lf as listWorkflows,f as logger,ti as organizeVideos,hi as patchCursorAgentForCI,q as pickFromPool,Ni as postProcessEvents,an as providerForHost,Kf as readPinnedSessionPathFromEnv,un as redactGitSecrets,Bt as registerBuiltInStrategies,td as registerSkill,Ui as resetExecutionCount,At as resolveIntegrationToken,Ii as resolveMaxParallelRuns,Qn as resolveModelFamily,jf as resolveWorkflowSession,Rn as runPlaywrightTestTool,ea as runTest,_i as saveApprovalKeys,Vs as scrubRemoteToTokenless,qs as securePush,on as selfHostGitlabHost,Tn as sessionSkill,Gf as shouldTrustInheritedSessionEnv,zf as syncProcessEnvToSession,Fi as testGenerationManager,zi as testVerificationManager,ne as timeline,cn as tokenlessUrl,is as workflow,Hf as z};