@zibby/core 0.3.12 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- var cn=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});import{readFileSync as tn,existsSync as rn}from"node:fs";import{join as $e,resolve as nn,isAbsolute as li}from"node:path";import{DEFAULT_OUTPUT_BASE as ui,SESSIONS_DIR as sn,RESULT_FILE as pi,resolveWorkflowSession as fi,clearInheritedSessionEnvForFreshRun as di,readPinnedSessionPathFromEnv as mi}from"@zibby/agent-workflow";import{registerStrategy as Le}from"@zibby/agent-workflow";import{AgentStrategy as $n,DEFAULT_OUTPUT_BASE as On,SESSION_INFO_FILE as Pn,STOP_REQUEST_FILE as Cn,getAllSkills as Nn,getSkill as Vt}from"@zibby/agent-workflow";import{spawn as Rn,execSync as ee}from"node:child_process";import{writeFileSync as Qt,readFileSync as er,mkdirSync as tr,existsSync as Ce,accessSync as rr,constants as nr,unlinkSync as kn}from"node:fs";import{join as Y,resolve as Mn}from"node:path";import{homedir as Ne}from"node:os";import Pe from"chalk";var K={debug:0,info:1,warn:2,error:3,silent:4},Ye=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return K.debug;if(process.env.ZIBBY_VERBOSE==="true")return K.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in K?K[e]:K.info}_shouldLog(e){return K[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 K&&(this._level=K[e])}getLevel(){return Object.keys(K).find(e=>K[e]===this._level)}},f=new Ye;var j={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"},ln={ASSISTANT:"assistant",CLAUDE:"claude",CURSOR:"cursor",CODEX:"codex",GEMINI:"gemini"},un={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error",SILENT:"silent"},pt={auto:"claude-sonnet-4-6","sonnet-4.6":"claude-sonnet-4-6","sonnet-4-6":"claude-sonnet-4-6","opus-4.6":"claude-opus-4-6","opus-4-6":"claude-opus-4-6","sonnet-4.5":"claude-sonnet-4-5-20250929","sonnet-4-5":"claude-sonnet-4-5-20250929","opus-4.5":"claude-opus-4-20250514","opus-4-5":"claude-opus-4-20250514","claude-sonnet-4-6":"claude-sonnet-4-6","claude-opus-4-6":"claude-opus-4-6","claude-sonnet-4-5-20250929":"claude-sonnet-4-5-20250929","claude-opus-4-20250514":"claude-opus-4-20250514"},ft={auto:"o4-mini","o4-mini":"o4-mini",o3:"o3","o3-mini":"o3-mini","codex-mini":"codex-mini-latest","gpt-4o":"gpt-4o","gpt-4o-mini":"gpt-4o-mini","gpt-5.2-codex":"gpt-5.2-codex","gpt-5.2":"gpt-5.2","gpt-5.3":"gpt-5.3","gpt-5.4":"gpt-5.4"},Yt={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},He={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var H=class o{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(e){if(!e)return null;this.buffer+=e;let t=this.buffer.split(`
2
- `);this.buffer=t.pop()||"";let r="";for(let n of t)if(n.trim())try{let s=JSON.parse(n);this._emitToolCalls(s);let i=this.extractText(s);if(i){if(this.rawText&&i.startsWith(this.rawText)){let c=i.substring(this.rawText.length);this.rawText=i,r+=c}else(!this.rawText.includes(i)||i.length<20)&&(this.rawText+=i,r+=i);this.tryExtractResult(this.rawText)}else this.isValidResult(s)&&(this.rawText+=`${n}
1
+ var gn=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});import{readFileSync as ln,existsSync as un}from"node:fs";import{join as Oe,resolve as pn,isAbsolute as wi}from"node:path";import{DEFAULT_OUTPUT_BASE as xi,SESSIONS_DIR as fn,RESULT_FILE as _i,resolveWorkflowSession as Ei,clearInheritedSessionEnvForFreshRun as Ti,readPinnedSessionPathFromEnv as vi}from"@zibby/agent-workflow";import{registerStrategy as De}from"@zibby/agent-workflow";import{AgentStrategy as Jn,DEFAULT_OUTPUT_BASE as Kn,SESSION_INFO_FILE as Yn,STOP_REQUEST_FILE as Hn,getAllSkills as Wn,getSkill as or}from"@zibby/agent-workflow";import{spawn as Zn,execSync as te}from"node:child_process";import{writeFileSync as ir,readFileSync as ar,mkdirSync as cr,existsSync as Re,accessSync as lr,constants as ur,unlinkSync as Xn}from"node:fs";import{join as H,resolve as qn}from"node:path";import{homedir as Ne}from"node:os";import Ce from"chalk";var Y={debug:0,info:1,warn:2,error:3,silent:4},He=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return Y.debug;if(process.env.ZIBBY_VERBOSE==="true")return Y.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in Y?Y[e]:Y.info}_shouldLog(e){return Y[e]>=this._level}_formatMessage(e,t,r={}){let n=new Date().toISOString(),i=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(i+=Ce.dim(` ${JSON.stringify(r)}`)),i}_getPrefix(e){return{debug:Ce.gray("[DEBUG]"),info:Ce.cyan("[INFO]"),warn:Ce.yellow("[WARN]"),error:Ce.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 Y&&(this._level=Y[e])}getLevel(){return Object.keys(Y).find(e=>Y[e]===this._level)}},f=new He;var G={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"},hn={ASSISTANT:"assistant",CLAUDE:"claude",CURSOR:"cursor",CODEX:"codex",GEMINI:"gemini"},yn={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error",SILENT:"silent"},mt={auto:"claude-sonnet-4-6","sonnet-4.6":"claude-sonnet-4-6","sonnet-4-6":"claude-sonnet-4-6","opus-4.6":"claude-opus-4-6","opus-4-6":"claude-opus-4-6","sonnet-4.5":"claude-sonnet-4-5-20250929","sonnet-4-5":"claude-sonnet-4-5-20250929","opus-4.5":"claude-opus-4-20250514","opus-4-5":"claude-opus-4-20250514","claude-sonnet-4-6":"claude-sonnet-4-6","claude-opus-4-6":"claude-opus-4-6","claude-sonnet-4-5-20250929":"claude-sonnet-4-5-20250929","claude-opus-4-20250514":"claude-opus-4-20250514"},gt={auto:"o4-mini","o4-mini":"o4-mini",o3:"o3","o3-mini":"o3-mini","codex-mini":"codex-mini-latest","gpt-4o":"gpt-4o","gpt-4o-mini":"gpt-4o-mini","gpt-5.2-codex":"gpt-5.2-codex","gpt-5.2":"gpt-5.2","gpt-5.3":"gpt-5.3","gpt-5.4":"gpt-5.4"},Xt={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},We={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var W=class o{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(e){if(!e)return null;this.buffer+=e;let t=this.buffer.split(`
2
+ `);this.buffer=t.pop()||"";let r="";for(let n of t)if(n.trim())try{let s=JSON.parse(n);this._emitToolCalls(s);let i=this.extractText(s);if(i){if(this.rawText&&i.startsWith(this.rawText)){let a=i.substring(this.rawText.length);this.rawText=i,r+=a}else(!this.rawText.includes(i)||i.length<20)&&(this.rawText+=i,r+=i);this.tryExtractResult(this.rawText)}else this.isValidResult(s)&&(this.rawText+=`${n}
3
3
  `,r+=`${n}
4
- `,this.extractedResult=s)}catch{if(n.includes('"text"')||n.includes('"content"')){let i=n.match(/"text"\s*:\s*"([^"]*)/),c=n.match(/"content"\s*:\s*"([^"]*)/),l=i?i[1]:c?c[1]:null;l&&!this.rawText.includes(l)&&(r+=l,this.rawText+=l)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(i,c)=>{if(!i)return;let l=`${i}:${JSON.stringify(c??{})}`;this._lastToolEmit!==l&&(this._lastToolEmit=l,this.onToolCall(i,c??void 0))},r=i=>{if(i!=null){if(typeof i=="object"&&!Array.isArray(i))return i;if(typeof i=="string")try{return JSON.parse(i)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,r(e.input??e.arguments));return}let i=e.tool_call;if(i&&typeof i=="object"&&!Array.isArray(i)){let c=Object.keys(i);if(c.length===1){let l=c[0],a=i[l],u=a&&typeof a=="object"?a.args??a.input??a:void 0;t(l,r(u))}return}return}if(Array.isArray(e.tool_calls)){for(let i of e.tool_calls)t(i.name,r(i.input??i.arguments));return}let n=e.message??e;if(Array.isArray(n?.tool_calls)){for(let i of n.tool_calls)t(i.name,r(i.input??i.arguments));return}let s=n?.content??e.content;if(Array.isArray(s))for(let i of s)(i.type==="tool_use"||i.type==="tool_call")&&i.name&&t(i.name,r(i.input??i.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return e.type==="thinking"&&e.text||e.text?e.text:e.content&&typeof e.content=="string"?e.content:e.delta?e.delta:null}tryExtractResult(e){if(!e||typeof e!="string")return;let t=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,n;for(;(n=r.exec(e))!==null;){let d=n[1].trim();try{JSON.parse(d),t.push({text:d,source:"markdown"})}catch{}}let s=0,i=0;for(;s<e.length&&(s=e.indexOf("{",s),s!==-1);){let d=0,m=s;for(let p=s;p<e.length;p++)if(e[p]==="{")d++;else if(e[p]==="}"&&(d--,d===0)){m=p,t.push({text:e.substring(s,m+1),source:"brace"}),i++;break}s=m+1}let c=this.extractedResult,l=c?JSON.stringify(c).length:0,a=0,u=-1;for(let d=0;d<t.length;d++){let m=t[d];try{let p=m.text.replace(/,(\s*[}\]])/g,"$1"),g=JSON.parse(p);this.isValidResult(g)&&(a++,l=JSON.stringify(g).length,c=g,u=d)}catch{}}c&&(this.extractedResult=c)}isValidResult(e){if(!e||typeof e!="object"||Array.isArray(e)||e.session_id||e.timestamp_ms||e.type||e.call_id||e.tool_call||e.result&&typeof e.result=="object"&&(e.result.success&&typeof e.result.success=="object"||e.result.error&&typeof e.result.error=="object")||e.args&&typeof e.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(e),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(e,t=null){let r=new o;r.zodSchema=t,r.processChunk(e),r.flush();let n=r.getResult();return!n&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),n}};import{zodToJsonSchema as pn}from"zod-to-json-schema";var We=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=pn(e,{target:"openApi3"}):r=e;let n=this._buildExample(r);return`
4
+ `,this.extractedResult=s)}catch{if(n.includes('"text"')||n.includes('"content"')){let i=n.match(/"text"\s*:\s*"([^"]*)/),a=n.match(/"content"\s*:\s*"([^"]*)/),c=i?i[1]:a?a[1]:null;c&&!this.rawText.includes(c)&&(r+=c,this.rawText+=c)}}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,a)=>{if(!i)return;let c=`${i}:${JSON.stringify(a??{})}`;this._lastToolEmit!==c&&(this._lastToolEmit=c,this.onToolCall(i,a??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 a=Object.keys(i);if(a.length===1){let c=a[0],l=i[c],u=l&&typeof l=="object"?l.args??l.input??l:void 0;t(c,r(u))}return}return}if(Array.isArray(e.tool_calls)){for(let i of e.tool_calls)t(i.name,r(i.input??i.arguments));return}let n=e.message??e;if(Array.isArray(n?.tool_calls)){for(let i of n.tool_calls)t(i.name,r(i.input??i.arguments));return}let s=n?.content??e.content;if(Array.isArray(s))for(let i of s)(i.type==="tool_use"||i.type==="tool_call")&&i.name&&t(i.name,r(i.input??i.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return e.type==="thinking"&&e.text||e.text?e.text:e.content&&typeof e.content=="string"?e.content:e.delta?e.delta:null}tryExtractResult(e){if(!e||typeof e!="string")return;let t=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,n;for(;(n=r.exec(e))!==null;){let m=n[1].trim();try{JSON.parse(m),t.push({text:m,source:"markdown"})}catch{}}let s=0,i=0;for(;s<e.length&&(s=e.indexOf("{",s),s!==-1);){let m=0,d=s;for(let p=s;p<e.length;p++)if(e[p]==="{")m++;else if(e[p]==="}"&&(m--,m===0)){d=p,t.push({text:e.substring(s,d+1),source:"brace"}),i++;break}s=d+1}let a=this.extractedResult,c=a?JSON.stringify(a).length:0,l=0,u=-1;for(let m=0;m<t.length;m++){let d=t[m];try{let p=d.text.replace(/,(\s*[}\]])/g,"$1"),g=JSON.parse(p);this.isValidResult(g)&&(l++,c=JSON.stringify(g).length,a=g,u=m)}catch{}}a&&(this.extractedResult=a)}isValidResult(e){if(!e||typeof e!="object"||Array.isArray(e)||e.session_id||e.timestamp_ms||e.type||e.call_id||e.tool_call||e.result&&typeof e.result=="object"&&(e.result.success&&typeof e.result.success=="object"||e.result.error&&typeof e.result.error=="object")||e.args&&typeof e.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(e),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(e,t=null){let r=new o;r.zodSchema=t,r.processChunk(e),r.flush();let n=r.getResult();return!n&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),n}};import{zodToJsonSchema as Sn}from"zod-to-json-schema";var Ze=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=Sn(e,{target:"openApi3"}):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
@@ -21,9 +21,9 @@ JSON types (strict \u2014 validators reject wrong types):
21
21
  - Use true/false without quotes for booleans.
22
22
  - Use unquoted null where a field may be null.
23
23
 
24
- Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(e){if(!e)return{};let t=e.type;if(t==="object"&&e.properties){let r={};for(let[n,s]of Object.entries(e.properties))r[n]=this._buildExample(s);return r}if(t==="array"&&e.items)return[this._buildExample(e.items)];if(e.enum&&Array.isArray(e.enum)&&e.enum.length>0)return`<${e.enum.join("|")}>`;if(t==="string")return"<string>";if(t==="number"||t==="integer")return 0;if(t==="boolean")return!1;if(e.description)return`<${e.description}>`;if(e.nullable||e.oneOf||e.anyOf){let r=e.oneOf?.find(n=>n.type!=="null")||e.anyOf?.find(n=>n.type!=="null");return r?this._buildExample(r):null}return"<value>"}};var de=class o{constructor(e=""){this.userPrompt=e,this.systemInstructions=[],this.metadata={}}setUserPrompt(e){return this.userPrompt=e,this}appendUserPrompt(e){return this.userPrompt?this.userPrompt+=`
24
+ Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(e){if(!e)return{};let t=e.type;if(t==="object"&&e.properties){let r={};for(let[n,s]of Object.entries(e.properties))r[n]=this._buildExample(s);return r}if(t==="array"&&e.items)return[this._buildExample(e.items)];if(e.enum&&Array.isArray(e.enum)&&e.enum.length>0)return`<${e.enum.join("|")}>`;if(t==="string")return"<string>";if(t==="number"||t==="integer")return 0;if(t==="boolean")return!1;if(e.description)return`<${e.description}>`;if(e.nullable||e.oneOf||e.anyOf){let r=e.oneOf?.find(n=>n.type!=="null")||e.anyOf?.find(n=>n.type!=="null");return r?this._buildExample(r):null}return"<value>"}};var me=class o{constructor(e=""){this.userPrompt=e,this.systemInstructions=[],this.metadata={}}setUserPrompt(e){return this.userPrompt=e,this}appendUserPrompt(e){return this.userPrompt?this.userPrompt+=`
25
25
 
26
- ${e}`:this.userPrompt=e,this}addSkillHints(e){return e&&this.systemInstructions.push({type:"skill_hints",content:e,position:"prepend"}),this}addStructuredOutput(e,t){if(e&&t){let r=We.generateFileOutputInstructions(e,t);this.systemInstructions.push({type:"structured_output",content:r,position:"append"}),this.metadata.structuredOutputPath=t}return this}addExtraInstructions(e){if(e?.trim()){let t=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
26
+ ${e}`:this.userPrompt=e,this}addSkillHints(e){return e&&this.systemInstructions.push({type:"skill_hints",content:e,position:"prepend"}),this}addStructuredOutput(e,t){if(e&&t){let r=Ze.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,19 @@ ${e.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:t,p
31
31
 
32
32
  `),position:"append"}),this}addSystemInstruction(e,t="custom",r="append"){return e&&this.systemInstructions.push({type:t,content:e,position:r}),this}getUserPrompt(){return this.userPrompt}getSystemInstructions(){return this.systemInstructions}getMetadata(){return this.metadata}build(){let e=this.systemInstructions.filter(n=>n.position==="prepend").map(n=>n.content),t=this.systemInstructions.filter(n=>n.position==="append").map(n=>n.content);return[...e,this.userPrompt,...t].filter(Boolean).join(`
33
33
 
34
- `)}getStats(){let e=this.userPrompt.length,t=this.build().length;return{userPromptLength:e,fullPromptLength:t,systemInstructionsLength:t-e,instructionCount:this.systemInstructions.length,instructionTypes:this.systemInstructions.map(r=>r.type)}}clone(){let e=new o(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};import fn from"axios";import{homedir as dn}from"node:os";import{join as mn}from"node:path";import{existsSync as gn,readFileSync as hn}from"node:fs";import{toJSONSchema as yn}from"zod";function Sn(){if(process.env.OPENAI_PROXY_TOKEN)return f.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return f.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let o=mn(dn(),".zibby","config.json");if(gn(o)){let e=JSON.parse(hn(o,"utf-8"));if(e.sessionToken)return f.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(o){f.debug(`[Auth] Could not read zibby login session: ${o.message}`)}return null}function bn(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function me(o){if(!(typeof o!="object"||o===null)){if(Object.keys(o).length===0){o.type="object",o.additionalProperties=!0;return}if(o.type||(o.properties?o.type="object":o.items&&(o.type="array")),o.type==="object")if(o.properties){for(let[e,t]of Object.entries(o.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(o.properties[e]={type:["object","null"]});o.additionalProperties=!1,o.required=Object.keys(o.properties),Object.values(o.properties).forEach(me)}else"additionalProperties"in o||(o.additionalProperties=!0);o.type==="array"&&o.items&&me(o.items),o.anyOf&&o.anyOf.forEach(me),o.oneOf&&o.oneOf.forEach(me),o.allOf&&o.allOf.forEach(me)}}async function Ht(o,e){f.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=Sn();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=bn();f.info(`\u{1F517} Using OpenAI proxy: ${r}`);let n=yn(e),s=n;if(n.$ref&&n.definitions){let u=n.$ref.split("/").pop();s=n.definitions[u]||n,f.debug(`Extracted schema from $ref: ${u}`)}delete s.$schema,me(s);let i=4e5,c=o;o.length>i&&(f.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${o.length} chars) exceeds limit, keeping last ${i} chars`),c=`... [truncated early content] ...
35
- ${o.slice(-i)}`);let l=`Extract and format the following information into structured JSON matching the schema.
34
+ `)}getStats(){let e=this.userPrompt.length,t=this.build().length;return{userPromptLength:e,fullPromptLength:t,systemInstructionsLength:t-e,instructionCount:this.systemInstructions.length,instructionTypes:this.systemInstructions.map(r=>r.type)}}clone(){let e=new o(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};import bn from"axios";import{homedir as wn}from"node:os";import{join as xn}from"node:path";import{existsSync as _n,readFileSync as En}from"node:fs";import{toJSONSchema as Tn}from"zod";function vn(){if(process.env.OPENAI_PROXY_TOKEN)return f.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return f.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let o=xn(wn(),".zibby","config.json");if(_n(o)){let e=JSON.parse(En(o,"utf-8"));if(e.sessionToken)return f.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(o){f.debug(`[Auth] Could not read zibby login session: ${o.message}`)}return null}function An(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function ge(o){if(!(typeof o!="object"||o===null)){if(Object.keys(o).length===0){o.type="object",o.additionalProperties=!0;return}if(o.type||(o.properties?o.type="object":o.items&&(o.type="array")),o.type==="object")if(o.properties){for(let[e,t]of Object.entries(o.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(o.properties[e]={type:["object","null"]});o.additionalProperties=!1,o.required=Object.keys(o.properties),Object.values(o.properties).forEach(ge)}else"additionalProperties"in o||(o.additionalProperties=!0);o.type==="array"&&o.items&&ge(o.items),o.anyOf&&o.anyOf.forEach(ge),o.oneOf&&o.oneOf.forEach(ge),o.allOf&&o.allOf.forEach(ge)}}async function qt(o,e){f.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=An();f.info(`\u{1F517} Using OpenAI proxy: ${r}`);let n=Tn(e),s=n;if(n.$ref&&n.definitions){let u=n.$ref.split("/").pop();s=n.definitions[u]||n,f.debug(`Extracted schema from $ref: ${u}`)}delete s.$schema,ge(s);let i=4e5,a=o;o.length>i&&(f.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${o.length} chars) exceeds limit, keeping last ${i} chars`),a=`... [truncated early content] ...
35
+ ${o.slice(-i)}`);let c=`Extract and format the following information into structured JSON matching the schema.
36
36
 
37
37
  RAW CONTENT:
38
- ${c}
38
+ ${a}
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:s,strict:!0}}};f.info(`\u{1F4E4} Sending to OpenAI proxy: model=${j.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(s.properties||{}).join(", ")}`),f.debug(` Schema size: ${JSON.stringify(s).length} chars`),f.debug(` Prompt size: ${l.length} chars`);try{let u={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(u["x-proxy-token"]=t,u["x-execution-id"]=process.env.EXECUTION_ID||""):(u.Authorization=`Bearer ${t}`,u["x-api-key"]=process.env.ZIBBY_API_KEY||"",u["x-execution-id"]=process.env.EXECUTION_ID||"");let m=(await fn.post(r,a,{headers:u,timeout:He.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!m)throw new Error("OpenAI proxy returned empty response");let p=JSON.parse(m);return f.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:p,raw:o}}catch(u){if(u.response){let d=u.response.status,m=u.response.data;throw f.error(`\u274C OpenAI proxy request failed: ${d}`),f.error(` Status: ${d}`),f.error(` Response: ${JSON.stringify(m,null,2)}`),d===401||d===403?new Error(`Authentication failed for OpenAI proxy.
40
+ Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,l={model:G.OPENAI_POSTPROCESSING,messages:[{role:"user",content:c}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:s,strict:!0}}};f.info(`\u{1F4E4} Sending to OpenAI proxy: model=${G.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(s.properties||{}).join(", ")}`),f.debug(` Schema size: ${JSON.stringify(s).length} chars`),f.debug(` Prompt size: ${c.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 d=(await bn.post(r,l,{headers:u,timeout:We.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!d)throw new Error("OpenAI proxy returned empty response");let p=JSON.parse(d);return f.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:p,raw:o}}catch(u){if(u.response){let m=u.response.status,d=u.response.data;throw f.error(`\u274C OpenAI proxy request failed: ${m}`),f.error(` Status: ${m}`),f.error(` Response: ${JSON.stringify(d,null,2)}`),m===401||m===403?new Error(`Authentication failed for OpenAI proxy.
41
41
  Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
42
- Response: ${JSON.stringify(m)}`,{cause:u}):new Error(`Failed to format Cursor output: ${m?.error?.message||"Unknown error"}`,{cause:u})}throw f.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}function J(o){let e=`${o}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let r=t.split(/[,\n]+/).map(i=>i.trim()).filter(Boolean);if(r.length===0)return{picked:null,count:0,dispose:()=>{}};let n=r[Math.floor(Math.random()*r.length)],s=process.env[o];return process.env[o]=n,f.debug(`[auth-pool] ${o}: picked 1 of ${r.length} from pool (***${n.slice(-4)})`),{picked:n,count:r.length,dispose(){s===void 0?delete process.env[o]:process.env[o]=s}}}import{timeline as W,Timeline as Fi,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as ji}from"@zibby/agent-workflow";import{copyFileSync as wn,existsSync as dt,lstatSync as xn,mkdirSync as Wt,rmSync as _n,symlinkSync as En,unlinkSync as Tn}from"node:fs";import{join as Z}from"node:path";import{homedir as vn}from"node:os";import{randomBytes as An}from"node:crypto";var In=["cli-config.json","config.json","auth.json","argv.json"];function Zt(o){return!(!o||typeof o!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function Xt(o){let e=Z(o||process.cwd(),".zibby","tmp");Wt(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${An(4).toString("hex")}`,r=Z(e,`cursor-agent-home-${t}`),n=Z(r,".cursor");Wt(n,{recursive:!0});let s=vn(),i=Z(s,".cursor");if(dt(i))for(let c of In){let l=Z(i,c);if(dt(l))try{wn(l,Z(n,c))}catch{}}if(process.platform==="darwin"){let c=Z(s,"Library");if(dt(c))try{En(c,Z(r,"Library"))}catch{}}return r}function qt(o){if(!(!o||typeof o!="string"))try{let e=Z(o,"Library");try{xn(e).isSymbolicLink()&&Tn(e)}catch{}_n(o,{recursive:!0,force:!0})}catch{}}var te=class extends $n{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[Y(Ne(),".local","bin","cursor-agent"),Y(Ne(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"];for(let r of t)try{if(r.startsWith("/")){rr(r,nr.X_OK);let n=ee(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(n&&n.length>0)return f.debug(`[Cursor] Found agent at: ${r} (version: ${n.trim().slice(0,50)})`),!0}else{let n=ee(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!n)continue;let s=ee(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return f.debug(`[Cursor] Found '${r}' in PATH at ${n} (version: ${s.trim().slice(0,50)})`),!0}}catch{continue}return f.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:r=process.cwd(),print:n=!1,schema:s=null,skills:i=null,sessionPath:c=null,nodeName:l=null,timeout:a=He.CURSOR_AGENT_DEFAULT,config:u={},signal:d=null}=t,m=u?.agent?.strictMode||!1,p=t.model??u?.agent?.cursor?.model??j.CURSOR,g=J("CURSOR_API_KEY");try{f.debug(`[Cursor] Invoking (model: ${p}, timeout: ${a/1e3}s, skills: ${JSON.stringify(i)})`);let h=(this._setupMcpConfig(c,r,u,i,l)||{}).isolatedMcpHome??null,b=[Y(Ne(),".local","bin","cursor-agent"),Y(Ne(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],x=null;for(let O of b)try{if(O.startsWith("/"))rr(O,nr.X_OK),ee(`"${O}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!ee(`which ${O}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");ee(`${O} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}x=O,f.debug(`[Agent] Using binary: ${O}`);break}catch(y){f.debug(`[Agent] Binary '${O}' check failed: ${y.message}`);continue}if(!x)throw new Error(`Cursor Agent CLI not found or not working.
42
+ Response: ${JSON.stringify(d)}`,{cause:u}):new Error(`Failed to format Cursor output: ${d?.error?.message||"Unknown error"}`,{cause:u})}throw f.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}import{execSync as In}from"node:child_process";import{existsSync as Qt,mkdirSync as $n}from"node:fs";import{join as Vt,resolve as On}from"node:path";var Pn="/workspace/repos",Cn=".zibby/repos";function er(){return process.env.REPOS?Pn:On(process.cwd(),Cn)}function Rn(o){return String(o).replace(/\//g,"-")}function Nn(){let o=process.env.REPOS;if(!o)return[];try{let e=JSON.parse(o);return Array.isArray(e)?e:[]}catch{return[]}}function Xe(o={}){let e=o.baseDir||er();return Nn().map((r,n)=>{let s=Vt(e,Rn(r.name));return{name:r.name,url:r.cloneUrl||r.url||null,branch:r.branch||null,provider:r.provider||"github",localPath:s,isCheckedOut:Qt(Vt(s,".git")),primary:n===0}})}function ht(o,e={}){let t=Xe(e);return t.length===0?null:o?t.find(r=>r.name===o)||null:t[0]}function kn(o,e={}){let t=ht(o,e);return t?t.localPath:null}async function Mn(o,e={}){let{branch:t=null,depth:r=1,baseDir:n=er()}=e,s=ht(o,{baseDir:n});if(!s){let l=Xe({baseDir:n}).map(u=>u.name).join(", ")||"(none)";throw new Error(`No repo "${o||"primary"}" configured for this workflow. Available: ${l}. Configure repos under project integrations, or set the REPOS env var.`)}if(s.isCheckedOut)return s.localPath;let i=s.provider==="gitlab"?process.env.GITLAB_TOKEN:process.env.GITHUB_TOKEN;if(!i)throw new Error(`${s.provider==="gitlab"?"GITLAB_TOKEN":"GITHUB_TOKEN"} not set \u2014 cannot clone ${s.name}. Connect the integration under project settings.`);if(!s.url)throw new Error(`Repo "${s.name}" has no clone URL configured.`);Qt(n)||$n(n,{recursive:!0});let a=s.provider==="gitlab"?s.url.replace(/^https:\/\//,`https://oauth2:${i}@`):s.url.replace(/^https:\/\//,`https://x-access-token:${i}@`),c=["clone"];r>0&&c.push("--depth",String(r)),(t||s.branch)&&c.push("--branch",t||s.branch),c.push(a,s.localPath);try{In(`git ${c.join(" ")}`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}catch(l){let u=String(l.message||l).replace(i,"***").replace(a,s.url);throw new Error(`Failed to clone ${s.name}: ${u}`,{cause:l})}return s.localPath}function ee(o={}){let e=Xe(o);if(e.length===0)return null;let t=["## Available repositories",""];for(let r of e){let n=r.isCheckedOut?"already checked out at":"will be checked out to",s=r.primary?" (primary)":"";t.push(`- \`${r.name}\`${s} \u2014 ${n} \`${r.localPath}\``)}return t.push(""),t.push(`To materialize a repo: call the \`git_checkout\` skill with the repo name (e.g. \`git_checkout({ url: "${e[0].name}" })\`). In code, \`import { ensureRepo } from "@zibby/core"\` and \`await ensureRepo()\` returns the local path (clones on first call, no-op after).`),t.join(`
43
+ `)}function J(o){let e=`${o}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let r=t.split(/[,\n]+/).map(i=>i.trim()).filter(Boolean);if(r.length===0)return{picked:null,count:0,dispose:()=>{}};let n=r[Math.floor(Math.random()*r.length)],s=process.env[o];return process.env[o]=n,f.debug(`[auth-pool] ${o}: picked 1 of ${r.length} from pool (***${n.slice(-4)})`),{picked:n,count:r.length,dispose(){s===void 0?delete process.env[o]:process.env[o]=s}}}import{timeline as Z,Timeline as ta,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as ra}from"@zibby/agent-workflow";import{copyFileSync as Ln,existsSync as yt,lstatSync as Dn,mkdirSync as tr,rmSync as Un,symlinkSync as Bn,unlinkSync as Fn}from"node:fs";import{join as X}from"node:path";import{homedir as jn}from"node:os";import{randomBytes as Gn}from"node:crypto";var zn=["cli-config.json","config.json","auth.json","argv.json"];function rr(o){return!(!o||typeof o!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function nr(o){let e=X(o||process.cwd(),".zibby","tmp");tr(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${Gn(4).toString("hex")}`,r=X(e,`cursor-agent-home-${t}`),n=X(r,".cursor");tr(n,{recursive:!0});let s=jn(),i=X(s,".cursor");if(yt(i))for(let a of zn){let c=X(i,a);if(yt(c))try{Ln(c,X(n,a))}catch{}}if(process.platform==="darwin"){let a=X(s,"Library");if(yt(a))try{Bn(a,X(r,"Library"))}catch{}}return r}function sr(o){if(!(!o||typeof o!="string"))try{let e=X(o,"Library");try{Dn(e).isSymbolicLink()&&Fn(e)}catch{}Un(o,{recursive:!0,force:!0})}catch{}}var re=class extends Jn{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[H(Ne(),".local","bin","cursor-agent"),H(Ne(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"];for(let r of t)try{if(r.startsWith("/")){lr(r,ur.X_OK);let n=te(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(n&&n.length>0)return f.debug(`[Cursor] Found agent at: ${r} (version: ${n.trim().slice(0,50)})`),!0}else{let n=te(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!n)continue;let s=te(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return f.debug(`[Cursor] Found '${r}' in PATH at ${n} (version: ${s.trim().slice(0,50)})`),!0}}catch{continue}return f.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:r=process.cwd(),print:n=!1,schema:s=null,skills:i=null,sessionPath:a=null,nodeName:c=null,timeout:l=We.CURSOR_AGENT_DEFAULT,config:u={},signal:m=null}=t,d=u?.agent?.strictMode||!1,p=t.model??u?.agent?.cursor?.model??G.CURSOR,g=J("CURSOR_API_KEY");try{f.debug(`[Cursor] Invoking (model: ${p}, timeout: ${l/1e3}s, skills: ${JSON.stringify(i)})`);let h=(this._setupMcpConfig(a,r,u,i,c)||{}).isolatedMcpHome??null,S=[H(Ne(),".local","bin","cursor-agent"),H(Ne(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],_=null;for(let w of S)try{if(w.startsWith("/"))lr(w,ur.X_OK),te(`"${w}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!te(`which ${w}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");te(`${w} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}_=w,f.debug(`[Agent] Using binary: ${w}`);break}catch(O){f.debug(`[Agent] Binary '${w}' check failed: ${O.message}`);continue}if(!_)throw new Error(`Cursor Agent CLI not found or not working.
43
44
 
44
45
  Checked paths:
45
- ${b.map(O=>` - ${O}`).join(`
46
+ ${S.map(w=>` - ${w}`).join(`
46
47
  `)}
47
48
 
48
49
  Install cursor-agent:
@@ -51,58 +52,60 @@ Install cursor-agent:
51
52
  Then add to PATH:
52
53
  echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
53
54
 
54
- Test with: agent --version`);let T=new de(e),w=null;if(s){let O=`zibby-result-${Date.now()}.json`;w=Y(r,".zibby","tmp",O);let y=Y(r,".zibby","tmp");Ce(y)||tr(y,{recursive:!0}),T.addStructuredOutput(s,w)}let I=process.env.CURSOR_API_KEY,$=I?` | key: ***${I.slice(-4)}`:" | key: not set";console.log(`
55
- \u25C6 Model: ${p||"auto"}${$}
56
- `);let C=(await import("chalk")).default,v=T.getUserPrompt();console.log(`
57
- ${C.bold("Prompt sent to LLM:")}`),console.log(C.dim("\u2500".repeat(60))),console.log(C.dim(v)),console.log(C.dim("\u2500".repeat(60)));let A=T.build(),D=T.getStats(),E=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",p||"auto"];if(process.env.CURSOR_API_KEY&&E.push("--api-key",process.env.CURSOR_API_KEY),E.push(A),f.debug(`[Agent] User prompt: ${D.userPromptLength} chars, System instructions: ${D.systemInstructionsLength} chars (${D.instructionCount} blocks), Full: ${D.fullPromptLength} chars, model: ${p||"auto"}`),f.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${p||"auto"} (from .zibby.config.js agent.cursor.model)
58
- `)}catch{}let R,M=null;try{let O=c||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);R=await this._spawnWithStreaming(x,E,r,a,null,O,h,d)}catch(O){M=O}let N=R?.stdout||"";if(s){let O=typeof s.parse=="function",y=null,k=!!(w&&Ce(w));if(w&&f.info(`[Agent] Result file: ${k?"present":"missing"} at ${w}`),k)try{let _=er(w,"utf-8").trim();y=JSON.parse(_),f.info(`[Agent] Parsed JSON from result file OK (${_.length} chars) \u2192 object ready for validation`),M&&f.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(_){f.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${_.message}`)}else if(M)f.warn(`[Agent] Result file missing at ${w} (agent process error \u2014 may still recover if strictMode repairs)`);else throw f.error(`\u274C [Agent] Result file was never created at ${w}`),new Error(`Agent did not write required result file at ${w}`);if(y&&O)try{let _=s.parse(y);return f.info("\u2705 [Agent] Zod validation passed for structured result file"),m&&f.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:N,structured:_}}catch(_){let B=_.issues?_.issues.map(L=>` - ${L.path.join(".")}: ${L.message}`).join(`
59
- `):_.message?.slice(0,400);if(f.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
60
- ${B}`),f.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
61
- ${JSON.stringify(y,null,2).slice(0,500)}`),!m)throw new Error(`Agent output failed schema validation:
62
- ${B}
55
+ Test with: agent --version`);let A=new me(e),E=ee();E&&A.addSystemInstruction(E,"repo_context","prepend");let v=null;if(s){let w=`zibby-result-${Date.now()}.json`;v=H(r,".zibby","tmp",w);let O=H(r,".zibby","tmp");Re(O)||cr(O,{recursive:!0}),A.addStructuredOutput(s,v)}let P=process.env.CURSOR_API_KEY,M=P?` | key: ***${P.slice(-4)}`:" | key: not set";console.log(`
56
+ \u25C6 Model: ${p||"auto"}${M}
57
+ `);let T=(await import("chalk")).default,C=A.getUserPrompt();console.log(`
58
+ ${T.bold("Prompt sent to LLM:")}`),console.log(T.dim("\u2500".repeat(60))),console.log(T.dim(C)),console.log(T.dim("\u2500".repeat(60)));let U=A.build(),x=A.getStats(),N=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",p||"auto"];if(process.env.CURSOR_API_KEY&&N.push("--api-key",process.env.CURSOR_API_KEY),N.push(U),f.debug(`[Agent] User prompt: ${x.userPromptLength} chars, System instructions: ${x.systemInstructionsLength} chars (${x.instructionCount} blocks), Full: ${x.fullPromptLength} chars, model: ${p||"auto"}`),f.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${p||"auto"} (from .zibby.config.js agent.cursor.model)
59
+ `)}catch{}let k,R=null;try{let w=a||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);k=await this._spawnWithStreaming(_,N,r,l,null,w,h,m)}catch(w){R=w}let L=k?.stdout||"";if(s){let w=typeof s.parse=="function",O=null,b=!!(v&&Re(v));if(v&&f.info(`[Agent] Result file: ${b?"present":"missing"} at ${v}`),b)try{let I=ar(v,"utf-8").trim();O=JSON.parse(I),f.info(`[Agent] Parsed JSON from result file OK (${I.length} chars) \u2192 object ready for validation`),R&&f.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(I){f.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${I.message}`)}else if(R)f.warn(`[Agent] Result file missing at ${v} (agent process error \u2014 may still recover if strictMode repairs)`);else throw f.error(`\u274C [Agent] Result file was never created at ${v}`),new Error(`Agent did not write required result file at ${v}`);if(O&&w)try{let I=s.parse(O);return f.info("\u2705 [Agent] Zod validation passed for structured result file"),d&&f.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:L,structured:I}}catch(I){let $=I.issues?I.issues.map(B=>` - ${B.path.join(".")}: ${B.message}`).join(`
60
+ `):I.message?.slice(0,400);if(f.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
61
+ ${$}`),f.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
62
+ ${JSON.stringify(O,null,2).slice(0,500)}`),!d)throw new Error(`Agent output failed schema validation:
63
+ ${$}
63
64
 
64
65
  The agent wrote invalid data that doesn't match the required outputSchema.
65
- Enable strictMode in .zibby.config.js for automatic repair.`,{cause:_})}else{if(y)return f.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),m&&f.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:N,structured:y};k&&f.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(m&&!M){let _=R.parsedText,B=y?JSON.stringify(y):_;f.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${B.length} chars in)`);try{let L=await Ht(B,s);if(O){let F=s.parse(L.structured);return f.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:N,structured:F}}return{raw:N,...L}}catch(L){if(f.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${L.message}`),y)return f.warn("[Agent] Using agent's original result file as fallback"),{raw:N,structured:y}}}if(M)throw M;let P=k?y==null?"file existed but JSON.parse failed \u2014 see WARN log above":O?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw f.error(`\u274C [Agent] No validated structured output: ${P}`),f.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error(`Agent did not produce a valid result file at ${w}. Enable strictMode for proxy fallback.`)}if(M)throw M;return this._extractFinalResult(N)||R?.parsedText||N}finally{g.dispose()}}_extractFinalResult(e){if(!e)return null;let t=e.split(`
66
- `),r=null;for(let n of t){let s=n.trim();if(s)try{let i=JSON.parse(s);if(i.type==="assistant"&&i.message?.content){let c=i.message.content;if(Array.isArray(c)){let l=c.filter(a=>a.type==="text"&&a.text).map(a=>a.text).join("");l&&(r=l)}else typeof c=="string"&&c&&(r=c)}}catch{}}return r?.trim()||null}_setupMcpConfig(e,t,r,n=null,s=null){let i=r?.headless,c=Y(Ne(),".cursor"),l=Y(c,"mcp.json"),a={};if(Ce(l))try{a=JSON.parse(er(l,"utf-8"))}catch{}let u=a.mcpServers||{},d=r?.paths?.output||On,m=Y(t||process.cwd(),d,Pn),p=Array.isArray(n)?n.map(h=>Vt(h)).filter(Boolean):[...Nn()].map(([,h])=>h),g=new Set;for(let h of p)typeof h.resolve=="function"&&(g.has(h.serverName)||(g.add(h.serverName),this._ensureSkillConfigured(u,h,e,m,s,i)));if(e){let h=Vt("browser");h&&typeof h.resolve=="function"&&!g.has(h.serverName)&&this._ensureSkillConfigured(u,h,e,m,"execute_live",i)}if(Object.keys(u).length===0)return f.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let S=`${JSON.stringify({mcpServers:u},null,2)}
67
- `;if(Zt(e)){let h=Xt(t||process.cwd()),b=Y(h,".cursor","mcp.json");return Qt(b,S,"utf8"),f.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${h} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:h}}return Ce(c)||tr(c,{recursive:!0}),Qt(l,S,"utf8"),f.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,n,s=null,i){let c=t.cursorKey||t.serverName,l=e[c]?c:e[t.serverName]?t.serverName:null;if(l&&r){let u=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:s,headless:i}):null;u?.args?e[l].args=u.args:e[l].args=(e[l].args||[]).map(p=>p.startsWith("--output-dir=")?`--output-dir=${r}`:p);let d=u?.env||{},m=t.sessionEnvKey?{[t.sessionEnvKey]:n}:{};e[l].env={...e[l].env||{},...d,...m},f.debug(`[MCP] Updated ${l} session \u2192 ${r}`);return}if(l)return;let a=t.resolve({sessionPath:r,nodeName:s,headless:i});a&&(e[c]={...a,...t.sessionEnvKey&&{env:{...a.env||{},[t.sessionEnvKey]:n}}},f.debug(`[MCP] Configured ${c}`))}_spawnWithStreaming(e,t,r,n,s=null,i=null,c=null,l=null){return new Promise((a,u)=>{let d=Date.now(),m="",p="",g=Date.now(),S=0,h=!1,b=null,x=!1,T=!1,w=null;if(i)try{w=Y(Mn(String(i)),Cn)}catch{w=null}let I=!1,$=()=>{I||(I=!0,qt(c))},C={...process.env};c&&(C.HOME=c,process.platform==="win32"&&(C.USERPROFILE=c),f.debug(`[Agent] cursor-agent HOME=${c} (isolated MCP config)`));let v=Rn(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:C,...l&&{signal:l}});f.debug(`[Agent] PID: ${v.pid}`);let A=null,D=()=>{h||T||(h=!0,b="aborted",f.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),A=setTimeout(()=>{if(!T){f.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{v.kill("SIGKILL")}catch{}}},5e3))};l&&(l.aborted?D():l.addEventListener("abort",D,{once:!0})),v.stdin.on("error",y=>{y.code!=="EPIPE"&&f.warn(`[Agent] stdin error: ${y.message}`)}),v.stdout.on("error",y=>{y.code!=="EPIPE"&&f.warn(`[Agent] stdout error: ${y.message}`)}),v.stderr.on("error",y=>{y.code!=="EPIPE"&&f.warn(`[Agent] stderr error: ${y.message}`)}),s?(v.stdin.write(s,y=>{y&&y.code!=="EPIPE"&&f.warn(`[Agent] Failed to write to stdin: ${y.message}`),v.stdin.end()}),f.debug(`[Agent] Prompt also piped to stdin (${s.length} chars)`)):v.stdin.end();let E=null;w&&(E=setInterval(()=>{if(!(h||T))try{if(Ce(w)){h=!0,b="aborted";try{kn(w)}catch{}f.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 R=new Set,M=new Date(d).toISOString().replace(/\.\d+Z$/,""),N=setInterval(()=>{let y=Math.round((Date.now()-d)/1e3),k=Math.round((Date.now()-g)/1e3),P=[];try{let B=Math.ceil(y/60)+1,L=ee(`find "${r}" -type f -mmin -${B} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(L)for(let F of L.split(`
68
- `)){let Q=F.replace(`${r}/`,"");R.has(Q)||(R.add(Q),P.push(Q))}}catch{}let _="";P.length>0&&(_=` | \u{1F4C1} new: ${P.map(L=>L.split("/").pop()).join(", ")}`),R.size>0&&(_+=` | \u{1F4E6} total: ${R.size} files`),f.debug(`\u{1F493} [Agent] Running for ${y}s | ${S} lines output${_}`),S===0&&y>=30&&R.size===0&&(y<35&&f.warn(`\u26A0\uFE0F [Agent] No output after ${y}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),y>=60&&(h=!0,b=b||"stall",f.error(`\u274C [Agent] No response after ${y}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),U=setTimeout(()=>{h=!0,b=b||"timeout";let y=Math.round((Date.now()-d)/1e3);f.error(`\u23F1\uFE0F [Agent] Timeout after ${y}s \u2014 killing process (PID: ${v.pid})`),m.trim()&&f.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),O=new H;O.onToolCall=(y,k)=>{let P=y,_=k;if(y==="mcpToolCall"&&k?.name)P=k.name.replace(/^mcp_+[^_]+_+/,""),P.includes("-")&&P.split("-")[0]===P.split("-")[1]&&(P=P.split("-")[0]),_=k.args??k.input??k;else{if(y==="readToolCall"||y==="editToolCall"||y==="writeToolCall")return;(y.startsWith("mcp__")||y.includes("ToolCall"))&&(P=y.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(P.includes("memory")?W.stepMemory(`Tool: ${P}`):W.stepTool(`Tool: ${P}`),_!=null&&typeof _=="object"&&Object.keys(_).length>0&&!T){let L=JSON.stringify(_),F=L.length>100?`${L.substring(0,100)}...`:L;console.log(` Input: ${F}`)}},v.stdout.on("data",y=>{let k=y.toString();m+=k,g=Date.now(),x||(x=!0);let P=O.processChunk(k);P&&!T&&process.stdout.write(P);let _=k.split(`
70
- `).filter(B=>B.trim());S+=_.length}),v.stderr.on("data",y=>{let k=y.toString();p+=k,g=Date.now(),x||(x=!0);let P=k.split(`
71
- `).filter(_=>_.trim());for(let _ of P)f.warn(`\u26A0\uFE0F [Agent stderr] ${_}`)}),v.on("close",(y,k)=>{if(T=!0,$(),clearTimeout(U),clearInterval(N),E&&clearInterval(E),A&&clearTimeout(A),l&&!l.aborted)try{l.removeEventListener("abort",D)}catch{}O.flush();let P=Math.round((Date.now()-d)/1e3);if(f.debug(`[Agent] Exited: code=${y}, signal=${k}, elapsed=${P}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 ${P}s (limit: ${n/1e3}s). ${S} lines produced. Last output ${Math.round((Date.now()-g)/1e3)}s ago. ${m.trim()?`
66
+ Enable strictMode in .zibby.config.js for automatic repair.`,{cause:I})}else{if(O)return f.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),d&&f.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:L,structured:O};b&&f.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(d&&!R){let I=k.parsedText,$=O?JSON.stringify(O):I;f.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${$.length} chars in)`);try{let B=await qt($,s);if(w){let j=s.parse(B.structured);return f.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:L,structured:j}}return{raw:L,...B}}catch(B){if(f.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${B.message}`),O)return f.warn("[Agent] Using agent's original result file as fallback"),{raw:L,structured:O}}}if(R)throw R;let D=b?O==null?"file existed but JSON.parse failed \u2014 see WARN log above":w?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw f.error(`\u274C [Agent] No validated structured output: ${D}`),f.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error(`Agent did not produce a valid result file at ${v}. Enable strictMode for proxy fallback.`)}if(R)throw R;return this._extractFinalResult(L)||k?.parsedText||L}finally{g.dispose()}}_extractFinalResult(e){if(!e)return null;let t=e.split(`
67
+ `),r=null;for(let n of t){let s=n.trim();if(s)try{let i=JSON.parse(s);if(i.type==="assistant"&&i.message?.content){let a=i.message.content;if(Array.isArray(a)){let c=a.filter(l=>l.type==="text"&&l.text).map(l=>l.text).join("");c&&(r=c)}else typeof a=="string"&&a&&(r=a)}}catch{}}return r?.trim()||null}_setupMcpConfig(e,t,r,n=null,s=null){let i=r?.headless,a=H(Ne(),".cursor"),c=H(a,"mcp.json"),l={};if(Re(c))try{l=JSON.parse(ar(c,"utf-8"))}catch{}let u=l.mcpServers||{},m=r?.paths?.output||Kn,d=H(t||process.cwd(),m,Yn),p=Array.isArray(n)?n.map(h=>or(h)).filter(Boolean):[...Wn()].map(([,h])=>h),g=new Set;for(let h of p)typeof h.resolve=="function"&&(g.has(h.serverName)||(g.add(h.serverName),this._ensureSkillConfigured(u,h,e,d,s,i)));if(e){let h=or("browser");h&&typeof h.resolve=="function"&&!g.has(h.serverName)&&this._ensureSkillConfigured(u,h,e,d,"execute_live",i)}if(Object.keys(u).length===0)return f.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let y=`${JSON.stringify({mcpServers:u},null,2)}
68
+ `;if(rr(e)){let h=nr(t||process.cwd()),S=H(h,".cursor","mcp.json");return ir(S,y,"utf8"),f.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${h} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:h}}return Re(a)||cr(a,{recursive:!0}),ir(c,y,"utf8"),f.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,n,s=null,i){let a=t.cursorKey||t.serverName,c=e[a]?a:e[t.serverName]?t.serverName:null;if(c&&r){let u=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:s,headless:i}):null;u?.args?e[c].args=u.args:e[c].args=(e[c].args||[]).map(p=>p.startsWith("--output-dir=")?`--output-dir=${r}`:p);let m=u?.env||{},d=t.sessionEnvKey?{[t.sessionEnvKey]:n}:{};e[c].env={...e[c].env||{},...m,...d},f.debug(`[MCP] Updated ${c} session \u2192 ${r}`);return}if(c)return;let l=t.resolve({sessionPath:r,nodeName:s,headless:i});l&&(e[a]={...l,...t.sessionEnvKey&&{env:{...l.env||{},[t.sessionEnvKey]:n}}},f.debug(`[MCP] Configured ${a}`))}_spawnWithStreaming(e,t,r,n,s=null,i=null,a=null,c=null){return new Promise((l,u)=>{let m=Date.now(),d="",p="",g=Date.now(),y=0,h=!1,S=null,_=!1,A=!1,E=null;if(i)try{E=H(qn(String(i)),Hn)}catch{E=null}let v=!1,P=()=>{v||(v=!0,sr(a))},M={...process.env};a&&(M.HOME=a,process.platform==="win32"&&(M.USERPROFILE=a),f.debug(`[Agent] cursor-agent HOME=${a} (isolated MCP config)`));let T=Zn(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:M,...c&&{signal:c}});f.debug(`[Agent] PID: ${T.pid}`);let C=null,U=()=>{h||A||(h=!0,S="aborted",f.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),C=setTimeout(()=>{if(!A){f.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{T.kill("SIGKILL")}catch{}}},5e3))};c&&(c.aborted?U():c.addEventListener("abort",U,{once:!0})),T.stdin.on("error",w=>{w.code!=="EPIPE"&&f.warn(`[Agent] stdin error: ${w.message}`)}),T.stdout.on("error",w=>{w.code!=="EPIPE"&&f.warn(`[Agent] stdout error: ${w.message}`)}),T.stderr.on("error",w=>{w.code!=="EPIPE"&&f.warn(`[Agent] stderr error: ${w.message}`)}),s?(T.stdin.write(s,w=>{w&&w.code!=="EPIPE"&&f.warn(`[Agent] Failed to write to stdin: ${w.message}`),T.stdin.end()}),f.debug(`[Agent] Prompt also piped to stdin (${s.length} chars)`)):T.stdin.end();let x=null;E&&(x=setInterval(()=>{if(!(h||A))try{if(Re(E)){h=!0,S="aborted";try{Xn(E)}catch{}f.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),T.kill("SIGTERM"),setTimeout(()=>{T.killed||T.kill("SIGKILL")},2e3)}}catch{}},600));let N=new Set,k=new Date(m).toISOString().replace(/\.\d+Z$/,""),R=setInterval(()=>{let w=Math.round((Date.now()-m)/1e3),O=Math.round((Date.now()-g)/1e3),b=[];try{let I=Math.ceil(w/60)+1,$=te(`find "${r}" -type f -mmin -${I} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if($)for(let B of $.split(`
69
+ `)){let j=B.replace(`${r}/`,"");N.has(j)||(N.add(j),b.push(j))}}catch{}let D="";b.length>0&&(D=` | \u{1F4C1} new: ${b.map($=>$.split("/").pop()).join(", ")}`),N.size>0&&(D+=` | \u{1F4E6} total: ${N.size} files`),f.debug(`\u{1F493} [Agent] Running for ${w}s | ${y} lines output${D}`),y===0&&w>=30&&N.size===0&&(w<35&&f.warn(`\u26A0\uFE0F [Agent] No output after ${w}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),w>=60&&(h=!0,S=S||"stall",f.error(`\u274C [Agent] No response after ${w}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),T.kill("SIGTERM"),setTimeout(()=>{T.killed||T.kill("SIGKILL")},3e3)))},3e4),L=setTimeout(()=>{h=!0,S=S||"timeout";let w=Math.round((Date.now()-m)/1e3);f.error(`\u23F1\uFE0F [Agent] Timeout after ${w}s \u2014 killing process (PID: ${T.pid})`),d.trim()&&f.warn(`\u{1F4E4} [Agent] Partial output (${d.length} chars) before timeout:
70
+ ${d.slice(-2e3)}`),T.kill("SIGTERM"),setTimeout(()=>{T.killed||T.kill("SIGKILL")},5e3)},n),F=new W;F.onToolCall=(w,O)=>{let b=w,D=O;if(w==="mcpToolCall"&&O?.name)b=O.name.replace(/^mcp_+[^_]+_+/,""),b.includes("-")&&b.split("-")[0]===b.split("-")[1]&&(b=b.split("-")[0]),D=O.args??O.input??O;else{if(w==="readToolCall"||w==="editToolCall"||w==="writeToolCall")return;(w.startsWith("mcp__")||w.includes("ToolCall"))&&(b=w.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(b.includes("memory")?Z.stepMemory(`Tool: ${b}`):Z.stepTool(`Tool: ${b}`),D!=null&&typeof D=="object"&&Object.keys(D).length>0&&!A){let $=JSON.stringify(D),B=$.length>100?`${$.substring(0,100)}...`:$;console.log(` Input: ${B}`)}},T.stdout.on("data",w=>{let O=w.toString();d+=O,g=Date.now(),_||(_=!0);let b=F.processChunk(O);b&&!A&&process.stdout.write(b);let D=O.split(`
71
+ `).filter(I=>I.trim());y+=D.length}),T.stderr.on("data",w=>{let O=w.toString();p+=O,g=Date.now(),_||(_=!0);let b=O.split(`
72
+ `).filter(D=>D.trim());for(let D of b)f.warn(`\u26A0\uFE0F [Agent stderr] ${D}`)}),T.on("close",(w,O)=>{if(A=!0,P(),clearTimeout(L),clearInterval(R),x&&clearInterval(x),C&&clearTimeout(C),c&&!c.aborted)try{c.removeEventListener("abort",U)}catch{}F.flush();let b=Math.round((Date.now()-m)/1e3);if(f.debug(`[Agent] Exited: code=${w}, signal=${O}, elapsed=${b}s, output=${d.length} chars`),h){if(S==="aborted"){let $=new Error("Aborted via signal");$.name="AbortError",u($);return}u(new Error(`Cursor Agent timed out after ${b}s (limit: ${n/1e3}s). ${y} lines produced. Last output ${Math.round((Date.now()-g)/1e3)}s ago. ${d.trim()?`
72
73
  Partial output (last 500 chars):
73
- ${m.slice(-500)}`:"No output captured."}`));return}if(y!==0){u(new Error(`Cursor Agent failed: exit code ${y}, signal ${l}. ${p.trim()?`
74
- Stderr: ${p.slice(-1e3)}`:""}${m.trim()?`
75
- Stdout (last 500 chars): ${m.slice(-500)}`:""}`));return}let _=O.getResult(),B=_?JSON.stringify(_,null,2):O.getRawText()||m||"";a({stdout:m||p||"",parsedText:B})}),v.on("error",y=>{if($(),clearTimeout(U),clearInterval(N),E&&clearInterval(E),A&&clearTimeout(A),l&&!l.aborted)try{l.removeEventListener("abort",D)}catch{}u(new Error(`Cursor Agent spawn error: ${y.message}
74
+ ${d.slice(-500)}`:"No output captured."}`));return}if(w!==0){u(new Error(`Cursor Agent failed: exit code ${w}, signal ${c}. ${p.trim()?`
75
+ Stderr: ${p.slice(-1e3)}`:""}${d.trim()?`
76
+ Stdout (last 500 chars): ${d.slice(-500)}`:""}`));return}let D=F.getResult(),I=D?JSON.stringify(D,null,2):F.getRawText()||d||"";l({stdout:d||p||"",parsedText:I})}),T.on("error",w=>{if(P(),clearTimeout(L),clearInterval(R),x&&clearInterval(x),C&&clearTimeout(C),c&&!c.aborted)try{c.removeEventListener("abort",U)}catch{}u(new Error(`Cursor Agent spawn error: ${w.message}
76
77
  Binary: ${e}
77
78
  This usually means the binary is not in PATH. Try:
78
- echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};import{AgentStrategy as Ln,getSkill as Dn}from"@zibby/agent-workflow";import{query as Un}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as Bn}from"zod-to-json-schema";import{writeFileSync as mt,mkdirSync as gt,existsSync as sr,readFileSync as or}from"fs";import{homedir as ir}from"os";import{join as ge}from"path";var re=class extends Ln{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,s=t||r||n;return s||f.debug("ClaudeAgentStrategy: no credentials. Set one of ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_AUTH_TOKEN (or a *_POOL variant for multi-token rotation)."),s}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,images:i=[],skills:c=null,sessionPath:l=null,nodeName:a=null,timeout:u,config:d={},signal:m=null}=t,p=r;(!p||p==="auto")&&(f.debug(`Model is '${p||"undefined"}', using default: ${j.CLAUDE}`),p=j.CLAUDE);let g=pt[p]||p;pt[p]&&p!==g&&f.debug(`Mapped model: ${p} \u2192 ${g}`);let S=[J("ANTHROPIC_API_KEY"),J("CLAUDE_CODE_OAUTH_TOKEN"),J("ANTHROPIC_AUTH_TOKEN")];try{f.debug(`Invoking Claude Agent SDK with model: ${g}, skills: ${JSON.stringify(c)}`);let h=process.env.CLAUDE_CODE_OAUTH_TOKEN,b=process.env.ANTHROPIC_API_KEY,x=process.env.ANTHROPIC_AUTH_TOKEN;process.env.CLAUDE_CODE_CREDENTIALS_JSON?Gn(process.env.CLAUDE_CODE_CREDENTIALS_JSON):h&&jn(h,process.env.__ZIBBY_CLAUDE_PLAN);let T=process.env.__ZIBBY_CLAUDE_PLAN,w=T?T.charAt(0).toUpperCase()+T.slice(1):null,I;h?I=w?`Claude ${w} plan \xB7 ***${h.slice(-4)}`:`Subscription \xB7 ***${h.slice(-4)}`:b?I=`API key \xB7 ***${b.slice(-4)}`:x?I=`Bearer \xB7 ***${x.slice(-4)}`:I="NONE \u2014 request will fail";let $=(await import("chalk")).default;console.log(""),console.log(` ${$.cyan("\u25C6")} ${$.bold(g)}`),console.log(` ${$.dim("Auth: ")}${I}`),console.log(` ${$.dim("Workdir: ")}${n}`),console.log(""),console.log($.bold("Prompt sent to LLM:")),console.log($.dim("\u2500".repeat(60))),console.log($.dim(e)),console.log($.dim("\u2500".repeat(60)));let{allowedTools:C,mcpServers:v}=this._resolveSkills(c,{sessionPath:l,workspace:n,nodeName:a});try{let A={cwd:n,allowedTools:C,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,settings:{permissions:{allow:["Bash(*)","Read(*)","Write(*)","Edit(*)","MultiEdit(*)","NotebookEdit(*)","Grep(*)","Glob(*)","WebFetch(*)","WebSearch(*)","Task(*)","TodoWrite(*)","Skill(*)"],defaultMode:"bypassPermissions"}},model:g,...Object.keys(v).length>0&&{mcpServers:v}};if(s){let k=typeof s.parse=="function"?Bn(s,{target:"openApi3"}):s;A.outputFormat={type:"json_schema",schema:k},f.debug("Structured output enforced via SDK outputFormat")}f.debug(`Agent SDK options: ${JSON.stringify({cwd:A.cwd,toolCount:C.length,permissionMode:A.permissionMode,model:A.model,hasOutputFormat:!!A.outputFormat})}`);let D="",E=0,R=[];f.debug("Starting Claude Agent SDK query stream");let M;try{M=Un({prompt:e,options:A})}catch(y){throw f.error(`Failed to initialize Claude Agent SDK: ${y.message}`),y}let N=null,U=0,O=3;if(m?.aborted){let y=new Error("Aborted via signal");throw y.name="AbortError",y}try{for await(let y of M){if(m?.aborted){let P=new Error("Aborted via signal");throw P.name="AbortError",P}if(R.push(y),y.type==="error"||y.error){let P=y.error?.message||y.error||y.message||"Unknown API error";try{f.error("SDK error event raw payload",{fullMessage:JSON.stringify(y,null,2)})}catch{}throw new Error(typeof P=="string"?P:JSON.stringify(P))}let k=JSON.stringify(y.message?.content||y.text||"").slice(0,200);if(k===N){if(U++,U>=O){let P=(y.message?.content?.[0]?.text||y.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${U}x repeated): ${P}`)}}else N=k,U=1;if(y.type==="assistant"||y.constructor?.name==="AssistantMessage"){let P=y.message?.content||y.content||[];for(let _ of P)if(_.type==="thinking"&&_.thinking)console.log(`${_.thinking.substring(0,200)}${_.thinking.length>200?"...":""}`);else if(_.type==="text"&&_.text)D+=_.text,_.text.length<500?console.log(`${_.text}`):console.log(`${_.text.substring(0,200)}... (${_.text.length} chars)`);else if(_.type==="tool_use"){E++,_.name.includes("memory")?W.stepMemory(`Tool: ${_.name}`):W.stepTool(`Tool: ${_.name}`);let L=JSON.stringify(_.input).substring(0,100);console.log(` Input: ${L}${JSON.stringify(_.input).length>100?"...":""}`)}}else if(!(y.type==="user"&&y.tool_use_result)){if(y.type==="result"||y.constructor?.name==="ResultMessage"){let P=y.result||y.text||y.content||D;try{Fn({message:y,sessionPath:l,nodeName:a,model:p,toolCallCount:E})}catch(_){f.debug(`usage.json write failed: ${_.message}`)}if(s){if(y.structured_output){f.debug("Using SDK native structured_output");let B=typeof s.parse=="function"?s.parse(y.structured_output):y.structured_output;return{raw:P,structured:B}}if(P){let _=this._extractJson(P,s);if(_)return{raw:P,structured:_}}f.warn(`Could not extract structured output \u2014 returning raw text (${(P||"").length} chars)`)}return P||""}}}if(f.warn(`Agent SDK ended without result. Collected ${R.length} messages`),D.length>0)return f.debug("Returning accumulated text from messages"),D;throw new Error("Claude Agent SDK query ended without result")}catch(y){let k={message:y?.message,name:y?.name,code:y?.code,cause:y?.cause?.message||y?.cause,stack:y?.stack?.split(`
79
+ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};import{AgentStrategy as Vn,getSkill as Qn}from"@zibby/agent-workflow";import{query as es}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as ts}from"zod-to-json-schema";import{writeFileSync as St,mkdirSync as bt,existsSync as pr,readFileSync as fr}from"fs";import{homedir as dr}from"os";import{join as he}from"path";var ne=class extends Vn{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,s=t||r||n;return s||f.debug("ClaudeAgentStrategy: no credentials. Set one of ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_AUTH_TOKEN (or a *_POOL variant for multi-token rotation)."),s}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,images:i=[],skills:a=null,sessionPath:c=null,nodeName:l=null,timeout:u,config:m={},signal:d=null}=t,p=r;(!p||p==="auto")&&(f.debug(`Model is '${p||"undefined"}', using default: ${G.CLAUDE}`),p=G.CLAUDE);let g=mt[p]||p;mt[p]&&p!==g&&f.debug(`Mapped model: ${p} \u2192 ${g}`);let y=[J("ANTHROPIC_API_KEY"),J("CLAUDE_CODE_OAUTH_TOKEN"),J("ANTHROPIC_AUTH_TOKEN")];try{f.debug(`Invoking Claude Agent SDK with model: ${g}, skills: ${JSON.stringify(a)}`);let h=process.env.CLAUDE_CODE_OAUTH_TOKEN,S=process.env.ANTHROPIC_API_KEY,_=process.env.ANTHROPIC_AUTH_TOKEN;process.env.CLAUDE_CODE_CREDENTIALS_JSON?ss(process.env.CLAUDE_CODE_CREDENTIALS_JSON):h&&ns(h,process.env.__ZIBBY_CLAUDE_PLAN);let A=process.env.__ZIBBY_CLAUDE_PLAN,E=A?A.charAt(0).toUpperCase()+A.slice(1):null,v;h?v=E?`Claude ${E} plan \xB7 ***${h.slice(-4)}`:`Subscription \xB7 ***${h.slice(-4)}`:S?v=`API key \xB7 ***${S.slice(-4)}`:_?v=`Bearer \xB7 ***${_.slice(-4)}`:v="NONE \u2014 request will fail";let P=(await import("chalk")).default,M=ee(),T=M?`${M}
80
+
81
+ ${e}`:e;console.log(""),console.log(` ${P.cyan("\u25C6")} ${P.bold(g)}`),console.log(` ${P.dim("Auth: ")}${v}`),console.log(` ${P.dim("Workdir: ")}${n}`),console.log(""),console.log(P.bold("Prompt sent to LLM:")),console.log(P.dim("\u2500".repeat(60))),console.log(P.dim(T)),console.log(P.dim("\u2500".repeat(60)));let{allowedTools:C,mcpServers:U}=this._resolveSkills(a,{sessionPath:c,workspace:n,nodeName:l});try{let x={cwd:n,allowedTools:C,settings:{permissions:{allow:["Bash(*)","Read(*)","Write(*)","Edit(*)","MultiEdit(*)","NotebookEdit(*)","Grep(*)","Glob(*)","WebFetch(*)","WebSearch(*)","Task(*)","TodoWrite(*)","Skill(*)"]}},model:g,...Object.keys(U).length>0&&{mcpServers:U}};if(s){let D=typeof s.parse=="function"?ts(s,{target:"openApi3"}):s;x.outputFormat={type:"json_schema",schema:D},f.debug("Structured output enforced via SDK outputFormat")}f.debug(`Agent SDK options: ${JSON.stringify({cwd:x.cwd,toolCount:C.length,permissionMode:x.permissionMode,model:x.model,hasOutputFormat:!!x.outputFormat})}`);let N="",k=0,R=[];f.debug("Starting Claude Agent SDK query stream");let L;try{L=es({prompt:T,options:x})}catch(b){throw f.error(`Failed to initialize Claude Agent SDK: ${b.message}`),b}let F=null,w=0,O=3;if(d?.aborted){let b=new Error("Aborted via signal");throw b.name="AbortError",b}try{for await(let b of L){if(d?.aborted){let I=new Error("Aborted via signal");throw I.name="AbortError",I}if(R.push(b),b.type==="error"||b.error){let I=b.error?.message||b.error||b.message||"Unknown API error";try{f.error("SDK error event raw payload",{fullMessage:JSON.stringify(b,null,2)})}catch{}throw new Error(typeof I=="string"?I:JSON.stringify(I))}let D=JSON.stringify(b.message?.content||b.text||"").slice(0,200);if(D===F){if(w++,w>=O){let I=(b.message?.content?.[0]?.text||b.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${w}x repeated): ${I}`)}}else F=D,w=1;if(b.type==="assistant"||b.constructor?.name==="AssistantMessage"){let I=b.message?.content||b.content||[];for(let $ of I)if($.type==="thinking"&&$.thinking)console.log(`${$.thinking.substring(0,200)}${$.thinking.length>200?"...":""}`);else if($.type==="text"&&$.text)N+=$.text,$.text.length<500?console.log(`${$.text}`):console.log(`${$.text.substring(0,200)}... (${$.text.length} chars)`);else if($.type==="tool_use"){k++,$.name.includes("memory")?Z.stepMemory(`Tool: ${$.name}`):Z.stepTool(`Tool: ${$.name}`);let j=JSON.stringify($.input).substring(0,100);console.log(` Input: ${j}${JSON.stringify($.input).length>100?"...":""}`)}}else if(!(b.type==="user"&&b.tool_use_result)){if(b.type==="result"||b.constructor?.name==="ResultMessage"){let I=b.result||b.text||b.content||N;try{rs({message:b,sessionPath:c,nodeName:l,model:p,toolCallCount:k})}catch($){f.debug(`usage.json write failed: ${$.message}`)}if(s){if(b.structured_output){f.debug("Using SDK native structured_output");let B=typeof s.parse=="function"?s.parse(b.structured_output):b.structured_output;return{raw:I,structured:B}}if(I){let $=this._extractJson(I,s);if($)return{raw:I,structured:$}}f.warn(`Could not extract structured output \u2014 returning raw text (${(I||"").length} chars)`)}return I||""}}}if(f.warn(`Agent SDK ended without result. Collected ${R.length} messages`),N.length>0)return f.debug("Returning accumulated text from messages"),N;throw new Error("Claude Agent SDK query ended without result")}catch(b){let D={message:b?.message,name:b?.name,code:b?.code,cause:b?.cause?.message||b?.cause,stack:b?.stack?.split(`
79
82
  `).slice(0,5).join(`
80
- `),stringified:(()=>{try{return JSON.stringify(y,Object.getOwnPropertyNames(Object(y)))}catch{return String(y)}})()};throw f.error(`Error during query stream: ${y?.message||y}`,k),y}}catch(A){throw f.error("Claude Agent SDK call failed",{message:A?.message,name:A?.name,code:A?.code,cause:A?.cause?.message||A?.cause}),A}}finally{for(let h of S)h.dispose()}}_resolveSkills(e,t){let r=["Read","Write","Edit","Bash","Grep","Glob"];if(e===null)return f.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return f.debug("Default IDE skills for code generation"),{allowedTools:[...r],mcpServers:{}};let n=[...r],s={};for(let i of e){let c=Dn(i);if(!c){f.warn(`Unknown skill "${i}" \u2014 skipping`);continue}if(c.allowedTools&&n.push(...c.allowedTools),typeof c.resolve=="function"){let l=c.resolve(t);l&&(s[c.serverName]=l,f.debug(`MCP: ${c.serverName} \u2192 ${l.command} ${l.args[0]}`))}}return{allowedTools:n,mcpServers:s}}_extractJson(e,t){let r=[()=>{if(e.includes("===JSON_START===")){let n=e.indexOf("===JSON_START===")+16,s=e.indexOf("===JSON_END===");return e.substring(n,s).trim()}},()=>e.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!e.startsWith("{"))return e.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>e.trim(),()=>{let n=e.indexOf("{"),s=e.lastIndexOf("}");if(n!==-1&&s>n)return e.substring(n,s+1)}];for(let n of r)try{let s=n();if(!s)continue;let i=JSON.parse(s);if(typeof i!="object"||i===null)continue;return typeof t.parse=="function"?t.parse(i):i}catch{}return null}};function Fn({message:o,sessionPath:e,nodeName:t,model:r,toolCallCount:n}){if(!e||!t)return;let s=o?.usage||o?.message?.usage||{},i=Re(s.input_tokens,s.inputTokens),c=Re(s.output_tokens,s.outputTokens),l=Re(s.cache_read_input_tokens,s.cacheReadInputTokens),a=Re(s.cache_creation_input_tokens,s.cacheCreationInputTokens),u=Re(o?.duration_ms,o?.durationMs),d={model:r||null,input_tokens:i,output_tokens:c,cache_read_tokens:l,cache_creation_tokens:a,tool_call_count:typeof n=="number"?n:null,duration_ms:u,captured_at:new Date().toISOString()},m=ge(e,t);try{gt(m,{recursive:!0})}catch{}mt(ge(m,"usage.json"),JSON.stringify(d,null,2),"utf-8")}function Re(...o){for(let e of o){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e)))return Number(e)}return null}function jn(o,e){let t=ge(ir(),".claude"),r=ge(t,".credentials.json"),n={claudeAiOauth:{accessToken:o,...e?{subscriptionType:String(e).toLowerCase()}:{}}};try{if(sr(r)&&JSON.parse(or(r,"utf-8"))?.claudeAiOauth?.accessToken===o)return;gt(t,{recursive:!0}),mt(r,JSON.stringify(n,null,2),"utf-8"),f.debug(`Wrote Claude Code OAuth credentials to ${r}`)}catch(s){f.warn(`Could not write ${r}: ${s.message} \u2014 Claude SDK may fail to authenticate.`)}}function Gn(o){let e=ge(ir(),".claude"),t=ge(e,".credentials.json"),r;try{r=JSON.parse(o)}catch(n){f.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${n.message}`);return}if(!r?.claudeAiOauth?.accessToken){f.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if(sr(t)){let n=JSON.parse(or(t,"utf-8"));if(n?.claudeAiOauth?.accessToken===r.claudeAiOauth.accessToken&&n?.claudeAiOauth?.expiresAt===r.claudeAiOauth.expiresAt)return}gt(e,{recursive:!0}),mt(t,JSON.stringify(r,null,2),"utf-8"),f.debug(`Wrote full Claude Code credentials blob to ${t}`)}catch(n){f.warn(`Could not write ${t}: ${n.message} \u2014 Claude SDK may fail to authenticate.`)}}import{AgentStrategy as Jn,getSkill as zn}from"@zibby/agent-workflow";import{execSync as Kn}from"node:child_process";import{zodToJsonSchema as Yn}from"zod-to-json-schema";var ne=class extends Jn{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY_POOL||process.env.CODEX_API_KEY||process.env.CODEX_API_KEY_POOL))return f.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return Kn("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return f.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,skills:i=null,sessionPath:c=null,nodeName:l=null,timeout:a,config:u={},signal:d=null}=t,m=[J("OPENAI_API_KEY"),J("CODEX_API_KEY")];try{let{Codex:p}=await import("@openai/codex-sdk"),g=r;(!g||g==="auto")&&(f.debug(`Model is '${g||"undefined"}', using default: ${j.CODEX}`),g=j.CODEX);let S=ft[g]||g;ft[g]&&g!==S&&f.debug(`Mapped model: ${g} \u2192 ${S}`),f.debug(`Invoking Codex SDK with model: ${S}, skills: ${JSON.stringify(i)}`);let h=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;h&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=h);let b=h?` | key: ***${h.slice(-4)}`:" | key: not set";console.log(`
81
- \u25C6 Model: ${S}${b}
83
+ `),stringified:(()=>{try{return JSON.stringify(b,Object.getOwnPropertyNames(Object(b)))}catch{return String(b)}})()};throw f.error(`Error during query stream: ${b?.message||b}`,D),b}}catch(x){throw f.error("Claude Agent SDK call failed",{message:x?.message,name:x?.name,code:x?.code,cause:x?.cause?.message||x?.cause}),x}}finally{for(let h of y)h.dispose()}}_resolveSkills(e,t){let r=["Read","Write","Edit","Bash","Grep","Glob"];if(e===null)return f.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return f.debug("Default IDE skills for code generation"),{allowedTools:[...r],mcpServers:{}};let n=[...r],s={};for(let i of e){let a=Qn(i);if(!a){f.warn(`Unknown skill "${i}" \u2014 skipping`);continue}if(a.allowedTools&&n.push(...a.allowedTools),typeof a.resolve=="function"){let c=a.resolve(t);c&&(s[a.serverName]=c,f.debug(`MCP: ${a.serverName} \u2192 ${c.command} ${c.args[0]}`))}}return{allowedTools:n,mcpServers:s}}_extractJson(e,t){let r=[()=>{if(e.includes("===JSON_START===")){let n=e.indexOf("===JSON_START===")+16,s=e.indexOf("===JSON_END===");return e.substring(n,s).trim()}},()=>e.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!e.startsWith("{"))return e.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>e.trim(),()=>{let n=e.indexOf("{"),s=e.lastIndexOf("}");if(n!==-1&&s>n)return e.substring(n,s+1)}];for(let n of r)try{let s=n();if(!s)continue;let i=JSON.parse(s);if(typeof i!="object"||i===null)continue;return typeof t.parse=="function"?t.parse(i):i}catch{}return null}};function rs({message:o,sessionPath:e,nodeName:t,model:r,toolCallCount:n}){if(!e||!t)return;let s=o?.usage||o?.message?.usage||{},i=ke(s.input_tokens,s.inputTokens),a=ke(s.output_tokens,s.outputTokens),c=ke(s.cache_read_input_tokens,s.cacheReadInputTokens),l=ke(s.cache_creation_input_tokens,s.cacheCreationInputTokens),u=ke(o?.duration_ms,o?.durationMs),m={model:r||null,input_tokens:i,output_tokens:a,cache_read_tokens:c,cache_creation_tokens:l,tool_call_count:typeof n=="number"?n:null,duration_ms:u,captured_at:new Date().toISOString()},d=he(e,t);try{bt(d,{recursive:!0})}catch{}St(he(d,"usage.json"),JSON.stringify(m,null,2),"utf-8")}function ke(...o){for(let e of o){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e)))return Number(e)}return null}function ns(o,e){let t=he(dr(),".claude"),r=he(t,".credentials.json"),n={claudeAiOauth:{accessToken:o,...e?{subscriptionType:String(e).toLowerCase()}:{}}};try{if(pr(r)&&JSON.parse(fr(r,"utf-8"))?.claudeAiOauth?.accessToken===o)return;bt(t,{recursive:!0}),St(r,JSON.stringify(n,null,2),"utf-8"),f.debug(`Wrote Claude Code OAuth credentials to ${r}`)}catch(s){f.warn(`Could not write ${r}: ${s.message} \u2014 Claude SDK may fail to authenticate.`)}}function ss(o){let e=he(dr(),".claude"),t=he(e,".credentials.json"),r;try{r=JSON.parse(o)}catch(n){f.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${n.message}`);return}if(!r?.claudeAiOauth?.accessToken){f.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if(pr(t)){let n=JSON.parse(fr(t,"utf-8"));if(n?.claudeAiOauth?.accessToken===r.claudeAiOauth.accessToken&&n?.claudeAiOauth?.expiresAt===r.claudeAiOauth.expiresAt)return}bt(e,{recursive:!0}),St(t,JSON.stringify(r,null,2),"utf-8"),f.debug(`Wrote full Claude Code credentials blob to ${t}`)}catch(n){f.warn(`Could not write ${t}: ${n.message} \u2014 Claude SDK may fail to authenticate.`)}}import{AgentStrategy as os,getSkill as is}from"@zibby/agent-workflow";import{execSync as as}from"node:child_process";import{zodToJsonSchema as cs}from"zod-to-json-schema";var se=class extends os{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY_POOL||process.env.CODEX_API_KEY||process.env.CODEX_API_KEY_POOL))return f.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return as("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return f.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,skills:i=null,sessionPath:a=null,nodeName:c=null,timeout:l,config:u={},signal:m=null}=t,d=[J("OPENAI_API_KEY"),J("CODEX_API_KEY")];try{let{Codex:p}=await import("@openai/codex-sdk"),g=r;(!g||g==="auto")&&(f.debug(`Model is '${g||"undefined"}', using default: ${G.CODEX}`),g=G.CODEX);let y=gt[g]||g;gt[g]&&g!==y&&f.debug(`Mapped model: ${g} \u2192 ${y}`),f.debug(`Invoking Codex SDK with model: ${y}, skills: ${JSON.stringify(i)}`);let h=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;h&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=h);let S=h?` | key: ***${h.slice(-4)}`:" | key: not set";console.log(`
84
+ \u25C6 Model: ${y}${S}
85
+ `);let _=(await import("chalk")).default;console.log(`
86
+ ${_.bold("Prompt sent to LLM:")}`),console.log(_.dim("\u2500".repeat(60))),console.log(_.dim(e)),console.log(_.dim("\u2500".repeat(60)));let A=this._resolveSkillsToMcp(i,{sessionPath:a,workspace:n,nodeName:c}),E={};Object.keys(A).length>0&&(E.mcp_servers=A,f.debug(`[Codex] MCP servers: ${Object.keys(A).join(", ")}`));let P=new p({...Object.keys(E).length>0&&{config:E}}).startThread({workingDirectory:n,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),M=s&&typeof s.parse=="function",T={};if(s)try{let C=M?cs(s,{target:"openAi"}):s;T.outputSchema=C,f.debug("Structured output via SDK outputSchema")}catch(C){f.warn(`[Codex] Schema conversion failed, will extract from text: ${C.message}`)}if(m?.aborted){let C=new Error("Aborted via signal");throw C.name="AbortError",C}try{let{events:C}=await P.runStreamed(e,T),U=0,x="";for await(let N of C){if(m?.aborted){let R=new Error("Aborted via signal");throw R.name="AbortError",R}let k=N.type;if(k==="item.completed"){let R=N.item,L=R?.type;if(L==="mcp_tool_call"){U++;let F=`${R.server}/${R.tool}`;if(Z.stepTool(`Tool: ${F}`),R.arguments){let w=JSON.stringify(R.arguments),O=w.length>100?`${w.substring(0,100)}...`:w;console.log(` Input: ${O}`)}}else if(L==="tool_call"||L==="function_call"||L==="command_execution"){U++;let F=R.name||R.tool||R.command||"unknown";Z.stepTool(`Tool: ${F}`)}else L==="agent_message"&&(x=R.text||"",x.length<500?console.log(x):console.log(`${x.substring(0,200)}... (${x.length} chars)`))}else k==="turn.completed"?f.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(N.usage||{})}`):f.debug(`[Codex] Event: ${k} ${JSON.stringify(N).slice(0,300)}`)}if(f.debug(`[Codex] Last agent message (${x.length} chars): ${x.slice(0,500)}`),s){if(!x)throw new Error("Codex agent returned no response");let N=JSON.parse(x),k=M?s.parse(N):N;return f.debug("\u2705 [Codex] Structured output validated"),{raw:x,structured:k}}return x||""}catch(C){let U=C.message||String(C);throw f.error(`\u274C [Codex] SDK call failed: ${U}`),U.includes("exited with code")&&(f.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),f.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),C}}finally{for(let p of d)p.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=is(n);if(!s){f.warn(`[Codex] Unknown skill "${n}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let a=s.serverName||n,c={command:i.command};i.args?.length&&(c.args=i.args),i.env&&Object.keys(i.env).length>0&&(c.env=i.env),r[a]=c,f.debug(`[Codex] MCP: ${a} \u2192 ${i.command} ${(i.args||[]).join(" ")}`)}return r}};import{AgentStrategy as ls,getSkill as us}from"@zibby/agent-workflow";import{execSync as ps,spawn as fs}from"node:child_process";import{zodToJsonSchema as ds}from"zod-to-json-schema";import{existsSync as mr,mkdirSync as gr,readFileSync as hr,rmSync as ms,writeFileSync as yr}from"node:fs";import{join as oe}from"node:path";function gs(o){if(!o)return null;let e=String(o),t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t?.[1])try{return JSON.parse(t[1].trim())}catch{}let r=e.indexOf("{");if(r<0)return null;let n=0,s=!1,i=!1,a=-1;for(let c=r;c<e.length;c++){let l=e[c];if(s){i?i=!1:l==="\\"?i=!0:l==='"'&&(s=!1);continue}if(l==='"'){s=!0;continue}if(l==="{"){n===0&&(a=c),n+=1;continue}if(l==="}"){if(n===0)continue;if(n-=1,n===0&&a>=0){let u=e.slice(a,c+1);try{return JSON.parse(u)}catch{a=-1}}}}return null}function hs(o){let e=String(o||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return gs(e)}}function ys(o){try{let e=JSON.parse(o);if(typeof e=="string")return e;if(typeof e?.response=="string")return e.response;if(typeof e?.text=="string")return e.text;if(typeof e?.output=="string")return e.output;if(Array.isArray(e?.candidates)&&e.candidates.length>0){let t=e.candidates[0];if(typeof t?.content=="string")return t.content;if(Array.isArray(t?.content?.parts)){let r=t.content.parts.map(n=>typeof n?.text=="string"?n.text:"").join("");if(r.trim())return r}}}catch{}return o}var ie=class extends ls{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GEMINI_API_KEY_POOL||process.env.GOOGLE_API_KEY||process.env.GOOGLE_API_KEY_POOL))return f.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return ps("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return f.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,skills:i=null,sessionPath:a=null,nodeName:c=null,timeout:l=600*1e3,signal:u=null}=t,m=[J("GEMINI_API_KEY"),J("GOOGLE_API_KEY")];try{let d=r;(!d||d==="auto")&&(d=G.GEMINI);let p=Xt[d]||d,g=String(process.env.GEMINI_API_KEY||"").trim(),y=String(process.env.GOOGLE_API_KEY||"").trim(),h=this._resolveSkillsToMcp(i,{sessionPath:a,workspace:n,nodeName:c}),S=Object.keys(h).length>0,_=new me(e),A=ee();A&&_.addSystemInstruction(A,"repo_context","prepend");let E=s&&typeof s.parse=="function",v=null;if(s){let I;try{let $=E?ds(s,{target:"openAi"}):s;I=JSON.stringify($,null,2)}catch{I="{}"}if(S){_.addSystemInstruction(`Write valid JSON that matches this schema:
87
+ ${I}`,"schema_instruction","append");let $=`zibby-result-${Date.now()}.json`,B=oe(n,".zibby","tmp");v=oe(B,$),gr(B,{recursive:!0}),_.addStructuredOutput(s,v)}else _.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
88
+ ${I}`,"json_instruction","append")}let P=_.build(),M=_.getUserPrompt(),T=_.getStats(),C=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),U=C?` | key: ***${C.slice(-4)}`:" | key: not set";console.log(`
89
+ \u25C6 Model: ${p||"auto"}${U}
82
90
  `);let x=(await import("chalk")).default;console.log(`
83
- ${x.bold("Prompt sent to LLM:")}`),console.log(x.dim("\u2500".repeat(60))),console.log(x.dim(e)),console.log(x.dim("\u2500".repeat(60)));let T=this._resolveSkillsToMcp(i,{sessionPath:c,workspace:n,nodeName:l}),w={};Object.keys(T).length>0&&(w.mcp_servers=T,f.debug(`[Codex] MCP servers: ${Object.keys(T).join(", ")}`));let $=new p({...Object.keys(w).length>0&&{config:w}}).startThread({workingDirectory:n,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),C=s&&typeof s.parse=="function",v={};if(s)try{let A=C?Yn(s,{target:"openAi"}):s;v.outputSchema=A,f.debug("Structured output via SDK outputSchema")}catch(A){f.warn(`[Codex] Schema conversion failed, will extract from text: ${A.message}`)}if(d?.aborted){let A=new Error("Aborted via signal");throw A.name="AbortError",A}try{let{events:A}=await $.runStreamed(e,v),D=0,E="";for await(let R of A){if(d?.aborted){let N=new Error("Aborted via signal");throw N.name="AbortError",N}let M=R.type;if(M==="item.completed"){let N=R.item,U=N?.type;if(U==="mcp_tool_call"){D++;let O=`${N.server}/${N.tool}`;if(W.stepTool(`Tool: ${O}`),N.arguments){let y=JSON.stringify(N.arguments),k=y.length>100?`${y.substring(0,100)}...`:y;console.log(` Input: ${k}`)}}else if(U==="tool_call"||U==="function_call"||U==="command_execution"){D++;let O=N.name||N.tool||N.command||"unknown";W.stepTool(`Tool: ${O}`)}else U==="agent_message"&&(E=N.text||"",E.length<500?console.log(E):console.log(`${E.substring(0,200)}... (${E.length} chars)`))}else M==="turn.completed"?f.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(R.usage||{})}`):f.debug(`[Codex] Event: ${M} ${JSON.stringify(R).slice(0,300)}`)}if(f.debug(`[Codex] Last agent message (${E.length} chars): ${E.slice(0,500)}`),s){if(!E)throw new Error("Codex agent returned no response");let R=JSON.parse(E),M=C?s.parse(R):R;return f.debug("\u2705 [Codex] Structured output validated"),{raw:E,structured:M}}return E||""}catch(A){let D=A.message||String(A);throw f.error(`\u274C [Codex] SDK call failed: ${D}`),D.includes("exited with code")&&(f.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),f.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),A}}finally{for(let p of m)p.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=zn(n);if(!s){f.warn(`[Codex] Unknown skill "${n}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let c=s.serverName||n,l={command:i.command};i.args?.length&&(l.args=i.args),i.env&&Object.keys(i.env).length>0&&(l.env=i.env),r[c]=l,f.debug(`[Codex] MCP: ${c} \u2192 ${i.command} ${(i.args||[]).join(" ")}`)}return r}};import{AgentStrategy as Hn,getSkill as Wn}from"@zibby/agent-workflow";import{execSync as Zn,spawn as Xn}from"node:child_process";import{zodToJsonSchema as qn}from"zod-to-json-schema";import{existsSync as ar,mkdirSync as cr,readFileSync as lr,rmSync as Vn,writeFileSync as ur}from"node:fs";import{join as se}from"node:path";function Qn(o){if(!o)return null;let e=String(o),t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t?.[1])try{return JSON.parse(t[1].trim())}catch{}let r=e.indexOf("{");if(r<0)return null;let n=0,s=!1,i=!1,c=-1;for(let l=r;l<e.length;l++){let a=e[l];if(s){i?i=!1:a==="\\"?i=!0:a==='"'&&(s=!1);continue}if(a==='"'){s=!0;continue}if(a==="{"){n===0&&(c=l),n+=1;continue}if(a==="}"){if(n===0)continue;if(n-=1,n===0&&c>=0){let u=e.slice(c,l+1);try{return JSON.parse(u)}catch{c=-1}}}}return null}function es(o){let e=String(o||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return Qn(e)}}function ts(o){try{let e=JSON.parse(o);if(typeof e=="string")return e;if(typeof e?.response=="string")return e.response;if(typeof e?.text=="string")return e.text;if(typeof e?.output=="string")return e.output;if(Array.isArray(e?.candidates)&&e.candidates.length>0){let t=e.candidates[0];if(typeof t?.content=="string")return t.content;if(Array.isArray(t?.content?.parts)){let r=t.content.parts.map(n=>typeof n?.text=="string"?n.text:"").join("");if(r.trim())return r}}}catch{}return o}var oe=class extends Hn{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GEMINI_API_KEY_POOL||process.env.GOOGLE_API_KEY||process.env.GOOGLE_API_KEY_POOL))return f.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return Zn("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return f.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:s=null,skills:i=null,sessionPath:c=null,nodeName:l=null,timeout:a=600*1e3,signal:u=null}=t,d=[J("GEMINI_API_KEY"),J("GOOGLE_API_KEY")];try{let m=r;(!m||m==="auto")&&(m=j.GEMINI);let p=Yt[m]||m,g=String(process.env.GEMINI_API_KEY||"").trim(),S=String(process.env.GOOGLE_API_KEY||"").trim(),h=this._resolveSkillsToMcp(i,{sessionPath:c,workspace:n,nodeName:l}),b=Object.keys(h).length>0,x=new de(e),T=s&&typeof s.parse=="function",w=null;if(s){let _;try{let B=T?qn(s,{target:"openAi"}):s;_=JSON.stringify(B,null,2)}catch{_="{}"}if(b){x.addSystemInstruction(`Write valid JSON that matches this schema:
84
- ${_}`,"schema_instruction","append");let B=`zibby-result-${Date.now()}.json`,L=se(n,".zibby","tmp");w=se(L,B),cr(L,{recursive:!0}),x.addStructuredOutput(s,w)}else x.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
85
- ${_}`,"json_instruction","append")}let I=x.build(),$=x.getUserPrompt(),C=x.getStats(),v=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),A=v?` | key: ***${v.slice(-4)}`:" | key: not set";console.log(`
86
- \u25C6 Model: ${p||"auto"}${A}
87
- `);let D=(await import("chalk")).default;console.log(`
88
- ${D.bold("Prompt sent to LLM:")}`),console.log(D.dim("\u2500".repeat(60))),console.log(D.dim($)),console.log(D.dim("\u2500".repeat(60)));let E=this._createGeminiConfigDir(n,h),R=["--output-format","json"];p&&p!=="auto"&&R.push("--model",p);let M=Object.keys(h);if(M.length>0){R.push("--approval-mode","yolo");for(let _ of M)R.push("--allowed-mcp-server-names",_);f.info(`[Gemini] Enabling MCP servers: ${M.join(", ")}`)}else i&&i.length>0&&f.warn(`[Gemini] Skills requested but no MCP servers configured: ${i.join(", ")}`);R.push("-p",I);let N={...process.env,GEMINI_CLI_HOME:E};g?(N.GEMINI_API_KEY=g,delete N.GOOGLE_API_KEY):S&&(N.GOOGLE_API_KEY=S,delete N.GEMINI_API_KEY),f.debug(`[Gemini] Command: gemini ${R.slice(0,8).join(" ")}... (${R.length} total args)`),f.debug(`[Gemini] User prompt: ${C.userPromptLength} chars, System instructions: ${C.systemInstructionsLength} chars (${C.instructionCount} blocks), Full: ${C.fullPromptLength} chars`),f.debug(`[Gemini] Config home: ${E}`),f.debug(`[Gemini] GEMINI_CLI_HOME env: ${N.GEMINI_CLI_HOME}`);let U="",O=null;try{U=await new Promise((B,L)=>{let F=Xn("gemini",R,{cwd:n,env:N,stdio:["ignore","pipe","pipe"],...u&&{signal:u}}),Q="",Jt="",lt=!1,Oe=null,ut=!1,zt=setTimeout(()=>{try{F.kill("SIGTERM")}catch{}},a),Ke=()=>{ut||lt||(ut=!0,Oe=setTimeout(()=>{if(!lt)try{F.kill("SIGKILL")}catch{}},5e3))};u&&(u.aborted?Ke():u.addEventListener("abort",Ke,{once:!0})),F.stdout.on("data",X=>{Q+=X.toString()}),F.stderr.on("data",X=>{Jt+=X.toString()}),F.on("error",X=>{if(clearTimeout(zt),Oe&&clearTimeout(Oe),u&&!u.aborted)try{u.removeEventListener("abort",Ke)}catch{}L(X)}),F.on("close",X=>{if(lt=!0,clearTimeout(zt),Oe&&clearTimeout(Oe),u&&!u.aborted)try{u.removeEventListener("abort",Ke)}catch{}if(ut){let Kt=new Error("Aborted via signal");return Kt.name="AbortError",L(Kt)}if(X===0)return B(Q.trim());L(new Error(`gemini failed with code ${X}: ${(Jt||Q).trim()}`))})})}catch(_){O=_}finally{try{Vn(E,{recursive:!0,force:!0})}catch{}}let y=ts(U).trim();if(!s){if(O)throw O;return y}if(w){let _=ar(w);if(f.info(`[Gemini] Result file: ${_?"present":"missing"} at ${w}`),_)try{let B=lr(w,"utf-8").trim(),L=JSON.parse(B),F=T?s.parse(L):L;return f.info("[Gemini] Structured output recovered from result file"),{raw:y,structured:F}}catch(B){f.warn(`[Gemini] Result file parse/validation failed: ${B.message}`)}else O||f.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let k=null;if(s){let _=new H;_.zodSchema=s,_.processChunk(y),_.flush(),k=_.getResult()}if(f.info(`[Gemini] Raw stdout length: ${U.length} chars`),f.info(`[Gemini] Extracted text length: ${y.length} chars`),f.info(`[Gemini] StreamParser result: ${k?"extracted":"null"}`),k||(y.length<2e3?f.info(`[Gemini] Raw text preview:
89
- ${y}`):f.info(`[Gemini] Raw text preview (first 1000 chars):
90
- ${y.slice(0,1e3)}`),k=es(y)),!k)throw O||(f.error("[Gemini] Failed to extract valid JSON from output"),f.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error("Gemini did not return valid JSON for structured output. Enable strictMode for proxy fallback."));let P=T?s.parse(k):k;return{raw:y,structured:P}}finally{for(let m of d)m.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=Wn(n);if(!s||typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let c=s.cursorKey||s.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=se(e||process.cwd(),".zibby","tmp",`gemini-home-${r}`),s=se(n,".gemini");cr(s,{recursive:!0});let i=se(s,"settings.json"),c={},l=se(process.env.HOME||"",".gemini","settings.json");if(ar(l))try{c=JSON.parse(lr(l,"utf-8"))}catch{c={}}let a={...c,mcpServers:{...c.mcpServers&&typeof c.mcpServers=="object"?c.mcpServers:{},...t||{}}};ur(i,`${JSON.stringify(a,null,2)}
91
- `,"utf-8");let u=se(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{ur(u,`${JSON.stringify(a,null,2)}
92
- `,"utf-8")}catch{}return f.debug(`[Gemini] Created isolated config with ${Object.keys(a.mcpServers||{}).length} MCP servers`),f.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(a.mcpServers||{}),null,2)}`),n}};import{AgentStrategy as ms,getSkill as Qe}from"@zibby/agent-workflow";var he=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 ie=class extends he{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 ke=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 Ze(o){return Buffer.byteLength(JSON.stringify(o),"utf8")}function Xe(o,e){let t=String(o||"");if(t.length<=e)return t;let r=Math.max(0,e-28);return`${t.slice(0,r)}
93
-
94
- [truncated for size budget]`}function ht(o,e=0){if(!o||typeof o!="object"||e>8)return o;if(Array.isArray(o))return o.map(r=>ht(r,e+1));let t={};for(let[r,n]of Object.entries(o))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=ht(n,e+1));return t}function rs(o=[]){return o.map(e=>({...e,function:{...e.function,description:Xe(e.function?.description||"",180),parameters:ht(e.function?.parameters||{type:"object",properties:{}})}}))}function pr(o){let e=new Set;for(let n of o)if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let s of n.tool_calls)e.add(s.id);let t=o.filter(n=>n.role==="tool"?e.has(n.tool_call_id):!0),r=new Set;for(let n of t)n.role==="tool"&&r.add(n.tool_call_id);return t.map(n=>{if(n.role!=="assistant"||!Array.isArray(n.tool_calls)||n.tool_calls.every(l=>r.has(l.id)))return n;let{tool_calls:i,...c}=n;return{...c,content:c.content||""}})}function yt(o,e={}){let t=e.maxBytes||49e3,r=e.systemMaxChars||12e3,n={...o,messages:Array.isArray(o.messages)?[...o.messages]:[],tools:Array.isArray(o.tools)?rs(o.tools):o.tools};n.messages.length>0&&n.messages[0]?.role==="system"&&(n.messages[0]={...n.messages[0],content:Xe(n.messages[0].content,r)});let s=!1;for(;Ze(n)>t&&n.messages.length>2;)n.messages.splice(1,1),s=!0;if(s&&(n.messages=pr(n.messages)),Ze(n)>t&&n.messages.length>0&&(n.messages[0]={...n.messages[0],content:Xe(n.messages[0].content,6e3)},s=!0),Ze(n)>t){let i=n.messages.find(l=>l.role==="system")||n.messages[0],c=n.messages.slice(-2);n.messages=pr([i,...c].filter(Boolean).map((l,a)=>({...l,content:Xe(l.content,a===0?4e3:8e3)}))),s=!0}return{body:n,meta:{bytes:Ze(n),trimmed:s,maxBytes:t,messageCount:n.messages.length}}}var fr=o=>Buffer.byteLength(JSON.stringify(o),"utf8"),ye=class extends ke{async fetchCompletion(e,t,r={}){let n=fr(e),{body:s,meta:i}=yt(e,r.payloadCompaction);r.onBudget?.({streaming:!1,beforeBytes:n,meta:i});let c=this.#e(r),l=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,a=await fetch(l,{method:"POST",headers:t.headers,body:JSON.stringify(s),signal:c});if(!a.ok){let u=await a.text();throw a.status===401||a.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${a.status}: ${u}`)}return a.json()}async fetchStreamingCompletion(e,t,r={}){let n={...e,stream:!0},s=fr(n),{body:i,meta:c}=yt(n,r.payloadCompaction);r.onBudget?.({streaming:!0,beforeBytes:s,meta:c});let l=this.#e(r),a=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,u=await fetch(a,{method:"POST",headers:t.headers,body:JSON.stringify(i),signal:l});if(!u.ok){let h=await u.text();throw u.status===401||u.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${u.status}: ${h}`)}let d=u.body.getReader(),m=new TextDecoder,p="",g="",S=new Map;for(;;){let{done:h,value:b}=await d.read();if(h)break;p+=m.decode(b,{stream:!0});let x=p.split(`
95
- `);p=x.pop();for(let T of x){if(!T.startsWith("data: "))continue;let w=T.slice(6).trim();if(w==="[DONE]")continue;let I;try{I=JSON.parse(w)}catch{continue}let $=I.choices?.[0]?.delta;if($&&($.content&&(g+=$.content,r.onToken&&r.onToken($.content)),$.tool_calls))for(let C of $.tool_calls){let v=C.index??0;S.has(v)||S.set(v,{id:"",name:"",args:""});let A=S.get(v);C.id&&(A.id=C.id),C.function?.name&&(A.name=C.function.name),C.function?.arguments!=null&&(A.args+=C.function.arguments)}}}if(S.size>0){let h=[...S.entries()].sort(([b],[x])=>b-x).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 ns}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as ss}from"@modelcontextprotocol/sdk/client/stdio.js";var Me=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:r,args:n=[],env:s={}}=t;f.debug(`[MCP] Starting ${e}: ${r} ${n.join(" ")}`);let i=new ss({command:r,args:n,env:{...process.env,...s}}),c=new ns({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await c.connect(i);let l={client:c,transport:i,serverConfig:t};return this.#e.set(e,l),l}async callTool(e,t,r={}){let n=this.#e.get(e);if(!n)throw new Error(`MCP server "${e}" not running`);f.debug(`[MCP] ${e}.${t}(${JSON.stringify(r).slice(0,200)})`);let s=await n.client.callTool({name:t,arguments:r});return{text:s.content?.filter(c=>c.type==="text").map(c=>c.text).join(`
96
- `)||"",isError:s.isError||!1}}isRunning(e){return this.#e.has(e)}async stopServer(e){let t=this.#e.get(e);if(t){try{await t.client.close()}catch(r){f.debug(`[MCP] Error closing ${e}: ${r.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}};import{existsSync as os,readFileSync as is}from"node:fs";import{join as as}from"node:path";import{homedir as cs}from"node:os";function ls(){try{let o=as(cs(),".zibby","config.json");return os(o)?JSON.parse(is(o,"utf-8")):{}}catch{return{}}}function qe(o){return String(o||"").replace(/\/v1\/?$/,"")}function us(o,e){let t=process.env.OPENAI_PROXY_URL;if(t)return qe(t);if(o==="session")return e.proxyUrl?qe(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(o==="byok"){let r=process.env.OPENAI_BASE_URL;return qe(r||"https://api.openai.com")}return qe(t||"")}function St(){let o=ls(),e=process.env.ZIBBY_USER_TOKEN||o.sessionToken||null,t=process.env.OPENAI_API_KEY||null,r=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),n=process.env.OPENAI_PROXY_NO_AUTH==="true",s=process.env.OPENAI_PROXY_URL,i="session";r==="byok"||r==="local"||r==="session"?i=r:e?i="session":t?i="byok":s&&n&&(i="local");let c=us(i,o),l={"Content-Type":"application/json"};if(i==="session"){if(!e)return{ok:!1,mode:i,reason:"missing_session_token"};l.Authorization=`Bearer ${e}`}else if(i==="byok"){if(!t)return{ok:!1,mode:i,reason:"missing_openai_api_key"};l.Authorization=`Bearer ${t}`}else if(i==="local"){if(!c)return{ok:!1,mode:i,reason:"missing_openai_proxy_url"};!n&&t&&(l.Authorization=`Bearer ${t}`)}return c?{ok:!0,mode:i,baseUrl:c,headers:l,tokenPreview:l.Authorization?`***${l.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:i,reason:"missing_base_url"}}function Ve(o,e){let t=String(o??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
97
-
98
- [tool result truncated for size]`}function ps(o,e){if(typeof o=="string")return Ve(o,e);try{return Ve(JSON.stringify(o),e)}catch{return Ve(String(o),e)}}function dr(o){let e=new Set;for(let n of o)if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let s of n.tool_calls)e.add(s.id);let t=o.filter(n=>n.role==="tool"?e.has(n.tool_call_id):!0),r=new Set;for(let n of t)n.role==="tool"&&r.add(n.tool_call_id);return t.map(n=>{if(n.role!=="assistant"||!Array.isArray(n.tool_calls)||n.tool_calls.every(l=>r.has(l.id)))return n;let{tool_calls:i,...c}=n;return{...c,content:c.content||""}})}function fs(o){let e=Array.isArray(o?.messages)?o.messages:[],t=e.find(s=>s.role==="system"),r=e.slice(-4).map(s=>({...s,content:Ve(s.content,s.role==="tool"?1200:2500)}));r=dr(r);let n={...o,messages:[t,...r].filter(Boolean)};return delete n.tools,n}async function ds({body:o,streaming:e,auth:t,options:r,fetchCompletion:n,fetchStreamingCompletion:s,onFallbackLog:i}){try{return e?await s(o,t,r):await n(o,t,r)}catch(c){let l=String(c?.message||c||"");if(!/proxy error 413|payload too large/i.test(l))throw c;let a=fs(o);return typeof i=="function"&&i(o,a),{data:e?await s(a,t,r):await n(a,t,r),fallback:a}}}async function mr({body:o,auth:e,options:t,streaming:r,toolContext:n,activeSkills:s,round:i,verbose:c,dependencies:l,config:a={}}){let u=a.maxToolResultChars||3e3,{fetchCompletion:d,fetchStreamingCompletion:m,onFallbackLog:p,hasToolCalls:g,getTextContent:S,parseToolCalls:h,buildAssistantMessage:b,buildToolResultMessage:x,executeTool:T,onToolCallLog:w,injectTools:I}=l;Array.isArray(o?.messages)&&(o.messages=dr(o.messages));let $=await ds({body:o,streaming:r,auth:e,options:t,fetchCompletion:d,fetchStreamingCompletion:m,onFallbackLog:p}),C=$?.data||$;if(!g(C))return{done:!0,text:S(C),body:$?.fallback||o};let v=h(C),A=$?.fallback||o;A.messages.push(b(C)),c&&typeof w=="function"&&w(v);let D=await Promise.all(v.map((E,R)=>(typeof t.onToolCall=="function"&&t.onToolCall(E.name,E.args,{round:i,index:R,total:v.length}),T(E,n))));for(let E=0;E<v.length;E++){let M=v[E].name==="get_skill_context"?typeof D[E]=="string"?D[E]:JSON.stringify(D[E]):ps(D[E],u);A.messages.push(x(v[E].id,M))}return typeof t.onToolCall=="function"&&t.onToolCall(null),I(A,s),{done:!1,body:A}}var gs=j.ASSISTANT,hs=15,bt="get_skill_context";function be(o){!o||typeof o!="object"||(o.type==="object"&&o.properties&&(o.required=Object.keys(o.properties),o.additionalProperties=!1,Object.values(o.properties).forEach(be)),o.type==="array"&&o.items&&be(o.items),o.anyOf&&o.anyOf.forEach(be),o.oneOf&&o.oneOf.forEach(be),o.allOf&&o.allOf.forEach(be))}var gr={maxBytes:49e3,systemMaxChars:12e3},Se=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",ys=o=>Buffer.byteLength(JSON.stringify(o),"utf8");function et(o){return Array.isArray(o)?new Set(o.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function Ss(o){return Array.isArray(o)?o.map(e=>String(e||"").trim()).filter(Boolean):[]}var ae=class extends ms{#e;#t;#r=new Me;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new ie,this.#t=e.completionProvider||new ye):(this.#e=e||new ie,this.#t=new ye)}canHandle(e){return St().ok}async invoke(e,t={}){let r=J("OPENAI_API_KEY");try{let n=t.model&&t.model!=="auto"?t.model:gs,s=St();if(!s.ok)throw s.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):s.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):s.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${s.reason}).`);let i=t.messages||[{role:"user",content:e}],c=s.baseUrl,l=Se();if(l?await this.#m(i,n,c,s.tokenPreview||"none"):f.debug(`[Assistant] ${c} | model: ${n} | messages: ${i.length}`),t.schema)return this.#l(n,i,s,t);let a=t.activeSkills||[],u=this.#p(t),d=this.#f(a,u),m=this.#d(d),p=this.#u(t),g={...t,payloadCompaction:p},S={activeSkills:d,options:g,executionRegistry:m,capabilityPolicy:u},h=!!t.stream,b={model:n,messages:[...i],stream:!1};this.#s(b,d,u);for(let x=0;x<hs;x++){if(t.signal?.aborted){let w=new Error("Aborted via signal");throw w.name="AbortError",w}let T=await mr({body:b,auth:s,options:g,streaming:h,toolContext:S,activeSkills:d,round:x,verbose:l,dependencies:{fetchCompletion:this.#o.bind(this),fetchStreamingCompletion:this.#c.bind(this),onFallbackLog:(w,I)=>{Se()&&console.log(`413 fallback: messages ${w.messages.length} -> ${I.messages.length}, bytes=${ys(I)}`)},hasToolCalls:w=>this.#e.hasToolCalls(w),getTextContent:w=>this.#e.getTextContent(w),parseToolCalls:w=>this.#e.parseToolCalls(w),buildAssistantMessage:w=>this.#e.buildAssistantMessage(w),buildToolResultMessage:(w,I)=>this.#e.buildToolResultMessage(w,I),executeTool:(w,I)=>this.#a(w,I),onToolCallLog:async w=>{let I=(await import("chalk")).default;console.log(I.dim(` ${w.map($=>`${$.name}(${JSON.stringify($.args).slice(0,80)})`).join(", ")}`))},injectTools:(w,I)=>this.#s(w,I,u)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(T.done)return T.text;b.messages=T.body.messages,T.body.tools?b.tools=T.body.tools:delete b.tools}return"I hit my tool-calling limit for this turn. Please try again."}finally{r.dispose()}}async cleanup(){await this.#r.stopAll()}#s(e,t,r=null){let n=this.#i(t,r),s=this.#e.formatTools(n);this.#e.injectToolsIntoBody(e,s)}#i(e,t=null){let r=[],n=new Set;for(let s of e){let i=Qe(s);if(i?.tools?.length)for(let c of i.tools)this.#n(c.name,t)&&(n.has(c.name)||(n.add(c.name),r.push({name:c.name,description:c.description,parameters:c.parameters||c.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#n(bt,t)&&r.push({name:bt,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),r}async#a(e,t){let{activeSkills:r,options:n,executionRegistry:s,capabilityPolicy:i}=t;if(!this.#n(e.name,i))return`Tool "${e.name}" blocked by policy`;if(e.name===bt){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=Qe(a);if(!u)return JSON.stringify({error:`Skill "${a}" not found`});let d=typeof u.promptFragment=="function"?u.promptFragment():u.promptFragment||"",m=(u.tools||[]).map(g=>g.name),p=JSON.stringify({skillId:a,description:u.description||"",toolNames:m,promptFragment:d||""});return Se()&&(console.log(`
99
- \u{1F4D6} get_skill_context("${a}") \u2192 ${p.length} chars (fragment: ${d.length} chars)`),console.log(` tools: [${m.join(", ")}]`),console.log(` fragment preview: ${d.slice(0,200).replace(/\n/g,"\\n")}\u2026
100
- `)),p}let c=s?.get(e.name)||null;if(!c)return`Unknown tool: ${e.name}`;let l=Qe(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#c(e,t,r){return this.#t.fetchStreamingCompletion(e,t,{...r,onBudget:({beforeBytes:n,meta:s})=>{Se()&&console.log(`payload bytes (stream) before=${n} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#o(e,t,r){return this.#t.fetchCompletion(e,t,{...r,onBudget:({beforeBytes:n,meta:s})=>{Se()&&console.log(`payload bytes before=${n} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#l(e,t,r,n){let{zodToJsonSchema:s}=await import("zod-to-json-schema"),i=typeof n.schema?.parse=="function",c=i?s(n.schema):n.schema;delete c.$schema,be(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.#o(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||gr.maxBytes),systemMaxChars:Number(t.systemMaxChars||gr.systemMaxChars)}}#p(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:et(t.allowTools||e.allowTools),denyTools:et(t.denyTools||e.denyTools),denyPrefixes:Ss(t.denyPrefixes||e.denyToolPrefixes),includeSkills:et(t.includeSkills||e.includeSkills),excludeSkills:et(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#f(e,t){let r=t?.includeSkills||new Set,n=t?.excludeSkills||new Set;return r.size===0&&n.size===0?e:e.filter(s=>!(r.size>0&&!r.has(s)||n.has(s)))}#n(e,t){let r=String(e||"").trim();if(!r)return!1;let n=t?.allowTools;if(n&&n.size>0&&!n.has(r))return!1;let s=t?.denyTools;return!(s&&s.has(r)||(t?.denyPrefixes||[]).some(c=>r.startsWith(c)))}#d(e){let t=new Map,r=[];for(let n of e){let s=Qe(n);if(!s?.tools?.length)continue;let i=typeof s.handleToolCall=="function"?"handler":s.serverName&&typeof s.resolve=="function"?"mcp":null;if(i)for(let c of s.tools){let l=String(c?.name||"").trim();if(l){if(t.has(l)){r.push({tool:l,winner:t.get(l).skillId,skipped:n});continue}t.set(l,{skillId:n,mode:i})}}}if(r.length>0&&Se()){let n=r.slice(0,5).map(s=>`${s.tool}:${s.winner}>${s.skipped}`).join(", ");console.log(`tool registry collisions: ${n}${r.length>5?" ...":""}`)}return t}async#m(e,t,r,n){console.log(`
91
+ ${x.bold("Prompt sent to LLM:")}`),console.log(x.dim("\u2500".repeat(60))),console.log(x.dim(M)),console.log(x.dim("\u2500".repeat(60)));let N=this._createGeminiConfigDir(n,h),k=["--output-format","json"];p&&p!=="auto"&&k.push("--model",p);let R=Object.keys(h);if(R.length>0){k.push("--approval-mode","yolo");for(let I of R)k.push("--allowed-mcp-server-names",I);f.info(`[Gemini] Enabling MCP servers: ${R.join(", ")}`)}else i&&i.length>0&&f.warn(`[Gemini] Skills requested but no MCP servers configured: ${i.join(", ")}`);k.push("-p",P);let L={...process.env,GEMINI_CLI_HOME:N};g?(L.GEMINI_API_KEY=g,delete L.GOOGLE_API_KEY):y&&(L.GOOGLE_API_KEY=y,delete L.GEMINI_API_KEY),f.debug(`[Gemini] Command: gemini ${k.slice(0,8).join(" ")}... (${k.length} total args)`),f.debug(`[Gemini] User prompt: ${T.userPromptLength} chars, System instructions: ${T.systemInstructionsLength} chars (${T.instructionCount} blocks), Full: ${T.fullPromptLength} chars`),f.debug(`[Gemini] Config home: ${N}`),f.debug(`[Gemini] GEMINI_CLI_HOME env: ${L.GEMINI_CLI_HOME}`);let F="",w=null;try{F=await new Promise(($,B)=>{let j=fs("gemini",k,{cwd:n,env:L,stdio:["ignore","pipe","pipe"],...u&&{signal:u}}),pt="",Ht="",ft=!1,Pe=null,dt=!1,Wt=setTimeout(()=>{try{j.kill("SIGTERM")}catch{}},l),Ye=()=>{dt||ft||(dt=!0,Pe=setTimeout(()=>{if(!ft)try{j.kill("SIGKILL")}catch{}},5e3))};u&&(u.aborted?Ye():u.addEventListener("abort",Ye,{once:!0})),j.stdout.on("data",q=>{pt+=q.toString()}),j.stderr.on("data",q=>{Ht+=q.toString()}),j.on("error",q=>{if(clearTimeout(Wt),Pe&&clearTimeout(Pe),u&&!u.aborted)try{u.removeEventListener("abort",Ye)}catch{}B(q)}),j.on("close",q=>{if(ft=!0,clearTimeout(Wt),Pe&&clearTimeout(Pe),u&&!u.aborted)try{u.removeEventListener("abort",Ye)}catch{}if(dt){let Zt=new Error("Aborted via signal");return Zt.name="AbortError",B(Zt)}if(q===0)return $(pt.trim());B(new Error(`gemini failed with code ${q}: ${(Ht||pt).trim()}`))})})}catch(I){w=I}finally{try{ms(N,{recursive:!0,force:!0})}catch{}}let O=ys(F).trim();if(!s){if(w)throw w;return O}if(v){let I=mr(v);if(f.info(`[Gemini] Result file: ${I?"present":"missing"} at ${v}`),I)try{let $=hr(v,"utf-8").trim(),B=JSON.parse($),j=E?s.parse(B):B;return f.info("[Gemini] Structured output recovered from result file"),{raw:O,structured:j}}catch($){f.warn(`[Gemini] Result file parse/validation failed: ${$.message}`)}else w||f.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let b=null;if(s){let I=new W;I.zodSchema=s,I.processChunk(O),I.flush(),b=I.getResult()}if(f.info(`[Gemini] Raw stdout length: ${F.length} chars`),f.info(`[Gemini] Extracted text length: ${O.length} chars`),f.info(`[Gemini] StreamParser result: ${b?"extracted":"null"}`),b||(O.length<2e3?f.info(`[Gemini] Raw text preview:
92
+ ${O}`):f.info(`[Gemini] Raw text preview (first 1000 chars):
93
+ ${O.slice(0,1e3)}`),b=hs(O)),!b)throw w||(f.error("[Gemini] Failed to extract valid JSON from output"),f.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error("Gemini did not return valid JSON for structured output. Enable strictMode for proxy fallback."));let D=E?s.parse(b):b;return{raw:O,structured:D}}finally{for(let d of m)d.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=us(n);if(!s||typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let a=s.cursorKey||s.serverName||n,c={command:i.command};i.args?.length&&(c.args=i.args),i.env&&Object.keys(i.env).length>0&&(c.env=i.env),i.cwd&&(c.cwd=i.cwd),r[a]=c}return r}_createGeminiConfigDir(e,t){let r=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,n=oe(e||process.cwd(),".zibby","tmp",`gemini-home-${r}`),s=oe(n,".gemini");gr(s,{recursive:!0});let i=oe(s,"settings.json"),a={},c=oe(process.env.HOME||"",".gemini","settings.json");if(mr(c))try{a=JSON.parse(hr(c,"utf-8"))}catch{a={}}let l={...a,mcpServers:{...a.mcpServers&&typeof a.mcpServers=="object"?a.mcpServers:{},...t||{}}};yr(i,`${JSON.stringify(l,null,2)}
94
+ `,"utf-8");let u=oe(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{yr(u,`${JSON.stringify(l,null,2)}
95
+ `,"utf-8")}catch{}return f.debug(`[Gemini] Created isolated config with ${Object.keys(l.mcpServers||{}).length} MCP servers`),f.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(l.mcpServers||{}),null,2)}`),n}};import{AgentStrategy as Ps,getSkill as tt}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 ae=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 Me=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 qe(o){return Buffer.byteLength(JSON.stringify(o),"utf8")}function Ve(o,e){let t=String(o||"");if(t.length<=e)return t;let r=Math.max(0,e-28);return`${t.slice(0,r)}
96
+
97
+ [truncated for size budget]`}function wt(o,e=0){if(!o||typeof o!="object"||e>8)return o;if(Array.isArray(o))return o.map(r=>wt(r,e+1));let t={};for(let[r,n]of Object.entries(o))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=wt(n,e+1));return t}function Ss(o=[]){return o.map(e=>({...e,function:{...e.function,description:Ve(e.function?.description||"",180),parameters:wt(e.function?.parameters||{type:"object",properties:{}})}}))}function Sr(o){let e=new Set;for(let n of o)if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let s of n.tool_calls)e.add(s.id);let t=o.filter(n=>n.role==="tool"?e.has(n.tool_call_id):!0),r=new Set;for(let n of t)n.role==="tool"&&r.add(n.tool_call_id);return t.map(n=>{if(n.role!=="assistant"||!Array.isArray(n.tool_calls)||n.tool_calls.every(c=>r.has(c.id)))return n;let{tool_calls:i,...a}=n;return{...a,content:a.content||""}})}function xt(o,e={}){let t=e.maxBytes||49e3,r=e.systemMaxChars||12e3,n={...o,messages:Array.isArray(o.messages)?[...o.messages]:[],tools:Array.isArray(o.tools)?Ss(o.tools):o.tools};n.messages.length>0&&n.messages[0]?.role==="system"&&(n.messages[0]={...n.messages[0],content:Ve(n.messages[0].content,r)});let s=!1;for(;qe(n)>t&&n.messages.length>2;)n.messages.splice(1,1),s=!0;if(s&&(n.messages=Sr(n.messages)),qe(n)>t&&n.messages.length>0&&(n.messages[0]={...n.messages[0],content:Ve(n.messages[0].content,6e3)},s=!0),qe(n)>t){let i=n.messages.find(c=>c.role==="system")||n.messages[0],a=n.messages.slice(-2);n.messages=Sr([i,...a].filter(Boolean).map((c,l)=>({...c,content:Ve(c.content,l===0?4e3:8e3)}))),s=!0}return{body:n,meta:{bytes:qe(n),trimmed:s,maxBytes:t,messageCount:n.messages.length}}}var br=o=>Buffer.byteLength(JSON.stringify(o),"utf8"),Se=class extends Me{async fetchCompletion(e,t,r={}){let n=br(e),{body:s,meta:i}=xt(e,r.payloadCompaction);r.onBudget?.({streaming:!1,beforeBytes:n,meta:i});let a=this.#e(r),c=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,l=await fetch(c,{method:"POST",headers:t.headers,body:JSON.stringify(s),signal:a});if(!l.ok){let u=await l.text();throw l.status===401||l.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${l.status}: ${u}`)}return l.json()}async fetchStreamingCompletion(e,t,r={}){let n={...e,stream:!0},s=br(n),{body:i,meta:a}=xt(n,r.payloadCompaction);r.onBudget?.({streaming:!0,beforeBytes:s,meta:a});let c=this.#e(r),l=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,u=await fetch(l,{method:"POST",headers:t.headers,body:JSON.stringify(i),signal:c});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 m=u.body.getReader(),d=new TextDecoder,p="",g="",y=new Map;for(;;){let{done:h,value:S}=await m.read();if(h)break;p+=d.decode(S,{stream:!0});let _=p.split(`
98
+ `);p=_.pop();for(let A of _){if(!A.startsWith("data: "))continue;let E=A.slice(6).trim();if(E==="[DONE]")continue;let v;try{v=JSON.parse(E)}catch{continue}let P=v.choices?.[0]?.delta;if(P&&(P.content&&(g+=P.content,r.onToken&&r.onToken(P.content)),P.tool_calls))for(let M of P.tool_calls){let T=M.index??0;y.has(T)||y.set(T,{id:"",name:"",args:""});let C=y.get(T);M.id&&(C.id=M.id),M.function?.name&&(C.name=M.function.name),M.function?.arguments!=null&&(C.args+=M.function.arguments)}}}if(y.size>0){let h=[...y.entries()].sort(([S],[_])=>S-_).map(([,S])=>({id:S.id,type:"function",function:{name:S.name,arguments:S.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 bs}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as ws}from"@modelcontextprotocol/sdk/client/stdio.js";var Le=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:r,args:n=[],env:s={}}=t;f.debug(`[MCP] Starting ${e}: ${r} ${n.join(" ")}`);let i=new ws({command:r,args:n,env:{...process.env,...s}}),a=new bs({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await a.connect(i);let c={client:a,transport:i,serverConfig:t};return this.#e.set(e,c),c}async callTool(e,t,r={}){let n=this.#e.get(e);if(!n)throw new Error(`MCP server "${e}" not running`);f.debug(`[MCP] ${e}.${t}(${JSON.stringify(r).slice(0,200)})`);let s=await n.client.callTool({name:t,arguments:r});return{text:s.content?.filter(a=>a.type==="text").map(a=>a.text).join(`
99
+ `)||"",isError:s.isError||!1}}isRunning(e){return this.#e.has(e)}async stopServer(e){let t=this.#e.get(e);if(t){try{await t.client.close()}catch(r){f.debug(`[MCP] Error closing ${e}: ${r.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}};import{existsSync as xs,readFileSync as _s}from"node:fs";import{join as Es}from"node:path";import{homedir as Ts}from"node:os";function vs(){try{let o=Es(Ts(),".zibby","config.json");return xs(o)?JSON.parse(_s(o,"utf-8")):{}}catch{return{}}}function Qe(o){return String(o||"").replace(/\/v1\/?$/,"")}function As(o,e){let t=process.env.OPENAI_PROXY_URL;if(t)return Qe(t);if(o==="session")return e.proxyUrl?Qe(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(o==="byok"){let r=process.env.OPENAI_BASE_URL;return Qe(r||"https://api.openai.com")}return Qe(t||"")}function _t(){let o=vs(),e=process.env.ZIBBY_USER_TOKEN||o.sessionToken||null,t=process.env.OPENAI_API_KEY||null,r=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),n=process.env.OPENAI_PROXY_NO_AUTH==="true",s=process.env.OPENAI_PROXY_URL,i="session";r==="byok"||r==="local"||r==="session"?i=r:e?i="session":t?i="byok":s&&n&&(i="local");let a=As(i,o),c={"Content-Type":"application/json"};if(i==="session"){if(!e)return{ok:!1,mode:i,reason:"missing_session_token"};c.Authorization=`Bearer ${e}`}else if(i==="byok"){if(!t)return{ok:!1,mode:i,reason:"missing_openai_api_key"};c.Authorization=`Bearer ${t}`}else if(i==="local"){if(!a)return{ok:!1,mode:i,reason:"missing_openai_proxy_url"};!n&&t&&(c.Authorization=`Bearer ${t}`)}return a?{ok:!0,mode:i,baseUrl:a,headers:c,tokenPreview:c.Authorization?`***${c.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:i,reason:"missing_base_url"}}function et(o,e){let t=String(o??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
100
+
101
+ [tool result truncated for size]`}function Is(o,e){if(typeof o=="string")return et(o,e);try{return et(JSON.stringify(o),e)}catch{return et(String(o),e)}}function wr(o){let e=new Set;for(let n of o)if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let s of n.tool_calls)e.add(s.id);let t=o.filter(n=>n.role==="tool"?e.has(n.tool_call_id):!0),r=new Set;for(let n of t)n.role==="tool"&&r.add(n.tool_call_id);return t.map(n=>{if(n.role!=="assistant"||!Array.isArray(n.tool_calls)||n.tool_calls.every(c=>r.has(c.id)))return n;let{tool_calls:i,...a}=n;return{...a,content:a.content||""}})}function $s(o){let e=Array.isArray(o?.messages)?o.messages:[],t=e.find(s=>s.role==="system"),r=e.slice(-4).map(s=>({...s,content:et(s.content,s.role==="tool"?1200:2500)}));r=wr(r);let n={...o,messages:[t,...r].filter(Boolean)};return delete n.tools,n}async function Os({body:o,streaming:e,auth:t,options:r,fetchCompletion:n,fetchStreamingCompletion:s,onFallbackLog:i}){try{return e?await s(o,t,r):await n(o,t,r)}catch(a){let c=String(a?.message||a||"");if(!/proxy error 413|payload too large/i.test(c))throw a;let l=$s(o);return typeof i=="function"&&i(o,l),{data:e?await s(l,t,r):await n(l,t,r),fallback:l}}}async function xr({body:o,auth:e,options:t,streaming:r,toolContext:n,activeSkills:s,round:i,verbose:a,dependencies:c,config:l={}}){let u=l.maxToolResultChars||3e3,{fetchCompletion:m,fetchStreamingCompletion:d,onFallbackLog:p,hasToolCalls:g,getTextContent:y,parseToolCalls:h,buildAssistantMessage:S,buildToolResultMessage:_,executeTool:A,onToolCallLog:E,injectTools:v}=c;Array.isArray(o?.messages)&&(o.messages=wr(o.messages));let P=await Os({body:o,streaming:r,auth:e,options:t,fetchCompletion:m,fetchStreamingCompletion:d,onFallbackLog:p}),M=P?.data||P;if(!g(M))return{done:!0,text:y(M),body:P?.fallback||o};let T=h(M),C=P?.fallback||o;C.messages.push(S(M)),a&&typeof E=="function"&&E(T);let U=await Promise.all(T.map((x,N)=>(typeof t.onToolCall=="function"&&t.onToolCall(x.name,x.args,{round:i,index:N,total:T.length}),A(x,n))));for(let x=0;x<T.length;x++){let k=T[x].name==="get_skill_context"?typeof U[x]=="string"?U[x]:JSON.stringify(U[x]):Is(U[x],u);C.messages.push(_(T[x].id,k))}return typeof t.onToolCall=="function"&&t.onToolCall(null),v(C,s),{done:!1,body:C}}var Cs=G.ASSISTANT,Rs=15,Et="get_skill_context";function we(o){!o||typeof o!="object"||(o.type==="object"&&o.properties&&(o.required=Object.keys(o.properties),o.additionalProperties=!1,Object.values(o.properties).forEach(we)),o.type==="array"&&o.items&&we(o.items),o.anyOf&&o.anyOf.forEach(we),o.oneOf&&o.oneOf.forEach(we),o.allOf&&o.allOf.forEach(we))}var _r={maxBytes:49e3,systemMaxChars:12e3},be=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Ns=o=>Buffer.byteLength(JSON.stringify(o),"utf8");function rt(o){return Array.isArray(o)?new Set(o.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function ks(o){return Array.isArray(o)?o.map(e=>String(e||"").trim()).filter(Boolean):[]}var ce=class extends Ps{#e;#t;#r=new Le;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new ae,this.#t=e.completionProvider||new Se):(this.#e=e||new ae,this.#t=new Se)}canHandle(e){return _t().ok}async invoke(e,t={}){let r=J("OPENAI_API_KEY");try{let n=t.model&&t.model!=="auto"?t.model:Cs,s=_t();if(!s.ok)throw s.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):s.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):s.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${s.reason}).`);let i=t.messages||[{role:"user",content:e}],a=s.baseUrl,c=be();if(c?await this.#m(i,n,a,s.tokenPreview||"none"):f.debug(`[Assistant] ${a} | model: ${n} | messages: ${i.length}`),t.schema)return this.#l(n,i,s,t);let l=t.activeSkills||[],u=this.#p(t),m=this.#f(l,u),d=this.#d(m),p=this.#u(t),g={...t,payloadCompaction:p},y={activeSkills:m,options:g,executionRegistry:d,capabilityPolicy:u},h=!!t.stream,S={model:n,messages:[...i],stream:!1};this.#s(S,m,u);for(let _=0;_<Rs;_++){if(t.signal?.aborted){let E=new Error("Aborted via signal");throw E.name="AbortError",E}let A=await xr({body:S,auth:s,options:g,streaming:h,toolContext:y,activeSkills:m,round:_,verbose:c,dependencies:{fetchCompletion:this.#o.bind(this),fetchStreamingCompletion:this.#c.bind(this),onFallbackLog:(E,v)=>{be()&&console.log(`413 fallback: messages ${E.messages.length} -> ${v.messages.length}, bytes=${Ns(v)}`)},hasToolCalls:E=>this.#e.hasToolCalls(E),getTextContent:E=>this.#e.getTextContent(E),parseToolCalls:E=>this.#e.parseToolCalls(E),buildAssistantMessage:E=>this.#e.buildAssistantMessage(E),buildToolResultMessage:(E,v)=>this.#e.buildToolResultMessage(E,v),executeTool:(E,v)=>this.#a(E,v),onToolCallLog:async E=>{let v=(await import("chalk")).default;console.log(v.dim(` ${E.map(P=>`${P.name}(${JSON.stringify(P.args).slice(0,80)})`).join(", ")}`))},injectTools:(E,v)=>this.#s(E,v,u)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(A.done)return A.text;S.messages=A.body.messages,A.body.tools?S.tools=A.body.tools:delete S.tools}return"I hit my tool-calling limit for this turn. Please try again."}finally{r.dispose()}}async cleanup(){await this.#r.stopAll()}#s(e,t,r=null){let n=this.#i(t,r),s=this.#e.formatTools(n);this.#e.injectToolsIntoBody(e,s)}#i(e,t=null){let r=[],n=new Set;for(let s of e){let i=tt(s);if(i?.tools?.length)for(let a of i.tools)this.#n(a.name,t)&&(n.has(a.name)||(n.add(a.name),r.push({name:a.name,description:a.description,parameters:a.parameters||a.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#n(Et,t)&&r.push({name:Et,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),r}async#a(e,t){let{activeSkills:r,options:n,executionRegistry:s,capabilityPolicy:i}=t;if(!this.#n(e.name,i))return`Tool "${e.name}" blocked by policy`;if(e.name===Et){let l=String(e.args?.skillId||"").trim();if(!l)return JSON.stringify({error:"skillId is required"});if(!r.includes(l))return JSON.stringify({error:`Skill "${l}" is not active`,activeSkills:r});let u=tt(l);if(!u)return JSON.stringify({error:`Skill "${l}" not found`});let m=typeof u.promptFragment=="function"?u.promptFragment():u.promptFragment||"",d=(u.tools||[]).map(g=>g.name),p=JSON.stringify({skillId:l,description:u.description||"",toolNames:d,promptFragment:m||""});return be()&&(console.log(`
102
+ \u{1F4D6} get_skill_context("${l}") \u2192 ${p.length} chars (fragment: ${m.length} chars)`),console.log(` tools: [${d.join(", ")}]`),console.log(` fragment preview: ${m.slice(0,200).replace(/\n/g,"\\n")}\u2026
103
+ `)),p}let a=s?.get(e.name)||null;if(!a)return`Unknown tool: ${e.name}`;let c=tt(a.skillId);if(!c)return`Skill "${a.skillId}" not found for tool "${e.name}"`;if(a.mode==="handler")try{return c.handleToolCall(e.name,e.args,t)}catch(l){return`Error in ${e.name}: ${l.message}`}if(a.mode==="mcp")try{if(!this.#r.isRunning(c.serverName)){let u=c.resolve(n);if(!u)return`Skill "${a.skillId}" is not available (cannot start server)`;await this.#r.ensureServer(c.serverName,u)}let l=await this.#r.callTool(c.serverName,e.name,e.args);return l.text||(l.isError?"Tool call failed":"Done")}catch(l){return`MCP error (${c.serverName}): ${l.message}`}return`Skill "${a.skillId}" owns tool "${e.name}" but has no execution mode`}async#c(e,t,r){return this.#t.fetchStreamingCompletion(e,t,{...r,onBudget:({beforeBytes:n,meta:s})=>{be()&&console.log(`payload bytes (stream) before=${n} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#o(e,t,r){return this.#t.fetchCompletion(e,t,{...r,onBudget:({beforeBytes:n,meta:s})=>{be()&&console.log(`payload bytes before=${n} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#l(e,t,r,n){let{zodToJsonSchema:s}=await import("zod-to-json-schema"),i=typeof n.schema?.parse=="function",a=i?s(n.schema):n.schema;delete a.$schema,we(a);let c={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:a,strict:!0}}},l=await this.#o(c,r,n),u=this.#e.getTextContent(l),m=JSON.parse(u),d=i?n.schema.parse(m):m;return{raw:u,structured:d}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||_r.maxBytes),systemMaxChars:Number(t.systemMaxChars||_r.systemMaxChars)}}#p(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:rt(t.allowTools||e.allowTools),denyTools:rt(t.denyTools||e.denyTools),denyPrefixes:ks(t.denyPrefixes||e.denyToolPrefixes),includeSkills:rt(t.includeSkills||e.includeSkills),excludeSkills:rt(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#f(e,t){let r=t?.includeSkills||new Set,n=t?.excludeSkills||new Set;return r.size===0&&n.size===0?e:e.filter(s=>!(r.size>0&&!r.has(s)||n.has(s)))}#n(e,t){let r=String(e||"").trim();if(!r)return!1;let n=t?.allowTools;if(n&&n.size>0&&!n.has(r))return!1;let s=t?.denyTools;return!(s&&s.has(r)||(t?.denyPrefixes||[]).some(a=>r.startsWith(a)))}#d(e){let t=new Map,r=[];for(let n of e){let s=tt(n);if(!s?.tools?.length)continue;let i=typeof s.handleToolCall=="function"?"handler":s.serverName&&typeof s.resolve=="function"?"mcp":null;if(i)for(let a of s.tools){let c=String(a?.name||"").trim();if(c){if(t.has(c)){r.push({tool:c,winner:t.get(c).skillId,skipped:n});continue}t.set(c,{skillId:n,mode:i})}}}if(r.length>0&&be()){let n=r.slice(0,5).map(s=>`${s.tool}:${s.winner}>${s.skipped}`).join(", ");console.log(`tool registry collisions: ${n}${r.length>5?" ...":""}`)}return t}async#m(e,t,r,n){console.log(`
101
104
  \u25C6 Model: ${t} | proxy: ${r} | token: ${n||"none"}
102
- `);let s=(await import("chalk")).default;console.log(s.bold("Prompt sent to LLM:")),console.log(s.dim("\u2500".repeat(60)));let i=!1;for(let c of e)if(c.role==="system")console.log(s.dim(`[System] ${c.content||""}`));else{i||(console.log(s.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),i=!0);let l=c.role==="user"?"Human":"AI",a=c.content?.length>200?`${c.content.slice(0,200)}...`:c.content||"";console.log(s.dim(`[${l}] ${a}`))}console.log(s.dim("\u2500".repeat(60)))}};var hr=!1;function wt(){hr||(Le(new ae),Le(new te),Le(new re),Le(new ne),Le(new oe),hr=!0)}import{existsSync as Ue,readdirSync as Ar,statSync as Os}from"fs";import{join as z,relative as Et,sep as De,resolve as ce}from"path";import{appendFileSync as bs,readFileSync as ws,existsSync as yr,mkdirSync as xs}from"node:fs";import{join as tt}from"node:path";import{DEFAULT_OUTPUT_BASE as Sr}from"@zibby/agent-workflow";var br="run-index.jsonl";function wr(o,e=Sr){let t=tt(o,e);return tt(t,br)}function rt(o){if(!o||!o.sessionId)return;let e=o.cwd||process.cwd(),t=o.outputBase||Sr,r=tt(e,t);yr(r)||xs(r,{recursive:!0});let n=tt(r,br),s=`${JSON.stringify(o)}
103
- `;bs(n,s,"utf8")}function xr(o){if(!o||!yr(o))return[];let e;try{e=ws(o,"utf8")}catch{return[]}let t=[];for(let r of e.split(`
104
- `)){let n=r.trim();if(n)try{t.push(JSON.parse(n))}catch{}}return t}import{existsSync as _s,mkdirSync as Es,readFileSync as Ts,readdirSync as Ac,statSync as Ic,writeFileSync as vs}from"node:fs";import{join as As}from"node:path";var Is="zibby-run-state.json";function _r(o){return As(o,Is)}function xt(o){if(!o||typeof o!="string")return null;let e=_r(o);if(!_s(e))return null;try{let t=Ts(e,"utf8"),r=JSON.parse(t);return r&&typeof r=="object"?r:null}catch{return null}}function nt(o,e){if(!o||typeof o!="string")return;try{Es(o,{recursive:!0})}catch{return}let r={...xt(o)||{v:1},...e,v:1,updatedAt:Date.now()};try{vs(_r(o),`${JSON.stringify(r)}
105
- `,"utf8")}catch(n){console.warn(`[zibby run-state] ${n.message}`)}}function $s(o){return o?.recordKind==="progress"}function Er(o){let e=Number(o)||0;return e<=0?0:e<1e12?e*1e3:e}function Tr(o,e={}){let t=e.maxProgressAgeMs!=null&&Number.isFinite(e.maxProgressAgeMs)?Math.max(0,e.maxProgressAgeMs):21e5,r=typeof e.now=="number"?e.now:Date.now(),{summary:n,progress:s}=o||{};if(!s)return!1;let i=Er(s.ts);if(t>0&&i>0&&r-i>t)return!1;if(!n)return i>0;let c=Er(n.ts);return i>c}function vr(o){let e=new Map;for(let t of o||[]){if(!t?.sessionId)continue;let r=e.get(t.sessionId);r||(r={summary:null,progress:null});let n=Number(t.ts)||0;$s(t)?(!r.progress||n>=(Number(r.progress.ts)||0))&&(r.progress=t):(!r.summary||n>=(Number(r.summary.ts)||0))&&(r.summary=t),e.set(t.sessionId,r)}return e}import{DEFAULT_OUTPUT_BASE as le,SESSIONS_DIR as Tt}from"@zibby/agent-workflow";var _t=Object.freeze(["preflight","execute_live","generate_script"]);function vt(o){let e=process.env.ZIBBY_STUDIO_TEST_CASE_ID;return e!=null&&String(e).trim()!==""?String(e).trim():o!=null?String(o):""}var Ps=[z("generate_script","generated-test.spec.js"),z("generate_script","generated-test.spec.ts"),z("generate_script","playwright.spec.ts"),z("generate_script","test.spec.ts")];function Cs(o){let e=[z(o,"execute_live","videos"),z(o,"execute_live"),o];for(let t of e){if(!Ue(t))continue;let r;try{r=Ar(t)}catch{continue}let n=r.find(s=>s.endsWith(".webm"));if(n)return z(t,n)}return null}function Ns(o){let e=[z(o,"execute_live","events.json"),z(o,"events.json")];for(let t of e)if(Ue(t))return t;return null}function Rs(o){for(let e of Ps){let t=z(o,e);if(Ue(t))return t}return null}function ks(o){return!o||!Ue(o)?{videoPathAbs:null,eventsPathAbs:null,scriptPathAbs:null}:{videoPathAbs:Cs(o),eventsPathAbs:Ns(o),scriptPathAbs:Rs(o)}}function Ir(o){let e=o.cwd||process.cwd(),t=o.outputBase||le,s=((o.result||{}).state||{}).sessionPath;if(!s||typeof s!="string")return null;let i=s.split(/[/\\]/).filter(Boolean).pop();if(!i)return null;let{videoPathAbs:c,eventsPathAbs:l,scriptPathAbs:a}=ks(s),u=m=>{if(!m)return null;try{return Et(e,m).split(De).join("/")}catch{return null}},d=null;if(o.specPath)try{let m=ce(e,o.specPath);d=Et(e,m).split(De).join("/")}catch{d=String(o.specPath).split(De).join("/")}return{v:1,recordKind:"summary",ts:Date.now(),sessionId:i,status:o.status??(o.success?"completed":"failed"),cwd:e,outputBase:t,sessionPathAbs:s,sessionDirRel:u(s),videoPathAbs:c||null,eventsPathAbs:l||null,scriptPathAbs:a||null,videoRel:u(c),eventsRel:u(l),scriptRel:u(a),specRel:d,source:process.env.ZIBBY_RUN_SOURCE||"cli",studioTestCaseId:vt(i)||null,errorMessage:o.errorMessage||null}}function $r({cwd:o,config:e,result:t,success:r,specPath:n,errorMessage:s}){try{let i=Ir({cwd:o||process.cwd(),result:t,success:r,outputBase:e?.paths?.output||le,specPath:n,errorMessage:s});i&&(rt(i),i.sessionPathAbs&&nt(i.sessionPathAbs,{sessionId:i.sessionId,studioTestCaseId:i.studioTestCaseId||i.sessionId,status:i.status,activeNode:null,activeStageIndex:null,errorMessage:i.errorMessage||null,runSource:i.source||"cli",cwd:i.cwd,outputBase:i.outputBase,sessionPathAbs:i.sessionPathAbs}))}catch(i){console.warn(`[zibby browser-test run-index] ${i.message}`)}}function Ms({sessionPath:o,sessionId:e,cwd:t,outputBase:r=le}={}){let n=t||process.cwd(),s=r||le,i=e!=null&&String(e).trim()!==""?String(e).trim():null,c=process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true",l=process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim();if(c&&l)return ce(l);let a=o&&String(o).trim();if(a)return ce(a);let u=process.env.ZIBBY_SESSIONS_ROOT&&String(process.env.ZIBBY_SESSIONS_ROOT).trim();return u&&i?ce(z(u,i)):process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim()?ce(String(process.env.ZIBBY_SESSION_PATH).trim()):ce(z(n,s,Tt,i||"invalid"))}function Ls(o){try{let e=o?.currentNode;if(!e||!_t.includes(e))return;let t=o.sessionPath,r=o.sessionId||t&&String(t).split(/[/\\]/).filter(Boolean).pop()||null;if(!r)return;let n=o.cwd||process.cwd(),s=o.outputBase||le,i=_t.indexOf(e),c=o?.specPath!=null?String(o.specPath).trim():"",l=o?.taskDescription!=null?String(o.taskDescription):"",a=null;if(c)try{let d=ce(n,c);a=Et(n,d).split(De).join("/")}catch{a=c.split(De).join("/")}let u=Ms({sessionPath:t,sessionId:r,cwd:n,outputBase:s});rt({v:1,recordKind:"progress",ts:Date.now(),sessionId:r,cwd:n,outputBase:s,sessionPathAbs:u,activeNode:e,activeStageIndex:i,specRel:a,taskDescription:l||null,studioTestCaseId:vt(r)||null,source:process.env.ZIBBY_RUN_SOURCE||"cli"}),nt(u,{sessionId:r,studioTestCaseId:vt(r)||r,status:"running",activeNode:e,activeStageIndex:i,sessionPathAbs:u,cwd:n,outputBase:s,specPath:a||null,task:l||null,taskDescription:l||null,runSource:process.env.ZIBBY_RUN_SOURCE||"cli",pid:typeof process.pid=="number"?process.pid:null})}catch(e){console.warn(`[zibby browser-test run-index progress] ${e.message}`)}}function Or({cwd:o,config:e}={}){let t=o||process.cwd(),r=e?.paths?.output||le;return n=>{Ls({cwd:n?.cwd||t,outputBase:n?.outputBase||r,sessionPath:n?.sessionPath,sessionId:n?.sessionId,currentNode:n?.currentNode,specPath:n?.specPath,taskDescription:n?.taskDescription})}}function Pr(o={}){try{let e=o.cwd||process.cwd(),t=o.config?.paths?.output||o.outputBase||le,r=wr(e,t),n=xr(r),s=vr(n),i=new Set,c=o.errorMessage||"Run stopped (SIGINT/SIGTERM) before a normal summary was written.",l=(d,m)=>{if(!d||!m||i.has(d))return;i.add(d);let p=Ir({cwd:e,outputBase:t,result:{state:{sessionPath:m}},success:!1,specPath:null,status:"interrupted",errorMessage:c});p&&(rt(p),nt(m,{sessionId:d,studioTestCaseId:p.studioTestCaseId||d,status:"interrupted",activeNode:null,activeStageIndex:null,errorMessage:p.errorMessage||null,runSource:p.source||"cli",cwd:e,outputBase:t,sessionPathAbs:m}))};for(let[d,m]of s){if(!Tr(m))continue;let p=m.progress;if(!p)continue;let g=String(d),S=p.sessionPathAbs&&String(p.sessionPathAbs)||z(e,t,Tt,g);l(g,S)}let a=z(e,t,Tt);if(!Ue(a))return;let u;try{u=Ar(a)}catch{return}for(let d of u){let m=z(a,d),p;try{p=Os(m)}catch{continue}if(!p.isDirectory())continue;let g=xt(m);!g||g.status!=="running"||l(String(d),m)}}catch(e){console.warn(`[zibby browser-test run-index interrupt] ${e.message}`)}}function st(o){$r(o)}function At(o){Pr(o)}function Cr(o){return Or(o)}import{spawn as Gs}from"node:child_process";import{mkdirSync as Rr,existsSync as Js,writeFileSync as zs}from"node:fs";import{join as Pt}from"node:path";import{ContextLoader as Ks,WorkflowGraph as Ys,Node as Hs,WorkflowState as Ws,DEFAULT_OUTPUT_BASE as kr,SESSIONS_DIR as Zs,SESSION_INFO_FILE as Xs}from"@zibby/agent-workflow";import{exec as Ds}from"node:child_process";import{promisify as Us}from"node:util";import{existsSync as Bs}from"node:fs";import{join as It}from"node:path";import{homedir as $t}from"node:os";var Nr=Us(Ds);async function Ot(){try{return await Nr("cursor-agent --version"),"cursor-agent"}catch{let e=[It($t(),".local","bin","cursor-agent"),It($t(),".cursor","bin","cursor-agent"),It($t(),".cursor-agent","bin","cursor-agent")];for(let t of e)if(Bs(t))try{return await Nr(`"${t}" --version`),t}catch{}return null}}async function Fs(){return await Ot()!==null}function js(){return`
105
+ `);let s=(await import("chalk")).default;console.log(s.bold("Prompt sent to LLM:")),console.log(s.dim("\u2500".repeat(60)));let i=!1;for(let a of e)if(a.role==="system")console.log(s.dim(`[System] ${a.content||""}`));else{i||(console.log(s.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),i=!0);let c=a.role==="user"?"Human":"AI",l=a.content?.length>200?`${a.content.slice(0,200)}...`:a.content||"";console.log(s.dim(`[${c}] ${l}`))}console.log(s.dim("\u2500".repeat(60)))}};var Er=!1;function Tt(){Er||(De(new ce),De(new re),De(new ne),De(new se),De(new ie),Er=!0)}import{existsSync as Be,readdirSync as Nr,statSync as Ks}from"fs";import{join as K,relative as It,sep as Ue,resolve as le}from"path";import{appendFileSync as Ms,readFileSync as Ls,existsSync as Tr,mkdirSync as Ds}from"node:fs";import{join as nt}from"node:path";import{DEFAULT_OUTPUT_BASE as vr}from"@zibby/agent-workflow";var Ar="run-index.jsonl";function Ir(o,e=vr){let t=nt(o,e);return nt(t,Ar)}function st(o){if(!o||!o.sessionId)return;let e=o.cwd||process.cwd(),t=o.outputBase||vr,r=nt(e,t);Tr(r)||Ds(r,{recursive:!0});let n=nt(r,Ar),s=`${JSON.stringify(o)}
106
+ `;Ms(n,s,"utf8")}function $r(o){if(!o||!Tr(o))return[];let e;try{e=Ls(o,"utf8")}catch{return[]}let t=[];for(let r of e.split(`
107
+ `)){let n=r.trim();if(n)try{t.push(JSON.parse(n))}catch{}}return t}import{existsSync as Us,mkdirSync as Bs,readFileSync as Fs,readdirSync as Jc,statSync as Kc,writeFileSync as js}from"node:fs";import{join as Gs}from"node:path";var zs="zibby-run-state.json";function Or(o){return Gs(o,zs)}function vt(o){if(!o||typeof o!="string")return null;let e=Or(o);if(!Us(e))return null;try{let t=Fs(e,"utf8"),r=JSON.parse(t);return r&&typeof r=="object"?r:null}catch{return null}}function ot(o,e){if(!o||typeof o!="string")return;try{Bs(o,{recursive:!0})}catch{return}let r={...vt(o)||{v:1},...e,v:1,updatedAt:Date.now()};try{js(Or(o),`${JSON.stringify(r)}
108
+ `,"utf8")}catch(n){console.warn(`[zibby run-state] ${n.message}`)}}function Js(o){return o?.recordKind==="progress"}function Pr(o){let e=Number(o)||0;return e<=0?0:e<1e12?e*1e3:e}function Cr(o,e={}){let t=e.maxProgressAgeMs!=null&&Number.isFinite(e.maxProgressAgeMs)?Math.max(0,e.maxProgressAgeMs):21e5,r=typeof e.now=="number"?e.now:Date.now(),{summary:n,progress:s}=o||{};if(!s)return!1;let i=Pr(s.ts);if(t>0&&i>0&&r-i>t)return!1;if(!n)return i>0;let a=Pr(n.ts);return i>a}function Rr(o){let e=new Map;for(let t of o||[]){if(!t?.sessionId)continue;let r=e.get(t.sessionId);r||(r={summary:null,progress:null});let n=Number(t.ts)||0;Js(t)?(!r.progress||n>=(Number(r.progress.ts)||0))&&(r.progress=t):(!r.summary||n>=(Number(r.summary.ts)||0))&&(r.summary=t),e.set(t.sessionId,r)}return e}import{DEFAULT_OUTPUT_BASE as ue,SESSIONS_DIR as $t}from"@zibby/agent-workflow";var At=Object.freeze(["preflight","execute_live","generate_script"]);function Ot(o){let e=process.env.ZIBBY_STUDIO_TEST_CASE_ID;return e!=null&&String(e).trim()!==""?String(e).trim():o!=null?String(o):""}var Ys=[K("generate_script","generated-test.spec.js"),K("generate_script","generated-test.spec.ts"),K("generate_script","playwright.spec.ts"),K("generate_script","test.spec.ts")];function Hs(o){let e=[K(o,"execute_live","videos"),K(o,"execute_live"),o];for(let t of e){if(!Be(t))continue;let r;try{r=Nr(t)}catch{continue}let n=r.find(s=>s.endsWith(".webm"));if(n)return K(t,n)}return null}function Ws(o){let e=[K(o,"execute_live","events.json"),K(o,"events.json")];for(let t of e)if(Be(t))return t;return null}function Zs(o){for(let e of Ys){let t=K(o,e);if(Be(t))return t}return null}function Xs(o){return!o||!Be(o)?{videoPathAbs:null,eventsPathAbs:null,scriptPathAbs:null}:{videoPathAbs:Hs(o),eventsPathAbs:Ws(o),scriptPathAbs:Zs(o)}}function kr(o){let e=o.cwd||process.cwd(),t=o.outputBase||ue,s=((o.result||{}).state||{}).sessionPath;if(!s||typeof s!="string")return null;let i=s.split(/[/\\]/).filter(Boolean).pop();if(!i)return null;let{videoPathAbs:a,eventsPathAbs:c,scriptPathAbs:l}=Xs(s),u=d=>{if(!d)return null;try{return It(e,d).split(Ue).join("/")}catch{return null}},m=null;if(o.specPath)try{let d=le(e,o.specPath);m=It(e,d).split(Ue).join("/")}catch{m=String(o.specPath).split(Ue).join("/")}return{v:1,recordKind:"summary",ts:Date.now(),sessionId:i,status:o.status??(o.success?"completed":"failed"),cwd:e,outputBase:t,sessionPathAbs:s,sessionDirRel:u(s),videoPathAbs:a||null,eventsPathAbs:c||null,scriptPathAbs:l||null,videoRel:u(a),eventsRel:u(c),scriptRel:u(l),specRel:m,source:process.env.ZIBBY_RUN_SOURCE||"cli",studioTestCaseId:Ot(i)||null,errorMessage:o.errorMessage||null}}function Mr({cwd:o,config:e,result:t,success:r,specPath:n,errorMessage:s}){try{let i=kr({cwd:o||process.cwd(),result:t,success:r,outputBase:e?.paths?.output||ue,specPath:n,errorMessage:s});i&&(st(i),i.sessionPathAbs&&ot(i.sessionPathAbs,{sessionId:i.sessionId,studioTestCaseId:i.studioTestCaseId||i.sessionId,status:i.status,activeNode:null,activeStageIndex:null,errorMessage:i.errorMessage||null,runSource:i.source||"cli",cwd:i.cwd,outputBase:i.outputBase,sessionPathAbs:i.sessionPathAbs}))}catch(i){console.warn(`[zibby browser-test run-index] ${i.message}`)}}function qs({sessionPath:o,sessionId:e,cwd:t,outputBase:r=ue}={}){let n=t||process.cwd(),s=r||ue,i=e!=null&&String(e).trim()!==""?String(e).trim():null,a=process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true",c=process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim();if(a&&c)return le(c);let l=o&&String(o).trim();if(l)return le(l);let u=process.env.ZIBBY_SESSIONS_ROOT&&String(process.env.ZIBBY_SESSIONS_ROOT).trim();return u&&i?le(K(u,i)):process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim()?le(String(process.env.ZIBBY_SESSION_PATH).trim()):le(K(n,s,$t,i||"invalid"))}function Vs(o){try{let e=o?.currentNode;if(!e||!At.includes(e))return;let t=o.sessionPath,r=o.sessionId||t&&String(t).split(/[/\\]/).filter(Boolean).pop()||null;if(!r)return;let n=o.cwd||process.cwd(),s=o.outputBase||ue,i=At.indexOf(e),a=o?.specPath!=null?String(o.specPath).trim():"",c=o?.taskDescription!=null?String(o.taskDescription):"",l=null;if(a)try{let m=le(n,a);l=It(n,m).split(Ue).join("/")}catch{l=a.split(Ue).join("/")}let u=qs({sessionPath:t,sessionId:r,cwd:n,outputBase:s});st({v:1,recordKind:"progress",ts:Date.now(),sessionId:r,cwd:n,outputBase:s,sessionPathAbs:u,activeNode:e,activeStageIndex:i,specRel:l,taskDescription:c||null,studioTestCaseId:Ot(r)||null,source:process.env.ZIBBY_RUN_SOURCE||"cli"}),ot(u,{sessionId:r,studioTestCaseId:Ot(r)||r,status:"running",activeNode:e,activeStageIndex:i,sessionPathAbs:u,cwd:n,outputBase:s,specPath:l||null,task:c||null,taskDescription:c||null,runSource:process.env.ZIBBY_RUN_SOURCE||"cli",pid:typeof process.pid=="number"?process.pid:null})}catch(e){console.warn(`[zibby browser-test run-index progress] ${e.message}`)}}function Lr({cwd:o,config:e}={}){let t=o||process.cwd(),r=e?.paths?.output||ue;return n=>{Vs({cwd:n?.cwd||t,outputBase:n?.outputBase||r,sessionPath:n?.sessionPath,sessionId:n?.sessionId,currentNode:n?.currentNode,specPath:n?.specPath,taskDescription:n?.taskDescription})}}function Dr(o={}){try{let e=o.cwd||process.cwd(),t=o.config?.paths?.output||o.outputBase||ue,r=Ir(e,t),n=$r(r),s=Rr(n),i=new Set,a=o.errorMessage||"Run stopped (SIGINT/SIGTERM) before a normal summary was written.",c=(m,d)=>{if(!m||!d||i.has(m))return;i.add(m);let p=kr({cwd:e,outputBase:t,result:{state:{sessionPath:d}},success:!1,specPath:null,status:"interrupted",errorMessage:a});p&&(st(p),ot(d,{sessionId:m,studioTestCaseId:p.studioTestCaseId||m,status:"interrupted",activeNode:null,activeStageIndex:null,errorMessage:p.errorMessage||null,runSource:p.source||"cli",cwd:e,outputBase:t,sessionPathAbs:d}))};for(let[m,d]of s){if(!Cr(d))continue;let p=d.progress;if(!p)continue;let g=String(m),y=p.sessionPathAbs&&String(p.sessionPathAbs)||K(e,t,$t,g);c(g,y)}let l=K(e,t,$t);if(!Be(l))return;let u;try{u=Nr(l)}catch{return}for(let m of u){let d=K(l,m),p;try{p=Ks(d)}catch{continue}if(!p.isDirectory())continue;let g=vt(d);!g||g.status!=="running"||c(String(m),d)}}catch(e){console.warn(`[zibby browser-test run-index interrupt] ${e.message}`)}}function it(o){Mr(o)}function Pt(o){Dr(o)}function Ur(o){return Lr(o)}import{spawn as so}from"node:child_process";import{mkdirSync as Fr,existsSync as oo,writeFileSync as io}from"node:fs";import{join as kt}from"node:path";import{ContextLoader as ao,WorkflowGraph as co,Node as lo,WorkflowState as uo,DEFAULT_OUTPUT_BASE as jr,SESSIONS_DIR as po,SESSION_INFO_FILE as fo}from"@zibby/agent-workflow";import{exec as Qs}from"node:child_process";import{promisify as eo}from"node:util";import{existsSync as to}from"node:fs";import{join as Ct}from"node:path";import{homedir as Rt}from"node:os";var Br=eo(Qs);async function Nt(){try{return await Br("cursor-agent --version"),"cursor-agent"}catch{let e=[Ct(Rt(),".local","bin","cursor-agent"),Ct(Rt(),".cursor","bin","cursor-agent"),Ct(Rt(),".cursor-agent","bin","cursor-agent")];for(let t of e)if(to(t))try{return await Br(`"${t}" --version`),t}catch{}return null}}async function ro(){return await Nt()!==null}function no(){return`
106
109
  \u274C cursor-agent CLI not found!
107
110
 
108
111
  To use the Cursor agent, install it from:
@@ -119,23 +122,23 @@ After installation:
119
122
  2. Or restart your terminal/shell
120
123
 
121
124
  Then retry your command.
122
- `}var we=class o{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 H.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:s}=e,i=typeof r=="function"?r(t):r;console.log(`
125
+ `}var xe=class o{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 W.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:s}=e,i=typeof r=="function"?r(t):r;console.log(`
123
126
  \u{1F4DD} Prompt:
124
127
  ${i}
125
- `);let c=await this.executePrompt(i,t.cwd,3e5,s);console.log(`
128
+ `);let a=await this.executePrompt(i,t.cwd,3e5,s);console.log(`
126
129
  \u{1F4E4} Raw Output:
127
- ${c}
128
- `);let l=null;if(n)try{if(l=o.extractJsonFromStream(c),!l)throw new Error("No valid result JSON found in output");console.log(`
130
+ ${a}
131
+ `);let c=null;if(n)try{if(c=o.extractJsonFromStream(a),!c)throw new Error("No valid result JSON found in output");console.log(`
129
132
  \u2705 Parsed Output:
130
- ${JSON.stringify(l,null,2)}
131
- `)}catch(a){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${a.message}`)}return{success:!0,output:l,raw:c}}async cleanup(){this.adapter&&this.adapter.isConnected()&&await this.adapter.disconnect()}async executePrompt(e,t=process.cwd(),r=3e5,n=null,s=!0){let i=this.agentCommand;if(i==="cursor-agent"){let c=await Ot();c&&(i=c)}return new Promise((c,l)=>{let a="",u=this.buildArgs(e,s);n&&u.push("--model",n);let d={...process.env},m=Gs(i,u,{cwd:t,env:d,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),p=setTimeout(()=>{console.log(`
132
- \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,S=Date.now(),h=setInterval(()=>{if(a.length>g)g=a.length,S=Date.now();else{let w=Date.now()-S;w>1e4&&console.log(`\u23F3 AI agent is thinking... (${Math.floor(w/1e3)}s, ${a.length} bytes so far)`)}},1e4),b=()=>{clearTimeout(p),clearInterval(h),m&&!m.killed&&(m.kill("SIGTERM"),setTimeout(()=>{m.killed||m.kill("SIGKILL")},2e3))},x=()=>{console.log(`
133
+ ${JSON.stringify(c,null,2)}
134
+ `)}catch(l){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${l.message}`)}return{success:!0,output:c,raw:a}}async cleanup(){this.adapter&&this.adapter.isConnected()&&await this.adapter.disconnect()}async executePrompt(e,t=process.cwd(),r=3e5,n=null,s=!0){let i=this.agentCommand;if(i==="cursor-agent"){let a=await Nt();a&&(i=a)}return new Promise((a,c)=>{let l="",u=this.buildArgs(e,s);n&&u.push("--model",n);let m={...process.env},d=so(i,u,{cwd:t,env:m,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),p=setTimeout(()=>{console.log(`
135
+ \u23F1\uFE0F Timeout reached (${r/1e3}s) - killing agent...`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||(console.log("\u26A0\uFE0F Forcing kill (SIGKILL)..."),d.kill("SIGKILL"))},2e3),c(new Error(`Agent timed out after ${r/1e3}s. The agent may be stuck or waiting for user input.`))},r),g=0,y=Date.now(),h=setInterval(()=>{if(l.length>g)g=l.length,y=Date.now();else{let E=Date.now()-y;E>1e4&&console.log(`\u23F3 AI agent is thinking... (${Math.floor(E/1e3)}s, ${l.length} bytes so far)`)}},1e4),S=()=>{clearTimeout(p),clearInterval(h),d&&!d.killed&&(d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},2e3))},_=()=>{console.log(`
133
136
 
134
- \u{1F6D1} Interrupted by user (Ctrl+C)`),b(),l(new Error("Interrupted by user"))};process.on("SIGINT",x);let T=new H;m.stdout.on("data",w=>{let I=w.toString();a+=I;let $=T.processChunk(I);$&&(process.stdout.write($,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),S=Date.now(),g+=$.length)}),m.on("close",w=>{process.off("SIGINT",x),clearTimeout(p),clearInterval(h);let I=T.flush();I&&process.stdout.write(I),a=T.getRawText();let $=T.getResult();w===0?c({raw:a,extracted:$}):l(new Error(`Agent exited with code ${w}`))}),m.on("error",w=>{process.off("SIGINT",x),clearTimeout(p),clearInterval(h),l(new Error(`Failed to spawn agent: ${w.message}`))})})}async runSingleNode(e,t,r){let n=t[e];if(!n)throw new Error(`Unknown node: ${e}. Available nodes: ${Object.keys(t).join(", ")}`);let{cwd:s}=r;if(!s)throw new Error("cwd is required for single node execution");let i=r.sessionPath,c=r.sessionTimestamp,l=r.config||{};if(!i){let h=process.env.CI_JOB_ID||process.env.GITHUB_RUN_ID||process.env.CIRCLE_WORKFLOW_ID||process.env.BUILD_ID||Date.now().toString(),b=l.paths?.sessionPrefix,x=b?`${b}_${h}`:h;c=c||Date.now();let T=l.paths?.output||kr;i=Pt(s,T,Zs,x),Js(i)||Rr(i,{recursive:!0})}let a=l.paths?.output||kr,u=Pt(s,a,Xs);Rr(Pt(s,a),{recursive:!0}),zs(u,JSON.stringify({sessionPath:i,sessionTimestamp:c||i.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
137
+ \u{1F6D1} Interrupted by user (Ctrl+C)`),S(),c(new Error("Interrupted by user"))};process.on("SIGINT",_);let A=new W;d.stdout.on("data",E=>{let v=E.toString();l+=v;let P=A.processChunk(v);P&&(process.stdout.write(P,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),y=Date.now(),g+=P.length)}),d.on("close",E=>{process.off("SIGINT",_),clearTimeout(p),clearInterval(h);let v=A.flush();v&&process.stdout.write(v),l=A.getRawText();let P=A.getResult();E===0?a({raw:l,extracted:P}):c(new Error(`Agent exited with code ${E}`))}),d.on("error",E=>{process.off("SIGINT",_),clearTimeout(p),clearInterval(h),c(new Error(`Failed to spawn agent: ${E.message}`))})})}async runSingleNode(e,t,r){let n=t[e];if(!n)throw new Error(`Unknown node: ${e}. Available nodes: ${Object.keys(t).join(", ")}`);let{cwd:s}=r;if(!s)throw new Error("cwd is required for single node execution");let i=r.sessionPath,a=r.sessionTimestamp,c=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(),S=c.paths?.sessionPrefix,_=S?`${S}_${h}`:h;a=a||Date.now();let A=c.paths?.output||jr;i=kt(s,A,po,_),oo(i)||Fr(i,{recursive:!0})}let l=c.paths?.output||jr,u=kt(s,l,fo);Fr(kt(s,l),{recursive:!0}),io(u,JSON.stringify({sessionPath:i,sessionTimestamp:a||i.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
135
138
  ${"=".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)}
136
- `);let d=await Ks.loadContext(r.specPath||"",s,r.contextConfig||{}),m=new Ws({...r,sessionPath:i,sessionTimestamp:c,context:d}),g=await new Hs(n).execute(this,m);return console.log(`
139
+ `);let m=await ao.loadContext(r.specPath||"",s,r.contextConfig||{}),d=new uo({...r,sessionPath:i,sessionTimestamp:a,context:m}),g=await new lo(n).execute(this,d);return console.log(`
137
140
  ${"=".repeat(80)}`),console.log(`\u2705 Node ${e} completed`),console.log(`${"=".repeat(80)}
138
- `),{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 qs(o,e={}){let t=new we(e);return t.buildGraph=function(){let r=new Ys;return o(r),r},e.onComplete&&(t.onComplete=e.onComplete),t}import{WorkflowGraph as hp,resolveWorkflowSession as yp,generateWorkflowSessionId as Sp,clearInheritedSessionEnvForFreshRun as bp,shouldTrustInheritedSessionEnv as wp,readPinnedSessionPathFromEnv as xp,syncProcessEnvToSession as _p}from"@zibby/agent-workflow";import{writeFileSync as Mr,existsSync as Vs,mkdirSync as Qs}from"node:fs";import{join as Ct}from"node:path";var Nt=class o{static saveTitle(e,t){let r=e.state.sessionPath;if(!r)return;let n=o._findInState(e.state,"title")||o._findInState(e.state,"result");if(!(!n||typeof n!="string"))try{let s=Ct(r,"title.txt");Mr(s,n,"utf-8"),f.info(`Saved title to session: "${n}"`)}catch(s){console.warn("\u26A0\uFE0F Could not save title file:",s.message)}}static _findInState(e,t){for(let[,r]of Object.entries(e))if(r&&typeof r=="object"&&r[t]!==void 0)return r[t]}static async saveExecutionData(e){let t=e.state.sessionPath;if(t)for(let[r,n]of Object.entries(e.state)){if(!n||typeof n!="object")continue;let s=Array.isArray(n.actions)&&n.actions.length>0,i=typeof n.scriptPath=="string"&&n.scriptPath.trim().length>0;if(!(!s&&!i))try{let c=Ct(t,r);Vs(c)||Qs(c,{recursive:!0});let l=Ct(c,"result.json");Mr(l,JSON.stringify(n,null,2),"utf-8"),f.info(`Saved execution data to ${r} folder`),await this.onNodeSaved(c,n)}catch(c){console.warn(`\u26A0\uFE0F Could not save execution data for ${r}:`,c.message)}}}static async onNodeSaved(e,t){}static logResult(e,t){let r=Object.entries(e.state).filter(([,i])=>i&&typeof i=="object"&&i.success!==void 0),n=r.length>0&&r.every(([,i])=>i.success),s=r.some(([,i])=>i.success===!1);if(n)f.info("Workflow completed successfully."),t&&f.info(`Output: ${t}`);else if(s){let i=r.filter(([,c])=>!c.success).map(([c])=>c);f.info(`Workflow completed with failures in: ${i.join(", ")}`),t&&f.info(`Output: ${t}`)}return n}static handle(e,t,r){return this.saveTitle(e,t),this.saveExecutionData(e),this.logResult(e,r)}};import{z as vp}from"zod/v3";import{AgentStrategy as to}from"@zibby/agent-workflow";var Lr=[new ae,new te,new re,new ne,new oe];function Dr(o={}){let{state:e={},preferredAgent:t=null}=o,r=t||e.agentType||process.env.AGENT_TYPE;if(!r)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");f.debug(`Agent selection: requested=${r}`);let n=Lr.find(s=>s.getName()===r);if(!n)throw new Error(`Unknown agent '${r}'. Available: ${Lr.map(s=>s.getName()).join(", ")}`);if(f.debug(`Checking if ${r} can handle this environment...`),!n.canHandle(o)){let i={assistant:"Run `zibby login` to authenticate",claude:"Set ANTHROPIC_API_KEY in .env",cursor:"Install cursor-agent CLI or set CURSOR_API_KEY",codex:"Install codex CLI (npm i -g @openai/codex) and set OPENAI_API_KEY in .env",gemini:"Install gemini CLI (npm i -g @google/gemini-cli) and set GEMINI_API_KEY in .env"}[r]||"Check your environment configuration";throw new Error(`Agent '${r}' is not available. ${i}`)}return f.debug(`Using agent: ${n.getName()}`),n}async function eo(o,e={},t={}){try{await import("@zibby/skills")}catch{}let r=Dr(e),n=e.state?.config||t.config||{},s=n.models||{},i=t.nodeName&&s[t.nodeName]||null,c=s.default||null,l=r.name,a=n.agent?.[l]?.model||null,u=i||c||a||t.model||null,d={...t,model:u,workspace:e.state?.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:n},m=d.skills||[],p=o;if(m.length>0&&!t.skipPromptFragments){let{getSkill:S}=await import("@zibby/agent-workflow"),h=m.map(b=>{let x=S(b)?.promptFragment;return typeof x=="function"?x():x}).filter(Boolean);h.length>0&&(p+=`
141
+ `),{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 mo(o,e={}){let t=new xe(e);return t.buildGraph=function(){let r=new co;return o(r),r},e.onComplete&&(t.onComplete=e.onComplete),t}import{WorkflowGraph as Pp,resolveWorkflowSession as Cp,generateWorkflowSessionId as Rp,clearInheritedSessionEnvForFreshRun as Np,shouldTrustInheritedSessionEnv as kp,readPinnedSessionPathFromEnv as Mp,syncProcessEnvToSession as Lp}from"@zibby/agent-workflow";import{writeFileSync as Gr,existsSync as go,mkdirSync as ho}from"node:fs";import{join as Mt}from"node:path";var Lt=class o{static saveTitle(e,t){let r=e.state.sessionPath;if(!r)return;let n=o._findInState(e.state,"title")||o._findInState(e.state,"result");if(!(!n||typeof n!="string"))try{let s=Mt(r,"title.txt");Gr(s,n,"utf-8"),f.info(`Saved title to session: "${n}"`)}catch(s){console.warn("\u26A0\uFE0F Could not save title file:",s.message)}}static _findInState(e,t){for(let[,r]of Object.entries(e))if(r&&typeof r=="object"&&r[t]!==void 0)return r[t]}static async saveExecutionData(e){let t=e.state.sessionPath;if(t)for(let[r,n]of Object.entries(e.state)){if(!n||typeof n!="object")continue;let s=Array.isArray(n.actions)&&n.actions.length>0,i=typeof n.scriptPath=="string"&&n.scriptPath.trim().length>0;if(!(!s&&!i))try{let a=Mt(t,r);go(a)||ho(a,{recursive:!0});let c=Mt(a,"result.json");Gr(c,JSON.stringify(n,null,2),"utf-8"),f.info(`Saved execution data to ${r} folder`),await this.onNodeSaved(a,n)}catch(a){console.warn(`\u26A0\uFE0F Could not save execution data for ${r}:`,a.message)}}}static async onNodeSaved(e,t){}static logResult(e,t){let r=Object.entries(e.state).filter(([,i])=>i&&typeof i=="object"&&i.success!==void 0),n=r.length>0&&r.every(([,i])=>i.success),s=r.some(([,i])=>i.success===!1);if(n)f.info("Workflow completed successfully."),t&&f.info(`Output: ${t}`);else if(s){let i=r.filter(([,a])=>!a.success).map(([a])=>a);f.info(`Workflow completed with failures in: ${i.join(", ")}`),t&&f.info(`Output: ${t}`)}return n}static handle(e,t,r){return this.saveTitle(e,t),this.saveExecutionData(e),this.logResult(e,r)}};import{z as Bp}from"zod/v3";import{AgentStrategy as So}from"@zibby/agent-workflow";var zr=[new ce,new re,new ne,new se,new ie];function Jr(o={}){let{state:e={},preferredAgent:t=null}=o,r=t||e.agentType||process.env.AGENT_TYPE;if(!r)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");f.debug(`Agent selection: requested=${r}`);let n=zr.find(s=>s.getName()===r);if(!n)throw new Error(`Unknown agent '${r}'. Available: ${zr.map(s=>s.getName()).join(", ")}`);if(f.debug(`Checking if ${r} can handle this environment...`),!n.canHandle(o)){let i={assistant:"Run `zibby login` to authenticate",claude:"Set ANTHROPIC_API_KEY in .env",cursor:"Install cursor-agent CLI or set CURSOR_API_KEY",codex:"Install codex CLI (npm i -g @openai/codex) and set OPENAI_API_KEY in .env",gemini:"Install gemini CLI (npm i -g @google/gemini-cli) and set GEMINI_API_KEY in .env"}[r]||"Check your environment configuration";throw new Error(`Agent '${r}' is not available. ${i}`)}return f.debug(`Using agent: ${n.getName()}`),n}async function yo(o,e={},t={}){try{await import("@zibby/skills")}catch{}let r=Jr(e),n=e.state?.config||t.config||{},s=n.models||{},i=t.nodeName&&s[t.nodeName]||null,a=s.default||null,c=r.name,l=n.agent?.[c]?.model||null,u=i||a||l||t.model||null,m={...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},d=m.skills||[],p=o;if(d.length>0&&!t.skipPromptFragments){let{getSkill:y}=await import("@zibby/agent-workflow"),h=d.map(S=>{let _=y(S)?.promptFragment;return typeof _=="function"?_():_}).filter(Boolean);h.length>0&&(p+=`
139
142
 
140
143
  ${h.join(`
141
144
 
@@ -147,13 +150,13 @@ ${h.join(`
147
150
 
148
151
  ${g}
149
152
  `),f.debug(`Prompt length: ${p.length} chars`),process.env.STAGE!=="prod"&&f.debug(`Full prompt:
150
- ${p}`),r.invoke(p,d)}import{SKILLS as Cp}from"@zibby/agent-workflow";import{registerSkill as Rp,getSkill as kp,hasSkill as Mp,getAllSkills as Lp,listSkillIds as Dp}from"@zibby/agent-workflow";var ro={READ_FILE:"read_file",WRITE_FILE:"write_file",LIST_DIRECTORY:"list_directory",RUN_COMMAND:"run_command",OPEN_URL:"open_url",WAIT:"wait"},no={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"},so={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"},oo={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"},io={GENERATE:"run_generate",TEST:"run_test",STATUS:"run_status",CANCEL:"run_cancel",WAIT:"run_wait",ARTIFACTS:"run_artifacts",LIST_SPECS:"list_specs"},ao={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"},co={STORE:"memory_store",RECALL:"memory_recall",BRIEF:"memory_brief",END_SESSION:"memory_end_session",TASK_LOG:"task_log",TASK_HISTORY:"task_history"},lo={INSTALL:"install_skill",UNINSTALL:"uninstall_skill",LIST_AVAILABLE:"list_available_skills"},dl={...ro,...no,...so,...oo,...io,...ao,...co,...lo};import{existsSync as uo,readFileSync as po}from"node:fs";import{homedir as fo}from"node:os";import{join as mo}from"node:path";var ot=new Map;function go(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let o=mo(fo(),".zibby","config.json");return uo(o)&&JSON.parse(po(o,"utf-8")).sessionToken||null}catch{return null}}function ho(){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://account-api-prod.zibby.app"}async function yo(o){let e=Date.now(),t=ot.get(o);if(t&&t.expiresAt>e)return t.data;let r=go();if(!r)throw new Error("No session token. Run `zibby login` first.");let n=`${ho()}/integrations/token/${o}`,s=await fetch(n,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!s.ok){let l=await s.text().catch(()=>"");throw s.status===404?new Error(`${o} is not connected. Connect it at https://studio.zibby.dev/integrations`):s.status===401||s.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Failed to resolve ${o} token (${s.status}): ${l}`)}let i=await s.json();if(!i||typeof i!="object")throw new Error(`Invalid response from ${o} token endpoint: expected object, got ${typeof i}`);if(o==="jira"){if(!i.token||typeof i.token!="string")throw new Error(`Invalid jira token response: token is ${typeof i.token}, expected string`);if(!i.cloudId)throw new Error("Invalid jira token response: missing cloudId")}else if(o==="github"&&(!i.token||typeof i.token!="string"))throw new Error(`Invalid github token response: token is ${typeof i.token}, expected string`);let c=((i.expiresInSec||3e3)-120)*1e3;return ot.set(o,{data:i,expiresAt:e+c}),i}function So(o){o?ot.delete(o):ot.clear()}import{readdir as bo,access as Ur,copyFile as wo,constants as Br}from"fs/promises";import{join as it,relative as xo}from"node:path";async function _o(o={}){let{testResultsDir:e="test-results",testsDir:t="tests",projectRoot:r=process.cwd(),verbose:n=!0}=o;n&&console.log(`\u{1F3A5} Organizing test videos...
151
- `);let s=it(r,e),i=it(r,t);try{let c=await bo(s),l=0;for(let a of c){if(a.startsWith("."))continue;let u=it(s,a,"video.webm");try{await Ur(u,Br.F_OK)}catch{continue}let d=a.replace(/-chromium$/,"").replace(/-firefox$/,"").replace(/-webkit$/,""),m=await Eo(i,d);if(m){let p=m.replace(/\.spec\.(js|ts)$/,".spec.webm");await wo(u,p),n&&console.log(`\u2705 ${xo(r,p)}`),l++}else n&&console.log(`\u26A0\uFE0F Could not find test file for: ${a}`)}return n&&(console.log(`
152
- \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 Eo(o,e){let t=e.split("-");for(let r=t.length;r>0;r--){let s=t.slice(0,r).join("/");for(let i of["js","ts"]){let c=it(o,`${s}.spec.${i}`);try{return await Ur(c,Br.F_OK),c}catch{}}}return null}var Be=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 Fr(){let o=process.env.ZIBBY_API_KEY;return new Be(o)}import{execSync as To}from"node:child_process";import{existsSync as vo,mkdirSync as Ao}from"node:fs";import{join as Io}from"node:path";async function $o(o={}){let{baseDir:e="/workspace/repos",repos:t=null,depth:r=1,branch:n=null}=o,s=process.env.REPOS;if(!s)throw new Error("REPOS environment variable not set. Are you running in a Zibby workflow container?");let i;try{i=JSON.parse(s)}catch(a){throw new Error(`Failed to parse REPOS env var: ${a.message}`,{cause:a})}if(!Array.isArray(i)||i.length===0)throw new Error("No repositories configured for this project");let c=t?i.filter(a=>t.includes(a.name)):i;if(c.length===0)throw new Error(`No matching repositories found. Available: ${i.map(a=>a.name).join(", ")}`);vo(e)||Ao(e,{recursive:!0});let l={};return await Promise.all(c.map(async a=>{let u=a.provider||"github",d=u==="gitlab"?process.env.GITLAB_TOKEN:process.env.GITHUB_TOKEN;if(!d){console.error(`${u.toUpperCase()}_TOKEN not set, skipping ${a.name}`),l[a.name]=null;return}let m=a.name.replace(/\//g,"-"),p=Io(e,m),g=a.cloneUrl||a.url;if(!g){console.error(`Repository "${a.name}" has no clone URL`),l[a.name]=null;return}let S;u==="gitlab"?S=g.replace(/^https:\/\//,`https://oauth2:${d}@`):S=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(S,p);let b=`git ${h.join(" ")}`;console.log(`Cloning ${a.name} (${u}) to ${p}...`);try{To(b,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),console.log(`Repository ${a.name} cloned successfully`),l[a.name]=p}catch(x){let T=x.message.replace(d,"***").replace(S,g);console.error(`Failed to clone ${a.name}: ${T}`),l[a.name]=null}})),l}import{spawn as jr}from"node:child_process";import{readFileSync as Oo,writeFileSync as Po,existsSync as at}from"node:fs";import{homedir as Gr}from"node:os";import{join as xe}from"node:path";async function Co(){let o=xe(Gr(),".local/share/cursor-agent/versions");if(!at(o))throw new Error(`cursor-agent not found at ${o}. Please install cursor-agent first.`);return console.log(`\u{1F527} Patching cursor-agent for CI/CD...
153
- `),new Promise((e,t)=>{let r=xe(__dirname,"../../scripts/patch-cursor-mcp.py");if(!at(r)){t(new Error("Patch script not found"));return}let n=jr("python3",[r],{stdio:"inherit"});n.on("close",s=>{s===0?e({success:!0}):t(new Error(`Patch failed with code ${s}`))}),n.on("error",s=>{t(s)})})}function No(){let o=xe(Gr(),".local/share/cursor-agent/versions");if(!at(o))return{patched:!1,installed:!1};try{let e=cn("fs").readdirSync(o);if(e.length===0)return{patched:!1,installed:!1};let t=e.sort().reverse()[0],r=xe(o,t,"index.js");return at(r)?{patched:Oo(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 Ro(o){return console.log(`\u{1F511} Getting MCP approval keys...
154
- `),new Promise((e,t)=>{let r=jr("cursor-agent",["mcp","list"],{cwd:o,stdio:"pipe"}),n="";r.stdout.on("data",s=>{n+=s.toString(),process.stdout.write(s)}),r.stderr.on("data",s=>{process.stderr.write(s)}),r.on("close",s=>{if(s===0){let i=ko(n);e({success:!0,keys:i,output:n})}else t(new Error(`Failed to get approval keys (exit code ${s})`))}),r.on("error",s=>{t(s)})})}function ko(o){let e={},t=/🔑 APPROVAL KEY:\s+(\S+)\s+=>\s+(\S+)/g,r;for(;(r=t.exec(o))!==null;)e[r[1]]=r[2];return e}function Mo(o,e){let t=xe(o,".cursor/projects"),r=xe(t,"mcp-approvals.json");Po(r,JSON.stringify(e,null,2)),console.log(`
153
+ ${p}`),r.invoke(p,m)}import{SKILLS as Kp}from"@zibby/agent-workflow";import{registerSkill as Hp,getSkill as Wp,hasSkill as Zp,getAllSkills as Xp,listSkillIds as qp}from"@zibby/agent-workflow";var bo={READ_FILE:"read_file",WRITE_FILE:"write_file",LIST_DIRECTORY:"list_directory",RUN_COMMAND:"run_command",OPEN_URL:"open_url",WAIT:"wait"},wo={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"},xo={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"},_o={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"},Eo={GENERATE:"run_generate",TEST:"run_test",STATUS:"run_status",CANCEL:"run_cancel",WAIT:"run_wait",ARTIFACTS:"run_artifacts",LIST_SPECS:"list_specs"},To={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"},vo={STORE:"memory_store",RECALL:"memory_recall",BRIEF:"memory_brief",END_SESSION:"memory_end_session",TASK_LOG:"task_log",TASK_HISTORY:"task_history"},Ao={INSTALL:"install_skill",UNINSTALL:"uninstall_skill",LIST_AVAILABLE:"list_available_skills"},Cl={...bo,...wo,...xo,..._o,...Eo,...To,...vo,...Ao};import{existsSync as Io,readFileSync as $o}from"node:fs";import{homedir as Oo}from"node:os";import{join as Po}from"node:path";var at=new Map;function Co(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let o=Po(Oo(),".zibby","config.json");return Io(o)&&JSON.parse($o(o,"utf-8")).sessionToken||null}catch{return null}}function Ro(){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://account-api-prod.zibby.app"}async function No(o){let e=Date.now(),t=at.get(o);if(t&&t.expiresAt>e)return t.data;let r=Co();if(!r)throw new Error("No session token. Run `zibby login` first.");let n=`${Ro()}/integrations/token/${o}`,s=await fetch(n,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!s.ok){let c=await s.text().catch(()=>"");throw s.status===404?new Error(`${o} is not connected. Connect it at https://studio.zibby.dev/integrations`):s.status===401||s.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Failed to resolve ${o} token (${s.status}): ${c}`)}let i=await s.json();if(!i||typeof i!="object")throw new Error(`Invalid response from ${o} token endpoint: expected object, got ${typeof i}`);if(o==="jira"){if(!i.token||typeof i.token!="string")throw new Error(`Invalid jira token response: token is ${typeof i.token}, expected string`);if(!i.cloudId)throw new Error("Invalid jira token response: missing cloudId")}else if(o==="github"&&(!i.token||typeof i.token!="string"))throw new Error(`Invalid github token response: token is ${typeof i.token}, expected string`);let a=((i.expiresInSec||3e3)-120)*1e3;return at.set(o,{data:i,expiresAt:e+a}),i}function ko(o){o?at.delete(o):at.clear()}import{readdir as Mo,access as Kr,copyFile as Lo,constants as Yr}from"fs/promises";import{join as ct,relative as Do}from"node:path";async function Uo(o={}){let{testResultsDir:e="test-results",testsDir:t="tests",projectRoot:r=process.cwd(),verbose:n=!0}=o;n&&console.log(`\u{1F3A5} Organizing test videos...
154
+ `);let s=ct(r,e),i=ct(r,t);try{let a=await Mo(s),c=0;for(let l of a){if(l.startsWith("."))continue;let u=ct(s,l,"video.webm");try{await Kr(u,Yr.F_OK)}catch{continue}let m=l.replace(/-chromium$/,"").replace(/-firefox$/,"").replace(/-webkit$/,""),d=await Bo(i,m);if(d){let p=d.replace(/\.spec\.(js|ts)$/,".spec.webm");await Lo(u,p),n&&console.log(`\u2705 ${Do(r,p)}`),c++}else n&&console.log(`\u26A0\uFE0F Could not find test file for: ${l}`)}return n&&(console.log(`
155
+ \u{1F3AC} Organized ${c} video(s)`),console.log(`\u{1F4C2} Videos are now next to their test files in ${t}/`)),{movedCount:c,success:!0}}catch(a){return n&&console.error("\u274C Error organizing videos:",a.message),{movedCount:0,success:!1,error:a.message}}}async function Bo(o,e){let t=e.split("-");for(let r=t.length;r>0;r--){let s=t.slice(0,r).join("/");for(let i of["js","ts"]){let a=ct(o,`${s}.spec.${i}`);try{return await Kr(a,Yr.F_OK),a}catch{}}}return null}var Fe=class{constructor(e,t={}){this.apiKey=e,this.baseUrl=t.baseUrl||process.env.ZIBBY_API_URL||"https://api-prod.zibby.app",this.enabled=!!e}isEnabled(){return this.enabled}};function Hr(){let o=process.env.ZIBBY_API_KEY;return new Fe(o)}import{spawn as Wr}from"node:child_process";import{readFileSync as Fo,writeFileSync as jo,existsSync as lt}from"node:fs";import{homedir as Zr}from"node:os";import{join as _e}from"node:path";async function Go(){let o=_e(Zr(),".local/share/cursor-agent/versions");if(!lt(o))throw new Error(`cursor-agent not found at ${o}. Please install cursor-agent first.`);return console.log(`\u{1F527} Patching cursor-agent for CI/CD...
156
+ `),new Promise((e,t)=>{let r=_e(__dirname,"../../scripts/patch-cursor-mcp.py");if(!lt(r)){t(new Error("Patch script not found"));return}let n=Wr("python3",[r],{stdio:"inherit"});n.on("close",s=>{s===0?e({success:!0}):t(new Error(`Patch failed with code ${s}`))}),n.on("error",s=>{t(s)})})}function zo(){let o=_e(Zr(),".local/share/cursor-agent/versions");if(!lt(o))return{patched:!1,installed:!1};try{let e=gn("fs").readdirSync(o);if(e.length===0)return{patched:!1,installed:!1};let t=e.sort().reverse()[0],r=_e(o,t,"index.js");return lt(r)?{patched:Fo(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 Jo(o){return console.log(`\u{1F511} Getting MCP approval keys...
157
+ `),new Promise((e,t)=>{let r=Wr("cursor-agent",["mcp","list"],{cwd:o,stdio:"pipe"}),n="";r.stdout.on("data",s=>{n+=s.toString(),process.stdout.write(s)}),r.stderr.on("data",s=>{process.stderr.write(s)}),r.on("close",s=>{if(s===0){let i=Ko(n);e({success:!0,keys:i,output:n})}else t(new Error(`Failed to get approval keys (exit code ${s})`))}),r.on("error",s=>{t(s)})})}function Ko(o){let e={},t=/🔑 APPROVAL KEY:\s+(\S+)\s+=>\s+(\S+)/g,r;for(;(r=t.exec(o))!==null;)e[r[1]]=r[2];return e}function Yo(o,e){let t=_e(o,".cursor/projects"),r=_e(t,"mcp-approvals.json");jo(r,JSON.stringify(e,null,2)),console.log(`
155
158
  \u2705 Saved approval keys to: ${r}
156
- `)}import{DEFAULT_OUTPUT_BASE as Yp,SESSIONS_DIR as Hp,SESSION_INFO_FILE as Wp,RESULT_FILE as Zp,RAW_OUTPUT_FILE as Xp,EVENTS_FILE as qp,CI_ENV_VARS as Vp}from"@zibby/agent-workflow";var Jr=`
159
+ `)}import{DEFAULT_OUTPUT_BASE as af,SESSIONS_DIR as cf,SESSION_INFO_FILE as lf,RESULT_FILE as uf,RAW_OUTPUT_FILE as pf,EVENTS_FILE as ff,CI_ENV_VARS as df}from"@zibby/agent-workflow";var Xr=`
157
160
  const style = document.createElement('style');
158
161
  style.textContent = \`
159
162
  @keyframes zibby-ripple {
@@ -214,7 +217,7 @@ ${p}`),r.invoke(p,d)}import{SKILLS as Cp}from"@zibby/agent-workflow";import{regi
214
217
  setTimeout(() => ripple.remove(), 600);
215
218
  }
216
219
  };
217
- `;function Lo(o){return o.addInitScript(Jr)}function Do(){return`
220
+ `;function Ho(o){return o.addInitScript(Xr)}function Wo(){return`
218
221
  async function showRipple(page, locator) {
219
222
  const box = await locator.boundingBox().catch(() => null);
220
223
  if (box) {
@@ -227,97 +230,97 @@ async function showRipple(page, locator) {
227
230
  }, { x, y }).catch(() => {});
228
231
  }
229
232
  }
230
- `.trim()}var Fe=class{static generate(e,t="element"){let{selectors:r}=e;if(!r||typeof r!="object")return this.generateFallbackSelector(e,t);let n=[];return r.role&&n.push(this.generateRoleSelector(r.role)),r.attributes&&n.push(this.generateAttributeSelector(r.attributes)),r.partialMatch&&n.push(this.generatePartialMatchSelector(r.partialMatch)),r.structure&&n.push(this.generateStructuralSelector(r.structure)),n.length===0?this.generateFallbackSelector(e,t):n.length===1?`const ${t} = ${n[0]};`:`const ${t} = ${n[0]}
233
+ `.trim()}var je=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]}
231
234
  ${n.slice(1).map(i=>` .or(${i})`).join(`
232
- `)};`}static generateRoleSelector(e){let{role:t,name:r}=e;if(!t)return null;if(r){let n=this.escapeRegex(r);return`page.getByRole('${t}', { name: /${n}/i })`}return`page.getByRole('${t}')`}static generateAttributeSelector(e){if(!e||typeof e!="object")return null;let t=Object.entries(e).filter(([n,s])=>s!=null).map(([n,s])=>n==="placeholder"||n==="aria-label"?n==="placeholder"?`page.getByPlaceholder('${this.escapeString(s)}')`:`page.locator('[${n}="${this.escapeString(s)}"]')`:`[${n}="${this.escapeString(s)}"]`);if(e.placeholder)return`page.getByPlaceholder('${this.escapeString(e.placeholder)}')`;let r=t.filter(n=>!n.startsWith("page.")).join("");return r?`page.locator('${r}')`:null}static generatePartialMatchSelector(e){if(!e||typeof e!="object")return null;let t=Object.entries(e).filter(([r,n])=>n!==void 0).map(([r,n])=>{let s=n.replace(/^\^/,"");return`[${r}^="${this.escapeString(s)}"]`});return t.length>0?`page.locator('${t.join("")}')`:null}static generateStructuralSelector(e){return!e||typeof e!="string"?null:`page.locator('${this.escapeString(e)}')`}static generateFallbackSelector(e,t){let{description:r,type:n}=e;if(n==="fill"||n==="type")return`const ${t} = page.locator('input').first();`;if(n==="click"){if(r.toLowerCase().includes("button"))return`const ${t} = page.locator('button').first();`;if(r.toLowerCase().includes("link"))return`const ${t} = page.locator('a').first();`}return`const ${t} = page.locator('body');`}static escapeString(e){return typeof e!="string"?String(e):e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/"/g,'\\"')}static escapeRegex(e){return typeof e!="string"?String(e):e.replace(/[.*+?^${}()[\]\\]/g,"\\$&")}static generateActionCode(e,t){let{type:r,value:n,description:s,selectors:i}=e,c=`element${t}`,l=this.generate(e,c),a=this.generateActionMethod(r,c,n);return`${l}
233
- ${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:s,passed:i}=e;return r.toLowerCase().includes("url")?`await expect(page).toHaveURL(/${this.escapeRegex(s)}/);`:r.toLowerCase().includes("visible")?"await expect(page.locator('body')).toBeVisible();":`// ${r}`}};import je 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:s}=await import("fs"),i=JSON.parse(s(t,"utf-8")),c=i.filter(p=>["navigate","type","fill","click","select_option"].includes(p.type)),l=c.filter(p=>p.type!=="navigate");console.log(`[TestPostProcessor] Found ${c.length} action events, ${r.length} trace actions`);let a=`import { ZibbyRuntime } from '@zibby/core';
235
+ `)};`}static generateRoleSelector(e){let{role:t,name:r}=e;if(!t)return null;if(r){let n=this.escapeRegex(r);return`page.getByRole('${t}', { name: /${n}/i })`}return`page.getByRole('${t}')`}static generateAttributeSelector(e){if(!e||typeof e!="object")return null;let t=Object.entries(e).filter(([n,s])=>s!=null).map(([n,s])=>n==="placeholder"||n==="aria-label"?n==="placeholder"?`page.getByPlaceholder('${this.escapeString(s)}')`:`page.locator('[${n}="${this.escapeString(s)}"]')`:`[${n}="${this.escapeString(s)}"]`);if(e.placeholder)return`page.getByPlaceholder('${this.escapeString(e.placeholder)}')`;let r=t.filter(n=>!n.startsWith("page.")).join("");return r?`page.locator('${r}')`:null}static generatePartialMatchSelector(e){if(!e||typeof e!="object")return null;let t=Object.entries(e).filter(([r,n])=>n!==void 0).map(([r,n])=>{let s=n.replace(/^\^/,"");return`[${r}^="${this.escapeString(s)}"]`});return t.length>0?`page.locator('${t.join("")}')`:null}static generateStructuralSelector(e){return!e||typeof e!="string"?null:`page.locator('${this.escapeString(e)}')`}static generateFallbackSelector(e,t){let{description:r,type:n}=e;if(n==="fill"||n==="type")return`const ${t} = page.locator('input').first();`;if(n==="click"){if(r.toLowerCase().includes("button"))return`const ${t} = page.locator('button').first();`;if(r.toLowerCase().includes("link"))return`const ${t} = page.locator('a').first();`}return`const ${t} = page.locator('body');`}static escapeString(e){return typeof e!="string"?String(e):e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/"/g,'\\"')}static escapeRegex(e){return typeof e!="string"?String(e):e.replace(/[.*+?^${}()[\]\\]/g,"\\$&")}static generateActionCode(e,t){let{type:r,value:n,description:s,selectors:i}=e,a=`element${t}`,c=this.generate(e,a),l=this.generateActionMethod(r,a,n);return`${c}
236
+ ${l}`}static generateActionMethod(e,t,r){switch(e){case"fill":case"type":return`await ${t}.fill('${this.escapeString(r||"")}');`;case"click":return`await ${t}.click();`;case"navigate":return`await page.goto('${this.escapeString(r||"")}');`;case"wait":return`await page.waitForTimeout(${parseInt(r)||2e3});`;default:return`// Unknown action type: ${e}`}}static generateAssertionCode(e,t){let{description:r,expected:n,actual:s,passed:i}=e;return r.toLowerCase().includes("url")?`await expect(page).toHaveURL(/${this.escapeRegex(s)}/);`:r.toLowerCase().includes("visible")?"await expect(page.locator('body')).toBeVisible();":`// ${r}`}};import Ge from"fs/promises";var Dt=class{static async generateFromEvents(e,t,r,n){try{console.log("[TestPostProcessor] \u{1F3AF} Generating test from events.json (100% accurate)");let{readFileSync:s}=await import("fs"),i=JSON.parse(s(t,"utf-8")),a=i.filter(p=>["navigate","type","fill","click","select_option"].includes(p.type)),c=a.filter(p=>p.type!=="navigate");console.log(`[TestPostProcessor] Found ${a.length} action events, ${r.length} trace actions`);let l=`import { ZibbyRuntime } from '@zibby/core';
234
237
  import { test, expect } from '@playwright/test';
235
238
 
236
- `;a+=`test('${n}', async ({ page }) => {
237
- `,a+=` const timestamp = Date.now();
238
-
239
- `;let u=0;for(let p of c)if(p.type==="navigate")a+=` await page.goto('${p.data.params.url}');
240
-
241
- `;else if(p.type==="type"||p.type==="fill"){let{element:g,text:S}=p.data.params,h=r[u]?.strategies||[];a+=` await ZibbyRuntime.step(page, ${JSON.stringify({name:g,action:"fill",value:S,strategies:h},null,2)});
242
-
243
- `,u++}else if(p.type==="click"){let{element:g}=p.data.params,S=r[u]?.strategies||[];a+=` await ZibbyRuntime.step(page, ${JSON.stringify({name:g,action:"click",value:"",strategies:S},null,2)});
244
-
245
- `,u++}else if(p.type==="select_option"){let{element:g,values:S}=p.data.params,h=r[u]?.strategies||[],b={name:g,action:"selectOption",value:Array.isArray(S)?S[0]:S,strategies:h};a+=` await ZibbyRuntime.step(page, ${JSON.stringify(b,null,2)});
246
-
247
- `,u++}a+=`});
248
- `;let{dirname:d}=await import("path"),{mkdirSync:m}=await import("fs");return m(d(e),{recursive:!0}),await je.writeFile(e,a,"utf-8"),console.log(`[TestPostProcessor] \u2705 Generated test with ${i.filter(p=>["type","fill","click","select_option"].includes(p.type)).length} actions`),!0}catch(s){return console.warn("[TestPostProcessor] Failed to generate from events:",s.message),!1}}static async enhanceSelectorsWithTrace(e,t,r){try{console.log("[TestPostProcessor] \u{1F6E1}\uFE0F Applying Zibby Safe Action Wrappers...");let n=await je.readFile(e,"utf-8");n.includes("ZibbyRuntime")||(n=`import { ZibbyRuntime } from '@zibby/core';
249
- ${n}`);for(let s=0;s<t.length;s++){let i=t[s],c=`element${s}`,l=new RegExp(`const ${c}\\b\\s*=\\s*page\\.[^;]+;(\\s*await ${c}\\.waitFor\\([^)]*\\);)?\\s*await ${c}\\.(click|fill|type|selectOption|pressSequentially)\\(([^)]*)\\);`,"s"),a=n.match(l);if(!a)continue;let u={name:i.name||`Action ${s}`,action:i.method==="type"?"fill":i.method,value:a[3].trim().replace(/^['"]|['"]$/g,""),strategies:i.strategies||[]},d=`await ZibbyRuntime.step(page, ${JSON.stringify(u,null,2)});`;n=n.replace(a[0],d)}return await je.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 je.readFile(e,"utf-8"),s=this.buildSelectorMap(r);return n=this.replaceSimpleSelectors(n,s),await je.writeFile(e,n,"utf-8"),!0}catch(r){return console.warn("Failed to enhance selectors:",r),!1}}static buildSelectorMap(e){let t=new Map;for(let r=0;r<e.length;r++){let n=e[r];if(!n.selectors||n.type==="navigate")continue;let s=`element${r}`,c=Fe.generate(n,s).match(/= (.+);/s);if(c){let l=c[1].trim(),a=`${n.type}:${this.normalizeDescription(n.description)}`;t.set(a,l),n.selectors.role&&t.set(`role:${n.selectors.role.name}`,l),n.selectors.attributes?.placeholder&&t.set(`placeholder:${n.selectors.attributes.placeholder}`,l)}}return t}static replaceSimpleSelectors(e,t){let r=e,n=[/await page\.(getByRole|getByPlaceholder|getByText|getByLabel|locator)\([^)]+\)\.(fill|click|type)\([^)]*\)/g];for(let s of n)r=r.replace(s,i=>{for(let[c,l]of t.entries())if(i.includes(c.split(":")[1])){let a=i.match(/\.(fill|click|type)\(([^)]*)\)/);if(a){let[,u,d]=a,m="element";return`const ${m} = ${l};
250
- await ${m}.${u}(${d})`}}return i});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as Uo,existsSync as zr,readdirSync as Kr}from"node:fs";import{join as kt}from"node:path";import{execSync as Bo}from"node:child_process";import{tmpdir as Fo}from"node:os";var Ge=class{static async parseTraceZip(e){let t;if(e.endsWith(".zip")&&zr(e)){let r=kt(Fo(),`trace-${Date.now()}`);Bo(`unzip -q "${e}" -d "${r}"`,{stdio:"pipe"});let s=Kr(r).find(i=>i.endsWith(".trace"));if(!s)throw new Error("No .trace file found in zip");t=kt(r,s)}else if(zr(e)){let n=Kr(e).find(s=>s.endsWith(".trace"));if(!n)throw new Error("No .trace file found");t=kt(e,n)}else throw new Error(`Trace not found at ${e}`);try{let n=Uo(t,"utf-8").trim().split(`
251
- `),s=[],i=new Map,c=new Map;for(let l of n)try{let a=JSON.parse(l);if(a.type==="snapshot"&&a.snapshot&&a.snapshot.accessibility){let u=new Map;for(let d of a.snapshot.accessibility)d.ref&&u.set(d.ref,d);i.set(a.snapshotName,u)}if(a.type==="frame-snapshot"&&a.snapshot){let u=Buffer.from(a.snapshot.html||"","base64").toString("utf-8");u&&u.length>100&&c.set(a.pageId||"default",u)}}catch{}for(let l of n)try{let a=JSON.parse(l);if(a.type==="before"&&a.params&&a.params.selector){let u=a.method;if(["click","fill","type","selectOption"].includes(u)){let d=a.params.selector,m=a.params.text||a.params.value||"",p=[],g=null,S=null,h=null,b=d.match(/aria-ref=([a-z0-9]+)/i);if(b&&a.snapshotName){let E=b[1],R=i.get(a.snapshotName);if(R&&R.has(E)){let M=R.get(E);g=M.name||null,S=M.role||null,h=M.label||null,console.log(`[TraceParser] \u2705 Found ACTUAL element data: text="${g}", role="${S}"`)}}let x=d.match(/internal:text="([^"]+)"/i),T=d.match(/internal:label="([^"]+)"/i),w=d.match(/internal:placeholder="([^"]+)"/i),I=d.match(/internal:role=([^ ]+)/i),$=d.match(/internal:describe="([^"]+)"/i),C=d.match(/name="([^"]+)"/i);if(x){p.push({type:"text",text:x[1]});let E=x[1].split(" ");E.length>1&&(p.push({type:"text",text:E[0],fuzzy:!0}),p.push({type:"text",text:E[E.length-1],fuzzy:!0}))}if(T&&p.push({type:"label",label:T[1]}),w&&p.push({type:"placeholder",placeholder:w[1]}),g){p.unshift({type:"text",text:g,source:"accessibility-tree"});let E=g.split(" ");E.length>1&&p.push({type:"text",text:E[0],fuzzy:!0,source:"accessibility-tree"})}if(S||I){let E=S||I[1],R=g||(C?C[1]:x?x[1]:null);p.unshift({type:"role",role:E,name:R,source:g?"accessibility-tree":"selector"})}if(h&&p.unshift({type:"label",label:h,source:"accessibility-tree"}),$){let E=$[1],R=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],M=null,N=E;for(let U of R)if(E.toLowerCase().endsWith(` ${U}`)){M=U.replace(" ",""),N=E.substring(0,E.length-U.length-1);break}if(M){p.push({type:"role",role:M,name:N});let U=N.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:U}),p.push({type:"text",text:N});let O=N.split(" ");O.length>1&&(p.push({type:"text",text:O[0],fuzzy:!0}),p.push({type:"text",text:O.slice(0,2).join(" "),fuzzy:!0}))}else{let U=E.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:U}),p.push({type:"text",text:E})}}let v=this.extractDOMStrategies(d,c,x?.[1]||$?.[1],a.pageId);p.push(...v);let A=this.extractStructuralContext(d);(A.parent||A.sibling)&&p.forEach(E=>{["role","text","label","testid"].includes(E.type)&&(A.parent&&(E.parent=A.parent),A.sibling&&(E.sibling=A.sibling))}),p.push({type:"css",value:d});let D=g||x?x[1]:$?$[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${s.length}`;s.push({method:u,name:D,action:u==="type"?"fill":u,value:m,strategies:p,timestamp:a.startTime,actualText:g,actualRole:S,actualAriaLabel:h})}}}catch{}return s}catch(r){throw new Error(`Failed to parse trace: ${r.message}`,{cause:r})}}static extractDOMStrategies(e,t,r,n){let s=[];if(!t||t.size===0||!r)return s;try{let i=t.get(n);if(!i)return s;let c=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),a=i.match(l);a&&s.push({type:"testid",value:a[1],priority:"high"});let u=new RegExp(`class=["']([^"']+)["'][^>]*>[^<]*${c}`,"gi"),d=i.matchAll(u);for(let g of d){let S=g[1].split(/\s+/).filter(h=>h&&!h.match(/^(css|jss|makeStyles|MuiBox|MuiStack)-\w+/)&&h.length>2);S.length>0&&(s.push({type:"class",value:S.join("."),priority:"medium"}),S.length===1&&s.push({type:"class",value:S[0],priority:"medium"}))}let m=new RegExp(`id=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),p=i.match(m);p&&!p[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&s.push({type:"id",value:p[1],priority:"high"})}catch(i){console.warn(`[TraceParser] DOM extraction failed: ${i.message}`)}return s}static extractStructuralContext(e){let t={parent:null,sibling:null},r=e.split(">>").map(i=>i.trim());if(r.length>1){let c=r[r.length-2].replace(/internal:text="[^"]+"\s*/gi,"").replace(/internal:role=\S+\s*/gi,"").replace(/internal:label="[^"]+"\s*/gi,"").trim();c&&(c.match(/^(form|section|nav|header|aside|main|article)\b/)||c.includes("[")||c.match(/[#.]\w/))&&(t.parent=c)}let s=r[r.length-1].match(/([^+~]+)\s*[+~]\s*(.+)/);return s&&(t.sibling=s[1].trim()),t}};var Mt=class{static async step(e,t){let{name:r,action:n,value:s,strategies:i,options:c={timeout:1e4},enrichedData:l}=t;console.log(`[Zibby] \u26A1 Executing step: ${r}`),await this.waitForPageStability(e,c.timeout);let a=await this.findBestMatch(e,i,r);if(!a)throw new Error(`[Zibby] \u274C Failed to find "${r}" using ${i.length} strategies`);l?.position&&await this.verifyPosition(a,l.position),await this.performActionWithRetry(e,a,n,s,3),console.log(`[Zibby] \u2728 Step "${r}" completed.`)}static async waitForPageStability(e,t=1e4){try{await e.waitForLoadState("networkidle",{timeout:3e3}).catch(()=>{}),await e.evaluate(()=>new Promise(r=>{let n,s=new MutationObserver(()=>{clearTimeout(n),n=setTimeout(()=>{s.disconnect(),r()},500)});s.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),n=setTimeout(()=>{s.disconnect(),r()},500)})).catch(()=>{})}catch{}}static async verifyPosition(e,t){try{let r=await e.boundingBox();if(!r)return;let n=Math.abs(r.x-t.x),s=Math.abs(r.y-t.y);(n>50||s>50)&&(console.log(`[Zibby] \u26A0\uFE0F Element moved: expected (${t.x}, ${t.y}), got (${r.x}, ${r.y})`),await new Promise(i=>setTimeout(i,500)))}catch{}}static async performActionWithRetry(e,t,r,n,s=3){for(let i=1;i<=s;i++)try{r==="click"?await t.click():r==="fill"?await t.fill(n||""):r==="type"?await t.pressSequentially(n||""):r==="selectOption"&&await t.selectOption(n||"");return}catch(c){if(i===s)throw c;console.log(`[Zibby] \u26A0\uFE0F Action failed (attempt ${i}/${s}), retrying...`),await new Promise(l=>setTimeout(l,1e3*i))}}static async findBestMatch(e,t,r){let s=Date.now(),i=t.map(async(a,u)=>{try{let m=await this.getLocator(e,a).all();return m.length===0?[]:(await Promise.all(m.map(async(g,S)=>{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:S}}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 Lt=class{static async beforeEach(e){await this.injectStableIds(e),e.on("load",async()=>{await this.injectStableIds(e)})}static async afterNavigation(e){await e.waitForLoadState("domcontentloaded").catch(()=>{}),await this.injectStableIds(e)}static async clickWithRetry(e,t,r={}){let n=r.timeout||1e4,s=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let c=e.locator(s);if(await c.count()>0)try{await c.click({timeout:2e3});return}catch(l){if(l.message.includes("intercepts pointer")){await c.click({force:!0});return}}await e.waitForTimeout(200)}throw new Error(`Element ${s} not found after ${n}ms`)}static async fillWithRetry(e,t,r,n=1e4){let s=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let c=e.locator(s);if(await c.count()>0){await c.fill(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${s} not found after ${n}ms`)}static async selectWithRetry(e,t,r,n=1e4){let s=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let c=e.locator(s);if(await c.count()>0){await c.selectOption(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${s} not found after ${n}ms`)}static async injectStableIds(e){try{await e.evaluate(()=>{function t(l){if(l.getAttribute("aria-label"))return l.getAttribute("aria-label").trim();let a=l.getAttribute("aria-labelledby");if(a){let m=document.getElementById(a);if(m)return m.textContent.trim()}if(l.id){let m=document.querySelector(`label[for="${l.id}"]`);if(m)return m.textContent.trim()}let u=l.closest("label");if(u){let m=u.cloneNode(!0);m.querySelectorAll("input, select, textarea").forEach(g=>g.remove());let p=m.textContent.trim();if(p)return p}if(l.placeholder)return l.placeholder;let d=l.tagName.toLowerCase();return d==="button"||d==="a"||l.getAttribute("role")==="button"?(l.textContent||"").trim().slice(0,50):l.title?l.title:d==="input"&&(l.type==="submit"||l.type==="button")&&l.value||""}function r(l){let a=[],u=l.closest("form");if(u)if(u.id)a.push(`form#${u.id}`);else if(u.name)a.push(`form[name=${u.name}]`);else if(u.action)try{let S=new URL(u.action,window.location.origin).pathname;a.push(`form[action=${S}]`)}catch{a.push(`form[action=${u.getAttribute("action")}]`)}else{let S=document.querySelectorAll("form"),h=Array.from(S).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 S=d.tagName.toLowerCase(),h=d.getAttribute("role");a.push(h||S)}let m=l.closest('section, article, [role="region"]');if(m){let S=m.querySelector("h1, h2, h3, h4, h5, h6");S&&a.push(`section:${S.textContent.trim().slice(0,30)}`)}let p=l.closest("fieldset");if(p){let S=p.querySelector("legend");S&&a.push(`fieldset:${S.textContent.trim()}`)}let g=l.closest('dialog, [role="dialog"], [role="alertdialog"]');if(g){let S=g.querySelector('[role="heading"], h1, h2, h3');S?a.push(`dialog:${S.textContent.trim().slice(0,30)}`):a.push("dialog")}return a.join("/")}function n(l){let a=l.tagName.toLowerCase(),u=l.id||"",d=l.name||"",m=l.type||"",p=l.getAttribute("role")||"",g="";if(l.href)try{g=new URL(l.href,window.location.origin).pathname.slice(0,50)}catch{g=l.getAttribute("href")?.slice(0,50)||""}let S=t(l).slice(0,50).replace(/\s+/g," "),h=r(l),b=[a,u,d,m,p,g,S,h].join("|"),x=5381;for(let T=0;T<b.length;T++)x=(x<<5)+x^b.charCodeAt(T);return`zibby-${(x>>>0).toString(36)}`}let s=["button","a","input","select","textarea","label[for]",'[role="button"]','[role="link"]','[role="textbox"]','[role="checkbox"]','[role="radio"]','[role="combobox"]','[role="menuitem"]','[role="tab"]','[role="option"]','[role="switch"]','[role="slider"]',"[onclick]","[data-action]"].join(", "),i=new Map,c=0;document.querySelectorAll(s).forEach(l=>{let a=window.getComputedStyle(l);if(a.display==="none"||a.visibility==="hidden")return;let u=n(l),d=u,m=i.get(d)||0;m>0&&(u=`${d}-${m}`),i.set(d,m+1),l.setAttribute("data-zibby-id",u),c++}),console.log(`[Zibby] Injected ${c} stable IDs`)})}catch{}}};var jo=8,Go=1,Jo=64;function zo(o){if(!o||typeof o!="object")return 8;let e=o.parallel;if(!e||typeof e!="object")return 8;let t=e.maxConcurrentRuns??e.maxConcurrent,r=Number(t);if(!Number.isFinite(r))return 8;let n=Math.floor(r);return n<1?8:Math.min(64,n)}import{readFileSync as Yo,writeFileSync as Hr,existsSync as Ho}from"node:fs";import{join as Wr}from"node:path";var G=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 Ko}from"node:fs";import{join as Yr}from"node:path";var ue=class extends G{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=Yr(e,"traces"),r=Yr(e,"trace.zip");if(Ko(r))try{this.traceData=await Ge.parseTraceZip(r),console.log(`[TraceTextEnricher] \u2705 Loaded trace with ${this.traceData.length} actions`)}catch(n){console.log(`[TraceTextEnricher] \u26A0\uFE0F Failed to parse trace: ${n.message}`)}}async enrich(e,t){let r=e.data?.params?.ref,n=e.id;if(r===void 0&&n===void 0||(!this.traceData&&t.sessionPath&&await this.loadTrace(t.sessionPath),!this.traceData))return null;let s=this.traceData[n];if(!s)return console.log(`[TraceTextEnricher] \u26A0\uFE0F No trace action for event ${n}`),null;let i=s.actualText||this._extractTextFromSelector(s.selector),c=s.actualRole,l=s.actualAriaLabel;return i||c||l?(console.log(`[TraceTextEnricher] \u2705 Event ${n}: text="${i}", role="${c}", label="${l}"`),{traceActualText:i,traceActualRole:c,traceActualAriaLabel:l,traceSelector:s.selector,traceStrategies:s.strategies}):null}_extractTextFromSelector(e){if(!e)return null;let t=e.match(/internal:label="([^"]+)"/);if(t)return t[1];let r=e.match(/internal:text="([^"]+)"/);if(r)return r[1];let n=e.match(/getByText\(['"]([^'"]+)['"]\)/);if(n)return n[1];let s=e.match(/name:\s*['"]([^'"]+)['"]/);return s?s[1]:null}};async function Wo(o){let e=Wr(o,"events.json"),t=Wr(o,"events-enriched.json");if(!Ho(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(Yo(e,"utf-8")),n=new ue,s=0,i=0;for(let c of r)try{let l=await n.enrich(c,{sessionPath:o});l&&(c.enrichedData={...c.enrichedData||{},...l},s++)}catch(l){console.log(`[PostProcess] Failed to enrich event ${c.id}: ${l.message}`),i++}return s>0&&(Hr(t,JSON.stringify(r,null,2)),Hr(e,JSON.stringify(r,null,2)),console.log(`[PostProcess] \u2705 Enriched ${s} events (${i} failed)`)),{enriched:s,failed:i}}catch(r){return console.log(`[PostProcess] \u274C Failed to post-process events: ${r.message}`),{enriched:0,failed:0}}}import{spawn as Zo}from"node:child_process";import{existsSync as Xo}from"node:fs";import{dirname as qo,resolve as Zr,relative as Vo}from"node:path";var ct=new Map,Je=8,Xr={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 ${Je} attempts per session.`,inputSchema:{type:"object",properties:{scriptPath:{type:"string",description:"Path to the Playwright test file (e.g., tests/login.spec.js)"}},required:["scriptPath"]},async execute({scriptPath:o},e){let r=`${e?.sessionId||"default"}:${o}`,n=(ct.get(r)||0)+1;if(ct.set(r,n),n>Je)return{success:!1,executionCount:n,maxReached:!0,error:`Maximum ${Je} executions reached. Stop retrying and return your best result.`};let s=e?.projectRoot||process.cwd(),i=Zr(s,o),c=Vo(s,i);return c.startsWith("..")||Zr(i)!==i&&c.includes("..")?{success:!1,executionCount:n,error:"Path traversal detected: scriptPath must be within the project root."}:Xo(i)?new Promise(l=>{let a=qo(i),u=Zo("npx",["playwright","test",i,"--reporter=line"],{cwd:s,env:{...process.env,FORCE_COLOR:"0"}}),d="",m="";u.stdout.on("data",g=>{d+=g.toString()}),u.stderr.on("data",g=>{m+=g.toString()});let p=setTimeout(()=>{u.kill("SIGTERM"),l({success:!1,executionCount:n,error:"Test timed out after 60 seconds",stdout:d.slice(-2e3),stderr:m.slice(-1e3)})},6e4);u.on("close",g=>{clearTimeout(p);let h=`${d}
252
- ${m}`.split(`
253
- `),b="",x=null;for(let T=0;T<h.length;T++){let w=h[T];if(w.includes("Error:")||w.includes("error:")||w.includes("\u2718")){b+=`${w}
254
- `;for(let I=T+1;I<Math.min(T+5,h.length);I++)b+=`${h[I]}
255
- `}if(w.includes("at ")&&w.includes(".spec.")){let I=w.match(/:(\d+):\d+/);I&&(x=parseInt(I[1]))}}l(g===0?{success:!0,executionCount:n,message:"All tests passed!",output:d.slice(-500)}:{success:!1,executionCount:n,remainingAttempts:Je-n,error:b.slice(0,1500)||"Test failed (see output)",failedAtLine:x,stdout:d.slice(-1500),stderr:m.slice(-500),hint:n<Je?"Fix the error and run again.":"Last attempt - make your best fix."})}),u.on("error",g=>{clearTimeout(p),l({success:!1,executionCount:n,error:`Failed to run test: ${g.message}`})})}):{success:!1,executionCount:n,error:`Test file not found: ${i}. Make sure you wrote the file first using the write tool.`}},resetCount(o){for(let e of ct.keys())e.startsWith(`${o}:`)&&ct.delete(e)}};function Qo(o){Xr.resetCount(o)}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 qr,writeFileSync as ei}from"node:fs";var _e=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(qr(t,"utf-8")).some(s=>s.data?.params?.element)?(console.log("[MCPRefStrategy] \u2705 MCP element descriptions available"),!0):(console.log("[MCPRefStrategy] \u274C No MCP element descriptions found in events"),!1)}catch(r){return console.log("[MCPRefStrategy] \u274C Failed to read events:",r.message),!1}}getName(){return"MCP Reference Replay (Exact 1:1)"}getPriority(){return 200}async generate(e){let{testFilePath:t,sessionPath:r,state:n}=e,s=`${r}/execute_live/events.json`,i=n?.title||"Generated Test";console.log("[MCPRefStrategy] \u{1F3AF} Generating test using MCP element descriptions (1:1 replay)"),console.log(`[MCPRefStrategy] events: ${s}`),console.log(`[MCPRefStrategy] output: ${t}`);let l=JSON.parse(qr(s,"utf-8")).filter(u=>["navigate","type","fill","click","select_option"].includes(u.type)),a=`import { test, expect } from '@playwright/test';
256
- `;a+=`import { ZibbyRuntime } from '@zibby/core';
257
-
258
- `,a+=`test('${i}', async ({ page }) => {
259
- `,a+=` const timestamp = Date.now();
260
-
261
- `;for(let u of l){let d=u.data?.params?.element||"element",m=u.data?.params?.ref,p=u.enrichedData?.traceActualText,g=u.enrichedData?.traceActualRole,S=u.enrichedData?.traceActualAriaLabel,h=u.enrichedData?.actualText,b=p||h,x=g||u.enrichedData?.actualRole,T=b||d,w=b||this._extractName(d),I=x||this._extractRole(d),$=p?" [accessibility-tree]":h?" [live]":" [AI]";if(u.type==="navigate")a+=` await page.goto('${u.data.params.url}');
262
-
263
- `;else if(u.type==="click")a+=` // ${d}${b?` (actual: "${b}")${$}`:""}
264
- `,a+=` await ZibbyRuntime.step(page, {
265
- `,a+=` name: '${this._escapeString(d)}',
266
- `,a+=` action: 'click',
267
- `,a+=` strategies: [
268
- `,a+=` { type: 'role', role: '${I}', name: '${this._escapeString(w)}' },
269
- `,a+=` { type: 'text', text: '${this._escapeString(w)}' }
270
- `,a+=` ]
271
- `,a+=` });
272
-
273
- `;else if(u.type==="fill"||u.type==="type"){let C=u.data.params.text;a+=` // ${d}${b?` (actual: "${b}")${$}`:""}
274
- `,a+=` await ZibbyRuntime.step(page, {
275
- `,a+=` name: '${this._escapeString(d)}',
276
- `,a+=` action: 'fill',
277
- `,a+=` value: '${this._escapeString(C)}',
278
- `,a+=` strategies: [
279
- `,a+=` { type: 'role', role: '${I}', name: '${this._escapeString(w)}' },
280
- `,a+=` { type: 'attributes', placeholder: '${this._escapeString(w)}' }
281
- `,a+=` ]
282
- `,a+=` });
283
-
284
- `}else if(u.type==="select_option"){let C=u.data.params.values,v=Array.isArray(C)?C[0]:C;a+=` // ${d}${b?` (actual: "${b}")${$}`:""}
285
- `,a+=` await ZibbyRuntime.step(page, {
286
- `,a+=` name: '${this._escapeString(d)}',
287
- `,a+=` action: 'select',
288
- `,a+=` value: '${this._escapeString(v)}',
289
- `,a+=` strategies: [
290
- `,a+=` { type: 'role', role: 'combobox', name: '${this._escapeString(w)}' }
291
- `,a+=` ]
292
- `,a+=` });
293
-
294
- `}}return a+=`});
295
- `,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 Vr,writeFileSync as ti}from"node:fs";var Ee=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(Vr(t,"utf-8")).some(s=>s.stableId||s.data?.stableId)?(console.log("[StableIdStrategy] \u2705 Stable IDs available"),!0):(console.log("[StableIdStrategy] \u274C No stable IDs found in events"),!1)}catch(r){return console.log("[StableIdStrategy] \u274C Failed to read events:",r.message),!1}}getName(){return"Stable ID Injection (Experimental)"}getPriority(){return 300}async generate(e){let{testFilePath:t,sessionPath:r,state:n}=e,s=`${r}/execute_live/events.json`,i=n?.title||"Generated Test";console.log("[StableIdStrategy] \u{1F3AF} Generating test using stable IDs"),console.log(`[StableIdStrategy] events: ${s}`),console.log(`[StableIdStrategy] output: ${t}`);let l=JSON.parse(Vr(s,"utf-8")).filter(m=>["navigate","type","fill","click","select_option","select"].includes(m.type)),a=`import { test, expect } from '@playwright/test';
296
- `;a+=`import { StableIdRuntime } from '@zibby/core';
297
-
298
- `,a+=`test('${i}', async ({ page }) => {
299
- `;let u=!1,d=null;for(let m=0;m<l.length;m++){let p=l[m],g=p.stableId||p.data?.stableId,S=p.data?.element||p.data?.params?.element||"element";if(p.type==="click"&&g&&g===d){console.log(`[StableIdStrategy] Skipping duplicate click on ${g}`);continue}if(p.type==="navigate"){let h=p.data?.url||p.data?.params?.url;h&&!u&&(a+=` await page.goto('${h}');
300
- `,a+=` await StableIdRuntime.injectStableIds(page);
301
-
302
- `)}else if(p.type==="click")if(u=!0,d=g,g)a+=` await StableIdRuntime.clickWithRetry(page, '${g}');
303
- `;else{let h=this._generateSemanticSelector(S);a+=` await ${h}.click();
304
- `,a+=` await StableIdRuntime.afterNavigation(page);
305
- `}else if(p.type==="fill"||p.type==="type"){u=!1;let h=p.data?.text||p.data?.params?.text||"";g?a+=` await StableIdRuntime.fillWithRetry(page, '${g}', '${this._escapeString(h)}');
306
- `:a+=` await page.getByPlaceholder('${this._escapeString(S)}').fill('${this._escapeString(h)}');
307
- `}else if(p.type==="select_option"||p.type==="select"){u=!1;let h=p.data?.values||p.data?.params?.values,b=Array.isArray(h)?h[0]:h||"";g?a+=` await StableIdRuntime.selectWithRetry(page, '${g}', '${this._escapeString(b)}');
308
- `:a+=` await page.locator('select').selectOption('${this._escapeString(b)}');
309
- `}}return a+=`});
310
- `,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 Dt=class{constructor(){this.strategies=[new Ee,new _e],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(`
239
+ `;l+=`test('${n}', async ({ page }) => {
240
+ `,l+=` const timestamp = Date.now();
241
+
242
+ `;let u=0;for(let p of a)if(p.type==="navigate")l+=` await page.goto('${p.data.params.url}');
243
+
244
+ `;else if(p.type==="type"||p.type==="fill"){let{element:g,text:y}=p.data.params,h=r[u]?.strategies||[];l+=` await ZibbyRuntime.step(page, ${JSON.stringify({name:g,action:"fill",value:y,strategies:h},null,2)});
245
+
246
+ `,u++}else if(p.type==="click"){let{element:g}=p.data.params,y=r[u]?.strategies||[];l+=` await ZibbyRuntime.step(page, ${JSON.stringify({name:g,action:"click",value:"",strategies:y},null,2)});
247
+
248
+ `,u++}else if(p.type==="select_option"){let{element:g,values:y}=p.data.params,h=r[u]?.strategies||[],S={name:g,action:"selectOption",value:Array.isArray(y)?y[0]:y,strategies:h};l+=` await ZibbyRuntime.step(page, ${JSON.stringify(S,null,2)});
249
+
250
+ `,u++}l+=`});
251
+ `;let{dirname:m}=await import("path"),{mkdirSync:d}=await import("fs");return d(m(e),{recursive:!0}),await Ge.writeFile(e,l,"utf-8"),console.log(`[TestPostProcessor] \u2705 Generated test with ${i.filter(p=>["type","fill","click","select_option"].includes(p.type)).length} actions`),!0}catch(s){return console.warn("[TestPostProcessor] Failed to generate from events:",s.message),!1}}static async enhanceSelectorsWithTrace(e,t,r){try{console.log("[TestPostProcessor] \u{1F6E1}\uFE0F Applying Zibby Safe Action Wrappers...");let n=await Ge.readFile(e,"utf-8");n.includes("ZibbyRuntime")||(n=`import { ZibbyRuntime } from '@zibby/core';
252
+ ${n}`);for(let s=0;s<t.length;s++){let i=t[s],a=`element${s}`,c=new RegExp(`const ${a}\\b\\s*=\\s*page\\.[^;]+;(\\s*await ${a}\\.waitFor\\([^)]*\\);)?\\s*await ${a}\\.(click|fill|type|selectOption|pressSequentially)\\(([^)]*)\\);`,"s"),l=n.match(c);if(!l)continue;let u={name:i.name||`Action ${s}`,action:i.method==="type"?"fill":i.method,value:l[3].trim().replace(/^['"]|['"]$/g,""),strategies:i.strategies||[]},m=`await ZibbyRuntime.step(page, ${JSON.stringify(u,null,2)});`;n=n.replace(l[0],m)}return await Ge.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 Ge.readFile(e,"utf-8"),s=this.buildSelectorMap(r);return n=this.replaceSimpleSelectors(n,s),await Ge.writeFile(e,n,"utf-8"),!0}catch(r){return console.warn("Failed to enhance selectors:",r),!1}}static buildSelectorMap(e){let t=new Map;for(let r=0;r<e.length;r++){let n=e[r];if(!n.selectors||n.type==="navigate")continue;let s=`element${r}`,a=je.generate(n,s).match(/= (.+);/s);if(a){let c=a[1].trim(),l=`${n.type}:${this.normalizeDescription(n.description)}`;t.set(l,c),n.selectors.role&&t.set(`role:${n.selectors.role.name}`,c),n.selectors.attributes?.placeholder&&t.set(`placeholder:${n.selectors.attributes.placeholder}`,c)}}return t}static replaceSimpleSelectors(e,t){let r=e,n=[/await page\.(getByRole|getByPlaceholder|getByText|getByLabel|locator)\([^)]+\)\.(fill|click|type)\([^)]*\)/g];for(let s of n)r=r.replace(s,i=>{for(let[a,c]of t.entries())if(i.includes(a.split(":")[1])){let l=i.match(/\.(fill|click|type)\(([^)]*)\)/);if(l){let[,u,m]=l,d="element";return`const ${d} = ${c};
253
+ await ${d}.${u}(${m})`}}return i});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as Zo,existsSync as qr,readdirSync as Vr}from"node:fs";import{join as Ut}from"node:path";import{execSync as Xo}from"node:child_process";import{tmpdir as qo}from"node:os";var ze=class{static async parseTraceZip(e){let t;if(e.endsWith(".zip")&&qr(e)){let r=Ut(qo(),`trace-${Date.now()}`);Xo(`unzip -q "${e}" -d "${r}"`,{stdio:"pipe"});let s=Vr(r).find(i=>i.endsWith(".trace"));if(!s)throw new Error("No .trace file found in zip");t=Ut(r,s)}else if(qr(e)){let n=Vr(e).find(s=>s.endsWith(".trace"));if(!n)throw new Error("No .trace file found");t=Ut(e,n)}else throw new Error(`Trace not found at ${e}`);try{let n=Zo(t,"utf-8").trim().split(`
254
+ `),s=[],i=new Map,a=new Map;for(let c of n)try{let l=JSON.parse(c);if(l.type==="snapshot"&&l.snapshot&&l.snapshot.accessibility){let u=new Map;for(let m of l.snapshot.accessibility)m.ref&&u.set(m.ref,m);i.set(l.snapshotName,u)}if(l.type==="frame-snapshot"&&l.snapshot){let u=Buffer.from(l.snapshot.html||"","base64").toString("utf-8");u&&u.length>100&&a.set(l.pageId||"default",u)}}catch{}for(let c of n)try{let l=JSON.parse(c);if(l.type==="before"&&l.params&&l.params.selector){let u=l.method;if(["click","fill","type","selectOption"].includes(u)){let m=l.params.selector,d=l.params.text||l.params.value||"",p=[],g=null,y=null,h=null,S=m.match(/aria-ref=([a-z0-9]+)/i);if(S&&l.snapshotName){let x=S[1],N=i.get(l.snapshotName);if(N&&N.has(x)){let k=N.get(x);g=k.name||null,y=k.role||null,h=k.label||null,console.log(`[TraceParser] \u2705 Found ACTUAL element data: text="${g}", role="${y}"`)}}let _=m.match(/internal:text="([^"]+)"/i),A=m.match(/internal:label="([^"]+)"/i),E=m.match(/internal:placeholder="([^"]+)"/i),v=m.match(/internal:role=([^ ]+)/i),P=m.match(/internal:describe="([^"]+)"/i),M=m.match(/name="([^"]+)"/i);if(_){p.push({type:"text",text:_[1]});let x=_[1].split(" ");x.length>1&&(p.push({type:"text",text:x[0],fuzzy:!0}),p.push({type:"text",text:x[x.length-1],fuzzy:!0}))}if(A&&p.push({type:"label",label:A[1]}),E&&p.push({type:"placeholder",placeholder:E[1]}),g){p.unshift({type:"text",text:g,source:"accessibility-tree"});let x=g.split(" ");x.length>1&&p.push({type:"text",text:x[0],fuzzy:!0,source:"accessibility-tree"})}if(y||v){let x=y||v[1],N=g||(M?M[1]:_?_[1]:null);p.unshift({type:"role",role:x,name:N,source:g?"accessibility-tree":"selector"})}if(h&&p.unshift({type:"label",label:h,source:"accessibility-tree"}),P){let x=P[1],N=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],k=null,R=x;for(let L of N)if(x.toLowerCase().endsWith(` ${L}`)){k=L.replace(" ",""),R=x.substring(0,x.length-L.length-1);break}if(k){p.push({type:"role",role:k,name:R});let L=R.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:L}),p.push({type:"text",text:R});let F=R.split(" ");F.length>1&&(p.push({type:"text",text:F[0],fuzzy:!0}),p.push({type:"text",text:F.slice(0,2).join(" "),fuzzy:!0}))}else{let L=x.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:L}),p.push({type:"text",text:x})}}let T=this.extractDOMStrategies(m,a,_?.[1]||P?.[1],l.pageId);p.push(...T);let C=this.extractStructuralContext(m);(C.parent||C.sibling)&&p.forEach(x=>{["role","text","label","testid"].includes(x.type)&&(C.parent&&(x.parent=C.parent),C.sibling&&(x.sibling=C.sibling))}),p.push({type:"css",value:m});let U=g||_?_[1]:P?P[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${s.length}`;s.push({method:u,name:U,action:u==="type"?"fill":u,value:d,strategies:p,timestamp:l.startTime,actualText:g,actualRole:y,actualAriaLabel:h})}}}catch{}return s}catch(r){throw new Error(`Failed to parse trace: ${r.message}`,{cause:r})}}static extractDOMStrategies(e,t,r,n){let s=[];if(!t||t.size===0||!r)return s;try{let i=t.get(n);if(!i)return s;let a=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${a}`,"i"),l=i.match(c);l&&s.push({type:"testid",value:l[1],priority:"high"});let u=new RegExp(`class=["']([^"']+)["'][^>]*>[^<]*${a}`,"gi"),m=i.matchAll(u);for(let g of m){let y=g[1].split(/\s+/).filter(h=>h&&!h.match(/^(css|jss|makeStyles|MuiBox|MuiStack)-\w+/)&&h.length>2);y.length>0&&(s.push({type:"class",value:y.join("."),priority:"medium"}),y.length===1&&s.push({type:"class",value:y[0],priority:"medium"}))}let d=new RegExp(`id=["']([^"']+)["'][^>]*>[^<]*${a}`,"i"),p=i.match(d);p&&!p[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&s.push({type:"id",value:p[1],priority:"high"})}catch(i){console.warn(`[TraceParser] DOM extraction failed: ${i.message}`)}return s}static extractStructuralContext(e){let t={parent:null,sibling:null},r=e.split(">>").map(i=>i.trim());if(r.length>1){let a=r[r.length-2].replace(/internal:text="[^"]+"\s*/gi,"").replace(/internal:role=\S+\s*/gi,"").replace(/internal:label="[^"]+"\s*/gi,"").trim();a&&(a.match(/^(form|section|nav|header|aside|main|article)\b/)||a.includes("[")||a.match(/[#.]\w/))&&(t.parent=a)}let s=r[r.length-1].match(/([^+~]+)\s*[+~]\s*(.+)/);return s&&(t.sibling=s[1].trim()),t}};var Bt=class{static async step(e,t){let{name:r,action:n,value:s,strategies:i,options:a={timeout:1e4},enrichedData:c}=t;console.log(`[Zibby] \u26A1 Executing step: ${r}`),await this.waitForPageStability(e,a.timeout);let l=await this.findBestMatch(e,i,r);if(!l)throw new Error(`[Zibby] \u274C Failed to find "${r}" using ${i.length} strategies`);c?.position&&await this.verifyPosition(l,c.position),await this.performActionWithRetry(e,l,n,s,3),console.log(`[Zibby] \u2728 Step "${r}" completed.`)}static async waitForPageStability(e,t=1e4){try{await e.waitForLoadState("networkidle",{timeout:3e3}).catch(()=>{}),await e.evaluate(()=>new Promise(r=>{let n,s=new MutationObserver(()=>{clearTimeout(n),n=setTimeout(()=>{s.disconnect(),r()},500)});s.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),n=setTimeout(()=>{s.disconnect(),r()},500)})).catch(()=>{})}catch{}}static async verifyPosition(e,t){try{let r=await e.boundingBox();if(!r)return;let n=Math.abs(r.x-t.x),s=Math.abs(r.y-t.y);(n>50||s>50)&&(console.log(`[Zibby] \u26A0\uFE0F Element moved: expected (${t.x}, ${t.y}), got (${r.x}, ${r.y})`),await new Promise(i=>setTimeout(i,500)))}catch{}}static async performActionWithRetry(e,t,r,n,s=3){for(let i=1;i<=s;i++)try{r==="click"?await t.click():r==="fill"?await t.fill(n||""):r==="type"?await t.pressSequentially(n||""):r==="selectOption"&&await t.selectOption(n||"");return}catch(a){if(i===s)throw a;console.log(`[Zibby] \u26A0\uFE0F Action failed (attempt ${i}/${s}), retrying...`),await new Promise(c=>setTimeout(c,1e3*i))}}static async findBestMatch(e,t,r){let s=Date.now(),i=t.map(async(l,u)=>{try{let d=await this.getLocator(e,l).all();return d.length===0?[]:(await Promise.all(d.map(async(g,y)=>{try{if(!await g.isVisible({timeout:100}))return null;let S=await this.scoreCandidate(g,l,e);return{element:g,strategy:l,score:S,strategyIdx:u,elIdx:y}}catch{return null}}))).filter(g=>g!==null)}catch{return[]}}),a=(await Promise.all(i)).flat();if(a.length===0)return console.log(`[Zibby] \u274C No visible candidates found for "${r}"`),null;a.sort((l,u)=>u.score-l.score);let c=a[0];return console.log(`[Zibby] \u2705 Found element using ${c.strategy.type} (score: ${c.score.toFixed(2)}, ${a.length} candidates)`),c.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((c,l)=>c.matches(l),t.parent)&&(n+=30)}catch{}if(t.sibling)try{await e.evaluate((a,c)=>a.parentElement?.querySelector(c)!==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(a=>{let c=0,l=a;for(;l;)l.tagName==="IFRAME"&&c++,l=l.parentElement;return c});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 Ft=class{static async beforeEach(e){await this.injectStableIds(e),e.on("load",async()=>{await this.injectStableIds(e)})}static async afterNavigation(e){await e.waitForLoadState("domcontentloaded").catch(()=>{}),await this.injectStableIds(e)}static async clickWithRetry(e,t,r={}){let n=r.timeout||1e4,s=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let a=e.locator(s);if(await a.count()>0)try{await a.click({timeout:2e3});return}catch(c){if(c.message.includes("intercepts pointer")){await a.click({force:!0});return}}await e.waitForTimeout(200)}throw new Error(`Element ${s} not found after ${n}ms`)}static async fillWithRetry(e,t,r,n=1e4){let s=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let a=e.locator(s);if(await a.count()>0){await a.fill(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${s} not found after ${n}ms`)}static async selectWithRetry(e,t,r,n=1e4){let s=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let a=e.locator(s);if(await a.count()>0){await a.selectOption(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${s} not found after ${n}ms`)}static async injectStableIds(e){try{await e.evaluate(()=>{function t(c){if(c.getAttribute("aria-label"))return c.getAttribute("aria-label").trim();let l=c.getAttribute("aria-labelledby");if(l){let d=document.getElementById(l);if(d)return d.textContent.trim()}if(c.id){let d=document.querySelector(`label[for="${c.id}"]`);if(d)return d.textContent.trim()}let u=c.closest("label");if(u){let d=u.cloneNode(!0);d.querySelectorAll("input, select, textarea").forEach(g=>g.remove());let p=d.textContent.trim();if(p)return p}if(c.placeholder)return c.placeholder;let m=c.tagName.toLowerCase();return m==="button"||m==="a"||c.getAttribute("role")==="button"?(c.textContent||"").trim().slice(0,50):c.title?c.title:m==="input"&&(c.type==="submit"||c.type==="button")&&c.value||""}function r(c){let l=[],u=c.closest("form");if(u)if(u.id)l.push(`form#${u.id}`);else if(u.name)l.push(`form[name=${u.name}]`);else if(u.action)try{let y=new URL(u.action,window.location.origin).pathname;l.push(`form[action=${y}]`)}catch{l.push(`form[action=${u.getAttribute("action")}]`)}else{let y=document.querySelectorAll("form"),h=Array.from(y).indexOf(u);l.push(`form:nth(${h})`)}let m=c.closest('header, nav, main, footer, aside, [role="banner"], [role="navigation"], [role="main"], [role="contentinfo"]');if(m){let y=m.tagName.toLowerCase(),h=m.getAttribute("role");l.push(h||y)}let d=c.closest('section, article, [role="region"]');if(d){let y=d.querySelector("h1, h2, h3, h4, h5, h6");y&&l.push(`section:${y.textContent.trim().slice(0,30)}`)}let p=c.closest("fieldset");if(p){let y=p.querySelector("legend");y&&l.push(`fieldset:${y.textContent.trim()}`)}let g=c.closest('dialog, [role="dialog"], [role="alertdialog"]');if(g){let y=g.querySelector('[role="heading"], h1, h2, h3');y?l.push(`dialog:${y.textContent.trim().slice(0,30)}`):l.push("dialog")}return l.join("/")}function n(c){let l=c.tagName.toLowerCase(),u=c.id||"",m=c.name||"",d=c.type||"",p=c.getAttribute("role")||"",g="";if(c.href)try{g=new URL(c.href,window.location.origin).pathname.slice(0,50)}catch{g=c.getAttribute("href")?.slice(0,50)||""}let y=t(c).slice(0,50).replace(/\s+/g," "),h=r(c),S=[l,u,m,d,p,g,y,h].join("|"),_=5381;for(let A=0;A<S.length;A++)_=(_<<5)+_^S.charCodeAt(A);return`zibby-${(_>>>0).toString(36)}`}let s=["button","a","input","select","textarea","label[for]",'[role="button"]','[role="link"]','[role="textbox"]','[role="checkbox"]','[role="radio"]','[role="combobox"]','[role="menuitem"]','[role="tab"]','[role="option"]','[role="switch"]','[role="slider"]',"[onclick]","[data-action]"].join(", "),i=new Map,a=0;document.querySelectorAll(s).forEach(c=>{let l=window.getComputedStyle(c);if(l.display==="none"||l.visibility==="hidden")return;let u=n(c),m=u,d=i.get(m)||0;d>0&&(u=`${m}-${d}`),i.set(m,d+1),c.setAttribute("data-zibby-id",u),a++}),console.log(`[Zibby] Injected ${a} stable IDs`)})}catch{}}};var Vo=8,Qo=1,ei=64;function ti(o){if(!o||typeof o!="object")return 8;let e=o.parallel;if(!e||typeof e!="object")return 8;let t=e.maxConcurrentRuns??e.maxConcurrent,r=Number(t);if(!Number.isFinite(r))return 8;let n=Math.floor(r);return n<1?8:Math.min(64,n)}import{readFileSync as ni,writeFileSync as en,existsSync as si}from"node:fs";import{join as tn}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 ri}from"node:fs";import{join as Qr}from"node:path";var pe=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=Qr(e,"traces"),r=Qr(e,"trace.zip");if(ri(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 s=this.traceData[n];if(!s)return console.log(`[TraceTextEnricher] \u26A0\uFE0F No trace action for event ${n}`),null;let i=s.actualText||this._extractTextFromSelector(s.selector),a=s.actualRole,c=s.actualAriaLabel;return i||a||c?(console.log(`[TraceTextEnricher] \u2705 Event ${n}: text="${i}", role="${a}", label="${c}"`),{traceActualText:i,traceActualRole:a,traceActualAriaLabel:c,traceSelector:s.selector,traceStrategies:s.strategies}):null}_extractTextFromSelector(e){if(!e)return null;let t=e.match(/internal:label="([^"]+)"/);if(t)return t[1];let r=e.match(/internal:text="([^"]+)"/);if(r)return r[1];let n=e.match(/getByText\(['"]([^'"]+)['"]\)/);if(n)return n[1];let s=e.match(/name:\s*['"]([^'"]+)['"]/);return s?s[1]:null}};async function oi(o){let e=tn(o,"events.json"),t=tn(o,"events-enriched.json");if(!si(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(ni(e,"utf-8")),n=new pe,s=0,i=0;for(let a of r)try{let c=await n.enrich(a,{sessionPath:o});c&&(a.enrichedData={...a.enrichedData||{},...c},s++)}catch(c){console.log(`[PostProcess] Failed to enrich event ${a.id}: ${c.message}`),i++}return s>0&&(en(t,JSON.stringify(r,null,2)),en(e,JSON.stringify(r,null,2)),console.log(`[PostProcess] \u2705 Enriched ${s} events (${i} failed)`)),{enriched:s,failed:i}}catch(r){return console.log(`[PostProcess] \u274C Failed to post-process events: ${r.message}`),{enriched:0,failed:0}}}import{spawn as ii}from"node:child_process";import{existsSync as ai}from"node:fs";import{dirname as ci,resolve as rn,relative as li}from"node:path";var ut=new Map,Je=8,nn={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 ${Je} attempts per session.`,inputSchema:{type:"object",properties:{scriptPath:{type:"string",description:"Path to the Playwright test file (e.g., tests/login.spec.js)"}},required:["scriptPath"]},async execute({scriptPath:o},e){let r=`${e?.sessionId||"default"}:${o}`,n=(ut.get(r)||0)+1;if(ut.set(r,n),n>Je)return{success:!1,executionCount:n,maxReached:!0,error:`Maximum ${Je} executions reached. Stop retrying and return your best result.`};let s=e?.projectRoot||process.cwd(),i=rn(s,o),a=li(s,i);return a.startsWith("..")||rn(i)!==i&&a.includes("..")?{success:!1,executionCount:n,error:"Path traversal detected: scriptPath must be within the project root."}:ai(i)?new Promise(c=>{let l=ci(i),u=ii("npx",["playwright","test",i,"--reporter=line"],{cwd:s,env:{...process.env,FORCE_COLOR:"0"}}),m="",d="";u.stdout.on("data",g=>{m+=g.toString()}),u.stderr.on("data",g=>{d+=g.toString()});let p=setTimeout(()=>{u.kill("SIGTERM"),c({success:!1,executionCount:n,error:"Test timed out after 60 seconds",stdout:m.slice(-2e3),stderr:d.slice(-1e3)})},6e4);u.on("close",g=>{clearTimeout(p);let h=`${m}
255
+ ${d}`.split(`
256
+ `),S="",_=null;for(let A=0;A<h.length;A++){let E=h[A];if(E.includes("Error:")||E.includes("error:")||E.includes("\u2718")){S+=`${E}
257
+ `;for(let v=A+1;v<Math.min(A+5,h.length);v++)S+=`${h[v]}
258
+ `}if(E.includes("at ")&&E.includes(".spec.")){let v=E.match(/:(\d+):\d+/);v&&(_=parseInt(v[1]))}}c(g===0?{success:!0,executionCount:n,message:"All tests passed!",output:m.slice(-500)}:{success:!1,executionCount:n,remainingAttempts:Je-n,error:S.slice(0,1500)||"Test failed (see output)",failedAtLine:_,stdout:m.slice(-1500),stderr:d.slice(-500),hint:n<Je?"Fix the error and run again.":"Last attempt - make your best fix."})}),u.on("error",g=>{clearTimeout(p),c({success:!1,executionCount:n,error:`Failed to run test: ${g.message}`})})}):{success:!1,executionCount:n,error:`Test file not found: ${i}. Make sure you wrote the file first using the write tool.`}},resetCount(o){for(let e of ut.keys())e.startsWith(`${o}:`)&&ut.delete(e)}};function ui(o){nn.resetCount(o)}var V=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 sn,writeFileSync as pi}from"node:fs";var Ee=class extends V{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(sn(t,"utf-8")).some(s=>s.data?.params?.element)?(console.log("[MCPRefStrategy] \u2705 MCP element descriptions available"),!0):(console.log("[MCPRefStrategy] \u274C No MCP element descriptions found in events"),!1)}catch(r){return console.log("[MCPRefStrategy] \u274C Failed to read events:",r.message),!1}}getName(){return"MCP Reference Replay (Exact 1:1)"}getPriority(){return 200}async generate(e){let{testFilePath:t,sessionPath:r,state:n}=e,s=`${r}/execute_live/events.json`,i=n?.title||"Generated Test";console.log("[MCPRefStrategy] \u{1F3AF} Generating test using MCP element descriptions (1:1 replay)"),console.log(`[MCPRefStrategy] events: ${s}`),console.log(`[MCPRefStrategy] output: ${t}`);let c=JSON.parse(sn(s,"utf-8")).filter(u=>["navigate","type","fill","click","select_option"].includes(u.type)),l=`import { test, expect } from '@playwright/test';
259
+ `;l+=`import { ZibbyRuntime } from '@zibby/core';
260
+
261
+ `,l+=`test('${i}', async ({ page }) => {
262
+ `,l+=` const timestamp = Date.now();
263
+
264
+ `;for(let u of c){let m=u.data?.params?.element||"element",d=u.data?.params?.ref,p=u.enrichedData?.traceActualText,g=u.enrichedData?.traceActualRole,y=u.enrichedData?.traceActualAriaLabel,h=u.enrichedData?.actualText,S=p||h,_=g||u.enrichedData?.actualRole,A=S||m,E=S||this._extractName(m),v=_||this._extractRole(m),P=p?" [accessibility-tree]":h?" [live]":" [AI]";if(u.type==="navigate")l+=` await page.goto('${u.data.params.url}');
265
+
266
+ `;else if(u.type==="click")l+=` // ${m}${S?` (actual: "${S}")${P}`:""}
267
+ `,l+=` await ZibbyRuntime.step(page, {
268
+ `,l+=` name: '${this._escapeString(m)}',
269
+ `,l+=` action: 'click',
270
+ `,l+=` strategies: [
271
+ `,l+=` { type: 'role', role: '${v}', name: '${this._escapeString(E)}' },
272
+ `,l+=` { type: 'text', text: '${this._escapeString(E)}' }
273
+ `,l+=` ]
274
+ `,l+=` });
275
+
276
+ `;else if(u.type==="fill"||u.type==="type"){let M=u.data.params.text;l+=` // ${m}${S?` (actual: "${S}")${P}`:""}
277
+ `,l+=` await ZibbyRuntime.step(page, {
278
+ `,l+=` name: '${this._escapeString(m)}',
279
+ `,l+=` action: 'fill',
280
+ `,l+=` value: '${this._escapeString(M)}',
281
+ `,l+=` strategies: [
282
+ `,l+=` { type: 'role', role: '${v}', name: '${this._escapeString(E)}' },
283
+ `,l+=` { type: 'attributes', placeholder: '${this._escapeString(E)}' }
284
+ `,l+=` ]
285
+ `,l+=` });
286
+
287
+ `}else if(u.type==="select_option"){let M=u.data.params.values,T=Array.isArray(M)?M[0]:M;l+=` // ${m}${S?` (actual: "${S}")${P}`:""}
288
+ `,l+=` await ZibbyRuntime.step(page, {
289
+ `,l+=` name: '${this._escapeString(m)}',
290
+ `,l+=` action: 'select',
291
+ `,l+=` value: '${this._escapeString(T)}',
292
+ `,l+=` strategies: [
293
+ `,l+=` { type: 'role', role: 'combobox', name: '${this._escapeString(E)}' }
294
+ `,l+=` ]
295
+ `,l+=` });
296
+
297
+ `}}return l+=`});
298
+ `,pi(t,l),console.log(`[MCPRefStrategy] \u2705 Generated test with ${c.length} actions using MCP descriptions`),{success:!0,testPath:t,method:"MCP Reference Replay (1:1)",actionsGenerated:c.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 on,writeFileSync as fi}from"node:fs";var Te=class extends V{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(on(t,"utf-8")).some(s=>s.stableId||s.data?.stableId)?(console.log("[StableIdStrategy] \u2705 Stable IDs available"),!0):(console.log("[StableIdStrategy] \u274C No stable IDs found in events"),!1)}catch(r){return console.log("[StableIdStrategy] \u274C Failed to read events:",r.message),!1}}getName(){return"Stable ID Injection (Experimental)"}getPriority(){return 300}async generate(e){let{testFilePath:t,sessionPath:r,state:n}=e,s=`${r}/execute_live/events.json`,i=n?.title||"Generated Test";console.log("[StableIdStrategy] \u{1F3AF} Generating test using stable IDs"),console.log(`[StableIdStrategy] events: ${s}`),console.log(`[StableIdStrategy] output: ${t}`);let c=JSON.parse(on(s,"utf-8")).filter(d=>["navigate","type","fill","click","select_option","select"].includes(d.type)),l=`import { test, expect } from '@playwright/test';
299
+ `;l+=`import { StableIdRuntime } from '@zibby/core';
300
+
301
+ `,l+=`test('${i}', async ({ page }) => {
302
+ `;let u=!1,m=null;for(let d=0;d<c.length;d++){let p=c[d],g=p.stableId||p.data?.stableId,y=p.data?.element||p.data?.params?.element||"element";if(p.type==="click"&&g&&g===m){console.log(`[StableIdStrategy] Skipping duplicate click on ${g}`);continue}if(p.type==="navigate"){let h=p.data?.url||p.data?.params?.url;h&&!u&&(l+=` await page.goto('${h}');
303
+ `,l+=` await StableIdRuntime.injectStableIds(page);
304
+
305
+ `)}else if(p.type==="click")if(u=!0,m=g,g)l+=` await StableIdRuntime.clickWithRetry(page, '${g}');
306
+ `;else{let h=this._generateSemanticSelector(y);l+=` await ${h}.click();
307
+ `,l+=` await StableIdRuntime.afterNavigation(page);
308
+ `}else if(p.type==="fill"||p.type==="type"){u=!1;let h=p.data?.text||p.data?.params?.text||"";g?l+=` await StableIdRuntime.fillWithRetry(page, '${g}', '${this._escapeString(h)}');
309
+ `:l+=` await page.getByPlaceholder('${this._escapeString(y)}').fill('${this._escapeString(h)}');
310
+ `}else if(p.type==="select_option"||p.type==="select"){u=!1;let h=p.data?.values||p.data?.params?.values,S=Array.isArray(h)?h[0]:h||"";g?l+=` await StableIdRuntime.selectWithRetry(page, '${g}', '${this._escapeString(S)}');
311
+ `:l+=` await page.locator('select').selectOption('${this._escapeString(S)}');
312
+ `}}return l+=`});
313
+ `,fi(t,l),console.log(`[StableIdStrategy] \u2705 Generated test with ${c.length} actions using stable IDs`),{success:!0,testPath:t,method:"Stable ID Injection (Experimental)",actionsGenerated:c.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 jt=class{constructor(){this.strategies=[new Te,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(`
311
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(`
312
- \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 Dt;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 si}from"node:fs";var ve=class extends Te{getName(){return"Playwright JSON Reporter"}getPriority(){return 100}canVerify(e){let{testFilePath:t}=e;return si(t)}async verify(e){let{testFilePath:t,cwd:r,timeout:n=3e4}=e;try{console.log(`\u{1F9EA} Running test: ${t}`);let s=`npx playwright test ${t} --reporter=json --timeout=${n}`,i=ni(s,{cwd:r,encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:n+1e4}),l=JSON.parse(i).stats||{};return{success:l.unexpected===0,passed:l.expected||0,failed:l.unexpected||0,error:null,errorDetails:null}}catch(s){let i=s.stdout||s.stderr||s.message;try{let c=JSON.parse(i),l=c.stats||{},a="Test execution failed";if(c.suites&&c.suites.length>0){let d=c.suites[0];if(d.specs&&d.specs.length>0){let m=d.specs[0];if(m.tests&&m.tests.length>0){let p=m.tests[0];if(p.results&&p.results.length>0){let g=p.results[0];g.error&&(a=g.error.message||a)}}}}let u=a.includes("Executable doesn't exist")||a.includes("browserType.launch")||a.includes("Please run the following command")||a.includes("npx playwright install")||i.includes("Executable doesn't exist")||i.includes("npx playwright install");return{success:!1,passed:l.expected||0,failed:l.unexpected||0,error:a,errorDetails:a,isEnvironmentError:u}}catch{let l=i.match(/Error: (.+)/),a=l?l[1]:"Test execution failed",u=a.includes("Executable doesn't exist")||a.includes("browserType.launch")||a.includes("Please run the following command")||a.includes("npx playwright install")||i.includes("Executable doesn't exist")||i.includes("npx playwright install");return{success:!1,passed:0,failed:1,error:a,errorDetails:a,isEnvironmentError:u}}}}};var Ut=class{constructor(){this.strategies=[new ve],this.strategies.sort((e,t)=>t.getPriority()-e.getPriority())}registerStrategy(e){this.strategies.push(e),this.strategies.sort((t,r)=>r.getPriority()-t.getPriority())}async verify(e){console.log(`
315
+ \u{1F3AF} Selected: ${t.getName()}`),t.generate(e);throw new Error("No generation strategy available for this context")}getStrategy(e){return this.strategies.find(t=>t.getName().includes(e))||null}},di=new jt;var ve=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 mi}from"node:child_process";import{existsSync as gi}from"node:fs";var Ae=class extends ve{getName(){return"Playwright JSON Reporter"}getPriority(){return 100}canVerify(e){let{testFilePath:t}=e;return gi(t)}async verify(e){let{testFilePath:t,cwd:r,timeout:n=3e4}=e;try{console.log(`\u{1F9EA} Running test: ${t}`);let s=`npx playwright test ${t} --reporter=json --timeout=${n}`,i=mi(s,{cwd:r,encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:n+1e4}),c=JSON.parse(i).stats||{};return{success:c.unexpected===0,passed:c.expected||0,failed:c.unexpected||0,error:null,errorDetails:null}}catch(s){let i=s.stdout||s.stderr||s.message;try{let a=JSON.parse(i),c=a.stats||{},l="Test execution failed";if(a.suites&&a.suites.length>0){let m=a.suites[0];if(m.specs&&m.specs.length>0){let d=m.specs[0];if(d.tests&&d.tests.length>0){let p=d.tests[0];if(p.results&&p.results.length>0){let g=p.results[0];g.error&&(l=g.error.message||l)}}}}let u=l.includes("Executable doesn't exist")||l.includes("browserType.launch")||l.includes("Please run the following command")||l.includes("npx playwright install")||i.includes("Executable doesn't exist")||i.includes("npx playwright install");return{success:!1,passed:c.expected||0,failed:c.unexpected||0,error:l,errorDetails:l,isEnvironmentError:u}}catch{let c=i.match(/Error: (.+)/),l=c?c[1]:"Test execution failed",u=l.includes("Executable doesn't exist")||l.includes("browserType.launch")||l.includes("Please run the following command")||l.includes("npx playwright install")||i.includes("Executable doesn't exist")||i.includes("npx playwright install");return{success:!1,passed:0,failed:1,error:l,errorDetails:l,isEnvironmentError:u}}}}};var Gt=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(`
313
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(`
314
- \u{1F3AF} Selected: ${t.getName()}`),t.verify(e);throw new Error("No verification strategy available for this context")}getStrategy(e){return this.strategies.find(t=>t.getName().includes(e))||null}},oi=new Ut;var V=class{constructor(e={}){this.enrichers=[],this.config=e,this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}register(e){return this.enrichers.push(e),this.enrichers.sort((t,r)=>r.getPriority()-t.getPriority()),this}unregister(e){return this.enrichers=this.enrichers.filter(t=>t.getName()!==e),this}get(e){return this.enrichers.find(t=>t.getName()===e)}setEnabled(e,t){let r=this.get(e);return r&&(r.enabled=t),this}async enrich(e,t){this.stats.totalEvents++;let r={...e},n=[],s=[],i=[];for(let c of this.enrichers)try{if(!c.canEnrich(t)){s.push(c.getName());continue}let l=Date.now(),a=await c.enrich(e,t),u=Date.now()-l;a?(Object.assign(r,a),n.push({name:c.getName(),duration:u})):s.push(c.getName())}catch(l){console.warn(`[EnrichmentPipeline] ${c.getName()} failed:`,l.message),i.push(c.getName()),this.stats.errors[c.getName()]=(this.stats.errors[c.getName()]||0)+1}return r._enrichment={version:"1.0",timestamp:new Date().toISOString(),enrichers:{run:n,skipped:s,failed:i}},n.length>0?this.stats.enrichedEvents++:this.stats.skippedEvents++,r}async enrichBatch(e,t){let r=[];for(let n of e){let s=await this.enrich(n,t);r.push(s)}return r}getStats(){return{...this.stats,enrichers:this.enrichers.map(e=>({name:e.getName(),enabled:e.enabled,priority:e.getPriority(),errors:this.stats.errors[e.getName()]||0}))}}resetStats(){this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}logStatus(){console.log(`
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}},hi=new Gt;var Q=class{constructor(e={}){this.enrichers=[],this.config=e,this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}register(e){return this.enrichers.push(e),this.enrichers.sort((t,r)=>r.getPriority()-t.getPriority()),this}unregister(e){return this.enrichers=this.enrichers.filter(t=>t.getName()!==e),this}get(e){return this.enrichers.find(t=>t.getName()===e)}setEnabled(e,t){let r=this.get(e);return r&&(r.enabled=t),this}async enrich(e,t){this.stats.totalEvents++;let r={...e},n=[],s=[],i=[];for(let a of this.enrichers)try{if(!a.canEnrich(t)){s.push(a.getName());continue}let c=Date.now(),l=await a.enrich(e,t),u=Date.now()-c;l?(Object.assign(r,l),n.push({name:a.getName(),duration:u})):s.push(a.getName())}catch(c){console.warn(`[EnrichmentPipeline] ${a.getName()} failed:`,c.message),i.push(a.getName()),this.stats.errors[a.getName()]=(this.stats.errors[a.getName()]||0)+1}return r._enrichment={version:"1.0",timestamp:new Date().toISOString(),enrichers:{run:n,skipped:s,failed:i}},n.length>0?this.stats.enrichedEvents++:this.stats.skippedEvents++,r}async enrichBatch(e,t){let r=[];for(let n of e){let s=await this.enrich(n,t);r.push(s)}return r}getStats(){return{...this.stats,enrichers:this.enrichers.map(e=>({name:e.getName(),enabled:e.enabled,priority:e.getPriority(),errors:this.stats.errors[e.getName()]||0}))}}resetStats(){this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}logStatus(){console.log(`
315
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(`
316
- 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 Ae=class extends G{getName(){return"PositionEnricher"}getPriority(){return 90}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:n}=t,s=await n.boundingBox();if(!s)return null;let i=await r.evaluate(()=>({scrollX:window.scrollX,scrollY:window.scrollY,width:window.innerWidth,height:window.innerHeight})),c=s.y>=i.scrollY&&s.y+s.height<=i.scrollY+i.height&&s.x>=0&&s.x+s.width<=i.width;return{position:{boundingBox:s,viewport:i,inViewport:c,centerPoint:{x:Math.round(s.x+s.width/2),y:Math.round(s.y+s.height/2)}}}}catch(r){return this.handleError(r,e)}}};import Qr from"node:crypto";var pe=class extends G{getName(){return"AccessibilityEnricher"}getPriority(){return 100}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:n}=t,s=await r.accessibility.snapshot(),i=await this.findAxNode(n,s);if(!i)return null;let c=await this.getAxContext(i,s),l=this.hashAxSubtree(i),a=this.hashAxPath(c.path);return{accessibility:{role:i.role,name:i.name||"",level:c.level,parent:c.parent,siblings:c.siblings,axTreeHash:l,axPathHash:a}}}catch(r){return this.handleError(r,e)}}async findAxNode(e,t){let r=await e.evaluate(n=>({role:n.getAttribute("role")||n.tagName.toLowerCase(),name:n.getAttribute("aria-label")||n.textContent?.trim()||"",tagName:n.tagName.toLowerCase()}));return this.searchAxTree(t,r)}searchAxTree(e,t){if(!e)return null;if(e.role===t.role&&(e.name||"").includes(t.name.substring(0,20)))return e;if(e.children)for(let r of e.children){let n=this.searchAxTree(r,t);if(n)return n}return null}getAxContext(e,t){let r={level:0,parent:null,siblings:[],path:[]},n=this.findParent(e,t);return n&&(r.parent={role:n.role,name:n.name},r.siblings=(n.children||[]).filter(s=>s!==e).map(s=>({role:s.role,name:s.name})).slice(0,3)),r.level=this.calculateLevel(e,t),r.path=this.buildPath(e,t),r}findParent(e,t,r=t){if(!r||!r.children)return null;if(r.children.includes(e))return r;for(let n of r.children){let s=this.findParent(e,t,n);if(s)return s}return null}calculateLevel(e,t,r=t,n=0){if(r===e)return n;if(r.children)for(let s of r.children){let i=this.calculateLevel(e,t,s,n+1);if(i>=0)return i}return-1}buildPath(e,t,r=t,n=[]){if(r===e)return[...n,{role:r.role,name:r.name}];if(r.children)for(let s of r.children){let i=this.buildPath(e,t,s,[...n,{role:r.role,name:r.name}]);if(i)return i}return null}hashAxSubtree(e){let t=JSON.stringify({role:e.role,name:e.name,children:(e.children||[]).map(r=>({role:r.role,name:r.name}))});return 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 G{constructor(e={}){super(e),this.pendingRequests=new Set,this.setupNetworkTracking=!1}getName(){return"PageStateEnricher"}getPriority(){return 95}canEnrich(e){return this.enabled&&e.page}async setupTracking(e){this.setupNetworkTracking||(e.on("request",t=>{["document","xhr","fetch"].includes(t.resourceType())&&this.pendingRequests.add(t.url())}),e.on("requestfinished",t=>{this.pendingRequests.delete(t.url())}),e.on("requestfailed",t=>{this.pendingRequests.delete(t.url())}),this.setupNetworkTracking=!0)}async enrich(e,t){try{let{page:r}=t;await this.setupTracking(r);let n=await r.evaluate(()=>({readyState:document.readyState,domContentLoaded:document.readyState!=="loading",loadComplete:document.readyState==="complete",url:document.location.href})),s=await this.checkDOMStability(r);return{page:{networkIdle:this.pendingRequests.size===0,pendingRequests:this.pendingRequests.size,domStable:s,...n}}}catch(r){return this.handleError(r,e)}}async checkDOMStability(e,t=500){try{return await e.evaluate(n=>new Promise(s=>{let i,c=0,l=new MutationObserver(()=>{c++,clearTimeout(i),i=setTimeout(()=>{l.disconnect(),s(c===0)},n)});l.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),i=setTimeout(()=>{l.disconnect(),s(!0)},n)}),t)}catch{return!1}}reset(){this.pendingRequests.clear(),this.setupNetworkTracking=!1}};var Ie=class extends G{getName(){return"DOMEnricher"}getPriority(){return 85}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{element:r}=t,n=await r.evaluate(s=>{let i=p=>{let g=[],S=p;for(;S&&S!==document.body;){let h=S.tagName.toLowerCase(),b=S.parentElement;if(b){let x=Array.from(b.children).filter(T=>T.tagName===S.tagName);if(x.length>1){let T=x.indexOf(S)+1;h+=`:nth-child(${T})`}}g.unshift(h),S=S.parentElement}return`body > ${g.join(" > ")}`},c=p=>{let g=[],S=p;for(;S&&S!==document.body;){let h=1,b=S.previousSibling;for(;b;)b.nodeType===1&&b.tagName===S.tagName&&h++,b=b.previousSibling;let x=S.tagName.toLowerCase();g.unshift(`${x}[${h}]`),S=S.parentElement}return`/html/body/${g.join("/")}`},l={};for(let p of s.attributes)l[p.name]=p.value;let a=window.getComputedStyle(s),u={display:a.display,visibility:a.visibility,opacity:a.opacity,pointerEvents:a.pointerEvents},d=0,m=s.parentElement;for(;m;)d++,m=m.parentElement;return{path:i(s),xpath:c(s),depth:d,parent:s.parentElement?s.parentElement.tagName.toLowerCase():null,tagName:s.tagName.toLowerCase(),attributes:l,state:{visible:a.display!=="none"&&a.visibility!=="hidden",enabled:!s.disabled,focused:document.activeElement===s,...u}}});return{dom:{path:n.path,xpath:n.xpath,depth:n.depth,parent:n.parent,selector:this.buildSmartSelector(n)},attributes:n.attributes,state:n.state}}catch(r){return this.handleError(r,e)}}buildSmartSelector(e){let t=e.tagName;if(e.attributes.id)return`#${e.attributes.id}`;if(e.attributes["data-test-id"])return`[data-test-id="${e.attributes["data-test-id"]}"]`;if(e.attributes.class){let r=e.attributes.class.split(" ").filter(n=>n&&!n.match(/^(active|focus|hover|disabled)/));r.length>0&&(t+=`.${r.slice(0,2).join(".")}`)}return e.parent&&(t=`${e.parent} > ${t}`),t}};var ze=class extends G{constructor(e={}){super(e),this.priority=200}getName(){return"MCPRef"}getPriority(){return this.priority}async enrich(e,t){let r=e.data?.params?.ref,n=e.data?.params?.element;if(!r&&!n)return null;let s=null,i=null,c=null;if(t?.element)try{let l=await t.element.evaluate(a=>({text:a.textContent?.trim()||"",innerText:a.innerText?.trim()||"",value:a.value||"",label:a.getAttribute("aria-label")||a.getAttribute("label")||"",role:a.getAttribute("role")||a.tagName.toLowerCase(),placeholder:a.getAttribute("placeholder")||"",title:a.getAttribute("title")||""}));s=l.text||l.innerText||l.value||l.placeholder,i=l.role,c=l.label||l.title,console.log(`[MCPRefEnricher] \u2705 Captured actual text: "${s}" (AI said: "${n}")`)}catch(l){console.log(`[MCPRefEnricher] \u26A0\uFE0F Could not extract actual text: ${l.message}`)}return{mcpRef:r,mcpElement:n,actualText:s,actualRole:i,actualLabel:c,recordedSelector:s||n}}};function Bt(o={}){let e=new V(o);return o.enableMCPRef!==!1&&e.register(new ze(o)),o.enableTraceText!==!1&&e.register(new ue(o)),o.enableAccessibility!==!1&&e.register(new pe(o)),o.enablePageState!==!1&&e.register(new fe(o)),o.enablePosition!==!1&&e.register(new Ae(o)),o.enableDOM!==!1&&e.register(new Ie(o)),e}function Ft(o={}){let e=new V(o);return e.register(new pe(o)),e.register(new fe(o)),e}function ii(o,e={}){let t=new V(e);for(let r of o)t.register(r);return t}import{readFileSync as ai,writeFileSync as jt}from"node:fs";import{join as en}from"node:path";async function ci(o,e={}){let t=en(o,"events.json"),r=en(o,"trace.zip");try{let n=JSON.parse(ai(t,"utf-8")),s=n.map(c=>({...c,_enrichmentNote:"Full enrichment requires live Playwright access. Use EnrichmentPipeline during test execution."})),i=`${t}.backup`;return jt(i,JSON.stringify(n,null,2)),jt(t,JSON.stringify(s,null,2)),{enrichedCount:s.length,skippedCount:0,errors:[]}}catch(n){return console.error("[EnrichmentIntegration] Failed to enrich events:",n.message),{enrichedCount:0,skippedCount:0,errors:[n.message]}}}var Gt=class{constructor(e={}){this.pipeline=e.minimal?Ft(e):Bt(e),this.events=[],this.config=e}async recordEvent(e,t,r){let n={id:this.events.length,type:e,timestamp:new Date().toISOString(),data:t},s=await this.pipeline.enrich(n,{...r,event:n});return this.events.push(s),s}saveEvents(e){jt(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()}};wt();var on=o=>{o?.message?.includes("Connection closed")||o?.message?.includes("MCP error -32000")||o?.code===-32e3||console.error("Unhandled rejection:",o)};process.listeners("unhandledRejection").includes(on)||process.on("unhandledRejection",on);async function gi(o,e={}){let{agent:t,mcp:r,headless:n,cwd:s=process.cwd(),specPath:i,sessionPath:c,sessionTimestamp:l,...a}=e,u=tn(o,"utf-8"),d=null,{agent:m,error:p}=await Si(s,a),g=m;if(!g&&e.fallbackAgentModule){let b=e.fallbackAgentModule,x=b.BrowserTestAutomationAgent||b.default;x&&(g=new x(a))}if(!g&&p&&console.warn(`\u26A0\uFE0F Failed to load local agent: ${p}`),!g)throw new Error(`No agent found. Please run:
319
+ Registered enrichers (${this.enrichers.length}):`);for(let e of this.enrichers){let t=e.enabled?"\u2713":"\u2717",r=this.stats.errors[e.getName()]||0,n=r>0?` (${r} errors)`:"";console.log(` ${t} ${e.getName()} (priority: ${e.getPriority()})${n}`)}console.log()}};var Ie=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,s=await n.boundingBox();if(!s)return null;let i=await r.evaluate(()=>({scrollX:window.scrollX,scrollY:window.scrollY,width:window.innerWidth,height:window.innerHeight})),a=s.y>=i.scrollY&&s.y+s.height<=i.scrollY+i.height&&s.x>=0&&s.x+s.width<=i.width;return{position:{boundingBox:s,viewport:i,inViewport:a,centerPoint:{x:Math.round(s.x+s.width/2),y:Math.round(s.y+s.height/2)}}}}catch(r){return this.handleError(r,e)}}};import an from"node:crypto";var fe=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,s=await r.accessibility.snapshot(),i=await this.findAxNode(n,s);if(!i)return null;let a=await this.getAxContext(i,s),c=this.hashAxSubtree(i),l=this.hashAxPath(a.path);return{accessibility:{role:i.role,name:i.name||"",level:a.level,parent:a.parent,siblings:a.siblings,axTreeHash:c,axPathHash:l}}}catch(r){return this.handleError(r,e)}}async findAxNode(e,t){let r=await e.evaluate(n=>({role:n.getAttribute("role")||n.tagName.toLowerCase(),name:n.getAttribute("aria-label")||n.textContent?.trim()||"",tagName:n.tagName.toLowerCase()}));return this.searchAxTree(t,r)}searchAxTree(e,t){if(!e)return null;if(e.role===t.role&&(e.name||"").includes(t.name.substring(0,20)))return e;if(e.children)for(let r of e.children){let n=this.searchAxTree(r,t);if(n)return n}return null}getAxContext(e,t){let r={level:0,parent:null,siblings:[],path:[]},n=this.findParent(e,t);return n&&(r.parent={role:n.role,name:n.name},r.siblings=(n.children||[]).filter(s=>s!==e).map(s=>({role:s.role,name:s.name})).slice(0,3)),r.level=this.calculateLevel(e,t),r.path=this.buildPath(e,t),r}findParent(e,t,r=t){if(!r||!r.children)return null;if(r.children.includes(e))return r;for(let n of r.children){let s=this.findParent(e,t,n);if(s)return s}return null}calculateLevel(e,t,r=t,n=0){if(r===e)return n;if(r.children)for(let s of r.children){let i=this.calculateLevel(e,t,s,n+1);if(i>=0)return i}return-1}buildPath(e,t,r=t,n=[]){if(r===e)return[...n,{role:r.role,name:r.name}];if(r.children)for(let s of r.children){let i=this.buildPath(e,t,s,[...n,{role:r.role,name:r.name}]);if(i)return i}return null}hashAxSubtree(e){let t=JSON.stringify({role:e.role,name:e.name,children:(e.children||[]).map(r=>({role:r.role,name:r.name}))});return an.createHash("md5").update(t).digest("hex").substring(0,12)}hashAxPath(e){let t=e.map(r=>`${r.role}:${r.name}`).join("/");return an.createHash("md5").update(t).digest("hex").substring(0,12)}};var de=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})),s=await this.checkDOMStability(r);return{page:{networkIdle:this.pendingRequests.size===0,pendingRequests:this.pendingRequests.size,domStable:s,...n}}}catch(r){return this.handleError(r,e)}}async checkDOMStability(e,t=500){try{return await e.evaluate(n=>new Promise(s=>{let i,a=0,c=new MutationObserver(()=>{a++,clearTimeout(i),i=setTimeout(()=>{c.disconnect(),s(a===0)},n)});c.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),i=setTimeout(()=>{c.disconnect(),s(!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(s=>{let i=p=>{let g=[],y=p;for(;y&&y!==document.body;){let h=y.tagName.toLowerCase(),S=y.parentElement;if(S){let _=Array.from(S.children).filter(A=>A.tagName===y.tagName);if(_.length>1){let A=_.indexOf(y)+1;h+=`:nth-child(${A})`}}g.unshift(h),y=y.parentElement}return`body > ${g.join(" > ")}`},a=p=>{let g=[],y=p;for(;y&&y!==document.body;){let h=1,S=y.previousSibling;for(;S;)S.nodeType===1&&S.tagName===y.tagName&&h++,S=S.previousSibling;let _=y.tagName.toLowerCase();g.unshift(`${_}[${h}]`),y=y.parentElement}return`/html/body/${g.join("/")}`},c={};for(let p of s.attributes)c[p.name]=p.value;let l=window.getComputedStyle(s),u={display:l.display,visibility:l.visibility,opacity:l.opacity,pointerEvents:l.pointerEvents},m=0,d=s.parentElement;for(;d;)m++,d=d.parentElement;return{path:i(s),xpath:a(s),depth:m,parent:s.parentElement?s.parentElement.tagName.toLowerCase():null,tagName:s.tagName.toLowerCase(),attributes:c,state:{visible:l.display!=="none"&&l.visibility!=="hidden",enabled:!s.disabled,focused:document.activeElement===s,...u}}});return{dom:{path:n.path,xpath:n.xpath,depth:n.depth,parent:n.parent,selector:this.buildSmartSelector(n)},attributes:n.attributes,state:n.state}}catch(r){return this.handleError(r,e)}}buildSmartSelector(e){let t=e.tagName;if(e.attributes.id)return`#${e.attributes.id}`;if(e.attributes["data-test-id"])return`[data-test-id="${e.attributes["data-test-id"]}"]`;if(e.attributes.class){let r=e.attributes.class.split(" ").filter(n=>n&&!n.match(/^(active|focus|hover|disabled)/));r.length>0&&(t+=`.${r.slice(0,2).join(".")}`)}return e.parent&&(t=`${e.parent} > ${t}`),t}};var Ke=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 s=null,i=null,a=null;if(t?.element)try{let c=await t.element.evaluate(l=>({text:l.textContent?.trim()||"",innerText:l.innerText?.trim()||"",value:l.value||"",label:l.getAttribute("aria-label")||l.getAttribute("label")||"",role:l.getAttribute("role")||l.tagName.toLowerCase(),placeholder:l.getAttribute("placeholder")||"",title:l.getAttribute("title")||""}));s=c.text||c.innerText||c.value||c.placeholder,i=c.role,a=c.label||c.title,console.log(`[MCPRefEnricher] \u2705 Captured actual text: "${s}" (AI said: "${n}")`)}catch(c){console.log(`[MCPRefEnricher] \u26A0\uFE0F Could not extract actual text: ${c.message}`)}return{mcpRef:r,mcpElement:n,actualText:s,actualRole:i,actualLabel:a,recordedSelector:s||n}}};function zt(o={}){let e=new Q(o);return o.enableMCPRef!==!1&&e.register(new Ke(o)),o.enableTraceText!==!1&&e.register(new pe(o)),o.enableAccessibility!==!1&&e.register(new fe(o)),o.enablePageState!==!1&&e.register(new de(o)),o.enablePosition!==!1&&e.register(new Ie(o)),o.enableDOM!==!1&&e.register(new $e(o)),e}function Jt(o={}){let e=new Q(o);return e.register(new fe(o)),e.register(new de(o)),e}function yi(o,e={}){let t=new Q(e);for(let r of o)t.register(r);return t}import{readFileSync as Si,writeFileSync as Kt}from"node:fs";import{join as cn}from"node:path";async function bi(o,e={}){let t=cn(o,"events.json"),r=cn(o,"trace.zip");try{let n=JSON.parse(Si(t,"utf-8")),s=n.map(a=>({...a,_enrichmentNote:"Full enrichment requires live Playwright access. Use EnrichmentPipeline during test execution."})),i=`${t}.backup`;return Kt(i,JSON.stringify(n,null,2)),Kt(t,JSON.stringify(s,null,2)),{enrichedCount:s.length,skippedCount:0,errors:[]}}catch(n){return console.error("[EnrichmentIntegration] Failed to enrich events:",n.message),{enrichedCount:0,skippedCount:0,errors:[n.message]}}}var Yt=class{constructor(e={}){this.pipeline=e.minimal?Jt(e):zt(e),this.events=[],this.config=e}async recordEvent(e,t,r){let n={id:this.events.length,type:e,timestamp:new Date().toISOString(),data:t},s=await this.pipeline.enrich(n,{...r,event:n});return this.events.push(s),s}saveEvents(e){Kt(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()}};Tt();var dn=o=>{o?.message?.includes("Connection closed")||o?.message?.includes("MCP error -32000")||o?.code===-32e3||console.error("Unhandled rejection:",o)};process.listeners("unhandledRejection").includes(dn)||process.on("unhandledRejection",dn);async function Ai(o,e={}){let{agent:t,mcp:r,headless:n,cwd:s=process.cwd(),specPath:i,sessionPath:a,sessionTimestamp:c,...l}=e,u=ln(o,"utf-8"),m=null,{agent:d,error:p}=await Oi(s,l),g=d;if(!g&&e.fallbackAgentModule){let S=e.fallbackAgentModule,_=S.BrowserTestAutomationAgent||S.default;_&&(g=new _(l))}if(!g&&p&&console.warn(`\u26A0\uFE0F Failed to load local agent: ${p}`),!g)throw new Error(`No agent found. Please run:
317
320
  zibby init
318
321
 
319
- This will create .zibby/graph.mjs with your workflow definition.`);await g.initialize(d);let S=!1,h=()=>{if(!S)try{At({cwd:s||process.cwd(),config:e}),S=!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
+ This will create .zibby/graph.mjs with your workflow definition.`);await g.initialize(m);let y=!1,h=()=>{if(!y)try{Pt({cwd:s||process.cwd(),config:e}),y=!0}catch(S){console.warn("[zibby] run-index interrupt row:",S?.message||S)}};process.on("SIGINT",h),process.on("SIGTERM",h);try{if(e.singleNode){console.log(`
320
323
  \u{1F3AF} Running Single Node: ${e.singleNode} (Framework Mode)
321
- `);let v=g.calculateOutputPath(i||o),A=g.buildGraph(),D={};for(let[M,N]of A.nodes.entries())D[M]=N.config||N;let E={};if(e.sessionId){let M=e.sessionId,N=e.paths?.output||ui;if(M==="last"){let k=$e(s,N,sn);if(rn(k)){let{readdirSync:P,statSync:_}=await import("fs"),B=P(k).filter(L=>_($e(k,L)).isDirectory()).map(L=>({name:L,time:_($e(k,L)).mtimeMs})).sort((L,F)=>F.time-L.time);B.length>0?(M=B[0].name,console.log(`\u{1F4C2} Using latest session: ${M}`)):console.log(`\u26A0\uFE0F No sessions found in ${k}`)}}let U=$e(s,N,sn,M),O=$e(U,"execute_live"),y=$e(O,pi);rn(y)?(console.log(`\u{1F4C2} Loading session: ${M}`),E={sessionPath:U,execute_live_output:JSON.parse(tn(y,"utf-8"))}):console.log(`\u26A0\uFE0F Session not found: ${U}`)}let R=await g.runSingleNode(e.singleNode,D,{testSpec:u,outputPath:v,cwd:s||process.cwd(),contextConfig:e.contextConfig,specPath:i||o,config:e,...E});return typeof g.onComplete=="function"&&await g.onComplete(R),st({cwd:s,config:e,result:R,success:!0,specPath:i||o}),R}let b;typeof e.onPipelineProgress=="function"?b=e.onPipelineProgress:e.runIndex?.pipelineProgress!==!1&&(b=Cr({cwd:s||process.cwd(),config:e}));let x=s||process.cwd(),T=c!=null&&String(c).trim()!==""?(()=>{let v=String(c).trim();try{return li(v)?nn(v):nn(x,v)}catch{return v}})():void 0,w=mi(),I=T??w;di();let $=fi({cwd:x,config:e,traceFrom:"runTest",initialState:{sessionPath:I,sessionTimestamp:l}}),C;try{C=await g.run(u,{testSpec:u,specPath:i||o,cwd:x,config:e,sessionPath:$.sessionPath,sessionTimestamp:$.sessionTimestamp,...b?{onPipelineProgress:b}:{}})}catch(v){throw typeof v?.message=="string"&&v.message.includes("Interrupted by user")&&At({cwd:s||process.cwd(),config:e}),S||st({cwd:s,config:e,result:v?.partialResult||{},success:!1,specPath:i||o,errorMessage:v?.message}),v}return st({cwd:s,config:e,result:C,success:!0,specPath:i||o}),C}finally{process.off("SIGINT",h),process.off("SIGTERM",h),await g.cleanup()}}function hi(o){return o.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function yi(o,e){if(o[e])return o[e];let t=hi(e);if(o[t])return o[t];let r=`${t}Workflow`;return o[r]?o[r]:null}async function dp(o=process.cwd()){try{let{join:e}=await import("path"),{existsSync:t}=await import("fs"),{pathToFileURL:r}=await import("url"),n=e(o,".zibby/graph.mjs");if(!t(n))return{available:[],default:null,error:"No .zibby/graph.mjs found"};let s=await import(r(n).href),i=Object.keys(s).filter(l=>l!=="default"&&typeof s[l]=="function"&&s[l].prototype instanceof we),c=s.BrowserTestAutomationAgent?"BrowserTestAutomationAgent":s.CursorAgent?"CursorAgent":s.default?"default":i[0]||null;return{available:i,default:c,error:null}}catch(e){return{available:[],default:null,error:e.message}}}async function Si(o,e){try{let{join:t}=await import("path"),{existsSync:r}=await import("fs"),{pathToFileURL:n}=await import("url"),s=t(o,".zibby/graph.mjs");if(!r(s))return{agent:null,error:null};let i=await import(n(s).href),c=e.workflow,l;if(c){if(l=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
+ `);let T=g.calculateOutputPath(i||o),C=g.buildGraph(),U={};for(let[k,R]of C.nodes.entries())U[k]=R.config||R;let x={};if(e.sessionId){let k=e.sessionId,R=e.paths?.output||xi;if(k==="last"){let O=Oe(s,R,fn);if(un(O)){let{readdirSync:b,statSync:D}=await import("fs"),I=b(O).filter($=>D(Oe(O,$)).isDirectory()).map($=>({name:$,time:D(Oe(O,$)).mtimeMs})).sort(($,B)=>B.time-$.time);I.length>0?(k=I[0].name,console.log(`\u{1F4C2} Using latest session: ${k}`)):console.log(`\u26A0\uFE0F No sessions found in ${O}`)}}let L=Oe(s,R,fn,k),F=Oe(L,"execute_live"),w=Oe(F,_i);un(w)?(console.log(`\u{1F4C2} Loading session: ${k}`),x={sessionPath:L,execute_live_output:JSON.parse(ln(w,"utf-8"))}):console.log(`\u26A0\uFE0F Session not found: ${L}`)}let N=await g.runSingleNode(e.singleNode,U,{testSpec:u,outputPath:T,cwd:s||process.cwd(),contextConfig:e.contextConfig,specPath:i||o,config:e,...x});return typeof g.onComplete=="function"&&await g.onComplete(N),it({cwd:s,config:e,result:N,success:!0,specPath:i||o}),N}let S;typeof e.onPipelineProgress=="function"?S=e.onPipelineProgress:e.runIndex?.pipelineProgress!==!1&&(S=Ur({cwd:s||process.cwd(),config:e}));let _=s||process.cwd(),A=a!=null&&String(a).trim()!==""?(()=>{let T=String(a).trim();try{return wi(T)?pn(T):pn(_,T)}catch{return T}})():void 0,E=vi(),v=A??E;Ti();let P=Ei({cwd:_,config:e,traceFrom:"runTest",initialState:{sessionPath:v,sessionTimestamp:c}}),M;try{M=await g.run(u,{testSpec:u,specPath:i||o,cwd:_,config:e,sessionPath:P.sessionPath,sessionTimestamp:P.sessionTimestamp,...S?{onPipelineProgress:S}:{}})}catch(T){throw typeof T?.message=="string"&&T.message.includes("Interrupted by user")&&Pt({cwd:s||process.cwd(),config:e}),y||it({cwd:s,config:e,result:T?.partialResult||{},success:!1,specPath:i||o,errorMessage:T?.message}),T}return it({cwd:s,config:e,result:M,success:!0,specPath:i||o}),M}finally{process.off("SIGINT",h),process.off("SIGTERM",h),await g.cleanup()}}function Ii(o){return o.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function $i(o,e){if(o[e])return o[e];let t=Ii(e);if(o[t])return o[t];let r=`${t}Workflow`;return o[r]?o[r]:null}async function Ip(o=process.cwd()){try{let{join:e}=await import("path"),{existsSync:t}=await import("fs"),{pathToFileURL:r}=await import("url"),n=e(o,".zibby/graph.mjs");if(!t(n))return{available:[],default:null,error:"No .zibby/graph.mjs found"};let s=await import(r(n).href),i=Object.keys(s).filter(c=>c!=="default"&&typeof s[c]=="function"&&s[c].prototype instanceof xe),a=s.BrowserTestAutomationAgent?"BrowserTestAutomationAgent":s.CursorAgent?"CursorAgent":s.default?"default":i[0]||null;return{available:i,default:a,error:null}}catch(e){return{available:[],default:null,error:e.message}}}async function Oi(o,e){try{let{join:t}=await import("path"),{existsSync:r}=await import("fs"),{pathToFileURL:n}=await import("url"),s=t(o,".zibby/graph.mjs");if(!r(s))return{agent:null,error:null};let i=await import(n(s).href),a=e.workflow,c;if(a){if(c=$i(i,a),!c){let u=Object.keys(i).filter(m=>m!=="default"&&typeof i[m]=="function");throw new Error(`Workflow "${a}" not found.
322
325
  Available workflows: ${u.join(", ")}
323
- 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 we);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 an=class{constructor(e={}){this.config=e}async run(e){return gi(e.spec||e.specPath,{...this.config,...e})}};export{ln as AGENT_TYPES,dl as ALL_TOOLS,pe as AccessibilityEnricher,to as AgentStrategy,ae as AssistantStrategy,co as CHAT_MEMORY_TOOLS,Vp as CI_ENV_VARS,un as CORE_LOG_LEVELS,ro as CORE_TOOLS,re as ClaudeAgentStrategy,ne as CodexAgentStrategy,te as CursorAgentStrategy,jo as DEFAULT_MAX_CONCURRENT_RUNS,j as DEFAULT_MODELS,Yp as DEFAULT_OUTPUT_BASE,Ie as DOMEnricher,qp as EVENTS_FILE,V as EnrichmentPipeline,G as EventEnricher,so as GITHUB_TOOLS,oe as GeminiAgentStrategy,no as JIRA_TOOLS,K as LOG_LEVELS,Gt as LiveEnrichmentRecorder,Ye as Logger,Jo as MAX_MAX_CONCURRENT_RUNS,_e as MCPRefStrategy,ao as MEMORY_TOOLS,Go as MIN_MAX_CONCURRENT_RUNS,Me as McpClientManager,ie as OpenAIToolProvider,fe as PageStateEnricher,ve as PlaywrightJsonVerificationStrategy,Ae as PositionEnricher,Xp as RAW_OUTPUT_FILE,Zp as RESULT_FILE,Jr as RIPPLE_EFFECT_SCRIPT,io as RUNNER_TOOLS,Nt as ResultHandler,Hp as SESSIONS_DIR,Wp as SESSION_INFO_FILE,Cp as SKILLS,lo as SKILL_TOOLS,oo as SLACK_TOOLS,Fe as SelectorGenerator,Lt as StableIdRuntime,Ee as StableIdStrategy,H as StreamingParser,an as TestAutomation,q as TestGenerationStrategy,Rt as TestPostProcessor,Te as TestVerificationStrategy,he as ToolCallProvider,Ge as TraceParser,we as WorkflowAgent,hp as WorkflowGraph,Mt as ZibbyRuntime,Be as ZibbyUploader,Fs as checkCursorAgentInstalled,No as checkCursorAgentPatched,bp as clearInheritedSessionEnvForFreshRun,So as clearTokenCache,$o as cloneRepo,ii as createCustomPipeline,Bt as createDefaultPipeline,Ft as createMinimalPipeline,Fr as createUploader,ci as enrichRecordedEvents,Do as generateRippleHelperCode,Sp as generateWorkflowSessionId,Dr as getAgentStrategy,Lp as getAllSkills,Ro as getApprovalKeys,js as getCursorAgentInstallInstructions,kp as getSkill,Mp as hasSkill,Lo as injectRippleEffect,eo as invokeAgent,Dp as listSkillIds,dp as listWorkflows,f as logger,_o as organizeVideos,Co as patchCursorAgentForCI,J as pickFromPool,Wo as postProcessEvents,xp as readPinnedSessionPathFromEnv,wt as registerBuiltInStrategies,Rp as registerSkill,Qo as resetExecutionCount,yo as resolveIntegrationToken,zo as resolveMaxParallelRuns,yp as resolveWorkflowSession,Xr as runPlaywrightTestTool,gi as runTest,Mo as saveApprovalKeys,wp as shouldTrustInheritedSessionEnv,_p as syncProcessEnvToSession,ri as testGenerationManager,oi as testVerificationManager,W as timeline,qs as workflow,vp as z};
326
+ Supported formats: QuickSmokeWorkflow, QuickSmoke, quick-smoke`)}let l=Object.keys(i).find(u=>i[u]===c);console.log(`\u2713 Using workflow: ${l} (from --workflow ${a})`)}else{if(c=i.BrowserTestAutomationAgent||i.CursorAgent||i.default,!c){let l=Object.keys(i).filter(u=>u!=="default"&&typeof i[u]=="function"&&i[u].prototype instanceof xe);l.length>0&&(c=i[l[0]],console.log(`\u2713 Using workflow: ${l[0]} (auto-detected)`))}if(!c)return{agent:null,error:"Could not find any WorkflowAgent export in local graph.js"};c.name?.includes("auto-detected")||console.log("\u2713 Using local agent from .zibby/graph.mjs")}return{agent:new c(e),error:null}}catch(t){return{agent:null,error:t.message}}}var mn=class{constructor(e={}){this.config=e}async run(e){return Ai(e.spec||e.specPath,{...this.config,...e})}};export{hn as AGENT_TYPES,Cl as ALL_TOOLS,fe as AccessibilityEnricher,So as AgentStrategy,ce as AssistantStrategy,vo as CHAT_MEMORY_TOOLS,df as CI_ENV_VARS,yn as CORE_LOG_LEVELS,bo as CORE_TOOLS,ne as ClaudeAgentStrategy,se as CodexAgentStrategy,re as CursorAgentStrategy,Vo as DEFAULT_MAX_CONCURRENT_RUNS,G as DEFAULT_MODELS,af as DEFAULT_OUTPUT_BASE,$e as DOMEnricher,ff as EVENTS_FILE,Q as EnrichmentPipeline,z as EventEnricher,xo as GITHUB_TOOLS,ie as GeminiAgentStrategy,wo as JIRA_TOOLS,Y as LOG_LEVELS,Yt as LiveEnrichmentRecorder,He as Logger,ei as MAX_MAX_CONCURRENT_RUNS,Ee as MCPRefStrategy,To as MEMORY_TOOLS,Qo as MIN_MAX_CONCURRENT_RUNS,Le as McpClientManager,ae as OpenAIToolProvider,de as PageStateEnricher,Ae as PlaywrightJsonVerificationStrategy,Ie as PositionEnricher,pf as RAW_OUTPUT_FILE,uf as RESULT_FILE,Xr as RIPPLE_EFFECT_SCRIPT,Eo as RUNNER_TOOLS,Lt as ResultHandler,cf as SESSIONS_DIR,lf as SESSION_INFO_FILE,Kp as SKILLS,Ao as SKILL_TOOLS,_o as SLACK_TOOLS,je as SelectorGenerator,Ft as StableIdRuntime,Te as StableIdStrategy,W as StreamingParser,mn as TestAutomation,V as TestGenerationStrategy,Dt as TestPostProcessor,ve as TestVerificationStrategy,ye as ToolCallProvider,ze as TraceParser,xe as WorkflowAgent,Pp as WorkflowGraph,Bt as ZibbyRuntime,Fe as ZibbyUploader,ee as buildRepoContextHint,ro as checkCursorAgentInstalled,zo as checkCursorAgentPatched,Np as clearInheritedSessionEnvForFreshRun,ko as clearTokenCache,yi as createCustomPipeline,zt as createDefaultPipeline,Jt as createMinimalPipeline,Hr as createUploader,bi as enrichRecordedEvents,Mn as ensureRepo,Wo as generateRippleHelperCode,Rp as generateWorkflowSessionId,Jr as getAgentStrategy,Xp as getAllSkills,Jo as getApprovalKeys,no as getCursorAgentInstallInstructions,ht as getRepo,Wp as getSkill,Zp as hasSkill,Ho as injectRippleEffect,yo as invokeAgent,Xe as listRepos,qp as listSkillIds,Ip as listWorkflows,f as logger,Uo as organizeVideos,Go as patchCursorAgentForCI,J as pickFromPool,oi as postProcessEvents,Mp as readPinnedSessionPathFromEnv,Tt as registerBuiltInStrategies,Hp as registerSkill,kn as repoPath,ui as resetExecutionCount,No as resolveIntegrationToken,ti as resolveMaxParallelRuns,Cp as resolveWorkflowSession,nn as runPlaywrightTestTool,Ai as runTest,Yo as saveApprovalKeys,kp as shouldTrustInheritedSessionEnv,Lp as syncProcessEnvToSession,di as testGenerationManager,hi as testVerificationManager,Z as timeline,mo as workflow,Bp as z};