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