@zibby/core 2.0.5 → 2.0.6
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 +77 -77
- package/dist/package.json +4 -4
- package/dist/register-built-in-strategies.js +36 -36
- package/dist/strategies/claude-strategy.js +6 -6
- package/dist/strategies/index.js +47 -47
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
var so=Object.defineProperty;var io=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var br=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var Sr=(n,e)=>{for(var t in e)so(n,t,{get:e[t],enumerable:!0})};var xr={};Sr(xr,{zodToJson:()=>de});import{z as wr}from"zod";import{zodToJsonSchema as po}from"zod-to-json-schema";function fo(n){if(!n||typeof n!="object")return n;if(Array.isArray(n.type))return n.type.includes("null")||(n.type=[...n.type,"null"]),n;if(typeof n.type=="string")return n.type=[n.type,"null"],n;for(let e of["anyOf","oneOf"])if(Array.isArray(n[e]))return n[e].some(t=>t&&t.type==="null")||(n[e]=[...n[e],{type:"null"}]),n;return{anyOf:[n,{type:"null"}]}}function ve(n){if(!n||typeof n!="object")return n;for(let e of["$defs","definitions"])if(n[e]&&typeof n[e]=="object")for(let t of Object.keys(n[e]))n[e][t]=ve(n[e][t]);for(let e of["anyOf","oneOf","allOf"])Array.isArray(n[e])&&(n[e]=n[e].map(ve));if(n.properties&&typeof n.properties=="object"){n.additionalProperties=!1;let e=Object.keys(n.properties),t=new Set(Array.isArray(n.required)?n.required:[]);for(let r of e){let o=ve(n.properties[r]);t.has(r)||(o=fo(o)),n.properties[r]=o}n.required=e}return n.items&&(Array.isArray(n.items)?n.items=n.items.map(ve):n.items=ve(n.items)),n}function de(n,e={target:"openApi3"}){if(!n)return null;let t=e?.target==="openAi",r=null;if(typeof wr?.toJSONSchema=="function")try{r=wr.toJSONSchema(n)}catch{}if(!r)try{r=po(n,e)}catch{return null}if(t&&r)try{return ve(r)}catch{return r}return r}var He=br(()=>{});var yn={};Sr(yn,{INTEGRATION_API_TIMEOUT_MS:()=>dn,clearConnectedCache:()=>si,clearTokenCache:()=>hn,getConnectedIntegrations:()=>oi,resolveIntegrationToken:()=>Ct});import{existsSync as Qs,readFileSync as ei}from"node:fs";import{homedir as ti}from"node:os";import{join as ri}from"node:path";function un(){let n=process.env.ZIBBY_SELF_HOST;return n!=null&&n!==""&&n!=="0"&&n.toLowerCase()!=="false"}function pn(){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 n=ri(ti(),".zibby","config.json");return Qs(n)&&JSON.parse(ei(n,"utf-8")).sessionToken||null}catch{return null}}function fn(){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"}function ni(n=process.env){let e=Number(n.INTEGRATION_API_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.min(12e4,Math.max(1e3,Math.floor(e))):dn}function mn(){let n=ni();return{signal:AbortSignal.timeout(n),label:`after ${n}ms (INTEGRATION_API_TIMEOUT_MS)`}}function gn(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}function an(n,e,t){if(!gn(n))return n;let r=new Error(`${t} TIMED OUT ${e.label}`);return r.timedOut=!0,r.cause=n,r}async function Ct(n){if(un()){let l=cn[n];if(l&&process.env[l])return{token:process.env[l]}}let e=Date.now(),t=It.get(n);if(t&&t.expiresAt>e)return t.data;let r=pn();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 o=`${fn()}/integrations/token/${n}`,s=mn(),i;try{i=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${r}`},signal:s.signal})}catch(l){throw an(l,s,`${n} token lookup`)}if(!i.ok){let l=await i.text().catch(()=>"");if(i.status===404){let u="";try{u=String(JSON.parse(l)?.error||"").trim()}catch{}throw new Error(u||`${n} is not connected. Connect it at https://studio.zibby.dev/integrations`)}throw i.status===401||i.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Failed to resolve ${n} token (${i.status}): ${l}`)}let c;try{c=await i.json()}catch(l){throw an(l,s,`${n} token body read`)}if(!c||typeof c!="object")throw new Error(`Invalid response from ${n} token endpoint: expected object, got ${typeof c}`);if(n==="jira"){if(!c.token||typeof c.token!="string")throw new Error(`Invalid jira token response: token is ${typeof c.token}, expected string`);if(!c.cloudId&&!c.instanceUrl&&!c.baseUrl)throw new Error("Invalid jira token response: carries neither cloudId (OAuth connection) nor instanceUrl (API-token connection) \u2014 reconnect Jira.")}else if(n==="github"&&(!c.token||typeof c.token!="string"))throw new Error(`Invalid github token response: token is ${typeof c.token}, expected string`);let a=((c.expiresInSec||3e3)-120)*1e3;return It.set(n,{data:c,expiresAt:e+a}),c}function hn(n){n?It.delete(n):It.clear()}function ln(n){let e=process.env.WORKFLOW_ENABLED_INTEGRATIONS;if(typeof e!="string"||e.trim()==="")return n;let t=new Set(e.split(",").map(o=>o.trim()).filter(Boolean));if(t.size===0)return n;let r={};for(let[o,s]of Object.entries(n))t.has(o)&&(r[o]=s);return r}async function oi(){let n=Date.now();if(Me&&Me.expiresAt>n)return Me.data;if(un()){let r={};for(let[s,i]of Object.entries(cn))r[s]=!!process.env[i];let o=ln(r);return Me={data:o,expiresAt:n+6e4},o}let e=pn();if(!e)return{};let t=mn();try{let r=await fetch(`${fn()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:t.signal});if(!r.ok)return{};let o=await r.json(),s={};if(o&&typeof o=="object")for(let[c,a]of Object.entries(o))a&&typeof a=="object"&&"connected"in a&&(s[c]=!!a.connected);let i=ln(s);return Me={data:i,expiresAt:n+6e4},i}catch(r){return gn(r)&&console.warn(`[backend-client] /integrations/status TIMED OUT ${t.label} \u2014 proceeding with no connection map`),{}}}function si(){Me=null}var It,cn,dn,Me,Pt=br(()=>{It=new Map,cn={github:"GITHUB_TOKEN",gitlab:"GITLAB_TOKEN",sentry:"SENTRY_AUTH_TOKEN",slack:"SLACK_BOT_TOKEN"};dn=2e4;Me=null});import{readFileSync as Qn,existsSync as eo}from"node:fs";import{join as Je,resolve as to,isAbsolute as ya}from"node:path";import{DEFAULT_OUTPUT_BASE as ba,SESSIONS_DIR as ro,RESULT_FILE as Sa,resolveWorkflowSession as _a,clearInheritedSessionEnvForFreshRun as wa,readPinnedSessionPathFromEnv as xa}from"@zibby/agent-workflow";import{registerStrategy as $t}from"@zibby/agent-workflow";import{AgentStrategy as So,getSkill as Ar,NO_INTEGRATION_TOGGLEABLE_SKILL_IDS as _o}from"@zibby/agent-workflow";import{query as wo}from"@anthropic-ai/claude-agent-sdk";import ao from"node:process";var _r=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 Ae(n=ao.env){let e={},t=new Set(_r);for(let[r,o]of Object.entries(n))t.has(r)||o!==void 0&&(e[r]=o);return e}function ut(n){return!!n&&(n.transport==="http"||typeof n.url=="string"&&!n.command)}var lo=new Set(["claude"]);function co(){let n=String(process.env.MCP_ALWAYS_LOAD??"").trim().toLowerCase();return!(n==="0"||n==="false"||n==="off")}function uo(n,e){return lo.has(n)?co()?typeof e.alwaysLoad=="boolean"?{alwaysLoad:e.alwaysLoad}:{}:{}:{}}function re(n,e,{processEnv:t}={}){if(!e)return null;let r=uo(n,e);if(ut(e)){let s=String(e.url||"").trim();if(!s)return null;let i=e.headers&&typeof e.headers=="object"?e.headers:void 0;switch(n){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 o={command:e.command};return e.args?.length&&(o.args=e.args),e.cwd&&(o.cwd=e.cwd),t?o.env={...t,...e.env||{}}:e.env&&Object.keys(e.env).length&&(o.env=e.env),{...o,...r}}function pt(n){return ut(n)?`http \u2192 ${String(n.url||"").replace(/\?.*$/,"")}`:`${n?.command||"?"} ${(n?.args||[]).join(" ")}`.trim()}He();import{writeFileSync as Dt,mkdirSync as jt,existsSync as Oe,readFileSync as $r}from"fs";import{homedir as Or}from"os";import{join as te}from"path";import Ye from"chalk";var ne={debug:0,info:1,warn:2,error:3,silent:4},ft=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return ne.debug;if(process.env.ZIBBY_VERBOSE==="true")return ne.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in ne?ne[e]:ne.info}_shouldLog(e){return ne[e]>=this._level}_formatMessage(e,t,r={}){let o=new Date().toISOString(),i=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(i+=Ye.dim(` ${JSON.stringify(r)}`)),i}_getPrefix(e){return{debug:Ye.gray("[DEBUG]"),info:Ye.cyan("[INFO]"),warn:Ye.yellow("[WARN]"),error:Ye.red("\u274C [ERROR]")}[e]||""}debug(e,t){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,t))}info(e,t){this._shouldLog("info")&&console.log(this._formatMessage("info",e,t))}warn(e,t){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,t))}error(e,t){this._shouldLog("error")&&console.error(this._formatMessage("error",e,t))}setLevel(e){e in ne&&(this._level=ne[e])}getLevel(){return Object.keys(ne).find(e=>ne[e]===this._level)}},p=new ft;import{timeline as ie,Timeline as Ua,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as Da}from"@zibby/agent-workflow";var Ze=[{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},{alias:"sonnet-4-6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.6"},{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:"sonnet-4.6"},{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:"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:"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 Ve(n){let e={};for(let t of Ze)t.vendor===n&&(e[t.alias]=t.canonicalId);return e}function mo(n){if(!n||typeof n!="string")return null;let e=n.toLowerCase();for(let t of Ze)if(t.alias.toLowerCase()===e)return t.family??null;for(let t of Ze)if(t.canonicalId.toLowerCase()===e)return t.family??null;return null}function Er(n){let e=String(n||"").match(/(\d+(?:\.\d+)?)/);return e?parseFloat(e[1]):0}function Tr(n){let e=String(n||"").toLowerCase();return/\b(base|mini)\b/.test(e)?0:/\b(opus|pro)\b/.test(e)?2:1}function go(n,e){let t=Er(e.label)-Er(n.label);if(t!==0)return t;let r=Tr(e.label)-Tr(n.label);return r!==0?r:n.label.localeCompare(e.label)}function ho(){let n=[],e=new Map;for(let r of Ze)r.pickerVisible&&(e.has(r.vendor)||(e.set(r.vendor,[]),n.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}));let t=[];for(let r of n)t.push(...e.get(r).sort(go));return t}function $e(n,e){let t=typeof e=="string"?e.trim():"";if(t)return t;throw new Error(`[${n}] 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 ce={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"},yo={ASSISTANT:"assistant",CLAUDE:"claude",CURSOR:"cursor",CODEX:"codex",GEMINI:"gemini"},bo={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error",SILENT:"silent"},dt=Ve("claude"),mt=Ve("codex"),Ut=Ve("gemini"),gt={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};function W(n){let e=`${n}_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 o=r[Math.floor(Math.random()*r.length)],s=process.env[n];return process.env[n]=o,p.debug(`[auth-pool] ${n}: picked 1 of ${r.length} from pool (***${o.slice(-4)})`),{picked:o,count:r.length,dispose(){s===void 0?delete process.env[n]:process.env[n]=s}}}function ht(n){if(!n||typeof n!="object")return null;let e=(...o)=>{for(let s of o){if(s==null||s==="")continue;let i=Number(s);if(Number.isFinite(i))return i}return null},t=e(n.input_tokens,n.inputTokens,n.prompt_tokens,n.promptTokens),r=e(n.output_tokens,n.outputTokens,n.completion_tokens,n.completionTokens);return t==null&&r==null?null:{input:t||0,output:r||0}}import{createRequire as xo}from"module";import J from"process";var vr=xo(import.meta.url);function Eo(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")}function Ir(n){if(!n||typeof n!="object")return null;let e=n.message?.content??n.content;return Array.isArray(e)&&e.length||typeof e=="string"&&e.length?e:typeof n.text=="string"&&n.text.length?n.text:null}function To(n){let e=Ir(n);if(e===null)return null;let t;try{t=JSON.stringify(e)}catch{return null}return typeof t!="string"||!t?null:`${`${n.type||n.constructor?.name||"?"}`}:${t.length}:${Eo(t)}`}function Ao(n){if(!n||typeof n!="object")return"a message with no type";let e=n.type||n.constructor?.name||"unknown-type",t=n.subtype?`/${n.subtype}`:"",r=Ir(n);if(typeof r=="string")return`${e}${t} text "${r.slice(0,80)}"`;if(!Array.isArray(r))return`${e}${t} (no readable content)`;let o=r.slice(0,4).map(s=>!s||typeof s!="object"?String(s).slice(0,30):s.type==="tool_use"?`tool_use ${s.name||"(unnamed)"}`:s.type==="tool_result"?`tool_result${s.is_error?" (error)":""}`:s.type==="text"&&typeof s.text=="string"?`text "${s.text.slice(0,60)}"`:s.type==="thinking"?"thinking":String(s.type||"block").slice(0,30));return r.length>o.length&&o.push(`+${r.length-o.length} more`),`${e}${t} [${o.join(", ")}]`}var Cr=(n,e)=>{let t=String(n??"");return t.length>e?`${t.slice(0,e)}\u2026`:t},vo=/secret|token|password|passwd|credential|authorization|bearer|api[-_]?key|private[-_]?key|access[-_]?key/i,Pr=(n,e=0)=>{if(n==null||e>6||typeof n!="object")return n;let t=Array.isArray(n)?[]:{};for(let[r,o]of Object.entries(n)){let s=vo.test(r)||r==="value"&&typeof n.key=="string";t[r]=s&&typeof o=="string"&&o?"[redacted]":Pr(o,e+1)}return t},kr=n=>{try{if(n==null)return"";let e=Pr(n),t=typeof e=="string"?e:JSON.stringify(e);return Cr(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""}},$o=500;function Oo(n){let e=n&&typeof n=="object"?n.content:void 0,t=new Set,r=0;if(typeof e=="string")r=e.length,e&&t.add("text");else if(Array.isArray(e))for(let a of e){if(typeof a=="string"){t.add("text"),r+=a.length;continue}!a||typeof a!="object"||(t.add(typeof a.type=="string"&&a.type?a.type:"unknown"),typeof a.text=="string"&&(r+=a.text.length))}else if(e!=null){t.add("json");try{r=JSON.stringify(e).length}catch{r=0}}let o=!(n&&n.is_error===!0),s={ok:o,chars:r};if(t.size&&(s.kind=[...t].join("+")),o)return s;let i=e;Array.isArray(e)&&(i=e.map(a=>typeof a=="string"?a:a&&typeof a.text=="string"?a.text:"").filter(Boolean).join(`
|
|
2
|
-
`));let c=
|
|
1
|
+
var ao=Object.defineProperty;var lo=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var Sr=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var _r=(n,e)=>{for(var t in e)ao(n,t,{get:e[t],enumerable:!0})};var Er={};_r(Er,{zodToJson:()=>de});import{z as wr}from"zod";import{zodToJsonSchema as mo}from"zod-to-json-schema";function go(n){if(!n||typeof n!="object")return n;if(Array.isArray(n.type))return n.type.includes("null")||(n.type=[...n.type,"null"]),n;if(typeof n.type=="string")return n.type=[n.type,"null"],n;for(let e of["anyOf","oneOf"])if(Array.isArray(n[e]))return n[e].some(t=>t&&t.type==="null")||(n[e]=[...n[e],{type:"null"}]),n;return{anyOf:[n,{type:"null"}]}}function ve(n){if(!n||typeof n!="object")return n;for(let e of["$defs","definitions"])if(n[e]&&typeof n[e]=="object")for(let t of Object.keys(n[e]))n[e][t]=ve(n[e][t]);for(let e of["anyOf","oneOf","allOf"])Array.isArray(n[e])&&(n[e]=n[e].map(ve));if(n.properties&&typeof n.properties=="object"){n.additionalProperties=!1;let e=Object.keys(n.properties),t=new Set(Array.isArray(n.required)?n.required:[]);for(let r of e){let o=ve(n.properties[r]);t.has(r)||(o=go(o)),n.properties[r]=o}n.required=e}return n.items&&(Array.isArray(n.items)?n.items=n.items.map(ve):n.items=ve(n.items)),n}function de(n,e={target:"openApi3"}){if(!n)return null;let t=e?.target==="openAi",r=null;if(typeof wr?.toJSONSchema=="function")try{r=wr.toJSONSchema(n)}catch{}if(!r)try{r=mo(n,e)}catch{return null}if(t&&r)try{return ve(r)}catch{return r}return r}var He=Sr(()=>{});var Sn={};_r(Sn,{INTEGRATION_API_TIMEOUT_MS:()=>gn,clearConnectedCache:()=>li,clearTokenCache:()=>bn,getConnectedIntegrations:()=>ai,resolveIntegrationToken:()=>Pt});import{existsSync as ri,readFileSync as ni}from"node:fs";import{homedir as oi}from"node:os";import{join as si}from"node:path";function fn(){let n=process.env.ZIBBY_SELF_HOST;return n!=null&&n!==""&&n!=="0"&&n.toLowerCase()!=="false"}function dn(){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 n=si(oi(),".zibby","config.json");return ri(n)&&JSON.parse(ni(n,"utf-8")).sessionToken||null}catch{return null}}function mn(){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"}function ii(n=process.env){let e=Number(n.INTEGRATION_API_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.min(12e4,Math.max(1e3,Math.floor(e))):gn}function hn(){let n=ii();return{signal:AbortSignal.timeout(n),label:`after ${n}ms (INTEGRATION_API_TIMEOUT_MS)`}}function yn(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}function cn(n,e,t){if(!yn(n))return n;let r=new Error(`${t} TIMED OUT ${e.label}`);return r.timedOut=!0,r.cause=n,r}async function Pt(n){if(fn()){let l=pn[n];if(l&&process.env[l])return{token:process.env[l]}}let e=Date.now(),t=Ct.get(n);if(t&&t.expiresAt>e)return t.data;let r=dn();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 o=`${mn()}/integrations/token/${n}`,s=hn(),i;try{i=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${r}`},signal:s.signal})}catch(l){throw cn(l,s,`${n} token lookup`)}if(!i.ok){let l=await i.text().catch(()=>"");if(i.status===404){let u="";try{u=String(JSON.parse(l)?.error||"").trim()}catch{}throw new Error(u||`${n} is not connected. Connect it at https://studio.zibby.dev/integrations`)}throw i.status===401||i.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Failed to resolve ${n} token (${i.status}): ${l}`)}let c;try{c=await i.json()}catch(l){throw cn(l,s,`${n} token body read`)}if(!c||typeof c!="object")throw new Error(`Invalid response from ${n} token endpoint: expected object, got ${typeof c}`);if(n==="jira"){if(!c.token||typeof c.token!="string")throw new Error(`Invalid jira token response: token is ${typeof c.token}, expected string`);if(!c.cloudId&&!c.instanceUrl&&!c.baseUrl)throw new Error("Invalid jira token response: carries neither cloudId (OAuth connection) nor instanceUrl (API-token connection) \u2014 reconnect Jira.")}else if(n==="github"&&(!c.token||typeof c.token!="string"))throw new Error(`Invalid github token response: token is ${typeof c.token}, expected string`);let a=((c.expiresInSec||3e3)-120)*1e3;return Ct.set(n,{data:c,expiresAt:e+a}),c}function bn(n){n?Ct.delete(n):Ct.clear()}function un(n){let e=process.env.WORKFLOW_ENABLED_INTEGRATIONS;if(typeof e!="string"||e.trim()==="")return n;let t=new Set(e.split(",").map(o=>o.trim()).filter(Boolean));if(t.size===0)return n;let r={};for(let[o,s]of Object.entries(n))t.has(o)&&(r[o]=s);return r}async function ai(){let n=Date.now();if(Me&&Me.expiresAt>n)return Me.data;if(fn()){let r={};for(let[s,i]of Object.entries(pn))r[s]=!!process.env[i];let o=un(r);return Me={data:o,expiresAt:n+6e4},o}let e=dn();if(!e)return{};let t=hn();try{let r=await fetch(`${mn()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:t.signal});if(!r.ok)return{};let o=await r.json(),s={};if(o&&typeof o=="object")for(let[c,a]of Object.entries(o))a&&typeof a=="object"&&"connected"in a&&(s[c]=!!a.connected);let i=un(s);return Me={data:i,expiresAt:n+6e4},i}catch(r){return yn(r)&&console.warn(`[backend-client] /integrations/status TIMED OUT ${t.label} \u2014 proceeding with no connection map`),{}}}function li(){Me=null}var Ct,pn,gn,Me,kt=Sr(()=>{Ct=new Map,pn={github:"GITHUB_TOKEN",gitlab:"GITLAB_TOKEN",sentry:"SENTRY_AUTH_TOKEN",slack:"SLACK_BOT_TOKEN"};gn=2e4;Me=null});import{readFileSync as to,existsSync as ro}from"node:fs";import{join as Je,resolve as no,isAbsolute as _a}from"node:path";import{DEFAULT_OUTPUT_BASE as xa,SESSIONS_DIR as oo,RESULT_FILE as wa,resolveWorkflowSession as Ea,clearInheritedSessionEnvForFreshRun as Ta,readPinnedSessionPathFromEnv as Aa}from"@zibby/agent-workflow";import{registerStrategy as Ot}from"@zibby/agent-workflow";import{AgentStrategy as xo,getSkill as vr,NO_INTEGRATION_TOGGLEABLE_SKILL_IDS as wo,formatProviderError as Eo}from"@zibby/agent-workflow";import{query as To}from"@anthropic-ai/claude-agent-sdk";import co from"node:process";var xr=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 Ae(n=co.env){let e={},t=new Set(xr);for(let[r,o]of Object.entries(n))t.has(r)||o!==void 0&&(e[r]=o);return e}function pt(n){return!!n&&(n.transport==="http"||typeof n.url=="string"&&!n.command)}var uo=new Set(["claude"]);function po(){let n=String(process.env.MCP_ALWAYS_LOAD??"").trim().toLowerCase();return!(n==="0"||n==="false"||n==="off")}function fo(n,e){return uo.has(n)?po()?typeof e.alwaysLoad=="boolean"?{alwaysLoad:e.alwaysLoad}:{}:{}:{}}function re(n,e,{processEnv:t}={}){if(!e)return null;let r=fo(n,e);if(pt(e)){let s=String(e.url||"").trim();if(!s)return null;let i=e.headers&&typeof e.headers=="object"?e.headers:void 0;switch(n){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 o={command:e.command};return e.args?.length&&(o.args=e.args),e.cwd&&(o.cwd=e.cwd),t?o.env={...t,...e.env||{}}:e.env&&Object.keys(e.env).length&&(o.env=e.env),{...o,...r}}function ft(n){return pt(n)?`http \u2192 ${String(n.url||"").replace(/\?.*$/,"")}`:`${n?.command||"?"} ${(n?.args||[]).join(" ")}`.trim()}He();import{writeFileSync as jt,mkdirSync as Bt,existsSync as Oe,readFileSync as Or}from"fs";import{homedir as Ir}from"os";import{join as te}from"path";import Ye from"chalk";var ne={debug:0,info:1,warn:2,error:3,silent:4},dt=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return ne.debug;if(process.env.ZIBBY_VERBOSE==="true")return ne.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in ne?ne[e]:ne.info}_shouldLog(e){return ne[e]>=this._level}_formatMessage(e,t,r={}){let o=new Date().toISOString(),i=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(i+=Ye.dim(` ${JSON.stringify(r)}`)),i}_getPrefix(e){return{debug:Ye.gray("[DEBUG]"),info:Ye.cyan("[INFO]"),warn:Ye.yellow("[WARN]"),error:Ye.red("\u274C [ERROR]")}[e]||""}debug(e,t){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,t))}info(e,t){this._shouldLog("info")&&console.log(this._formatMessage("info",e,t))}warn(e,t){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,t))}error(e,t){this._shouldLog("error")&&console.error(this._formatMessage("error",e,t))}setLevel(e){e in ne&&(this._level=ne[e])}getLevel(){return Object.keys(ne).find(e=>ne[e]===this._level)}},p=new dt;import{timeline as ie,Timeline as Ba,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as Fa}from"@zibby/agent-workflow";var Ze=[{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},{alias:"sonnet-4-6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.6"},{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:"sonnet-4.6"},{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:"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:"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 Ve(n){let e={};for(let t of Ze)t.vendor===n&&(e[t.alias]=t.canonicalId);return e}function ho(n){if(!n||typeof n!="string")return null;let e=n.toLowerCase();for(let t of Ze)if(t.alias.toLowerCase()===e)return t.family??null;for(let t of Ze)if(t.canonicalId.toLowerCase()===e)return t.family??null;return null}function Tr(n){let e=String(n||"").match(/(\d+(?:\.\d+)?)/);return e?parseFloat(e[1]):0}function Ar(n){let e=String(n||"").toLowerCase();return/\b(base|mini)\b/.test(e)?0:/\b(opus|pro)\b/.test(e)?2:1}function yo(n,e){let t=Tr(e.label)-Tr(n.label);if(t!==0)return t;let r=Ar(e.label)-Ar(n.label);return r!==0?r:n.label.localeCompare(e.label)}function bo(){let n=[],e=new Map;for(let r of Ze)r.pickerVisible&&(e.has(r.vendor)||(e.set(r.vendor,[]),n.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}));let t=[];for(let r of n)t.push(...e.get(r).sort(yo));return t}function $e(n,e){let t=typeof e=="string"?e.trim():"";if(t)return t;throw new Error(`[${n}] 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 ce={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"},So={ASSISTANT:"assistant",CLAUDE:"claude",CURSOR:"cursor",CODEX:"codex",GEMINI:"gemini"},_o={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error",SILENT:"silent"},mt=Ve("claude"),gt=Ve("codex"),Dt=Ve("gemini"),ht={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};function q(n){let e=`${n}_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 o=r[Math.floor(Math.random()*r.length)],s=process.env[n];return process.env[n]=o,p.debug(`[auth-pool] ${n}: picked 1 of ${r.length} from pool (***${o.slice(-4)})`),{picked:o,count:r.length,dispose(){s===void 0?delete process.env[n]:process.env[n]=s}}}function yt(n){if(!n||typeof n!="object")return null;let e=(...o)=>{for(let s of o){if(s==null||s==="")continue;let i=Number(s);if(Number.isFinite(i))return i}return null},t=e(n.input_tokens,n.inputTokens,n.prompt_tokens,n.promptTokens),r=e(n.output_tokens,n.outputTokens,n.completion_tokens,n.completionTokens);return t==null&&r==null?null:{input:t||0,output:r||0}}import{createRequire as Ao}from"module";import J from"process";var $r=Ao(import.meta.url);function vo(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")}function Cr(n){if(!n||typeof n!="object")return null;let e=n.message?.content??n.content;return Array.isArray(e)&&e.length||typeof e=="string"&&e.length?e:typeof n.text=="string"&&n.text.length?n.text:null}function $o(n){let e=Cr(n);if(e===null)return null;let t;try{t=JSON.stringify(e)}catch{return null}return typeof t!="string"||!t?null:`${`${n.type||n.constructor?.name||"?"}`}:${t.length}:${vo(t)}`}function Pr(n){if(!n||typeof n!="object")return"a message with no type";let e=n.type||n.constructor?.name||"unknown-type",t=n.subtype?`/${n.subtype}`:"",r=Cr(n);if(typeof r=="string")return`${e}${t} text "${r.slice(0,80)}"`;if(!Array.isArray(r))return`${e}${t} (no readable content)`;let o=r.slice(0,4).map(s=>!s||typeof s!="object"?String(s).slice(0,30):s.type==="tool_use"?`tool_use ${s.name||"(unnamed)"}`:s.type==="tool_result"?`tool_result${s.is_error?" (error)":""}`:s.type==="text"&&typeof s.text=="string"?`text "${s.text.slice(0,60)}"`:s.type==="thinking"?"thinking":String(s.type||"block").slice(0,30));return r.length>o.length&&o.push(`+${r.length-o.length} more`),`${e}${t} [${o.join(", ")}]`}function Oo(n){if(!n||typeof n!="object")return"";let e=n.message?.content??n.content;if(Array.isArray(e)){let t=e.filter(r=>r&&r.type==="text"&&typeof r.text=="string"&&r.text.trim()).map(r=>r.text.trim());if(t.length)return We(t.join(" "))}else if(typeof e=="string"&&e.trim())return We(e);return n.error&&typeof n.error=="object"&&typeof n.error.message=="string"?We(n.error.message):typeof n.message=="string"&&n.message.trim()?We(n.message):typeof n.result=="string"&&n.result.trim()?We(n.result):Pr(n)}function We(n){let e=String(n).replace(/\s+/g," ").trim();return e.length>400?`${e.slice(0,400)}\u2026`:e}var kr=(n,e)=>{let t=String(n??"");return t.length>e?`${t.slice(0,e)}\u2026`:t},Io=/secret|token|password|passwd|credential|authorization|bearer|api[-_]?key|private[-_]?key|access[-_]?key/i,Nr=(n,e=0)=>{if(n==null||e>6||typeof n!="object")return n;let t=Array.isArray(n)?[]:{};for(let[r,o]of Object.entries(n)){let s=Io.test(r)||r==="value"&&typeof n.key=="string";t[r]=s&&typeof o=="string"&&o?"[redacted]":Nr(o,e+1)}return t},Rr=n=>{try{if(n==null)return"";let e=Nr(n),t=typeof e=="string"?e:JSON.stringify(e);return kr(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""}},Co=500;function Po(n){let e=n&&typeof n=="object"?n.content:void 0,t=new Set,r=0;if(typeof e=="string")r=e.length,e&&t.add("text");else if(Array.isArray(e))for(let a of e){if(typeof a=="string"){t.add("text"),r+=a.length;continue}!a||typeof a!="object"||(t.add(typeof a.type=="string"&&a.type?a.type:"unknown"),typeof a.text=="string"&&(r+=a.text.length))}else if(e!=null){t.add("json");try{r=JSON.stringify(e).length}catch{r=0}}let o=!(n&&n.is_error===!0),s={ok:o,chars:r};if(t.size&&(s.kind=[...t].join("+")),o)return s;let i=e;Array.isArray(e)&&(i=e.map(a=>typeof a=="string"?a:a&&typeof a.text=="string"?a.text:"").filter(Boolean).join(`
|
|
2
|
+
`));let c=Rr(i);return c&&(s.error=c),s}function ko(){try{if(J.env.CLAUDE_CODE_EXECUTABLE&&Oe(J.env.CLAUDE_CODE_EXECUTABLE))return J.env.CLAUDE_CODE_EXECUTABLE;let n=J.platform,e=J.arch,t=`@anthropic-ai/claude-agent-sdk-${n}-${e}`,r=n==="win32"?"claude.exe":"claude";try{let o=$r.resolve(`${t}/package.json`),s=te(o,"..",r);if(Oe(s))return s}catch{}try{let o=$r.resolve("@anthropic-ai/claude-agent-sdk/package.json"),s=te(o,"..");for(let c of[r,te("vendor",r),te("bin",r)]){let a=te(s,c);if(Oe(a))return a}let i=te(s,"..",`claude-agent-sdk-${n}-${e}`,r);if(Oe(i))return i}catch{}}catch{}return null}var bt=ko();bt&&p.debug(`Claude native CLI resolved to baked binary: ${bt}`);var me=class extends xo{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,o=!!J.env.ANTHROPIC_AUTH_TOKEN||!!J.env.ANTHROPIC_AUTH_TOKEN_POOL,s=t||r||o;return s||p.debug("ClaudeAgentStrategy: no credentials. Set one of ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_AUTH_TOKEN (or a *_POOL variant for multi-token rotation)."),s}async invoke(e,t={}){let{model:r,workspace:o=J.cwd(),schema:s=null,images:i=[],skills:c=null,sessionPath:a=null,nodeName:l=null,timeout:u,config:d={},activityLog:m=!1,signal:f=null,sessionId:g,resume:y,forkSession:h,sessionStore:b}=t,_=$e("claude",r),T=mt[_]||_;mt[_]&&_!==T&&p.debug(`Mapped model: ${_} \u2192 ${T}`);let S=[q("ANTHROPIC_API_KEY"),q("CLAUDE_CODE_OAUTH_TOKEN"),q("ANTHROPIC_AUTH_TOKEN")];try{p.debug(`Invoking Claude Agent SDK with model: ${T}, skills: ${JSON.stringify(c)}`);let A=kr,P=($,I)=>{try{console.log(JSON.stringify({mode:$,...I}))}catch{}},R=J.env.CLAUDE_CODE_OAUTH_TOKEN,O=J.env.ANTHROPIC_API_KEY,U=J.env.ANTHROPIC_AUTH_TOKEN;J.env.CLAUDE_CODE_CREDENTIALS_JSON?Lo(J.env.CLAUDE_CODE_CREDENTIALS_JSON):R&&Ro(R,J.env.__ZIBBY_CLAUDE_PLAN);let z=J.env.__ZIBBY_CLAUDE_PLAN,k=z?z.charAt(0).toUpperCase()+z.slice(1):null,D;if(R?D=k?`Claude ${k} plan \xB7 ***${R.slice(-4)}`:`Subscription \xB7 ***${R.slice(-4)}`:O?D=`API key \xB7 ***${O.slice(-4)}`:U?D=`Bearer \xB7 ***${U.slice(-4)}`:D="NONE \u2014 request will fail",!m){let $=(await import("chalk")).default;console.log(""),console.log(` ${$.cyan("\u25C6")} ${$.bold(T)}`),console.log(` ${$.dim("Auth: ")}${D}`),console.log(` ${$.dim("Workdir: ")}${o}`),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:j,mcpServers:w}=this._resolveSkills(c,{sessionPath:a,workspace:o,nodeName:l});for(let $ of t.extraMcpServers||[])if($&&$.serverName&&$.def){if(Object.prototype.hasOwnProperty.call(w,$.serverName)){console.warn(`[custom-mcp] skip "${$.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let I=re("claude",$.def);I&&(w[$.serverName]=I,j.push(`mcp__${$.serverName}__*`))}try{let $={cwd:o,allowedTools:j,...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:T,env:Ae(J.env),...bt&&{pathToClaudeCodeExecutable:bt},...Object.keys(w).length>0&&{mcpServers:w},...g&&{sessionId:g},...y&&{resume:y},...h&&{forkSession:!0},...b&&{sessionStore:b}};if(s){let X=typeof s.parse=="function"?de(s):s;$.outputFormat={type:"json_schema",schema:X},p.debug("Structured output enforced via SDK outputFormat")}p.debug(`Agent SDK options: ${JSON.stringify({cwd:$.cwd,toolCount:j.length,permissionMode:$.permissionMode,model:$.model,hasOutputFormat:!!$.outputFormat})}`);let I="",E=0,L=new Map,M=[];p.debug("Starting Claude Agent SDK query stream");let C=e,G=Array.isArray(i)?i.filter(x=>x&&typeof x.path=="string"&&x.path.startsWith("/")):[];if(G.length){let x=G.map((X,F)=>` ${F+1}. ${X.path}${X.name?` (${X.name})`:""}`).join(`
|
|
3
3
|
`);C=`${e}
|
|
4
4
|
|
|
5
5
|
# Attached image files \u2014 VIEW THESE
|
|
6
6
|
The user attached ${G.length} image(s), saved locally. Use the Read tool on each path to SEE the image, then use what it shows to answer:
|
|
7
|
-
${
|
|
7
|
+
${x}`}let v;try{v=To({prompt:C,options:$})}catch(x){throw p.error(`Failed to initialize Claude Agent SDK: ${x.message}`),x}let K=null,H=0,se=3;if(f?.aborted){let x=new Error("Aborted via signal");throw x.name="AbortError",x}try{for await(let x of v){if(f?.aborted){let F=new Error("Aborted via signal");throw F.name="AbortError",F}if(M.push(x),x.type==="system"&&x.subtype==="init"){let F=x.mcp_servers||[];if(F.length>0){let N=F.map(B=>`${B.name}=${B.status}${B.error?` (${String(B.error).slice(0,120)})`:""}`).join(", ");p.info(`[mcp] SDK init \u2014 ${F.length} server(s): ${N}`);for(let B of F)B.status!=="connected"&&p.warn(`[mcp] server '${B.name}' did not connect: status=${B.status}`,{name:B.name,status:B.status,error:B.error})}else Object.keys(w||{}).length>0&&p.warn(`[mcp] SDK init returned no mcp_servers despite passing ${Object.keys(w).length} server(s) \u2014 SDK version may not expose this field, or config was dropped`);if(Array.isArray(x.tools)){let N=x.tools.filter(B=>B.startsWith("mcp__"));if(N.length>0){let B=Q=>Q.split("__")[1]||"",Y=new Set(Object.entries(w||{}).filter(([,Q])=>Q&&Q.alwaysLoad===!0).map(([Q])=>Q)),Z=N.filter(Q=>Y.has(B(Q))),ee=N.length-Z.length,Te={};for(let Q of N){let fe=B(Q);Y.has(fe)||(Te[fe]=(Te[fe]||0)+1)}let br=Object.entries(Te).sort((Q,fe)=>fe[1]-Q[1]).map(([Q,fe])=>`${Q}:${fe}`).join(" ");p.info(`[mcp] ${N.length} tool(s) reachable \u2014 ${Z.length} IN PROMPT${Z.length?` (${Z.join(", ")})`:""}; ${ee} DEFERRED behind ToolSearch${br?` [${br}]`:""}`)}else Object.keys(w||{}).length>0&&p.warn("[mcp] no mcp__* tools in model's tool list \u2014 MCP servers configured but tools didn't reach the prompt")}}if(x.type==="system"&&x.subtype==="api_retry"){let F=Number(x.attempt)||0,N=Number(x.max_retries)||0,B=x.error_status!=null?String(x.error_status):"?",Y=typeof x.error=="string"?x.error:"error",Z=Number.isFinite(x.retry_delay_ms)?Math.round(x.retry_delay_ms):null,ee=`upstream ${B} (${Y}) \u2014 SDK retry ${F}/${N}`+(Z!=null?` in ${Z}ms`:"");m&&P("turn:retry",{status:B,kind:Y,attempt:F,maxRetries:N,delayMs:Z,detail:ee}),p.warn(`[claude] transient ${ee}`);continue}if(x.type==="error"||x.error){let F=typeof x.error=="string"?x.error:x.error?.type||x.error?.name||null,N=x.error_status??x.error?.status??null,B=Oo(x);try{p.error("SDK error event raw payload",{fullMessage:JSON.stringify(x,null,2)})}catch{}let Y=new Error(Eo({kind:F,status:N,text:B}));Y.providerErrorKind=F||null;let Z=N==null?NaN:Number(N);throw Y.providerErrorStatus=Number.isInteger(Z)&&Z>=100&&Z<=599?Z:null,Y.providerErrorText=B,Y}let X=$o(x);if(X!==null)if(X===K){if(H++,H>=se)throw new Error(`API stuck in loop (${H}x identical): ${Pr(x)}`)}else K=X,H=1;if(x.type==="assistant"||x.constructor?.name==="AssistantMessage"){let F=x.message?.content||x.content||[];for(let N of F)if(N.type==="thinking"&&N.thinking)m?P("turn:thinking",{text:A(N.thinking,600)}):console.log(`${N.thinking.substring(0,200)}${N.thinking.length>200?"...":""}`);else if(N.type==="text"&&N.text)I+=N.text,m||(N.text.length<500?console.log(`${N.text}`):console.log(`${N.text.substring(0,200)}... (${N.text.length} chars)`));else if(N.type==="tool_use")if(E++,N.name.includes("memory")?ie.stepMemory(`Tool: ${N.name}`):ie.stepTool(`Tool: ${N.name}`),m){let Y=Rr(N.input);P("turn:tool",{name:N.name,...Y?{input:Y}:{}}),N.id&&(L.set(N.id,N.name),L.size>Co&&L.delete(L.keys().next().value))}else{let Y=JSON.stringify(N.input).substring(0,100);console.log(` Input: ${Y}${JSON.stringify(N.input).length>100?"...":""}`)}}else if(x.type==="user"){if(m){let F=x.message?.content||x.content;if(Array.isArray(F))for(let N of F){if(!N||N.type!=="tool_result")continue;let B=L.get(N.tool_use_id);P("turn:tool-result",{...B?{name:B}:{},...Po(N)})}}}else if(x.type==="result"||x.constructor?.name==="ResultMessage"){let F=x.result||x.text||x.content||I;try{No({message:x,sessionPath:a,nodeName:l,model:_,toolCallCount:E})}catch(B){p.debug(`usage.json write failed: ${B.message}`)}let N=yt(x?.usage||x?.message?.usage);if(s){if(x.structured_output){p.debug("Using SDK native structured_output");let Y=typeof s.parse=="function"?s.parse(x.structured_output):x.structured_output;return{raw:F,structured:Y,...N?{usage:N}:{},toolUseCount:E}}if(F){let B=this._extractJson(F,s);if(B)return{raw:F,structured:B,...N?{usage:N}:{},toolUseCount:E}}p.warn(`Could not extract structured output \u2014 returning raw text (${(F||"").length} chars)`)}return F||""}}if(p.warn(`Agent SDK ended without result. Collected ${M.length} messages`),I.length>0)return p.debug("Returning accumulated text from messages"),I;throw new Error("Claude Agent SDK query ended without result")}catch(x){let X={message:x?.message,name:x?.name,code:x?.code,cause:x?.cause?.message||x?.cause,stack:x?.stack?.split(`
|
|
8
8
|
`).slice(0,5).join(`
|
|
9
|
-
`),stringified:(()=>{try{return JSON.stringify(
|
|
10
|
-
\u25C6 Model: ${b}${
|
|
11
|
-
`),Array.isArray(a)&&a.length>0){let w=this._resolveCodexHome(l);process.env.CODEX_HOME=w;try{
|
|
12
|
-
${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 A=this._resolveSkillsToMcp(c,{sessionPath:l,workspace:o,nodeName:u});for(let w of t.extraMcpServers||[])if(w&&w.serverName&&w.def){if(Object.prototype.hasOwnProperty.call(A,w.serverName)){console.warn(`[custom-mcp] skip "${w.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let $=re("codex",w.def);$&&(A[w.serverName]=$)}let P={};Object.keys(A).length>0&&(P.mcp_servers=A,Object.values(A).some(w=>w&&typeof w.url=="string")&&(P.experimental_use_rmcp_client=!0),p.debug(`[Codex] MCP servers: ${Object.keys(A).join(", ")}`));let
|
|
9
|
+
`),stringified:(()=>{try{return JSON.stringify(x,Object.getOwnPropertyNames(Object(x)))}catch{return String(x)}})()};throw p.error(`Error during query stream: ${x?.message||x}`,X),x}}catch($){throw p.error("Claude Agent SDK call failed",{message:$?.message,name:$?.name,code:$?.code,cause:$?.cause?.message||$?.cause}),$}}finally{for(let A of S)A.dispose()}}_resolveSkills(e,t){let r=["Read","Write","Edit","Bash","Grep","Glob"];if(e===null)return p.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return p.debug("Default IDE skills for code generation"),{allowedTools:[...r],mcpServers:{}};let o=[...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,a=u=>{let d=vr(u);return d?.meta?.toggleable===!0?!0:d?.meta?.toggleable===void 0&&wo.includes(u)},l=u=>c!==null&&c.size>0&&a(u)&&!c.has(u);for(let u of e){if(l(u)){p.debug(`Skill "${u}" disabled by enabledIntegrations allowlist \u2014 skipping`);continue}let d=vr(u);if(!d){p.warn(`Unknown skill "${u}" \u2014 skipping`);continue}if(d.allowedTools&&o.push(...d.allowedTools),typeof d.resolve=="function"){let m=d.resolve(t),f=re("claude",m);f&&(s[d.serverName]=f,p.debug(`MCP: ${d.serverName} \u2192 ${ft(m)}`))}}return{allowedTools:o,mcpServers:s}}_extractJson(e,t){let r=[()=>{if(e.includes("===JSON_START===")){let o=e.indexOf("===JSON_START===")+16,s=e.indexOf("===JSON_END===");return e.substring(o,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 o=e.indexOf("{"),s=e.lastIndexOf("}");if(o!==-1&&s>o)return e.substring(o,s+1)}];for(let o of r)try{let s=o();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 No({message:n,sessionPath:e,nodeName:t,model:r,toolCallCount:o}){if(!e||!t)return;let s=n?.usage||n?.message?.usage||{},i=qe(s.input_tokens,s.inputTokens),c=qe(s.output_tokens,s.outputTokens),a=qe(s.cache_read_input_tokens,s.cacheReadInputTokens),l=qe(s.cache_creation_input_tokens,s.cacheCreationInputTokens),u=qe(n?.duration_ms,n?.durationMs),d={model:r||null,input_tokens:i,output_tokens:c,cache_read_tokens:a,cache_creation_tokens:l,tool_call_count:typeof o=="number"?o:null,duration_ms:u,captured_at:new Date().toISOString()},m=te(e,t);try{Bt(m,{recursive:!0})}catch{}jt(te(m,"usage.json"),JSON.stringify(d,null,2),"utf-8")}function qe(...n){for(let e of n){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e)))return Number(e)}return null}function Ro(n,e){let t=te(Ir(),".claude"),r=te(t,".credentials.json"),o={claudeAiOauth:{accessToken:n,refreshToken:"",expiresAt:Date.now()+365*24*60*60*1e3,scopes:["user:inference","user:profile"],...e?{subscriptionType:String(e).toLowerCase()}:{}}};try{if(Oe(r)&&JSON.parse(Or(r,"utf-8"))?.claudeAiOauth?.accessToken===n)return;Bt(t,{recursive:!0}),jt(r,JSON.stringify(o,null,2),"utf-8"),p.debug(`Wrote Claude Code OAuth credentials to ${r}`)}catch(s){p.warn(`Could not write ${r}: ${s.message} \u2014 Claude SDK may fail to authenticate.`)}}function Lo(n){let e=te(Ir(),".claude"),t=te(e,".credentials.json"),r;try{r=JSON.parse(n)}catch(o){p.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${o.message}`);return}if(!r?.claudeAiOauth?.accessToken){p.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if(Oe(t)){let o=JSON.parse(Or(t,"utf-8"));if(o?.claudeAiOauth?.accessToken===r.claudeAiOauth.accessToken&&o?.claudeAiOauth?.expiresAt===r.claudeAiOauth.expiresAt)return}Bt(e,{recursive:!0}),jt(t,JSON.stringify(r,null,2),"utf-8"),p.debug(`Wrote full Claude Code credentials blob to ${t}`)}catch(o){p.warn(`Could not write ${t}: ${o.message} \u2014 Claude SDK may fail to authenticate.`)}}import{AgentStrategy as Uo,getSkill as Do}from"@zibby/agent-workflow";import{execSync as _t}from"node:child_process";import{execSync as Mo}from"node:child_process";function St(n){if(!/^[A-Za-z0-9._-]+$/.test(n))return!1;try{return Mo(`command -v ${n}`,{encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim().length>0}catch{return!1}}He();import{readFileSync as jo,mkdirSync as Ft,cpSync as Bo,existsSync as Fo}from"node:fs";import{join as Xe}from"node:path";import{homedir as Go}from"node:os";function Gt(n){if(Array.isArray(n))return n.map(Gt);if(n&&typeof n=="object"){let e={};for(let[t,r]of Object.entries(n))r!==null&&(e[t]=Gt(r));return e}return n}var ge=class extends Uo{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){return!(process.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY_POOL||process.env.CODEX_API_KEY||process.env.CODEX_API_KEY_POOL)?(p.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1):St("codex")?!0:(p.warn("[Codex] codex CLI not on PATH. Install: npm install -g @openai/codex"),!1)}async invoke(e,t={}){let{model:r,workspace:o=process.cwd(),schema:s=null,images:i=[],skills:c=null,plugins:a=null,sessionPath:l=null,nodeName:u=null,timeout:d,config:m={},signal:f=null}=t,g=[q("OPENAI_API_KEY"),q("CODEX_API_KEY")];try{let{Codex:y}=await import("@openai/codex-sdk"),h=$e("codex",r),b=gt[h]||h;gt[h]&&h!==b&&p.debug(`Mapped model: ${h} \u2192 ${b}`),p.debug(`Invoking Codex SDK with model: ${b}, skills: ${JSON.stringify(c)}`);let _=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;_&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=_);let T=_?` | key: ***${_.slice(-4)}`:" | key: not set";if(console.log(`
|
|
10
|
+
\u25C6 Model: ${b}${T}
|
|
11
|
+
`),Array.isArray(a)&&a.length>0){let w=this._resolveCodexHome(l);process.env.CODEX_HOME=w;try{Ft(w,{recursive:!0})}catch{}this._ensurePlugins(a,w)}let S=(await import("chalk")).default;console.log(`
|
|
12
|
+
${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 A=this._resolveSkillsToMcp(c,{sessionPath:l,workspace:o,nodeName:u});for(let w of t.extraMcpServers||[])if(w&&w.serverName&&w.def){if(Object.prototype.hasOwnProperty.call(A,w.serverName)){console.warn(`[custom-mcp] skip "${w.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let $=re("codex",w.def);$&&(A[w.serverName]=$)}let P={};Object.keys(A).length>0&&(P.mcp_servers=A,Object.values(A).some(w=>w&&typeof w.url=="string")&&(P.experimental_use_rmcp_client=!0),p.debug(`[Codex] MCP servers: ${Object.keys(A).join(", ")}`));let R=this._resolveCodexBin(),O=new y({...R?{codexPathOverride:R}:{},...Object.keys(P).length>0&&{config:P},env:Ae(process.env)}),U=o;try{U&&Ft(U,{recursive:!0})}catch{}(!U||!Fo(U))&&(U=process.cwd());let z=O.startThread({workingDirectory:U,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),k=s&&typeof s.parse=="function",D={};if(s)try{let w=k?de(s,{target:"openAi"}):s;D.outputSchema=w,p.debug("Structured output via SDK outputSchema")}catch(w){p.warn(`[Codex] Schema conversion failed, will extract from text: ${w.message}`)}let j=Array.isArray(i)?i.filter(w=>w&&typeof w.path=="string"&&w.path.startsWith("/")):[];if(j.length&&(e=`${e}
|
|
13
13
|
|
|
14
14
|
# Attached image files \u2014 VIEW THESE
|
|
15
15
|
The user attached ${j.length} image(s), saved locally. Read each path to SEE the image, then use what it shows to answer:
|
|
16
16
|
${j.map((w,$)=>` ${$+1}. ${w.path}${w.name?` (${w.name})`:""}`).join(`
|
|
17
|
-
`)}`),f?.aborted){let w=new Error("Aborted via signal");throw w.name="AbortError",w}try{let{events:w}=await z.runStreamed(e,D),$=0,I="",
|
|
18
|
-
`).some(o=>o.includes(e)&&/installed/.test(o))}catch{return!1}}};import{AgentStrategy as
|
|
17
|
+
`)}`),f?.aborted){let w=new Error("Aborted via signal");throw w.name="AbortError",w}try{let{events:w}=await z.runStreamed(e,D),$=0,I="",E=null;for await(let L of w){if(f?.aborted){let C=new Error("Aborted via signal");throw C.name="AbortError",C}let M=L.type;if(M==="item.completed"){let C=L.item,G=C?.type;if(G==="mcp_tool_call"){$++;let v=`${C.server}/${C.tool}`;if(ie.stepTool(`Tool: ${v}`),C.arguments){let K=JSON.stringify(C.arguments),H=K.length>100?`${K.substring(0,100)}...`:K;console.log(` Input: ${H}`)}}else if(G==="tool_call"||G==="function_call"||G==="command_execution"){$++;let v=C.name||C.tool||C.command||"unknown";ie.stepTool(`Tool: ${v}`)}else G==="agent_message"&&(I=C.text||"",I.length<500?console.log(I):console.log(`${I.substring(0,200)}... (${I.length} chars)`))}else M==="turn.completed"?(p.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(L.usage||{})}`),L.usage&&(E=L.usage)):p.debug(`[Codex] Event: ${M} ${JSON.stringify(L).slice(0,300)}`)}if(p.debug(`[Codex] Last agent message (${I.length} chars): ${I.slice(0,500)}`),s){if(!I)throw new Error("Codex agent returned no response");let L=JSON.parse(I),M=L;if(k)try{M=s.parse(L)}catch{M=s.parse(Gt(L))}p.debug("\u2705 [Codex] Structured output validated");let C=yt(E);return{raw:I,structured:M,...C?{usage:C}:{}}}return I||""}catch(w){let $=w.message||String(w);throw p.error(`\u274C [Codex] SDK call failed: ${$}`),$.includes("exited with code")&&(D.outputSchema&&p.error("\u{1F4A1} [Codex] An outputSchema was sent \u2014 an OpenAI strict-mode-invalid schema (a property missing from `required`) makes codex exit 1 here."),p.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),p.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),w}}finally{for(let y of g)y.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let o of e){let s=Do(o);if(!s){p.warn(`[Codex] Unknown skill "${o}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let c=s.serverName||o,a=re("codex",i,{processEnv:process.env});a&&(r[c]=a,p.debug(`[Codex] MCP: ${c} \u2192 ${i.command} ${(i.args||[]).join(" ")}`))}return r}_resolveCodexHome(e){return process.env.CODEX_HOME?process.env.CODEX_HOME:e&&!this._isTempPath(e)?Xe(e,".codex-home"):Xe(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 _t("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 o of e){let s=typeof o=="string"?o:o?.name,i=o&&typeof o=="object"?o.marketplacePath:null;if(!s||!i){p.warn(`[Codex][plugins] skipping malformed plugin declaration: ${JSON.stringify(o)} (need { name, marketplacePath })`);continue}let c=this._readMarketplaceName(i),a=`${s}@${c}`;if(this._isPluginInstalled(a,r)){p.info(`[Codex][plugins] ${a} already installed \u2014 skipping (idempotent)`),console.log(`\u25C6 [Codex] plugin ${a} already installed \u2014 skip`);continue}let l=this._safeMarketplacePath(i,t);p.info(`[Codex][plugins] installing ${a} from local marketplace ${l}`),console.log(`\u25C6 [Codex] installing plugin ${a} (local, no network)`);try{_t(`codex plugin marketplace add ${JSON.stringify(l)}`,{env:r,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),_t(`codex plugin add ${JSON.stringify(a)}`,{env:r,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),console.log(`\u25C6 [Codex] plugin ${a} installed`)}catch(u){let d=u.stderr&&u.stderr.toString()||u.message||String(u);throw p.error(`[Codex][plugins] failed to install ${a}: ${d}`),new Error(`Codex plugin install failed for ${a}: ${d}`,{cause:u})}}}_safeMarketplacePath(e,t){if(!String(e).includes("@"))return e;let r=Xe(t,".zibby-mkt",String(e).replace(/[^a-zA-Z0-9]+/g,"_"));try{return Ft(Xe(t,".zibby-mkt"),{recursive:!0}),Bo(e,r,{recursive:!0}),r}catch(o){return p.warn(`[Codex][plugins] could not copy @-containing marketplace to a safe path: ${o.message}`),e}}_readMarketplaceName(e){let t=Xe(e,".agents","plugins","marketplace.json"),r;try{r=JSON.parse(jo(t,"utf-8"))}catch(o){throw new Error(`Codex plugin marketplace manifest missing/unreadable at ${t}: ${o.message}`,{cause:o})}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 _t("codex plugin list",{env:t,stdio:"pipe",timeout:15e3,encoding:"utf-8"}).split(`
|
|
18
|
+
`).some(o=>o.includes(e)&&/installed/.test(o))}catch{return!1}}};import{AgentStrategy as Jo,getSkill as Ho}from"@zibby/agent-workflow";import{spawn as Yo}from"node:child_process";He();import{existsSync as Mr,mkdirSync as Ur,readFileSync as Dr,rmSync as Zo,writeFileSync as jr}from"node:fs";import{join as he}from"node:path";import{z as Lr}from"zod";import{zodToJsonSchema as Ko}from"zod-to-json-schema";function zo(n){if(!n)return null;if(typeof Lr?.toJSONSchema=="function")try{return Lr.toJSONSchema(n)}catch{}try{return Ko(n,{target:"openApi3"})}catch{return null}}var xt=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=zo(e):r=e;let o=this._buildExample(r);return`
|
|
19
19
|
\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
|
|
20
20
|
\u{1F6A8} MANDATORY: WRITE RESULT TO FILE \u{1F6A8}
|
|
21
21
|
\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
|
|
@@ -37,7 +37,7 @@ JSON types (strict \u2014 validators reject wrong types):
|
|
|
37
37
|
|
|
38
38
|
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[o,s]of Object.entries(e.properties))r[o]=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(o=>o.type!=="null")||e.anyOf?.find(o=>o.type!=="null");return r?this._buildExample(r):null}return"<value>"}};var Ie=class n{constructor(e=""){this.userPrompt=e,this.systemInstructions=[],this.metadata={}}setUserPrompt(e){return this.userPrompt=e,this}appendUserPrompt(e){return this.userPrompt?this.userPrompt+=`
|
|
39
39
|
|
|
40
|
-
${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=
|
|
40
|
+
${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=xt.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
|
|
41
41
|
\u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
42
42
|
\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
|
|
43
43
|
|
|
@@ -48,31 +48,31 @@ ${e.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:t,p
|
|
|
48
48
|
`)}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 n(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};var ae=class n{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(`
|
|
49
49
|
`);this.buffer=t.pop()||"";let r="";for(let o of t)if(o.trim())try{let s=JSON.parse(o);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+=`${o}
|
|
50
50
|
`,r+=`${o}
|
|
51
|
-
`,this.extractedResult=s)}catch{if(o.includes('"text"')||o.includes('"content"')){let i=o.match(/"text"\s*:\s*"([^"]*)/),c=o.match(/"content"\s*:\s*"([^"]*)/),a=i?i[1]:c?c[1]:null;a&&!this.rawText.includes(a)&&(r+=a,this.rawText+=a)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(i,c)=>{if(!i)return;let a=`${i}:${JSON.stringify(c??{})}`;this._lastToolEmit!==a&&(this._lastToolEmit=a,this.onToolCall(i,c??void 0))},r=i=>{if(i!=null){if(typeof i=="object"&&!Array.isArray(i))return i;if(typeof i=="string")try{return JSON.parse(i)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,r(e.input??e.arguments));return}let i=e.tool_call;if(i&&typeof i=="object"&&!Array.isArray(i)){let c=Object.keys(i);if(c.length===1){let a=c[0],l=i[a],u=l&&typeof l=="object"?l.args??l.input??l:void 0;t(a,r(u))}return}return}if(Array.isArray(e.tool_calls)){for(let i of e.tool_calls)t(i.name,r(i.input??i.arguments));return}let o=e.message??e;if(Array.isArray(o?.tool_calls)){for(let i of o.tool_calls)t(i.name,r(i.input??i.arguments));return}let s=o?.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,o;for(;(o=r.exec(e))!==null;){let d=o[1].trim();try{JSON.parse(d),t.push({text:d,source:"markdown"})}catch{}}let s=0,i=0;for(;s<e.length&&(s=e.indexOf("{",s),s!==-1);){let d=0,m=s;for(let f=s;f<e.length;f++)if(e[f]==="{")d++;else if(e[f]==="}"&&(d--,d===0)){m=f,t.push({text:e.substring(s,m+1),source:"brace"}),i++;break}s=m+1}let c=this.extractedResult,a=c?JSON.stringify(c).length:0,l=0,u=-1;for(let d=0;d<t.length;d++){let m=t[d];try{let f=m.text.replace(/,(\s*[}\]])/g,"$1"),g=JSON.parse(f);this.isValidResult(g)&&(l++,a=JSON.stringify(g).length,c=g,u=d)}catch{}}c&&(this.extractedResult=c)}isValidResult(e){if(!e||typeof e!="object"||Array.isArray(e)||e.session_id||e.timestamp_ms||e.type||e.call_id||e.tool_call||e.result&&typeof e.result=="object"&&(e.result.success&&typeof e.result.success=="object"||e.result.error&&typeof e.result.error=="object")||e.args&&typeof e.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(e),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(e,t=null){let r=new n;r.zodSchema=t,r.processChunk(e),r.flush();let o=r.getResult();return!o&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),o}};function
|
|
52
|
-
${v}`,"schema_instruction","append");let K=`zibby-result-${Date.now()}.json`,H=he(o,".zibby","tmp");A=he(H,K),
|
|
53
|
-
${v}`,"json_instruction","append")}let P=
|
|
51
|
+
`,this.extractedResult=s)}catch{if(o.includes('"text"')||o.includes('"content"')){let i=o.match(/"text"\s*:\s*"([^"]*)/),c=o.match(/"content"\s*:\s*"([^"]*)/),a=i?i[1]:c?c[1]:null;a&&!this.rawText.includes(a)&&(r+=a,this.rawText+=a)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(i,c)=>{if(!i)return;let a=`${i}:${JSON.stringify(c??{})}`;this._lastToolEmit!==a&&(this._lastToolEmit=a,this.onToolCall(i,c??void 0))},r=i=>{if(i!=null){if(typeof i=="object"&&!Array.isArray(i))return i;if(typeof i=="string")try{return JSON.parse(i)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,r(e.input??e.arguments));return}let i=e.tool_call;if(i&&typeof i=="object"&&!Array.isArray(i)){let c=Object.keys(i);if(c.length===1){let a=c[0],l=i[a],u=l&&typeof l=="object"?l.args??l.input??l:void 0;t(a,r(u))}return}return}if(Array.isArray(e.tool_calls)){for(let i of e.tool_calls)t(i.name,r(i.input??i.arguments));return}let o=e.message??e;if(Array.isArray(o?.tool_calls)){for(let i of o.tool_calls)t(i.name,r(i.input??i.arguments));return}let s=o?.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,o;for(;(o=r.exec(e))!==null;){let d=o[1].trim();try{JSON.parse(d),t.push({text:d,source:"markdown"})}catch{}}let s=0,i=0;for(;s<e.length&&(s=e.indexOf("{",s),s!==-1);){let d=0,m=s;for(let f=s;f<e.length;f++)if(e[f]==="{")d++;else if(e[f]==="}"&&(d--,d===0)){m=f,t.push({text:e.substring(s,m+1),source:"brace"}),i++;break}s=m+1}let c=this.extractedResult,a=c?JSON.stringify(c).length:0,l=0,u=-1;for(let d=0;d<t.length;d++){let m=t[d];try{let f=m.text.replace(/,(\s*[}\]])/g,"$1"),g=JSON.parse(f);this.isValidResult(g)&&(l++,a=JSON.stringify(g).length,c=g,u=d)}catch{}}c&&(this.extractedResult=c)}isValidResult(e){if(!e||typeof e!="object"||Array.isArray(e)||e.session_id||e.timestamp_ms||e.type||e.call_id||e.tool_call||e.result&&typeof e.result=="object"&&(e.result.success&&typeof e.result.success=="object"||e.result.error&&typeof e.result.error=="object")||e.args&&typeof e.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(e),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(e,t=null){let r=new n;r.zodSchema=t,r.processChunk(e),r.flush();let o=r.getResult();return!o&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),o}};function Vo(n){if(!n)return null;let e=String(n),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 o=0,s=!1,i=!1,c=-1;for(let a=r;a<e.length;a++){let l=e[a];if(s){i?i=!1:l==="\\"?i=!0:l==='"'&&(s=!1);continue}if(l==='"'){s=!0;continue}if(l==="{"){o===0&&(c=a),o+=1;continue}if(l==="}"){if(o===0)continue;if(o-=1,o===0&&c>=0){let u=e.slice(c,a+1);try{return JSON.parse(u)}catch{c=-1}}}}return null}function Wo(n){let e=String(n||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return Vo(e)}}function qo(n){try{let e=JSON.parse(n);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(o=>typeof o?.text=="string"?o.text:"").join("");if(r.trim())return r}}}catch{}return n}var ye=class extends Jo{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){return!(process.env.GEMINI_API_KEY||process.env.GEMINI_API_KEY_POOL||process.env.GOOGLE_API_KEY||process.env.GOOGLE_API_KEY_POOL)?(p.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1):St("gemini")?!0:(p.warn("[Gemini] gemini CLI not on PATH. Install: npm install -g @google/gemini-cli"),!1)}async invoke(e,t={}){let{model:r,workspace:o=process.cwd(),schema:s=null,images:i=[],skills:c=null,sessionPath:a=null,nodeName:l=null,timeout:u=600*1e3,signal:d=null}=t,m=[q("GEMINI_API_KEY"),q("GOOGLE_API_KEY")];try{let f=$e("gemini",r),g=Dt[f]||f,y=String(process.env.GEMINI_API_KEY||"").trim(),h=String(process.env.GOOGLE_API_KEY||"").trim(),b=this._resolveSkillsToMcp(c,{sessionPath:a,workspace:o,nodeName:l});for(let v of t.extraMcpServers||[])if(v&&v.serverName&&v.def){if(Object.prototype.hasOwnProperty.call(b,v.serverName)){console.warn(`[custom-mcp] skip "${v.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let K=re("gemini",v.def);K&&(b[v.serverName]=K)}let _=Object.keys(b).length>0,T=new Ie(e),S=s&&typeof s.parse=="function",A=null;if(s){let v;try{let K=S?de(s,{target:"openAi"}):s;v=JSON.stringify(K,null,2)}catch{v="{}"}if(_){T.addSystemInstruction(`Write valid JSON that matches this schema:
|
|
52
|
+
${v}`,"schema_instruction","append");let K=`zibby-result-${Date.now()}.json`,H=he(o,".zibby","tmp");A=he(H,K),Ur(H,{recursive:!0}),T.addStructuredOutput(s,A)}else T.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
|
|
53
|
+
${v}`,"json_instruction","append")}let P=T.build(),R=Array.isArray(i)?i.filter(v=>v&&typeof v.path=="string"&&v.path.startsWith("/")):[];R.length&&(P+=`
|
|
54
54
|
|
|
55
55
|
# Attached image files \u2014 VIEW THESE
|
|
56
|
-
The user attached ${
|
|
57
|
-
${
|
|
58
|
-
`)}`);let O=
|
|
56
|
+
The user attached ${R.length} image(s), saved locally. Read each path to SEE the image, then use what it shows to answer:
|
|
57
|
+
${R.map((v,K)=>` ${K+1}. ${v.path}${v.name?` (${v.name})`:""}`).join(`
|
|
58
|
+
`)}`);let O=T.getUserPrompt(),U=T.getStats(),z=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),k=z?` | key: ***${z.slice(-4)}`:" | key: not set";console.log(`
|
|
59
59
|
\u25C6 Model: ${g}${k}
|
|
60
60
|
`);let D=(await import("chalk")).default;console.log(`
|
|
61
|
-
${D.bold("Prompt sent to LLM:")}`),console.log(D.dim("\u2500".repeat(60))),console.log(D.dim(O)),console.log(D.dim("\u2500".repeat(60)));let j=this._createGeminiConfigDir(o,b),w=["--output-format","json"];w.push("--model",g);let $=Object.keys(b);if($.length>0){w.push("--approval-mode","yolo");for(let v of $)w.push("--allowed-mcp-server-names",v);p.info(`[Gemini] Enabling MCP servers: ${$.join(", ")}`)}else c&&c.length>0&&p.warn(`[Gemini] Skills requested but no MCP servers configured: ${c.join(", ")}`);w.push("-p",P);let I={...Ae(process.env),GEMINI_CLI_HOME:j,GEMINI_CLI_TRUST_WORKSPACE:"true"};y?(I.GEMINI_API_KEY=y,delete I.GOOGLE_API_KEY):h&&(I.GOOGLE_API_KEY=h,delete I.GEMINI_API_KEY),p.debug(`[Gemini] Command: gemini ${w.slice(0,8).join(" ")}... (${w.length} total args)`),p.debug(`[Gemini] User prompt: ${U.userPromptLength} chars, System instructions: ${U.systemInstructionsLength} chars (${U.instructionCount} blocks), Full: ${U.fullPromptLength} chars`),p.debug(`[Gemini] Config home: ${j}`),p.debug(`[Gemini] GEMINI_CLI_HOME env: ${I.GEMINI_CLI_HOME}`);let
|
|
61
|
+
${D.bold("Prompt sent to LLM:")}`),console.log(D.dim("\u2500".repeat(60))),console.log(D.dim(O)),console.log(D.dim("\u2500".repeat(60)));let j=this._createGeminiConfigDir(o,b),w=["--output-format","json"];w.push("--model",g);let $=Object.keys(b);if($.length>0){w.push("--approval-mode","yolo");for(let v of $)w.push("--allowed-mcp-server-names",v);p.info(`[Gemini] Enabling MCP servers: ${$.join(", ")}`)}else c&&c.length>0&&p.warn(`[Gemini] Skills requested but no MCP servers configured: ${c.join(", ")}`);w.push("-p",P);let I={...Ae(process.env),GEMINI_CLI_HOME:j,GEMINI_CLI_TRUST_WORKSPACE:"true"};y?(I.GEMINI_API_KEY=y,delete I.GOOGLE_API_KEY):h&&(I.GOOGLE_API_KEY=h,delete I.GEMINI_API_KEY),p.debug(`[Gemini] Command: gemini ${w.slice(0,8).join(" ")}... (${w.length} total args)`),p.debug(`[Gemini] User prompt: ${U.userPromptLength} chars, System instructions: ${U.systemInstructionsLength} chars (${U.instructionCount} blocks), Full: ${U.fullPromptLength} chars`),p.debug(`[Gemini] Config home: ${j}`),p.debug(`[Gemini] GEMINI_CLI_HOME env: ${I.GEMINI_CLI_HOME}`);let E="",L=null;try{E=await new Promise((K,H)=>{let se=Yo("gemini",w,{cwd:o,env:I,stdio:["ignore","pipe","pipe"],...d&&{signal:d}}),x="",X="",F=!1,N=null,B=!1,Y=setTimeout(()=>{try{se.kill("SIGTERM")}catch{}},u),Z=()=>{B||F||(B=!0,N=setTimeout(()=>{if(!F)try{se.kill("SIGKILL")}catch{}},5e3))};d&&(d.aborted?Z():d.addEventListener("abort",Z,{once:!0})),se.stdout.on("data",ee=>{x+=ee.toString()}),se.stderr.on("data",ee=>{X+=ee.toString()}),se.on("error",ee=>{if(clearTimeout(Y),N&&clearTimeout(N),d&&!d.aborted)try{d.removeEventListener("abort",Z)}catch{}H(ee)}),se.on("close",ee=>{if(F=!0,clearTimeout(Y),N&&clearTimeout(N),d&&!d.aborted)try{d.removeEventListener("abort",Z)}catch{}if(B){let Te=new Error("Aborted via signal");return Te.name="AbortError",H(Te)}if(ee===0)return K(x.trim());H(new Error(`gemini failed with code ${ee}: ${(X||x).trim()}`))})})}catch(v){L=v}finally{try{Zo(j,{recursive:!0,force:!0})}catch{}}let M=qo(E).trim();if(!s){if(L)throw L;return M}if(A){let v=Mr(A);if(p.info(`[Gemini] Result file: ${v?"present":"missing"} at ${A}`),v)try{let K=Dr(A,"utf-8").trim(),H=JSON.parse(K),se=S?s.parse(H):H;return p.info("[Gemini] Structured output recovered from result file"),{raw:M,structured:se}}catch(K){p.warn(`[Gemini] Result file parse/validation failed: ${K.message}`)}else L||p.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let C=null;if(s){let v=new ae;v.zodSchema=s,v.processChunk(M),v.flush(),C=v.getResult()}if(p.info(`[Gemini] Raw stdout length: ${E.length} chars`),p.info(`[Gemini] Extracted text length: ${M.length} chars`),p.info(`[Gemini] StreamParser result: ${C?"extracted":"null"}`),C||(M.length<2e3?p.info(`[Gemini] Raw text preview:
|
|
62
62
|
${M}`):p.info(`[Gemini] Raw text preview (first 1000 chars):
|
|
63
|
-
${M.slice(0,1e3)}`),C=
|
|
64
|
-
`,"utf-8");let u=he(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{
|
|
65
|
-
`,"utf-8")}catch{}return p.debug(`[Gemini] Created isolated config with ${Object.keys(l.mcpServers||{}).length} MCP servers`),p.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(l.mcpServers||{}),null,2)}`),o}};import{AgentStrategy as
|
|
63
|
+
${M.slice(0,1e3)}`),C=Wo(M)),!C)throw L||(p.error("[Gemini] Failed to extract valid JSON from output"),p.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error("Gemini did not return valid JSON for structured output. Enable strictMode for proxy fallback."));let G=S?s.parse(C):C;return{raw:M,structured:G}}finally{for(let f of m)f.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let o of e){let s=Ho(o);if(!s||typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let c=s.cursorKey||s.serverName||o,a=re("gemini",i);a&&(r[c]=a)}return r}_createGeminiConfigDir(e,t){let r=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,o=he(e||process.cwd(),".zibby","tmp",`gemini-home-${r}`),s=he(o,".gemini");Ur(s,{recursive:!0});let i=he(s,"settings.json"),c={},a=he(process.env.HOME||"",".gemini","settings.json");if(Mr(a))try{c=JSON.parse(Dr(a,"utf-8"))}catch{c={}}let l={...c,mcpServers:{...c.mcpServers&&typeof c.mcpServers=="object"?c.mcpServers:{},...t||{}}};jr(i,`${JSON.stringify(l,null,2)}
|
|
64
|
+
`,"utf-8");let u=he(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{jr(u,`${JSON.stringify(l,null,2)}
|
|
65
|
+
`,"utf-8")}catch{}return p.debug(`[Gemini] Created isolated config with ${Object.keys(l.mcpServers||{}).length} MCP servers`),p.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(l.mcpServers||{}),null,2)}`),o}};import{AgentStrategy as us,getSkill as vt}from"@zibby/agent-workflow";var Ce=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 be=class extends Ce{formatTools(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters||t.input_schema||{type:"object",properties:{}}}}))}hasToolCalls(e){let t=e.choices?.[0]?.message;return!!(t?.tool_calls&&t.tool_calls.length>0)}parseToolCalls(e){return(e.choices?.[0]?.message?.tool_calls||[]).map(r=>({id:r.id,name:r.function.name,args:JSON.parse(r.function.arguments||"{}")}))}getTextContent(e){return e.choices?.[0]?.message?.content||""}buildAssistantMessage(e){return e.choices?.[0]?.message}buildToolResultMessage(e,t){return{role:"tool",tool_call_id:e,content:typeof t=="string"?t:JSON.stringify(t)}}injectToolsIntoBody(e,t){return t.length>0&&(e.tools=t),e}};var Qe=class{async fetchCompletion(e,t,r={}){throw new Error("fetchCompletion() must be implemented")}async fetchStreamingCompletion(e,t,r={}){throw new Error("fetchStreamingCompletion() must be implemented")}};function wt(n){return Buffer.byteLength(JSON.stringify(n),"utf8")}function Et(n,e){let t=String(n||"");if(t.length<=e)return t;let r=Math.max(0,e-28);return`${t.slice(0,r)}
|
|
66
66
|
|
|
67
|
-
[truncated for size budget]`}function
|
|
68
|
-
`);f=_.pop();for(let
|
|
69
|
-
`)||"",isError:s.isError||!1}}isRunning(e){return this.#e.has(e)}async stopServer(e){let t=this.#e.get(e);if(t){try{await t.client.close()}catch(r){p.debug(`[MCP] Error closing ${e}: ${r.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}};import{existsSync as
|
|
67
|
+
[truncated for size budget]`}function Kt(n,e=0){if(!n||typeof n!="object"||e>8)return n;if(Array.isArray(n))return n.map(r=>Kt(r,e+1));let t={};for(let[r,o]of Object.entries(n))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=Kt(o,e+1));return t}function Xo(n=[]){return n.map(e=>({...e,function:{...e.function,description:Et(e.function?.description||"",180),parameters:Kt(e.function?.parameters||{type:"object",properties:{}})}}))}function Br(n){let e=new Set;for(let o of n)if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let s of o.tool_calls)e.add(s.id);let t=n.filter(o=>o.role==="tool"?e.has(o.tool_call_id):!0),r=new Set;for(let o of t)o.role==="tool"&&r.add(o.tool_call_id);return t.map(o=>{if(o.role!=="assistant"||!Array.isArray(o.tool_calls)||o.tool_calls.every(a=>r.has(a.id)))return o;let{tool_calls:i,...c}=o;return{...c,content:c.content||""}})}function zt(n,e={}){let t=e.maxBytes||49e3,r=e.systemMaxChars||12e3,o={...n,messages:Array.isArray(n.messages)?[...n.messages]:[],tools:Array.isArray(n.tools)?Xo(n.tools):n.tools};o.messages.length>0&&o.messages[0]?.role==="system"&&(o.messages[0]={...o.messages[0],content:Et(o.messages[0].content,r)});let s=!1;for(;wt(o)>t&&o.messages.length>2;)o.messages.splice(1,1),s=!0;if(s&&(o.messages=Br(o.messages)),wt(o)>t&&o.messages.length>0&&(o.messages[0]={...o.messages[0],content:Et(o.messages[0].content,6e3)},s=!0),wt(o)>t){let i=o.messages.find(a=>a.role==="system")||o.messages[0],c=o.messages.slice(-2);o.messages=Br([i,...c].filter(Boolean).map((a,l)=>({...a,content:Et(a.content,l===0?4e3:8e3)}))),s=!0}return{body:o,meta:{bytes:wt(o),trimmed:s,maxBytes:t,messageCount:o.messages.length}}}var Fr=n=>Buffer.byteLength(JSON.stringify(n),"utf8"),Pe=class extends Qe{async fetchCompletion(e,t,r={}){let o=Fr(e),{body:s,meta:i}=zt(e,r.payloadCompaction);r.onBudget?.({streaming:!1,beforeBytes:o,meta:i});let c=this.#e(r),a=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,l=await fetch(a,{method:"POST",headers:t.headers,body:JSON.stringify(s),signal:c});if(!l.ok){let u=await l.text();throw l.status===401||l.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${l.status}: ${u}`)}return l.json()}async fetchStreamingCompletion(e,t,r={}){let o={...e,stream:!0},s=Fr(o),{body:i,meta:c}=zt(o,r.payloadCompaction);r.onBudget?.({streaming:!0,beforeBytes:s,meta:c});let a=this.#e(r),l=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,u=await fetch(l,{method:"POST",headers:t.headers,body:JSON.stringify(i),signal:a});if(!u.ok){let h=await u.text();throw u.status===401||u.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${u.status}: ${h}`)}let d=u.body.getReader(),m=new TextDecoder,f="",g="",y=new Map;for(;;){let{done:h,value:b}=await d.read();if(h)break;f+=m.decode(b,{stream:!0});let _=f.split(`
|
|
68
|
+
`);f=_.pop();for(let T of _){if(!T.startsWith("data: "))continue;let S=T.slice(6).trim();if(S==="[DONE]")continue;let A;try{A=JSON.parse(S)}catch{continue}let P=A.choices?.[0]?.delta;if(P&&(P.content&&(g+=P.content,r.onToken&&r.onToken(P.content)),P.tool_calls))for(let R of P.tool_calls){let O=R.index??0;y.has(O)||y.set(O,{id:"",name:"",args:""});let U=y.get(O);R.id&&(U.id=R.id),R.function?.name&&(U.name=R.function.name),R.function?.arguments!=null&&(U.args+=R.function.arguments)}}}if(y.size>0){let h=[...y.entries()].sort(([b],[_])=>b-_).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 Qo}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as es}from"@modelcontextprotocol/sdk/client/stdio.js";var et=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:r,args:o=[],env:s={}}=t;p.debug(`[MCP] Starting ${e}: ${r} ${o.join(" ")}`);let i=new es({command:r,args:o,env:{...process.env,...s}}),c=new Qo({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await c.connect(i);let a={client:c,transport:i,serverConfig:t};return this.#e.set(e,a),a}async callTool(e,t,r={}){let o=this.#e.get(e);if(!o)throw new Error(`MCP server "${e}" not running`);p.debug(`[MCP] ${e}.${t}(${JSON.stringify(r).slice(0,200)})`);let s=await o.client.callTool({name:t,arguments:r});return{text:s.content?.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
69
|
+
`)||"",isError:s.isError||!1}}isRunning(e){return this.#e.has(e)}async stopServer(e){let t=this.#e.get(e);if(t){try{await t.client.close()}catch(r){p.debug(`[MCP] Error closing ${e}: ${r.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}};import{existsSync as ts,readFileSync as rs}from"node:fs";import{join as ns}from"node:path";import{homedir as os}from"node:os";function ss(){try{let n=ns(os(),".zibby","config.json");return ts(n)?JSON.parse(rs(n,"utf-8")):{}}catch{return{}}}function Tt(n){return String(n||"").replace(/\/v1\/?$/,"")}function is(n,e){let t=process.env.OPENAI_PROXY_URL;if(t)return Tt(t);if(n==="session")return e.proxyUrl?Tt(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(n==="byok"){let r=process.env.OPENAI_BASE_URL;return Tt(r||"https://api.openai.com")}return Tt(t||"")}function Jt(){let n=ss(),e=process.env.ZIBBY_USER_TOKEN||n.sessionToken||null,t=process.env.OPENAI_API_KEY||null,r=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),o=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&&o&&(i="local");let c=is(i,n),a={"Content-Type":"application/json"};if(i==="session"){if(!e)return{ok:!1,mode:i,reason:"missing_session_token"};a.Authorization=`Bearer ${e}`}else if(i==="byok"){if(!t)return{ok:!1,mode:i,reason:"missing_openai_api_key"};a.Authorization=`Bearer ${t}`}else if(i==="local"){if(!c)return{ok:!1,mode:i,reason:"missing_openai_proxy_url"};!o&&t&&(a.Authorization=`Bearer ${t}`)}return c?{ok:!0,mode:i,baseUrl:c,headers:a,tokenPreview:a.Authorization?`***${a.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:i,reason:"missing_base_url"}}function At(n,e){let t=String(n??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
|
|
70
70
|
|
|
71
|
-
[tool result truncated for size]`}function
|
|
71
|
+
[tool result truncated for size]`}function as(n,e){if(typeof n=="string")return At(n,e);try{return At(JSON.stringify(n),e)}catch{return At(String(n),e)}}function Gr(n){let e=new Set;for(let o of n)if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let s of o.tool_calls)e.add(s.id);let t=n.filter(o=>o.role==="tool"?e.has(o.tool_call_id):!0),r=new Set;for(let o of t)o.role==="tool"&&r.add(o.tool_call_id);return t.map(o=>{if(o.role!=="assistant"||!Array.isArray(o.tool_calls)||o.tool_calls.every(a=>r.has(a.id)))return o;let{tool_calls:i,...c}=o;return{...c,content:c.content||""}})}function ls(n){let e=Array.isArray(n?.messages)?n.messages:[],t=e.find(s=>s.role==="system"),r=e.slice(-4).map(s=>({...s,content:At(s.content,s.role==="tool"?1200:2500)}));r=Gr(r);let o={...n,messages:[t,...r].filter(Boolean)};return delete o.tools,o}async function cs({body:n,streaming:e,auth:t,options:r,fetchCompletion:o,fetchStreamingCompletion:s,onFallbackLog:i}){try{return e?await s(n,t,r):await o(n,t,r)}catch(c){let a=String(c?.message||c||"");if(!/proxy error 413|payload too large/i.test(a))throw c;let l=ls(n);return typeof i=="function"&&i(n,l),{data:e?await s(l,t,r):await o(l,t,r),fallback:l}}}async function Kr({body:n,auth:e,options:t,streaming:r,toolContext:o,activeSkills:s,round:i,verbose:c,dependencies:a,config:l={}}){let u=l.maxToolResultChars||3e3,{fetchCompletion:d,fetchStreamingCompletion:m,onFallbackLog:f,hasToolCalls:g,getTextContent:y,parseToolCalls:h,buildAssistantMessage:b,buildToolResultMessage:_,executeTool:T,onToolCallLog:S,injectTools:A}=a;Array.isArray(n?.messages)&&(n.messages=Gr(n.messages));let P=await cs({body:n,streaming:r,auth:e,options:t,fetchCompletion:d,fetchStreamingCompletion:m,onFallbackLog:f}),R=P?.data||P;if(!g(R))return{done:!0,text:y(R),body:P?.fallback||n};let O=h(R),U=P?.fallback||n;U.messages.push(b(R)),c&&typeof S=="function"&&S(O);let z=await Promise.all(O.map((k,D)=>(typeof t.onToolCall=="function"&&t.onToolCall(k.name,k.args,{round:i,index:D,total:O.length}),T(k,o))));for(let k=0;k<O.length;k++){let j=O[k].name==="get_skill_context"?typeof z[k]=="string"?z[k]:JSON.stringify(z[k]):as(z[k],u);U.messages.push(_(O[k].id,j))}return typeof t.onToolCall=="function"&&t.onToolCall(null),A(U,s),{done:!1,body:U}}var ps=ce.ASSISTANT,fs=15,Ht="get_skill_context";function Ne(n){!n||typeof n!="object"||(n.type==="object"&&n.properties&&(n.required=Object.keys(n.properties),n.additionalProperties=!1,Object.values(n.properties).forEach(Ne)),n.type==="array"&&n.items&&Ne(n.items),n.anyOf&&n.anyOf.forEach(Ne),n.oneOf&&n.oneOf.forEach(Ne),n.allOf&&n.allOf.forEach(Ne))}var zr={maxBytes:49e3,systemMaxChars:12e3},ke=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",ds=n=>Buffer.byteLength(JSON.stringify(n),"utf8");function $t(n){return Array.isArray(n)?new Set(n.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function ms(n){return Array.isArray(n)?n.map(e=>String(e||"").trim()).filter(Boolean):[]}var Se=class extends us{#e;#t;#r=new et;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new be,this.#t=e.completionProvider||new Pe):(this.#e=e||new be,this.#t=new Pe)}canHandle(e){return Jt().ok}async invoke(e,t={}){let r=q("OPENAI_API_KEY");try{let o=t.model||ps,s=Jt();if(!s.ok)throw s.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):s.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):s.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${s.reason}).`);let i=t.messages||[{role:"user",content:e}],c=s.baseUrl,a=ke();if(a?await this.#m(i,o,c,s.tokenPreview||"none"):p.debug(`[Assistant] ${c} | model: ${o} | messages: ${i.length}`),t.schema)return this.#c(o,i,s,t);let l=t.activeSkills||[],u=this.#p(t),d=this.#f(l,u),m=this.#d(d),f=this.#u(t),g={...t,payloadCompaction:f},y={activeSkills:d,options:g,executionRegistry:m,capabilityPolicy:u},h=!!t.stream,b={model:o,messages:[...i],stream:!1};this.#o(b,d,u);for(let _=0;_<fs;_++){if(t.signal?.aborted){let S=new Error("Aborted via signal");throw S.name="AbortError",S}let T=await Kr({body:b,auth:s,options:g,streaming:h,toolContext:y,activeSkills:d,round:_,verbose:a,dependencies:{fetchCompletion:this.#s.bind(this),fetchStreamingCompletion:this.#l.bind(this),onFallbackLog:(S,A)=>{ke()&&console.log(`413 fallback: messages ${S.messages.length} -> ${A.messages.length}, bytes=${ds(A)}`)},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,A)=>this.#e.buildToolResultMessage(S,A),executeTool:(S,A)=>this.#a(S,A),onToolCallLog:async S=>{let A=(await import("chalk")).default;console.log(A.dim(` ${S.map(P=>`${P.name}(${JSON.stringify(P.args).slice(0,80)})`).join(", ")}`))},injectTools:(S,A)=>this.#o(S,A,u)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(T.done)return T.text;b.messages=T.body.messages,T.body.tools?b.tools=T.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 o=this.#i(t,r),s=this.#e.formatTools(o);this.#e.injectToolsIntoBody(e,s)}#i(e,t=null){let r=[],o=new Set;for(let s of e){let i=vt(s);if(i?.tools?.length)for(let c of i.tools)this.#n(c.name,t)&&(o.has(c.name)||(o.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(Ht,t)&&r.push({name:Ht,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:o,executionRegistry:s,capabilityPolicy:i}=t;if(!this.#n(e.name,i))return`Tool "${e.name}" blocked by policy`;if(e.name===Ht){let l=String(e.args?.skillId||"").trim();if(!l)return JSON.stringify({error:"skillId is required"});if(!r.includes(l))return JSON.stringify({error:`Skill "${l}" is not active`,activeSkills:r});let u=vt(l);if(!u)return JSON.stringify({error:`Skill "${l}" not found`});let d=typeof u.promptFragment=="function"?u.promptFragment():u.promptFragment||"",m=(u.tools||[]).map(g=>g.name),f=JSON.stringify({skillId:l,description:u.description||"",toolNames:m,promptFragment:d||""});return ke()&&(console.log(`
|
|
72
72
|
\u{1F4D6} get_skill_context("${l}") \u2192 ${f.length} chars (fragment: ${d.length} chars)`),console.log(` tools: [${m.join(", ")}]`),console.log(` fragment preview: ${d.slice(0,200).replace(/\n/g,"\\n")}\u2026
|
|
73
|
-
`)),f}let c=s?.get(e.name)||null;if(!c)return`Unknown tool: ${e.name}`;let a=
|
|
73
|
+
`)),f}let c=s?.get(e.name)||null;if(!c)return`Unknown tool: ${e.name}`;let a=vt(c.skillId);if(!a)return`Skill "${c.skillId}" not found for tool "${e.name}"`;if(c.mode==="handler")try{return a.handleToolCall(e.name,e.args,t)}catch(l){return`Error in ${e.name}: ${l.message}`}if(c.mode==="mcp")try{if(!this.#r.isRunning(a.serverName)){let u=a.resolve(o);if(!u)return`Skill "${c.skillId}" is not available (cannot start server)`;await this.#r.ensureServer(a.serverName,u)}let l=await this.#r.callTool(a.serverName,e.name,e.args);return l.text||(l.isError?"Tool call failed":"Done")}catch(l){return`MCP error (${a.serverName}): ${l.message}`}return`Skill "${c.skillId}" owns tool "${e.name}" but has no execution mode`}async#l(e,t,r){return this.#t.fetchStreamingCompletion(e,t,{...r,onBudget:({beforeBytes:o,meta:s})=>{ke()&&console.log(`payload bytes (stream) before=${o} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#s(e,t,r){return this.#t.fetchCompletion(e,t,{...r,onBudget:({beforeBytes:o,meta:s})=>{ke()&&console.log(`payload bytes before=${o} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#c(e,t,r,o){let{zodToJson:s}=await Promise.resolve().then(()=>(He(),Er)),i=typeof o.schema?.parse=="function",c=i?s(o.schema,{}):o.schema;delete c.$schema,Ne(c);let a={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:c,strict:!0}}},l=await this.#s(a,r,o),u=this.#e.getTextContent(l),d=JSON.parse(u),m=i?o.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||zr.maxBytes),systemMaxChars:Number(t.systemMaxChars||zr.systemMaxChars)}}#p(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:$t(t.allowTools||e.allowTools),denyTools:$t(t.denyTools||e.denyTools),denyPrefixes:ms(t.denyPrefixes||e.denyToolPrefixes),includeSkills:$t(t.includeSkills||e.includeSkills),excludeSkills:$t(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#f(e,t){let r=t?.includeSkills||new Set,o=t?.excludeSkills||new Set;return r.size===0&&o.size===0?e:e.filter(s=>!(r.size>0&&!r.has(s)||o.has(s)))}#n(e,t){let r=String(e||"").trim();if(!r)return!1;let o=t?.allowTools;if(o&&o.size>0&&!o.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 o of e){let s=vt(o);if(!s?.tools?.length)continue;let i=typeof s.handleToolCall=="function"?"handler":s.serverName&&typeof s.resolve=="function"?"mcp":null;if(i)for(let c of s.tools){let a=String(c?.name||"").trim();if(a){if(t.has(a)){r.push({tool:a,winner:t.get(a).skillId,skipped:o});continue}t.set(a,{skillId:o,mode:i})}}}if(r.length>0&&ke()){let o=r.slice(0,5).map(s=>`${s.tool}:${s.winner}>${s.skipped}`).join(", ");console.log(`tool registry collisions: ${o}${r.length>5?" ...":""}`)}return t}async#m(e,t,r,o){console.log(`
|
|
74
74
|
\u25C6 Model: ${t} | proxy: ${r} | token: ${o||"none"}
|
|
75
|
-
`);let s=(await import("chalk")).default;console.log(s.bold("Prompt sent to LLM:")),console.log(s.dim("\u2500".repeat(60)));let i=!1;for(let c of e)if(c.role==="system")console.log(s.dim(`[System] ${c.content||""}`));else{i||(console.log(s.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),i=!0);let a=c.role==="user"?"Human":"AI",l=c.content?.length>200?`${c.content.slice(0,200)}...`:c.content||"";console.log(s.dim(`[${a}] ${l}`))}console.log(s.dim("\u2500".repeat(60)))}};var
|
|
75
|
+
`);let s=(await import("chalk")).default;console.log(s.bold("Prompt sent to LLM:")),console.log(s.dim("\u2500".repeat(60)));let i=!1;for(let c of e)if(c.role==="system")console.log(s.dim(`[System] ${c.content||""}`));else{i||(console.log(s.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),i=!0);let a=c.role==="user"?"Human":"AI",l=c.content?.length>200?`${c.content.slice(0,200)}...`:c.content||"";console.log(s.dim(`[${a}] ${l}`))}console.log(s.dim("\u2500".repeat(60)))}};var Jr=!1;function Yt(){Jr||(Ot(new Se),Ot(new me),Ot(new ge),Ot(new ye),Jr=!0)}function Hr(n){return null}import{spawn as _s}from"node:child_process";import{mkdirSync as Zr,existsSync as xs,writeFileSync as ws}from"node:fs";import{join as qt}from"node:path";import{ContextLoader as Es,WorkflowGraph as Ts,Node as As,WorkflowState as vs,DEFAULT_OUTPUT_BASE as Vr,SESSIONS_DIR as $s,SESSION_INFO_FILE as Os}from"@zibby/agent-workflow";import{exec as gs}from"node:child_process";import{promisify as hs}from"node:util";import{existsSync as ys}from"node:fs";import{join as Zt}from"node:path";import{homedir as Vt}from"node:os";var Yr=hs(gs);async function Wt(){try{return await Yr("cursor-agent --version"),"cursor-agent"}catch{let e=[Zt(Vt(),".local","bin","cursor-agent"),Zt(Vt(),".cursor","bin","cursor-agent"),Zt(Vt(),".cursor-agent","bin","cursor-agent")];for(let t of e)if(ys(t))try{return await Yr(`"${t}" --version`),t}catch{}return null}}async function bs(){return await Wt()!==null}function Ss(){return`
|
|
76
76
|
\u274C cursor-agent CLI not found!
|
|
77
77
|
|
|
78
78
|
To use the Cursor agent, install it from:
|
|
@@ -98,22 +98,22 @@ ${c}
|
|
|
98
98
|
`);let a=null;if(o)try{if(a=n.extractJsonFromStream(c),!a)throw new Error("No valid result JSON found in output");console.log(`
|
|
99
99
|
\u2705 Parsed Output:
|
|
100
100
|
${JSON.stringify(a,null,2)}
|
|
101
|
-
`)}catch(l){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${l.message}`)}return{success:!0,output:a,raw:c}}async cleanup(){this.adapter&&this.adapter.isConnected()&&await this.adapter.disconnect()}async executePrompt(e,t=process.cwd(),r=3e5,o=null,s=!0){let i=this.agentCommand;if(i==="cursor-agent"){let c=await
|
|
101
|
+
`)}catch(l){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${l.message}`)}return{success:!0,output:a,raw:c}}async cleanup(){this.adapter&&this.adapter.isConnected()&&await this.adapter.disconnect()}async executePrompt(e,t=process.cwd(),r=3e5,o=null,s=!0){let i=this.agentCommand;if(i==="cursor-agent"){let c=await Wt();c&&(i=c)}return new Promise((c,a)=>{let l="",u=this.buildArgs(e,s);o&&u.push("--model",o);let d={...process.env},m=_s(i,u,{cwd:t,env:d,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),f=setTimeout(()=>{console.log(`
|
|
102
102
|
\u23F1\uFE0F Timeout reached (${r/1e3}s) - killing agent...`),m.kill("SIGTERM"),setTimeout(()=>{m.killed||(console.log("\u26A0\uFE0F Forcing kill (SIGKILL)..."),m.kill("SIGKILL"))},2e3),a(new Error(`Agent timed out after ${r/1e3}s. The agent may be stuck or waiting for user input.`))},r),g=0,y=Date.now(),h=setInterval(()=>{if(l.length>g)g=l.length,y=Date.now();else{let S=Date.now()-y;S>1e4&&console.log(`\u23F3 AI agent is thinking... (${Math.floor(S/1e3)}s, ${l.length} bytes so far)`)}},1e4),b=()=>{clearTimeout(f),clearInterval(h),m&&!m.killed&&(m.kill("SIGTERM"),setTimeout(()=>{m.killed||m.kill("SIGKILL")},2e3))},_=()=>{console.log(`
|
|
103
103
|
|
|
104
|
-
\u{1F6D1} Interrupted by user (Ctrl+C)`),b(),a(new Error("Interrupted by user"))};process.on("SIGINT",_);let
|
|
104
|
+
\u{1F6D1} Interrupted by user (Ctrl+C)`),b(),a(new Error("Interrupted by user"))};process.on("SIGINT",_);let T=new ae;m.stdout.on("data",S=>{let A=S.toString();l+=A;let P=T.processChunk(A);P&&(process.stdout.write(P,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),y=Date.now(),g+=P.length)}),m.on("close",S=>{process.off("SIGINT",_),clearTimeout(f),clearInterval(h);let A=T.flush();A&&process.stdout.write(A),l=T.getRawText();let P=T.getResult();S===0?c({raw:l,extracted:P}):a(new Error(`Agent exited with code ${S}`))}),m.on("error",S=>{process.off("SIGINT",_),clearTimeout(f),clearInterval(h),a(new Error(`Failed to spawn agent: ${S.message}`))})})}async runSingleNode(e,t,r){let o=t[e];if(!o)throw new Error(`Unknown node: ${e}. Available nodes: ${Object.keys(t).join(", ")}`);let{cwd:s}=r;if(!s)throw new Error("cwd is required for single node execution");let i=r.sessionPath,c=r.sessionTimestamp,a=r.config||{};if(!i){let h=process.env.CI_JOB_ID||process.env.GITHUB_RUN_ID||process.env.CIRCLE_WORKFLOW_ID||process.env.BUILD_ID||Date.now().toString(),b=a.paths?.sessionPrefix,_=b?`${b}_${h}`:h;c=c||Date.now();let T=a.paths?.output||Vr;i=qt(s,T,$s,_),xs(i)||Zr(i,{recursive:!0})}let l=a.paths?.output||Vr,u=qt(s,l,Os);Zr(qt(s,l),{recursive:!0}),ws(u,JSON.stringify({sessionPath:i,sessionTimestamp:c||i.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
|
|
105
105
|
${"=".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)}
|
|
106
|
-
`);let d=await
|
|
106
|
+
`);let d=await Es.loadContext(r.specPath||"",s,r.contextConfig||{}),m=new vs({...r,sessionPath:i,sessionTimestamp:c,context:d}),g=await new As(o).execute(this,m);return console.log(`
|
|
107
107
|
${"=".repeat(80)}`),console.log(`\u2705 Node ${e} completed`),console.log(`${"=".repeat(80)}
|
|
108
|
-
`),{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 o=e.replace(new RegExp(`^${t}/`),"").replace(/\.[^.]+$/,".spec.js");return`${r}/${o}`.replace(/\/+/g,"/")}};function
|
|
108
|
+
`),{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 o=e.replace(new RegExp(`^${t}/`),"").replace(/\.[^.]+$/,".spec.js");return`${r}/${o}`.replace(/\/+/g,"/")}};function Is(n,e={}){let t=new Re(e);return t.buildGraph=function(){let r=new Ts;return n(r),r},e.onComplete&&(t.onComplete=e.onComplete),t}import{WorkflowGraph as yd,resolveWorkflowSession as bd,generateWorkflowSessionId as Sd,clearInheritedSessionEnvForFreshRun as _d,shouldTrustInheritedSessionEnv as xd,readPinnedSessionPathFromEnv as wd,syncProcessEnvToSession as Ed}from"@zibby/agent-workflow";import{writeFileSync as Wr,existsSync as Cs,mkdirSync as Ps}from"node:fs";import{join as Xt}from"node:path";var Qt=class n{static saveTitle(e,t){let r=e.state.sessionPath;if(!r)return;let o=n._findInState(e.state,"title")||n._findInState(e.state,"result");if(!(!o||typeof o!="string"))try{let s=Xt(r,"title.txt");Wr(s,o,"utf-8"),p.info(`Saved title to session: "${o}"`)}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,o]of Object.entries(e.state)){if(!o||typeof o!="object")continue;let s=Array.isArray(o.actions)&&o.actions.length>0,i=typeof o.scriptPath=="string"&&o.scriptPath.trim().length>0;if(!(!s&&!i))try{let c=Xt(t,r);Cs(c)||Ps(c,{recursive:!0});let a=Xt(c,"result.json");Wr(a,JSON.stringify(o,null,2),"utf-8"),p.info(`Saved execution data to ${r} folder`),await this.onNodeSaved(c,o)}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),o=r.length>0&&r.every(([,i])=>i.success),s=r.some(([,i])=>i.success===!1);if(o)p.info("Workflow completed successfully."),t&&p.info(`Output: ${t}`);else if(s){let i=r.filter(([,c])=>!c.success).map(([c])=>c);p.info(`Workflow completed with failures in: ${i.join(", ")}`),t&&p.info(`Output: ${t}`)}return o}static handle(e,t,r){return this.saveTitle(e,t),this.saveExecutionData(e),this.logResult(e,r)}};import{z as vd}from"zod/v3";import{resolveInvocationModel as ci,resolveInvocationExtras as ui}from"@zibby/agent-workflow";import{AgentStrategy as Zs,DEFAULT_OUTPUT_BASE as Vs,SESSION_INFO_FILE as Ws,STOP_REQUEST_FILE as qs,getAllSkills as Xs,getSkill as rn}from"@zibby/agent-workflow";import{spawn as Qs,execSync as _e}from"node:child_process";import{writeFileSync as nn,readFileSync as on,mkdirSync as sn,existsSync as tt,accessSync as an,constants as ln,unlinkSync as ei}from"node:fs";import{join as oe,resolve as ti}from"node:path";import{homedir as rt}from"node:os";import ks from"axios";import{homedir as Ns}from"node:os";import{join as Rs}from"node:path";import{existsSync as Ls,readFileSync as Ms}from"node:fs";import{toJSONSchema as Us}from"zod";function Ds(){if(process.env.OPENAI_PROXY_TOKEN)return p.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return p.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let n=Rs(Ns(),".zibby","config.json");if(Ls(n)){let e=JSON.parse(Ms(n,"utf-8"));if(e.sessionToken)return p.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(n){p.debug(`[Auth] Could not read zibby login session: ${n.message}`)}return null}function js(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function Le(n){if(!(typeof n!="object"||n===null)){if(Object.keys(n).length===0){n.type="object",n.additionalProperties=!0;return}if(n.type||(n.properties?n.type="object":n.items&&(n.type="array")),n.type==="object")if(n.properties){for(let[e,t]of Object.entries(n.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(n.properties[e]={type:["object","null"]});n.additionalProperties=!1,n.required=Object.keys(n.properties),Object.values(n.properties).forEach(Le)}else"additionalProperties"in n||(n.additionalProperties=!0);n.type==="array"&&n.items&&Le(n.items),n.anyOf&&n.anyOf.forEach(Le),n.oneOf&&n.oneOf.forEach(Le),n.allOf&&n.allOf.forEach(Le)}}async function qr(n,e){p.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=Ds();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=js();p.info(`\u{1F517} Using OpenAI proxy: ${r}`);let o=Us(e),s=o;if(o.$ref&&o.definitions){let u=o.$ref.split("/").pop();s=o.definitions[u]||o,p.debug(`Extracted schema from $ref: ${u}`)}delete s.$schema,Le(s);let i=4e5,c=n;n.length>i&&(p.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${n.length} chars) exceeds limit, keeping last ${i} chars`),c=`... [truncated early content] ...
|
|
109
109
|
${n.slice(-i)}`);let a=`Extract and format the following information into structured JSON matching the schema.
|
|
110
110
|
|
|
111
111
|
RAW CONTENT:
|
|
112
112
|
${c}
|
|
113
113
|
|
|
114
|
-
Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,l={model:ce.OPENAI_POSTPROCESSING,messages:[{role:"user",content:a}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:s,strict:!0}}};p.info(`\u{1F4E4} Sending to OpenAI proxy: model=${ce.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(s.properties||{}).join(", ")}`),p.debug(` Schema size: ${JSON.stringify(s).length} chars`),p.debug(` Prompt size: ${a.length} chars`);try{let u={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(u["x-proxy-token"]=t,u["x-execution-id"]=process.env.EXECUTION_ID||""):(u.Authorization=`Bearer ${t}`,u["x-api-key"]=process.env.ZIBBY_API_KEY||"",u["x-execution-id"]=process.env.EXECUTION_ID||"");let m=(await
|
|
114
|
+
Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,l={model:ce.OPENAI_POSTPROCESSING,messages:[{role:"user",content:a}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:s,strict:!0}}};p.info(`\u{1F4E4} Sending to OpenAI proxy: model=${ce.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(s.properties||{}).join(", ")}`),p.debug(` Schema size: ${JSON.stringify(s).length} chars`),p.debug(` Prompt size: ${a.length} chars`);try{let u={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(u["x-proxy-token"]=t,u["x-execution-id"]=process.env.EXECUTION_ID||""):(u.Authorization=`Bearer ${t}`,u["x-api-key"]=process.env.ZIBBY_API_KEY||"",u["x-execution-id"]=process.env.EXECUTION_ID||"");let m=(await ks.post(r,l,{headers:u,timeout:ht.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!m)throw new Error("OpenAI proxy returned empty response");let f=JSON.parse(m);return p.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:f,raw:n}}catch(u){if(u.response){let d=u.response.status,m=u.response.data;throw p.error(`\u274C OpenAI proxy request failed: ${d}`),p.error(` Status: ${d}`),p.error(` Response: ${JSON.stringify(m,null,2)}`),d===401||d===403?new Error(`Authentication failed for OpenAI proxy.
|
|
115
115
|
Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
|
|
116
|
-
Response: ${JSON.stringify(m)}`,{cause:u}):new Error(`Failed to format Cursor output: ${m?.error?.message||"Unknown error"}`,{cause:u})}throw p.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}import{copyFileSync as
|
|
116
|
+
Response: ${JSON.stringify(m)}`,{cause:u}):new Error(`Failed to format Cursor output: ${m?.error?.message||"Unknown error"}`,{cause:u})}throw p.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}import{copyFileSync as Bs,existsSync as er,lstatSync as Fs,mkdirSync as Xr,rmSync as Gs,symlinkSync as Ks,unlinkSync as zs}from"node:fs";import{join as le}from"node:path";import{homedir as Js}from"node:os";import{randomBytes as Hs}from"node:crypto";var Ys=["cli-config.json","config.json","auth.json","argv.json"];function Qr(n){return!(!n||typeof n!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function en(n){let e=le(n||process.cwd(),".zibby","tmp");Xr(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${Hs(4).toString("hex")}`,r=le(e,`cursor-agent-home-${t}`),o=le(r,".cursor");Xr(o,{recursive:!0});let s=Js(),i=le(s,".cursor");if(er(i))for(let c of Ys){let a=le(i,c);if(er(a))try{Bs(a,le(o,c))}catch{}}if(process.platform==="darwin"){let c=le(s,"Library");if(er(c))try{Ks(c,le(r,"Library"))}catch{}}return r}function tn(n){if(!(!n||typeof n!="string"))try{let e=le(n,"Library");try{Fs(e).isSymbolicLink()&&zs(e)}catch{}Gs(n,{recursive:!0,force:!0})}catch{}}var It=class extends Zs{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[oe(rt(),".local","bin","cursor-agent"),oe(rt(),".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("/")){an(r,ln.X_OK);let o=_e(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(o&&o.length>0)return p.debug(`[Cursor] Found agent at: ${r} (version: ${o.trim().slice(0,50)})`),!0}else{let o=_e(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!o)continue;let s=_e(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return p.debug(`[Cursor] Found '${r}' in PATH at ${o} (version: ${s.trim().slice(0,50)})`),!0}}catch{continue}return p.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:r=process.cwd(),print:o=!1,schema:s=null,skills:i=null,sessionPath:c=null,nodeName:a=null,timeout:l=ht.CURSOR_AGENT_DEFAULT,config:u={},signal:d=null}=t,m=u?.agent?.strictMode||!1,f=t.model??u?.agent?.cursor?.model??ce.CURSOR,g=q("CURSOR_API_KEY");try{p.debug(`[Cursor] Invoking (model: ${f}, timeout: ${l/1e3}s, skills: ${JSON.stringify(i)})`);let h=(this._setupMcpConfig(c,r,u,i,a)||{}).isolatedMcpHome??null,b=[oe(rt(),".local","bin","cursor-agent"),oe(rt(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"],_=null;for(let I of b)try{if(I.startsWith("/"))an(I,ln.X_OK),_e(`"${I}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!_e(`which ${I}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");_e(`${I} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}_=I,p.debug(`[Agent] Using binary: ${I}`);break}catch(E){p.debug(`[Agent] Binary '${I}' check failed: ${E.message}`);continue}if(!_)throw new Error(`Cursor Agent CLI not found or not working.
|
|
117
117
|
|
|
118
118
|
Checked paths:
|
|
119
119
|
${b.map(I=>` - ${I}`).join(`
|
|
@@ -125,36 +125,36 @@ Install cursor-agent:
|
|
|
125
125
|
Then add to PATH:
|
|
126
126
|
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
|
|
127
127
|
|
|
128
|
-
Test with: agent --version`);let
|
|
128
|
+
Test with: agent --version`);let T=new Ie(e),S=null;if(s){let I=`zibby-result-${Date.now()}.json`;S=oe(r,".zibby","tmp",I);let E=oe(r,".zibby","tmp");tt(E)||sn(E,{recursive:!0}),T.addStructuredOutput(s,S)}let A=process.env.CURSOR_API_KEY,P=A?` | key: ***${A.slice(-4)}`:" | key: not set";console.log(`
|
|
129
129
|
\u25C6 Model: ${f||"auto"}${P}
|
|
130
|
-
`);let
|
|
131
|
-
${
|
|
132
|
-
`)}catch{}let D,j=null;try{let I=c||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);D=await this._spawnWithStreaming(_,k,r,l,null,I,h,d)}catch(I){j=I}let w=D?.stdout||"";if(s){let I=typeof s.parse=="function",
|
|
130
|
+
`);let R=(await import("chalk")).default,O=T.getUserPrompt();console.log(`
|
|
131
|
+
${R.bold("Prompt sent to LLM:")}`),console.log(R.dim("\u2500".repeat(60))),console.log(R.dim(O)),console.log(R.dim("\u2500".repeat(60)));let U=T.build(),z=T.getStats(),k=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",f||"auto"];if(process.env.CURSOR_API_KEY&&k.push("--api-key",process.env.CURSOR_API_KEY),k.push(U),p.debug(`[Agent] User prompt: ${z.userPromptLength} chars, System instructions: ${z.systemInstructionsLength} chars (${z.instructionCount} blocks), Full: ${z.fullPromptLength} chars, model: ${f||"auto"}`),p.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${f||"auto"} (from .zibby.config.js agent.cursor.model)
|
|
132
|
+
`)}catch{}let D,j=null;try{let I=c||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);D=await this._spawnWithStreaming(_,k,r,l,null,I,h,d)}catch(I){j=I}let w=D?.stdout||"";if(s){let I=typeof s.parse=="function",E=null,L=!!(S&&tt(S));if(S&&p.info(`[Agent] Result file: ${L?"present":"missing"} at ${S}`),L)try{let C=on(S,"utf-8").trim();E=JSON.parse(C),p.info(`[Agent] Parsed JSON from result file OK (${C.length} chars) \u2192 object ready for validation`),j&&p.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(C){p.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${C.message}`)}else if(j)p.warn(`[Agent] Result file missing at ${S} (agent process error \u2014 may still recover if strictMode repairs)`);else throw p.error(`\u274C [Agent] Result file was never created at ${S}`),new Error(`Agent did not write required result file at ${S}`);if(E&&I)try{let C=s.parse(E);return p.info("\u2705 [Agent] Zod validation passed for structured result file"),m&&p.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:w,structured:C}}catch(C){let G=C.issues?C.issues.map(v=>` - ${v.path.join(".")}: ${v.message}`).join(`
|
|
133
133
|
`):C.message?.slice(0,400);if(p.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
|
|
134
134
|
${G}`),p.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
|
|
135
|
-
${JSON.stringify(
|
|
135
|
+
${JSON.stringify(E,null,2).slice(0,500)}`),!m)throw new Error(`Agent output failed schema validation:
|
|
136
136
|
${G}
|
|
137
137
|
|
|
138
138
|
The agent wrote invalid data that doesn't match the required outputSchema.
|
|
139
|
-
Enable strictMode in .zibby.config.js for automatic repair.`,{cause:C})}else{if(
|
|
140
|
-
`),r=null;for(let o of t){let s=o.trim();if(s)try{let i=JSON.parse(s);if(i.type==="assistant"&&i.message?.content){let c=i.message.content;if(Array.isArray(c)){let a=c.filter(l=>l.type==="text"&&l.text).map(l=>l.text).join("");a&&(r=a)}else typeof c=="string"&&c&&(r=c)}}catch{}}return r?.trim()||null}_setupMcpConfig(e,t,r,o=null,s=null){let i=r?.headless,c=oe(
|
|
141
|
-
`;if(
|
|
142
|
-
`)){let H=K.replace(`${r}/`,"");D.has(H)||(D.add(H),M.push(H))}}catch{}let C="";M.length>0&&(C=` | \u{1F4C1} new: ${M.map(v=>v.split("/").pop()).join(", ")}`),D.size>0&&(C+=` | \u{1F4E6} total: ${D.size} files`),p.debug(`\u{1F493} [Agent] Running for ${
|
|
143
|
-
${m.slice(-2e3)}`),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},5e3)},o),I=new ae;I.onToolCall=(
|
|
144
|
-
`).filter(G=>G.trim());y+=C.length}),O.stderr.on("data",
|
|
145
|
-
`).filter(C=>C.trim());for(let C of M)p.warn(`\u26A0\uFE0F [Agent stderr] ${C}`)}),O.on("close",(
|
|
139
|
+
Enable strictMode in .zibby.config.js for automatic repair.`,{cause:C})}else{if(E)return p.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),m&&p.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:w,structured:E};L&&p.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(m&&!j){let C=D.parsedText,G=E?JSON.stringify(E):C;p.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${G.length} chars in)`);try{let v=await qr(G,s);if(I){let K=s.parse(v.structured);return p.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:w,structured:K}}return{raw:w,...v}}catch(v){if(p.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${v.message}`),E)return p.warn("[Agent] Using agent's original result file as fallback"),{raw:w,structured:E}}}if(j)throw j;let M=L?E==null?"file existed but JSON.parse failed \u2014 see WARN log above":I?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw p.error(`\u274C [Agent] No validated structured output: ${M}`),p.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error(`Agent did not produce a valid result file at ${S}. Enable strictMode for proxy fallback.`)}if(j)throw j;return this._extractFinalResult(w)||D?.parsedText||w}finally{g.dispose()}}_extractFinalResult(e){if(!e)return null;let t=e.split(`
|
|
140
|
+
`),r=null;for(let o of t){let s=o.trim();if(s)try{let i=JSON.parse(s);if(i.type==="assistant"&&i.message?.content){let c=i.message.content;if(Array.isArray(c)){let a=c.filter(l=>l.type==="text"&&l.text).map(l=>l.text).join("");a&&(r=a)}else typeof c=="string"&&c&&(r=c)}}catch{}}return r?.trim()||null}_setupMcpConfig(e,t,r,o=null,s=null){let i=r?.headless,c=oe(rt(),".cursor"),a=oe(c,"mcp.json"),l={};if(tt(a))try{l=JSON.parse(on(a,"utf-8"))}catch{}let u=l.mcpServers||{},d=r?.paths?.output||Vs,m=oe(t||process.cwd(),d,Ws),f=Array.isArray(o)?o.map(h=>rn(h)).filter(Boolean):[...Xs()].map(([,h])=>h),g=new Set;for(let h of f)typeof h.resolve=="function"&&(g.has(h.serverName)||(g.add(h.serverName),this._ensureSkillConfigured(u,h,e,m,s,i)));if(e){let h=rn("browser");h&&typeof h.resolve=="function"&&!g.has(h.serverName)&&this._ensureSkillConfigured(u,h,e,m,"execute_live",i)}if(Object.keys(u).length===0)return p.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let y=`${JSON.stringify({mcpServers:u},null,2)}
|
|
141
|
+
`;if(Qr(e)){let h=en(t||process.cwd()),b=oe(h,".cursor","mcp.json");return nn(b,y,"utf8"),p.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${h} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:h}}return tt(c)||sn(c,{recursive:!0}),nn(a,y,"utf8"),p.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,o,s=null,i){let c=t.cursorKey||t.serverName,a=e[c]?c:e[t.serverName]?t.serverName:null;if(a&&r){let u=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:s,headless:i}):null;u?.args?e[a].args=u.args:e[a].args=(e[a].args||[]).map(f=>f.startsWith("--output-dir=")?`--output-dir=${r}`:f);let d=u?.env||{},m=t.sessionEnvKey?{[t.sessionEnvKey]:o}:{};e[a].env={...e[a].env||{},...d,...m},p.debug(`[MCP] Updated ${a} session \u2192 ${r}`);return}if(a)return;let l=t.resolve({sessionPath:r,nodeName:s,headless:i});if(l){if(pt(l)){e[c]=re("cursor",l),p.debug(`[MCP] ${c} \u2192 ${ft(l)}`);return}e[c]={...l,...t.sessionEnvKey&&{env:{...l.env||{},[t.sessionEnvKey]:o}}},p.debug(`[MCP] Configured ${c}`)}}_spawnWithStreaming(e,t,r,o,s=null,i=null,c=null,a=null){return new Promise((l,u)=>{let d=Date.now(),m="",f="",g=Date.now(),y=0,h=!1,b=null,_=!1,T=!1,S=null;if(i)try{S=oe(ti(String(i)),qs)}catch{S=null}let A=!1,P=()=>{A||(A=!0,tn(c))},R={...process.env};c&&(R.HOME=c,process.platform==="win32"&&(R.USERPROFILE=c),p.debug(`[Agent] cursor-agent HOME=${c} (isolated MCP config)`));let O=Qs(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:R,...a&&{signal:a}});p.debug(`[Agent] PID: ${O.pid}`);let U=null,z=()=>{h||T||(h=!0,b="aborted",p.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),U=setTimeout(()=>{if(!T){p.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{O.kill("SIGKILL")}catch{}}},5e3))};a&&(a.aborted?z():a.addEventListener("abort",z,{once:!0})),O.stdin.on("error",E=>{E.code!=="EPIPE"&&p.warn(`[Agent] stdin error: ${E.message}`)}),O.stdout.on("error",E=>{E.code!=="EPIPE"&&p.warn(`[Agent] stdout error: ${E.message}`)}),O.stderr.on("error",E=>{E.code!=="EPIPE"&&p.warn(`[Agent] stderr error: ${E.message}`)}),s?(O.stdin.write(s,E=>{E&&E.code!=="EPIPE"&&p.warn(`[Agent] Failed to write to stdin: ${E.message}`),O.stdin.end()}),p.debug(`[Agent] Prompt also piped to stdin (${s.length} chars)`)):O.stdin.end();let k=null;S&&(k=setInterval(()=>{if(!(h||T))try{if(tt(S)){h=!0,b="aborted";try{ei(S)}catch{}p.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},2e3)}}catch{}},600));let D=new Set,j=new Date(d).toISOString().replace(/\.\d+Z$/,""),w=setInterval(()=>{let E=Math.round((Date.now()-d)/1e3),L=Math.round((Date.now()-g)/1e3),M=[];try{let G=Math.ceil(E/60)+1,v=_e(`find "${r}" -type f -mmin -${G} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(v)for(let K of v.split(`
|
|
142
|
+
`)){let H=K.replace(`${r}/`,"");D.has(H)||(D.add(H),M.push(H))}}catch{}let C="";M.length>0&&(C=` | \u{1F4C1} new: ${M.map(v=>v.split("/").pop()).join(", ")}`),D.size>0&&(C+=` | \u{1F4E6} total: ${D.size} files`),p.debug(`\u{1F493} [Agent] Running for ${E}s | ${y} lines output${C}`),y===0&&E>=30&&D.size===0&&(E<35&&p.warn(`\u26A0\uFE0F [Agent] No output after ${E}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),E>=60&&(h=!0,b=b||"stall",p.error(`\u274C [Agent] No response after ${E}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},3e3)))},3e4),$=setTimeout(()=>{h=!0,b=b||"timeout";let E=Math.round((Date.now()-d)/1e3);p.error(`\u23F1\uFE0F [Agent] Timeout after ${E}s \u2014 killing process (PID: ${O.pid})`),m.trim()&&p.warn(`\u{1F4E4} [Agent] Partial output (${m.length} chars) before timeout:
|
|
143
|
+
${m.slice(-2e3)}`),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},5e3)},o),I=new ae;I.onToolCall=(E,L)=>{let M=E,C=L;if(E==="mcpToolCall"&&L?.name)M=L.name.replace(/^mcp_+[^_]+_+/,""),M.includes("-")&&M.split("-")[0]===M.split("-")[1]&&(M=M.split("-")[0]),C=L.args??L.input??L;else{if(E==="readToolCall"||E==="editToolCall"||E==="writeToolCall")return;(E.startsWith("mcp__")||E.includes("ToolCall"))&&(M=E.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(M.includes("memory")?ie.stepMemory(`Tool: ${M}`):ie.stepTool(`Tool: ${M}`),C!=null&&typeof C=="object"&&Object.keys(C).length>0&&!T){let v=JSON.stringify(C),K=v.length>100?`${v.substring(0,100)}...`:v;console.log(` Input: ${K}`)}},O.stdout.on("data",E=>{let L=E.toString();m+=L,g=Date.now(),_||(_=!0);let M=I.processChunk(L);M&&!T&&process.stdout.write(M);let C=L.split(`
|
|
144
|
+
`).filter(G=>G.trim());y+=C.length}),O.stderr.on("data",E=>{let L=E.toString();f+=L,g=Date.now(),_||(_=!0);let M=L.split(`
|
|
145
|
+
`).filter(C=>C.trim());for(let C of M)p.warn(`\u26A0\uFE0F [Agent stderr] ${C}`)}),O.on("close",(E,L)=>{if(T=!0,P(),clearTimeout($),clearInterval(w),k&&clearInterval(k),U&&clearTimeout(U),a&&!a.aborted)try{a.removeEventListener("abort",z)}catch{}I.flush();let M=Math.round((Date.now()-d)/1e3);if(p.debug(`[Agent] Exited: code=${E}, signal=${L}, elapsed=${M}s, output=${m.length} chars`),h){if(b==="aborted"){let v=new Error("Aborted via signal");v.name="AbortError",u(v);return}u(new Error(`Cursor Agent timed out after ${M}s (limit: ${o/1e3}s). ${y} lines produced. Last output ${Math.round((Date.now()-g)/1e3)}s ago. ${m.trim()?`
|
|
146
146
|
Partial output (last 500 chars):
|
|
147
|
-
${m.slice(-500)}`:"No output captured."}`));return}if(
|
|
147
|
+
${m.slice(-500)}`:"No output captured."}`));return}if(E!==0){u(new Error(`Cursor Agent failed: exit code ${E}, signal ${a}. ${f.trim()?`
|
|
148
148
|
Stderr: ${f.slice(-1e3)}`:""}${m.trim()?`
|
|
149
|
-
Stdout (last 500 chars): ${m.slice(-500)}`:""}`));return}let C=I.getResult(),G=C?JSON.stringify(C,null,2):I.getRawText()||m||"";l({stdout:m||f||"",parsedText:G})}),O.on("error",
|
|
149
|
+
Stdout (last 500 chars): ${m.slice(-500)}`:""}`));return}let C=I.getResult(),G=C?JSON.stringify(C,null,2):I.getRawText()||m||"";l({stdout:m||f||"",parsedText:G})}),O.on("error",E=>{if(P(),clearTimeout($),clearInterval(w),k&&clearInterval(k),U&&clearTimeout(U),a&&!a.aborted)try{a.removeEventListener("abort",z)}catch{}u(new Error(`Cursor Agent spawn error: ${E.message}
|
|
150
150
|
Binary: ${e}
|
|
151
151
|
This usually means the binary is not in PATH. Try:
|
|
152
|
-
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};import{AgentStrategy as
|
|
152
|
+
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};import{AgentStrategy as fi}from"@zibby/agent-workflow";var _n=[new Se,new me,new ge,new ye];function xn(n={}){let{state:e={},preferredAgent:t=null}=n,r=t||e.agentType||process.env.AGENT_TYPE;if(!r)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");p.debug(`Agent selection: requested=${r}`);let o=_n.find(s=>s.getName()===r);if(!o)throw new Error(`Unknown agent '${r}'. Available: ${_n.map(s=>s.getName()).join(", ")}`);if(p.debug(`Checking if ${r} can handle this environment...`),!o.canHandle(n)){let i={assistant:"Run `zibby login` to authenticate",claude:"Set ANTHROPIC_API_KEY in .env",cursor:"Install cursor-agent CLI or set CURSOR_API_KEY",codex:"Install codex CLI (npm i -g @openai/codex) and set OPENAI_API_KEY in .env",gemini:"Install gemini CLI (npm i -g @google/gemini-cli) and set GEMINI_API_KEY in .env"}[r]||"Check your environment configuration";throw new Error(`Agent '${r}' is not available. ${i}`)}return p.debug(`Using agent: ${o.getName()}`),o}async function pi(n,e={},t={}){try{await import("@zibby/skills")}catch{}try{await import("@zibby/skills-internal")}catch{}let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},o={...e,state:r},s=xn(o),i=r.config||t.config||{},c=r._currentNodeConfig||{},a=typeof c.agent=="string"?c.agent.trim():"",l=!a||a===s.name?c.model:null,u=ci({config:i,options:t,strategyName:s.name,envModel:process.env.MODEL,nodeConfigModel:l}),d={...t,model:u,...ui({options:t,stateView:r,context:e}),config:i},m=d.skills||[],f=n;if(m.length>0&&!t.skipPromptFragments){let{getSkill:h}=await import("@zibby/agent-workflow"),b=null;try{let{getConnectedIntegrations:S}=await Promise.resolve().then(()=>(kt(),Sn));b=await S()}catch{b=null}let _=S=>{let A=S&&S.requiresIntegration;return!A||!b?!0:(Array.isArray(A)?A:[A]).some(R=>b[R]===!0)},T=m.map(S=>{let A=h(S);if(!_(A))return null;let P=A?.promptFragment;return typeof P=="function"?P():P}).filter(Boolean);T.length>0&&(f+=`
|
|
153
153
|
|
|
154
|
-
${
|
|
154
|
+
${T.join(`
|
|
155
155
|
|
|
156
|
-
`)}`)}let g=r._currentNodeConfig?.stores;if(Array.isArray(g)&&g.length>0&&typeof g[0]=="object"){let h=g.length<=8,b=g.map(_=>{let
|
|
157
|
-
fields: ${O.join(", ")}`)}return
|
|
156
|
+
`)}`)}let g=r._currentNodeConfig?.stores;if(Array.isArray(g)&&g.length>0&&typeof g[0]=="object"){let h=g.length<=8,b=g.map(_=>{let T=_?.id??_?.storeId??"",S=_?.name??T,A=_?.type?` \xB7 ${_.type}`:"",P=(_?.description||"").toString().replace(/\s+/g," ").trim(),R=`- ${S} \xB7 ${P||"(no description)"}${A}${T?` (id: ${T})`:""}`;if(h&&_?.schema&&typeof _.schema=="object"){let O=_.schema.properties&&typeof _.schema.properties=="object"?Object.keys(_.schema.properties):Object.keys(_.schema);O.length&&(R+=`
|
|
157
|
+
fields: ${O.join(", ")}`)}return R});f+=`
|
|
158
158
|
|
|
159
159
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
160
160
|
${b.join(`
|
|
@@ -166,13 +166,13 @@ ${b.join(`
|
|
|
166
166
|
|
|
167
167
|
${y}
|
|
168
168
|
`),p.debug(`Prompt length: ${f.length} chars`),process.env.STAGE!=="prod"&&p.debug(`Full prompt:
|
|
169
|
-
${f}`),s.invoke(f,d)}import{SKILL_IDS as
|
|
170
|
-
`);let s=
|
|
171
|
-
\u{1F3AC} Organized ${a} video(s)`),console.log(`\u{1F4C2} Videos are now next to their test files in ${t}/`)),{movedCount:a,success:!0}}catch(c){return o&&console.error("\u274C Error organizing videos:",c.message),{movedCount:0,success:!1,error:c.message}}}async function
|
|
172
|
-
`),new Promise((e,t)=>{let r=De(__dirname,"../../scripts/patch-cursor-mcp.py");if(!
|
|
173
|
-
`),new Promise((e,t)=>{let r=
|
|
169
|
+
${f}`),s.invoke(f,d)}import{SKILL_IDS as kd}from"@zibby/skill-ids";import{registerSkill as Rd,getSkill as Ld,hasSkill as Md,getAllSkills as Ud,listSkillIds as Dd}from"@zibby/agent-workflow";import{classifyFailure as Bd,isTransientFailure as Fd,formatProviderError as Gd,providerErrorKindOf as Kd,providerErrorStatusOf as zd,PROVIDER_ERROR_KIND_CLASS as Jd}from"@zibby/agent-workflow";var di={READ_FILE:"read_file",WRITE_FILE:"write_file",LIST_DIRECTORY:"list_directory",RUN_COMMAND:"run_command",OPEN_URL:"open_url",WAIT:"wait"},mi={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"},gi={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"},hi={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"},yi={GENERATE:"run_generate",TEST:"run_test",STATUS:"run_status",CANCEL:"run_cancel",WAIT:"run_wait",ARTIFACTS:"run_artifacts",LIST_SPECS:"list_specs"},bi={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"},Si={STORE:"memory_store",RECALL:"memory_recall",BRIEF:"memory_brief",END_SESSION:"memory_end_session",TASK_LOG:"task_log",TASK_HISTORY:"task_history"},_i={INSTALL:"install_skill",UNINSTALL:"uninstall_skill",LIST_AVAILABLE:"list_available_skills"},Fu={...di,...mi,...gi,...hi,...yi,...bi,...Si,..._i};kt();kt();var xi=Object.freeze(["github.com","gitlab.com"]);function Ue(n){try{return new URL(n).hostname.toLowerCase()}catch{return""}}function Nt(n){if(typeof n!="string"||n===""||/[\\\x00-\x20\x7f]/.test(n))return"";let e;try{e=new URL(n)}catch{return""}return e.protocol!=="https:"?"":e.hostname.toLowerCase()}function wn(n=process.env){let e=n&&(n.GITLAB_URL||n.GITLAB_INSTANCE_URL)||"";return Ue(e)}function nt(n={}){if(n.gitlabHost){let e=String(n.gitlabHost).trim().toLowerCase();return e?e.includes("://")?Ue(e):e.replace(/:\d+$/,""):""}return wn()}function En(n,e={}){let t=Nt(n);if(!t)return!1;if(t==="github.com"||t==="gitlab.com")return!0;let r=nt(e);return!!(r&&t===r)}function tr(n,e={}){if(n==="github.com")return"github";if(n==="gitlab.com")return"gitlab";let t=nt(e);return t&&n===t?"gitlab":null}function Rt(n={},e={}){let t=n&&(n.cloneUrl||n.url)||"",r=Ue(t);if(!r)return null;let o=n.provider==="github"||n.provider==="gitlab"?n.provider:null,s=Tn(n,e),i=tr(r,s?{gitlabHost:s}:{});return i?o&&o!==i?null:i:o==="gitlab"?"gitlab":null}function Tn(n,e={}){let t=nt(e);return t||(n&&n.provider==="gitlab"?Nt(n.cloneUrl||n.url||""):"")}function rr(n={},e="",t={}){let r=n&&(n.cloneUrl||n.url)||"";if(!r||!e||!Rt(n,t))return r;let o=Tn(n,t);return nr(r,e,o?{gitlabHost:o}:{})}function nr(n,e,t={}){if(!n||!e)return n;let r=Nt(n);if(!r)return n;if(r==="github.com")return n.replace(/^https:\/\/(?:[^@/]+@)?github\.com(?=[:/]|$)/i,`https://x-access-token:${e}@github.com`);if(r==="gitlab.com")return n.replace(/^https:\/\/(?:[^@/]+@)?gitlab\.com(?=[:/]|$)/i,`https://oauth2:${e}@gitlab.com`);let o=nt(t);if(o&&r===o){let s=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^https:\\/\\/(?:[^@/]+@)?${s}(?=[:/]|$)`,"i");return n.replace(i,`https://oauth2:${e}@${o}`)}return n}function An(n){return n&&String(n).replace(/^(https:\/\/)[^@/]+@/i,"$1")}function vn(n,e){let t=n==null?"":String(n);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 wi(n,e,t){try{await n("git",["remote","set-url","origin",An(t)],e)}catch(r){console.warn(`\u26A0\uFE0F could not scrub token from origin remote (continuing): ${r?.message||r}`)}}async function Ei({run:n,repoPath:e,repoUrl:t,branch:r,token:o,resolveToken:s=Pt,gitlabHost:i}={}){if(typeof n!="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=nt({gitlabHost:i}),a=Nt(t),l=En(t,{gitlabHost:c}),u=o||"";if(!u&&l&&typeof s=="function"){let g=tr(a,{gitlabHost:c});if(g)try{u=(await s(g))?.token||""}catch{}}else!u&&!l&&console.warn(`\u26A0\uFE0F push target host '${a||"(unparseable)"}' is not a trusted VCS host \u2014 refusing to mint a token`);let d=u&&l,m=d?nr(t,u,{gitlabHost:c}):"origin",f=await n("git",["push",m,r],e);if(!f||f.code!==0){let g=vn(f&&f.stderr||"",u);throw new Error(`git push failed (exit ${f?f.code:"?"}): ${String(g).slice(-500)}`)}return{code:f.code,stdout:f.stdout,stderr:f.stderr,pushedAuthed:!!d,target:d?"<authed>":"origin"}}import{readdir as Ti,access as $n,copyFile as Ai,constants as On}from"fs/promises";import{join as Lt,relative as vi}from"node:path";async function $i(n={}){let{testResultsDir:e="test-results",testsDir:t="tests",projectRoot:r=process.cwd(),verbose:o=!0}=n;o&&console.log(`\u{1F3A5} Organizing test videos...
|
|
170
|
+
`);let s=Lt(r,e),i=Lt(r,t);try{let c=await Ti(s),a=0;for(let l of c){if(l.startsWith("."))continue;let u=Lt(s,l,"video.webm");try{await $n(u,On.F_OK)}catch{continue}let d=l.replace(/-chromium$/,"").replace(/-firefox$/,"").replace(/-webkit$/,""),m=await Oi(i,d);if(m){let f=m.replace(/\.spec\.(js|ts)$/,".spec.webm");await Ai(u,f),o&&console.log(`\u2705 ${vi(r,f)}`),a++}else o&&console.log(`\u26A0\uFE0F Could not find test file for: ${l}`)}return o&&(console.log(`
|
|
171
|
+
\u{1F3AC} Organized ${a} video(s)`),console.log(`\u{1F4C2} Videos are now next to their test files in ${t}/`)),{movedCount:a,success:!0}}catch(c){return o&&console.error("\u274C Error organizing videos:",c.message),{movedCount:0,success:!1,error:c.message}}}async function Oi(n,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=Lt(n,`${s}.spec.${i}`);try{return await $n(c,On.F_OK),c}catch{}}}return null}var ot=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 In(){let n=process.env.ZIBBY_API_KEY;return new ot(n)}import{execSync as Pn}from"node:child_process";import{existsSync as Ii,mkdirSync as Ci}from"node:fs";import{join as Pi}from"node:path";function Cn(n,e,t,r,o="clone"){try{n(`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(`[${o}] WARNING: failed to strip token from .git/config: ${i}`)}}async function ki(n={}){let{baseDir:e="/workspace/repos",repos:t=null,depth:r=1,branch:o=null}=n,s=process.env.REPOS;if(!s)throw new Error("REPOS environment variable not set. Are you running in a Zibby workflow container?");let i;try{i=JSON.parse(s)}catch(l){throw new Error(`Failed to parse REPOS env var: ${l.message}`,{cause:l})}if(!Array.isArray(i)||i.length===0)throw new Error("No repositories configured for this project");let c=t?i.filter(l=>t.includes(l.name)):i;if(c.length===0)throw new Error(`No matching repositories found. Available: ${i.map(l=>l.name).join(", ")}`);Ii(e)||Ci(e,{recursive:!0});let a={};return await Promise.all(c.map(async l=>{let u=l.cloneUrl||l.url;if(!u){console.error(`Repository "${l.name}" has no clone URL`),a[l.name]=null;return}let d=Rt(l);if(!d){console.error(`Refusing to clone ${l.name}: '${Ue(u)||u}' is not a recognized VCS host (expected github.com, gitlab.com, or the self-hosted GitLab named by GITLAB_URL/GITLAB_INSTANCE_URL${l.provider?`; the repo declares provider='${l.provider}'`:""}). No token was sent.`),a[l.name]=null;return}let m=d==="gitlab"?process.env.GITLAB_TOKEN:process.env.GITHUB_TOKEN;if(!m){console.error(`${d.toUpperCase()}_TOKEN not set, skipping ${l.name}`),a[l.name]=null;return}let f=l.name.replace(/\//g,"-"),g=Pi(e,f),y=rr({...l,cloneUrl:u},m);if(y===u){console.error(`Refusing to clone ${l.name}: could not safely attach credentials to '${u}' (an https:// URL on an exact trusted host is required). No token was sent.`),a[l.name]=null;return}let h=["clone"];r>0&&h.push("--depth",r.toString()),o&&h.push("--branch",o),h.push(y,g);let b=`git ${h.join(" ")}`;console.log(`Cloning ${l.name} (${d}) to ${g}...`);try{Pn(b,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),Cn(Pn,g,u,m,`cloneRepo:${l.name}`),console.log(`Repository ${l.name} cloned successfully`),a[l.name]=g}catch(_){let T=_.message.replace(m,"***").replace(y,u);console.error(`Failed to clone ${l.name}: ${T}`),a[l.name]=null}})),a}var kn=/^(?:[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 Ni(n){return typeof n=="string"&&kn.test(n)}var Nn=Ni;function Ri(n){if(!Nn(n))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(n.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(n.slice(9,13),16))>>>8,e&255,(e=parseInt(n.slice(14,18),16))>>>8,e&255,(e=parseInt(n.slice(19,23),16))>>>8,e&255,(e=parseInt(n.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}var or=Ri;var V=[];for(let n=0;n<256;++n)V.push((n+256).toString(16).slice(1));function Rn(n,e=0){return(V[n[e+0]]+V[n[e+1]]+V[n[e+2]]+V[n[e+3]]+"-"+V[n[e+4]]+V[n[e+5]]+"-"+V[n[e+6]]+V[n[e+7]]+"-"+V[n[e+8]]+V[n[e+9]]+"-"+V[n[e+10]]+V[n[e+11]]+V[n[e+12]]+V[n[e+13]]+V[n[e+14]]+V[n[e+15]]).toLowerCase()}function Li(n){n=unescape(encodeURIComponent(n));let e=new Uint8Array(n.length);for(let t=0;t<n.length;++t)e[t]=n.charCodeAt(t);return e}var Ln="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Mn="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function sr(n,e,t,r,o,s){let i=typeof t=="string"?Li(t):t,c=typeof r=="string"?or(r):r;if(typeof r=="string"&&(r=or(r)),r?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+i.length);if(a.set(c),a.set(i,c.length),a=e(a),a[6]=a[6]&15|n,a[8]=a[8]&63|128,o){if(s=s||0,s<0||s+16>o.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let l=0;l<16;++l)o[s+l]=a[l];return o}return Rn(a)}import{createHash as Mi}from"crypto";function Ui(n){return Array.isArray(n)?n=Buffer.from(n):typeof n=="string"&&(n=Buffer.from(n,"utf8")),Mi("sha1").update(n).digest()}var Un=Ui;function ir(n,e,t,r){return sr(80,Un,n,e,t,r)}ir.DNS=Ln;ir.URL=Mn;var ar=ir;var Dn="@zibby/core ZibbySessionStore/1",st=class{constructor({apiUrl:e,apiKey:t,workflowUuid:r,fetchImpl:o=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=o}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`,o=await this._fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this._apiKey}`,"Content-Type":"application/json","User-Agent":Dn},body:JSON.stringify({entries:t})});if(!o.ok)throw new Error(`ZibbySessionStore.append HTTP ${o.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":Dn}})}catch{return null}if(r.status===404||!r.ok)return null;let o;try{o=await r.json()}catch{return null}let s=Array.isArray(o?.entries)?o.entries:null;return s&&s.length>0?s:null}};var Di="6ba7b810-9dad-11d1-80b4-00c04fd430c8",jn=new Set;function ji(){return(process.env.PROGRESS_API_URL||process.env.ZIBBY_API_BASE||"").replace(/\/executions\/?$/,"").replace(/\/+$/,"")}function Bn({namespace:n=Di}={}){return{id:"session",description:"Persist agent conversation state across invocations (Claude-only in v1)",envKeys:[],tools:[],invokeAgentOptions(e,t){let r=e?.conversationId,o=e?.workflowUuid;if(!r||!o)return null;let s=t?.agentType;if(s&&s!=="claude")return jn.has(s)||(console.warn(`[SKILLS.SESSION] agent type '${s}' does not support native sessions \u2014 node running stateless`),jn.add(s)),null;let i=ar(`${o}:${r}`,n),c=ji(),a=process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN,l=null;if(c&&a)try{l=new st({apiUrl:c,apiKey:a,workflowUuid:o})}catch(m){console.warn(`[SKILLS.SESSION] failed to build SessionStore: ${m.message}`),l=null}return e.resetConversation?{sessionId:i,resume:i,forkSession:!0,...l&&{sessionStore:l}}:e.hasPriorSession?{resume:i,...l&&{sessionStore:l}}:{sessionId:i,...l&&{sessionStore:l}}}}}import{spawn as Fn}from"node:child_process";import{readFileSync as Bi,writeFileSync as Fi,existsSync as Mt}from"node:fs";import{homedir as Gn}from"node:os";import{join as De}from"node:path";async function Gi(){let n=De(Gn(),".local/share/cursor-agent/versions");if(!Mt(n))throw new Error(`cursor-agent not found at ${n}. Please install cursor-agent first.`);return console.log(`\u{1F527} Patching cursor-agent for CI/CD...
|
|
172
|
+
`),new Promise((e,t)=>{let r=De(__dirname,"../../scripts/patch-cursor-mcp.py");if(!Mt(r)){t(new Error("Patch script not found"));return}let o=Fn("python3",[r],{stdio:"inherit"});o.on("close",s=>{s===0?e({success:!0}):t(new Error(`Patch failed with code ${s}`))}),o.on("error",s=>{t(s)})})}function Ki(){let n=De(Gn(),".local/share/cursor-agent/versions");if(!Mt(n))return{patched:!1,installed:!1};try{let e=lo("fs").readdirSync(n);if(e.length===0)return{patched:!1,installed:!1};let t=e.sort().reverse()[0],r=De(n,t,"index.js");return Mt(r)?{patched:Bi(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 zi(n){return console.log(`\u{1F511} Getting MCP approval keys...
|
|
173
|
+
`),new Promise((e,t)=>{let r=Fn("cursor-agent",["mcp","list"],{cwd:n,stdio:"pipe"}),o="";r.stdout.on("data",s=>{o+=s.toString(),process.stdout.write(s)}),r.stderr.on("data",s=>{process.stderr.write(s)}),r.on("close",s=>{if(s===0){let i=Ji(o);e({success:!0,keys:i,output:o})}else t(new Error(`Failed to get approval keys (exit code ${s})`))}),r.on("error",s=>{t(s)})})}function Ji(n){let e={},t=/🔑 APPROVAL KEY:\s+(\S+)\s+=>\s+(\S+)/g,r;for(;(r=t.exec(n))!==null;)e[r[1]]=r[2];return e}function Hi(n,e){let t=De(n,".cursor/projects"),r=De(t,"mcp-approvals.json");Fi(r,JSON.stringify(e,null,2)),console.log(`
|
|
174
174
|
\u2705 Saved approval keys to: ${r}
|
|
175
|
-
`)}import{DEFAULT_OUTPUT_BASE as
|
|
175
|
+
`)}import{DEFAULT_OUTPUT_BASE as om,SESSIONS_DIR as sm,SESSION_INFO_FILE as im,RESULT_FILE as am,RAW_OUTPUT_FILE as lm,EVENTS_FILE as cm,CI_ENV_VARS as um}from"@zibby/agent-workflow";var Kn=`
|
|
176
176
|
const style = document.createElement('style');
|
|
177
177
|
style.textContent = \`
|
|
178
178
|
@keyframes zibby-ripple {
|
|
@@ -233,7 +233,7 @@ ${f}`),s.invoke(f,d)}import{SKILL_IDS as Id}from"@zibby/skill-ids";import{regist
|
|
|
233
233
|
setTimeout(() => ripple.remove(), 600);
|
|
234
234
|
}
|
|
235
235
|
};
|
|
236
|
-
`;function
|
|
236
|
+
`;function Yi(n){return n.addInitScript(Kn)}function Zi(){return`
|
|
237
237
|
async function showRipple(page, locator) {
|
|
238
238
|
const box = await locator.boundingBox().catch(() => null);
|
|
239
239
|
if (box) {
|
|
@@ -246,10 +246,10 @@ async function showRipple(page, locator) {
|
|
|
246
246
|
}, { x, y }).catch(() => {});
|
|
247
247
|
}
|
|
248
248
|
}
|
|
249
|
-
`.trim()}var
|
|
249
|
+
`.trim()}var it=class{static generate(e,t="element"){let{selectors:r}=e;if(!r||typeof r!="object")return this.generateFallbackSelector(e,t);let o=[];return r.role&&o.push(this.generateRoleSelector(r.role)),r.attributes&&o.push(this.generateAttributeSelector(r.attributes)),r.partialMatch&&o.push(this.generatePartialMatchSelector(r.partialMatch)),r.structure&&o.push(this.generateStructuralSelector(r.structure)),o.length===0?this.generateFallbackSelector(e,t):o.length===1?`const ${t} = ${o[0]};`:`const ${t} = ${o[0]}
|
|
250
250
|
${o.slice(1).map(i=>` .or(${i})`).join(`
|
|
251
251
|
`)};`}static generateRoleSelector(e){let{role:t,name:r}=e;if(!t)return null;if(r){let o=this.escapeRegex(r);return`page.getByRole('${t}', { name: /${o}/i })`}return`page.getByRole('${t}')`}static generateAttributeSelector(e){if(!e||typeof e!="object")return null;let t=Object.entries(e).filter(([o,s])=>s!=null).map(([o,s])=>o==="placeholder"||o==="aria-label"?o==="placeholder"?`page.getByPlaceholder('${this.escapeString(s)}')`:`page.locator('[${o}="${this.escapeString(s)}"]')`:`[${o}="${this.escapeString(s)}"]`);if(e.placeholder)return`page.getByPlaceholder('${this.escapeString(e.placeholder)}')`;let r=t.filter(o=>!o.startsWith("page.")).join("");return r?`page.locator('${r}')`:null}static generatePartialMatchSelector(e){if(!e||typeof e!="object")return null;let t=Object.entries(e).filter(([r,o])=>o!==void 0).map(([r,o])=>{let s=o.replace(/^\^/,"");return`[${r}^="${this.escapeString(s)}"]`});return t.length>0?`page.locator('${t.join("")}')`:null}static generateStructuralSelector(e){return!e||typeof e!="string"?null:`page.locator('${this.escapeString(e)}')`}static generateFallbackSelector(e,t){let{description:r,type:o}=e;if(o==="fill"||o==="type")return`const ${t} = page.locator('input').first();`;if(o==="click"){if(r.toLowerCase().includes("button"))return`const ${t} = page.locator('button').first();`;if(r.toLowerCase().includes("link"))return`const ${t} = page.locator('a').first();`}return`const ${t} = page.locator('body');`}static escapeString(e){return typeof e!="string"?String(e):e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/"/g,'\\"')}static escapeRegex(e){return typeof e!="string"?String(e):e.replace(/[.*+?^${}()[\]\\]/g,"\\$&")}static generateActionCode(e,t){let{type:r,value:o,description:s,selectors:i}=e,c=`element${t}`,a=this.generate(e,c),l=this.generateActionMethod(r,c,o);return`${a}
|
|
252
|
-
${l}`}static generateActionMethod(e,t,r){switch(e){case"fill":case"type":return`await ${t}.fill('${this.escapeString(r||"")}');`;case"click":return`await ${t}.click();`;case"navigate":return`await page.goto('${this.escapeString(r||"")}');`;case"wait":return`await page.waitForTimeout(${parseInt(r)||2e3});`;default:return`// Unknown action type: ${e}`}}static generateAssertionCode(e,t){let{description:r,expected:o,actual:s,passed:i}=e;return r.toLowerCase().includes("url")?`await expect(page).toHaveURL(/${this.escapeRegex(s)}/);`:r.toLowerCase().includes("visible")?"await expect(page.locator('body')).toBeVisible();":`// ${r}`}};import
|
|
252
|
+
${l}`}static generateActionMethod(e,t,r){switch(e){case"fill":case"type":return`await ${t}.fill('${this.escapeString(r||"")}');`;case"click":return`await ${t}.click();`;case"navigate":return`await page.goto('${this.escapeString(r||"")}');`;case"wait":return`await page.waitForTimeout(${parseInt(r)||2e3});`;default:return`// Unknown action type: ${e}`}}static generateAssertionCode(e,t){let{description:r,expected:o,actual:s,passed:i}=e;return r.toLowerCase().includes("url")?`await expect(page).toHaveURL(/${this.escapeRegex(s)}/);`:r.toLowerCase().includes("visible")?"await expect(page.locator('body')).toBeVisible();":`// ${r}`}};import at from"fs/promises";var lr=class{static async generateFromEvents(e,t,r,o){try{console.log("[TestPostProcessor] \u{1F3AF} Generating test from events.json (100% accurate)");let{readFileSync:s}=await import("fs"),i=JSON.parse(s(t,"utf-8")),c=i.filter(f=>["navigate","type","fill","click","select_option"].includes(f.type)),a=c.filter(f=>f.type!=="navigate");console.log(`[TestPostProcessor] Found ${c.length} action events, ${r.length} trace actions`);let l=`import { ZibbyRuntime } from '@zibby/core';
|
|
253
253
|
import { test, expect } from '@playwright/test';
|
|
254
254
|
|
|
255
255
|
`;l+=`test('${o}', async ({ page }) => {
|
|
@@ -264,20 +264,20 @@ import { test, expect } from '@playwright/test';
|
|
|
264
264
|
`,u++}else if(f.type==="select_option"){let{element:g,values:y}=f.data.params,h=r[u]?.strategies||[],b={name:g,action:"selectOption",value:Array.isArray(y)?y[0]:y,strategies:h};l+=` await ZibbyRuntime.step(page, ${JSON.stringify(b,null,2)});
|
|
265
265
|
|
|
266
266
|
`,u++}l+=`});
|
|
267
|
-
`;let{dirname:d}=await import("path"),{mkdirSync:m}=await import("fs");return m(d(e),{recursive:!0}),await
|
|
268
|
-
${o}`);for(let s=0;s<t.length;s++){let i=t[s],c=`element${s}`,a=new RegExp(`const ${c}\\b\\s*=\\s*page\\.[^;]+;(\\s*await ${c}\\.waitFor\\([^)]*\\);)?\\s*await ${c}\\.(click|fill|type|selectOption|pressSequentially)\\(([^)]*)\\);`,"s"),l=o.match(a);if(!l)continue;let u={name:i.name||`Action ${s}`,action:i.method==="type"?"fill":i.method,value:l[3].trim().replace(/^['"]|['"]$/g,""),strategies:i.strategies||[]},d=`await ZibbyRuntime.step(page, ${JSON.stringify(u,null,2)});`;o=o.replace(l[0],d)}return await
|
|
269
|
-
await ${m}.${u}(${d})`}}return i});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as
|
|
270
|
-
`),s=[],i=new Map,c=new Map;for(let a of o)try{let l=JSON.parse(a);if(l.type==="snapshot"&&l.snapshot&&l.snapshot.accessibility){let u=new Map;for(let d of l.snapshot.accessibility)d.ref&&u.set(d.ref,d);i.set(l.snapshotName,u)}if(l.type==="frame-snapshot"&&l.snapshot){let u=Buffer.from(l.snapshot.html||"","base64").toString("utf-8");u&&u.length>100&&c.set(l.pageId||"default",u)}}catch{}for(let a of o)try{let l=JSON.parse(a);if(l.type==="before"&&l.params&&l.params.selector){let u=l.method;if(["click","fill","type","selectOption"].includes(u)){let d=l.params.selector,m=l.params.text||l.params.value||"",f=[],g=null,y=null,h=null,b=d.match(/aria-ref=([a-z0-9]+)/i);if(b&&l.snapshotName){let k=b[1],D=i.get(l.snapshotName);if(D&&D.has(k)){let j=D.get(k);g=j.name||null,y=j.role||null,h=j.label||null,console.log(`[TraceParser] \u2705 Found ACTUAL element data: text="${g}", role="${y}"`)}}let _=d.match(/internal:text="([^"]+)"/i),E=d.match(/internal:label="([^"]+)"/i),S=d.match(/internal:placeholder="([^"]+)"/i),A=d.match(/internal:role=([^ ]+)/i),P=d.match(/internal:describe="([^"]+)"/i),N=d.match(/name="([^"]+)"/i);if(_){f.push({type:"text",text:_[1]});let k=_[1].split(" ");k.length>1&&(f.push({type:"text",text:k[0],fuzzy:!0}),f.push({type:"text",text:k[k.length-1],fuzzy:!0}))}if(E&&f.push({type:"label",label:E[1]}),S&&f.push({type:"placeholder",placeholder:S[1]}),g){f.unshift({type:"text",text:g,source:"accessibility-tree"});let k=g.split(" ");k.length>1&&f.push({type:"text",text:k[0],fuzzy:!0,source:"accessibility-tree"})}if(y||A){let k=y||A[1],D=g||(N?N[1]:_?_[1]:null);f.unshift({type:"role",role:k,name:D,source:g?"accessibility-tree":"selector"})}if(h&&f.unshift({type:"label",label:h,source:"accessibility-tree"}),P){let k=P[1],D=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],j=null,w=k;for(let $ of D)if(k.toLowerCase().endsWith(` ${$}`)){j=$.replace(" ",""),w=k.substring(0,k.length-$.length-1);break}if(j){f.push({type:"role",role:j,name:w});let $=w.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:$}),f.push({type:"text",text:w});let I=w.split(" ");I.length>1&&(f.push({type:"text",text:I[0],fuzzy:!0}),f.push({type:"text",text:I.slice(0,2).join(" "),fuzzy:!0}))}else{let $=k.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:$}),f.push({type:"text",text:k})}}let O=this.extractDOMStrategies(d,c,_?.[1]||P?.[1],l.pageId);f.push(...O);let U=this.extractStructuralContext(d);(U.parent||U.sibling)&&f.forEach(k=>{["role","text","label","testid"].includes(k.type)&&(U.parent&&(k.parent=U.parent),U.sibling&&(k.sibling=U.sibling))}),f.push({type:"css",value:d});let z=g||_?_[1]:P?P[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${s.length}`;s.push({method:u,name:z,action:u==="type"?"fill":u,value:m,strategies:f,timestamp:l.startTime,actualText:g,actualRole:y,actualAriaLabel:h})}}}catch{}return s}catch(r){throw new Error(`Failed to parse trace: ${r.message}`,{cause:r})}}static extractDOMStrategies(e,t,r,o){let s=[];if(!t||t.size===0||!r)return s;try{let i=t.get(o);if(!i)return s;let c=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),l=i.match(a);l&&s.push({type:"testid",value:l[1],priority:"high"});let u=new RegExp(`class=["']([^"']+)["'][^>]*>[^<]*${c}`,"gi"),d=i.matchAll(u);for(let g of d){let y=g[1].split(/\s+/).filter(h=>h&&!h.match(/^(css|jss|makeStyles|MuiBox|MuiStack)-\w+/)&&h.length>2);y.length>0&&(s.push({type:"class",value:y.join("."),priority:"medium"}),y.length===1&&s.push({type:"class",value:y[0],priority:"medium"}))}let m=new RegExp(`id=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),f=i.match(m);f&&!f[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&s.push({type:"id",value:f[1],priority:"high"})}catch(i){console.warn(`[TraceParser] DOM extraction failed: ${i.message}`)}return s}static extractStructuralContext(e){let t={parent:null,sibling:null},r=e.split(">>").map(i=>i.trim());if(r.length>1){let c=r[r.length-2].replace(/internal:text="[^"]+"\s*/gi,"").replace(/internal:role=\S+\s*/gi,"").replace(/internal:label="[^"]+"\s*/gi,"").trim();c&&(c.match(/^(form|section|nav|header|aside|main|article)\b/)||c.includes("[")||c.match(/[#.]\w/))&&(t.parent=c)}let s=r[r.length-1].match(/([^+~]+)\s*[+~]\s*(.+)/);return s&&(t.sibling=s[1].trim()),t}};var cr=class{static async step(e,t){let{name:r,action:o,value:s,strategies:i,options:c={timeout:1e4},enrichedData:a}=t;console.log(`[Zibby] \u26A1 Executing step: ${r}`),await this.waitForPageStability(e,c.timeout);let l=await this.findBestMatch(e,i,r);if(!l)throw new Error(`[Zibby] \u274C Failed to find "${r}" using ${i.length} strategies`);a?.position&&await this.verifyPosition(l,a.position),await this.performActionWithRetry(e,l,o,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 o,s=new MutationObserver(()=>{clearTimeout(o),o=setTimeout(()=>{s.disconnect(),r()},500)});s.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),o=setTimeout(()=>{s.disconnect(),r()},500)})).catch(()=>{})}catch{}}static async verifyPosition(e,t){try{let r=await e.boundingBox();if(!r)return;let o=Math.abs(r.x-t.x),s=Math.abs(r.y-t.y);(o>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,o,s=3){for(let i=1;i<=s;i++)try{r==="click"?await t.click():r==="fill"?await t.fill(o||""):r==="type"?await t.pressSequentially(o||""):r==="selectOption"&&await t.selectOption(o||"");return}catch(c){if(i===s)throw c;console.log(`[Zibby] \u26A0\uFE0F Action failed (attempt ${i}/${s}), retrying...`),await new Promise(a=>setTimeout(a,1e3*i))}}static async findBestMatch(e,t,r){let s=Date.now(),i=t.map(async(l,u)=>{try{let m=await this.getLocator(e,l).all();return m.length===0?[]:(await Promise.all(m.map(async(g,y)=>{try{if(!await g.isVisible({timeout:100}))return null;let b=await this.scoreCandidate(g,l,e);return{element:g,strategy:l,score:b,strategyIdx:u,elIdx:y}}catch{return null}}))).filter(g=>g!==null)}catch{return[]}}),c=(await Promise.all(i)).flat();if(c.length===0)return console.log(`[Zibby] \u274C No visible candidates found for "${r}"`),null;c.sort((l,u)=>u.score-l.score);let a=c[0];return console.log(`[Zibby] \u2705 Found element using ${a.strategy.type} (score: ${a.score.toFixed(2)}, ${c.length} candidates)`),a.element}static async scoreCandidate(e,t,r){let o=0;if(o+={testid:120,id:110,role:100,label:90,class:85,placeholder:85,text:80,css:50}[t.type]||50,t.priority==="high"&&(o+=20),t.priority==="medium"&&(o+=10),t.fuzzy&&(o-=15),t.parent)try{await e.locator("xpath=ancestor::*").first().evaluate((a,l)=>a.matches(l),t.parent)&&(o+=30)}catch{}if(t.sibling)try{await e.evaluate((c,a)=>c.parentElement?.querySelector(a)!==null,t.sibling)&&(o+=20)}catch{}try{let i=await e.boundingBox();i&&i.y<1e3&&(o+=10)}catch{}try{let i=await e.evaluate(c=>{let a=0,l=c;for(;l;)l.tagName==="IFRAME"&&a++,l=l.parentElement;return a});o-=i*5}catch{}return o}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 o=t.value?.replace(/aria-ref=e\d+ >> /g,"")||t.css;r=e.locator(o);break}}return t.parent&&(r=r.filter({has:e.locator(t.parent)})),r}};var ur=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 o=r.timeout||1e4,s=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<o;){await this.injectStableIds(e);let c=e.locator(s);if(await c.count()>0)try{await c.click({timeout:2e3});return}catch(a){if(a.message.includes("intercepts pointer")){await c.click({force:!0});return}}await e.waitForTimeout(200)}throw new Error(`Element ${s} not found after ${o}ms`)}static async fillWithRetry(e,t,r,o=1e4){let s=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<o;){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 ${o}ms`)}static async selectWithRetry(e,t,r,o=1e4){let s=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<o;){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 ${o}ms`)}static async injectStableIds(e){try{await e.evaluate(()=>{function t(a){if(a.getAttribute("aria-label"))return a.getAttribute("aria-label").trim();let l=a.getAttribute("aria-labelledby");if(l){let m=document.getElementById(l);if(m)return m.textContent.trim()}if(a.id){let m=document.querySelector(`label[for="${a.id}"]`);if(m)return m.textContent.trim()}let u=a.closest("label");if(u){let m=u.cloneNode(!0);m.querySelectorAll("input, select, textarea").forEach(g=>g.remove());let f=m.textContent.trim();if(f)return f}if(a.placeholder)return a.placeholder;let d=a.tagName.toLowerCase();return d==="button"||d==="a"||a.getAttribute("role")==="button"?(a.textContent||"").trim().slice(0,50):a.title?a.title:d==="input"&&(a.type==="submit"||a.type==="button")&&a.value||""}function r(a){let l=[],u=a.closest("form");if(u)if(u.id)l.push(`form#${u.id}`);else if(u.name)l.push(`form[name=${u.name}]`);else if(u.action)try{let y=new URL(u.action,window.location.origin).pathname;l.push(`form[action=${y}]`)}catch{l.push(`form[action=${u.getAttribute("action")}]`)}else{let y=document.querySelectorAll("form"),h=Array.from(y).indexOf(u);l.push(`form:nth(${h})`)}let d=a.closest('header, nav, main, footer, aside, [role="banner"], [role="navigation"], [role="main"], [role="contentinfo"]');if(d){let y=d.tagName.toLowerCase(),h=d.getAttribute("role");l.push(h||y)}let m=a.closest('section, article, [role="region"]');if(m){let y=m.querySelector("h1, h2, h3, h4, h5, h6");y&&l.push(`section:${y.textContent.trim().slice(0,30)}`)}let f=a.closest("fieldset");if(f){let y=f.querySelector("legend");y&&l.push(`fieldset:${y.textContent.trim()}`)}let g=a.closest('dialog, [role="dialog"], [role="alertdialog"]');if(g){let y=g.querySelector('[role="heading"], h1, h2, h3');y?l.push(`dialog:${y.textContent.trim().slice(0,30)}`):l.push("dialog")}return l.join("/")}function o(a){let l=a.tagName.toLowerCase(),u=a.id||"",d=a.name||"",m=a.type||"",f=a.getAttribute("role")||"",g="";if(a.href)try{g=new URL(a.href,window.location.origin).pathname.slice(0,50)}catch{g=a.getAttribute("href")?.slice(0,50)||""}let y=t(a).slice(0,50).replace(/\s+/g," "),h=r(a),b=[l,u,d,m,f,g,y,h].join("|"),_=5381;for(let E=0;E<b.length;E++)_=(_<<5)+_^b.charCodeAt(E);return`zibby-${(_>>>0).toString(36)}`}let s=["button","a","input","select","textarea","label[for]",'[role="button"]','[role="link"]','[role="textbox"]','[role="checkbox"]','[role="radio"]','[role="combobox"]','[role="menuitem"]','[role="tab"]','[role="option"]','[role="switch"]','[role="slider"]',"[onclick]","[data-action]"].join(", "),i=new Map,c=0;document.querySelectorAll(s).forEach(a=>{let l=window.getComputedStyle(a);if(l.display==="none"||l.visibility==="hidden")return;let u=o(a),d=u,m=i.get(d)||0;m>0&&(u=`${d}-${m}`),i.set(d,m+1),a.setAttribute("data-zibby-id",u),c++}),console.log(`[Zibby] Injected ${c} stable IDs`)})}catch{}}};var Vi=8,Wi=1,qi=64;function Xi(n){if(!n||typeof n!="object")return 8;let e=n.parallel;if(!e||typeof e!="object")return 8;let t=e.maxConcurrentRuns??e.maxConcurrent,r=Number(t);if(!Number.isFinite(r))return 8;let o=Math.floor(r);return o<1?8:Math.min(64,o)}import{readFileSync as ea,writeFileSync as Jn,existsSync as ta}from"node:fs";import{join as Hn}from"node:path";var Z=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 Qi}from"node:fs";import{join as zn}from"node:path";var we=class extends Z{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=zn(e,"traces"),r=zn(e,"trace.zip");if(Qi(r))try{this.traceData=await at.parseTraceZip(r),console.log(`[TraceTextEnricher] \u2705 Loaded trace with ${this.traceData.length} actions`)}catch(o){console.log(`[TraceTextEnricher] \u26A0\uFE0F Failed to parse trace: ${o.message}`)}}async enrich(e,t){let r=e.data?.params?.ref,o=e.id;if(r===void 0&&o===void 0||(!this.traceData&&t.sessionPath&&await this.loadTrace(t.sessionPath),!this.traceData))return null;let s=this.traceData[o];if(!s)return console.log(`[TraceTextEnricher] \u26A0\uFE0F No trace action for event ${o}`),null;let i=s.actualText||this._extractTextFromSelector(s.selector),c=s.actualRole,a=s.actualAriaLabel;return i||c||a?(console.log(`[TraceTextEnricher] \u2705 Event ${o}: text="${i}", role="${c}", label="${a}"`),{traceActualText:i,traceActualRole:c,traceActualAriaLabel:a,traceSelector:s.selector,traceStrategies:s.strategies}):null}_extractTextFromSelector(e){if(!e)return null;let t=e.match(/internal:label="([^"]+)"/);if(t)return t[1];let r=e.match(/internal:text="([^"]+)"/);if(r)return r[1];let o=e.match(/getByText\(['"]([^'"]+)['"]\)/);if(o)return o[1];let s=e.match(/name:\s*['"]([^'"]+)['"]/);return s?s[1]:null}};async function ra(n){let e=Hn(n,"events.json"),t=Hn(n,"events-enriched.json");if(!ta(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(ea(e,"utf-8")),o=new we,s=0,i=0;for(let c of r)try{let a=await o.enrich(c,{sessionPath:n});a&&(c.enrichedData={...c.enrichedData||{},...a},s++)}catch(a){console.log(`[PostProcess] Failed to enrich event ${c.id}: ${a.message}`),i++}return s>0&&(Jn(t,JSON.stringify(r,null,2)),Jn(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 na}from"node:child_process";import{existsSync as oa}from"node:fs";import{dirname as sa,resolve as Yn,relative as ia}from"node:path";var Mt=new Map,lt=8,Zn={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 ${lt} 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:n},e){let r=`${e?.sessionId||"default"}:${n}`,o=(Mt.get(r)||0)+1;if(Mt.set(r,o),o>lt)return{success:!1,executionCount:o,maxReached:!0,error:`Maximum ${lt} executions reached. Stop retrying and return your best result.`};let s=e?.projectRoot||process.cwd(),i=Yn(s,n),c=ia(s,i);return c.startsWith("..")||Yn(i)!==i&&c.includes("..")?{success:!1,executionCount:o,error:"Path traversal detected: scriptPath must be within the project root."}:oa(i)?new Promise(a=>{let l=sa(i),u=na("npx",["playwright","test",i,"--reporter=line"],{cwd:s,env:{...process.env,FORCE_COLOR:"0"}}),d="",m="";u.stdout.on("data",g=>{d+=g.toString()}),u.stderr.on("data",g=>{m+=g.toString()});let f=setTimeout(()=>{u.kill("SIGTERM"),a({success:!1,executionCount:o,error:"Test timed out after 60 seconds",stdout:d.slice(-2e3),stderr:m.slice(-1e3)})},6e4);u.on("close",g=>{clearTimeout(f);let h=`${d}
|
|
267
|
+
`;let{dirname:d}=await import("path"),{mkdirSync:m}=await import("fs");return m(d(e),{recursive:!0}),await at.writeFile(e,l,"utf-8"),console.log(`[TestPostProcessor] \u2705 Generated test with ${i.filter(f=>["type","fill","click","select_option"].includes(f.type)).length} actions`),!0}catch(s){return console.warn("[TestPostProcessor] Failed to generate from events:",s.message),!1}}static async enhanceSelectorsWithTrace(e,t,r){try{console.log("[TestPostProcessor] \u{1F6E1}\uFE0F Applying Zibby Safe Action Wrappers...");let o=await at.readFile(e,"utf-8");o.includes("ZibbyRuntime")||(o=`import { ZibbyRuntime } from '@zibby/core';
|
|
268
|
+
${o}`);for(let s=0;s<t.length;s++){let i=t[s],c=`element${s}`,a=new RegExp(`const ${c}\\b\\s*=\\s*page\\.[^;]+;(\\s*await ${c}\\.waitFor\\([^)]*\\);)?\\s*await ${c}\\.(click|fill|type|selectOption|pressSequentially)\\(([^)]*)\\);`,"s"),l=o.match(a);if(!l)continue;let u={name:i.name||`Action ${s}`,action:i.method==="type"?"fill":i.method,value:l[3].trim().replace(/^['"]|['"]$/g,""),strategies:i.strategies||[]},d=`await ZibbyRuntime.step(page, ${JSON.stringify(u,null,2)});`;o=o.replace(l[0],d)}return await at.writeFile(e,o,"utf-8"),console.log("[TestPostProcessor] \u2705 Successfully converted test to Resilient Zibby format"),!0}catch(o){return console.warn("[TestPostProcessor] Failed to apply safe wrappers:",o.message),!1}}static async enhanceSelectors(e,t){try{let{actions:r=[]}=t;if(!r.length)return!1;let o=await at.readFile(e,"utf-8"),s=this.buildSelectorMap(r);return o=this.replaceSimpleSelectors(o,s),await at.writeFile(e,o,"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 o=e[r];if(!o.selectors||o.type==="navigate")continue;let s=`element${r}`,c=it.generate(o,s).match(/= (.+);/s);if(c){let a=c[1].trim(),l=`${o.type}:${this.normalizeDescription(o.description)}`;t.set(l,a),o.selectors.role&&t.set(`role:${o.selectors.role.name}`,a),o.selectors.attributes?.placeholder&&t.set(`placeholder:${o.selectors.attributes.placeholder}`,a)}}return t}static replaceSimpleSelectors(e,t){let r=e,o=[/await page\.(getByRole|getByPlaceholder|getByText|getByLabel|locator)\([^)]+\)\.(fill|click|type)\([^)]*\)/g];for(let s of o)r=r.replace(s,i=>{for(let[c,a]of t.entries())if(i.includes(c.split(":")[1])){let l=i.match(/\.(fill|click|type)\(([^)]*)\)/);if(l){let[,u,d]=l,m="element";return`const ${m} = ${a};
|
|
269
|
+
await ${m}.${u}(${d})`}}return i});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as Vi,existsSync as zn,readdirSync as Jn}from"node:fs";import{join as cr}from"node:path";import{execSync as Wi}from"node:child_process";import{tmpdir as qi}from"node:os";var lt=class{static async parseTraceZip(e){let t;if(e.endsWith(".zip")&&zn(e)){let r=cr(qi(),`trace-${Date.now()}`);Wi(`unzip -q "${e}" -d "${r}"`,{stdio:"pipe"});let s=Jn(r).find(i=>i.endsWith(".trace"));if(!s)throw new Error("No .trace file found in zip");t=cr(r,s)}else if(zn(e)){let o=Jn(e).find(s=>s.endsWith(".trace"));if(!o)throw new Error("No .trace file found");t=cr(e,o)}else throw new Error(`Trace not found at ${e}`);try{let o=Vi(t,"utf-8").trim().split(`
|
|
270
|
+
`),s=[],i=new Map,c=new Map;for(let a of o)try{let l=JSON.parse(a);if(l.type==="snapshot"&&l.snapshot&&l.snapshot.accessibility){let u=new Map;for(let d of l.snapshot.accessibility)d.ref&&u.set(d.ref,d);i.set(l.snapshotName,u)}if(l.type==="frame-snapshot"&&l.snapshot){let u=Buffer.from(l.snapshot.html||"","base64").toString("utf-8");u&&u.length>100&&c.set(l.pageId||"default",u)}}catch{}for(let a of o)try{let l=JSON.parse(a);if(l.type==="before"&&l.params&&l.params.selector){let u=l.method;if(["click","fill","type","selectOption"].includes(u)){let d=l.params.selector,m=l.params.text||l.params.value||"",f=[],g=null,y=null,h=null,b=d.match(/aria-ref=([a-z0-9]+)/i);if(b&&l.snapshotName){let k=b[1],D=i.get(l.snapshotName);if(D&&D.has(k)){let j=D.get(k);g=j.name||null,y=j.role||null,h=j.label||null,console.log(`[TraceParser] \u2705 Found ACTUAL element data: text="${g}", role="${y}"`)}}let _=d.match(/internal:text="([^"]+)"/i),T=d.match(/internal:label="([^"]+)"/i),S=d.match(/internal:placeholder="([^"]+)"/i),A=d.match(/internal:role=([^ ]+)/i),P=d.match(/internal:describe="([^"]+)"/i),R=d.match(/name="([^"]+)"/i);if(_){f.push({type:"text",text:_[1]});let k=_[1].split(" ");k.length>1&&(f.push({type:"text",text:k[0],fuzzy:!0}),f.push({type:"text",text:k[k.length-1],fuzzy:!0}))}if(T&&f.push({type:"label",label:T[1]}),S&&f.push({type:"placeholder",placeholder:S[1]}),g){f.unshift({type:"text",text:g,source:"accessibility-tree"});let k=g.split(" ");k.length>1&&f.push({type:"text",text:k[0],fuzzy:!0,source:"accessibility-tree"})}if(y||A){let k=y||A[1],D=g||(R?R[1]:_?_[1]:null);f.unshift({type:"role",role:k,name:D,source:g?"accessibility-tree":"selector"})}if(h&&f.unshift({type:"label",label:h,source:"accessibility-tree"}),P){let k=P[1],D=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],j=null,w=k;for(let $ of D)if(k.toLowerCase().endsWith(` ${$}`)){j=$.replace(" ",""),w=k.substring(0,k.length-$.length-1);break}if(j){f.push({type:"role",role:j,name:w});let $=w.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:$}),f.push({type:"text",text:w});let I=w.split(" ");I.length>1&&(f.push({type:"text",text:I[0],fuzzy:!0}),f.push({type:"text",text:I.slice(0,2).join(" "),fuzzy:!0}))}else{let $=k.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:$}),f.push({type:"text",text:k})}}let O=this.extractDOMStrategies(d,c,_?.[1]||P?.[1],l.pageId);f.push(...O);let U=this.extractStructuralContext(d);(U.parent||U.sibling)&&f.forEach(k=>{["role","text","label","testid"].includes(k.type)&&(U.parent&&(k.parent=U.parent),U.sibling&&(k.sibling=U.sibling))}),f.push({type:"css",value:d});let z=g||_?_[1]:P?P[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${s.length}`;s.push({method:u,name:z,action:u==="type"?"fill":u,value:m,strategies:f,timestamp:l.startTime,actualText:g,actualRole:y,actualAriaLabel:h})}}}catch{}return s}catch(r){throw new Error(`Failed to parse trace: ${r.message}`,{cause:r})}}static extractDOMStrategies(e,t,r,o){let s=[];if(!t||t.size===0||!r)return s;try{let i=t.get(o);if(!i)return s;let c=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),l=i.match(a);l&&s.push({type:"testid",value:l[1],priority:"high"});let u=new RegExp(`class=["']([^"']+)["'][^>]*>[^<]*${c}`,"gi"),d=i.matchAll(u);for(let g of d){let y=g[1].split(/\s+/).filter(h=>h&&!h.match(/^(css|jss|makeStyles|MuiBox|MuiStack)-\w+/)&&h.length>2);y.length>0&&(s.push({type:"class",value:y.join("."),priority:"medium"}),y.length===1&&s.push({type:"class",value:y[0],priority:"medium"}))}let m=new RegExp(`id=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),f=i.match(m);f&&!f[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&s.push({type:"id",value:f[1],priority:"high"})}catch(i){console.warn(`[TraceParser] DOM extraction failed: ${i.message}`)}return s}static extractStructuralContext(e){let t={parent:null,sibling:null},r=e.split(">>").map(i=>i.trim());if(r.length>1){let c=r[r.length-2].replace(/internal:text="[^"]+"\s*/gi,"").replace(/internal:role=\S+\s*/gi,"").replace(/internal:label="[^"]+"\s*/gi,"").trim();c&&(c.match(/^(form|section|nav|header|aside|main|article)\b/)||c.includes("[")||c.match(/[#.]\w/))&&(t.parent=c)}let s=r[r.length-1].match(/([^+~]+)\s*[+~]\s*(.+)/);return s&&(t.sibling=s[1].trim()),t}};var ur=class{static async step(e,t){let{name:r,action:o,value:s,strategies:i,options:c={timeout:1e4},enrichedData:a}=t;console.log(`[Zibby] \u26A1 Executing step: ${r}`),await this.waitForPageStability(e,c.timeout);let l=await this.findBestMatch(e,i,r);if(!l)throw new Error(`[Zibby] \u274C Failed to find "${r}" using ${i.length} strategies`);a?.position&&await this.verifyPosition(l,a.position),await this.performActionWithRetry(e,l,o,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 o,s=new MutationObserver(()=>{clearTimeout(o),o=setTimeout(()=>{s.disconnect(),r()},500)});s.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),o=setTimeout(()=>{s.disconnect(),r()},500)})).catch(()=>{})}catch{}}static async verifyPosition(e,t){try{let r=await e.boundingBox();if(!r)return;let o=Math.abs(r.x-t.x),s=Math.abs(r.y-t.y);(o>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,o,s=3){for(let i=1;i<=s;i++)try{r==="click"?await t.click():r==="fill"?await t.fill(o||""):r==="type"?await t.pressSequentially(o||""):r==="selectOption"&&await t.selectOption(o||"");return}catch(c){if(i===s)throw c;console.log(`[Zibby] \u26A0\uFE0F Action failed (attempt ${i}/${s}), retrying...`),await new Promise(a=>setTimeout(a,1e3*i))}}static async findBestMatch(e,t,r){let s=Date.now(),i=t.map(async(l,u)=>{try{let m=await this.getLocator(e,l).all();return m.length===0?[]:(await Promise.all(m.map(async(g,y)=>{try{if(!await g.isVisible({timeout:100}))return null;let b=await this.scoreCandidate(g,l,e);return{element:g,strategy:l,score:b,strategyIdx:u,elIdx:y}}catch{return null}}))).filter(g=>g!==null)}catch{return[]}}),c=(await Promise.all(i)).flat();if(c.length===0)return console.log(`[Zibby] \u274C No visible candidates found for "${r}"`),null;c.sort((l,u)=>u.score-l.score);let a=c[0];return console.log(`[Zibby] \u2705 Found element using ${a.strategy.type} (score: ${a.score.toFixed(2)}, ${c.length} candidates)`),a.element}static async scoreCandidate(e,t,r){let o=0;if(o+={testid:120,id:110,role:100,label:90,class:85,placeholder:85,text:80,css:50}[t.type]||50,t.priority==="high"&&(o+=20),t.priority==="medium"&&(o+=10),t.fuzzy&&(o-=15),t.parent)try{await e.locator("xpath=ancestor::*").first().evaluate((a,l)=>a.matches(l),t.parent)&&(o+=30)}catch{}if(t.sibling)try{await e.evaluate((c,a)=>c.parentElement?.querySelector(a)!==null,t.sibling)&&(o+=20)}catch{}try{let i=await e.boundingBox();i&&i.y<1e3&&(o+=10)}catch{}try{let i=await e.evaluate(c=>{let a=0,l=c;for(;l;)l.tagName==="IFRAME"&&a++,l=l.parentElement;return a});o-=i*5}catch{}return o}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 o=t.value?.replace(/aria-ref=e\d+ >> /g,"")||t.css;r=e.locator(o);break}}return t.parent&&(r=r.filter({has:e.locator(t.parent)})),r}};var pr=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 o=r.timeout||1e4,s=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<o;){await this.injectStableIds(e);let c=e.locator(s);if(await c.count()>0)try{await c.click({timeout:2e3});return}catch(a){if(a.message.includes("intercepts pointer")){await c.click({force:!0});return}}await e.waitForTimeout(200)}throw new Error(`Element ${s} not found after ${o}ms`)}static async fillWithRetry(e,t,r,o=1e4){let s=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<o;){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 ${o}ms`)}static async selectWithRetry(e,t,r,o=1e4){let s=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<o;){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 ${o}ms`)}static async injectStableIds(e){try{await e.evaluate(()=>{function t(a){if(a.getAttribute("aria-label"))return a.getAttribute("aria-label").trim();let l=a.getAttribute("aria-labelledby");if(l){let m=document.getElementById(l);if(m)return m.textContent.trim()}if(a.id){let m=document.querySelector(`label[for="${a.id}"]`);if(m)return m.textContent.trim()}let u=a.closest("label");if(u){let m=u.cloneNode(!0);m.querySelectorAll("input, select, textarea").forEach(g=>g.remove());let f=m.textContent.trim();if(f)return f}if(a.placeholder)return a.placeholder;let d=a.tagName.toLowerCase();return d==="button"||d==="a"||a.getAttribute("role")==="button"?(a.textContent||"").trim().slice(0,50):a.title?a.title:d==="input"&&(a.type==="submit"||a.type==="button")&&a.value||""}function r(a){let l=[],u=a.closest("form");if(u)if(u.id)l.push(`form#${u.id}`);else if(u.name)l.push(`form[name=${u.name}]`);else if(u.action)try{let y=new URL(u.action,window.location.origin).pathname;l.push(`form[action=${y}]`)}catch{l.push(`form[action=${u.getAttribute("action")}]`)}else{let y=document.querySelectorAll("form"),h=Array.from(y).indexOf(u);l.push(`form:nth(${h})`)}let d=a.closest('header, nav, main, footer, aside, [role="banner"], [role="navigation"], [role="main"], [role="contentinfo"]');if(d){let y=d.tagName.toLowerCase(),h=d.getAttribute("role");l.push(h||y)}let m=a.closest('section, article, [role="region"]');if(m){let y=m.querySelector("h1, h2, h3, h4, h5, h6");y&&l.push(`section:${y.textContent.trim().slice(0,30)}`)}let f=a.closest("fieldset");if(f){let y=f.querySelector("legend");y&&l.push(`fieldset:${y.textContent.trim()}`)}let g=a.closest('dialog, [role="dialog"], [role="alertdialog"]');if(g){let y=g.querySelector('[role="heading"], h1, h2, h3');y?l.push(`dialog:${y.textContent.trim().slice(0,30)}`):l.push("dialog")}return l.join("/")}function o(a){let l=a.tagName.toLowerCase(),u=a.id||"",d=a.name||"",m=a.type||"",f=a.getAttribute("role")||"",g="";if(a.href)try{g=new URL(a.href,window.location.origin).pathname.slice(0,50)}catch{g=a.getAttribute("href")?.slice(0,50)||""}let y=t(a).slice(0,50).replace(/\s+/g," "),h=r(a),b=[l,u,d,m,f,g,y,h].join("|"),_=5381;for(let T=0;T<b.length;T++)_=(_<<5)+_^b.charCodeAt(T);return`zibby-${(_>>>0).toString(36)}`}let s=["button","a","input","select","textarea","label[for]",'[role="button"]','[role="link"]','[role="textbox"]','[role="checkbox"]','[role="radio"]','[role="combobox"]','[role="menuitem"]','[role="tab"]','[role="option"]','[role="switch"]','[role="slider"]',"[onclick]","[data-action]"].join(", "),i=new Map,c=0;document.querySelectorAll(s).forEach(a=>{let l=window.getComputedStyle(a);if(l.display==="none"||l.visibility==="hidden")return;let u=o(a),d=u,m=i.get(d)||0;m>0&&(u=`${d}-${m}`),i.set(d,m+1),a.setAttribute("data-zibby-id",u),c++}),console.log(`[Zibby] Injected ${c} stable IDs`)})}catch{}}};var Xi=8,Qi=1,ea=64;function ta(n){if(!n||typeof n!="object")return 8;let e=n.parallel;if(!e||typeof e!="object")return 8;let t=e.maxConcurrentRuns??e.maxConcurrent,r=Number(t);if(!Number.isFinite(r))return 8;let o=Math.floor(r);return o<1?8:Math.min(64,o)}import{readFileSync as na,writeFileSync as Yn,existsSync as oa}from"node:fs";import{join as Zn}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 ra}from"node:fs";import{join as Hn}from"node:path";var xe=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=Hn(e,"traces"),r=Hn(e,"trace.zip");if(ra(r))try{this.traceData=await lt.parseTraceZip(r),console.log(`[TraceTextEnricher] \u2705 Loaded trace with ${this.traceData.length} actions`)}catch(o){console.log(`[TraceTextEnricher] \u26A0\uFE0F Failed to parse trace: ${o.message}`)}}async enrich(e,t){let r=e.data?.params?.ref,o=e.id;if(r===void 0&&o===void 0||(!this.traceData&&t.sessionPath&&await this.loadTrace(t.sessionPath),!this.traceData))return null;let s=this.traceData[o];if(!s)return console.log(`[TraceTextEnricher] \u26A0\uFE0F No trace action for event ${o}`),null;let i=s.actualText||this._extractTextFromSelector(s.selector),c=s.actualRole,a=s.actualAriaLabel;return i||c||a?(console.log(`[TraceTextEnricher] \u2705 Event ${o}: text="${i}", role="${c}", label="${a}"`),{traceActualText:i,traceActualRole:c,traceActualAriaLabel:a,traceSelector:s.selector,traceStrategies:s.strategies}):null}_extractTextFromSelector(e){if(!e)return null;let t=e.match(/internal:label="([^"]+)"/);if(t)return t[1];let r=e.match(/internal:text="([^"]+)"/);if(r)return r[1];let o=e.match(/getByText\(['"]([^'"]+)['"]\)/);if(o)return o[1];let s=e.match(/name:\s*['"]([^'"]+)['"]/);return s?s[1]:null}};async function sa(n){let e=Zn(n,"events.json"),t=Zn(n,"events-enriched.json");if(!oa(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(na(e,"utf-8")),o=new xe,s=0,i=0;for(let c of r)try{let a=await o.enrich(c,{sessionPath:n});a&&(c.enrichedData={...c.enrichedData||{},...a},s++)}catch(a){console.log(`[PostProcess] Failed to enrich event ${c.id}: ${a.message}`),i++}return s>0&&(Yn(t,JSON.stringify(r,null,2)),Yn(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 ia}from"node:child_process";import{existsSync as aa}from"node:fs";import{dirname as la,resolve as Vn,relative as ca}from"node:path";var Ut=new Map,ct=8,Wn={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 ${ct} 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:n},e){let r=`${e?.sessionId||"default"}:${n}`,o=(Ut.get(r)||0)+1;if(Ut.set(r,o),o>ct)return{success:!1,executionCount:o,maxReached:!0,error:`Maximum ${ct} executions reached. Stop retrying and return your best result.`};let s=e?.projectRoot||process.cwd(),i=Vn(s,n),c=ca(s,i);return c.startsWith("..")||Vn(i)!==i&&c.includes("..")?{success:!1,executionCount:o,error:"Path traversal detected: scriptPath must be within the project root."}:aa(i)?new Promise(a=>{let l=la(i),u=ia("npx",["playwright","test",i,"--reporter=line"],{cwd:s,env:{...process.env,FORCE_COLOR:"0"}}),d="",m="";u.stdout.on("data",g=>{d+=g.toString()}),u.stderr.on("data",g=>{m+=g.toString()});let f=setTimeout(()=>{u.kill("SIGTERM"),a({success:!1,executionCount:o,error:"Test timed out after 60 seconds",stdout:d.slice(-2e3),stderr:m.slice(-1e3)})},6e4);u.on("close",g=>{clearTimeout(f);let h=`${d}
|
|
271
271
|
${m}`.split(`
|
|
272
|
-
`),b="",_=null;for(let
|
|
273
|
-
`;for(let A=
|
|
274
|
-
`}if(S.includes("at ")&&S.includes(".spec.")){let A=S.match(/:(\d+):\d+/);A&&(_=parseInt(A[1]))}}a(g===0?{success:!0,executionCount:o,message:"All tests passed!",output:d.slice(-500)}:{success:!1,executionCount:o,remainingAttempts:
|
|
272
|
+
`),b="",_=null;for(let T=0;T<h.length;T++){let S=h[T];if(S.includes("Error:")||S.includes("error:")||S.includes("\u2718")){b+=`${S}
|
|
273
|
+
`;for(let A=T+1;A<Math.min(T+5,h.length);A++)b+=`${h[A]}
|
|
274
|
+
`}if(S.includes("at ")&&S.includes(".spec.")){let A=S.match(/:(\d+):\d+/);A&&(_=parseInt(A[1]))}}a(g===0?{success:!0,executionCount:o,message:"All tests passed!",output:d.slice(-500)}:{success:!1,executionCount:o,remainingAttempts:ct-o,error:b.slice(0,1500)||"Test failed (see output)",failedAtLine:_,stdout:d.slice(-1500),stderr:m.slice(-500),hint:o<ct?"Fix the error and run again.":"Last attempt - make your best fix."})}),u.on("error",g=>{clearTimeout(f),a({success:!1,executionCount:o,error:`Failed to run test: ${g.message}`})})}):{success:!1,executionCount:o,error:`Test file not found: ${i}. Make sure you wrote the file first using the write tool.`}},resetCount(n){for(let e of Ut.keys())e.startsWith(`${n}:`)&&Ut.delete(e)}};function ua(n){Wn.resetCount(n)}var ue=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 qn,writeFileSync as pa}from"node:fs";var je=class extends ue{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(qn(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:o}=e,s=`${r}/execute_live/events.json`,i=o?.title||"Generated Test";console.log("[MCPRefStrategy] \u{1F3AF} Generating test using MCP element descriptions (1:1 replay)"),console.log(`[MCPRefStrategy] events: ${s}`),console.log(`[MCPRefStrategy] output: ${t}`);let a=JSON.parse(qn(s,"utf-8")).filter(u=>["navigate","type","fill","click","select_option"].includes(u.type)),l=`import { test, expect } from '@playwright/test';
|
|
275
275
|
`;l+=`import { ZibbyRuntime } from '@zibby/core';
|
|
276
276
|
|
|
277
277
|
`,l+=`test('${i}', async ({ page }) => {
|
|
278
278
|
`,l+=` const timestamp = Date.now();
|
|
279
279
|
|
|
280
|
-
`;for(let u of a){let d=u.data?.params?.element||"element",m=u.data?.params?.ref,f=u.enrichedData?.traceActualText,g=u.enrichedData?.traceActualRole,y=u.enrichedData?.traceActualAriaLabel,h=u.enrichedData?.actualText,b=f||h,_=g||u.enrichedData?.actualRole,
|
|
280
|
+
`;for(let u of a){let d=u.data?.params?.element||"element",m=u.data?.params?.ref,f=u.enrichedData?.traceActualText,g=u.enrichedData?.traceActualRole,y=u.enrichedData?.traceActualAriaLabel,h=u.enrichedData?.actualText,b=f||h,_=g||u.enrichedData?.actualRole,T=b||d,S=b||this._extractName(d),A=_||this._extractRole(d),P=f?" [accessibility-tree]":h?" [live]":" [AI]";if(u.type==="navigate")l+=` await page.goto('${u.data.params.url}');
|
|
281
281
|
|
|
282
282
|
`;else if(u.type==="click")l+=` // ${d}${b?` (actual: "${b}")${P}`:""}
|
|
283
283
|
`,l+=` await ZibbyRuntime.step(page, {
|
|
@@ -289,18 +289,18 @@ ${m}`.split(`
|
|
|
289
289
|
`,l+=` ]
|
|
290
290
|
`,l+=` });
|
|
291
291
|
|
|
292
|
-
`;else if(u.type==="fill"||u.type==="type"){let
|
|
292
|
+
`;else if(u.type==="fill"||u.type==="type"){let R=u.data.params.text;l+=` // ${d}${b?` (actual: "${b}")${P}`:""}
|
|
293
293
|
`,l+=` await ZibbyRuntime.step(page, {
|
|
294
294
|
`,l+=` name: '${this._escapeString(d)}',
|
|
295
295
|
`,l+=` action: 'fill',
|
|
296
|
-
`,l+=` value: '${this._escapeString(
|
|
296
|
+
`,l+=` value: '${this._escapeString(R)}',
|
|
297
297
|
`,l+=` strategies: [
|
|
298
298
|
`,l+=` { type: 'role', role: '${A}', name: '${this._escapeString(S)}' },
|
|
299
299
|
`,l+=` { type: 'attributes', placeholder: '${this._escapeString(S)}' }
|
|
300
300
|
`,l+=` ]
|
|
301
301
|
`,l+=` });
|
|
302
302
|
|
|
303
|
-
`}else if(u.type==="select_option"){let
|
|
303
|
+
`}else if(u.type==="select_option"){let R=u.data.params.values,O=Array.isArray(R)?R[0]:R;l+=` // ${d}${b?` (actual: "${b}")${P}`:""}
|
|
304
304
|
`,l+=` await ZibbyRuntime.step(page, {
|
|
305
305
|
`,l+=` name: '${this._escapeString(d)}',
|
|
306
306
|
`,l+=` action: 'select',
|
|
@@ -311,7 +311,7 @@ ${m}`.split(`
|
|
|
311
311
|
`,l+=` });
|
|
312
312
|
|
|
313
313
|
`}}return l+=`});
|
|
314
|
-
`,
|
|
314
|
+
`,pa(t,l),console.log(`[MCPRefStrategy] \u2705 Generated test with ${a.length} actions using MCP descriptions`),{success:!0,testPath:t,method:"MCP Reference Replay (1:1)",actionsGenerated:a.length}}_extractRole(e){let t=e.toLowerCase();return t.includes("button")?"button":t.includes("textbox")?"textbox":t.includes("link")?"link":t.includes("checkbox")?"checkbox":t.includes("radio")?"radio":t.includes("combobox")?"combobox":t.includes("heading")?"heading":"button"}_extractName(e){return e.replace(/\s+(button|textbox|link|checkbox|radio|combobox)$/i,"").trim()}_escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}};import{readFileSync as Xn,writeFileSync as fa}from"node:fs";var Be=class extends ue{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(Xn(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:o}=e,s=`${r}/execute_live/events.json`,i=o?.title||"Generated Test";console.log("[StableIdStrategy] \u{1F3AF} Generating test using stable IDs"),console.log(`[StableIdStrategy] events: ${s}`),console.log(`[StableIdStrategy] output: ${t}`);let a=JSON.parse(Xn(s,"utf-8")).filter(m=>["navigate","type","fill","click","select_option","select"].includes(m.type)),l=`import { test, expect } from '@playwright/test';
|
|
315
315
|
`;l+=`import { StableIdRuntime } from '@zibby/core';
|
|
316
316
|
|
|
317
317
|
`,l+=`test('${i}', async ({ page }) => {
|
|
@@ -326,17 +326,17 @@ ${m}`.split(`
|
|
|
326
326
|
`}else if(f.type==="select_option"||f.type==="select"){u=!1;let h=f.data?.values||f.data?.params?.values,b=Array.isArray(h)?h[0]:h||"";g?l+=` await StableIdRuntime.selectWithRetry(page, '${g}', '${this._escapeString(b)}');
|
|
327
327
|
`:l+=` await page.locator('select').selectOption('${this._escapeString(b)}');
|
|
328
328
|
`}}return l+=`});
|
|
329
|
-
`,
|
|
329
|
+
`,fa(t,l),console.log(`[StableIdStrategy] \u2705 Generated test with ${a.length} actions using stable IDs`),{success:!0,testPath:t,method:"Stable ID Injection (Experimental)",actionsGenerated:a.length}}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}_generateSemanticSelector(e){let t=e.toLowerCase(),r="locator",o=e;return t.includes("button")?(r="button",o=e.replace(/\s*button\s*/gi,"").trim()):t.includes("link")?(r="link",o=e.replace(/\s*link\s*/gi,"").trim()):t.includes("textbox")?(r="textbox",o=e.replace(/\s*textbox\s*/gi,"").trim()):t.includes("checkbox")?(r="checkbox",o=e.replace(/\s*checkbox\s*/gi,"").trim()):(t.includes("combobox")||t.includes("dropdown")||t.includes("select"))&&(r="combobox",o=e.replace(/\s*(combobox|dropdown|select)\s*/gi,"").trim()),r!=="locator"&&o?`page.getByRole('${r}', { name: '${this._escapeString(o)}' })`:`page.getByText('${this._escapeString(e)}')`}};var fr=class{constructor(){this.strategies=[new Be,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 generate(e){console.log(`
|
|
330
330
|
\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(`
|
|
331
|
-
\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}},
|
|
331
|
+
\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}},da=new fr;var Fe=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 ma}from"node:child_process";import{existsSync as ga}from"node:fs";var Ge=class extends Fe{getName(){return"Playwright JSON Reporter"}getPriority(){return 100}canVerify(e){let{testFilePath:t}=e;return ga(t)}async verify(e){let{testFilePath:t,cwd:r,timeout:o=3e4}=e;try{console.log(`\u{1F9EA} Running test: ${t}`);let s=`npx playwright test ${t} --reporter=json --timeout=${o}`,i=ma(s,{cwd:r,encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:o+1e4}),a=JSON.parse(i).stats||{};return{success:a.unexpected===0,passed:a.expected||0,failed:a.unexpected||0,error:null,errorDetails:null}}catch(s){let i=s.stdout||s.stderr||s.message;try{let c=JSON.parse(i),a=c.stats||{},l="Test execution failed";if(c.suites&&c.suites.length>0){let d=c.suites[0];if(d.specs&&d.specs.length>0){let m=d.specs[0];if(m.tests&&m.tests.length>0){let f=m.tests[0];if(f.results&&f.results.length>0){let g=f.results[0];g.error&&(l=g.error.message||l)}}}}let u=l.includes("Executable doesn't exist")||l.includes("browserType.launch")||l.includes("Please run the following command")||l.includes("npx playwright install")||i.includes("Executable doesn't exist")||i.includes("npx playwright install");return{success:!1,passed:a.expected||0,failed:a.unexpected||0,error:l,errorDetails:l,isEnvironmentError:u}}catch{let a=i.match(/Error: (.+)/),l=a?a[1]:"Test execution failed",u=l.includes("Executable doesn't exist")||l.includes("browserType.launch")||l.includes("Please run the following command")||l.includes("npx playwright install")||i.includes("Executable doesn't exist")||i.includes("npx playwright install");return{success:!1,passed:0,failed:1,error:l,errorDetails:l,isEnvironmentError:u}}}}};var dr=class{constructor(){this.strategies=[new Ge],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(`
|
|
332
332
|
\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(`
|
|
333
|
-
\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}},
|
|
333
|
+
\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}},ha=new dr;var pe=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},o=[],s=[],i=[];for(let c of this.enrichers)try{if(!c.canEnrich(t)){s.push(c.getName());continue}let a=Date.now(),l=await c.enrich(e,t),u=Date.now()-a;l?(Object.assign(r,l),o.push({name:c.getName(),duration:u})):s.push(c.getName())}catch(a){console.warn(`[EnrichmentPipeline] ${c.getName()} failed:`,a.message),i.push(c.getName()),this.stats.errors[c.getName()]=(this.stats.errors[c.getName()]||0)+1}return r._enrichment={version:"1.0",timestamp:new Date().toISOString(),enrichers:{run:o,skipped:s,failed:i}},o.length>0?this.stats.enrichedEvents++:this.stats.skippedEvents++,r}async enrichBatch(e,t){let r=[];for(let o of e){let s=await this.enrich(o,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(`
|
|
334
334
|
\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(`
|
|
335
|
-
Registered enrichers (${this.enrichers.length}):`);for(let e of this.enrichers){let t=e.enabled?"\u2713":"\u2717",r=this.stats.errors[e.getName()]||0,o=r>0?` (${r} errors)`:"";console.log(` ${t} ${e.getName()} (priority: ${e.getPriority()})${o}`)}console.log()}};var Ke=class extends
|
|
335
|
+
Registered enrichers (${this.enrichers.length}):`);for(let e of this.enrichers){let t=e.enabled?"\u2713":"\u2717",r=this.stats.errors[e.getName()]||0,o=r>0?` (${r} errors)`:"";console.log(` ${t} ${e.getName()} (priority: ${e.getPriority()})${o}`)}console.log()}};var Ke=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:o}=t,s=await o.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 Qn from"node:crypto";var we=class extends W{getName(){return"AccessibilityEnricher"}getPriority(){return 100}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:o}=t,s=await r.accessibility.snapshot(),i=await this.findAxNode(o,s);if(!i)return null;let c=await this.getAxContext(i,s),a=this.hashAxSubtree(i),l=this.hashAxPath(c.path);return{accessibility:{role:i.role,name:i.name||"",level:c.level,parent:c.parent,siblings:c.siblings,axTreeHash:a,axPathHash:l}}}catch(r){return this.handleError(r,e)}}async findAxNode(e,t){let r=await e.evaluate(o=>({role:o.getAttribute("role")||o.tagName.toLowerCase(),name:o.getAttribute("aria-label")||o.textContent?.trim()||"",tagName:o.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 o=this.searchAxTree(r,t);if(o)return o}return null}getAxContext(e,t){let r={level:0,parent:null,siblings:[],path:[]},o=this.findParent(e,t);return o&&(r.parent={role:o.role,name:o.name},r.siblings=(o.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 o of r.children){let s=this.findParent(e,t,o);if(s)return s}return null}calculateLevel(e,t,r=t,o=0){if(r===e)return o;if(r.children)for(let s of r.children){let i=this.calculateLevel(e,t,s,o+1);if(i>=0)return i}return-1}buildPath(e,t,r=t,o=[]){if(r===e)return[...o,{role:r.role,name:r.name}];if(r.children)for(let s of r.children){let i=this.buildPath(e,t,s,[...o,{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 Qn.createHash("md5").update(t).digest("hex").substring(0,12)}hashAxPath(e){let t=e.map(r=>`${r.role}:${r.name}`).join("/");return Qn.createHash("md5").update(t).digest("hex").substring(0,12)}};var Ee=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 o=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,...o}}}catch(r){return this.handleError(r,e)}}async checkDOMStability(e,t=500){try{return await e.evaluate(o=>new Promise(s=>{let i,c=0,a=new MutationObserver(()=>{c++,clearTimeout(i),i=setTimeout(()=>{a.disconnect(),s(c===0)},o)});a.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),i=setTimeout(()=>{a.disconnect(),s(!0)},o)}),t)}catch{return!1}}reset(){this.pendingRequests.clear(),this.setupNetworkTracking=!1}};var ze=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,o=await r.evaluate(s=>{let i=f=>{let g=[],y=f;for(;y&&y!==document.body;){let h=y.tagName.toLowerCase(),b=y.parentElement;if(b){let _=Array.from(b.children).filter(T=>T.tagName===y.tagName);if(_.length>1){let T=_.indexOf(y)+1;h+=`:nth-child(${T})`}}g.unshift(h),y=y.parentElement}return`body > ${g.join(" > ")}`},c=f=>{let g=[],y=f;for(;y&&y!==document.body;){let h=1,b=y.previousSibling;for(;b;)b.nodeType===1&&b.tagName===y.tagName&&h++,b=b.previousSibling;let _=y.tagName.toLowerCase();g.unshift(`${_}[${h}]`),y=y.parentElement}return`/html/body/${g.join("/")}`},a={};for(let f of s.attributes)a[f.name]=f.value;let l=window.getComputedStyle(s),u={display:l.display,visibility:l.visibility,opacity:l.opacity,pointerEvents:l.pointerEvents},d=0,m=s.parentElement;for(;m;)d++,m=m.parentElement;return{path:i(s),xpath:c(s),depth:d,parent:s.parentElement?s.parentElement.tagName.toLowerCase():null,tagName:s.tagName.toLowerCase(),attributes:a,state:{visible:l.display!=="none"&&l.visibility!=="hidden",enabled:!s.disabled,focused:document.activeElement===s,...u}}});return{dom:{path:o.path,xpath:o.xpath,depth:o.depth,parent:o.parent,selector:this.buildSmartSelector(o)},attributes:o.attributes,state:o.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(o=>o&&!o.match(/^(active|focus|hover|disabled)/));r.length>0&&(t+=`.${r.slice(0,2).join(".")}`)}return e.parent&&(t=`${e.parent} > ${t}`),t}};var ut=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,o=e.data?.params?.element;if(!r&&!o)return null;let s=null,i=null,c=null;if(t?.element)try{let a=await t.element.evaluate(l=>({text:l.textContent?.trim()||"",innerText:l.innerText?.trim()||"",value:l.value||"",label:l.getAttribute("aria-label")||l.getAttribute("label")||"",role:l.getAttribute("role")||l.tagName.toLowerCase(),placeholder:l.getAttribute("placeholder")||"",title:l.getAttribute("title")||""}));s=a.text||a.innerText||a.value||a.placeholder,i=a.role,c=a.label||a.title,console.log(`[MCPRefEnricher] \u2705 Captured actual text: "${s}" (AI said: "${o}")`)}catch(a){console.log(`[MCPRefEnricher] \u26A0\uFE0F Could not extract actual text: ${a.message}`)}return{mcpRef:r,mcpElement:o,actualText:s,actualRole:i,actualLabel:c,recordedSelector:s||o}}};function mr(n={}){let e=new pe(n);return n.enableMCPRef!==!1&&e.register(new ut(n)),n.enableTraceText!==!1&&e.register(new xe(n)),n.enableAccessibility!==!1&&e.register(new we(n)),n.enablePageState!==!1&&e.register(new Ee(n)),n.enablePosition!==!1&&e.register(new Ke(n)),n.enableDOM!==!1&&e.register(new ze(n)),e}function gr(n={}){let e=new pe(n);return e.register(new we(n)),e.register(new Ee(n)),e}function ya(n,e={}){let t=new pe(e);for(let r of n)t.register(r);return t}import{readFileSync as ba,writeFileSync as hr}from"node:fs";import{join as eo}from"node:path";async function Sa(n,e={}){let t=eo(n,"events.json"),r=eo(n,"trace.zip");try{let o=JSON.parse(ba(t,"utf-8")),s=o.map(c=>({...c,_enrichmentNote:"Full enrichment requires live Playwright access. Use EnrichmentPipeline during test execution."})),i=`${t}.backup`;return hr(i,JSON.stringify(o,null,2)),hr(t,JSON.stringify(s,null,2)),{enrichedCount:s.length,skippedCount:0,errors:[]}}catch(o){return console.error("[EnrichmentIntegration] Failed to enrich events:",o.message),{enrichedCount:0,skippedCount:0,errors:[o.message]}}}var yr=class{constructor(e={}){this.pipeline=e.minimal?gr(e):mr(e),this.events=[],this.config=e}async recordEvent(e,t,r){let o={id:this.events.length,type:e,timestamp:new Date().toISOString(),data:t},s=await this.pipeline.enrich(o,{...r,event:o});return this.events.push(s),s}saveEvents(e){hr(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()}};Yt();var so=n=>{n?.message?.includes("Connection closed")||n?.message?.includes("MCP error -32000")||n?.code===-32e3||console.error("Unhandled rejection:",n)};process.listeners("unhandledRejection").includes(so)||process.on("unhandledRejection",so);async function va(n,e={}){let{agent:t,mcp:r,headless:o,cwd:s=process.cwd(),specPath:i,sessionPath:c,sessionTimestamp:a,...l}=e,u=to(n,"utf-8"),d=null,{agent:m,error:f}=await Ia(s,l),g=m;if(!g&&e.fallbackAgentModule){let b=e.fallbackAgentModule,_=b.BrowserTestAutomationAgent||b.default;_&&(g=new _(l))}if(!g&&f&&console.warn(`\u26A0\uFE0F Failed to load local agent: ${f}`),!g)throw new Error(`No agent found. Please run:
|
|
336
336
|
zibby init
|
|
337
337
|
|
|
338
338
|
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(`
|
|
339
339
|
\u{1F3AF} Running Single Node: ${e.singleNode} (Framework Mode)
|
|
340
|
-
`);let O=g.calculateOutputPath(i||n),U=g.buildGraph(),z={};for(let[j,w]of U.nodes.entries())z[j]=w.config||w;let k={};if(e.sessionId){let j=e.sessionId,w=e.paths?.output||
|
|
340
|
+
`);let O=g.calculateOutputPath(i||n),U=g.buildGraph(),z={};for(let[j,w]of U.nodes.entries())z[j]=w.config||w;let k={};if(e.sessionId){let j=e.sessionId,w=e.paths?.output||xa;if(j==="last"){let L=Je(s,w,oo);if(ro(L)){let{readdirSync:M,statSync:C}=await import("fs"),G=M(L).filter(v=>C(Je(L,v)).isDirectory()).map(v=>({name:v,time:C(Je(L,v)).mtimeMs})).sort((v,K)=>K.time-v.time);G.length>0?(j=G[0].name,console.log(`\u{1F4C2} Using latest session: ${j}`)):console.log(`\u26A0\uFE0F No sessions found in ${L}`)}}let $=Je(s,w,oo,j),I=Je($,"execute_live"),E=Je(I,wa);ro(E)?(console.log(`\u{1F4C2} Loading session: ${j}`),k={sessionPath:$,execute_live_output:JSON.parse(to(E,"utf-8"))}):console.log(`\u26A0\uFE0F Session not found: ${$}`)}let D=await g.runSingleNode(e.singleNode,z,{testSpec:u,outputPath:O,cwd:s||process.cwd(),contextConfig:e.contextConfig,specPath:i||n,config:e,...k});return typeof g.onComplete=="function"&&await g.onComplete(D),D}let b;typeof e.onPipelineProgress=="function"?b=e.onPipelineProgress:e.runIndex?.pipelineProgress!==!1&&(b=Hr({cwd:s||process.cwd(),config:e}));let _=s||process.cwd(),T=c!=null&&String(c).trim()!==""?(()=>{let O=String(c).trim();try{return _a(O)?no(O):no(_,O)}catch{return O}})():void 0,S=Aa(),A=T??S;Ta();let P=Ea({cwd:_,config:e,traceFrom:"runTest",initialState:{sessionPath:A,sessionTimestamp:a}}),R;try{R=await g.run(u,{testSpec:u,specPath:i||n,cwd:_,config:e,sessionPath:P.sessionPath,sessionTimestamp:P.sessionTimestamp,...b?{onPipelineProgress:b}:{}})}catch(O){throw typeof O?.message=="string"&&O.message.includes("Interrupted by user")&&(s||process.cwd(),void 0),y||(O?.partialResult,O?.message,void 0),O}return R}finally{process.off("SIGINT",h),process.off("SIGTERM",h),await g.cleanup()}}function $a(n){return n.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function Oa(n,e){if(n[e])return n[e];let t=$a(e);if(n[t])return n[t];let r=`${t}Workflow`;return n[r]?n[r]:null}async function md(n=process.cwd()){try{let{join:e}=await import("path"),{existsSync:t}=await import("fs"),{pathToFileURL:r}=await import("url"),o=e(n,".zibby/graph.mjs");if(!t(o))return{available:[],default:null,error:"No .zibby/graph.mjs found"};let s=await import(r(o).href),i=Object.keys(s).filter(a=>a!=="default"&&typeof s[a]=="function"&&s[a].prototype instanceof Re),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 Ia(n,e){try{let{join:t}=await import("path"),{existsSync:r}=await import("fs"),{pathToFileURL:o}=await import("url"),s=t(n,".zibby/graph.mjs");if(!r(s))return{agent:null,error:null};let i=await import(o(s).href),c=e.workflow,a;if(c){if(a=Oa(i,c),!a){let u=Object.keys(i).filter(d=>d!=="default"&&typeof i[d]=="function");throw new Error(`Workflow "${c}" not found.
|
|
341
341
|
Available workflows: ${u.join(", ")}
|
|
342
|
-
Supported formats: QuickSmokeWorkflow, QuickSmoke, quick-smoke`)}let l=Object.keys(i).find(u=>i[u]===a);console.log(`\u2713 Using workflow: ${l} (from --workflow ${c})`)}else{if(a=i.BrowserTestAutomationAgent||i.CursorAgent||i.default,!a){let l=Object.keys(i).filter(u=>u!=="default"&&typeof i[u]=="function"&&i[u].prototype instanceof Re);l.length>0&&(a=i[l[0]],console.log(`\u2713 Using workflow: ${l[0]} (auto-detected)`))}if(!a)return{agent:null,error:"Could not find any WorkflowAgent export in local graph.js"};a.name?.includes("auto-detected")||console.log("\u2713 Using local agent from .zibby/graph.mjs")}return{agent:new a(e),error:null}}catch(t){return{agent:null,error:t.message}}}var
|
|
342
|
+
Supported formats: QuickSmokeWorkflow, QuickSmoke, quick-smoke`)}let l=Object.keys(i).find(u=>i[u]===a);console.log(`\u2713 Using workflow: ${l} (from --workflow ${c})`)}else{if(a=i.BrowserTestAutomationAgent||i.CursorAgent||i.default,!a){let l=Object.keys(i).filter(u=>u!=="default"&&typeof i[u]=="function"&&i[u].prototype instanceof Re);l.length>0&&(a=i[l[0]],console.log(`\u2713 Using workflow: ${l[0]} (auto-detected)`))}if(!a)return{agent:null,error:"Could not find any WorkflowAgent export in local graph.js"};a.name?.includes("auto-detected")||console.log("\u2713 Using local agent from .zibby/graph.mjs")}return{agent:new a(e),error:null}}catch(t){return{agent:null,error:t.message}}}var io=class{constructor(e={}){this.config=e}async run(e){return va(e.spec||e.specPath,{...this.config,...e})}};export{So as AGENT_TYPES,Fu as ALL_TOOLS,we as AccessibilityEnricher,fi as AgentStrategy,Se as AssistantStrategy,Si as CHAT_MEMORY_TOOLS,um as CI_ENV_VARS,mt as CLAUDE_MODEL_MAP,gt as CODEX_MODEL_MAP,_o as CORE_LOG_LEVELS,di as CORE_TOOLS,me as ClaudeAgentStrategy,ge as CodexAgentStrategy,It as CursorAgentStrategy,Xi as DEFAULT_MAX_CONCURRENT_RUNS,ce as DEFAULT_MODELS,om as DEFAULT_OUTPUT_BASE,ze as DOMEnricher,cm as EVENTS_FILE,pe as EnrichmentPipeline,W as EventEnricher,Dt as GEMINI_MODEL_MAP,gi as GITHUB_TOOLS,ye as GeminiAgentStrategy,mi as JIRA_TOOLS,ne as LOG_LEVELS,yr as LiveEnrichmentRecorder,dt as Logger,ea as MAX_MAX_CONCURRENT_RUNS,je as MCPRefStrategy,bi as MEMORY_TOOLS,Qi as MIN_MAX_CONCURRENT_RUNS,Ze as MODEL_REGISTRY,et as McpClientManager,be as OpenAIToolProvider,Jd as PROVIDER_ERROR_KIND_CLASS,Ee as PageStateEnricher,Ge as PlaywrightJsonVerificationStrategy,Ke as PositionEnricher,lm as RAW_OUTPUT_FILE,am as RESULT_FILE,Kn as RIPPLE_EFFECT_SCRIPT,yi as RUNNER_TOOLS,Qt as ResultHandler,sm as SESSIONS_DIR,im as SESSION_INFO_FILE,kd as SKILLS,_i as SKILL_TOOLS,hi as SLACK_TOOLS,it as SelectorGenerator,pr as StableIdRuntime,Be as StableIdStrategy,ae as StreamingParser,xi as TRUSTED_VCS_HOSTS,io as TestAutomation,ue as TestGenerationStrategy,lr as TestPostProcessor,Fe as TestVerificationStrategy,Ce as ToolCallProvider,lt as TraceParser,Re as WorkflowAgent,yd as WorkflowGraph,ur as ZibbyRuntime,ot as ZibbyUploader,nr as authedUrl,rr as authedUrlForRepo,Ve as buildVendorModelMap,bs as checkCursorAgentInstalled,Ki as checkCursorAgentPatched,Bd as classifyFailure,_d as clearInheritedSessionEnvForFreshRun,bn as clearTokenCache,ki as cloneRepo,ya as createCustomPipeline,mr as createDefaultPipeline,gr as createMinimalPipeline,In as createUploader,Sa as enrichRecordedEvents,Gd as formatProviderError,Zi as generateRippleHelperCode,Sd as generateWorkflowSessionId,xn as getAgentStrategy,Ud as getAllSkills,zi as getApprovalKeys,Ss as getCursorAgentInstallInstructions,bo as getPickerModels,Ld as getSkill,Md as hasSkill,Ue as hostnameOf,Yi as injectRippleEffect,pi as invokeAgent,Fd as isTransientFailure,En as isTrustedVcsHost,Dd as listSkillIds,md as listWorkflows,p as logger,$i as organizeVideos,Gi as patchCursorAgentForCI,q as pickFromPool,sa as postProcessEvents,Kd as providerErrorKindOf,zd as providerErrorStatusOf,tr as providerForHost,Rt as providerForRepo,wd as readPinnedSessionPathFromEnv,vn as redactGitSecrets,Yt as registerBuiltInStrategies,Rd as registerSkill,ua as resetExecutionCount,Pt as resolveIntegrationToken,ta as resolveMaxParallelRuns,ho as resolveModelFamily,bd as resolveWorkflowSession,Wn as runPlaywrightTestTool,va as runTest,Hi as saveApprovalKeys,wi as scrubRemoteToTokenless,Ei as securePush,wn as selfHostGitlabHost,Bn as sessionSkill,xd as shouldTrustInheritedSessionEnv,Ed as syncProcessEnvToSession,da as testGenerationManager,ha as testVerificationManager,ie as timeline,An as tokenlessUrl,Is as workflow,vd as z};
|