@zibby/core 0.4.6 → 0.5.1

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.
Files changed (78) hide show
  1. package/dist/index.js +150 -153
  2. package/dist/package.json +2 -9
  3. package/dist/utils/run-index-post-cli.js +1 -4
  4. package/package.json +2 -9
  5. package/dist/templates/browser-test-automation/README.md +0 -136
  6. package/dist/templates/browser-test-automation/chat.mjs +0 -36
  7. package/dist/templates/browser-test-automation/graph.mjs +0 -80
  8. package/dist/templates/browser-test-automation/nodes/cache-replay.mjs +0 -213
  9. package/dist/templates/browser-test-automation/nodes/execute-live.mjs +0 -254
  10. package/dist/templates/browser-test-automation/nodes/generate-script.mjs +0 -108
  11. package/dist/templates/browser-test-automation/nodes/index.mjs +0 -4
  12. package/dist/templates/browser-test-automation/nodes/preflight.mjs +0 -94
  13. package/dist/templates/browser-test-automation/nodes/utils.mjs +0 -297
  14. package/dist/templates/browser-test-automation/pipeline-ids.js +0 -12
  15. package/dist/templates/browser-test-automation/result-handler.mjs +0 -327
  16. package/dist/templates/browser-test-automation/run-index.mjs +0 -420
  17. package/dist/templates/browser-test-automation/run_test.json +0 -358
  18. package/dist/templates/browser-test-automation/state.js +0 -61
  19. package/dist/templates/code-analysis/README.md +0 -60
  20. package/dist/templates/code-analysis/graph.js +0 -72
  21. package/dist/templates/code-analysis/graph.mjs +0 -33
  22. package/dist/templates/code-analysis/index.js +0 -18
  23. package/dist/templates/code-analysis/nodes/analyze-ticket-node.js +0 -204
  24. package/dist/templates/code-analysis/nodes/create-pr-node.js +0 -175
  25. package/dist/templates/code-analysis/nodes/finalize-node.js +0 -118
  26. package/dist/templates/code-analysis/nodes/generate-code-node.js +0 -425
  27. package/dist/templates/code-analysis/nodes/generate-test-cases-node.js +0 -376
  28. package/dist/templates/code-analysis/nodes/services/prMetaService.js +0 -86
  29. package/dist/templates/code-analysis/nodes/setup-node.js +0 -142
  30. package/dist/templates/code-analysis/prompts/analyze-ticket.md +0 -181
  31. package/dist/templates/code-analysis/prompts/generate-code.md +0 -33
  32. package/dist/templates/code-analysis/prompts/generate-test-cases.md +0 -110
  33. package/dist/templates/code-analysis/state.js +0 -48
  34. package/dist/templates/generate-test-cases/README.md +0 -72
  35. package/dist/templates/generate-test-cases/graph.mjs +0 -46
  36. package/dist/templates/generate-test-cases/nodes/generate-test-cases-node.js +0 -381
  37. package/dist/templates/generate-test-cases/nodes/setup-node.js +0 -142
  38. package/dist/templates/generate-test-cases/state.js +0 -54
  39. package/dist/templates/global-setup.js +0 -56
  40. package/dist/templates/index.js +0 -147
  41. package/dist/templates/register-nodes.js +0 -24
  42. package/templates/browser-test-automation/README.md +0 -136
  43. package/templates/browser-test-automation/chat.mjs +0 -36
  44. package/templates/browser-test-automation/graph.mjs +0 -80
  45. package/templates/browser-test-automation/nodes/cache-replay.mjs +0 -213
  46. package/templates/browser-test-automation/nodes/execute-live.mjs +0 -254
  47. package/templates/browser-test-automation/nodes/generate-script.mjs +0 -108
  48. package/templates/browser-test-automation/nodes/index.mjs +0 -4
  49. package/templates/browser-test-automation/nodes/preflight.mjs +0 -94
  50. package/templates/browser-test-automation/nodes/utils.mjs +0 -297
  51. package/templates/browser-test-automation/pipeline-ids.js +0 -12
  52. package/templates/browser-test-automation/result-handler.mjs +0 -327
  53. package/templates/browser-test-automation/run-index.mjs +0 -420
  54. package/templates/browser-test-automation/run_test.json +0 -358
  55. package/templates/browser-test-automation/state.js +0 -61
  56. package/templates/code-analysis/README.md +0 -60
  57. package/templates/code-analysis/graph.js +0 -72
  58. package/templates/code-analysis/graph.mjs +0 -33
  59. package/templates/code-analysis/index.js +0 -18
  60. package/templates/code-analysis/nodes/analyze-ticket-node.js +0 -204
  61. package/templates/code-analysis/nodes/create-pr-node.js +0 -175
  62. package/templates/code-analysis/nodes/finalize-node.js +0 -118
  63. package/templates/code-analysis/nodes/generate-code-node.js +0 -425
  64. package/templates/code-analysis/nodes/generate-test-cases-node.js +0 -376
  65. package/templates/code-analysis/nodes/services/prMetaService.js +0 -86
  66. package/templates/code-analysis/nodes/setup-node.js +0 -142
  67. package/templates/code-analysis/prompts/analyze-ticket.md +0 -181
  68. package/templates/code-analysis/prompts/generate-code.md +0 -33
  69. package/templates/code-analysis/prompts/generate-test-cases.md +0 -110
  70. package/templates/code-analysis/state.js +0 -48
  71. package/templates/generate-test-cases/README.md +0 -72
  72. package/templates/generate-test-cases/graph.mjs +0 -46
  73. package/templates/generate-test-cases/nodes/generate-test-cases-node.js +0 -381
  74. package/templates/generate-test-cases/nodes/setup-node.js +0 -142
  75. package/templates/generate-test-cases/state.js +0 -54
  76. package/templates/global-setup.js +0 -56
  77. package/templates/index.js +0 -147
  78. package/templates/register-nodes.js +0 -24
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- var En=(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 yn,existsSync as Sn}from"node:fs";import{join as Pe,resolve as bn,isAbsolute as Ci}from"node:path";import{DEFAULT_OUTPUT_BASE as Ni,SESSIONS_DIR as wn,RESULT_FILE as Ri,resolveWorkflowSession as ki,clearInheritedSessionEnvForFreshRun as Mi,readPinnedSessionPathFromEnv as Li}from"@zibby/agent-workflow";import{registerStrategy as Be}from"@zibby/agent-workflow";import{AgentStrategy as Kn,DEFAULT_OUTPUT_BASE as Jn,SESSION_INFO_FILE as zn,STOP_REQUEST_FILE as Yn,getAllSkills as Hn,getSkill as sr}from"@zibby/agent-workflow";import{spawn as Zn,execSync as re}from"node:child_process";import{writeFileSync as or,readFileSync as ir,mkdirSync as ar,existsSync as ke,accessSync as cr,constants as lr,unlinkSync as Wn}from"node:fs";import{join as W,resolve as Xn}from"node:path";import{homedir as Me}from"node:os";import Re from"chalk";var Z={debug:0,info:1,warn:2,error:3,silent:4},Xe=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return Z.debug;if(process.env.ZIBBY_VERBOSE==="true")return Z.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in Z?Z[e]:Z.info}_shouldLog(e){return Z[e]>=this._level}_formatMessage(e,t,r={}){let n=new Date().toISOString(),i=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(i+=Re.dim(` ${JSON.stringify(r)}`)),i}_getPrefix(e){return{debug:Re.gray("[DEBUG]"),info:Re.cyan("[INFO]"),warn:Re.yellow("[WARN]"),error:Re.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 Z&&(this._level=Z[e])}getLevel(){return Object.keys(Z).find(e=>Z[e]===this._level)}},f=new Xe;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"},Tn={ASSISTANT:"assistant",CLAUDE:"claude",CURSOR:"cursor",CODEX:"codex",GEMINI:"gemini"},vn={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"},Vt={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},qe={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var X=class o{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(e){if(!e)return null;this.buffer+=e;let t=this.buffer.split(`
2
- `);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 l=i.substring(this.rawText.length);this.rawText=i,r+=l}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 Hr=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});import{readFileSync as Br,existsSync as Gr}from"node:fs";import{join as $e,resolve as Kr,isAbsolute as Ds}from"node:path";import{DEFAULT_OUTPUT_BASE as Fs,SESSIONS_DIR as Jr,RESULT_FILE as js,resolveWorkflowSession as Bs,clearInheritedSessionEnvForFreshRun as Gs,readPinnedSessionPathFromEnv as Ks}from"@zibby/agent-workflow";import{registerStrategy as Me}from"@zibby/agent-workflow";import{AgentStrategy as mn,DEFAULT_OUTPUT_BASE as gn,SESSION_INFO_FILE as hn,STOP_REQUEST_FILE as yn,getAllSkills as Sn,getSkill as Kt}from"@zibby/agent-workflow";import{spawn as bn,execSync as te}from"node:child_process";import{writeFileSync as Jt,readFileSync as zt,mkdirSync as Yt,existsSync as Pe,accessSync as Ht,constants as Wt,unlinkSync as wn}from"node:fs";import{join as W,resolve as _n}from"node:path";import{homedir as ke}from"node:os";import Ce from"chalk";var H={debug:0,info:1,warn:2,error:3,silent:4},ze=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return H.debug;if(process.env.ZIBBY_VERBOSE==="true")return H.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in H?H[e]:H.info}_shouldLog(e){return H[e]>=this._level}_formatMessage(e,t,r={}){let n=new Date().toISOString(),s=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(s+=Ce.dim(` ${JSON.stringify(r)}`)),s}_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 H&&(this._level=H[e])}getLevel(){return Object.keys(H).find(e=>H[e]===this._level)}},p=new ze;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"},Wr={ASSISTANT:"assistant",CLAUDE:"claude",CURSOR:"cursor",CODEX:"codex",GEMINI:"gemini"},Zr={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error",SILENT:"silent"},st={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"},it={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"},Ut={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},Ye={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var Z=class i{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 o=JSON.parse(n);this._emitToolCalls(o);let s=this.extractText(o);if(s){if(this.rawText&&s.startsWith(this.rawText)){let c=s.substring(this.rawText.length);this.rawText=s,r+=c}else(!this.rawText.includes(s)||s.length<20)&&(this.rawText+=s,r+=s);this.tryExtractResult(this.rawText)}else this.isValidResult(o)&&(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*"([^"]*)/),l=n.match(/"content"\s*:\s*"([^"]*)/),c=i?i[1]:l?l[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,l)=>{if(!i)return;let c=`${i}:${JSON.stringify(l??{})}`;this._lastToolEmit!==c&&(this._lastToolEmit=c,this.onToolCall(i,l??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 l=Object.keys(i);if(l.length===1){let c=l[0],a=i[c],u=a&&typeof a=="object"?a.args??a.input??a: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 l=this.extractedResult,c=l?JSON.stringify(l).length:0,a=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)&&(a++,c=JSON.stringify(g).length,l=g,u=m)}catch{}}l&&(this.extractedResult=l)}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 An}from"zod-to-json-schema";var Ve=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=An(e,{target:"openApi3"}):r=e;let n=this._buildExample(r);return`
4
+ `,this.extractedResult=o)}catch{if(n.includes('"text"')||n.includes('"content"')){let s=n.match(/"text"\s*:\s*"([^"]*)/),c=n.match(/"content"\s*:\s*"([^"]*)/),a=s?s[1]:c?c[1]:null;a&&!this.rawText.includes(a)&&(r+=a,this.rawText+=a)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(s,c)=>{if(!s)return;let a=`${s}:${JSON.stringify(c??{})}`;this._lastToolEmit!==a&&(this._lastToolEmit=a,this.onToolCall(s,c??void 0))},r=s=>{if(s!=null){if(typeof s=="object"&&!Array.isArray(s))return s;if(typeof s=="string")try{return JSON.parse(s)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,r(e.input??e.arguments));return}let s=e.tool_call;if(s&&typeof s=="object"&&!Array.isArray(s)){let c=Object.keys(s);if(c.length===1){let a=c[0],l=s[a],u=l&&typeof l=="object"?l.args??l.input??l:void 0;t(a,r(u))}return}return}if(Array.isArray(e.tool_calls)){for(let s of e.tool_calls)t(s.name,r(s.input??s.arguments));return}let n=e.message??e;if(Array.isArray(n?.tool_calls)){for(let s of n.tool_calls)t(s.name,r(s.input??s.arguments));return}let o=n?.content??e.content;if(Array.isArray(o))for(let s of o)(s.type==="tool_use"||s.type==="tool_call")&&s.name&&t(s.name,r(s.input??s.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 o=0,s=0;for(;o<e.length&&(o=e.indexOf("{",o),o!==-1);){let m=0,d=o;for(let f=o;f<e.length;f++)if(e[f]==="{")m++;else if(e[f]==="}"&&(m--,m===0)){d=f,t.push({text:e.substring(o,d+1),source:"brace"}),s++;break}o=d+1}let c=this.extractedResult,a=c?JSON.stringify(c).length:0,l=0,u=-1;for(let m=0;m<t.length;m++){let d=t[m];try{let f=d.text.replace(/,(\s*[}\]])/g,"$1"),g=JSON.parse(f);this.isValidResult(g)&&(l++,a=JSON.stringify(g).length,c=g,u=m)}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 i;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 Xr}from"zod-to-json-schema";var He=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=Xr(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 ge=class o{constructor(e=""){this.userPrompt=e,this.systemInstructions=[],this.metadata={}}setUserPrompt(e){return this.userPrompt=e,this}appendUserPrompt(e){return this.userPrompt?this.userPrompt+=`
24
+ Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(e){if(!e)return{};let t=e.type;if(t==="object"&&e.properties){let r={};for(let[n,o]of Object.entries(e.properties))r[n]=this._buildExample(o);return r}if(t==="array"&&e.items)return[this._buildExample(e.items)];if(e.enum&&Array.isArray(e.enum)&&e.enum.length>0)return`<${e.enum.join("|")}>`;if(t==="string")return"<string>";if(t==="number"||t==="integer")return 0;if(t==="boolean")return!1;if(e.description)return`<${e.description}>`;if(e.nullable||e.oneOf||e.anyOf){let r=e.oneOf?.find(n=>n.type!=="null")||e.anyOf?.find(n=>n.type!=="null");return r?this._buildExample(r):null}return"<value>"}};var fe=class i{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=Ve.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=He.generateFileOutputInstructions(e,t);this.systemInstructions.push({type:"structured_output",content:r,position:"append"}),this.metadata.structuredOutputPath=t}return this}addExtraInstructions(e){if(e?.trim()){let t=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
27
27
  \u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
28
28
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
29
29
 
@@ -31,18 +31,18 @@ ${e.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:t,p
31
31
 
32
32
  `),position:"append"}),this}addSystemInstruction(e,t="custom",r="append"){return e&&this.systemInstructions.push({type:t,content:e,position:r}),this}getUserPrompt(){return this.userPrompt}getSystemInstructions(){return this.systemInstructions}getMetadata(){return this.metadata}build(){let e=this.systemInstructions.filter(n=>n.position==="prepend").map(n=>n.content),t=this.systemInstructions.filter(n=>n.position==="append").map(n=>n.content);return[...e,this.userPrompt,...t].filter(Boolean).join(`
33
33
 
34
- `)}getStats(){let e=this.userPrompt.length,t=this.build().length;return{userPromptLength:e,fullPromptLength:t,systemInstructionsLength:t-e,instructionCount:this.systemInstructions.length,instructionTypes:this.systemInstructions.map(r=>r.type)}}clone(){let e=new o(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};import In from"axios";import{homedir as $n}from"node:os";import{join as On}from"node:path";import{existsSync as Pn,readFileSync as Cn}from"node:fs";import{toJSONSchema as Nn}from"zod";function Rn(){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=On($n(),".zibby","config.json");if(Pn(o)){let e=JSON.parse(Cn(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 kn(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function he(o){if(!(typeof o!="object"||o===null)){if(Object.keys(o).length===0){o.type="object",o.additionalProperties=!0;return}if(o.type||(o.properties?o.type="object":o.items&&(o.type="array")),o.type==="object")if(o.properties){for(let[e,t]of Object.entries(o.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(o.properties[e]={type:["object","null"]});o.additionalProperties=!1,o.required=Object.keys(o.properties),Object.values(o.properties).forEach(he)}else"additionalProperties"in o||(o.additionalProperties=!0);o.type==="array"&&o.items&&he(o.items),o.anyOf&&o.anyOf.forEach(he),o.oneOf&&o.oneOf.forEach(he),o.allOf&&o.allOf.forEach(he)}}async function Qt(o,e){f.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=Rn();if(!t)throw new Error("Authentication required for structured output processing.\n Local development: Run `zibby login`\n CI/CD: Set ZIBBY_USER_TOKEN environment variable (Personal Access Token from UI settings)");let r=kn();f.info(`\u{1F517} Using OpenAI proxy: ${r}`);let n=Nn(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,he(s);let i=4e5,l=o;o.length>i&&(f.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${o.length} chars) exceeds limit, keeping last ${i} chars`),l=`... [truncated early content] ...
35
- ${o.slice(-i)}`);let c=`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 i(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};import qr from"axios";import{homedir as Vr}from"node:os";import{join as Qr}from"node:path";import{existsSync as en,readFileSync as tn}from"node:fs";import{toJSONSchema as rn}from"zod";function nn(){if(process.env.OPENAI_PROXY_TOKEN)return p.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return p.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let i=Qr(Vr(),".zibby","config.json");if(en(i)){let e=JSON.parse(tn(i,"utf-8"));if(e.sessionToken)return p.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(i){p.debug(`[Auth] Could not read zibby login session: ${i.message}`)}return null}function on(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function de(i){if(!(typeof i!="object"||i===null)){if(Object.keys(i).length===0){i.type="object",i.additionalProperties=!0;return}if(i.type||(i.properties?i.type="object":i.items&&(i.type="array")),i.type==="object")if(i.properties){for(let[e,t]of Object.entries(i.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(i.properties[e]={type:["object","null"]});i.additionalProperties=!1,i.required=Object.keys(i.properties),Object.values(i.properties).forEach(de)}else"additionalProperties"in i||(i.additionalProperties=!0);i.type==="array"&&i.items&&de(i.items),i.anyOf&&i.anyOf.forEach(de),i.oneOf&&i.oneOf.forEach(de),i.allOf&&i.allOf.forEach(de)}}async function Dt(i,e){p.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=nn();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=on();p.info(`\u{1F517} Using OpenAI proxy: ${r}`);let n=rn(e),o=n;if(n.$ref&&n.definitions){let u=n.$ref.split("/").pop();o=n.definitions[u]||n,p.debug(`Extracted schema from $ref: ${u}`)}delete o.$schema,de(o);let s=4e5,c=i;i.length>s&&(p.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${i.length} chars) exceeds limit, keeping last ${s} chars`),c=`... [truncated early content] ...
35
+ ${i.slice(-s)}`);let a=`Extract and format the following information into structured JSON matching the schema.
36
36
 
37
37
  RAW CONTENT:
38
- ${l}
38
+ ${c}
39
39
 
40
- Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,a={model:J.OPENAI_POSTPROCESSING,messages:[{role:"user",content:c}],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: ${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 In.post(r,a,{headers:u,timeout:qe.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.
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:J.OPENAI_POSTPROCESSING,messages:[{role:"user",content:a}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:o,strict:!0}}};p.info(`\u{1F4E4} Sending to OpenAI proxy: model=${J.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(o.properties||{}).join(", ")}`),p.debug(` Schema size: ${JSON.stringify(o).length} chars`),p.debug(` Prompt size: ${a.length} chars`);try{let u={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(u["x-proxy-token"]=t,u["x-execution-id"]=process.env.EXECUTION_ID||""):(u.Authorization=`Bearer ${t}`,u["x-api-key"]=process.env.ZIBBY_API_KEY||"",u["x-execution-id"]=process.env.EXECUTION_ID||"");let d=(await qr.post(r,l,{headers:u,timeout:Ye.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!d)throw new Error("OpenAI proxy returned empty response");let f=JSON.parse(d);return p.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:f,raw:i}}catch(u){if(u.response){let m=u.response.status,d=u.response.data;throw p.error(`\u274C OpenAI proxy request failed: ${m}`),p.error(` Status: ${m}`),p.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(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})}}function Y(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 q,Timeline as ca,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as la}from"@zibby/agent-workflow";import{copyFileSync as Mn,existsSync as ht,lstatSync as Ln,mkdirSync as er,rmSync as Dn,symlinkSync as Un,unlinkSync as Bn}from"node:fs";import{join as V}from"node:path";import{homedir as Fn}from"node:os";import{randomBytes as jn}from"node:crypto";var Gn=["cli-config.json","config.json","auth.json","argv.json"];function tr(o){return!(!o||typeof o!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function rr(o){let e=V(o||process.cwd(),".zibby","tmp");er(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${jn(4).toString("hex")}`,r=V(e,`cursor-agent-home-${t}`),n=V(r,".cursor");er(n,{recursive:!0});let s=Fn(),i=V(s,".cursor");if(ht(i))for(let l of Gn){let c=V(i,l);if(ht(c))try{Mn(c,V(n,l))}catch{}}if(process.platform==="darwin"){let l=V(s,"Library");if(ht(l))try{Un(l,V(r,"Library"))}catch{}}return r}function nr(o){if(!(!o||typeof o!="string"))try{let e=V(o,"Library");try{Ln(e).isSymbolicLink()&&Bn(e)}catch{}Dn(o,{recursive:!0,force:!0})}catch{}}var ne=class extends Kn{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[W(Me(),".local","bin","cursor-agent"),W(Me(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"];for(let r of t)try{if(r.startsWith("/")){cr(r,lr.X_OK);let n=re(`"${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=re(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!n)continue;let s=re(`${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:l=null,nodeName:c=null,timeout:a=qe.CURSOR_AGENT_DEFAULT,config:u={},signal:m=null}=t,d=u?.agent?.strictMode||!1,p=t.model??u?.agent?.cursor?.model??J.CURSOR,g=Y("CURSOR_API_KEY");try{f.debug(`[Cursor] Invoking (model: ${p}, timeout: ${a/1e3}s, skills: ${JSON.stringify(i)})`);let h=(this._setupMcpConfig(l,r,u,i,c)||{}).isolatedMcpHome??null,S=[W(Me(),".local","bin","cursor-agent"),W(Me(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],w=null;for(let N of S)try{if(N.startsWith("/"))cr(N,lr.X_OK),re(`"${N}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!re(`which ${N}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");re(`${N} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}w=N,f.debug(`[Agent] Using binary: ${N}`);break}catch(x){f.debug(`[Agent] Binary '${N}' check failed: ${x.message}`);continue}if(!w)throw new Error(`Cursor Agent CLI not found or not working.
42
+ Response: ${JSON.stringify(d)}`,{cause:u}):new Error(`Failed to format Cursor output: ${d?.error?.message||"Unknown error"}`,{cause:u})}throw p.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}function Y(i){let e=`${i}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let r=t.split(/[,\n]+/).map(s=>s.trim()).filter(Boolean);if(r.length===0)return{picked:null,count:0,dispose:()=>{}};let n=r[Math.floor(Math.random()*r.length)],o=process.env[i];return process.env[i]=n,p.debug(`[auth-pool] ${i}: picked 1 of ${r.length} from pool (***${n.slice(-4)})`),{picked:n,count:r.length,dispose(){o===void 0?delete process.env[i]:process.env[i]=o}}}import{timeline as X,Timeline as gi,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as hi}from"@zibby/agent-workflow";import{copyFileSync as sn,existsSync as at,lstatSync as an,mkdirSync as Ft,rmSync as ln,symlinkSync as cn,unlinkSync as un}from"node:fs";import{join as q}from"node:path";import{homedir as pn}from"node:os";import{randomBytes as fn}from"node:crypto";var dn=["cli-config.json","config.json","auth.json","argv.json"];function jt(i){return!(!i||typeof i!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function Bt(i){let e=q(i||process.cwd(),".zibby","tmp");Ft(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${fn(4).toString("hex")}`,r=q(e,`cursor-agent-home-${t}`),n=q(r,".cursor");Ft(n,{recursive:!0});let o=pn(),s=q(o,".cursor");if(at(s))for(let c of dn){let a=q(s,c);if(at(a))try{sn(a,q(n,c))}catch{}}if(process.platform==="darwin"){let c=q(o,"Library");if(at(c))try{cn(c,q(r,"Library"))}catch{}}return r}function Gt(i){if(!(!i||typeof i!="string"))try{let e=q(i,"Library");try{an(e).isSymbolicLink()&&un(e)}catch{}ln(i,{recursive:!0,force:!0})}catch{}}var re=class extends mn{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[W(ke(),".local","bin","cursor-agent"),W(ke(),".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("/")){Ht(r,Wt.X_OK);let n=te(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(n&&n.length>0)return p.debug(`[Cursor] Found agent at: ${r} (version: ${n.trim().slice(0,50)})`),!0}else{let n=te(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!n)continue;let o=te(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(o&&o.length>0)return p.debug(`[Cursor] Found '${r}' in PATH at ${n} (version: ${o.trim().slice(0,50)})`),!0}}catch{continue}return p.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:r=process.cwd(),print:n=!1,schema:o=null,skills:s=null,sessionPath:c=null,nodeName:a=null,timeout:l=Ye.CURSOR_AGENT_DEFAULT,config:u={},signal:m=null}=t,d=u?.agent?.strictMode||!1,f=t.model??u?.agent?.cursor?.model??J.CURSOR,g=Y("CURSOR_API_KEY");try{p.debug(`[Cursor] Invoking (model: ${f}, timeout: ${l/1e3}s, skills: ${JSON.stringify(s)})`);let h=(this._setupMcpConfig(c,r,u,s,a)||{}).isolatedMcpHome??null,S=[W(ke(),".local","bin","cursor-agent"),W(ke(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],w=null;for(let k of S)try{if(k.startsWith("/"))Ht(k,Wt.X_OK),te(`"${k}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!te(`which ${k}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");te(`${k} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}w=k,p.debug(`[Agent] Using binary: ${k}`);break}catch(_){p.debug(`[Agent] Binary '${k}' check failed: ${_.message}`);continue}if(!w)throw new Error(`Cursor Agent CLI not found or not working.
43
43
 
44
44
  Checked paths:
45
- ${S.map(N=>` - ${N}`).join(`
45
+ ${S.map(k=>` - ${k}`).join(`
46
46
  `)}
47
47
 
48
48
  Install cursor-agent:
@@ -51,58 +51,55 @@ Install cursor-agent:
51
51
  Then add to PATH:
52
52
  echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
53
53
 
54
- Test with: agent --version`);let T=new ge(e),b=null;if(s){let N=`zibby-result-${Date.now()}.json`;b=W(r,".zibby","tmp",N);let x=W(r,".zibby","tmp");ke(x)||ar(x,{recursive:!0}),T.addStructuredOutput(s,b)}let $=process.env.CURSOR_API_KEY,k=$?` | key: ***${$.slice(-4)}`:" | key: not set";console.log(`
55
- \u25C6 Model: ${p||"auto"}${k}
56
- `);let R=(await import("chalk")).default,v=T.getUserPrompt();console.log(`
57
- ${R.bold("Prompt sent to LLM:")}`),console.log(R.dim("\u2500".repeat(60))),console.log(R.dim(v)),console.log(R.dim("\u2500".repeat(60)));let O=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(O),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 P,I=null;try{let N=l||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);P=await this._spawnWithStreaming(w,E,r,a,null,N,h,m)}catch(N){I=N}let C=P?.stdout||"";if(s){let N=typeof s.parse=="function",x=null,L=!!(b&&ke(b));if(b&&f.info(`[Agent] Result file: ${L?"present":"missing"} at ${b}`),L)try{let A=ir(b,"utf-8").trim();x=JSON.parse(A),f.info(`[Agent] Parsed JSON from result file OK (${A.length} chars) \u2192 object ready for validation`),I&&f.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(A){f.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${A.message}`)}else if(I)f.warn(`[Agent] Result file missing at ${b} (agent process error \u2014 may still recover if strictMode repairs)`);else throw f.error(`\u274C [Agent] Result file was never created at ${b}`),new Error(`Agent did not write required result file at ${b}`);if(x&&N)try{let A=s.parse(x);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:C,structured:A}}catch(A){let _=A.issues?A.issues.map(M=>` - ${M.path.join(".")}: ${M.message}`).join(`
59
- `):A.message?.slice(0,400);if(f.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
60
- ${_}`),f.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
61
- ${JSON.stringify(x,null,2).slice(0,500)}`),!d)throw new Error(`Agent output failed schema validation:
62
- ${_}
54
+ Test with: agent --version`);let T=new fe(e),b=null;if(o){let k=`zibby-result-${Date.now()}.json`;b=W(r,".zibby","tmp",k);let _=W(r,".zibby","tmp");Pe(_)||Yt(_,{recursive:!0}),T.addStructuredOutput(o,b)}let O=process.env.CURSOR_API_KEY,R=O?` | key: ***${O.slice(-4)}`:" | key: not set";console.log(`
55
+ \u25C6 Model: ${f||"auto"}${R}
56
+ `);let N=(await import("chalk")).default,v=T.getUserPrompt();console.log(`
57
+ ${N.bold("Prompt sent to LLM:")}`),console.log(N.dim("\u2500".repeat(60))),console.log(N.dim(v)),console.log(N.dim("\u2500".repeat(60)));let I=T.build(),U=T.getStats(),E=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",f||"auto"];if(process.env.CURSOR_API_KEY&&E.push("--api-key",process.env.CURSOR_API_KEY),E.push(I),p.debug(`[Agent] User prompt: ${U.userPromptLength} chars, System instructions: ${U.systemInstructionsLength} chars (${U.instructionCount} blocks), Full: ${U.fullPromptLength} chars, model: ${f||"auto"}`),p.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${f||"auto"} (from .zibby.config.js agent.cursor.model)
58
+ `)}catch{}let C,$=null;try{let k=c||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);C=await this._spawnWithStreaming(w,E,r,l,null,k,h,m)}catch(k){$=k}let P=C?.stdout||"";if(o){let k=typeof o.parse=="function",_=null,M=!!(b&&Pe(b));if(b&&p.info(`[Agent] Result file: ${M?"present":"missing"} at ${b}`),M)try{let A=zt(b,"utf-8").trim();_=JSON.parse(A),p.info(`[Agent] Parsed JSON from result file OK (${A.length} chars) \u2192 object ready for validation`),$&&p.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(A){p.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${A.message}`)}else if($)p.warn(`[Agent] Result file missing at ${b} (agent process error \u2014 may still recover if strictMode repairs)`);else throw p.error(`\u274C [Agent] Result file was never created at ${b}`),new Error(`Agent did not write required result file at ${b}`);if(_&&k)try{let A=o.parse(_);return p.info("\u2705 [Agent] Zod validation passed for structured result file"),d&&p.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:P,structured:A}}catch(A){let x=A.issues?A.issues.map(L=>` - ${L.path.join(".")}: ${L.message}`).join(`
59
+ `):A.message?.slice(0,400);if(p.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
60
+ ${x}`),p.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
61
+ ${JSON.stringify(_,null,2).slice(0,500)}`),!d)throw new Error(`Agent output failed schema validation:
62
+ ${x}
63
63
 
64
64
  The agent wrote invalid data that doesn't match the required outputSchema.
65
- Enable strictMode in .zibby.config.js for automatic repair.`,{cause:A})}else{if(x)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:C,structured:x};L&&f.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(d&&!I){let A=P.parsedText,_=x?JSON.stringify(x):A;f.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${_.length} chars in)`);try{let M=await Qt(_,s);if(N){let U=s.parse(M.structured);return f.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:C,structured:U}}return{raw:C,...M}}catch(M){if(f.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${M.message}`),x)return f.warn("[Agent] Using agent's original result file as fallback"),{raw:C,structured:x}}}if(I)throw I;let F=L?x==null?"file existed but JSON.parse failed \u2014 see WARN log above":N?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw f.error(`\u274C [Agent] No validated structured output: ${F}`),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 ${b}. Enable strictMode for proxy fallback.`)}if(I)throw I;return this._extractFinalResult(C)||P?.parsedText||C}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 l=i.message.content;if(Array.isArray(l)){let c=l.filter(a=>a.type==="text"&&a.text).map(a=>a.text).join("");c&&(r=c)}else typeof l=="string"&&l&&(r=l)}}catch{}}return r?.trim()||null}_setupMcpConfig(e,t,r,n=null,s=null){let i=r?.headless,l=W(Me(),".cursor"),c=W(l,"mcp.json"),a={};if(ke(c))try{a=JSON.parse(ir(c,"utf-8"))}catch{}let u=a.mcpServers||{},m=r?.paths?.output||Jn,d=W(t||process.cwd(),m,zn),p=Array.isArray(n)?n.map(h=>sr(h)).filter(Boolean):[...Hn()].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=sr("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)}
67
- `;if(tr(e)){let h=rr(t||process.cwd()),S=W(h,".cursor","mcp.json");return or(S,y,"utf8"),f.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${h} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:h}}return ke(l)||ar(l,{recursive:!0}),or(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 l=t.cursorKey||t.serverName,c=e[l]?l: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 a=t.resolve({sessionPath:r,nodeName:s,headless:i});a&&(e[l]={...a,...t.sessionEnvKey&&{env:{...a.env||{},[t.sessionEnvKey]:n}}},f.debug(`[MCP] Configured ${l}`))}_spawnWithStreaming(e,t,r,n,s=null,i=null,l=null,c=null){return new Promise((a,u)=>{let m=Date.now(),d="",p="",g=Date.now(),y=0,h=!1,S=null,w=!1,T=!1,b=null;if(i)try{b=W(Xn(String(i)),Yn)}catch{b=null}let $=!1,k=()=>{$||($=!0,nr(l))},R={...process.env};l&&(R.HOME=l,process.platform==="win32"&&(R.USERPROFILE=l),f.debug(`[Agent] cursor-agent HOME=${l} (isolated MCP config)`));let v=Zn(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:R,...c&&{signal:c}});f.debug(`[Agent] PID: ${v.pid}`);let O=null,D=()=>{h||T||(h=!0,S="aborted",f.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),O=setTimeout(()=>{if(!T){f.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{v.kill("SIGKILL")}catch{}}},5e3))};c&&(c.aborted?D():c.addEventListener("abort",D,{once:!0})),v.stdin.on("error",x=>{x.code!=="EPIPE"&&f.warn(`[Agent] stdin error: ${x.message}`)}),v.stdout.on("error",x=>{x.code!=="EPIPE"&&f.warn(`[Agent] stdout error: ${x.message}`)}),v.stderr.on("error",x=>{x.code!=="EPIPE"&&f.warn(`[Agent] stderr error: ${x.message}`)}),s?(v.stdin.write(s,x=>{x&&x.code!=="EPIPE"&&f.warn(`[Agent] Failed to write to stdin: ${x.message}`),v.stdin.end()}),f.debug(`[Agent] Prompt also piped to stdin (${s.length} chars)`)):v.stdin.end();let E=null;b&&(E=setInterval(()=>{if(!(h||T))try{if(ke(b)){h=!0,S="aborted";try{Wn(b)}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 P=new Set,I=new Date(m).toISOString().replace(/\.\d+Z$/,""),C=setInterval(()=>{let x=Math.round((Date.now()-m)/1e3),L=Math.round((Date.now()-g)/1e3),F=[];try{let _=Math.ceil(x/60)+1,M=re(`find "${r}" -type f -mmin -${_} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(M)for(let U of M.split(`
68
- `)){let B=U.replace(`${r}/`,"");P.has(B)||(P.add(B),F.push(B))}}catch{}let A="";F.length>0&&(A=` | \u{1F4C1} new: ${F.map(M=>M.split("/").pop()).join(", ")}`),P.size>0&&(A+=` | \u{1F4E6} total: ${P.size} files`),f.debug(`\u{1F493} [Agent] Running for ${x}s | ${y} lines output${A}`),y===0&&x>=30&&P.size===0&&(x<35&&f.warn(`\u26A0\uFE0F [Agent] No output after ${x}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),x>=60&&(h=!0,S=S||"stall",f.error(`\u274C [Agent] No response after ${x}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),v.kill("SIGTERM"),setTimeout(()=>{v.killed||v.kill("SIGKILL")},3e3)))},3e4),j=setTimeout(()=>{h=!0,S=S||"timeout";let x=Math.round((Date.now()-m)/1e3);f.error(`\u23F1\uFE0F [Agent] Timeout after ${x}s \u2014 killing process (PID: ${v.pid})`),d.trim()&&f.warn(`\u{1F4E4} [Agent] Partial output (${d.length} chars) before timeout:
69
- ${d.slice(-2e3)}`),v.kill("SIGTERM"),setTimeout(()=>{v.killed||v.kill("SIGKILL")},5e3)},n),N=new X;N.onToolCall=(x,L)=>{let F=x,A=L;if(x==="mcpToolCall"&&L?.name)F=L.name.replace(/^mcp_+[^_]+_+/,""),F.includes("-")&&F.split("-")[0]===F.split("-")[1]&&(F=F.split("-")[0]),A=L.args??L.input??L;else{if(x==="readToolCall"||x==="editToolCall"||x==="writeToolCall")return;(x.startsWith("mcp__")||x.includes("ToolCall"))&&(F=x.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(F.includes("memory")?q.stepMemory(`Tool: ${F}`):q.stepTool(`Tool: ${F}`),A!=null&&typeof A=="object"&&Object.keys(A).length>0&&!T){let M=JSON.stringify(A),U=M.length>100?`${M.substring(0,100)}...`:M;console.log(` Input: ${U}`)}},v.stdout.on("data",x=>{let L=x.toString();d+=L,g=Date.now(),w||(w=!0);let F=N.processChunk(L);F&&!T&&process.stdout.write(F);let A=L.split(`
70
- `).filter(_=>_.trim());y+=A.length}),v.stderr.on("data",x=>{let L=x.toString();p+=L,g=Date.now(),w||(w=!0);let F=L.split(`
71
- `).filter(A=>A.trim());for(let A of F)f.warn(`\u26A0\uFE0F [Agent stderr] ${A}`)}),v.on("close",(x,L)=>{if(T=!0,k(),clearTimeout(j),clearInterval(C),E&&clearInterval(E),O&&clearTimeout(O),c&&!c.aborted)try{c.removeEventListener("abort",D)}catch{}N.flush();let F=Math.round((Date.now()-m)/1e3);if(f.debug(`[Agent] Exited: code=${x}, signal=${L}, elapsed=${F}s, output=${d.length} chars`),h){if(S==="aborted"){let M=new Error("Aborted via signal");M.name="AbortError",u(M);return}u(new Error(`Cursor Agent timed out after ${F}s (limit: ${n/1e3}s). ${y} lines produced. Last output ${Math.round((Date.now()-g)/1e3)}s ago. ${d.trim()?`
65
+ Enable strictMode in .zibby.config.js for automatic repair.`,{cause:A})}else{if(_)return p.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),d&&p.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:P,structured:_};M&&p.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(d&&!$){let A=C.parsedText,x=_?JSON.stringify(_):A;p.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${x.length} chars in)`);try{let L=await Dt(x,o);if(k){let D=o.parse(L.structured);return p.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:P,structured:D}}return{raw:P,...L}}catch(L){if(p.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${L.message}`),_)return p.warn("[Agent] Using agent's original result file as fallback"),{raw:P,structured:_}}}if($)throw $;let j=M?_==null?"file existed but JSON.parse failed \u2014 see WARN log above":k?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw p.error(`\u274C [Agent] No validated structured output: ${j}`),p.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error(`Agent did not produce a valid result file at ${b}. Enable strictMode for proxy fallback.`)}if($)throw $;return this._extractFinalResult(P)||C?.parsedText||P}finally{g.dispose()}}_extractFinalResult(e){if(!e)return null;let t=e.split(`
66
+ `),r=null;for(let n of t){let o=n.trim();if(o)try{let s=JSON.parse(o);if(s.type==="assistant"&&s.message?.content){let c=s.message.content;if(Array.isArray(c)){let a=c.filter(l=>l.type==="text"&&l.text).map(l=>l.text).join("");a&&(r=a)}else typeof c=="string"&&c&&(r=c)}}catch{}}return r?.trim()||null}_setupMcpConfig(e,t,r,n=null,o=null){let s=r?.headless,c=W(ke(),".cursor"),a=W(c,"mcp.json"),l={};if(Pe(a))try{l=JSON.parse(zt(a,"utf-8"))}catch{}let u=l.mcpServers||{},m=r?.paths?.output||gn,d=W(t||process.cwd(),m,hn),f=Array.isArray(n)?n.map(h=>Kt(h)).filter(Boolean):[...Sn()].map(([,h])=>h),g=new Set;for(let h of f)typeof h.resolve=="function"&&(g.has(h.serverName)||(g.add(h.serverName),this._ensureSkillConfigured(u,h,e,d,o,s)));if(e){let h=Kt("browser");h&&typeof h.resolve=="function"&&!g.has(h.serverName)&&this._ensureSkillConfigured(u,h,e,d,"execute_live",s)}if(Object.keys(u).length===0)return p.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let y=`${JSON.stringify({mcpServers:u},null,2)}
67
+ `;if(jt(e)){let h=Bt(t||process.cwd()),S=W(h,".cursor","mcp.json");return Jt(S,y,"utf8"),p.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${h} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:h}}return Pe(c)||Yt(c,{recursive:!0}),Jt(a,y,"utf8"),p.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,n,o=null,s){let c=t.cursorKey||t.serverName,a=e[c]?c:e[t.serverName]?t.serverName:null;if(a&&r){let u=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:o,headless:s}):null;u?.args?e[a].args=u.args:e[a].args=(e[a].args||[]).map(f=>f.startsWith("--output-dir=")?`--output-dir=${r}`:f);let m=u?.env||{},d=t.sessionEnvKey?{[t.sessionEnvKey]:n}:{};e[a].env={...e[a].env||{},...m,...d},p.debug(`[MCP] Updated ${a} session \u2192 ${r}`);return}if(a)return;let l=t.resolve({sessionPath:r,nodeName:o,headless:s});l&&(e[c]={...l,...t.sessionEnvKey&&{env:{...l.env||{},[t.sessionEnvKey]:n}}},p.debug(`[MCP] Configured ${c}`))}_spawnWithStreaming(e,t,r,n,o=null,s=null,c=null,a=null){return new Promise((l,u)=>{let m=Date.now(),d="",f="",g=Date.now(),y=0,h=!1,S=null,w=!1,T=!1,b=null;if(s)try{b=W(_n(String(s)),yn)}catch{b=null}let O=!1,R=()=>{O||(O=!0,Gt(c))},N={...process.env};c&&(N.HOME=c,process.platform==="win32"&&(N.USERPROFILE=c),p.debug(`[Agent] cursor-agent HOME=${c} (isolated MCP config)`));let v=bn(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:N,...a&&{signal:a}});p.debug(`[Agent] PID: ${v.pid}`);let I=null,U=()=>{h||T||(h=!0,S="aborted",p.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),I=setTimeout(()=>{if(!T){p.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{v.kill("SIGKILL")}catch{}}},5e3))};a&&(a.aborted?U():a.addEventListener("abort",U,{once:!0})),v.stdin.on("error",_=>{_.code!=="EPIPE"&&p.warn(`[Agent] stdin error: ${_.message}`)}),v.stdout.on("error",_=>{_.code!=="EPIPE"&&p.warn(`[Agent] stdout error: ${_.message}`)}),v.stderr.on("error",_=>{_.code!=="EPIPE"&&p.warn(`[Agent] stderr error: ${_.message}`)}),o?(v.stdin.write(o,_=>{_&&_.code!=="EPIPE"&&p.warn(`[Agent] Failed to write to stdin: ${_.message}`),v.stdin.end()}),p.debug(`[Agent] Prompt also piped to stdin (${o.length} chars)`)):v.stdin.end();let E=null;b&&(E=setInterval(()=>{if(!(h||T))try{if(Pe(b)){h=!0,S="aborted";try{wn(b)}catch{}p.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),v.kill("SIGTERM"),setTimeout(()=>{v.killed||v.kill("SIGKILL")},2e3)}}catch{}},600));let C=new Set,$=new Date(m).toISOString().replace(/\.\d+Z$/,""),P=setInterval(()=>{let _=Math.round((Date.now()-m)/1e3),M=Math.round((Date.now()-g)/1e3),j=[];try{let x=Math.ceil(_/60)+1,L=te(`find "${r}" -type f -mmin -${x} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(L)for(let D of L.split(`
68
+ `)){let F=D.replace(`${r}/`,"");C.has(F)||(C.add(F),j.push(F))}}catch{}let A="";j.length>0&&(A=` | \u{1F4C1} new: ${j.map(L=>L.split("/").pop()).join(", ")}`),C.size>0&&(A+=` | \u{1F4E6} total: ${C.size} files`),p.debug(`\u{1F493} [Agent] Running for ${_}s | ${y} lines output${A}`),y===0&&_>=30&&C.size===0&&(_<35&&p.warn(`\u26A0\uFE0F [Agent] No output after ${_}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),_>=60&&(h=!0,S=S||"stall",p.error(`\u274C [Agent] No response after ${_}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),v.kill("SIGTERM"),setTimeout(()=>{v.killed||v.kill("SIGKILL")},3e3)))},3e4),B=setTimeout(()=>{h=!0,S=S||"timeout";let _=Math.round((Date.now()-m)/1e3);p.error(`\u23F1\uFE0F [Agent] Timeout after ${_}s \u2014 killing process (PID: ${v.pid})`),d.trim()&&p.warn(`\u{1F4E4} [Agent] Partial output (${d.length} chars) before timeout:
69
+ ${d.slice(-2e3)}`),v.kill("SIGTERM"),setTimeout(()=>{v.killed||v.kill("SIGKILL")},5e3)},n),k=new Z;k.onToolCall=(_,M)=>{let j=_,A=M;if(_==="mcpToolCall"&&M?.name)j=M.name.replace(/^mcp_+[^_]+_+/,""),j.includes("-")&&j.split("-")[0]===j.split("-")[1]&&(j=j.split("-")[0]),A=M.args??M.input??M;else{if(_==="readToolCall"||_==="editToolCall"||_==="writeToolCall")return;(_.startsWith("mcp__")||_.includes("ToolCall"))&&(j=_.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(j.includes("memory")?X.stepMemory(`Tool: ${j}`):X.stepTool(`Tool: ${j}`),A!=null&&typeof A=="object"&&Object.keys(A).length>0&&!T){let L=JSON.stringify(A),D=L.length>100?`${L.substring(0,100)}...`:L;console.log(` Input: ${D}`)}},v.stdout.on("data",_=>{let M=_.toString();d+=M,g=Date.now(),w||(w=!0);let j=k.processChunk(M);j&&!T&&process.stdout.write(j);let A=M.split(`
70
+ `).filter(x=>x.trim());y+=A.length}),v.stderr.on("data",_=>{let M=_.toString();f+=M,g=Date.now(),w||(w=!0);let j=M.split(`
71
+ `).filter(A=>A.trim());for(let A of j)p.warn(`\u26A0\uFE0F [Agent stderr] ${A}`)}),v.on("close",(_,M)=>{if(T=!0,R(),clearTimeout(B),clearInterval(P),E&&clearInterval(E),I&&clearTimeout(I),a&&!a.aborted)try{a.removeEventListener("abort",U)}catch{}k.flush();let j=Math.round((Date.now()-m)/1e3);if(p.debug(`[Agent] Exited: code=${_}, signal=${M}, elapsed=${j}s, output=${d.length} chars`),h){if(S==="aborted"){let L=new Error("Aborted via signal");L.name="AbortError",u(L);return}u(new Error(`Cursor Agent timed out after ${j}s (limit: ${n/1e3}s). ${y} lines produced. Last output ${Math.round((Date.now()-g)/1e3)}s ago. ${d.trim()?`
72
72
  Partial output (last 500 chars):
73
- ${d.slice(-500)}`:"No output captured."}`));return}if(x!==0){u(new Error(`Cursor Agent failed: exit code ${x}, signal ${c}. ${p.trim()?`
74
- Stderr: ${p.slice(-1e3)}`:""}${d.trim()?`
75
- Stdout (last 500 chars): ${d.slice(-500)}`:""}`));return}let A=N.getResult(),_=A?JSON.stringify(A,null,2):N.getRawText()||d||"";a({stdout:d||p||"",parsedText:_})}),v.on("error",x=>{if(k(),clearTimeout(j),clearInterval(C),E&&clearInterval(E),O&&clearTimeout(O),c&&!c.aborted)try{c.removeEventListener("abort",D)}catch{}u(new Error(`Cursor Agent spawn error: ${x.message}
73
+ ${d.slice(-500)}`:"No output captured."}`));return}if(_!==0){u(new Error(`Cursor Agent failed: exit code ${_}, signal ${a}. ${f.trim()?`
74
+ Stderr: ${f.slice(-1e3)}`:""}${d.trim()?`
75
+ Stdout (last 500 chars): ${d.slice(-500)}`:""}`));return}let A=k.getResult(),x=A?JSON.stringify(A,null,2):k.getRawText()||d||"";l({stdout:d||f||"",parsedText:x})}),v.on("error",_=>{if(R(),clearTimeout(B),clearInterval(P),E&&clearInterval(E),I&&clearTimeout(I),a&&!a.aborted)try{a.removeEventListener("abort",U)}catch{}u(new Error(`Cursor Agent spawn error: ${_.message}
76
76
  Binary: ${e}
77
77
  This usually means the binary is not in PATH. Try:
78
- echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};import{AgentStrategy as qn,getSkill as Vn}from"@zibby/agent-workflow";import{query as Qn}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as es}from"zod-to-json-schema";import{writeFileSync as yt,mkdirSync as St,existsSync as ur,readFileSync as pr}from"fs";import{homedir as fr}from"os";import{join as ye}from"path";var se=class extends qn{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:l=null,sessionPath:c=null,nodeName:a=null,timeout:u,config:m={},signal:d=null,sessionId:p,resume:g,forkSession:y,sessionStore:h}=t,S=r;(!S||S==="auto")&&(f.debug(`Model is '${S||"undefined"}', using default: ${J.CLAUDE}`),S=J.CLAUDE);let w=mt[S]||S;mt[S]&&S!==w&&f.debug(`Mapped model: ${S} \u2192 ${w}`);let T=[Y("ANTHROPIC_API_KEY"),Y("CLAUDE_CODE_OAUTH_TOKEN"),Y("ANTHROPIC_AUTH_TOKEN")];try{f.debug(`Invoking Claude Agent SDK with model: ${w}, skills: ${JSON.stringify(l)}`);let b=process.env.CLAUDE_CODE_OAUTH_TOKEN,$=process.env.ANTHROPIC_API_KEY,k=process.env.ANTHROPIC_AUTH_TOKEN;process.env.CLAUDE_CODE_CREDENTIALS_JSON?ns(process.env.CLAUDE_CODE_CREDENTIALS_JSON):b&&rs(b,process.env.__ZIBBY_CLAUDE_PLAN);let R=process.env.__ZIBBY_CLAUDE_PLAN,v=R?R.charAt(0).toUpperCase()+R.slice(1):null,O;b?O=v?`Claude ${v} plan \xB7 ***${b.slice(-4)}`:`Subscription \xB7 ***${b.slice(-4)}`:$?O=`API key \xB7 ***${$.slice(-4)}`:k?O=`Bearer \xB7 ***${k.slice(-4)}`:O="NONE \u2014 request will fail";let D=(await import("chalk")).default;console.log(""),console.log(` ${D.cyan("\u25C6")} ${D.bold(w)}`),console.log(` ${D.dim("Auth: ")}${O}`),console.log(` ${D.dim("Workdir: ")}${n}`),console.log(""),console.log(D.bold("Prompt sent to LLM:")),console.log(D.dim("\u2500".repeat(60))),console.log(D.dim(e)),console.log(D.dim("\u2500".repeat(60)));let{allowedTools:E,mcpServers:P}=this._resolveSkills(l,{sessionPath:c,workspace:n,nodeName:a});try{let I={cwd:n,allowedTools:E,settings:{permissions:{allow:["Bash(*)","Read(*)","Write(*)","Edit(*)","MultiEdit(*)","NotebookEdit(*)","Grep(*)","Glob(*)","WebFetch(*)","WebSearch(*)","Task(*)","TodoWrite(*)","Skill(*)"]}},model:w,...Object.keys(P).length>0&&{mcpServers:P},...p&&{sessionId:p},...g&&{resume:g},...y&&{forkSession:!0},...h&&{sessionStore:h}};if(s){let M=typeof s.parse=="function"?es(s,{target:"openApi3"}):s;I.outputFormat={type:"json_schema",schema:M},f.debug("Structured output enforced via SDK outputFormat")}f.debug(`Agent SDK options: ${JSON.stringify({cwd:I.cwd,toolCount:E.length,permissionMode:I.permissionMode,model:I.model,hasOutputFormat:!!I.outputFormat})}`);let C="",j=0,N=[];f.debug("Starting Claude Agent SDK query stream");let x;try{x=Qn({prompt:e,options:I})}catch(_){throw f.error(`Failed to initialize Claude Agent SDK: ${_.message}`),_}let L=null,F=0,A=3;if(d?.aborted){let _=new Error("Aborted via signal");throw _.name="AbortError",_}try{for await(let _ of x){if(d?.aborted){let U=new Error("Aborted via signal");throw U.name="AbortError",U}if(N.push(_),_.type==="system"&&_.subtype==="init"){let U=_.mcp_servers||[];if(U.length>0){let B=U.map(G=>`${G.name}=${G.status}${G.error?` (${String(G.error).slice(0,120)})`:""}`).join(", ");f.info(`[mcp] SDK init \u2014 ${U.length} server(s): ${B}`);for(let G of U)G.status!=="connected"&&f.warn(`[mcp] server '${G.name}' did not connect: status=${G.status}`,{name:G.name,status:G.status,error:G.error})}else Object.keys(P||{}).length>0&&f.warn(`[mcp] SDK init returned no mcp_servers despite passing ${Object.keys(P).length} server(s) \u2014 SDK version may not expose this field, or config was dropped`);if(Array.isArray(_.tools)){let B=_.tools.filter(G=>G.startsWith("mcp__"));B.length>0?f.info(`[mcp] tools visible to model: ${B.join(", ")}`):Object.keys(P||{}).length>0&&f.warn("[mcp] no mcp__* tools in model's tool list \u2014 MCP servers configured but tools didn't reach the prompt")}}if(_.type==="error"||_.error){let U=_.error?.message||_.error||_.message||"Unknown API error";try{f.error("SDK error event raw payload",{fullMessage:JSON.stringify(_,null,2)})}catch{}throw new Error(typeof U=="string"?U:JSON.stringify(U))}let M=JSON.stringify(_.message?.content||_.text||"").slice(0,200);if(M===L){if(F++,F>=A){let U=(_.message?.content?.[0]?.text||_.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${F}x repeated): ${U}`)}}else L=M,F=1;if(_.type==="assistant"||_.constructor?.name==="AssistantMessage"){let U=_.message?.content||_.content||[];for(let B of U)if(B.type==="thinking"&&B.thinking)console.log(`${B.thinking.substring(0,200)}${B.thinking.length>200?"...":""}`);else if(B.type==="text"&&B.text)C+=B.text,B.text.length<500?console.log(`${B.text}`):console.log(`${B.text.substring(0,200)}... (${B.text.length} chars)`);else if(B.type==="tool_use"){j++,B.name.includes("memory")?q.stepMemory(`Tool: ${B.name}`):q.stepTool(`Tool: ${B.name}`);let Ce=JSON.stringify(B.input).substring(0,100);console.log(` Input: ${Ce}${JSON.stringify(B.input).length>100?"...":""}`)}}else if(!(_.type==="user"&&_.tool_use_result)){if(_.type==="result"||_.constructor?.name==="ResultMessage"){let U=_.result||_.text||_.content||C;try{ts({message:_,sessionPath:c,nodeName:a,model:S,toolCallCount:j})}catch(B){f.debug(`usage.json write failed: ${B.message}`)}if(s){if(_.structured_output){f.debug("Using SDK native structured_output");let G=typeof s.parse=="function"?s.parse(_.structured_output):_.structured_output;return{raw:U,structured:G}}if(U){let B=this._extractJson(U,s);if(B)return{raw:U,structured:B}}f.warn(`Could not extract structured output \u2014 returning raw text (${(U||"").length} chars)`)}return U||""}}}if(f.warn(`Agent SDK ended without result. Collected ${N.length} messages`),C.length>0)return f.debug("Returning accumulated text from messages"),C;throw new Error("Claude Agent SDK query ended without result")}catch(_){let M={message:_?.message,name:_?.name,code:_?.code,cause:_?.cause?.message||_?.cause,stack:_?.stack?.split(`
78
+ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};import{AgentStrategy as xn,getSkill as En}from"@zibby/agent-workflow";import{query as Tn}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as vn}from"zod-to-json-schema";import{writeFileSync as lt,mkdirSync as ct,existsSync as Zt,readFileSync as Xt}from"fs";import{homedir as qt}from"os";import{join as me}from"path";var ne=class extends xn{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!process.env.ANTHROPIC_API_KEY||!!process.env.ANTHROPIC_API_KEY_POOL,r=!!process.env.CLAUDE_CODE_OAUTH_TOKEN||!!process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,n=!!process.env.ANTHROPIC_AUTH_TOKEN||!!process.env.ANTHROPIC_AUTH_TOKEN_POOL,o=t||r||n;return o||p.debug("ClaudeAgentStrategy: no credentials. Set one of ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_AUTH_TOKEN (or a *_POOL variant for multi-token rotation)."),o}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:o=null,images:s=[],skills:c=null,sessionPath:a=null,nodeName:l=null,timeout:u,config:m={},signal:d=null,sessionId:f,resume:g,forkSession:y,sessionStore:h}=t,S=r;(!S||S==="auto")&&(p.debug(`Model is '${S||"undefined"}', using default: ${J.CLAUDE}`),S=J.CLAUDE);let w=st[S]||S;st[S]&&S!==w&&p.debug(`Mapped model: ${S} \u2192 ${w}`);let T=[Y("ANTHROPIC_API_KEY"),Y("CLAUDE_CODE_OAUTH_TOKEN"),Y("ANTHROPIC_AUTH_TOKEN")];try{p.debug(`Invoking Claude Agent SDK with model: ${w}, skills: ${JSON.stringify(c)}`);let b=process.env.CLAUDE_CODE_OAUTH_TOKEN,O=process.env.ANTHROPIC_API_KEY,R=process.env.ANTHROPIC_AUTH_TOKEN;process.env.CLAUDE_CODE_CREDENTIALS_JSON?On(process.env.CLAUDE_CODE_CREDENTIALS_JSON):b&&$n(b,process.env.__ZIBBY_CLAUDE_PLAN);let N=process.env.__ZIBBY_CLAUDE_PLAN,v=N?N.charAt(0).toUpperCase()+N.slice(1):null,I;b?I=v?`Claude ${v} plan \xB7 ***${b.slice(-4)}`:`Subscription \xB7 ***${b.slice(-4)}`:O?I=`API key \xB7 ***${O.slice(-4)}`:R?I=`Bearer \xB7 ***${R.slice(-4)}`:I="NONE \u2014 request will fail";let U=(await import("chalk")).default;console.log(""),console.log(` ${U.cyan("\u25C6")} ${U.bold(w)}`),console.log(` ${U.dim("Auth: ")}${I}`),console.log(` ${U.dim("Workdir: ")}${n}`),console.log(""),console.log(U.bold("Prompt sent to LLM:")),console.log(U.dim("\u2500".repeat(60))),console.log(U.dim(e)),console.log(U.dim("\u2500".repeat(60)));let{allowedTools:E,mcpServers:C}=this._resolveSkills(c,{sessionPath:a,workspace:n,nodeName:l});try{let $={cwd:n,allowedTools:E,settings:{permissions:{allow:["Bash(*)","Read(*)","Write(*)","Edit(*)","MultiEdit(*)","NotebookEdit(*)","Grep(*)","Glob(*)","WebFetch(*)","WebSearch(*)","Task(*)","TodoWrite(*)","Skill(*)"]}},model:w,...Object.keys(C).length>0&&{mcpServers:C},...f&&{sessionId:f},...g&&{resume:g},...y&&{forkSession:!0},...h&&{sessionStore:h}};if(o){let L=typeof o.parse=="function"?vn(o,{target:"openApi3"}):o;$.outputFormat={type:"json_schema",schema:L},p.debug("Structured output enforced via SDK outputFormat")}p.debug(`Agent SDK options: ${JSON.stringify({cwd:$.cwd,toolCount:E.length,permissionMode:$.permissionMode,model:$.model,hasOutputFormat:!!$.outputFormat})}`);let P="",B=0,k=[];p.debug("Starting Claude Agent SDK query stream");let _;try{_=Tn({prompt:e,options:$})}catch(x){throw p.error(`Failed to initialize Claude Agent SDK: ${x.message}`),x}let M=null,j=0,A=3;if(d?.aborted){let x=new Error("Aborted via signal");throw x.name="AbortError",x}try{for await(let x of _){if(d?.aborted){let D=new Error("Aborted via signal");throw D.name="AbortError",D}if(k.push(x),x.type==="system"&&x.subtype==="init"){let D=x.mcp_servers||[];if(D.length>0){let F=D.map(G=>`${G.name}=${G.status}${G.error?` (${String(G.error).slice(0,120)})`:""}`).join(", ");p.info(`[mcp] SDK init \u2014 ${D.length} server(s): ${F}`);for(let G of D)G.status!=="connected"&&p.warn(`[mcp] server '${G.name}' did not connect: status=${G.status}`,{name:G.name,status:G.status,error:G.error})}else Object.keys(C||{}).length>0&&p.warn(`[mcp] SDK init returned no mcp_servers despite passing ${Object.keys(C).length} server(s) \u2014 SDK version may not expose this field, or config was dropped`);if(Array.isArray(x.tools)){let F=x.tools.filter(G=>G.startsWith("mcp__"));F.length>0?p.info(`[mcp] tools visible to model: ${F.join(", ")}`):Object.keys(C||{}).length>0&&p.warn("[mcp] no mcp__* tools in model's tool list \u2014 MCP servers configured but tools didn't reach the prompt")}}if(x.type==="error"||x.error){let D=x.error?.message||x.error||x.message||"Unknown API error";try{p.error("SDK error event raw payload",{fullMessage:JSON.stringify(x,null,2)})}catch{}throw new Error(typeof D=="string"?D:JSON.stringify(D))}let L=JSON.stringify(x.message?.content||x.text||"").slice(0,200);if(L===M){if(j++,j>=A){let D=(x.message?.content?.[0]?.text||x.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${j}x repeated): ${D}`)}}else M=L,j=1;if(x.type==="assistant"||x.constructor?.name==="AssistantMessage"){let D=x.message?.content||x.content||[];for(let F of D)if(F.type==="thinking"&&F.thinking)console.log(`${F.thinking.substring(0,200)}${F.thinking.length>200?"...":""}`);else if(F.type==="text"&&F.text)P+=F.text,F.text.length<500?console.log(`${F.text}`):console.log(`${F.text.substring(0,200)}... (${F.text.length} chars)`);else if(F.type==="tool_use"){B++,F.name.includes("memory")?X.stepMemory(`Tool: ${F.name}`):X.stepTool(`Tool: ${F.name}`);let Oe=JSON.stringify(F.input).substring(0,100);console.log(` Input: ${Oe}${JSON.stringify(F.input).length>100?"...":""}`)}}else if(!(x.type==="user"&&x.tool_use_result)){if(x.type==="result"||x.constructor?.name==="ResultMessage"){let D=x.result||x.text||x.content||P;try{An({message:x,sessionPath:a,nodeName:l,model:S,toolCallCount:B})}catch(F){p.debug(`usage.json write failed: ${F.message}`)}if(o){if(x.structured_output){p.debug("Using SDK native structured_output");let G=typeof o.parse=="function"?o.parse(x.structured_output):x.structured_output;return{raw:D,structured:G}}if(D){let F=this._extractJson(D,o);if(F)return{raw:D,structured:F}}p.warn(`Could not extract structured output \u2014 returning raw text (${(D||"").length} chars)`)}return D||""}}}if(p.warn(`Agent SDK ended without result. Collected ${k.length} messages`),P.length>0)return p.debug("Returning accumulated text from messages"),P;throw new Error("Claude Agent SDK query ended without result")}catch(x){let L={message:x?.message,name:x?.name,code:x?.code,cause:x?.cause?.message||x?.cause,stack:x?.stack?.split(`
79
79
  `).slice(0,5).join(`
80
- `),stringified:(()=>{try{return JSON.stringify(_,Object.getOwnPropertyNames(Object(_)))}catch{return String(_)}})()};throw f.error(`Error during query stream: ${_?.message||_}`,M),_}}catch(I){throw f.error("Claude Agent SDK call failed",{message:I?.message,name:I?.name,code:I?.code,cause:I?.cause?.message||I?.cause}),I}}finally{for(let b of T)b.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 l=Vn(i);if(!l){f.warn(`Unknown skill "${i}" \u2014 skipping`);continue}if(l.allowedTools&&n.push(...l.allowedTools),typeof l.resolve=="function"){let c=l.resolve(t);c&&(s[l.serverName]=c,f.debug(`MCP: ${l.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 ts({message:o,sessionPath:e,nodeName:t,model:r,toolCallCount:n}){if(!e||!t)return;let s=o?.usage||o?.message?.usage||{},i=Le(s.input_tokens,s.inputTokens),l=Le(s.output_tokens,s.outputTokens),c=Le(s.cache_read_input_tokens,s.cacheReadInputTokens),a=Le(s.cache_creation_input_tokens,s.cacheCreationInputTokens),u=Le(o?.duration_ms,o?.durationMs),m={model:r||null,input_tokens:i,output_tokens:l,cache_read_tokens:c,cache_creation_tokens:a,tool_call_count:typeof n=="number"?n:null,duration_ms:u,captured_at:new Date().toISOString()},d=ye(e,t);try{St(d,{recursive:!0})}catch{}yt(ye(d,"usage.json"),JSON.stringify(m,null,2),"utf-8")}function Le(...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 rs(o,e){let t=ye(fr(),".claude"),r=ye(t,".credentials.json"),n={claudeAiOauth:{accessToken:o,...e?{subscriptionType:String(e).toLowerCase()}:{}}};try{if(ur(r)&&JSON.parse(pr(r,"utf-8"))?.claudeAiOauth?.accessToken===o)return;St(t,{recursive:!0}),yt(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 ns(o){let e=ye(fr(),".claude"),t=ye(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(ur(t)){let n=JSON.parse(pr(t,"utf-8"));if(n?.claudeAiOauth?.accessToken===r.claudeAiOauth.accessToken&&n?.claudeAiOauth?.expiresAt===r.claudeAiOauth.expiresAt)return}St(e,{recursive:!0}),yt(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 ss,getSkill as os}from"@zibby/agent-workflow";import{execSync as is}from"node:child_process";import{zodToJsonSchema as as}from"zod-to-json-schema";var oe=class extends ss{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 is("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:l=null,nodeName:c=null,timeout:a,config:u={},signal:m=null}=t,d=[Y("OPENAI_API_KEY"),Y("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 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(`
80
+ `),stringified:(()=>{try{return JSON.stringify(x,Object.getOwnPropertyNames(Object(x)))}catch{return String(x)}})()};throw p.error(`Error during query stream: ${x?.message||x}`,L),x}}catch($){throw p.error("Claude Agent SDK call failed",{message:$?.message,name:$?.name,code:$?.code,cause:$?.cause?.message||$?.cause}),$}}finally{for(let b of T)b.dispose()}}_resolveSkills(e,t){let r=["Read","Write","Edit","Bash","Grep","Glob"];if(e===null)return p.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return p.debug("Default IDE skills for code generation"),{allowedTools:[...r],mcpServers:{}};let n=[...r],o={};for(let s of e){let c=En(s);if(!c){p.warn(`Unknown skill "${s}" \u2014 skipping`);continue}if(c.allowedTools&&n.push(...c.allowedTools),typeof c.resolve=="function"){let a=c.resolve(t);a&&(o[c.serverName]=a,p.debug(`MCP: ${c.serverName} \u2192 ${a.command} ${a.args[0]}`))}}return{allowedTools:n,mcpServers:o}}_extractJson(e,t){let r=[()=>{if(e.includes("===JSON_START===")){let n=e.indexOf("===JSON_START===")+16,o=e.indexOf("===JSON_END===");return e.substring(n,o).trim()}},()=>e.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!e.startsWith("{"))return e.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>e.trim(),()=>{let n=e.indexOf("{"),o=e.lastIndexOf("}");if(n!==-1&&o>n)return e.substring(n,o+1)}];for(let n of r)try{let o=n();if(!o)continue;let s=JSON.parse(o);if(typeof s!="object"||s===null)continue;return typeof t.parse=="function"?t.parse(s):s}catch{}return null}};function An({message:i,sessionPath:e,nodeName:t,model:r,toolCallCount:n}){if(!e||!t)return;let o=i?.usage||i?.message?.usage||{},s=Ne(o.input_tokens,o.inputTokens),c=Ne(o.output_tokens,o.outputTokens),a=Ne(o.cache_read_input_tokens,o.cacheReadInputTokens),l=Ne(o.cache_creation_input_tokens,o.cacheCreationInputTokens),u=Ne(i?.duration_ms,i?.durationMs),m={model:r||null,input_tokens:s,output_tokens:c,cache_read_tokens:a,cache_creation_tokens:l,tool_call_count:typeof n=="number"?n:null,duration_ms:u,captured_at:new Date().toISOString()},d=me(e,t);try{ct(d,{recursive:!0})}catch{}lt(me(d,"usage.json"),JSON.stringify(m,null,2),"utf-8")}function Ne(...i){for(let e of i){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e)))return Number(e)}return null}function $n(i,e){let t=me(qt(),".claude"),r=me(t,".credentials.json"),n={claudeAiOauth:{accessToken:i,...e?{subscriptionType:String(e).toLowerCase()}:{}}};try{if(Zt(r)&&JSON.parse(Xt(r,"utf-8"))?.claudeAiOauth?.accessToken===i)return;ct(t,{recursive:!0}),lt(r,JSON.stringify(n,null,2),"utf-8"),p.debug(`Wrote Claude Code OAuth credentials to ${r}`)}catch(o){p.warn(`Could not write ${r}: ${o.message} \u2014 Claude SDK may fail to authenticate.`)}}function On(i){let e=me(qt(),".claude"),t=me(e,".credentials.json"),r;try{r=JSON.parse(i)}catch(n){p.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${n.message}`);return}if(!r?.claudeAiOauth?.accessToken){p.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if(Zt(t)){let n=JSON.parse(Xt(t,"utf-8"));if(n?.claudeAiOauth?.accessToken===r.claudeAiOauth.accessToken&&n?.claudeAiOauth?.expiresAt===r.claudeAiOauth.expiresAt)return}ct(e,{recursive:!0}),lt(t,JSON.stringify(r,null,2),"utf-8"),p.debug(`Wrote full Claude Code credentials blob to ${t}`)}catch(n){p.warn(`Could not write ${t}: ${n.message} \u2014 Claude SDK may fail to authenticate.`)}}import{AgentStrategy as In,getSkill as Cn}from"@zibby/agent-workflow";import{execSync as Pn}from"node:child_process";import{zodToJsonSchema as kn}from"zod-to-json-schema";var oe=class extends In{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY_POOL||process.env.CODEX_API_KEY||process.env.CODEX_API_KEY_POOL))return p.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return Pn("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return p.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:o=null,skills:s=null,sessionPath:c=null,nodeName:a=null,timeout:l,config:u={},signal:m=null}=t,d=[Y("OPENAI_API_KEY"),Y("CODEX_API_KEY")];try{let{Codex:f}=await import("@openai/codex-sdk"),g=r;(!g||g==="auto")&&(p.debug(`Model is '${g||"undefined"}', using default: ${J.CODEX}`),g=J.CODEX);let y=it[g]||g;it[g]&&g!==y&&p.debug(`Mapped model: ${g} \u2192 ${y}`),p.debug(`Invoking Codex SDK with model: ${y}, skills: ${JSON.stringify(s)}`);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(`
81
81
  \u25C6 Model: ${y}${S}
82
82
  `);let w=(await import("chalk")).default;console.log(`
83
- ${w.bold("Prompt sent to LLM:")}`),console.log(w.dim("\u2500".repeat(60))),console.log(w.dim(e)),console.log(w.dim("\u2500".repeat(60)));let T=this._resolveSkillsToMcp(i,{sessionPath:l,workspace:n,nodeName:c}),b={};Object.keys(T).length>0&&(b.mcp_servers=T,f.debug(`[Codex] MCP servers: ${Object.keys(T).join(", ")}`));let k=new p({...Object.keys(b).length>0&&{config:b}}).startThread({workingDirectory:n,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),R=s&&typeof s.parse=="function",v={};if(s)try{let O=R?as(s,{target:"openAi"}):s;v.outputSchema=O,f.debug("Structured output via SDK outputSchema")}catch(O){f.warn(`[Codex] Schema conversion failed, will extract from text: ${O.message}`)}if(m?.aborted){let O=new Error("Aborted via signal");throw O.name="AbortError",O}try{let{events:O}=await k.runStreamed(e,v),D=0,E="";for await(let P of O){if(m?.aborted){let C=new Error("Aborted via signal");throw C.name="AbortError",C}let I=P.type;if(I==="item.completed"){let C=P.item,j=C?.type;if(j==="mcp_tool_call"){D++;let N=`${C.server}/${C.tool}`;if(q.stepTool(`Tool: ${N}`),C.arguments){let x=JSON.stringify(C.arguments),L=x.length>100?`${x.substring(0,100)}...`:x;console.log(` Input: ${L}`)}}else if(j==="tool_call"||j==="function_call"||j==="command_execution"){D++;let N=C.name||C.tool||C.command||"unknown";q.stepTool(`Tool: ${N}`)}else j==="agent_message"&&(E=C.text||"",E.length<500?console.log(E):console.log(`${E.substring(0,200)}... (${E.length} chars)`))}else I==="turn.completed"?f.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(P.usage||{})}`):f.debug(`[Codex] Event: ${I} ${JSON.stringify(P).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 P=JSON.parse(E),I=R?s.parse(P):P;return f.debug("\u2705 [Codex] Structured output validated"),{raw:E,structured:I}}return E||""}catch(O){let D=O.message||String(O);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")),O}}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=os(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 l=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[l]=c,f.debug(`[Codex] MCP: ${l} \u2192 ${i.command} ${(i.args||[]).join(" ")}`)}return r}};import{AgentStrategy as cs,getSkill as ls}from"@zibby/agent-workflow";import{execSync as us,spawn as ps}from"node:child_process";import{zodToJsonSchema as fs}from"zod-to-json-schema";import{existsSync as dr,mkdirSync as mr,readFileSync as gr,rmSync as ds,writeFileSync as hr}from"node:fs";import{join as ie}from"node:path";function ms(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,l=-1;for(let c=r;c<e.length;c++){let a=e[c];if(s){i?i=!1:a==="\\"?i=!0:a==='"'&&(s=!1);continue}if(a==='"'){s=!0;continue}if(a==="{"){n===0&&(l=c),n+=1;continue}if(a==="}"){if(n===0)continue;if(n-=1,n===0&&l>=0){let u=e.slice(l,c+1);try{return JSON.parse(u)}catch{l=-1}}}}return null}function gs(o){let e=String(o||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return ms(e)}}function hs(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 ae=class extends cs{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 us("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:l=null,nodeName:c=null,timeout:a=600*1e3,signal:u=null}=t,m=[Y("GEMINI_API_KEY"),Y("GOOGLE_API_KEY")];try{let d=r;(!d||d==="auto")&&(d=J.GEMINI);let p=Vt[d]||d,g=String(process.env.GEMINI_API_KEY||"").trim(),y=String(process.env.GOOGLE_API_KEY||"").trim(),h=this._resolveSkillsToMcp(i,{sessionPath:l,workspace:n,nodeName:c}),S=Object.keys(h).length>0,w=new ge(e),T=s&&typeof s.parse=="function",b=null;if(s){let A;try{let _=T?fs(s,{target:"openAi"}):s;A=JSON.stringify(_,null,2)}catch{A="{}"}if(S){w.addSystemInstruction(`Write valid JSON that matches this schema:
84
- ${A}`,"schema_instruction","append");let _=`zibby-result-${Date.now()}.json`,M=ie(n,".zibby","tmp");b=ie(M,_),mr(M,{recursive:!0}),w.addStructuredOutput(s,b)}else w.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
85
- ${A}`,"json_instruction","append")}let $=w.build(),k=w.getUserPrompt(),R=w.getStats(),v=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),O=v?` | key: ***${v.slice(-4)}`:" | key: not set";console.log(`
86
- \u25C6 Model: ${p||"auto"}${O}
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(k)),console.log(D.dim("\u2500".repeat(60)));let E=this._createGeminiConfigDir(n,h),P=["--output-format","json"];p&&p!=="auto"&&P.push("--model",p);let I=Object.keys(h);if(I.length>0){P.push("--approval-mode","yolo");for(let A of I)P.push("--allowed-mcp-server-names",A);f.info(`[Gemini] Enabling MCP servers: ${I.join(", ")}`)}else i&&i.length>0&&f.warn(`[Gemini] Skills requested but no MCP servers configured: ${i.join(", ")}`);P.push("-p",$);let C={...process.env,GEMINI_CLI_HOME:E};g?(C.GEMINI_API_KEY=g,delete C.GOOGLE_API_KEY):y&&(C.GOOGLE_API_KEY=y,delete C.GEMINI_API_KEY),f.debug(`[Gemini] Command: gemini ${P.slice(0,8).join(" ")}... (${P.length} total args)`),f.debug(`[Gemini] User prompt: ${R.userPromptLength} chars, System instructions: ${R.systemInstructionsLength} chars (${R.instructionCount} blocks), Full: ${R.fullPromptLength} chars`),f.debug(`[Gemini] Config home: ${E}`),f.debug(`[Gemini] GEMINI_CLI_HOME env: ${C.GEMINI_CLI_HOME}`);let j="",N=null;try{j=await new Promise((_,M)=>{let U=ps("gemini",P,{cwd:n,env:C,stdio:["ignore","pipe","pipe"],...u&&{signal:u}}),B="",G="",Ce=!1,Ne=null,dt=!1,Xt=setTimeout(()=>{try{U.kill("SIGTERM")}catch{}},a),We=()=>{dt||Ce||(dt=!0,Ne=setTimeout(()=>{if(!Ce)try{U.kill("SIGKILL")}catch{}},5e3))};u&&(u.aborted?We():u.addEventListener("abort",We,{once:!0})),U.stdout.on("data",Q=>{B+=Q.toString()}),U.stderr.on("data",Q=>{G+=Q.toString()}),U.on("error",Q=>{if(clearTimeout(Xt),Ne&&clearTimeout(Ne),u&&!u.aborted)try{u.removeEventListener("abort",We)}catch{}M(Q)}),U.on("close",Q=>{if(Ce=!0,clearTimeout(Xt),Ne&&clearTimeout(Ne),u&&!u.aborted)try{u.removeEventListener("abort",We)}catch{}if(dt){let qt=new Error("Aborted via signal");return qt.name="AbortError",M(qt)}if(Q===0)return _(B.trim());M(new Error(`gemini failed with code ${Q}: ${(G||B).trim()}`))})})}catch(A){N=A}finally{try{ds(E,{recursive:!0,force:!0})}catch{}}let x=hs(j).trim();if(!s){if(N)throw N;return x}if(b){let A=dr(b);if(f.info(`[Gemini] Result file: ${A?"present":"missing"} at ${b}`),A)try{let _=gr(b,"utf-8").trim(),M=JSON.parse(_),U=T?s.parse(M):M;return f.info("[Gemini] Structured output recovered from result file"),{raw:x,structured:U}}catch(_){f.warn(`[Gemini] Result file parse/validation failed: ${_.message}`)}else N||f.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let L=null;if(s){let A=new X;A.zodSchema=s,A.processChunk(x),A.flush(),L=A.getResult()}if(f.info(`[Gemini] Raw stdout length: ${j.length} chars`),f.info(`[Gemini] Extracted text length: ${x.length} chars`),f.info(`[Gemini] StreamParser result: ${L?"extracted":"null"}`),L||(x.length<2e3?f.info(`[Gemini] Raw text preview:
89
- ${x}`):f.info(`[Gemini] Raw text preview (first 1000 chars):
90
- ${x.slice(0,1e3)}`),L=gs(x)),!L)throw N||(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 F=T?s.parse(L):L;return{raw:x,structured:F}}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=ls(n);if(!s||typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let l=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[l]=c}return r}_createGeminiConfigDir(e,t){let r=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,n=ie(e||process.cwd(),".zibby","tmp",`gemini-home-${r}`),s=ie(n,".gemini");mr(s,{recursive:!0});let i=ie(s,"settings.json"),l={},c=ie(process.env.HOME||"",".gemini","settings.json");if(dr(c))try{l=JSON.parse(gr(c,"utf-8"))}catch{l={}}let a={...l,mcpServers:{...l.mcpServers&&typeof l.mcpServers=="object"?l.mcpServers:{},...t||{}}};hr(i,`${JSON.stringify(a,null,2)}
91
- `,"utf-8");let u=ie(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{hr(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 Os,getSkill as nt}from"@zibby/agent-workflow";var Se=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 ce=class extends Se{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 De=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 et(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 bt(o,e=0){if(!o||typeof o!="object"||e>8)return o;if(Array.isArray(o))return o.map(r=>bt(r,e+1));let t={};for(let[r,n]of Object.entries(o))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=bt(n,e+1));return t}function ys(o=[]){return o.map(e=>({...e,function:{...e.function,description:et(e.function?.description||"",180),parameters:bt(e.function?.parameters||{type:"object",properties:{}})}}))}function yr(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,...l}=n;return{...l,content:l.content||""}})}function wt(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)?ys(o.tools):o.tools};n.messages.length>0&&n.messages[0]?.role==="system"&&(n.messages[0]={...n.messages[0],content:et(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=yr(n.messages)),Qe(n)>t&&n.messages.length>0&&(n.messages[0]={...n.messages[0],content:et(n.messages[0].content,6e3)},s=!0),Qe(n)>t){let i=n.messages.find(c=>c.role==="system")||n.messages[0],l=n.messages.slice(-2);n.messages=yr([i,...l].filter(Boolean).map((c,a)=>({...c,content:et(c.content,a===0?4e3:8e3)}))),s=!0}return{body:n,meta:{bytes:Qe(n),trimmed:s,maxBytes:t,messageCount:n.messages.length}}}var Sr=o=>Buffer.byteLength(JSON.stringify(o),"utf8"),be=class extends De{async fetchCompletion(e,t,r={}){let n=Sr(e),{body:s,meta:i}=wt(e,r.payloadCompaction);r.onBudget?.({streaming:!1,beforeBytes:n,meta:i});let l=this.#e(r),c=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,a=await fetch(c,{method:"POST",headers:t.headers,body:JSON.stringify(s),signal:l});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=Sr(n),{body:i,meta:l}=wt(n,r.payloadCompaction);r.onBudget?.({streaming:!0,beforeBytes:s,meta:l});let c=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: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 w=p.split(`
95
- `);p=w.pop();for(let T of w){if(!T.startsWith("data: "))continue;let b=T.slice(6).trim();if(b==="[DONE]")continue;let $;try{$=JSON.parse(b)}catch{continue}let k=$.choices?.[0]?.delta;if(k&&(k.content&&(g+=k.content,r.onToken&&r.onToken(k.content)),k.tool_calls))for(let R of k.tool_calls){let v=R.index??0;y.has(v)||y.set(v,{id:"",name:"",args:""});let O=y.get(v);R.id&&(O.id=R.id),R.function?.name&&(O.name=R.function.name),R.function?.arguments!=null&&(O.args+=R.function.arguments)}}}if(y.size>0){let h=[...y.entries()].sort(([S],[w])=>S-w).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 Ss}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as bs}from"@modelcontextprotocol/sdk/client/stdio.js";var Ue=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 bs({command:r,args:n,env:{...process.env,...s}}),l=new Ss({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await l.connect(i);let c={client:l,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(l=>l.type==="text").map(l=>l.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 ws,readFileSync as xs}from"node:fs";import{join as _s}from"node:path";import{homedir as Es}from"node:os";function Ts(){try{let o=_s(Es(),".zibby","config.json");return ws(o)?JSON.parse(xs(o,"utf-8")):{}}catch{return{}}}function tt(o){return String(o||"").replace(/\/v1\/?$/,"")}function vs(o,e){let t=process.env.OPENAI_PROXY_URL;if(t)return tt(t);if(o==="session")return e.proxyUrl?tt(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 tt(r||"https://api.openai.com")}return tt(t||"")}function xt(){let o=Ts(),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 l=vs(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(!l)return{ok:!1,mode:i,reason:"missing_openai_proxy_url"};!n&&t&&(c.Authorization=`Bearer ${t}`)}return l?{ok:!0,mode:i,baseUrl:l,headers:c,tokenPreview:c.Authorization?`***${c.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:i,reason:"missing_base_url"}}function rt(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 As(o,e){if(typeof o=="string")return rt(o,e);try{return rt(JSON.stringify(o),e)}catch{return rt(String(o),e)}}function br(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,...l}=n;return{...l,content:l.content||""}})}function Is(o){let e=Array.isArray(o?.messages)?o.messages:[],t=e.find(s=>s.role==="system"),r=e.slice(-4).map(s=>({...s,content:rt(s.content,s.role==="tool"?1200:2500)}));r=br(r);let n={...o,messages:[t,...r].filter(Boolean)};return delete n.tools,n}async function $s({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(l){let c=String(l?.message||l||"");if(!/proxy error 413|payload too large/i.test(c))throw l;let a=Is(o);return typeof i=="function"&&i(o,a),{data:e?await s(a,t,r):await n(a,t,r),fallback:a}}}async function wr({body:o,auth:e,options:t,streaming:r,toolContext:n,activeSkills:s,round:i,verbose:l,dependencies:c,config:a={}}){let u=a.maxToolResultChars||3e3,{fetchCompletion:m,fetchStreamingCompletion:d,onFallbackLog:p,hasToolCalls:g,getTextContent:y,parseToolCalls:h,buildAssistantMessage:S,buildToolResultMessage:w,executeTool:T,onToolCallLog:b,injectTools:$}=c;Array.isArray(o?.messages)&&(o.messages=br(o.messages));let k=await $s({body:o,streaming:r,auth:e,options:t,fetchCompletion:m,fetchStreamingCompletion:d,onFallbackLog:p}),R=k?.data||k;if(!g(R))return{done:!0,text:y(R),body:k?.fallback||o};let v=h(R),O=k?.fallback||o;O.messages.push(S(R)),l&&typeof b=="function"&&b(v);let D=await Promise.all(v.map((E,P)=>(typeof t.onToolCall=="function"&&t.onToolCall(E.name,E.args,{round:i,index:P,total:v.length}),T(E,n))));for(let E=0;E<v.length;E++){let I=v[E].name==="get_skill_context"?typeof D[E]=="string"?D[E]:JSON.stringify(D[E]):As(D[E],u);O.messages.push(w(v[E].id,I))}return typeof t.onToolCall=="function"&&t.onToolCall(null),$(O,s),{done:!1,body:O}}var Ps=J.ASSISTANT,Cs=15,_t="get_skill_context";function xe(o){!o||typeof o!="object"||(o.type==="object"&&o.properties&&(o.required=Object.keys(o.properties),o.additionalProperties=!1,Object.values(o.properties).forEach(xe)),o.type==="array"&&o.items&&xe(o.items),o.anyOf&&o.anyOf.forEach(xe),o.oneOf&&o.oneOf.forEach(xe),o.allOf&&o.allOf.forEach(xe))}var xr={maxBytes:49e3,systemMaxChars:12e3},we=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Ns=o=>Buffer.byteLength(JSON.stringify(o),"utf8");function st(o){return Array.isArray(o)?new Set(o.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function Rs(o){return Array.isArray(o)?o.map(e=>String(e||"").trim()).filter(Boolean):[]}var le=class extends Os{#e;#t;#r=new Ue;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new ce,this.#t=e.completionProvider||new be):(this.#e=e||new ce,this.#t=new be)}canHandle(e){return xt().ok}async invoke(e,t={}){let r=Y("OPENAI_API_KEY");try{let n=t.model&&t.model!=="auto"?t.model:Ps,s=xt();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}],l=s.baseUrl,c=we();if(c?await this.#m(i,n,l,s.tokenPreview||"none"):f.debug(`[Assistant] ${l} | model: ${n} | messages: ${i.length}`),t.schema)return this.#l(n,i,s,t);let a=t.activeSkills||[],u=this.#p(t),m=this.#f(a,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 w=0;w<Cs;w++){if(t.signal?.aborted){let b=new Error("Aborted via signal");throw b.name="AbortError",b}let T=await wr({body:S,auth:s,options:g,streaming:h,toolContext:y,activeSkills:m,round:w,verbose:c,dependencies:{fetchCompletion:this.#o.bind(this),fetchStreamingCompletion:this.#c.bind(this),onFallbackLog:(b,$)=>{we()&&console.log(`413 fallback: messages ${b.messages.length} -> ${$.messages.length}, bytes=${Ns($)}`)},hasToolCalls:b=>this.#e.hasToolCalls(b),getTextContent:b=>this.#e.getTextContent(b),parseToolCalls:b=>this.#e.parseToolCalls(b),buildAssistantMessage:b=>this.#e.buildAssistantMessage(b),buildToolResultMessage:(b,$)=>this.#e.buildToolResultMessage(b,$),executeTool:(b,$)=>this.#a(b,$),onToolCallLog:async b=>{let $=(await import("chalk")).default;console.log($.dim(` ${b.map(k=>`${k.name}(${JSON.stringify(k.args).slice(0,80)})`).join(", ")}`))},injectTools:(b,$)=>this.#s(b,$,u)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(T.done)return T.text;S.messages=T.body.messages,T.body.tools?S.tools=T.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=nt(s);if(i?.tools?.length)for(let l of i.tools)this.#n(l.name,t)&&(n.has(l.name)||(n.add(l.name),r.push({name:l.name,description:l.description,parameters:l.parameters||l.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#n(_t,t)&&r.push({name:_t,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),r}async#a(e,t){let{activeSkills:r,options:n,executionRegistry:s,capabilityPolicy:i}=t;if(!this.#n(e.name,i))return`Tool "${e.name}" blocked by policy`;if(e.name===_t){let 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=nt(a);if(!u)return JSON.stringify({error:`Skill "${a}" not found`});let m=typeof u.promptFragment=="function"?u.promptFragment():u.promptFragment||"",d=(u.tools||[]).map(g=>g.name),p=JSON.stringify({skillId:a,description:u.description||"",toolNames:d,promptFragment:m||""});return we()&&(console.log(`
99
- \u{1F4D6} get_skill_context("${a}") \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
100
- `)),p}let l=s?.get(e.name)||null;if(!l)return`Unknown tool: ${e.name}`;let c=nt(l.skillId);if(!c)return`Skill "${l.skillId}" not found for tool "${e.name}"`;if(l.mode==="handler")try{return c.handleToolCall(e.name,e.args,t)}catch(a){return`Error in ${e.name}: ${a.message}`}if(l.mode==="mcp")try{if(!this.#r.isRunning(c.serverName)){let u=c.resolve(n);if(!u)return`Skill "${l.skillId}" is not available (cannot start server)`;await this.#r.ensureServer(c.serverName,u)}let a=await this.#r.callTool(c.serverName,e.name,e.args);return a.text||(a.isError?"Tool call failed":"Done")}catch(a){return`MCP error (${c.serverName}): ${a.message}`}return`Skill "${l.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})=>{we()&&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})=>{we()&&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",l=i?s(n.schema):n.schema;delete l.$schema,xe(l);let c={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:l,strict:!0}}},a=await this.#o(c,r,n),u=this.#e.getTextContent(a),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||xr.maxBytes),systemMaxChars:Number(t.systemMaxChars||xr.systemMaxChars)}}#p(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:st(t.allowTools||e.allowTools),denyTools:st(t.denyTools||e.denyTools),denyPrefixes:Rs(t.denyPrefixes||e.denyToolPrefixes),includeSkills:st(t.includeSkills||e.includeSkills),excludeSkills:st(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(l=>r.startsWith(l)))}#d(e){let t=new Map,r=[];for(let n of e){let s=nt(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 l of s.tools){let c=String(l?.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&&we()){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(`
83
+ ${w.bold("Prompt sent to LLM:")}`),console.log(w.dim("\u2500".repeat(60))),console.log(w.dim(e)),console.log(w.dim("\u2500".repeat(60)));let T=this._resolveSkillsToMcp(s,{sessionPath:c,workspace:n,nodeName:a}),b={};Object.keys(T).length>0&&(b.mcp_servers=T,p.debug(`[Codex] MCP servers: ${Object.keys(T).join(", ")}`));let R=new f({...Object.keys(b).length>0&&{config:b}}).startThread({workingDirectory:n,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),N=o&&typeof o.parse=="function",v={};if(o)try{let I=N?kn(o,{target:"openAi"}):o;v.outputSchema=I,p.debug("Structured output via SDK outputSchema")}catch(I){p.warn(`[Codex] Schema conversion failed, will extract from text: ${I.message}`)}if(m?.aborted){let I=new Error("Aborted via signal");throw I.name="AbortError",I}try{let{events:I}=await R.runStreamed(e,v),U=0,E="";for await(let C of I){if(m?.aborted){let P=new Error("Aborted via signal");throw P.name="AbortError",P}let $=C.type;if($==="item.completed"){let P=C.item,B=P?.type;if(B==="mcp_tool_call"){U++;let k=`${P.server}/${P.tool}`;if(X.stepTool(`Tool: ${k}`),P.arguments){let _=JSON.stringify(P.arguments),M=_.length>100?`${_.substring(0,100)}...`:_;console.log(` Input: ${M}`)}}else if(B==="tool_call"||B==="function_call"||B==="command_execution"){U++;let k=P.name||P.tool||P.command||"unknown";X.stepTool(`Tool: ${k}`)}else B==="agent_message"&&(E=P.text||"",E.length<500?console.log(E):console.log(`${E.substring(0,200)}... (${E.length} chars)`))}else $==="turn.completed"?p.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(C.usage||{})}`):p.debug(`[Codex] Event: ${$} ${JSON.stringify(C).slice(0,300)}`)}if(p.debug(`[Codex] Last agent message (${E.length} chars): ${E.slice(0,500)}`),o){if(!E)throw new Error("Codex agent returned no response");let C=JSON.parse(E),$=N?o.parse(C):C;return p.debug("\u2705 [Codex] Structured output validated"),{raw:E,structured:$}}return E||""}catch(I){let U=I.message||String(I);throw p.error(`\u274C [Codex] SDK call failed: ${U}`),U.includes("exited with code")&&(p.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),p.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),I}}finally{for(let f of d)f.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let o=Cn(n);if(!o){p.warn(`[Codex] Unknown skill "${n}" \u2014 skipping`);continue}if(typeof o.resolve!="function")continue;let s=o.resolve(t);if(!s)continue;let c=o.serverName||n,a={command:s.command};s.args?.length&&(a.args=s.args),s.env&&Object.keys(s.env).length>0&&(a.env=s.env),r[c]=a,p.debug(`[Codex] MCP: ${c} \u2192 ${s.command} ${(s.args||[]).join(" ")}`)}return r}};import{AgentStrategy as Nn,getSkill as Rn}from"@zibby/agent-workflow";import{execSync as Ln,spawn as Mn}from"node:child_process";import{zodToJsonSchema as Un}from"zod-to-json-schema";import{existsSync as Vt,mkdirSync as Qt,readFileSync as er,rmSync as Dn,writeFileSync as tr}from"node:fs";import{join as se}from"node:path";function Fn(i){if(!i)return null;let e=String(i),t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t?.[1])try{return JSON.parse(t[1].trim())}catch{}let r=e.indexOf("{");if(r<0)return null;let n=0,o=!1,s=!1,c=-1;for(let a=r;a<e.length;a++){let l=e[a];if(o){s?s=!1:l==="\\"?s=!0:l==='"'&&(o=!1);continue}if(l==='"'){o=!0;continue}if(l==="{"){n===0&&(c=a),n+=1;continue}if(l==="}"){if(n===0)continue;if(n-=1,n===0&&c>=0){let u=e.slice(c,a+1);try{return JSON.parse(u)}catch{c=-1}}}}return null}function jn(i){let e=String(i||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return Fn(e)}}function Bn(i){try{let e=JSON.parse(i);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 i}var ie=class extends Nn{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GEMINI_API_KEY_POOL||process.env.GOOGLE_API_KEY||process.env.GOOGLE_API_KEY_POOL))return p.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return Ln("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return p.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:o=null,skills:s=null,sessionPath:c=null,nodeName:a=null,timeout:l=600*1e3,signal:u=null}=t,m=[Y("GEMINI_API_KEY"),Y("GOOGLE_API_KEY")];try{let d=r;(!d||d==="auto")&&(d=J.GEMINI);let f=Ut[d]||d,g=String(process.env.GEMINI_API_KEY||"").trim(),y=String(process.env.GOOGLE_API_KEY||"").trim(),h=this._resolveSkillsToMcp(s,{sessionPath:c,workspace:n,nodeName:a}),S=Object.keys(h).length>0,w=new fe(e),T=o&&typeof o.parse=="function",b=null;if(o){let A;try{let x=T?Un(o,{target:"openAi"}):o;A=JSON.stringify(x,null,2)}catch{A="{}"}if(S){w.addSystemInstruction(`Write valid JSON that matches this schema:
84
+ ${A}`,"schema_instruction","append");let x=`zibby-result-${Date.now()}.json`,L=se(n,".zibby","tmp");b=se(L,x),Qt(L,{recursive:!0}),w.addStructuredOutput(o,b)}else w.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
85
+ ${A}`,"json_instruction","append")}let O=w.build(),R=w.getUserPrompt(),N=w.getStats(),v=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),I=v?` | key: ***${v.slice(-4)}`:" | key: not set";console.log(`
86
+ \u25C6 Model: ${f||"auto"}${I}
87
+ `);let U=(await import("chalk")).default;console.log(`
88
+ ${U.bold("Prompt sent to LLM:")}`),console.log(U.dim("\u2500".repeat(60))),console.log(U.dim(R)),console.log(U.dim("\u2500".repeat(60)));let E=this._createGeminiConfigDir(n,h),C=["--output-format","json"];f&&f!=="auto"&&C.push("--model",f);let $=Object.keys(h);if($.length>0){C.push("--approval-mode","yolo");for(let A of $)C.push("--allowed-mcp-server-names",A);p.info(`[Gemini] Enabling MCP servers: ${$.join(", ")}`)}else s&&s.length>0&&p.warn(`[Gemini] Skills requested but no MCP servers configured: ${s.join(", ")}`);C.push("-p",O);let P={...process.env,GEMINI_CLI_HOME:E};g?(P.GEMINI_API_KEY=g,delete P.GOOGLE_API_KEY):y&&(P.GOOGLE_API_KEY=y,delete P.GEMINI_API_KEY),p.debug(`[Gemini] Command: gemini ${C.slice(0,8).join(" ")}... (${C.length} total args)`),p.debug(`[Gemini] User prompt: ${N.userPromptLength} chars, System instructions: ${N.systemInstructionsLength} chars (${N.instructionCount} blocks), Full: ${N.fullPromptLength} chars`),p.debug(`[Gemini] Config home: ${E}`),p.debug(`[Gemini] GEMINI_CLI_HOME env: ${P.GEMINI_CLI_HOME}`);let B="",k=null;try{B=await new Promise((x,L)=>{let D=Mn("gemini",C,{cwd:n,env:P,stdio:["ignore","pipe","pipe"],...u&&{signal:u}}),F="",G="",Oe=!1,Ie=null,ot=!1,Lt=setTimeout(()=>{try{D.kill("SIGTERM")}catch{}},l),Je=()=>{ot||Oe||(ot=!0,Ie=setTimeout(()=>{if(!Oe)try{D.kill("SIGKILL")}catch{}},5e3))};u&&(u.aborted?Je():u.addEventListener("abort",Je,{once:!0})),D.stdout.on("data",V=>{F+=V.toString()}),D.stderr.on("data",V=>{G+=V.toString()}),D.on("error",V=>{if(clearTimeout(Lt),Ie&&clearTimeout(Ie),u&&!u.aborted)try{u.removeEventListener("abort",Je)}catch{}L(V)}),D.on("close",V=>{if(Oe=!0,clearTimeout(Lt),Ie&&clearTimeout(Ie),u&&!u.aborted)try{u.removeEventListener("abort",Je)}catch{}if(ot){let Mt=new Error("Aborted via signal");return Mt.name="AbortError",L(Mt)}if(V===0)return x(F.trim());L(new Error(`gemini failed with code ${V}: ${(G||F).trim()}`))})})}catch(A){k=A}finally{try{Dn(E,{recursive:!0,force:!0})}catch{}}let _=Bn(B).trim();if(!o){if(k)throw k;return _}if(b){let A=Vt(b);if(p.info(`[Gemini] Result file: ${A?"present":"missing"} at ${b}`),A)try{let x=er(b,"utf-8").trim(),L=JSON.parse(x),D=T?o.parse(L):L;return p.info("[Gemini] Structured output recovered from result file"),{raw:_,structured:D}}catch(x){p.warn(`[Gemini] Result file parse/validation failed: ${x.message}`)}else k||p.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let M=null;if(o){let A=new Z;A.zodSchema=o,A.processChunk(_),A.flush(),M=A.getResult()}if(p.info(`[Gemini] Raw stdout length: ${B.length} chars`),p.info(`[Gemini] Extracted text length: ${_.length} chars`),p.info(`[Gemini] StreamParser result: ${M?"extracted":"null"}`),M||(_.length<2e3?p.info(`[Gemini] Raw text preview:
89
+ ${_}`):p.info(`[Gemini] Raw text preview (first 1000 chars):
90
+ ${_.slice(0,1e3)}`),M=jn(_)),!M)throw k||(p.error("[Gemini] Failed to extract valid JSON from output"),p.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error("Gemini did not return valid JSON for structured output. Enable strictMode for proxy fallback."));let j=T?o.parse(M):M;return{raw:_,structured:j}}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 o=Rn(n);if(!o||typeof o.resolve!="function")continue;let s=o.resolve(t);if(!s)continue;let c=o.cursorKey||o.serverName||n,a={command:s.command};s.args?.length&&(a.args=s.args),s.env&&Object.keys(s.env).length>0&&(a.env=s.env),s.cwd&&(a.cwd=s.cwd),r[c]=a}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}`),o=se(n,".gemini");Qt(o,{recursive:!0});let s=se(o,"settings.json"),c={},a=se(process.env.HOME||"",".gemini","settings.json");if(Vt(a))try{c=JSON.parse(er(a,"utf-8"))}catch{c={}}let l={...c,mcpServers:{...c.mcpServers&&typeof c.mcpServers=="object"?c.mcpServers:{},...t||{}}};tr(s,`${JSON.stringify(l,null,2)}
91
+ `,"utf-8");let u=se(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{tr(u,`${JSON.stringify(l,null,2)}
92
+ `,"utf-8")}catch{}return p.debug(`[Gemini] Created isolated config with ${Object.keys(l.mcpServers||{}).length} MCP servers`),p.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(l.mcpServers||{}),null,2)}`),n}};import{AgentStrategy as eo,getSkill as Ve}from"@zibby/agent-workflow";var ge=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 ge{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 Re=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 We(i){return Buffer.byteLength(JSON.stringify(i),"utf8")}function Ze(i,e){let t=String(i||"");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 ut(i,e=0){if(!i||typeof i!="object"||e>8)return i;if(Array.isArray(i))return i.map(r=>ut(r,e+1));let t={};for(let[r,n]of Object.entries(i))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=ut(n,e+1));return t}function Gn(i=[]){return i.map(e=>({...e,function:{...e.function,description:Ze(e.function?.description||"",180),parameters:ut(e.function?.parameters||{type:"object",properties:{}})}}))}function rr(i){let e=new Set;for(let n of i)if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let o of n.tool_calls)e.add(o.id);let t=i.filter(n=>n.role==="tool"?e.has(n.tool_call_id):!0),r=new Set;for(let n of t)n.role==="tool"&&r.add(n.tool_call_id);return t.map(n=>{if(n.role!=="assistant"||!Array.isArray(n.tool_calls)||n.tool_calls.every(a=>r.has(a.id)))return n;let{tool_calls:s,...c}=n;return{...c,content:c.content||""}})}function pt(i,e={}){let t=e.maxBytes||49e3,r=e.systemMaxChars||12e3,n={...i,messages:Array.isArray(i.messages)?[...i.messages]:[],tools:Array.isArray(i.tools)?Gn(i.tools):i.tools};n.messages.length>0&&n.messages[0]?.role==="system"&&(n.messages[0]={...n.messages[0],content:Ze(n.messages[0].content,r)});let o=!1;for(;We(n)>t&&n.messages.length>2;)n.messages.splice(1,1),o=!0;if(o&&(n.messages=rr(n.messages)),We(n)>t&&n.messages.length>0&&(n.messages[0]={...n.messages[0],content:Ze(n.messages[0].content,6e3)},o=!0),We(n)>t){let s=n.messages.find(a=>a.role==="system")||n.messages[0],c=n.messages.slice(-2);n.messages=rr([s,...c].filter(Boolean).map((a,l)=>({...a,content:Ze(a.content,l===0?4e3:8e3)}))),o=!0}return{body:n,meta:{bytes:We(n),trimmed:o,maxBytes:t,messageCount:n.messages.length}}}var nr=i=>Buffer.byteLength(JSON.stringify(i),"utf8"),he=class extends Re{async fetchCompletion(e,t,r={}){let n=nr(e),{body:o,meta:s}=pt(e,r.payloadCompaction);r.onBudget?.({streaming:!1,beforeBytes:n,meta:s});let c=this.#e(r),a=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,l=await fetch(a,{method:"POST",headers:t.headers,body:JSON.stringify(o),signal:c});if(!l.ok){let u=await l.text();throw l.status===401||l.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${l.status}: ${u}`)}return l.json()}async fetchStreamingCompletion(e,t,r={}){let n={...e,stream:!0},o=nr(n),{body:s,meta:c}=pt(n,r.payloadCompaction);r.onBudget?.({streaming:!0,beforeBytes:o,meta:c});let a=this.#e(r),l=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,u=await fetch(l,{method:"POST",headers:t.headers,body:JSON.stringify(s),signal:a});if(!u.ok){let h=await u.text();throw u.status===401||u.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${u.status}: ${h}`)}let m=u.body.getReader(),d=new TextDecoder,f="",g="",y=new Map;for(;;){let{done:h,value:S}=await m.read();if(h)break;f+=d.decode(S,{stream:!0});let w=f.split(`
95
+ `);f=w.pop();for(let T of w){if(!T.startsWith("data: "))continue;let b=T.slice(6).trim();if(b==="[DONE]")continue;let O;try{O=JSON.parse(b)}catch{continue}let R=O.choices?.[0]?.delta;if(R&&(R.content&&(g+=R.content,r.onToken&&r.onToken(R.content)),R.tool_calls))for(let N of R.tool_calls){let v=N.index??0;y.has(v)||y.set(v,{id:"",name:"",args:""});let I=y.get(v);N.id&&(I.id=N.id),N.function?.name&&(I.name=N.function.name),N.function?.arguments!=null&&(I.args+=N.function.arguments)}}}if(y.size>0){let h=[...y.entries()].sort(([S],[w])=>S-w).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 Kn}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Jn}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:o={}}=t;p.debug(`[MCP] Starting ${e}: ${r} ${n.join(" ")}`);let s=new Jn({command:r,args:n,env:{...process.env,...o}}),c=new Kn({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await c.connect(s);let a={client:c,transport:s,serverConfig:t};return this.#e.set(e,a),a}async callTool(e,t,r={}){let n=this.#e.get(e);if(!n)throw new Error(`MCP server "${e}" not running`);p.debug(`[MCP] ${e}.${t}(${JSON.stringify(r).slice(0,200)})`);let o=await n.client.callTool({name:t,arguments:r});return{text:o.content?.filter(c=>c.type==="text").map(c=>c.text).join(`
96
+ `)||"",isError:o.isError||!1}}isRunning(e){return this.#e.has(e)}async stopServer(e){let t=this.#e.get(e);if(t){try{await t.client.close()}catch(r){p.debug(`[MCP] Error closing ${e}: ${r.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}};import{existsSync as zn,readFileSync as Yn}from"node:fs";import{join as Hn}from"node:path";import{homedir as Wn}from"node:os";function Zn(){try{let i=Hn(Wn(),".zibby","config.json");return zn(i)?JSON.parse(Yn(i,"utf-8")):{}}catch{return{}}}function Xe(i){return String(i||"").replace(/\/v1\/?$/,"")}function Xn(i,e){let t=process.env.OPENAI_PROXY_URL;if(t)return Xe(t);if(i==="session")return e.proxyUrl?Xe(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(i==="byok"){let r=process.env.OPENAI_BASE_URL;return Xe(r||"https://api.openai.com")}return Xe(t||"")}function ft(){let i=Zn(),e=process.env.ZIBBY_USER_TOKEN||i.sessionToken||null,t=process.env.OPENAI_API_KEY||null,r=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),n=process.env.OPENAI_PROXY_NO_AUTH==="true",o=process.env.OPENAI_PROXY_URL,s="session";r==="byok"||r==="local"||r==="session"?s=r:e?s="session":t?s="byok":o&&n&&(s="local");let c=Xn(s,i),a={"Content-Type":"application/json"};if(s==="session"){if(!e)return{ok:!1,mode:s,reason:"missing_session_token"};a.Authorization=`Bearer ${e}`}else if(s==="byok"){if(!t)return{ok:!1,mode:s,reason:"missing_openai_api_key"};a.Authorization=`Bearer ${t}`}else if(s==="local"){if(!c)return{ok:!1,mode:s,reason:"missing_openai_proxy_url"};!n&&t&&(a.Authorization=`Bearer ${t}`)}return c?{ok:!0,mode:s,baseUrl:c,headers:a,tokenPreview:a.Authorization?`***${a.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:s,reason:"missing_base_url"}}function qe(i,e){let t=String(i??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
97
+
98
+ [tool result truncated for size]`}function qn(i,e){if(typeof i=="string")return qe(i,e);try{return qe(JSON.stringify(i),e)}catch{return qe(String(i),e)}}function or(i){let e=new Set;for(let n of i)if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let o of n.tool_calls)e.add(o.id);let t=i.filter(n=>n.role==="tool"?e.has(n.tool_call_id):!0),r=new Set;for(let n of t)n.role==="tool"&&r.add(n.tool_call_id);return t.map(n=>{if(n.role!=="assistant"||!Array.isArray(n.tool_calls)||n.tool_calls.every(a=>r.has(a.id)))return n;let{tool_calls:s,...c}=n;return{...c,content:c.content||""}})}function Vn(i){let e=Array.isArray(i?.messages)?i.messages:[],t=e.find(o=>o.role==="system"),r=e.slice(-4).map(o=>({...o,content:qe(o.content,o.role==="tool"?1200:2500)}));r=or(r);let n={...i,messages:[t,...r].filter(Boolean)};return delete n.tools,n}async function Qn({body:i,streaming:e,auth:t,options:r,fetchCompletion:n,fetchStreamingCompletion:o,onFallbackLog:s}){try{return e?await o(i,t,r):await n(i,t,r)}catch(c){let a=String(c?.message||c||"");if(!/proxy error 413|payload too large/i.test(a))throw c;let l=Vn(i);return typeof s=="function"&&s(i,l),{data:e?await o(l,t,r):await n(l,t,r),fallback:l}}}async function sr({body:i,auth:e,options:t,streaming:r,toolContext:n,activeSkills:o,round:s,verbose:c,dependencies:a,config:l={}}){let u=l.maxToolResultChars||3e3,{fetchCompletion:m,fetchStreamingCompletion:d,onFallbackLog:f,hasToolCalls:g,getTextContent:y,parseToolCalls:h,buildAssistantMessage:S,buildToolResultMessage:w,executeTool:T,onToolCallLog:b,injectTools:O}=a;Array.isArray(i?.messages)&&(i.messages=or(i.messages));let R=await Qn({body:i,streaming:r,auth:e,options:t,fetchCompletion:m,fetchStreamingCompletion:d,onFallbackLog:f}),N=R?.data||R;if(!g(N))return{done:!0,text:y(N),body:R?.fallback||i};let v=h(N),I=R?.fallback||i;I.messages.push(S(N)),c&&typeof b=="function"&&b(v);let U=await Promise.all(v.map((E,C)=>(typeof t.onToolCall=="function"&&t.onToolCall(E.name,E.args,{round:s,index:C,total:v.length}),T(E,n))));for(let E=0;E<v.length;E++){let $=v[E].name==="get_skill_context"?typeof U[E]=="string"?U[E]:JSON.stringify(U[E]):qn(U[E],u);I.messages.push(w(v[E].id,$))}return typeof t.onToolCall=="function"&&t.onToolCall(null),O(I,o),{done:!1,body:I}}var to=J.ASSISTANT,ro=15,dt="get_skill_context";function Se(i){!i||typeof i!="object"||(i.type==="object"&&i.properties&&(i.required=Object.keys(i.properties),i.additionalProperties=!1,Object.values(i.properties).forEach(Se)),i.type==="array"&&i.items&&Se(i.items),i.anyOf&&i.anyOf.forEach(Se),i.oneOf&&i.oneOf.forEach(Se),i.allOf&&i.allOf.forEach(Se))}var ir={maxBytes:49e3,systemMaxChars:12e3},ye=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",no=i=>Buffer.byteLength(JSON.stringify(i),"utf8");function Qe(i){return Array.isArray(i)?new Set(i.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function oo(i){return Array.isArray(i)?i.map(e=>String(e||"").trim()).filter(Boolean):[]}var le=class extends eo{#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 he):(this.#e=e||new ae,this.#t=new he)}canHandle(e){return ft().ok}async invoke(e,t={}){let r=Y("OPENAI_API_KEY");try{let n=t.model&&t.model!=="auto"?t.model:to,o=ft();if(!o.ok)throw o.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):o.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):o.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${o.reason}).`);let s=t.messages||[{role:"user",content:e}],c=o.baseUrl,a=ye();if(a?await this.#m(s,n,c,o.tokenPreview||"none"):p.debug(`[Assistant] ${c} | model: ${n} | messages: ${s.length}`),t.schema)return this.#c(n,s,o,t);let l=t.activeSkills||[],u=this.#p(t),m=this.#f(l,u),d=this.#d(m),f=this.#u(t),g={...t,payloadCompaction:f},y={activeSkills:m,options:g,executionRegistry:d,capabilityPolicy:u},h=!!t.stream,S={model:n,messages:[...s],stream:!1};this.#o(S,m,u);for(let w=0;w<ro;w++){if(t.signal?.aborted){let b=new Error("Aborted via signal");throw b.name="AbortError",b}let T=await sr({body:S,auth:o,options:g,streaming:h,toolContext:y,activeSkills:m,round:w,verbose:a,dependencies:{fetchCompletion:this.#s.bind(this),fetchStreamingCompletion:this.#l.bind(this),onFallbackLog:(b,O)=>{ye()&&console.log(`413 fallback: messages ${b.messages.length} -> ${O.messages.length}, bytes=${no(O)}`)},hasToolCalls:b=>this.#e.hasToolCalls(b),getTextContent:b=>this.#e.getTextContent(b),parseToolCalls:b=>this.#e.parseToolCalls(b),buildAssistantMessage:b=>this.#e.buildAssistantMessage(b),buildToolResultMessage:(b,O)=>this.#e.buildToolResultMessage(b,O),executeTool:(b,O)=>this.#a(b,O),onToolCallLog:async b=>{let O=(await import("chalk")).default;console.log(O.dim(` ${b.map(R=>`${R.name}(${JSON.stringify(R.args).slice(0,80)})`).join(", ")}`))},injectTools:(b,O)=>this.#o(b,O,u)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(T.done)return T.text;S.messages=T.body.messages,T.body.tools?S.tools=T.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()}#o(e,t,r=null){let n=this.#i(t,r),o=this.#e.formatTools(n);this.#e.injectToolsIntoBody(e,o)}#i(e,t=null){let r=[],n=new Set;for(let o of e){let s=Ve(o);if(s?.tools?.length)for(let c of s.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(dt,t)&&r.push({name:dt,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),r}async#a(e,t){let{activeSkills:r,options:n,executionRegistry:o,capabilityPolicy:s}=t;if(!this.#n(e.name,s))return`Tool "${e.name}" blocked by policy`;if(e.name===dt){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=Ve(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),f=JSON.stringify({skillId:l,description:u.description||"",toolNames:d,promptFragment:m||""});return ye()&&(console.log(`
99
+ \u{1F4D6} get_skill_context("${l}") \u2192 ${f.length} chars (fragment: ${m.length} chars)`),console.log(` tools: [${d.join(", ")}]`),console.log(` fragment preview: ${m.slice(0,200).replace(/\n/g,"\\n")}\u2026
100
+ `)),f}let c=o?.get(e.name)||null;if(!c)return`Unknown tool: ${e.name}`;let a=Ve(c.skillId);if(!a)return`Skill "${c.skillId}" not found for tool "${e.name}"`;if(c.mode==="handler")try{return a.handleToolCall(e.name,e.args,t)}catch(l){return`Error in ${e.name}: ${l.message}`}if(c.mode==="mcp")try{if(!this.#r.isRunning(a.serverName)){let u=a.resolve(n);if(!u)return`Skill "${c.skillId}" is not available (cannot start server)`;await this.#r.ensureServer(a.serverName,u)}let l=await this.#r.callTool(a.serverName,e.name,e.args);return l.text||(l.isError?"Tool call failed":"Done")}catch(l){return`MCP error (${a.serverName}): ${l.message}`}return`Skill "${c.skillId}" owns tool "${e.name}" but has no execution mode`}async#l(e,t,r){return this.#t.fetchStreamingCompletion(e,t,{...r,onBudget:({beforeBytes:n,meta:o})=>{ye()&&console.log(`payload bytes (stream) before=${n} after=${o.bytes} trimmed=${o.trimmed} messages=${o.messageCount}`)}})}async#s(e,t,r){return this.#t.fetchCompletion(e,t,{...r,onBudget:({beforeBytes:n,meta:o})=>{ye()&&console.log(`payload bytes before=${n} after=${o.bytes} trimmed=${o.trimmed} messages=${o.messageCount}`)}})}async#c(e,t,r,n){let{zodToJsonSchema:o}=await import("zod-to-json-schema"),s=typeof n.schema?.parse=="function",c=s?o(n.schema):n.schema;delete c.$schema,Se(c);let a={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:c,strict:!0}}},l=await this.#s(a,r,n),u=this.#e.getTextContent(l),m=JSON.parse(u),d=s?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||ir.maxBytes),systemMaxChars:Number(t.systemMaxChars||ir.systemMaxChars)}}#p(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:Qe(t.allowTools||e.allowTools),denyTools:Qe(t.denyTools||e.denyTools),denyPrefixes:oo(t.denyPrefixes||e.denyToolPrefixes),includeSkills:Qe(t.includeSkills||e.includeSkills),excludeSkills:Qe(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#f(e,t){let r=t?.includeSkills||new Set,n=t?.excludeSkills||new Set;return r.size===0&&n.size===0?e:e.filter(o=>!(r.size>0&&!r.has(o)||n.has(o)))}#n(e,t){let r=String(e||"").trim();if(!r)return!1;let n=t?.allowTools;if(n&&n.size>0&&!n.has(r))return!1;let o=t?.denyTools;return!(o&&o.has(r)||(t?.denyPrefixes||[]).some(c=>r.startsWith(c)))}#d(e){let t=new Map,r=[];for(let n of e){let o=Ve(n);if(!o?.tools?.length)continue;let s=typeof o.handleToolCall=="function"?"handler":o.serverName&&typeof o.resolve=="function"?"mcp":null;if(s)for(let c of o.tools){let a=String(c?.name||"").trim();if(a){if(t.has(a)){r.push({tool:a,winner:t.get(a).skillId,skipped:n});continue}t.set(a,{skillId:n,mode:s})}}}if(r.length>0&&ye()){let n=r.slice(0,5).map(o=>`${o.tool}:${o.winner}>${o.skipped}`).join(", ");console.log(`tool registry collisions: ${n}${r.length>5?" ...":""}`)}return t}async#m(e,t,r,n){console.log(`
101
101
  \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 l of e)if(l.role==="system")console.log(s.dim(`[System] ${l.content||""}`));else{i||(console.log(s.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),i=!0);let c=l.role==="user"?"Human":"AI",a=l.content?.length>200?`${l.content.slice(0,200)}...`:l.content||"";console.log(s.dim(`[${c}] ${a}`))}console.log(s.dim("\u2500".repeat(60)))}};var _r=!1;function Et(){_r||(Be(new le),Be(new ne),Be(new se),Be(new oe),Be(new ae),_r=!0)}import{existsSync as je,readdirSync as Nr,statSync as Js}from"fs";import{join as H,relative as At,sep as Fe,resolve as ue}from"path";import{appendFileSync as ks,readFileSync as Ms,existsSync as Er,mkdirSync as Ls}from"node:fs";import{join as ot}from"node:path";import{DEFAULT_OUTPUT_BASE as Tr}from"@zibby/agent-workflow";var vr="run-index.jsonl";function Ar(o,e=Tr){let t=ot(o,e);return ot(t,vr)}function it(o){if(!o||!o.sessionId)return;let e=o.cwd||process.cwd(),t=o.outputBase||Tr,r=ot(e,t);Er(r)||Ls(r,{recursive:!0});let n=ot(r,vr),s=`${JSON.stringify(o)}
103
- `;ks(n,s,"utf8")}function Ir(o){if(!o||!Er(o))return[];let e;try{e=Ms(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 Ds,mkdirSync as Us,readFileSync as Bs,readdirSync as Zc,statSync as Wc,writeFileSync as Fs}from"node:fs";import{join as js}from"node:path";var Gs="zibby-run-state.json";function $r(o){return js(o,Gs)}function Tt(o){if(!o||typeof o!="string")return null;let e=$r(o);if(!Ds(e))return null;try{let t=Bs(e,"utf8"),r=JSON.parse(t);return r&&typeof r=="object"?r:null}catch{return null}}function at(o,e){if(!o||typeof o!="string")return;try{Us(o,{recursive:!0})}catch{return}let r={...Tt(o)||{v:1},...e,v:1,updatedAt:Date.now()};try{Fs($r(o),`${JSON.stringify(r)}
105
- `,"utf8")}catch(n){console.warn(`[zibby run-state] ${n.message}`)}}function Ks(o){return o?.recordKind==="progress"}function Or(o){let e=Number(o)||0;return e<=0?0:e<1e12?e*1e3:e}function Pr(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=Or(s.ts);if(t>0&&i>0&&r-i>t)return!1;if(!n)return i>0;let l=Or(n.ts);return i>l}function Cr(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;Ks(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 pe,SESSIONS_DIR as It}from"@zibby/agent-workflow";var vt=Object.freeze(["preflight","execute_live","generate_script"]);function $t(o){let e=process.env.ZIBBY_STUDIO_TEST_CASE_ID;return e!=null&&String(e).trim()!==""?String(e).trim():o!=null?String(o):""}var zs=[H("generate_script","generated-test.spec.js"),H("generate_script","generated-test.spec.ts"),H("generate_script","playwright.spec.ts"),H("generate_script","test.spec.ts")];function Ys(o){let e=[H(o,"execute_live","videos"),H(o,"execute_live"),o];for(let t of e){if(!je(t))continue;let r;try{r=Nr(t)}catch{continue}let n=r.find(s=>s.endsWith(".webm"));if(n)return H(t,n)}return null}function Hs(o){let e=[H(o,"execute_live","events.json"),H(o,"events.json")];for(let t of e)if(je(t))return t;return null}function Zs(o){for(let e of zs){let t=H(o,e);if(je(t))return t}return null}function Ws(o){return!o||!je(o)?{videoPathAbs:null,eventsPathAbs:null,scriptPathAbs:null}:{videoPathAbs:Ys(o),eventsPathAbs:Hs(o),scriptPathAbs:Zs(o)}}function Rr(o){let e=o.cwd||process.cwd(),t=o.outputBase||pe,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:l,eventsPathAbs:c,scriptPathAbs:a}=Ws(s),u=d=>{if(!d)return null;try{return At(e,d).split(Fe).join("/")}catch{return null}},m=null;if(o.specPath)try{let d=ue(e,o.specPath);m=At(e,d).split(Fe).join("/")}catch{m=String(o.specPath).split(Fe).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:l||null,eventsPathAbs:c||null,scriptPathAbs:a||null,videoRel:u(l),eventsRel:u(c),scriptRel:u(a),specRel:m,source:process.env.ZIBBY_RUN_SOURCE||"cli",studioTestCaseId:$t(i)||null,errorMessage:o.errorMessage||null}}function kr({cwd:o,config:e,result:t,success:r,specPath:n,errorMessage:s}){try{let i=Rr({cwd:o||process.cwd(),result:t,success:r,outputBase:e?.paths?.output||pe,specPath:n,errorMessage:s});i&&(it(i),i.sessionPathAbs&&at(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 Xs({sessionPath:o,sessionId:e,cwd:t,outputBase:r=pe}={}){let n=t||process.cwd(),s=r||pe,i=e!=null&&String(e).trim()!==""?String(e).trim():null,l=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(l&&c)return ue(c);let a=o&&String(o).trim();if(a)return ue(a);let u=process.env.ZIBBY_SESSIONS_ROOT&&String(process.env.ZIBBY_SESSIONS_ROOT).trim();return u&&i?ue(H(u,i)):process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim()?ue(String(process.env.ZIBBY_SESSION_PATH).trim()):ue(H(n,s,It,i||"invalid"))}function qs(o){try{let e=o?.currentNode;if(!e||!vt.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||pe,i=vt.indexOf(e),l=o?.specPath!=null?String(o.specPath).trim():"",c=o?.taskDescription!=null?String(o.taskDescription):"",a=null;if(l)try{let m=ue(n,l);a=At(n,m).split(Fe).join("/")}catch{a=l.split(Fe).join("/")}let u=Xs({sessionPath:t,sessionId:r,cwd:n,outputBase:s});it({v:1,recordKind:"progress",ts:Date.now(),sessionId:r,cwd:n,outputBase:s,sessionPathAbs:u,activeNode:e,activeStageIndex:i,specRel:a,taskDescription:c||null,studioTestCaseId:$t(r)||null,source:process.env.ZIBBY_RUN_SOURCE||"cli"}),at(u,{sessionId:r,studioTestCaseId:$t(r)||r,status:"running",activeNode:e,activeStageIndex:i,sessionPathAbs:u,cwd:n,outputBase:s,specPath:a||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 Mr({cwd:o,config:e}={}){let t=o||process.cwd(),r=e?.paths?.output||pe;return n=>{qs({cwd:n?.cwd||t,outputBase:n?.outputBase||r,sessionPath:n?.sessionPath,sessionId:n?.sessionId,currentNode:n?.currentNode,specPath:n?.specPath,taskDescription:n?.taskDescription})}}function Lr(o={}){try{let e=o.cwd||process.cwd(),t=o.config?.paths?.output||o.outputBase||pe,r=Ar(e,t),n=Ir(r),s=Cr(n),i=new Set,l=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=Rr({cwd:e,outputBase:t,result:{state:{sessionPath:d}},success:!1,specPath:null,status:"interrupted",errorMessage:l});p&&(it(p),at(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(!Pr(d))continue;let p=d.progress;if(!p)continue;let g=String(m),y=p.sessionPathAbs&&String(p.sessionPathAbs)||H(e,t,It,g);c(g,y)}let a=H(e,t,It);if(!je(a))return;let u;try{u=Nr(a)}catch{return}for(let m of u){let d=H(a,m),p;try{p=Js(d)}catch{continue}if(!p.isDirectory())continue;let g=Tt(d);!g||g.status!=="running"||c(String(m),d)}}catch(e){console.warn(`[zibby browser-test run-index interrupt] ${e.message}`)}}function ct(o){kr(o)}function Ot(o){Lr(o)}function Dr(o){return Mr(o)}import{spawn as no}from"node:child_process";import{mkdirSync as Br,existsSync as so,writeFileSync as oo}from"node:fs";import{join as Rt}from"node:path";import{ContextLoader as io,WorkflowGraph as ao,Node as co,WorkflowState as lo,DEFAULT_OUTPUT_BASE as Fr,SESSIONS_DIR as uo,SESSION_INFO_FILE as po}from"@zibby/agent-workflow";import{exec as Vs}from"node:child_process";import{promisify as Qs}from"node:util";import{existsSync as eo}from"node:fs";import{join as Pt}from"node:path";import{homedir as Ct}from"node:os";var Ur=Qs(Vs);async function Nt(){try{return await Ur("cursor-agent --version"),"cursor-agent"}catch{let e=[Pt(Ct(),".local","bin","cursor-agent"),Pt(Ct(),".cursor","bin","cursor-agent"),Pt(Ct(),".cursor-agent","bin","cursor-agent")];for(let t of e)if(eo(t))try{return await Ur(`"${t}" --version`),t}catch{}return null}}async function to(){return await Nt()!==null}function ro(){return`
102
+ `);let o=(await import("chalk")).default;console.log(o.bold("Prompt sent to LLM:")),console.log(o.dim("\u2500".repeat(60)));let s=!1;for(let c of e)if(c.role==="system")console.log(o.dim(`[System] ${c.content||""}`));else{s||(console.log(o.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),s=!0);let a=c.role==="user"?"Human":"AI",l=c.content?.length>200?`${c.content.slice(0,200)}...`:c.content||"";console.log(o.dim(`[${a}] ${l}`))}console.log(o.dim("\u2500".repeat(60)))}};var ar=!1;function mt(){ar||(Me(new le),Me(new re),Me(new ne),Me(new oe),Me(new ie),ar=!0)}function lr(i){return null}import{spawn as uo}from"node:child_process";import{mkdirSync as ur,existsSync as po,writeFileSync as fo}from"node:fs";import{join as St}from"node:path";import{ContextLoader as mo,WorkflowGraph as go,Node as ho,WorkflowState as yo,DEFAULT_OUTPUT_BASE as pr,SESSIONS_DIR as So,SESSION_INFO_FILE as bo}from"@zibby/agent-workflow";import{exec as so}from"node:child_process";import{promisify as io}from"node:util";import{existsSync as ao}from"node:fs";import{join as gt}from"node:path";import{homedir as ht}from"node:os";var cr=io(so);async function yt(){try{return await cr("cursor-agent --version"),"cursor-agent"}catch{let e=[gt(ht(),".local","bin","cursor-agent"),gt(ht(),".cursor","bin","cursor-agent"),gt(ht(),".cursor-agent","bin","cursor-agent")];for(let t of e)if(ao(t))try{return await cr(`"${t}" --version`),t}catch{}return null}}async function lo(){return await yt()!==null}function co(){return`
106
103
  \u274C cursor-agent CLI not found!
107
104
 
108
105
  To use the Cursor agent, install it from:
@@ -119,41 +116,41 @@ After installation:
119
116
  2. Or restart your terminal/shell
120
117
 
121
118
  Then retry your command.
122
- `}var _e=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 X.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(`
119
+ `}var be=class i{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 Z.extractResult(e)}async initialize(e){this.adapter=e,e&&!e.isConnected()&&await e.connect()}buildGraph(){throw new Error("buildGraph() must be implemented by subclass")}async onComplete(e){}async run(e,t={}){let r=this.buildGraph(),n=typeof e=="object"&&!Array.isArray(e)?{input:e,...e,...t}:{input:e,...t};return await r.run(this,n)}async executeNode(e,t){let{prompt:r,outputSchema:n,model:o}=e,s=typeof r=="function"?r(t):r;console.log(`
123
120
  \u{1F4DD} Prompt:
124
- ${i}
125
- `);let l=await this.executePrompt(i,t.cwd,3e5,s);console.log(`
121
+ ${s}
122
+ `);let c=await this.executePrompt(s,t.cwd,3e5,o);console.log(`
126
123
  \u{1F4E4} Raw Output:
127
- ${l}
128
- `);let c=null;if(n)try{if(c=o.extractJsonFromStream(l),!c)throw new Error("No valid result JSON found in output");console.log(`
124
+ ${c}
125
+ `);let a=null;if(n)try{if(a=i.extractJsonFromStream(c),!a)throw new Error("No valid result JSON found in output");console.log(`
129
126
  \u2705 Parsed Output:
130
- ${JSON.stringify(c,null,2)}
131
- `)}catch(a){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${a.message}`)}return{success:!0,output:c,raw:l}}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 l=await Nt();l&&(i=l)}return new Promise((l,c)=>{let a="",u=this.buildArgs(e,s);n&&u.push("--model",n);let m={...process.env},d=no(i,u,{cwd:t,env:m,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),p=setTimeout(()=>{console.log(`
132
- \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(a.length>g)g=a.length,y=Date.now();else{let b=Date.now()-y;b>1e4&&console.log(`\u23F3 AI agent is thinking... (${Math.floor(b/1e3)}s, ${a.length} bytes so far)`)}},1e4),S=()=>{clearTimeout(p),clearInterval(h),d&&!d.killed&&(d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},2e3))},w=()=>{console.log(`
127
+ ${JSON.stringify(a,null,2)}
128
+ `)}catch(l){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${l.message}`)}return{success:!0,output:a,raw:c}}async cleanup(){this.adapter&&this.adapter.isConnected()&&await this.adapter.disconnect()}async executePrompt(e,t=process.cwd(),r=3e5,n=null,o=!0){let s=this.agentCommand;if(s==="cursor-agent"){let c=await yt();c&&(s=c)}return new Promise((c,a)=>{let l="",u=this.buildArgs(e,o);n&&u.push("--model",n);let m={...process.env},d=uo(s,u,{cwd:t,env:m,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),f=setTimeout(()=>{console.log(`
129
+ \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),a(new Error(`Agent timed out after ${r/1e3}s. The agent may be stuck or waiting for user input.`))},r),g=0,y=Date.now(),h=setInterval(()=>{if(l.length>g)g=l.length,y=Date.now();else{let b=Date.now()-y;b>1e4&&console.log(`\u23F3 AI agent is thinking... (${Math.floor(b/1e3)}s, ${l.length} bytes so far)`)}},1e4),S=()=>{clearTimeout(f),clearInterval(h),d&&!d.killed&&(d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},2e3))},w=()=>{console.log(`
133
130
 
134
- \u{1F6D1} Interrupted by user (Ctrl+C)`),S(),c(new Error("Interrupted by user"))};process.on("SIGINT",w);let T=new X;d.stdout.on("data",b=>{let $=b.toString();a+=$;let k=T.processChunk($);k&&(process.stdout.write(k,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),y=Date.now(),g+=k.length)}),d.on("close",b=>{process.off("SIGINT",w),clearTimeout(p),clearInterval(h);let $=T.flush();$&&process.stdout.write($),a=T.getRawText();let k=T.getResult();b===0?l({raw:a,extracted:k}):c(new Error(`Agent exited with code ${b}`))}),d.on("error",b=>{process.off("SIGINT",w),clearTimeout(p),clearInterval(h),c(new Error(`Failed to spawn agent: ${b.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,l=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,w=S?`${S}_${h}`:h;l=l||Date.now();let T=c.paths?.output||Fr;i=Rt(s,T,uo,w),so(i)||Br(i,{recursive:!0})}let a=c.paths?.output||Fr,u=Rt(s,a,po);Br(Rt(s,a),{recursive:!0}),oo(u,JSON.stringify({sessionPath:i,sessionTimestamp:l||i.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
135
- ${"=".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 m=await io.loadContext(r.specPath||"",s,r.contextConfig||{}),d=new lo({...r,sessionPath:i,sessionTimestamp:l,context:m}),g=await new co(n).execute(this,d);return console.log(`
131
+ \u{1F6D1} Interrupted by user (Ctrl+C)`),S(),a(new Error("Interrupted by user"))};process.on("SIGINT",w);let T=new Z;d.stdout.on("data",b=>{let O=b.toString();l+=O;let R=T.processChunk(O);R&&(process.stdout.write(R,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),y=Date.now(),g+=R.length)}),d.on("close",b=>{process.off("SIGINT",w),clearTimeout(f),clearInterval(h);let O=T.flush();O&&process.stdout.write(O),l=T.getRawText();let R=T.getResult();b===0?c({raw:l,extracted:R}):a(new Error(`Agent exited with code ${b}`))}),d.on("error",b=>{process.off("SIGINT",w),clearTimeout(f),clearInterval(h),a(new Error(`Failed to spawn agent: ${b.message}`))})})}async runSingleNode(e,t,r){let n=t[e];if(!n)throw new Error(`Unknown node: ${e}. Available nodes: ${Object.keys(t).join(", ")}`);let{cwd:o}=r;if(!o)throw new Error("cwd is required for single node execution");let s=r.sessionPath,c=r.sessionTimestamp,a=r.config||{};if(!s){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=a.paths?.sessionPrefix,w=S?`${S}_${h}`:h;c=c||Date.now();let T=a.paths?.output||pr;s=St(o,T,So,w),po(s)||ur(s,{recursive:!0})}let l=a.paths?.output||pr,u=St(o,l,bo);ur(St(o,l),{recursive:!0}),fo(u,JSON.stringify({sessionPath:s,sessionTimestamp:c||s.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
132
+ ${"=".repeat(80)}`),console.log(`\u{1F3AF} SINGLE NODE EXECUTION: ${e}`),console.log(`\u{1F4C1} Session: ${s.split("/").pop()}${r.sessionPath?" (reusing)":""}`),console.log(`${"=".repeat(80)}
133
+ `);let m=await mo.loadContext(r.specPath||"",o,r.contextConfig||{}),d=new yo({...r,sessionPath:s,sessionTimestamp:c,context:m}),g=await new ho(n).execute(this,d);return console.log(`
137
134
  ${"=".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 fo(o,e={}){let t=new _e(e);return t.buildGraph=function(){let r=new ao;return o(r),r},e.onComplete&&(t.onComplete=e.onComplete),t}import{WorkflowGraph as cf,resolveWorkflowSession as lf,generateWorkflowSessionId as uf,clearInheritedSessionEnvForFreshRun as pf,shouldTrustInheritedSessionEnv as ff,readPinnedSessionPathFromEnv as df,syncProcessEnvToSession as mf}from"@zibby/agent-workflow";import{writeFileSync as jr,existsSync as mo,mkdirSync as go}from"node:fs";import{join as kt}from"node:path";var Mt=class o{static saveTitle(e,t){let r=e.state.sessionPath;if(!r)return;let n=o._findInState(e.state,"title")||o._findInState(e.state,"result");if(!(!n||typeof n!="string"))try{let s=kt(r,"title.txt");jr(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 l=kt(t,r);mo(l)||go(l,{recursive:!0});let c=kt(l,"result.json");jr(c,JSON.stringify(n,null,2),"utf-8"),f.info(`Saved execution data to ${r} folder`),await this.onNodeSaved(l,n)}catch(l){console.warn(`\u26A0\uFE0F Could not save execution data for ${r}:`,l.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(([,l])=>!l.success).map(([l])=>l);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 yf}from"zod/v3";import{AgentStrategy as yo}from"@zibby/agent-workflow";var Gr=[new le,new ne,new se,new oe,new ae];function Kr(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=Gr.find(s=>s.getName()===r);if(!n)throw new Error(`Unknown agent '${r}'. Available: ${Gr.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 ho(o,e={},t={}){try{await import("@zibby/skills")}catch{}let r=Kr(e),n=e.state?.config||t.config||{},s=n.models||{},i=t.nodeName&&s[t.nodeName]||null,l=s.default||null,c=r.name,a=n.agent?.[c]?.model||null,u=i||l||a||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 w=y(S)?.promptFragment;return typeof w=="function"?w():w}).filter(Boolean);h.length>0&&(p+=`
135
+ `),{success:!0,output:g.output,outputPath:r.outputPath,state:g}}calculateOutputPath(e){let{specs:t,generated:r}=this.paths;if(!e)return`${r}/generated-test.spec.js`;let n=e.replace(new RegExp(`^${t}/`),"").replace(/\.[^.]+$/,".spec.js");return`${r}/${n}`.replace(/\/+/g,"/")}};function wo(i,e={}){let t=new be(e);return t.buildGraph=function(){let r=new go;return i(r),r},e.onComplete&&(t.onComplete=e.onComplete),t}import{WorkflowGraph as Xu,resolveWorkflowSession as qu,generateWorkflowSessionId as Vu,clearInheritedSessionEnvForFreshRun as Qu,shouldTrustInheritedSessionEnv as ep,readPinnedSessionPathFromEnv as tp,syncProcessEnvToSession as rp}from"@zibby/agent-workflow";import{writeFileSync as fr,existsSync as _o,mkdirSync as xo}from"node:fs";import{join as bt}from"node:path";var wt=class i{static saveTitle(e,t){let r=e.state.sessionPath;if(!r)return;let n=i._findInState(e.state,"title")||i._findInState(e.state,"result");if(!(!n||typeof n!="string"))try{let o=bt(r,"title.txt");fr(o,n,"utf-8"),p.info(`Saved title to session: "${n}"`)}catch(o){console.warn("\u26A0\uFE0F Could not save title file:",o.message)}}static _findInState(e,t){for(let[,r]of Object.entries(e))if(r&&typeof r=="object"&&r[t]!==void 0)return r[t]}static async saveExecutionData(e){let t=e.state.sessionPath;if(t)for(let[r,n]of Object.entries(e.state)){if(!n||typeof n!="object")continue;let o=Array.isArray(n.actions)&&n.actions.length>0,s=typeof n.scriptPath=="string"&&n.scriptPath.trim().length>0;if(!(!o&&!s))try{let c=bt(t,r);_o(c)||xo(c,{recursive:!0});let a=bt(c,"result.json");fr(a,JSON.stringify(n,null,2),"utf-8"),p.info(`Saved execution data to ${r} folder`),await this.onNodeSaved(c,n)}catch(c){console.warn(`\u26A0\uFE0F Could not save execution data for ${r}:`,c.message)}}}static async onNodeSaved(e,t){}static logResult(e,t){let r=Object.entries(e.state).filter(([,s])=>s&&typeof s=="object"&&s.success!==void 0),n=r.length>0&&r.every(([,s])=>s.success),o=r.some(([,s])=>s.success===!1);if(n)p.info("Workflow completed successfully."),t&&p.info(`Output: ${t}`);else if(o){let s=r.filter(([,c])=>!c.success).map(([c])=>c);p.info(`Workflow completed with failures in: ${s.join(", ")}`),t&&p.info(`Output: ${t}`)}return n}static handle(e,t,r){return this.saveTitle(e,t),this.saveExecutionData(e),this.logResult(e,r)}};import{z as sp}from"zod/v3";import{AgentStrategy as To}from"@zibby/agent-workflow";var dr=[new le,new re,new ne,new oe,new ie];function mr(i={}){let{state:e={},preferredAgent:t=null}=i,r=t||e.agentType||process.env.AGENT_TYPE;if(!r)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");p.debug(`Agent selection: requested=${r}`);let n=dr.find(o=>o.getName()===r);if(!n)throw new Error(`Unknown agent '${r}'. Available: ${dr.map(o=>o.getName()).join(", ")}`);if(p.debug(`Checking if ${r} can handle this environment...`),!n.canHandle(i)){let s={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. ${s}`)}return p.debug(`Using agent: ${n.getName()}`),n}async function Eo(i,e={},t={}){try{await import("@zibby/skills")}catch{}let r=mr(e),n=e.state?.config||t.config||{},o=n.models||{},s=t.nodeName&&o[t.nodeName]||null,c=o.default||null,a=r.name,l=n.agent?.[a]?.model||null,u=s||c||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||[],f=i;if(d.length>0&&!t.skipPromptFragments){let{getSkill:y}=await import("@zibby/agent-workflow"),h=d.map(S=>{let w=y(S)?.promptFragment;return typeof w=="function"?w():w}).filter(Boolean);h.length>0&&(f+=`
139
136
 
140
137
  ${h.join(`
141
138
 
142
- `)}`)}let g=e.state?._currentNodeConfig?.extraPromptInstructions?.trim();return g&&(p+=`
139
+ `)}`)}let g=e.state?._currentNodeConfig?.extraPromptInstructions?.trim();return g&&(f+=`
143
140
 
144
141
  \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
145
142
  \u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
146
143
  \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
147
144
 
148
145
  ${g}
149
- `),f.debug(`Prompt length: ${p.length} chars`),process.env.STAGE!=="prod"&&f.debug(`Full prompt:
150
- ${p}`),r.invoke(p,m)}import{SKILLS as Ef}from"@zibby/agent-workflow";import{registerSkill as vf,getSkill as Af,hasSkill as If,getAllSkills as $f,listSkillIds as Of}from"@zibby/agent-workflow";var So={READ_FILE:"read_file",WRITE_FILE:"write_file",LIST_DIRECTORY:"list_directory",RUN_COMMAND:"run_command",OPEN_URL:"open_url",WAIT:"wait"},bo={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"},wo={GET_USER:"github_get_user",LIST_ORGS:"github_list_orgs",LIST_REPOS:"github_list_repos",CLONE:"github_clone",SEARCH_REPOS:"github_search_repos",SEARCH_ISSUES:"github_search_issues",SEARCH_CODE:"github_search_code",GET_PR:"github_get_pr",GET_PR_DIFF:"github_get_pr_diff",LIST_PR_FILES:"github_list_pr_files",LIST_PR_COMMENTS:"github_list_pr_comments",LIST_COMMITS:"github_list_commits",GET_COMMIT:"github_get_commit",GET_FILE:"github_get_file",CREATE_ISSUE:"github_create_issue"},xo={LIST_CHANNELS:"slack_list_channels",POST_MESSAGE:"slack_post_message",REPLY_TO_THREAD:"slack_reply_to_thread",ADD_REACTION:"slack_add_reaction",GET_CHANNEL_HISTORY:"slack_get_channel_history",GET_THREAD_REPLIES:"slack_get_thread_replies",GET_USERS:"slack_get_users",GET_USER_PROFILE:"slack_get_user_profile"},_o={GENERATE:"run_generate",TEST:"run_test",STATUS:"run_status",CANCEL:"run_cancel",WAIT:"run_wait",ARTIFACTS:"run_artifacts",LIST_SPECS:"list_specs"},Eo={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"},To={STORE:"memory_store",RECALL:"memory_recall",BRIEF:"memory_brief",END_SESSION:"memory_end_session",TASK_LOG:"task_log",TASK_HISTORY:"task_history"},vo={INSTALL:"install_skill",UNINSTALL:"uninstall_skill",LIST_AVAILABLE:"list_available_skills"},Ml={...So,...bo,...wo,...xo,..._o,...Eo,...To,...vo};import{existsSync as Ao,readFileSync as Io}from"node:fs";import{homedir as $o}from"node:os";import{join as Oo}from"node:path";var lt=new Map;function Po(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let o=Oo($o(),".zibby","config.json");return Ao(o)&&JSON.parse(Io(o,"utf-8")).sessionToken||null}catch{return null}}function Co(){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=lt.get(o);if(t&&t.expiresAt>e)return t.data;let r=Po();if(!r)throw new Error("No session token. Run `zibby login` first.");let n=`${Co()}/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 l=((i.expiresInSec||3e3)-120)*1e3;return lt.set(o,{data:i,expiresAt:e+l}),i}function Ro(o){o?lt.delete(o):lt.clear()}import{readdir as ko,access as Jr,copyFile as Mo,constants as zr}from"fs/promises";import{join as ut,relative as Lo}from"node:path";async function Do(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=ut(r,e),i=ut(r,t);try{let l=await ko(s),c=0;for(let a of l){if(a.startsWith("."))continue;let u=ut(s,a,"video.webm");try{await Jr(u,zr.F_OK)}catch{continue}let m=a.replace(/-chromium$/,"").replace(/-firefox$/,"").replace(/-webkit$/,""),d=await Uo(i,m);if(d){let p=d.replace(/\.spec\.(js|ts)$/,".spec.webm");await Mo(u,p),n&&console.log(`\u2705 ${Lo(r,p)}`),c++}else n&&console.log(`\u26A0\uFE0F Could not find test file for: ${a}`)}return n&&(console.log(`
152
- \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(l){return n&&console.error("\u274C Error organizing videos:",l.message),{movedCount:0,success:!1,error:l.message}}}async function Uo(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 l=ut(o,`${s}.spec.${i}`);try{return await Jr(l,zr.F_OK),l}catch{}}}return null}var Ge=class{constructor(e,t={}){this.apiKey=e,this.baseUrl=t.baseUrl||process.env.ZIBBY_API_URL||"https://api-prod.zibby.app",this.enabled=!!e}isEnabled(){return this.enabled}};function Yr(){let o=process.env.ZIBBY_API_KEY;return new Ge(o)}import{execSync as Bo}from"node:child_process";import{existsSync as Fo,mkdirSync as jo}from"node:fs";import{join as Go}from"node:path";async function Ko(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 l=t?i.filter(a=>t.includes(a.name)):i;if(l.length===0)throw new Error(`No matching repositories found. Available: ${i.map(a=>a.name).join(", ")}`);Fo(e)||jo(e,{recursive:!0});let c={};return await Promise.all(l.map(async a=>{let u=a.provider||"github",m=u==="gitlab"?process.env.GITLAB_TOKEN:process.env.GITHUB_TOKEN;if(!m){console.error(`${u.toUpperCase()}_TOKEN not set, skipping ${a.name}`),c[a.name]=null;return}let d=a.name.replace(/\//g,"-"),p=Go(e,d),g=a.cloneUrl||a.url;if(!g){console.error(`Repository "${a.name}" has no clone URL`),c[a.name]=null;return}let y;u==="gitlab"?y=g.replace(/^https:\/\//,`https://oauth2:${m}@`):y=g.replace(/^https:\/\//,`https://x-access-token:${m}@`);let h=["clone"];r>0&&h.push("--depth",r.toString()),n&&h.push("--branch",n),h.push(y,p);let S=`git ${h.join(" ")}`;console.log(`Cloning ${a.name} (${u}) to ${p}...`);try{Bo(S,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),console.log(`Repository ${a.name} cloned successfully`),c[a.name]=p}catch(w){let T=w.message.replace(m,"***").replace(y,g);console.error(`Failed to clone ${a.name}: ${T}`),c[a.name]=null}})),c}var Hr=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Jo(o){return typeof o=="string"&&Hr.test(o)}var Zr=Jo;function zo(o){if(!Zr(o))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(o.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(o.slice(9,13),16))>>>8,e&255,(e=parseInt(o.slice(14,18),16))>>>8,e&255,(e=parseInt(o.slice(19,23),16))>>>8,e&255,(e=parseInt(o.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}var Lt=zo;var K=[];for(let o=0;o<256;++o)K.push((o+256).toString(16).slice(1));function Wr(o,e=0){return(K[o[e+0]]+K[o[e+1]]+K[o[e+2]]+K[o[e+3]]+"-"+K[o[e+4]]+K[o[e+5]]+"-"+K[o[e+6]]+K[o[e+7]]+"-"+K[o[e+8]]+K[o[e+9]]+"-"+K[o[e+10]]+K[o[e+11]]+K[o[e+12]]+K[o[e+13]]+K[o[e+14]]+K[o[e+15]]).toLowerCase()}function Yo(o){o=unescape(encodeURIComponent(o));let e=new Uint8Array(o.length);for(let t=0;t<o.length;++t)e[t]=o.charCodeAt(t);return e}var Xr="6ba7b810-9dad-11d1-80b4-00c04fd430c8",qr="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Dt(o,e,t,r,n,s){let i=typeof t=="string"?Yo(t):t,l=typeof r=="string"?Lt(r):r;if(typeof r=="string"&&(r=Lt(r)),r?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+i.length);if(c.set(l),c.set(i,l.length),c=e(c),c[6]=c[6]&15|o,c[8]=c[8]&63|128,n){if(s=s||0,s<0||s+16>n.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let a=0;a<16;++a)n[s+a]=c[a];return n}return Wr(c)}import{createHash as Ho}from"crypto";function Zo(o){return Array.isArray(o)?o=Buffer.from(o):typeof o=="string"&&(o=Buffer.from(o,"utf8")),Ho("sha1").update(o).digest()}var Vr=Zo;function Ut(o,e,t,r){return Dt(80,Vr,o,e,t,r)}Ut.DNS=Xr;Ut.URL=qr;var Bt=Ut;var Qr="@zibby/core ZibbySessionStore/1",Ke=class{constructor({apiUrl:e,apiKey:t,workflowUuid:r,fetchImpl:n=globalThis.fetch}){if(!e)throw new Error("ZibbySessionStore: apiUrl is required");if(!t)throw new Error("ZibbySessionStore: apiKey is required");if(!r)throw new Error("ZibbySessionStore: workflowUuid is required");this._apiUrl=String(e).replace(/\/+$/,""),this._apiKey=t,this._workflowUuid=r,this._fetch=n}async append(e,t){if(!Array.isArray(t)||t.length===0)return;let r=`${this._apiUrl}/workflows/${encodeURIComponent(this._workflowUuid)}/sessions/${encodeURIComponent(e.sessionId)}/append`,n=await this._fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this._apiKey}`,"Content-Type":"application/json","User-Agent":Qr},body:JSON.stringify({entries:t})});if(!n.ok)throw new Error(`ZibbySessionStore.append HTTP ${n.status}`)}async load(e){let t=`${this._apiUrl}/workflows/${encodeURIComponent(this._workflowUuid)}/sessions/${encodeURIComponent(e.sessionId)}`,r;try{r=await this._fetch(t,{method:"GET",headers:{Authorization:`Bearer ${this._apiKey}`,"User-Agent":Qr}})}catch{return null}if(r.status===404||!r.ok)return null;let n;try{n=await r.json()}catch{return null}let s=Array.isArray(n?.entries)?n.entries:null;return s&&s.length>0?s:null}};var Wo="6ba7b810-9dad-11d1-80b4-00c04fd430c8",en=new Set;function Xo(){return(process.env.PROGRESS_API_URL||process.env.ZIBBY_API_BASE||"").replace(/\/executions\/?$/,"").replace(/\/+$/,"")}function tn({namespace:o=Wo}={}){return{id:"session",description:"Persist agent conversation state across invocations (Claude-only in v1)",envKeys:[],tools:[],invokeAgentOptions(e,t){let r=e?.conversationId,n=e?.workflowUuid;if(!r||!n)return null;let s=t?.agentType;if(s&&s!=="claude")return en.has(s)||(console.warn(`[SKILLS.SESSION] agent type '${s}' does not support native sessions \u2014 node running stateless`),en.add(s)),null;let i=Bt(`${n}:${r}`,o),l=Xo(),c=process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN,a=null;if(l&&c)try{a=new Ke({apiUrl:l,apiKey:c,workflowUuid:n})}catch(d){console.warn(`[SKILLS.SESSION] failed to build SessionStore: ${d.message}`),a=null}return e.resetConversation?{sessionId:i,resume:i,forkSession:!0,...a&&{sessionStore:a}}:e.hasPriorSession?{resume:i,...a&&{sessionStore:a}}:{sessionId:i,...a&&{sessionStore:a}}}}}import{spawn as rn}from"node:child_process";import{readFileSync as qo,writeFileSync as Vo,existsSync as pt}from"node:fs";import{homedir as nn}from"node:os";import{join as Ee}from"node:path";async function Qo(){let o=Ee(nn(),".local/share/cursor-agent/versions");if(!pt(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=Ee(__dirname,"../../scripts/patch-cursor-mcp.py");if(!pt(r)){t(new Error("Patch script not found"));return}let n=rn("python3",[r],{stdio:"inherit"});n.on("close",s=>{s===0?e({success:!0}):t(new Error(`Patch failed with code ${s}`))}),n.on("error",s=>{t(s)})})}function ei(){let o=Ee(nn(),".local/share/cursor-agent/versions");if(!pt(o))return{patched:!1,installed:!1};try{let e=En("fs").readdirSync(o);if(e.length===0)return{patched:!1,installed:!1};let t=e.sort().reverse()[0],r=Ee(o,t,"index.js");return pt(r)?{patched:qo(r,"utf-8").includes("AUTO-APPROVE MCP TOOLS FOR CI/CD"),installed:!0,path:r}:{patched:!1,installed:!1}}catch(e){return{patched:!1,installed:!1,error:e.message}}}async function ti(o){return console.log(`\u{1F511} Getting MCP approval keys...
154
- `),new Promise((e,t)=>{let r=rn("cursor-agent",["mcp","list"],{cwd:o,stdio:"pipe"}),n="";r.stdout.on("data",s=>{n+=s.toString(),process.stdout.write(s)}),r.stderr.on("data",s=>{process.stderr.write(s)}),r.on("close",s=>{if(s===0){let i=ri(n);e({success:!0,keys:i,output:n})}else t(new Error(`Failed to get approval keys (exit code ${s})`))}),r.on("error",s=>{t(s)})})}function ri(o){let e={},t=/🔑 APPROVAL KEY:\s+(\S+)\s+=>\s+(\S+)/g,r;for(;(r=t.exec(o))!==null;)e[r[1]]=r[2];return e}function ni(o,e){let t=Ee(o,".cursor/projects"),r=Ee(t,"mcp-approvals.json");Vo(r,JSON.stringify(e,null,2)),console.log(`
146
+ `),p.debug(`Prompt length: ${f.length} chars`),process.env.STAGE!=="prod"&&p.debug(`Full prompt:
147
+ ${f}`),r.invoke(f,m)}import{SKILLS as pp}from"@zibby/agent-workflow";import{registerSkill as dp,getSkill as mp,hasSkill as gp,getAllSkills as hp,listSkillIds as yp}from"@zibby/agent-workflow";var vo={READ_FILE:"read_file",WRITE_FILE:"write_file",LIST_DIRECTORY:"list_directory",RUN_COMMAND:"run_command",OPEN_URL:"open_url",WAIT:"wait"},Ao={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"},$o={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"},Co={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"},Po={STORE:"memory_store",RECALL:"memory_recall",BRIEF:"memory_brief",END_SESSION:"memory_end_session",TASK_LOG:"task_log",TASK_HISTORY:"task_history"},ko={INSTALL:"install_skill",UNINSTALL:"uninstall_skill",LIST_AVAILABLE:"list_available_skills"},xl={...vo,...Ao,...$o,...Oo,...Io,...Co,...Po,...ko};import{existsSync as No,readFileSync as Ro}from"node:fs";import{homedir as Lo}from"node:os";import{join as Mo}from"node:path";var et=new Map;function Uo(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let i=Mo(Lo(),".zibby","config.json");return No(i)&&JSON.parse(Ro(i,"utf-8")).sessionToken||null}catch{return null}}function Do(){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 Fo(i){let e=Date.now(),t=et.get(i);if(t&&t.expiresAt>e)return t.data;let r=Uo();if(!r)throw new Error("No session token. Run `zibby login` first.");let n=`${Do()}/integrations/token/${i}`,o=await fetch(n,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!o.ok){let a=await o.text().catch(()=>"");throw o.status===404?new Error(`${i} is not connected. Connect it at https://studio.zibby.dev/integrations`):o.status===401||o.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Failed to resolve ${i} token (${o.status}): ${a}`)}let s=await o.json();if(!s||typeof s!="object")throw new Error(`Invalid response from ${i} token endpoint: expected object, got ${typeof s}`);if(i==="jira"){if(!s.token||typeof s.token!="string")throw new Error(`Invalid jira token response: token is ${typeof s.token}, expected string`);if(!s.cloudId)throw new Error("Invalid jira token response: missing cloudId")}else if(i==="github"&&(!s.token||typeof s.token!="string"))throw new Error(`Invalid github token response: token is ${typeof s.token}, expected string`);let c=((s.expiresInSec||3e3)-120)*1e3;return et.set(i,{data:s,expiresAt:e+c}),s}function jo(i){i?et.delete(i):et.clear()}import{readdir as Bo,access as gr,copyFile as Go,constants as hr}from"fs/promises";import{join as tt,relative as Ko}from"node:path";async function Jo(i={}){let{testResultsDir:e="test-results",testsDir:t="tests",projectRoot:r=process.cwd(),verbose:n=!0}=i;n&&console.log(`\u{1F3A5} Organizing test videos...
148
+ `);let o=tt(r,e),s=tt(r,t);try{let c=await Bo(o),a=0;for(let l of c){if(l.startsWith("."))continue;let u=tt(o,l,"video.webm");try{await gr(u,hr.F_OK)}catch{continue}let m=l.replace(/-chromium$/,"").replace(/-firefox$/,"").replace(/-webkit$/,""),d=await zo(s,m);if(d){let f=d.replace(/\.spec\.(js|ts)$/,".spec.webm");await Go(u,f),n&&console.log(`\u2705 ${Ko(r,f)}`),a++}else n&&console.log(`\u26A0\uFE0F Could not find test file for: ${l}`)}return n&&(console.log(`
149
+ \u{1F3AC} Organized ${a} video(s)`),console.log(`\u{1F4C2} Videos are now next to their test files in ${t}/`)),{movedCount:a,success:!0}}catch(c){return n&&console.error("\u274C Error organizing videos:",c.message),{movedCount:0,success:!1,error:c.message}}}async function zo(i,e){let t=e.split("-");for(let r=t.length;r>0;r--){let o=t.slice(0,r).join("/");for(let s of["js","ts"]){let c=tt(i,`${o}.spec.${s}`);try{return await gr(c,hr.F_OK),c}catch{}}}return null}var Ue=class{constructor(e,t={}){this.apiKey=e,this.baseUrl=t.baseUrl||process.env.ZIBBY_API_URL||"https://api-prod.zibby.app",this.enabled=!!e}isEnabled(){return this.enabled}};function yr(){let i=process.env.ZIBBY_API_KEY;return new Ue(i)}import{execSync as Yo}from"node:child_process";import{existsSync as Ho,mkdirSync as Wo}from"node:fs";import{join as Zo}from"node:path";async function Xo(i={}){let{baseDir:e="/workspace/repos",repos:t=null,depth:r=1,branch:n=null}=i,o=process.env.REPOS;if(!o)throw new Error("REPOS environment variable not set. Are you running in a Zibby workflow container?");let s;try{s=JSON.parse(o)}catch(l){throw new Error(`Failed to parse REPOS env var: ${l.message}`,{cause:l})}if(!Array.isArray(s)||s.length===0)throw new Error("No repositories configured for this project");let c=t?s.filter(l=>t.includes(l.name)):s;if(c.length===0)throw new Error(`No matching repositories found. Available: ${s.map(l=>l.name).join(", ")}`);Ho(e)||Wo(e,{recursive:!0});let a={};return await Promise.all(c.map(async l=>{let u=l.provider||"github",m=u==="gitlab"?process.env.GITLAB_TOKEN:process.env.GITHUB_TOKEN;if(!m){console.error(`${u.toUpperCase()}_TOKEN not set, skipping ${l.name}`),a[l.name]=null;return}let d=l.name.replace(/\//g,"-"),f=Zo(e,d),g=l.cloneUrl||l.url;if(!g){console.error(`Repository "${l.name}" has no clone URL`),a[l.name]=null;return}let y;u==="gitlab"?y=g.replace(/^https:\/\//,`https://oauth2:${m}@`):y=g.replace(/^https:\/\//,`https://x-access-token:${m}@`);let h=["clone"];r>0&&h.push("--depth",r.toString()),n&&h.push("--branch",n),h.push(y,f);let S=`git ${h.join(" ")}`;console.log(`Cloning ${l.name} (${u}) to ${f}...`);try{Yo(S,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),console.log(`Repository ${l.name} cloned successfully`),a[l.name]=f}catch(w){let T=w.message.replace(m,"***").replace(y,g);console.error(`Failed to clone ${l.name}: ${T}`),a[l.name]=null}})),a}var Sr=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function qo(i){return typeof i=="string"&&Sr.test(i)}var br=qo;function Vo(i){if(!br(i))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(i.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(i.slice(9,13),16))>>>8,e&255,(e=parseInt(i.slice(14,18),16))>>>8,e&255,(e=parseInt(i.slice(19,23),16))>>>8,e&255,(e=parseInt(i.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}var _t=Vo;var K=[];for(let i=0;i<256;++i)K.push((i+256).toString(16).slice(1));function wr(i,e=0){return(K[i[e+0]]+K[i[e+1]]+K[i[e+2]]+K[i[e+3]]+"-"+K[i[e+4]]+K[i[e+5]]+"-"+K[i[e+6]]+K[i[e+7]]+"-"+K[i[e+8]]+K[i[e+9]]+"-"+K[i[e+10]]+K[i[e+11]]+K[i[e+12]]+K[i[e+13]]+K[i[e+14]]+K[i[e+15]]).toLowerCase()}function Qo(i){i=unescape(encodeURIComponent(i));let e=new Uint8Array(i.length);for(let t=0;t<i.length;++t)e[t]=i.charCodeAt(t);return e}var _r="6ba7b810-9dad-11d1-80b4-00c04fd430c8",xr="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function xt(i,e,t,r,n,o){let s=typeof t=="string"?Qo(t):t,c=typeof r=="string"?_t(r):r;if(typeof r=="string"&&(r=_t(r)),r?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+s.length);if(a.set(c),a.set(s,c.length),a=e(a),a[6]=a[6]&15|i,a[8]=a[8]&63|128,n){if(o=o||0,o<0||o+16>n.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);for(let l=0;l<16;++l)n[o+l]=a[l];return n}return wr(a)}import{createHash as es}from"crypto";function ts(i){return Array.isArray(i)?i=Buffer.from(i):typeof i=="string"&&(i=Buffer.from(i,"utf8")),es("sha1").update(i).digest()}var Er=ts;function Et(i,e,t,r){return xt(80,Er,i,e,t,r)}Et.DNS=_r;Et.URL=xr;var Tt=Et;var Tr="@zibby/core ZibbySessionStore/1",De=class{constructor({apiUrl:e,apiKey:t,workflowUuid:r,fetchImpl:n=globalThis.fetch}){if(!e)throw new Error("ZibbySessionStore: apiUrl is required");if(!t)throw new Error("ZibbySessionStore: apiKey is required");if(!r)throw new Error("ZibbySessionStore: workflowUuid is required");this._apiUrl=String(e).replace(/\/+$/,""),this._apiKey=t,this._workflowUuid=r,this._fetch=n}async append(e,t){if(!Array.isArray(t)||t.length===0)return;let r=`${this._apiUrl}/workflows/${encodeURIComponent(this._workflowUuid)}/sessions/${encodeURIComponent(e.sessionId)}/append`,n=await this._fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this._apiKey}`,"Content-Type":"application/json","User-Agent":Tr},body:JSON.stringify({entries:t})});if(!n.ok)throw new Error(`ZibbySessionStore.append HTTP ${n.status}`)}async load(e){let t=`${this._apiUrl}/workflows/${encodeURIComponent(this._workflowUuid)}/sessions/${encodeURIComponent(e.sessionId)}`,r;try{r=await this._fetch(t,{method:"GET",headers:{Authorization:`Bearer ${this._apiKey}`,"User-Agent":Tr}})}catch{return null}if(r.status===404||!r.ok)return null;let n;try{n=await r.json()}catch{return null}let o=Array.isArray(n?.entries)?n.entries:null;return o&&o.length>0?o:null}};var rs="6ba7b810-9dad-11d1-80b4-00c04fd430c8",vr=new Set;function ns(){return(process.env.PROGRESS_API_URL||process.env.ZIBBY_API_BASE||"").replace(/\/executions\/?$/,"").replace(/\/+$/,"")}function Ar({namespace:i=rs}={}){return{id:"session",description:"Persist agent conversation state across invocations (Claude-only in v1)",envKeys:[],tools:[],invokeAgentOptions(e,t){let r=e?.conversationId,n=e?.workflowUuid;if(!r||!n)return null;let o=t?.agentType;if(o&&o!=="claude")return vr.has(o)||(console.warn(`[SKILLS.SESSION] agent type '${o}' does not support native sessions \u2014 node running stateless`),vr.add(o)),null;let s=Tt(`${n}:${r}`,i),c=ns(),a=process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN,l=null;if(c&&a)try{l=new De({apiUrl:c,apiKey:a,workflowUuid:n})}catch(d){console.warn(`[SKILLS.SESSION] failed to build SessionStore: ${d.message}`),l=null}return e.resetConversation?{sessionId:s,resume:s,forkSession:!0,...l&&{sessionStore:l}}:e.hasPriorSession?{resume:s,...l&&{sessionStore:l}}:{sessionId:s,...l&&{sessionStore:l}}}}}import{spawn as $r}from"node:child_process";import{readFileSync as os,writeFileSync as ss,existsSync as rt}from"node:fs";import{homedir as Or}from"node:os";import{join as we}from"node:path";async function is(){let i=we(Or(),".local/share/cursor-agent/versions");if(!rt(i))throw new Error(`cursor-agent not found at ${i}. Please install cursor-agent first.`);return console.log(`\u{1F527} Patching cursor-agent for CI/CD...
150
+ `),new Promise((e,t)=>{let r=we(__dirname,"../../scripts/patch-cursor-mcp.py");if(!rt(r)){t(new Error("Patch script not found"));return}let n=$r("python3",[r],{stdio:"inherit"});n.on("close",o=>{o===0?e({success:!0}):t(new Error(`Patch failed with code ${o}`))}),n.on("error",o=>{t(o)})})}function as(){let i=we(Or(),".local/share/cursor-agent/versions");if(!rt(i))return{patched:!1,installed:!1};try{let e=Hr("fs").readdirSync(i);if(e.length===0)return{patched:!1,installed:!1};let t=e.sort().reverse()[0],r=we(i,t,"index.js");return rt(r)?{patched:os(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 ls(i){return console.log(`\u{1F511} Getting MCP approval keys...
151
+ `),new Promise((e,t)=>{let r=$r("cursor-agent",["mcp","list"],{cwd:i,stdio:"pipe"}),n="";r.stdout.on("data",o=>{n+=o.toString(),process.stdout.write(o)}),r.stderr.on("data",o=>{process.stderr.write(o)}),r.on("close",o=>{if(o===0){let s=cs(n);e({success:!0,keys:s,output:n})}else t(new Error(`Failed to get approval keys (exit code ${o})`))}),r.on("error",o=>{t(o)})})}function cs(i){let e={},t=/🔑 APPROVAL KEY:\s+(\S+)\s+=>\s+(\S+)/g,r;for(;(r=t.exec(i))!==null;)e[r[1]]=r[2];return e}function us(i,e){let t=we(i,".cursor/projects"),r=we(t,"mcp-approvals.json");ss(r,JSON.stringify(e,null,2)),console.log(`
155
152
  \u2705 Saved approval keys to: ${r}
156
- `)}import{DEFAULT_OUTPUT_BASE as Bf,SESSIONS_DIR as Ff,SESSION_INFO_FILE as jf,RESULT_FILE as Gf,RAW_OUTPUT_FILE as Kf,EVENTS_FILE as Jf,CI_ENV_VARS as zf}from"@zibby/agent-workflow";var sn=`
153
+ `)}import{DEFAULT_OUTPUT_BASE as $p,SESSIONS_DIR as Op,SESSION_INFO_FILE as Ip,RESULT_FILE as Cp,RAW_OUTPUT_FILE as Pp,EVENTS_FILE as kp,CI_ENV_VARS as Np}from"@zibby/agent-workflow";var Ir=`
157
154
  const style = document.createElement('style');
158
155
  style.textContent = \`
159
156
  @keyframes zibby-ripple {
@@ -214,7 +211,7 @@ ${p}`),r.invoke(p,m)}import{SKILLS as Ef}from"@zibby/agent-workflow";import{regi
214
211
  setTimeout(() => ripple.remove(), 600);
215
212
  }
216
213
  };
217
- `;function si(o){return o.addInitScript(sn)}function oi(){return`
214
+ `;function ps(i){return i.addInitScript(Ir)}function fs(){return`
218
215
  async function showRipple(page, locator) {
219
216
  const box = await locator.boundingBox().catch(() => null);
220
217
  if (box) {
@@ -227,97 +224,97 @@ async function showRipple(page, locator) {
227
224
  }, { x, y }).catch(() => {});
228
225
  }
229
226
  }
230
- `.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
- ${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,l=`element${t}`,c=this.generate(e,l),a=this.generateActionMethod(r,l,n);return`${c}
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 ze from"fs/promises";var Ft=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")),l=i.filter(p=>["navigate","type","fill","click","select_option"].includes(p.type)),c=l.filter(p=>p.type!=="navigate");console.log(`[TestPostProcessor] Found ${l.length} action events, ${r.length} trace actions`);let a=`import { ZibbyRuntime } from '@zibby/core';
227
+ `.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]}
228
+ ${n.slice(1).map(s=>` .or(${s})`).join(`
229
+ `)};`}static generateRoleSelector(e){let{role:t,name:r}=e;if(!t)return null;if(r){let n=this.escapeRegex(r);return`page.getByRole('${t}', { name: /${n}/i })`}return`page.getByRole('${t}')`}static generateAttributeSelector(e){if(!e||typeof e!="object")return null;let t=Object.entries(e).filter(([n,o])=>o!=null).map(([n,o])=>n==="placeholder"||n==="aria-label"?n==="placeholder"?`page.getByPlaceholder('${this.escapeString(o)}')`:`page.locator('[${n}="${this.escapeString(o)}"]')`:`[${n}="${this.escapeString(o)}"]`);if(e.placeholder)return`page.getByPlaceholder('${this.escapeString(e.placeholder)}')`;let r=t.filter(n=>!n.startsWith("page.")).join("");return r?`page.locator('${r}')`:null}static generatePartialMatchSelector(e){if(!e||typeof e!="object")return null;let t=Object.entries(e).filter(([r,n])=>n!==void 0).map(([r,n])=>{let o=n.replace(/^\^/,"");return`[${r}^="${this.escapeString(o)}"]`});return t.length>0?`page.locator('${t.join("")}')`:null}static generateStructuralSelector(e){return!e||typeof e!="string"?null:`page.locator('${this.escapeString(e)}')`}static generateFallbackSelector(e,t){let{description:r,type:n}=e;if(n==="fill"||n==="type")return`const ${t} = page.locator('input').first();`;if(n==="click"){if(r.toLowerCase().includes("button"))return`const ${t} = page.locator('button').first();`;if(r.toLowerCase().includes("link"))return`const ${t} = page.locator('a').first();`}return`const ${t} = page.locator('body');`}static escapeString(e){return typeof e!="string"?String(e):e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/"/g,'\\"')}static escapeRegex(e){return typeof e!="string"?String(e):e.replace(/[.*+?^${}()[\]\\]/g,"\\$&")}static generateActionCode(e,t){let{type:r,value:n,description:o,selectors:s}=e,c=`element${t}`,a=this.generate(e,c),l=this.generateActionMethod(r,c,n);return`${a}
230
+ ${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:o,passed:s}=e;return r.toLowerCase().includes("url")?`await expect(page).toHaveURL(/${this.escapeRegex(o)}/);`:r.toLowerCase().includes("visible")?"await expect(page.locator('body')).toBeVisible();":`// ${r}`}};import je from"fs/promises";var vt=class{static async generateFromEvents(e,t,r,n){try{console.log("[TestPostProcessor] \u{1F3AF} Generating test from events.json (100% accurate)");let{readFileSync:o}=await import("fs"),s=JSON.parse(o(t,"utf-8")),c=s.filter(f=>["navigate","type","fill","click","select_option"].includes(f.type)),a=c.filter(f=>f.type!=="navigate");console.log(`[TestPostProcessor] Found ${c.length} action events, ${r.length} trace actions`);let l=`import { ZibbyRuntime } from '@zibby/core';
234
231
  import { test, expect } from '@playwright/test';
235
232
 
236
- `;a+=`test('${n}', async ({ page }) => {
237
- `,a+=` const timestamp = Date.now();
233
+ `;l+=`test('${n}', async ({ page }) => {
234
+ `,l+=` const timestamp = Date.now();
238
235
 
239
- `;let u=0;for(let p of l)if(p.type==="navigate")a+=` await page.goto('${p.data.params.url}');
236
+ `;let u=0;for(let f of c)if(f.type==="navigate")l+=` await page.goto('${f.data.params.url}');
240
237
 
241
- `;else if(p.type==="type"||p.type==="fill"){let{element:g,text:y}=p.data.params,h=r[u]?.strategies||[];a+=` await ZibbyRuntime.step(page, ${JSON.stringify({name:g,action:"fill",value:y,strategies:h},null,2)});
238
+ `;else if(f.type==="type"||f.type==="fill"){let{element:g,text:y}=f.data.params,h=r[u]?.strategies||[];l+=` await ZibbyRuntime.step(page, ${JSON.stringify({name:g,action:"fill",value:y,strategies:h},null,2)});
242
239
 
243
- `,u++}else if(p.type==="click"){let{element:g}=p.data.params,y=r[u]?.strategies||[];a+=` await ZibbyRuntime.step(page, ${JSON.stringify({name:g,action:"click",value:"",strategies:y},null,2)});
240
+ `,u++}else if(f.type==="click"){let{element:g}=f.data.params,y=r[u]?.strategies||[];l+=` await ZibbyRuntime.step(page, ${JSON.stringify({name:g,action:"click",value:"",strategies:y},null,2)});
244
241
 
245
- `,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};a+=` await ZibbyRuntime.step(page, ${JSON.stringify(S,null,2)});
242
+ `,u++}else if(f.type==="select_option"){let{element:g,values:y}=f.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)});
246
243
 
247
- `,u++}a+=`});
248
- `;let{dirname:m}=await import("path"),{mkdirSync:d}=await import("fs");return d(m(e),{recursive:!0}),await ze.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 ze.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],l=`element${s}`,c=new RegExp(`const ${l}\\b\\s*=\\s*page\\.[^;]+;(\\s*await ${l}\\.waitFor\\([^)]*\\);)?\\s*await ${l}\\.(click|fill|type|selectOption|pressSequentially)\\(([^)]*)\\);`,"s"),a=n.match(c);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||[]},m=`await ZibbyRuntime.step(page, ${JSON.stringify(u,null,2)});`;n=n.replace(a[0],m)}return await ze.writeFile(e,n,"utf-8"),console.log("[TestPostProcessor] \u2705 Successfully converted test to Resilient Zibby format"),!0}catch(n){return console.warn("[TestPostProcessor] Failed to apply safe wrappers:",n.message),!1}}static async enhanceSelectors(e,t){try{let{actions:r=[]}=t;if(!r.length)return!1;let n=await ze.readFile(e,"utf-8"),s=this.buildSelectorMap(r);return n=this.replaceSimpleSelectors(n,s),await ze.writeFile(e,n,"utf-8"),!0}catch(r){return console.warn("Failed to enhance selectors:",r),!1}}static buildSelectorMap(e){let t=new Map;for(let r=0;r<e.length;r++){let n=e[r];if(!n.selectors||n.type==="navigate")continue;let s=`element${r}`,l=Je.generate(n,s).match(/= (.+);/s);if(l){let c=l[1].trim(),a=`${n.type}:${this.normalizeDescription(n.description)}`;t.set(a,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[l,c]of t.entries())if(i.includes(l.split(":")[1])){let a=i.match(/\.(fill|click|type)\(([^)]*)\)/);if(a){let[,u,m]=a,d="element";return`const ${d} = ${c};
250
- await ${d}.${u}(${m})`}}return i});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as ii,existsSync as on,readdirSync as an}from"node:fs";import{join as jt}from"node:path";import{execSync as ai}from"node:child_process";import{tmpdir as ci}from"node:os";var Ye=class{static async parseTraceZip(e){let t;if(e.endsWith(".zip")&&on(e)){let r=jt(ci(),`trace-${Date.now()}`);ai(`unzip -q "${e}" -d "${r}"`,{stdio:"pipe"});let s=an(r).find(i=>i.endsWith(".trace"));if(!s)throw new Error("No .trace file found in zip");t=jt(r,s)}else if(on(e)){let n=an(e).find(s=>s.endsWith(".trace"));if(!n)throw new Error("No .trace file found");t=jt(e,n)}else throw new Error(`Trace not found at ${e}`);try{let n=ii(t,"utf-8").trim().split(`
251
- `),s=[],i=new Map,l=new Map;for(let c of n)try{let a=JSON.parse(c);if(a.type==="snapshot"&&a.snapshot&&a.snapshot.accessibility){let u=new Map;for(let m of a.snapshot.accessibility)m.ref&&u.set(m.ref,m);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&&l.set(a.pageId||"default",u)}}catch{}for(let c of n)try{let a=JSON.parse(c);if(a.type==="before"&&a.params&&a.params.selector){let u=a.method;if(["click","fill","type","selectOption"].includes(u)){let m=a.params.selector,d=a.params.text||a.params.value||"",p=[],g=null,y=null,h=null,S=m.match(/aria-ref=([a-z0-9]+)/i);if(S&&a.snapshotName){let E=S[1],P=i.get(a.snapshotName);if(P&&P.has(E)){let I=P.get(E);g=I.name||null,y=I.role||null,h=I.label||null,console.log(`[TraceParser] \u2705 Found ACTUAL element data: text="${g}", role="${y}"`)}}let w=m.match(/internal:text="([^"]+)"/i),T=m.match(/internal:label="([^"]+)"/i),b=m.match(/internal:placeholder="([^"]+)"/i),$=m.match(/internal:role=([^ ]+)/i),k=m.match(/internal:describe="([^"]+)"/i),R=m.match(/name="([^"]+)"/i);if(w){p.push({type:"text",text:w[1]});let E=w[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]}),b&&p.push({type:"placeholder",placeholder:b[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(y||$){let E=y||$[1],P=g||(R?R[1]:w?w[1]:null);p.unshift({type:"role",role:E,name:P,source:g?"accessibility-tree":"selector"})}if(h&&p.unshift({type:"label",label:h,source:"accessibility-tree"}),k){let E=k[1],P=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],I=null,C=E;for(let j of P)if(E.toLowerCase().endsWith(` ${j}`)){I=j.replace(" ",""),C=E.substring(0,E.length-j.length-1);break}if(I){p.push({type:"role",role:I,name:C});let j=C.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:j}),p.push({type:"text",text:C});let N=C.split(" ");N.length>1&&(p.push({type:"text",text:N[0],fuzzy:!0}),p.push({type:"text",text:N.slice(0,2).join(" "),fuzzy:!0}))}else{let j=E.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:j}),p.push({type:"text",text:E})}}let v=this.extractDOMStrategies(m,l,w?.[1]||k?.[1],a.pageId);p.push(...v);let O=this.extractStructuralContext(m);(O.parent||O.sibling)&&p.forEach(E=>{["role","text","label","testid"].includes(E.type)&&(O.parent&&(E.parent=O.parent),O.sibling&&(E.sibling=O.sibling))}),p.push({type:"css",value:m});let D=g||w?w[1]:k?k[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${s.length}`;s.push({method:u,name:D,action:u==="type"?"fill":u,value:d,strategies:p,timestamp:a.startTime,actualText:g,actualRole:y,actualAriaLabel:h})}}}catch{}return s}catch(r){throw new Error(`Failed to parse trace: ${r.message}`,{cause:r})}}static extractDOMStrategies(e,t,r,n){let s=[];if(!t||t.size===0||!r)return s;try{let i=t.get(n);if(!i)return s;let l=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${l}`,"i"),a=i.match(c);a&&s.push({type:"testid",value:a[1],priority:"high"});let u=new RegExp(`class=["']([^"']+)["'][^>]*>[^<]*${l}`,"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=["']([^"']+)["'][^>]*>[^<]*${l}`,"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 l=r[r.length-2].replace(/internal:text="[^"]+"\s*/gi,"").replace(/internal:role=\S+\s*/gi,"").replace(/internal:label="[^"]+"\s*/gi,"").trim();l&&(l.match(/^(form|section|nav|header|aside|main|article)\b/)||l.includes("[")||l.match(/[#.]\w/))&&(t.parent=l)}let s=r[r.length-1].match(/([^+~]+)\s*[+~]\s*(.+)/);return s&&(t.sibling=s[1].trim()),t}};var Gt=class{static async step(e,t){let{name:r,action:n,value:s,strategies:i,options:l={timeout:1e4},enrichedData:c}=t;console.log(`[Zibby] \u26A1 Executing step: ${r}`),await this.waitForPageStability(e,l.timeout);let a=await this.findBestMatch(e,i,r);if(!a)throw new Error(`[Zibby] \u274C Failed to find "${r}" using ${i.length} strategies`);c?.position&&await this.verifyPosition(a,c.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(l){if(i===s)throw l;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(a,u)=>{try{let d=await this.getLocator(e,a).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,a,e);return{element:g,strategy:a,score:S,strategyIdx:u,elIdx:y}}catch{return null}}))).filter(g=>g!==null)}catch{return[]}}),l=(await Promise.all(i)).flat();if(l.length===0)return console.log(`[Zibby] \u274C No visible candidates found for "${r}"`),null;l.sort((a,u)=>u.score-a.score);let c=l[0];return console.log(`[Zibby] \u2705 Found element using ${c.strategy.type} (score: ${c.score.toFixed(2)}, ${l.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,a)=>c.matches(a),t.parent)&&(n+=30)}catch{}if(t.sibling)try{await e.evaluate((l,c)=>l.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(l=>{let c=0,a=l;for(;a;)a.tagName==="IFRAME"&&c++,a=a.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 Kt=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 l=e.locator(s);if(await l.count()>0)try{await l.click({timeout:2e3});return}catch(c){if(c.message.includes("intercepts pointer")){await l.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 l=e.locator(s);if(await l.count()>0){await l.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 l=e.locator(s);if(await l.count()>0){await l.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 a=c.getAttribute("aria-labelledby");if(a){let d=document.getElementById(a);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 a=[],u=c.closest("form");if(u)if(u.id)a.push(`form#${u.id}`);else if(u.name)a.push(`form[name=${u.name}]`);else if(u.action)try{let y=new URL(u.action,window.location.origin).pathname;a.push(`form[action=${y}]`)}catch{a.push(`form[action=${u.getAttribute("action")}]`)}else{let y=document.querySelectorAll("form"),h=Array.from(y).indexOf(u);a.push(`form:nth(${h})`)}let 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");a.push(h||y)}let d=c.closest('section, article, [role="region"]');if(d){let y=d.querySelector("h1, h2, h3, h4, h5, h6");y&&a.push(`section:${y.textContent.trim().slice(0,30)}`)}let p=c.closest("fieldset");if(p){let y=p.querySelector("legend");y&&a.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?a.push(`dialog:${y.textContent.trim().slice(0,30)}`):a.push("dialog")}return a.join("/")}function n(c){let a=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=[a,u,m,d,p,g,y,h].join("|"),w=5381;for(let T=0;T<S.length;T++)w=(w<<5)+w^S.charCodeAt(T);return`zibby-${(w>>>0).toString(36)}`}let s=["button","a","input","select","textarea","label[for]",'[role="button"]','[role="link"]','[role="textbox"]','[role="checkbox"]','[role="radio"]','[role="combobox"]','[role="menuitem"]','[role="tab"]','[role="option"]','[role="switch"]','[role="slider"]',"[onclick]","[data-action]"].join(", "),i=new Map,l=0;document.querySelectorAll(s).forEach(c=>{let a=window.getComputedStyle(c);if(a.display==="none"||a.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),l++}),console.log(`[Zibby] Injected ${l} stable IDs`)})}catch{}}};var li=8,ui=1,pi=64;function fi(o){if(!o||typeof o!="object")return 8;let e=o.parallel;if(!e||typeof e!="object")return 8;let t=e.maxConcurrentRuns??e.maxConcurrent,r=Number(t);if(!Number.isFinite(r))return 8;let n=Math.floor(r);return n<1?8:Math.min(64,n)}import{readFileSync as mi,writeFileSync as ln,existsSync as gi}from"node:fs";import{join as un}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 di}from"node:fs";import{join as cn}from"node:path";var fe=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=cn(e,"traces"),r=cn(e,"trace.zip");if(di(r))try{this.traceData=await Ye.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),l=s.actualRole,c=s.actualAriaLabel;return i||l||c?(console.log(`[TraceTextEnricher] \u2705 Event ${n}: text="${i}", role="${l}", label="${c}"`),{traceActualText:i,traceActualRole:l,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 hi(o){let e=un(o,"events.json"),t=un(o,"events-enriched.json");if(!gi(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(mi(e,"utf-8")),n=new fe,s=0,i=0;for(let l of r)try{let c=await n.enrich(l,{sessionPath:o});c&&(l.enrichedData={...l.enrichedData||{},...c},s++)}catch(c){console.log(`[PostProcess] Failed to enrich event ${l.id}: ${c.message}`),i++}return s>0&&(ln(t,JSON.stringify(r,null,2)),ln(e,JSON.stringify(r,null,2)),console.log(`[PostProcess] \u2705 Enriched ${s} events (${i} failed)`)),{enriched:s,failed:i}}catch(r){return console.log(`[PostProcess] \u274C Failed to post-process events: ${r.message}`),{enriched:0,failed:0}}}import{spawn as yi}from"node:child_process";import{existsSync as Si}from"node:fs";import{dirname as bi,resolve as pn,relative as wi}from"node:path";var ft=new Map,He=8,fn={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 ${He} 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=(ft.get(r)||0)+1;if(ft.set(r,n),n>He)return{success:!1,executionCount:n,maxReached:!0,error:`Maximum ${He} executions reached. Stop retrying and return your best result.`};let s=e?.projectRoot||process.cwd(),i=pn(s,o),l=wi(s,i);return l.startsWith("..")||pn(i)!==i&&l.includes("..")?{success:!1,executionCount:n,error:"Path traversal detected: scriptPath must be within the project root."}:Si(i)?new Promise(c=>{let a=bi(i),u=yi("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}
244
+ `,u++}l+=`});
245
+ `;let{dirname:m}=await import("path"),{mkdirSync:d}=await import("fs");return d(m(e),{recursive:!0}),await je.writeFile(e,l,"utf-8"),console.log(`[TestPostProcessor] \u2705 Generated test with ${s.filter(f=>["type","fill","click","select_option"].includes(f.type)).length} actions`),!0}catch(o){return console.warn("[TestPostProcessor] Failed to generate from events:",o.message),!1}}static async enhanceSelectorsWithTrace(e,t,r){try{console.log("[TestPostProcessor] \u{1F6E1}\uFE0F Applying Zibby Safe Action Wrappers...");let n=await je.readFile(e,"utf-8");n.includes("ZibbyRuntime")||(n=`import { ZibbyRuntime } from '@zibby/core';
246
+ ${n}`);for(let o=0;o<t.length;o++){let s=t[o],c=`element${o}`,a=new RegExp(`const ${c}\\b\\s*=\\s*page\\.[^;]+;(\\s*await ${c}\\.waitFor\\([^)]*\\);)?\\s*await ${c}\\.(click|fill|type|selectOption|pressSequentially)\\(([^)]*)\\);`,"s"),l=n.match(a);if(!l)continue;let u={name:s.name||`Action ${o}`,action:s.method==="type"?"fill":s.method,value:l[3].trim().replace(/^['"]|['"]$/g,""),strategies:s.strategies||[]},m=`await ZibbyRuntime.step(page, ${JSON.stringify(u,null,2)});`;n=n.replace(l[0],m)}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"),o=this.buildSelectorMap(r);return n=this.replaceSimpleSelectors(n,o),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 o=`element${r}`,c=Fe.generate(n,o).match(/= (.+);/s);if(c){let a=c[1].trim(),l=`${n.type}:${this.normalizeDescription(n.description)}`;t.set(l,a),n.selectors.role&&t.set(`role:${n.selectors.role.name}`,a),n.selectors.attributes?.placeholder&&t.set(`placeholder:${n.selectors.attributes.placeholder}`,a)}}return t}static replaceSimpleSelectors(e,t){let r=e,n=[/await page\.(getByRole|getByPlaceholder|getByText|getByLabel|locator)\([^)]+\)\.(fill|click|type)\([^)]*\)/g];for(let o of n)r=r.replace(o,s=>{for(let[c,a]of t.entries())if(s.includes(c.split(":")[1])){let l=s.match(/\.(fill|click|type)\(([^)]*)\)/);if(l){let[,u,m]=l,d="element";return`const ${d} = ${a};
247
+ await ${d}.${u}(${m})`}}return s});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as ds,existsSync as Cr,readdirSync as Pr}from"node:fs";import{join as At}from"node:path";import{execSync as ms}from"node:child_process";import{tmpdir as gs}from"node:os";var Be=class{static async parseTraceZip(e){let t;if(e.endsWith(".zip")&&Cr(e)){let r=At(gs(),`trace-${Date.now()}`);ms(`unzip -q "${e}" -d "${r}"`,{stdio:"pipe"});let o=Pr(r).find(s=>s.endsWith(".trace"));if(!o)throw new Error("No .trace file found in zip");t=At(r,o)}else if(Cr(e)){let n=Pr(e).find(o=>o.endsWith(".trace"));if(!n)throw new Error("No .trace file found");t=At(e,n)}else throw new Error(`Trace not found at ${e}`);try{let n=ds(t,"utf-8").trim().split(`
248
+ `),o=[],s=new Map,c=new Map;for(let a of n)try{let l=JSON.parse(a);if(l.type==="snapshot"&&l.snapshot&&l.snapshot.accessibility){let u=new Map;for(let m of l.snapshot.accessibility)m.ref&&u.set(m.ref,m);s.set(l.snapshotName,u)}if(l.type==="frame-snapshot"&&l.snapshot){let u=Buffer.from(l.snapshot.html||"","base64").toString("utf-8");u&&u.length>100&&c.set(l.pageId||"default",u)}}catch{}for(let a of n)try{let l=JSON.parse(a);if(l.type==="before"&&l.params&&l.params.selector){let u=l.method;if(["click","fill","type","selectOption"].includes(u)){let m=l.params.selector,d=l.params.text||l.params.value||"",f=[],g=null,y=null,h=null,S=m.match(/aria-ref=([a-z0-9]+)/i);if(S&&l.snapshotName){let E=S[1],C=s.get(l.snapshotName);if(C&&C.has(E)){let $=C.get(E);g=$.name||null,y=$.role||null,h=$.label||null,console.log(`[TraceParser] \u2705 Found ACTUAL element data: text="${g}", role="${y}"`)}}let w=m.match(/internal:text="([^"]+)"/i),T=m.match(/internal:label="([^"]+)"/i),b=m.match(/internal:placeholder="([^"]+)"/i),O=m.match(/internal:role=([^ ]+)/i),R=m.match(/internal:describe="([^"]+)"/i),N=m.match(/name="([^"]+)"/i);if(w){f.push({type:"text",text:w[1]});let E=w[1].split(" ");E.length>1&&(f.push({type:"text",text:E[0],fuzzy:!0}),f.push({type:"text",text:E[E.length-1],fuzzy:!0}))}if(T&&f.push({type:"label",label:T[1]}),b&&f.push({type:"placeholder",placeholder:b[1]}),g){f.unshift({type:"text",text:g,source:"accessibility-tree"});let E=g.split(" ");E.length>1&&f.push({type:"text",text:E[0],fuzzy:!0,source:"accessibility-tree"})}if(y||O){let E=y||O[1],C=g||(N?N[1]:w?w[1]:null);f.unshift({type:"role",role:E,name:C,source:g?"accessibility-tree":"selector"})}if(h&&f.unshift({type:"label",label:h,source:"accessibility-tree"}),R){let E=R[1],C=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],$=null,P=E;for(let B of C)if(E.toLowerCase().endsWith(` ${B}`)){$=B.replace(" ",""),P=E.substring(0,E.length-B.length-1);break}if($){f.push({type:"role",role:$,name:P});let B=P.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:B}),f.push({type:"text",text:P});let k=P.split(" ");k.length>1&&(f.push({type:"text",text:k[0],fuzzy:!0}),f.push({type:"text",text:k.slice(0,2).join(" "),fuzzy:!0}))}else{let B=E.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:B}),f.push({type:"text",text:E})}}let v=this.extractDOMStrategies(m,c,w?.[1]||R?.[1],l.pageId);f.push(...v);let I=this.extractStructuralContext(m);(I.parent||I.sibling)&&f.forEach(E=>{["role","text","label","testid"].includes(E.type)&&(I.parent&&(E.parent=I.parent),I.sibling&&(E.sibling=I.sibling))}),f.push({type:"css",value:m});let U=g||w?w[1]:R?R[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${o.length}`;o.push({method:u,name:U,action:u==="type"?"fill":u,value:d,strategies:f,timestamp:l.startTime,actualText:g,actualRole:y,actualAriaLabel:h})}}}catch{}return o}catch(r){throw new Error(`Failed to parse trace: ${r.message}`,{cause:r})}}static extractDOMStrategies(e,t,r,n){let o=[];if(!t||t.size===0||!r)return o;try{let s=t.get(n);if(!s)return o;let c=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),l=s.match(a);l&&o.push({type:"testid",value:l[1],priority:"high"});let u=new RegExp(`class=["']([^"']+)["'][^>]*>[^<]*${c}`,"gi"),m=s.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&&(o.push({type:"class",value:y.join("."),priority:"medium"}),y.length===1&&o.push({type:"class",value:y[0],priority:"medium"}))}let d=new RegExp(`id=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),f=s.match(d);f&&!f[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&o.push({type:"id",value:f[1],priority:"high"})}catch(s){console.warn(`[TraceParser] DOM extraction failed: ${s.message}`)}return o}static extractStructuralContext(e){let t={parent:null,sibling:null},r=e.split(">>").map(s=>s.trim());if(r.length>1){let c=r[r.length-2].replace(/internal:text="[^"]+"\s*/gi,"").replace(/internal:role=\S+\s*/gi,"").replace(/internal:label="[^"]+"\s*/gi,"").trim();c&&(c.match(/^(form|section|nav|header|aside|main|article)\b/)||c.includes("[")||c.match(/[#.]\w/))&&(t.parent=c)}let o=r[r.length-1].match(/([^+~]+)\s*[+~]\s*(.+)/);return o&&(t.sibling=o[1].trim()),t}};var $t=class{static async step(e,t){let{name:r,action:n,value:o,strategies:s,options:c={timeout:1e4},enrichedData:a}=t;console.log(`[Zibby] \u26A1 Executing step: ${r}`),await this.waitForPageStability(e,c.timeout);let l=await this.findBestMatch(e,s,r);if(!l)throw new Error(`[Zibby] \u274C Failed to find "${r}" using ${s.length} strategies`);a?.position&&await this.verifyPosition(l,a.position),await this.performActionWithRetry(e,l,n,o,3),console.log(`[Zibby] \u2728 Step "${r}" completed.`)}static async waitForPageStability(e,t=1e4){try{await e.waitForLoadState("networkidle",{timeout:3e3}).catch(()=>{}),await e.evaluate(()=>new Promise(r=>{let n,o=new MutationObserver(()=>{clearTimeout(n),n=setTimeout(()=>{o.disconnect(),r()},500)});o.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),n=setTimeout(()=>{o.disconnect(),r()},500)})).catch(()=>{})}catch{}}static async verifyPosition(e,t){try{let r=await e.boundingBox();if(!r)return;let n=Math.abs(r.x-t.x),o=Math.abs(r.y-t.y);(n>50||o>50)&&(console.log(`[Zibby] \u26A0\uFE0F Element moved: expected (${t.x}, ${t.y}), got (${r.x}, ${r.y})`),await new Promise(s=>setTimeout(s,500)))}catch{}}static async performActionWithRetry(e,t,r,n,o=3){for(let s=1;s<=o;s++)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(s===o)throw c;console.log(`[Zibby] \u26A0\uFE0F Action failed (attempt ${s}/${o}), retrying...`),await new Promise(a=>setTimeout(a,1e3*s))}}static async findBestMatch(e,t,r){let o=Date.now(),s=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[]}}),c=(await Promise.all(s)).flat();if(c.length===0)return console.log(`[Zibby] \u274C No visible candidates found for "${r}"`),null;c.sort((l,u)=>u.score-l.score);let a=c[0];return console.log(`[Zibby] \u2705 Found element using ${a.strategy.type} (score: ${a.score.toFixed(2)}, ${c.length} candidates)`),a.element}static async scoreCandidate(e,t,r){let n=0;if(n+={testid:120,id:110,role:100,label:90,class:85,placeholder:85,text:80,css:50}[t.type]||50,t.priority==="high"&&(n+=20),t.priority==="medium"&&(n+=10),t.fuzzy&&(n-=15),t.parent)try{await e.locator("xpath=ancestor::*").first().evaluate((a,l)=>a.matches(l),t.parent)&&(n+=30)}catch{}if(t.sibling)try{await e.evaluate((c,a)=>c.parentElement?.querySelector(a)!==null,t.sibling)&&(n+=20)}catch{}try{let s=await e.boundingBox();s&&s.y<1e3&&(n+=10)}catch{}try{let s=await e.evaluate(c=>{let a=0,l=c;for(;l;)l.tagName==="IFRAME"&&a++,l=l.parentElement;return a});n-=s*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 Ot=class{static async beforeEach(e){await this.injectStableIds(e),e.on("load",async()=>{await this.injectStableIds(e)})}static async afterNavigation(e){await e.waitForLoadState("domcontentloaded").catch(()=>{}),await this.injectStableIds(e)}static async clickWithRetry(e,t,r={}){let n=r.timeout||1e4,o=`[data-zibby-id="${t}"]`,s=Date.now();for(;Date.now()-s<n;){await this.injectStableIds(e);let c=e.locator(o);if(await c.count()>0)try{await c.click({timeout:2e3});return}catch(a){if(a.message.includes("intercepts pointer")){await c.click({force:!0});return}}await e.waitForTimeout(200)}throw new Error(`Element ${o} not found after ${n}ms`)}static async fillWithRetry(e,t,r,n=1e4){let o=`[data-zibby-id="${t}"]`,s=Date.now();for(;Date.now()-s<n;){await this.injectStableIds(e);let c=e.locator(o);if(await c.count()>0){await c.fill(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${o} not found after ${n}ms`)}static async selectWithRetry(e,t,r,n=1e4){let o=`[data-zibby-id="${t}"]`,s=Date.now();for(;Date.now()-s<n;){await this.injectStableIds(e);let c=e.locator(o);if(await c.count()>0){await c.selectOption(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${o} not found after ${n}ms`)}static async injectStableIds(e){try{await e.evaluate(()=>{function t(a){if(a.getAttribute("aria-label"))return a.getAttribute("aria-label").trim();let l=a.getAttribute("aria-labelledby");if(l){let d=document.getElementById(l);if(d)return d.textContent.trim()}if(a.id){let d=document.querySelector(`label[for="${a.id}"]`);if(d)return d.textContent.trim()}let u=a.closest("label");if(u){let d=u.cloneNode(!0);d.querySelectorAll("input, select, textarea").forEach(g=>g.remove());let f=d.textContent.trim();if(f)return f}if(a.placeholder)return a.placeholder;let m=a.tagName.toLowerCase();return m==="button"||m==="a"||a.getAttribute("role")==="button"?(a.textContent||"").trim().slice(0,50):a.title?a.title:m==="input"&&(a.type==="submit"||a.type==="button")&&a.value||""}function r(a){let l=[],u=a.closest("form");if(u)if(u.id)l.push(`form#${u.id}`);else if(u.name)l.push(`form[name=${u.name}]`);else if(u.action)try{let y=new URL(u.action,window.location.origin).pathname;l.push(`form[action=${y}]`)}catch{l.push(`form[action=${u.getAttribute("action")}]`)}else{let y=document.querySelectorAll("form"),h=Array.from(y).indexOf(u);l.push(`form:nth(${h})`)}let m=a.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=a.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 f=a.closest("fieldset");if(f){let y=f.querySelector("legend");y&&l.push(`fieldset:${y.textContent.trim()}`)}let g=a.closest('dialog, [role="dialog"], [role="alertdialog"]');if(g){let y=g.querySelector('[role="heading"], h1, h2, h3');y?l.push(`dialog:${y.textContent.trim().slice(0,30)}`):l.push("dialog")}return l.join("/")}function n(a){let l=a.tagName.toLowerCase(),u=a.id||"",m=a.name||"",d=a.type||"",f=a.getAttribute("role")||"",g="";if(a.href)try{g=new URL(a.href,window.location.origin).pathname.slice(0,50)}catch{g=a.getAttribute("href")?.slice(0,50)||""}let y=t(a).slice(0,50).replace(/\s+/g," "),h=r(a),S=[l,u,m,d,f,g,y,h].join("|"),w=5381;for(let T=0;T<S.length;T++)w=(w<<5)+w^S.charCodeAt(T);return`zibby-${(w>>>0).toString(36)}`}let o=["button","a","input","select","textarea","label[for]",'[role="button"]','[role="link"]','[role="textbox"]','[role="checkbox"]','[role="radio"]','[role="combobox"]','[role="menuitem"]','[role="tab"]','[role="option"]','[role="switch"]','[role="slider"]',"[onclick]","[data-action]"].join(", "),s=new Map,c=0;document.querySelectorAll(o).forEach(a=>{let l=window.getComputedStyle(a);if(l.display==="none"||l.visibility==="hidden")return;let u=n(a),m=u,d=s.get(m)||0;d>0&&(u=`${m}-${d}`),s.set(m,d+1),a.setAttribute("data-zibby-id",u),c++}),console.log(`[Zibby] Injected ${c} stable IDs`)})}catch{}}};var hs=8,ys=1,Ss=64;function bs(i){if(!i||typeof i!="object")return 8;let e=i.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 _s,writeFileSync as Nr,existsSync as xs}from"node:fs";import{join as Rr}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 ws}from"node:fs";import{join as kr}from"node:path";var ce=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=kr(e,"traces"),r=kr(e,"trace.zip");if(ws(r))try{this.traceData=await Be.parseTraceZip(r),console.log(`[TraceTextEnricher] \u2705 Loaded trace with ${this.traceData.length} actions`)}catch(n){console.log(`[TraceTextEnricher] \u26A0\uFE0F Failed to parse trace: ${n.message}`)}}async enrich(e,t){let r=e.data?.params?.ref,n=e.id;if(r===void 0&&n===void 0||(!this.traceData&&t.sessionPath&&await this.loadTrace(t.sessionPath),!this.traceData))return null;let o=this.traceData[n];if(!o)return console.log(`[TraceTextEnricher] \u26A0\uFE0F No trace action for event ${n}`),null;let s=o.actualText||this._extractTextFromSelector(o.selector),c=o.actualRole,a=o.actualAriaLabel;return s||c||a?(console.log(`[TraceTextEnricher] \u2705 Event ${n}: text="${s}", role="${c}", label="${a}"`),{traceActualText:s,traceActualRole:c,traceActualAriaLabel:a,traceSelector:o.selector,traceStrategies:o.strategies}):null}_extractTextFromSelector(e){if(!e)return null;let t=e.match(/internal:label="([^"]+)"/);if(t)return t[1];let r=e.match(/internal:text="([^"]+)"/);if(r)return r[1];let n=e.match(/getByText\(['"]([^'"]+)['"]\)/);if(n)return n[1];let o=e.match(/name:\s*['"]([^'"]+)['"]/);return o?o[1]:null}};async function Es(i){let e=Rr(i,"events.json"),t=Rr(i,"events-enriched.json");if(!xs(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(_s(e,"utf-8")),n=new ce,o=0,s=0;for(let c of r)try{let a=await n.enrich(c,{sessionPath:i});a&&(c.enrichedData={...c.enrichedData||{},...a},o++)}catch(a){console.log(`[PostProcess] Failed to enrich event ${c.id}: ${a.message}`),s++}return o>0&&(Nr(t,JSON.stringify(r,null,2)),Nr(e,JSON.stringify(r,null,2)),console.log(`[PostProcess] \u2705 Enriched ${o} events (${s} failed)`)),{enriched:o,failed:s}}catch(r){return console.log(`[PostProcess] \u274C Failed to post-process events: ${r.message}`),{enriched:0,failed:0}}}import{spawn as Ts}from"node:child_process";import{existsSync as vs}from"node:fs";import{dirname as As,resolve as Lr,relative as $s}from"node:path";var nt=new Map,Ge=8,Mr={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 ${Ge} 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:i},e){let r=`${e?.sessionId||"default"}:${i}`,n=(nt.get(r)||0)+1;if(nt.set(r,n),n>Ge)return{success:!1,executionCount:n,maxReached:!0,error:`Maximum ${Ge} executions reached. Stop retrying and return your best result.`};let o=e?.projectRoot||process.cwd(),s=Lr(o,i),c=$s(o,s);return c.startsWith("..")||Lr(s)!==s&&c.includes("..")?{success:!1,executionCount:n,error:"Path traversal detected: scriptPath must be within the project root."}:vs(s)?new Promise(a=>{let l=As(s),u=Ts("npx",["playwright","test",s,"--reporter=line"],{cwd:o,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 f=setTimeout(()=>{u.kill("SIGTERM"),a({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(f);let h=`${m}
252
249
  ${d}`.split(`
253
250
  `),S="",w=null;for(let T=0;T<h.length;T++){let b=h[T];if(b.includes("Error:")||b.includes("error:")||b.includes("\u2718")){S+=`${b}
254
- `;for(let $=T+1;$<Math.min(T+5,h.length);$++)S+=`${h[$]}
255
- `}if(b.includes("at ")&&b.includes(".spec.")){let $=b.match(/:(\d+):\d+/);$&&(w=parseInt($[1]))}}c(g===0?{success:!0,executionCount:n,message:"All tests passed!",output:m.slice(-500)}:{success:!1,executionCount:n,remainingAttempts:He-n,error:S.slice(0,1500)||"Test failed (see output)",failedAtLine:w,stdout:m.slice(-1500),stderr:d.slice(-500),hint:n<He?"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 ft.keys())e.startsWith(`${o}:`)&&ft.delete(e)}};function xi(o){fn.resetCount(o)}var ee=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 dn,writeFileSync as _i}from"node:fs";var Te=class extends ee{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(dn(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(dn(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 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,w=g||u.enrichedData?.actualRole,T=S||m,b=S||this._extractName(m),$=w||this._extractRole(m),k=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+=` // ${m}${S?` (actual: "${S}")${k}`:""}
264
- `,a+=` await ZibbyRuntime.step(page, {
265
- `,a+=` name: '${this._escapeString(m)}',
266
- `,a+=` action: 'click',
267
- `,a+=` strategies: [
268
- `,a+=` { type: 'role', role: '${$}', name: '${this._escapeString(b)}' },
269
- `,a+=` { type: 'text', text: '${this._escapeString(b)}' }
270
- `,a+=` ]
271
- `,a+=` });
272
-
273
- `;else if(u.type==="fill"||u.type==="type"){let R=u.data.params.text;a+=` // ${m}${S?` (actual: "${S}")${k}`:""}
274
- `,a+=` await ZibbyRuntime.step(page, {
275
- `,a+=` name: '${this._escapeString(m)}',
276
- `,a+=` action: 'fill',
277
- `,a+=` value: '${this._escapeString(R)}',
278
- `,a+=` strategies: [
279
- `,a+=` { type: 'role', role: '${$}', name: '${this._escapeString(b)}' },
280
- `,a+=` { type: 'attributes', placeholder: '${this._escapeString(b)}' }
281
- `,a+=` ]
282
- `,a+=` });
283
-
284
- `}else if(u.type==="select_option"){let R=u.data.params.values,v=Array.isArray(R)?R[0]:R;a+=` // ${m}${S?` (actual: "${S}")${k}`:""}
285
- `,a+=` await ZibbyRuntime.step(page, {
286
- `,a+=` name: '${this._escapeString(m)}',
287
- `,a+=` action: 'select',
288
- `,a+=` value: '${this._escapeString(v)}',
289
- `,a+=` strategies: [
290
- `,a+=` { type: 'role', role: 'combobox', name: '${this._escapeString(b)}' }
291
- `,a+=` ]
292
- `,a+=` });
293
-
294
- `}}return a+=`});
295
- `,_i(t,a),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 mn,writeFileSync as Ei}from"node:fs";var ve=class extends ee{constructor(){super("stable-id","Stable ID Injection (Experimental)",300)}canGenerate(e){let t=e.eventsPath||`${e.sessionPath}/execute_live/events.json`;try{return JSON.parse(mn(t,"utf-8")).some(s=>s.stableId||s.data?.stableId)?(console.log("[StableIdStrategy] \u2705 Stable IDs available"),!0):(console.log("[StableIdStrategy] \u274C No stable IDs found in events"),!1)}catch(r){return console.log("[StableIdStrategy] \u274C Failed to read events:",r.message),!1}}getName(){return"Stable ID Injection (Experimental)"}getPriority(){return 300}async generate(e){let{testFilePath:t,sessionPath:r,state:n}=e,s=`${r}/execute_live/events.json`,i=n?.title||"Generated Test";console.log("[StableIdStrategy] \u{1F3AF} Generating test using stable IDs"),console.log(`[StableIdStrategy] events: ${s}`),console.log(`[StableIdStrategy] output: ${t}`);let c=JSON.parse(mn(s,"utf-8")).filter(d=>["navigate","type","fill","click","select_option","select"].includes(d.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,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&&(a+=` await page.goto('${h}');
300
- `,a+=` await StableIdRuntime.injectStableIds(page);
301
-
302
- `)}else if(p.type==="click")if(u=!0,m=g,g)a+=` await StableIdRuntime.clickWithRetry(page, '${g}');
303
- `;else{let h=this._generateSemanticSelector(y);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(y)}').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,S=Array.isArray(h)?h[0]:h||"";g?a+=` await StableIdRuntime.selectWithRetry(page, '${g}', '${this._escapeString(S)}');
308
- `:a+=` await page.locator('select').selectOption('${this._escapeString(S)}');
309
- `}}return a+=`});
310
- `,Ei(t,a),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 ve,new Te],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(`
251
+ `;for(let O=T+1;O<Math.min(T+5,h.length);O++)S+=`${h[O]}
252
+ `}if(b.includes("at ")&&b.includes(".spec.")){let O=b.match(/:(\d+):\d+/);O&&(w=parseInt(O[1]))}}a(g===0?{success:!0,executionCount:n,message:"All tests passed!",output:m.slice(-500)}:{success:!1,executionCount:n,remainingAttempts:Ge-n,error:S.slice(0,1500)||"Test failed (see output)",failedAtLine:w,stdout:m.slice(-1500),stderr:d.slice(-500),hint:n<Ge?"Fix the error and run again.":"Last attempt - make your best fix."})}),u.on("error",g=>{clearTimeout(f),a({success:!1,executionCount:n,error:`Failed to run test: ${g.message}`})})}):{success:!1,executionCount:n,error:`Test file not found: ${s}. Make sure you wrote the file first using the write tool.`}},resetCount(i){for(let e of nt.keys())e.startsWith(`${i}:`)&&nt.delete(e)}};function Os(i){Mr.resetCount(i)}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 Ur,writeFileSync as Is}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(Ur(t,"utf-8")).some(o=>o.data?.params?.element)?(console.log("[MCPRefStrategy] \u2705 MCP element descriptions available"),!0):(console.log("[MCPRefStrategy] \u274C No MCP element descriptions found in events"),!1)}catch(r){return console.log("[MCPRefStrategy] \u274C Failed to read events:",r.message),!1}}getName(){return"MCP Reference Replay (Exact 1:1)"}getPriority(){return 200}async generate(e){let{testFilePath:t,sessionPath:r,state:n}=e,o=`${r}/execute_live/events.json`,s=n?.title||"Generated Test";console.log("[MCPRefStrategy] \u{1F3AF} Generating test using MCP element descriptions (1:1 replay)"),console.log(`[MCPRefStrategy] events: ${o}`),console.log(`[MCPRefStrategy] output: ${t}`);let a=JSON.parse(Ur(o,"utf-8")).filter(u=>["navigate","type","fill","click","select_option"].includes(u.type)),l=`import { test, expect } from '@playwright/test';
253
+ `;l+=`import { ZibbyRuntime } from '@zibby/core';
254
+
255
+ `,l+=`test('${s}', async ({ page }) => {
256
+ `,l+=` const timestamp = Date.now();
257
+
258
+ `;for(let u of a){let m=u.data?.params?.element||"element",d=u.data?.params?.ref,f=u.enrichedData?.traceActualText,g=u.enrichedData?.traceActualRole,y=u.enrichedData?.traceActualAriaLabel,h=u.enrichedData?.actualText,S=f||h,w=g||u.enrichedData?.actualRole,T=S||m,b=S||this._extractName(m),O=w||this._extractRole(m),R=f?" [accessibility-tree]":h?" [live]":" [AI]";if(u.type==="navigate")l+=` await page.goto('${u.data.params.url}');
259
+
260
+ `;else if(u.type==="click")l+=` // ${m}${S?` (actual: "${S}")${R}`:""}
261
+ `,l+=` await ZibbyRuntime.step(page, {
262
+ `,l+=` name: '${this._escapeString(m)}',
263
+ `,l+=` action: 'click',
264
+ `,l+=` strategies: [
265
+ `,l+=` { type: 'role', role: '${O}', name: '${this._escapeString(b)}' },
266
+ `,l+=` { type: 'text', text: '${this._escapeString(b)}' }
267
+ `,l+=` ]
268
+ `,l+=` });
269
+
270
+ `;else if(u.type==="fill"||u.type==="type"){let N=u.data.params.text;l+=` // ${m}${S?` (actual: "${S}")${R}`:""}
271
+ `,l+=` await ZibbyRuntime.step(page, {
272
+ `,l+=` name: '${this._escapeString(m)}',
273
+ `,l+=` action: 'fill',
274
+ `,l+=` value: '${this._escapeString(N)}',
275
+ `,l+=` strategies: [
276
+ `,l+=` { type: 'role', role: '${O}', name: '${this._escapeString(b)}' },
277
+ `,l+=` { type: 'attributes', placeholder: '${this._escapeString(b)}' }
278
+ `,l+=` ]
279
+ `,l+=` });
280
+
281
+ `}else if(u.type==="select_option"){let N=u.data.params.values,v=Array.isArray(N)?N[0]:N;l+=` // ${m}${S?` (actual: "${S}")${R}`:""}
282
+ `,l+=` await ZibbyRuntime.step(page, {
283
+ `,l+=` name: '${this._escapeString(m)}',
284
+ `,l+=` action: 'select',
285
+ `,l+=` value: '${this._escapeString(v)}',
286
+ `,l+=` strategies: [
287
+ `,l+=` { type: 'role', role: 'combobox', name: '${this._escapeString(b)}' }
288
+ `,l+=` ]
289
+ `,l+=` });
290
+
291
+ `}}return l+=`});
292
+ `,Is(t,l),console.log(`[MCPRefStrategy] \u2705 Generated test with ${a.length} actions using MCP descriptions`),{success:!0,testPath:t,method:"MCP Reference Replay (1:1)",actionsGenerated:a.length}}_extractRole(e){let t=e.toLowerCase();return t.includes("button")?"button":t.includes("textbox")?"textbox":t.includes("link")?"link":t.includes("checkbox")?"checkbox":t.includes("radio")?"radio":t.includes("combobox")?"combobox":t.includes("heading")?"heading":"button"}_extractName(e){return e.replace(/\s+(button|textbox|link|checkbox|radio|combobox)$/i,"").trim()}_escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}};import{readFileSync as Dr,writeFileSync as Cs}from"node:fs";var xe=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(Dr(t,"utf-8")).some(o=>o.stableId||o.data?.stableId)?(console.log("[StableIdStrategy] \u2705 Stable IDs available"),!0):(console.log("[StableIdStrategy] \u274C No stable IDs found in events"),!1)}catch(r){return console.log("[StableIdStrategy] \u274C Failed to read events:",r.message),!1}}getName(){return"Stable ID Injection (Experimental)"}getPriority(){return 300}async generate(e){let{testFilePath:t,sessionPath:r,state:n}=e,o=`${r}/execute_live/events.json`,s=n?.title||"Generated Test";console.log("[StableIdStrategy] \u{1F3AF} Generating test using stable IDs"),console.log(`[StableIdStrategy] events: ${o}`),console.log(`[StableIdStrategy] output: ${t}`);let a=JSON.parse(Dr(o,"utf-8")).filter(d=>["navigate","type","fill","click","select_option","select"].includes(d.type)),l=`import { test, expect } from '@playwright/test';
293
+ `;l+=`import { StableIdRuntime } from '@zibby/core';
294
+
295
+ `,l+=`test('${s}', async ({ page }) => {
296
+ `;let u=!1,m=null;for(let d=0;d<a.length;d++){let f=a[d],g=f.stableId||f.data?.stableId,y=f.data?.element||f.data?.params?.element||"element";if(f.type==="click"&&g&&g===m){console.log(`[StableIdStrategy] Skipping duplicate click on ${g}`);continue}if(f.type==="navigate"){let h=f.data?.url||f.data?.params?.url;h&&!u&&(l+=` await page.goto('${h}');
297
+ `,l+=` await StableIdRuntime.injectStableIds(page);
298
+
299
+ `)}else if(f.type==="click")if(u=!0,m=g,g)l+=` await StableIdRuntime.clickWithRetry(page, '${g}');
300
+ `;else{let h=this._generateSemanticSelector(y);l+=` await ${h}.click();
301
+ `,l+=` await StableIdRuntime.afterNavigation(page);
302
+ `}else if(f.type==="fill"||f.type==="type"){u=!1;let h=f.data?.text||f.data?.params?.text||"";g?l+=` await StableIdRuntime.fillWithRetry(page, '${g}', '${this._escapeString(h)}');
303
+ `:l+=` await page.getByPlaceholder('${this._escapeString(y)}').fill('${this._escapeString(h)}');
304
+ `}else if(f.type==="select_option"||f.type==="select"){u=!1;let h=f.data?.values||f.data?.params?.values,S=Array.isArray(h)?h[0]:h||"";g?l+=` await StableIdRuntime.selectWithRetry(page, '${g}', '${this._escapeString(S)}');
305
+ `:l+=` await page.locator('select').selectOption('${this._escapeString(S)}');
306
+ `}}return l+=`});
307
+ `,Cs(t,l),console.log(`[StableIdStrategy] \u2705 Generated test with ${a.length} actions using stable IDs`),{success:!0,testPath:t,method:"Stable ID Injection (Experimental)",actionsGenerated:a.length}}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}_generateSemanticSelector(e){let t=e.toLowerCase(),r="locator",n=e;return t.includes("button")?(r="button",n=e.replace(/\s*button\s*/gi,"").trim()):t.includes("link")?(r="link",n=e.replace(/\s*link\s*/gi,"").trim()):t.includes("textbox")?(r="textbox",n=e.replace(/\s*textbox\s*/gi,"").trim()):t.includes("checkbox")?(r="checkbox",n=e.replace(/\s*checkbox\s*/gi,"").trim()):(t.includes("combobox")||t.includes("dropdown")||t.includes("select"))&&(r="combobox",n=e.replace(/\s*(combobox|dropdown|select)\s*/gi,"").trim()),r!=="locator"&&n?`page.getByRole('${r}', { name: '${this._escapeString(n)}' })`:`page.getByText('${this._escapeString(e)}')`}};var It=class{constructor(){this.strategies=[new xe,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(`
311
308
  \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}},Ti=new Jt;var Ae=class{async verify(e){throw new Error("TestVerificationStrategy.verify() must be implemented")}canVerify(e){throw new Error("TestVerificationStrategy.canVerify() must be implemented")}getName(){throw new Error("TestVerificationStrategy.getName() must be implemented")}getPriority(){return 0}};import{execSync as vi}from"node:child_process";import{existsSync as Ai}from"node:fs";var Ie=class extends Ae{getName(){return"Playwright JSON Reporter"}getPriority(){return 100}canVerify(e){let{testFilePath:t}=e;return Ai(t)}async verify(e){let{testFilePath:t,cwd:r,timeout:n=3e4}=e;try{console.log(`\u{1F9EA} Running test: ${t}`);let s=`npx playwright test ${t} --reporter=json --timeout=${n}`,i=vi(s,{cwd:r,encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:n+1e4}),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 l=JSON.parse(i),c=l.stats||{},a="Test execution failed";if(l.suites&&l.suites.length>0){let m=l.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&&(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:c.expected||0,failed:c.unexpected||0,error:a,errorDetails:a,isEnvironmentError:u}}catch{let c=i.match(/Error: (.+)/),a=c?c[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 zt=class{constructor(){this.strategies=[new Ie],this.strategies.sort((e,t)=>t.getPriority()-e.getPriority())}registerStrategy(e){this.strategies.push(e),this.strategies.sort((t,r)=>r.getPriority()-t.getPriority())}async verify(e){console.log(`
309
+ \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}},Ps=new It;var Ee=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 ks}from"node:child_process";import{existsSync as Ns}from"node:fs";var Te=class extends Ee{getName(){return"Playwright JSON Reporter"}getPriority(){return 100}canVerify(e){let{testFilePath:t}=e;return Ns(t)}async verify(e){let{testFilePath:t,cwd:r,timeout:n=3e4}=e;try{console.log(`\u{1F9EA} Running test: ${t}`);let o=`npx playwright test ${t} --reporter=json --timeout=${n}`,s=ks(o,{cwd:r,encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:n+1e4}),a=JSON.parse(s).stats||{};return{success:a.unexpected===0,passed:a.expected||0,failed:a.unexpected||0,error:null,errorDetails:null}}catch(o){let s=o.stdout||o.stderr||o.message;try{let c=JSON.parse(s),a=c.stats||{},l="Test execution failed";if(c.suites&&c.suites.length>0){let m=c.suites[0];if(m.specs&&m.specs.length>0){let d=m.specs[0];if(d.tests&&d.tests.length>0){let f=d.tests[0];if(f.results&&f.results.length>0){let g=f.results[0];g.error&&(l=g.error.message||l)}}}}let u=l.includes("Executable doesn't exist")||l.includes("browserType.launch")||l.includes("Please run the following command")||l.includes("npx playwright install")||s.includes("Executable doesn't exist")||s.includes("npx playwright install");return{success:!1,passed:a.expected||0,failed:a.unexpected||0,error:l,errorDetails:l,isEnvironmentError:u}}catch{let a=s.match(/Error: (.+)/),l=a?a[1]:"Test execution failed",u=l.includes("Executable doesn't exist")||l.includes("browserType.launch")||l.includes("Please run the following command")||l.includes("npx playwright install")||s.includes("Executable doesn't exist")||s.includes("npx playwright install");return{success:!1,passed:0,failed:1,error:l,errorDetails:l,isEnvironmentError:u}}}}};var Ct=class{constructor(){this.strategies=[new Te],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
310
  \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}},Ii=new zt;var te=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 l of this.enrichers)try{if(!l.canEnrich(t)){s.push(l.getName());continue}let c=Date.now(),a=await l.enrich(e,t),u=Date.now()-c;a?(Object.assign(r,a),n.push({name:l.getName(),duration:u})):s.push(l.getName())}catch(c){console.warn(`[EnrichmentPipeline] ${l.getName()} failed:`,c.message),i.push(l.getName()),this.stats.errors[l.getName()]=(this.stats.errors[l.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(`
311
+ \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}},Rs=new Ct;var ee=class{constructor(e={}){this.enrichers=[],this.config=e,this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}register(e){return this.enrichers.push(e),this.enrichers.sort((t,r)=>r.getPriority()-t.getPriority()),this}unregister(e){return this.enrichers=this.enrichers.filter(t=>t.getName()!==e),this}get(e){return this.enrichers.find(t=>t.getName()===e)}setEnabled(e,t){let r=this.get(e);return r&&(r.enabled=t),this}async enrich(e,t){this.stats.totalEvents++;let r={...e},n=[],o=[],s=[];for(let c of this.enrichers)try{if(!c.canEnrich(t)){o.push(c.getName());continue}let a=Date.now(),l=await c.enrich(e,t),u=Date.now()-a;l?(Object.assign(r,l),n.push({name:c.getName(),duration:u})):o.push(c.getName())}catch(a){console.warn(`[EnrichmentPipeline] ${c.getName()} failed:`,a.message),s.push(c.getName()),this.stats.errors[c.getName()]=(this.stats.errors[c.getName()]||0)+1}return r._enrichment={version:"1.0",timestamp:new Date().toISOString(),enrichers:{run:n,skipped:o,failed:s}},n.length>0?this.stats.enrichedEvents++:this.stats.skippedEvents++,r}async enrichBatch(e,t){let r=[];for(let n of e){let o=await this.enrich(n,t);r.push(o)}return r}getStats(){return{...this.stats,enrichers:this.enrichers.map(e=>({name:e.getName(),enabled:e.enabled,priority:e.getPriority(),errors:this.stats.errors[e.getName()]||0}))}}resetStats(){this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}logStatus(){console.log(`
315
312
  \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 $e=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})),l=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:l,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 gn from"node:crypto";var de=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 l=await this.getAxContext(i,s),c=this.hashAxSubtree(i),a=this.hashAxPath(l.path);return{accessibility:{role:i.role,name:i.name||"",level:l.level,parent:l.parent,siblings:l.siblings,axTreeHash:c,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 gn.createHash("md5").update(t).digest("hex").substring(0,12)}hashAxPath(e){let t=e.map(r=>`${r.role}:${r.name}`).join("/");return gn.createHash("md5").update(t).digest("hex").substring(0,12)}};var me=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,l=0,c=new MutationObserver(()=>{l++,clearTimeout(i),i=setTimeout(()=>{c.disconnect(),s(l===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 Oe=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 w=Array.from(S.children).filter(T=>T.tagName===y.tagName);if(w.length>1){let T=w.indexOf(y)+1;h+=`:nth-child(${T})`}}g.unshift(h),y=y.parentElement}return`body > ${g.join(" > ")}`},l=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 w=y.tagName.toLowerCase();g.unshift(`${w}[${h}]`),y=y.parentElement}return`/html/body/${g.join("/")}`},c={};for(let p of s.attributes)c[p.name]=p.value;let a=window.getComputedStyle(s),u={display:a.display,visibility:a.visibility,opacity:a.opacity,pointerEvents:a.pointerEvents},m=0,d=s.parentElement;for(;d;)m++,d=d.parentElement;return{path:i(s),xpath:l(s),depth:m,parent:s.parentElement?s.parentElement.tagName.toLowerCase():null,tagName:s.tagName.toLowerCase(),attributes:c,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 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,l=null;if(t?.element)try{let c=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=c.text||c.innerText||c.value||c.placeholder,i=c.role,l=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:l,recordedSelector:s||n}}};function Yt(o={}){let e=new te(o);return o.enableMCPRef!==!1&&e.register(new Ze(o)),o.enableTraceText!==!1&&e.register(new fe(o)),o.enableAccessibility!==!1&&e.register(new de(o)),o.enablePageState!==!1&&e.register(new me(o)),o.enablePosition!==!1&&e.register(new $e(o)),o.enableDOM!==!1&&e.register(new Oe(o)),e}function Ht(o={}){let e=new te(o);return e.register(new de(o)),e.register(new me(o)),e}function $i(o,e={}){let t=new te(e);for(let r of o)t.register(r);return t}import{readFileSync as Oi,writeFileSync as Zt}from"node:fs";import{join as hn}from"node:path";async function Pi(o,e={}){let t=hn(o,"events.json"),r=hn(o,"trace.zip");try{let n=JSON.parse(Oi(t,"utf-8")),s=n.map(l=>({...l,_enrichmentNote:"Full enrichment requires live Playwright access. Use EnrichmentPipeline during test execution."})),i=`${t}.backup`;return Zt(i,JSON.stringify(n,null,2)),Zt(t,JSON.stringify(s,null,2)),{enrichedCount:s.length,skippedCount:0,errors:[]}}catch(n){return console.error("[EnrichmentIntegration] Failed to enrich events:",n.message),{enrichedCount:0,skippedCount:0,errors:[n.message]}}}var Wt=class{constructor(e={}){this.pipeline=e.minimal?Ht(e):Yt(e),this.events=[],this.config=e}async recordEvent(e,t,r){let n={id:this.events.length,type:e,timestamp:new Date().toISOString(),data:t},s=await this.pipeline.enrich(n,{...r,event:n});return this.events.push(s),s}saveEvents(e){Zt(e,JSON.stringify(this.events,null,2)),console.log(`[LiveEnrichment] Saved ${this.events.length} enriched events to ${e}`),this.pipeline.logStatus()}getStats(){return this.pipeline.getStats()}};Et();var xn=o=>{o?.message?.includes("Connection closed")||o?.message?.includes("MCP error -32000")||o?.code===-32e3||console.error("Unhandled rejection:",o)};process.listeners("unhandledRejection").includes(xn)||process.on("unhandledRejection",xn);async function Di(o,e={}){let{agent:t,mcp:r,headless:n,cwd:s=process.cwd(),specPath:i,sessionPath:l,sessionTimestamp:c,...a}=e,u=yn(o,"utf-8"),m=null,{agent:d,error:p}=await Fi(s,a),g=d;if(!g&&e.fallbackAgentModule){let S=e.fallbackAgentModule,w=S.BrowserTestAutomationAgent||S.default;w&&(g=new w(a))}if(!g&&p&&console.warn(`\u26A0\uFE0F Failed to load local agent: ${p}`),!g)throw new Error(`No agent found. Please run:
313
+ 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 ve=class extends z{getName(){return"PositionEnricher"}getPriority(){return 90}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:n}=t,o=await n.boundingBox();if(!o)return null;let s=await r.evaluate(()=>({scrollX:window.scrollX,scrollY:window.scrollY,width:window.innerWidth,height:window.innerHeight})),c=o.y>=s.scrollY&&o.y+o.height<=s.scrollY+s.height&&o.x>=0&&o.x+o.width<=s.width;return{position:{boundingBox:o,viewport:s,inViewport:c,centerPoint:{x:Math.round(o.x+o.width/2),y:Math.round(o.y+o.height/2)}}}}catch(r){return this.handleError(r,e)}}};import Fr from"node:crypto";var ue=class extends z{getName(){return"AccessibilityEnricher"}getPriority(){return 100}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:n}=t,o=await r.accessibility.snapshot(),s=await this.findAxNode(n,o);if(!s)return null;let c=await this.getAxContext(s,o),a=this.hashAxSubtree(s),l=this.hashAxPath(c.path);return{accessibility:{role:s.role,name:s.name||"",level:c.level,parent:c.parent,siblings:c.siblings,axTreeHash:a,axPathHash:l}}}catch(r){return this.handleError(r,e)}}async findAxNode(e,t){let r=await e.evaluate(n=>({role:n.getAttribute("role")||n.tagName.toLowerCase(),name:n.getAttribute("aria-label")||n.textContent?.trim()||"",tagName:n.tagName.toLowerCase()}));return this.searchAxTree(t,r)}searchAxTree(e,t){if(!e)return null;if(e.role===t.role&&(e.name||"").includes(t.name.substring(0,20)))return e;if(e.children)for(let r of e.children){let n=this.searchAxTree(r,t);if(n)return n}return null}getAxContext(e,t){let r={level:0,parent:null,siblings:[],path:[]},n=this.findParent(e,t);return n&&(r.parent={role:n.role,name:n.name},r.siblings=(n.children||[]).filter(o=>o!==e).map(o=>({role:o.role,name:o.name})).slice(0,3)),r.level=this.calculateLevel(e,t),r.path=this.buildPath(e,t),r}findParent(e,t,r=t){if(!r||!r.children)return null;if(r.children.includes(e))return r;for(let n of r.children){let o=this.findParent(e,t,n);if(o)return o}return null}calculateLevel(e,t,r=t,n=0){if(r===e)return n;if(r.children)for(let o of r.children){let s=this.calculateLevel(e,t,o,n+1);if(s>=0)return s}return-1}buildPath(e,t,r=t,n=[]){if(r===e)return[...n,{role:r.role,name:r.name}];if(r.children)for(let o of r.children){let s=this.buildPath(e,t,o,[...n,{role:r.role,name:r.name}]);if(s)return s}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 Fr.createHash("md5").update(t).digest("hex").substring(0,12)}hashAxPath(e){let t=e.map(r=>`${r.role}:${r.name}`).join("/");return Fr.createHash("md5").update(t).digest("hex").substring(0,12)}};var pe=class extends z{constructor(e={}){super(e),this.pendingRequests=new Set,this.setupNetworkTracking=!1}getName(){return"PageStateEnricher"}getPriority(){return 95}canEnrich(e){return this.enabled&&e.page}async setupTracking(e){this.setupNetworkTracking||(e.on("request",t=>{["document","xhr","fetch"].includes(t.resourceType())&&this.pendingRequests.add(t.url())}),e.on("requestfinished",t=>{this.pendingRequests.delete(t.url())}),e.on("requestfailed",t=>{this.pendingRequests.delete(t.url())}),this.setupNetworkTracking=!0)}async enrich(e,t){try{let{page:r}=t;await this.setupTracking(r);let n=await r.evaluate(()=>({readyState:document.readyState,domContentLoaded:document.readyState!=="loading",loadComplete:document.readyState==="complete",url:document.location.href})),o=await this.checkDOMStability(r);return{page:{networkIdle:this.pendingRequests.size===0,pendingRequests:this.pendingRequests.size,domStable:o,...n}}}catch(r){return this.handleError(r,e)}}async checkDOMStability(e,t=500){try{return await e.evaluate(n=>new Promise(o=>{let s,c=0,a=new MutationObserver(()=>{c++,clearTimeout(s),s=setTimeout(()=>{a.disconnect(),o(c===0)},n)});a.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),s=setTimeout(()=>{a.disconnect(),o(!0)},n)}),t)}catch{return!1}}reset(){this.pendingRequests.clear(),this.setupNetworkTracking=!1}};var Ae=class extends z{getName(){return"DOMEnricher"}getPriority(){return 85}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{element:r}=t,n=await r.evaluate(o=>{let s=f=>{let g=[],y=f;for(;y&&y!==document.body;){let h=y.tagName.toLowerCase(),S=y.parentElement;if(S){let w=Array.from(S.children).filter(T=>T.tagName===y.tagName);if(w.length>1){let T=w.indexOf(y)+1;h+=`:nth-child(${T})`}}g.unshift(h),y=y.parentElement}return`body > ${g.join(" > ")}`},c=f=>{let g=[],y=f;for(;y&&y!==document.body;){let h=1,S=y.previousSibling;for(;S;)S.nodeType===1&&S.tagName===y.tagName&&h++,S=S.previousSibling;let w=y.tagName.toLowerCase();g.unshift(`${w}[${h}]`),y=y.parentElement}return`/html/body/${g.join("/")}`},a={};for(let f of o.attributes)a[f.name]=f.value;let l=window.getComputedStyle(o),u={display:l.display,visibility:l.visibility,opacity:l.opacity,pointerEvents:l.pointerEvents},m=0,d=o.parentElement;for(;d;)m++,d=d.parentElement;return{path:s(o),xpath:c(o),depth:m,parent:o.parentElement?o.parentElement.tagName.toLowerCase():null,tagName:o.tagName.toLowerCase(),attributes:a,state:{visible:l.display!=="none"&&l.visibility!=="hidden",enabled:!o.disabled,focused:document.activeElement===o,...u}}});return{dom:{path:n.path,xpath:n.xpath,depth:n.depth,parent:n.parent,selector:this.buildSmartSelector(n)},attributes:n.attributes,state:n.state}}catch(r){return this.handleError(r,e)}}buildSmartSelector(e){let t=e.tagName;if(e.attributes.id)return`#${e.attributes.id}`;if(e.attributes["data-test-id"])return`[data-test-id="${e.attributes["data-test-id"]}"]`;if(e.attributes.class){let r=e.attributes.class.split(" ").filter(n=>n&&!n.match(/^(active|focus|hover|disabled)/));r.length>0&&(t+=`.${r.slice(0,2).join(".")}`)}return e.parent&&(t=`${e.parent} > ${t}`),t}};var 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 o=null,s=null,c=null;if(t?.element)try{let a=await t.element.evaluate(l=>({text:l.textContent?.trim()||"",innerText:l.innerText?.trim()||"",value:l.value||"",label:l.getAttribute("aria-label")||l.getAttribute("label")||"",role:l.getAttribute("role")||l.tagName.toLowerCase(),placeholder:l.getAttribute("placeholder")||"",title:l.getAttribute("title")||""}));o=a.text||a.innerText||a.value||a.placeholder,s=a.role,c=a.label||a.title,console.log(`[MCPRefEnricher] \u2705 Captured actual text: "${o}" (AI said: "${n}")`)}catch(a){console.log(`[MCPRefEnricher] \u26A0\uFE0F Could not extract actual text: ${a.message}`)}return{mcpRef:r,mcpElement:n,actualText:o,actualRole:s,actualLabel:c,recordedSelector:o||n}}};function Pt(i={}){let e=new ee(i);return i.enableMCPRef!==!1&&e.register(new Ke(i)),i.enableTraceText!==!1&&e.register(new ce(i)),i.enableAccessibility!==!1&&e.register(new ue(i)),i.enablePageState!==!1&&e.register(new pe(i)),i.enablePosition!==!1&&e.register(new ve(i)),i.enableDOM!==!1&&e.register(new Ae(i)),e}function kt(i={}){let e=new ee(i);return e.register(new ue(i)),e.register(new pe(i)),e}function Ls(i,e={}){let t=new ee(e);for(let r of i)t.register(r);return t}import{readFileSync as Ms,writeFileSync as Nt}from"node:fs";import{join as jr}from"node:path";async function Us(i,e={}){let t=jr(i,"events.json"),r=jr(i,"trace.zip");try{let n=JSON.parse(Ms(t,"utf-8")),o=n.map(c=>({...c,_enrichmentNote:"Full enrichment requires live Playwright access. Use EnrichmentPipeline during test execution."})),s=`${t}.backup`;return Nt(s,JSON.stringify(n,null,2)),Nt(t,JSON.stringify(o,null,2)),{enrichedCount:o.length,skippedCount:0,errors:[]}}catch(n){return console.error("[EnrichmentIntegration] Failed to enrich events:",n.message),{enrichedCount:0,skippedCount:0,errors:[n.message]}}}var Rt=class{constructor(e={}){this.pipeline=e.minimal?kt(e):Pt(e),this.events=[],this.config=e}async recordEvent(e,t,r){let n={id:this.events.length,type:e,timestamp:new Date().toISOString(),data:t},o=await this.pipeline.enrich(n,{...r,event:n});return this.events.push(o),o}saveEvents(e){Nt(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()}};mt();var zr=i=>{i?.message?.includes("Connection closed")||i?.message?.includes("MCP error -32000")||i?.code===-32e3||console.error("Unhandled rejection:",i)};process.listeners("unhandledRejection").includes(zr)||process.on("unhandledRejection",zr);async function Js(i,e={}){let{agent:t,mcp:r,headless:n,cwd:o=process.cwd(),specPath:s,sessionPath:c,sessionTimestamp:a,...l}=e,u=Br(i,"utf-8"),m=null,{agent:d,error:f}=await Hs(o,l),g=d;if(!g&&e.fallbackAgentModule){let S=e.fallbackAgentModule,w=S.BrowserTestAutomationAgent||S.default;w&&(g=new w(l))}if(!g&&f&&console.warn(`\u26A0\uFE0F Failed to load local agent: ${f}`),!g)throw new Error(`No agent found. Please run:
317
314
  zibby init
318
315
 
319
- This will create .zibby/graph.mjs with your workflow definition.`);await g.initialize(m);let y=!1,h=()=>{if(!y)try{Ot({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(`
316
+ This will create .zibby/graph.mjs with your workflow definition.`);await g.initialize(m);let y=!1,h=()=>{if(!y)try{o||process.cwd(),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
317
  \u{1F3AF} Running Single Node: ${e.singleNode} (Framework Mode)
321
- `);let v=g.calculateOutputPath(i||o),O=g.buildGraph(),D={};for(let[I,C]of O.nodes.entries())D[I]=C.config||C;let E={};if(e.sessionId){let I=e.sessionId,C=e.paths?.output||Ni;if(I==="last"){let L=Pe(s,C,wn);if(Sn(L)){let{readdirSync:F,statSync:A}=await import("fs"),_=F(L).filter(M=>A(Pe(L,M)).isDirectory()).map(M=>({name:M,time:A(Pe(L,M)).mtimeMs})).sort((M,U)=>U.time-M.time);_.length>0?(I=_[0].name,console.log(`\u{1F4C2} Using latest session: ${I}`)):console.log(`\u26A0\uFE0F No sessions found in ${L}`)}}let j=Pe(s,C,wn,I),N=Pe(j,"execute_live"),x=Pe(N,Ri);Sn(x)?(console.log(`\u{1F4C2} Loading session: ${I}`),E={sessionPath:j,execute_live_output:JSON.parse(yn(x,"utf-8"))}):console.log(`\u26A0\uFE0F Session not found: ${j}`)}let P=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(P),ct({cwd:s,config:e,result:P,success:!0,specPath:i||o}),P}let S;typeof e.onPipelineProgress=="function"?S=e.onPipelineProgress:e.runIndex?.pipelineProgress!==!1&&(S=Dr({cwd:s||process.cwd(),config:e}));let w=s||process.cwd(),T=l!=null&&String(l).trim()!==""?(()=>{let v=String(l).trim();try{return Ci(v)?bn(v):bn(w,v)}catch{return v}})():void 0,b=Li(),$=T??b;Mi();let k=ki({cwd:w,config:e,traceFrom:"runTest",initialState:{sessionPath:$,sessionTimestamp:c}}),R;try{R=await g.run(u,{testSpec:u,specPath:i||o,cwd:w,config:e,sessionPath:k.sessionPath,sessionTimestamp:k.sessionTimestamp,...S?{onPipelineProgress:S}:{}})}catch(v){throw typeof v?.message=="string"&&v.message.includes("Interrupted by user")&&Ot({cwd:s||process.cwd(),config:e}),y||ct({cwd:s,config:e,result:v?.partialResult||{},success:!1,specPath:i||o,errorMessage:v?.message}),v}return ct({cwd:s,config:e,result:R,success:!0,specPath:i||o}),R}finally{process.off("SIGINT",h),process.off("SIGTERM",h),await g.cleanup()}}function Ui(o){return o.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function Bi(o,e){if(o[e])return o[e];let t=Ui(e);if(o[t])return o[t];let r=`${t}Workflow`;return o[r]?o[r]:null}async function sf(o=process.cwd()){try{let{join:e}=await import("path"),{existsSync:t}=await import("fs"),{pathToFileURL:r}=await import("url"),n=e(o,".zibby/graph.mjs");if(!t(n))return{available:[],default:null,error:"No .zibby/graph.mjs found"};let s=await import(r(n).href),i=Object.keys(s).filter(c=>c!=="default"&&typeof s[c]=="function"&&s[c].prototype instanceof _e),l=s.BrowserTestAutomationAgent?"BrowserTestAutomationAgent":s.CursorAgent?"CursorAgent":s.default?"default":i[0]||null;return{available:i,default:l,error:null}}catch(e){return{available:[],default:null,error:e.message}}}async function Fi(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),l=e.workflow,c;if(l){if(c=Bi(i,l),!c){let u=Object.keys(i).filter(m=>m!=="default"&&typeof i[m]=="function");throw new Error(`Workflow "${l}" not found.
318
+ `);let v=g.calculateOutputPath(s||i),I=g.buildGraph(),U={};for(let[$,P]of I.nodes.entries())U[$]=P.config||P;let E={};if(e.sessionId){let $=e.sessionId,P=e.paths?.output||Fs;if($==="last"){let M=$e(o,P,Jr);if(Gr(M)){let{readdirSync:j,statSync:A}=await import("fs"),x=j(M).filter(L=>A($e(M,L)).isDirectory()).map(L=>({name:L,time:A($e(M,L)).mtimeMs})).sort((L,D)=>D.time-L.time);x.length>0?($=x[0].name,console.log(`\u{1F4C2} Using latest session: ${$}`)):console.log(`\u26A0\uFE0F No sessions found in ${M}`)}}let B=$e(o,P,Jr,$),k=$e(B,"execute_live"),_=$e(k,js);Gr(_)?(console.log(`\u{1F4C2} Loading session: ${$}`),E={sessionPath:B,execute_live_output:JSON.parse(Br(_,"utf-8"))}):console.log(`\u26A0\uFE0F Session not found: ${B}`)}let C=await g.runSingleNode(e.singleNode,U,{testSpec:u,outputPath:v,cwd:o||process.cwd(),contextConfig:e.contextConfig,specPath:s||i,config:e,...E});return typeof g.onComplete=="function"&&await g.onComplete(C),C}let S;typeof e.onPipelineProgress=="function"?S=e.onPipelineProgress:e.runIndex?.pipelineProgress!==!1&&(S=lr({cwd:o||process.cwd(),config:e}));let w=o||process.cwd(),T=c!=null&&String(c).trim()!==""?(()=>{let v=String(c).trim();try{return Ds(v)?Kr(v):Kr(w,v)}catch{return v}})():void 0,b=Ks(),O=T??b;Gs();let R=Bs({cwd:w,config:e,traceFrom:"runTest",initialState:{sessionPath:O,sessionTimestamp:a}}),N;try{N=await g.run(u,{testSpec:u,specPath:s||i,cwd:w,config:e,sessionPath:R.sessionPath,sessionTimestamp:R.sessionTimestamp,...S?{onPipelineProgress:S}:{}})}catch(v){throw typeof v?.message=="string"&&v.message.includes("Interrupted by user")&&(o||process.cwd(),void 0),y||(v?.partialResult,v?.message,void 0),v}return N}finally{process.off("SIGINT",h),process.off("SIGTERM",h),await g.cleanup()}}function zs(i){return i.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function Ys(i,e){if(i[e])return i[e];let t=zs(e);if(i[t])return i[t];let r=`${t}Workflow`;return i[r]?i[r]:null}async function Hu(i=process.cwd()){try{let{join:e}=await import("path"),{existsSync:t}=await import("fs"),{pathToFileURL:r}=await import("url"),n=e(i,".zibby/graph.mjs");if(!t(n))return{available:[],default:null,error:"No .zibby/graph.mjs found"};let o=await import(r(n).href),s=Object.keys(o).filter(a=>a!=="default"&&typeof o[a]=="function"&&o[a].prototype instanceof be),c=o.BrowserTestAutomationAgent?"BrowserTestAutomationAgent":o.CursorAgent?"CursorAgent":o.default?"default":s[0]||null;return{available:s,default:c,error:null}}catch(e){return{available:[],default:null,error:e.message}}}async function Hs(i,e){try{let{join:t}=await import("path"),{existsSync:r}=await import("fs"),{pathToFileURL:n}=await import("url"),o=t(i,".zibby/graph.mjs");if(!r(o))return{agent:null,error:null};let s=await import(n(o).href),c=e.workflow,a;if(c){if(a=Ys(s,c),!a){let u=Object.keys(s).filter(m=>m!=="default"&&typeof s[m]=="function");throw new Error(`Workflow "${c}" not found.
322
319
  Available workflows: ${u.join(", ")}
323
- Supported formats: QuickSmokeWorkflow, QuickSmoke, quick-smoke`)}let a=Object.keys(i).find(u=>i[u]===c);console.log(`\u2713 Using workflow: ${a} (from --workflow ${l})`)}else{if(c=i.BrowserTestAutomationAgent||i.CursorAgent||i.default,!c){let a=Object.keys(i).filter(u=>u!=="default"&&typeof i[u]=="function"&&i[u].prototype instanceof _e);a.length>0&&(c=i[a[0]],console.log(`\u2713 Using workflow: ${a[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 _n=class{constructor(e={}){this.config=e}async run(e){return Di(e.spec||e.specPath,{...this.config,...e})}};export{Tn as AGENT_TYPES,Ml as ALL_TOOLS,de as AccessibilityEnricher,yo as AgentStrategy,le as AssistantStrategy,To as CHAT_MEMORY_TOOLS,zf as CI_ENV_VARS,vn as CORE_LOG_LEVELS,So as CORE_TOOLS,se as ClaudeAgentStrategy,oe as CodexAgentStrategy,ne as CursorAgentStrategy,li as DEFAULT_MAX_CONCURRENT_RUNS,J as DEFAULT_MODELS,Bf as DEFAULT_OUTPUT_BASE,Oe as DOMEnricher,Jf as EVENTS_FILE,te as EnrichmentPipeline,z as EventEnricher,wo as GITHUB_TOOLS,ae as GeminiAgentStrategy,bo as JIRA_TOOLS,Z as LOG_LEVELS,Wt as LiveEnrichmentRecorder,Xe as Logger,pi as MAX_MAX_CONCURRENT_RUNS,Te as MCPRefStrategy,Eo as MEMORY_TOOLS,ui as MIN_MAX_CONCURRENT_RUNS,Ue as McpClientManager,ce as OpenAIToolProvider,me as PageStateEnricher,Ie as PlaywrightJsonVerificationStrategy,$e as PositionEnricher,Kf as RAW_OUTPUT_FILE,Gf as RESULT_FILE,sn as RIPPLE_EFFECT_SCRIPT,_o as RUNNER_TOOLS,Mt as ResultHandler,Ff as SESSIONS_DIR,jf as SESSION_INFO_FILE,Ef as SKILLS,vo as SKILL_TOOLS,xo as SLACK_TOOLS,Je as SelectorGenerator,Kt as StableIdRuntime,ve as StableIdStrategy,X as StreamingParser,_n as TestAutomation,ee as TestGenerationStrategy,Ft as TestPostProcessor,Ae as TestVerificationStrategy,Se as ToolCallProvider,Ye as TraceParser,_e as WorkflowAgent,cf as WorkflowGraph,Gt as ZibbyRuntime,Ge as ZibbyUploader,to as checkCursorAgentInstalled,ei as checkCursorAgentPatched,pf as clearInheritedSessionEnvForFreshRun,Ro as clearTokenCache,Ko as cloneRepo,$i as createCustomPipeline,Yt as createDefaultPipeline,Ht as createMinimalPipeline,Yr as createUploader,Pi as enrichRecordedEvents,oi as generateRippleHelperCode,uf as generateWorkflowSessionId,Kr as getAgentStrategy,$f as getAllSkills,ti as getApprovalKeys,ro as getCursorAgentInstallInstructions,Af as getSkill,If as hasSkill,si as injectRippleEffect,ho as invokeAgent,Of as listSkillIds,sf as listWorkflows,f as logger,Do as organizeVideos,Qo as patchCursorAgentForCI,Y as pickFromPool,hi as postProcessEvents,df as readPinnedSessionPathFromEnv,Et as registerBuiltInStrategies,vf as registerSkill,xi as resetExecutionCount,No as resolveIntegrationToken,fi as resolveMaxParallelRuns,lf as resolveWorkflowSession,fn as runPlaywrightTestTool,Di as runTest,ni as saveApprovalKeys,tn as sessionSkill,ff as shouldTrustInheritedSessionEnv,mf as syncProcessEnvToSession,Ti as testGenerationManager,Ii as testVerificationManager,q as timeline,fo as workflow,yf as z};
320
+ Supported formats: QuickSmokeWorkflow, QuickSmoke, quick-smoke`)}let l=Object.keys(s).find(u=>s[u]===a);console.log(`\u2713 Using workflow: ${l} (from --workflow ${c})`)}else{if(a=s.BrowserTestAutomationAgent||s.CursorAgent||s.default,!a){let l=Object.keys(s).filter(u=>u!=="default"&&typeof s[u]=="function"&&s[u].prototype instanceof be);l.length>0&&(a=s[l[0]],console.log(`\u2713 Using workflow: ${l[0]} (auto-detected)`))}if(!a)return{agent:null,error:"Could not find any WorkflowAgent export in local graph.js"};a.name?.includes("auto-detected")||console.log("\u2713 Using local agent from .zibby/graph.mjs")}return{agent:new a(e),error:null}}catch(t){return{agent:null,error:t.message}}}var Yr=class{constructor(e={}){this.config=e}async run(e){return Js(e.spec||e.specPath,{...this.config,...e})}};export{Wr as AGENT_TYPES,xl as ALL_TOOLS,ue as AccessibilityEnricher,To as AgentStrategy,le as AssistantStrategy,Po as CHAT_MEMORY_TOOLS,Np as CI_ENV_VARS,Zr as CORE_LOG_LEVELS,vo as CORE_TOOLS,ne as ClaudeAgentStrategy,oe as CodexAgentStrategy,re as CursorAgentStrategy,hs as DEFAULT_MAX_CONCURRENT_RUNS,J as DEFAULT_MODELS,$p as DEFAULT_OUTPUT_BASE,Ae as DOMEnricher,kp as EVENTS_FILE,ee as EnrichmentPipeline,z as EventEnricher,$o as GITHUB_TOOLS,ie as GeminiAgentStrategy,Ao as JIRA_TOOLS,H as LOG_LEVELS,Rt as LiveEnrichmentRecorder,ze as Logger,Ss as MAX_MAX_CONCURRENT_RUNS,_e as MCPRefStrategy,Co as MEMORY_TOOLS,ys as MIN_MAX_CONCURRENT_RUNS,Le as McpClientManager,ae as OpenAIToolProvider,pe as PageStateEnricher,Te as PlaywrightJsonVerificationStrategy,ve as PositionEnricher,Pp as RAW_OUTPUT_FILE,Cp as RESULT_FILE,Ir as RIPPLE_EFFECT_SCRIPT,Io as RUNNER_TOOLS,wt as ResultHandler,Op as SESSIONS_DIR,Ip as SESSION_INFO_FILE,pp as SKILLS,ko as SKILL_TOOLS,Oo as SLACK_TOOLS,Fe as SelectorGenerator,Ot as StableIdRuntime,xe as StableIdStrategy,Z as StreamingParser,Yr as TestAutomation,Q as TestGenerationStrategy,vt as TestPostProcessor,Ee as TestVerificationStrategy,ge as ToolCallProvider,Be as TraceParser,be as WorkflowAgent,Xu as WorkflowGraph,$t as ZibbyRuntime,Ue as ZibbyUploader,lo as checkCursorAgentInstalled,as as checkCursorAgentPatched,Qu as clearInheritedSessionEnvForFreshRun,jo as clearTokenCache,Xo as cloneRepo,Ls as createCustomPipeline,Pt as createDefaultPipeline,kt as createMinimalPipeline,yr as createUploader,Us as enrichRecordedEvents,fs as generateRippleHelperCode,Vu as generateWorkflowSessionId,mr as getAgentStrategy,hp as getAllSkills,ls as getApprovalKeys,co as getCursorAgentInstallInstructions,mp as getSkill,gp as hasSkill,ps as injectRippleEffect,Eo as invokeAgent,yp as listSkillIds,Hu as listWorkflows,p as logger,Jo as organizeVideos,is as patchCursorAgentForCI,Y as pickFromPool,Es as postProcessEvents,tp as readPinnedSessionPathFromEnv,mt as registerBuiltInStrategies,dp as registerSkill,Os as resetExecutionCount,Fo as resolveIntegrationToken,bs as resolveMaxParallelRuns,qu as resolveWorkflowSession,Mr as runPlaywrightTestTool,Js as runTest,us as saveApprovalKeys,Ar as sessionSkill,ep as shouldTrustInheritedSessionEnv,rp as syncProcessEnvToSession,Ps as testGenerationManager,Rs as testVerificationManager,X as timeline,wo as workflow,sp as z};