@zibby/core 0.3.0 → 0.3.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.
- package/dist/backend-client.js +1 -1
- package/dist/index.js +91 -91
- package/dist/package.json +2 -2
- package/dist/register-built-in-strategies.js +57 -57
- package/dist/strategies/assistant-strategy.js +8 -8
- package/dist/strategies/claude-strategy.js +4 -4
- package/dist/strategies/codex-strategy.js +4 -4
- package/dist/strategies/cursor-strategy.js +34 -34
- package/dist/strategies/gemini-strategy.js +12 -12
- package/dist/strategies/index.js +54 -54
- package/dist/strategies/utils/auth-pool.js +1 -0
- package/dist/templates/code-analysis/nodes/create-pr-node.js +1 -1
- package/package.json +2 -2
- package/templates/code-analysis/nodes/create-pr-node.js +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
1
|
+
var en=(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 Zr,existsSync as Wr}from"node:fs";import{join as Ae,resolve as Xr,isAbsolute as Qo}from"node:path";import{DEFAULT_OUTPUT_BASE as ei,SESSIONS_DIR as qr,RESULT_FILE as ti,resolveWorkflowSession as ri,clearInheritedSessionEnvForFreshRun as ni,readPinnedSessionPathFromEnv as si}from"@zibby/agent-workflow";import{registerStrategy as ke}from"@zibby/agent-workflow";import{AgentStrategy as xn,DEFAULT_OUTPUT_BASE as _n,SESSION_INFO_FILE as En,STOP_REQUEST_FILE as Tn,getAllSkills as vn,getSkill as Zt}from"@zibby/agent-workflow";import{spawn as In,execSync as ee}from"node:child_process";import{writeFileSync as Wt,readFileSync as Xt,mkdirSync as qt,existsSync as Oe,accessSync as Vt,constants as Qt,unlinkSync as An}from"node:fs";import{join as Y,resolve as $n}from"node:path";import{homedir as Ce}from"node:os";import Pe from"chalk";var J={debug:0,info:1,warn:2,error:3,silent:4},Ke=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return J.debug;if(process.env.ZIBBY_VERBOSE==="true")return J.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in J?J[e]:J.info}_shouldLog(e){return J[e]>=this._level}_formatMessage(e,t,r={}){let n=new Date().toISOString(),o=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(o+=Pe.dim(` ${JSON.stringify(r)}`)),o}_getPrefix(e){return{debug:Pe.gray("[DEBUG]"),info:Pe.cyan("[INFO]"),warn:Pe.yellow("[WARN]"),error:Pe.red("\u274C [ERROR]")}[e]||""}debug(e,t){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,t))}info(e,t){this._shouldLog("info")&&console.log(this._formatMessage("info",e,t))}warn(e,t){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,t))}error(e,t){this._shouldLog("error")&&console.error(this._formatMessage("error",e,t))}setLevel(e){e in J&&(this._level=J[e])}getLevel(){return Object.keys(J).find(e=>J[e]===this._level)}},m=new Ke;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"},rn={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error",SILENT:"silent"},ct={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"},ut={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"},Gt={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},Je={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var H=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
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 o=this.extractText(s);if(o){if(this.rawText&&o.startsWith(this.rawText)){let l=o.substring(this.rawText.length);this.rawText=o,r+=l}else(!this.rawText.includes(o)||o.length<20)&&(this.rawText+=o,r+=o);this.tryExtractResult(this.rawText)}else this.isValidResult(s)&&(this.rawText+=`${n}
|
|
3
3
|
`,r+=`${n}
|
|
4
|
-
`,this.extractedResult=s)}catch{if(n.includes('"text"')||n.includes('"content"')){let o=n.match(/"text"\s*:\s*"([^"]*)/),l=n.match(/"content"\s*:\s*"([^"]*)/),c=o?o[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=(o,l)=>{if(!o)return;let c=`${o}:${JSON.stringify(l??{})}`;this._lastToolEmit!==c&&(this._lastToolEmit=c,this.onToolCall(o,l??void 0))},r=o=>{if(o!=null){if(typeof o=="object"&&!Array.isArray(o))return o;if(typeof o=="string")try{return JSON.parse(o)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,r(e.input??e.arguments));return}let o=e.tool_call;if(o&&typeof o=="object"&&!Array.isArray(o)){let l=Object.keys(o);if(l.length===1){let c=l[0],a=o[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 o of e.tool_calls)t(o.name,r(o.input??o.arguments));return}let n=e.message??e;if(Array.isArray(n?.tool_calls)){for(let o of n.tool_calls)t(o.name,r(o.input??o.arguments));return}let s=n?.content??e.content;if(Array.isArray(s))for(let o of s)(o.type==="tool_use"||o.type==="tool_call")&&o.name&&t(o.name,r(o.input??o.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 f=n[1].trim();try{JSON.parse(f),t.push({text:f,source:"markdown"})}catch{}}let s=0,o=0;for(;s<e.length&&(s=e.indexOf("{",s),s!==-1);){let f=0,d=s;for(let p=s;p<e.length;p++)if(e[p]==="{")f++;else if(e[p]==="}"&&(f--,f===0)){d=p,t.push({text:e.substring(s,d+1),source:"brace"}),o++;break}s=d+1}let l=this.extractedResult,c=l?JSON.stringify(l).length:0,a=0,u=-1;for(let f=0;f<t.length;f++){let d=t[f];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=f)}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 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
|
|
4
|
+
`,this.extractedResult=s)}catch{if(n.includes('"text"')||n.includes('"content"')){let o=n.match(/"text"\s*:\s*"([^"]*)/),l=n.match(/"content"\s*:\s*"([^"]*)/),c=o?o[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=(o,l)=>{if(!o)return;let c=`${o}:${JSON.stringify(l??{})}`;this._lastToolEmit!==c&&(this._lastToolEmit=c,this.onToolCall(o,l??void 0))},r=o=>{if(o!=null){if(typeof o=="object"&&!Array.isArray(o))return o;if(typeof o=="string")try{return JSON.parse(o)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,r(e.input??e.arguments));return}let o=e.tool_call;if(o&&typeof o=="object"&&!Array.isArray(o)){let l=Object.keys(o);if(l.length===1){let c=l[0],a=o[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 o of e.tool_calls)t(o.name,r(o.input??o.arguments));return}let n=e.message??e;if(Array.isArray(n?.tool_calls)){for(let o of n.tool_calls)t(o.name,r(o.input??o.arguments));return}let s=n?.content??e.content;if(Array.isArray(s))for(let o of s)(o.type==="tool_use"||o.type==="tool_call")&&o.name&&t(o.name,r(o.input??o.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 f=n[1].trim();try{JSON.parse(f),t.push({text:f,source:"markdown"})}catch{}}let s=0,o=0;for(;s<e.length&&(s=e.indexOf("{",s),s!==-1);){let f=0,d=s;for(let p=s;p<e.length;p++)if(e[p]==="{")f++;else if(e[p]==="}"&&(f--,f===0)){d=p,t.push({text:e.substring(s,d+1),source:"brace"}),o++;break}s=d+1}let l=this.extractedResult,c=l?JSON.stringify(l).length:0,a=0,u=-1;for(let f=0;f<t.length;f++){let d=t[f];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=f)}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 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 nn}from"zod-to-json-schema";var Ye=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=nn(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
|
|
24
|
+
Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(e){if(!e)return{};let t=e.type;if(t==="object"&&e.properties){let r={};for(let[n,s]of Object.entries(e.properties))r[n]=this._buildExample(s);return r}if(t==="array"&&e.items)return[this._buildExample(e.items)];if(e.enum&&Array.isArray(e.enum)&&e.enum.length>0)return`<${e.enum.join("|")}>`;if(t==="string")return"<string>";if(t==="number"||t==="integer")return 0;if(t==="boolean")return!1;if(e.description)return`<${e.description}>`;if(e.nullable||e.oneOf||e.anyOf){let r=e.oneOf?.find(n=>n.type!=="null")||e.anyOf?.find(n=>n.type!=="null");return r?this._buildExample(r):null}return"<value>"}};var de=class 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=
|
|
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=Ye.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 i(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};import
|
|
34
|
+
`)}getStats(){let e=this.userPrompt.length,t=this.build().length;return{userPromptLength:e,fullPromptLength:t,systemInstructionsLength:t-e,instructionCount:this.systemInstructions.length,instructionTypes:this.systemInstructions.map(r=>r.type)}}clone(){let e=new i(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};import sn from"axios";import{homedir as on}from"node:os";import{join as an}from"node:path";import{existsSync as ln,readFileSync as cn}from"node:fs";import{toJSONSchema as un}from"zod";function pn(){if(process.env.OPENAI_PROXY_TOKEN)return m.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return m.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let i=an(on(),".zibby","config.json");if(ln(i)){let e=JSON.parse(cn(i,"utf-8"));if(e.sessionToken)return m.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(i){m.debug(`[Auth] Could not read zibby login session: ${i.message}`)}return null}function fn(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function me(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(me)}else"additionalProperties"in i||(i.additionalProperties=!0);i.type==="array"&&i.items&&me(i.items),i.anyOf&&i.anyOf.forEach(me),i.oneOf&&i.oneOf.forEach(me),i.allOf&&i.allOf.forEach(me)}}async function zt(i,e){m.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=pn();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=fn();m.info(`\u{1F517} Using OpenAI proxy: ${r}`);let n=un(e),s=n;if(n.$ref&&n.definitions){let u=n.$ref.split("/").pop();s=n.definitions[u]||n,m.debug(`Extracted schema from $ref: ${u}`)}delete s.$schema,me(s);let o=4e5,l=i;i.length>o&&(m.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${i.length} chars) exceeds limit, keeping last ${o} chars`),l=`... [truncated early content] ...
|
|
35
35
|
${i.slice(-o)}`);let c=`Extract and format the following information into structured JSON matching the schema.
|
|
36
36
|
|
|
37
37
|
RAW CONTENT:
|
|
38
38
|
${l}
|
|
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:
|
|
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}}};m.info(`\u{1F4E4} Sending to OpenAI proxy: model=${j.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(s.properties||{}).join(", ")}`),m.debug(` Schema size: ${JSON.stringify(s).length} chars`),m.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 sn.post(r,a,{headers:u,timeout:Je.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!d)throw new Error("OpenAI proxy returned empty response");let p=JSON.parse(d);return m.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:p,raw:i}}catch(u){if(u.response){let f=u.response.status,d=u.response.data;throw m.error(`\u274C OpenAI proxy request failed: ${f}`),m.error(` Status: ${f}`),m.error(` Response: ${JSON.stringify(d,null,2)}`),f===401||f===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 m.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}import{timeline as
|
|
42
|
+
Response: ${JSON.stringify(d)}`,{cause:u}):new Error(`Failed to format Cursor output: ${d?.error?.message||"Unknown error"}`,{cause:u})}throw m.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}function z(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(o=>o.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[i];return process.env[i]=n,m.debug(`[auth-pool] ${i}: picked 1 of ${r.length} from pool (***${n.slice(-4)})`),{picked:n,count:r.length,dispose(){s===void 0?delete process.env[i]:process.env[i]=s}}}import{timeline as Z,Timeline as Oi,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as Ci}from"@zibby/agent-workflow";import{copyFileSync as dn,existsSync as pt,lstatSync as mn,mkdirSync as Kt,rmSync as gn,symlinkSync as hn,unlinkSync as yn}from"node:fs";import{join as W}from"node:path";import{homedir as Sn}from"node:os";import{randomBytes as bn}from"node:crypto";var wn=["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 Yt(i){let e=W(i||process.cwd(),".zibby","tmp");Kt(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${bn(4).toString("hex")}`,r=W(e,`cursor-agent-home-${t}`),n=W(r,".cursor");Kt(n,{recursive:!0});let s=Sn(),o=W(s,".cursor");if(pt(o))for(let l of wn){let c=W(o,l);if(pt(c))try{dn(c,W(n,l))}catch{}}if(process.platform==="darwin"){let l=W(s,"Library");if(pt(l))try{hn(l,W(r,"Library"))}catch{}}return r}function Ht(i){if(!(!i||typeof i!="string"))try{let e=W(i,"Library");try{mn(e).isSymbolicLink()&&yn(e)}catch{}gn(i,{recursive:!0,force:!0})}catch{}}var te=class extends xn{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[Y(Ce(),".local","bin","cursor-agent"),Y(Ce(),".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("/")){Vt(r,Qt.X_OK);let n=ee(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(n&&n.length>0)return m.debug(`[Cursor] Found agent at: ${r} (version: ${n.trim().slice(0,50)})`),!0}else{let n=ee(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!n)continue;let s=ee(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return m.debug(`[Cursor] Found '${r}' in PATH at ${n} (version: ${s.trim().slice(0,50)})`),!0}}catch{continue}return m.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:o=null,sessionPath:l=null,nodeName:c=null,timeout:a=Je.CURSOR_AGENT_DEFAULT,config:u={},signal:f=null}=t,d=u?.agent?.strictMode||!1,p=t.model??u?.agent?.cursor?.model??j.CURSOR,g=z("CURSOR_API_KEY");try{m.debug(`[Cursor] Invoking (model: ${p}, timeout: ${a/1e3}s, skills: ${JSON.stringify(o)})`);let h=(this._setupMcpConfig(l,r,u,o,c)||{}).isolatedMcpHome??null,S=[Y(Ce(),".local","bin","cursor-agent"),Y(Ce(),".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 T of S)try{if(T.startsWith("/"))Vt(T,Qt.X_OK),ee(`"${T}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!ee(`which ${T}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");ee(`${T} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}w=T,m.debug(`[Agent] Using binary: ${T}`);break}catch(x){m.debug(`[Agent] Binary '${T}' check failed: ${x.message}`);continue}if(!w)throw new Error(`Cursor Agent CLI not found or not working.
|
|
43
43
|
|
|
44
44
|
Checked paths:
|
|
45
|
-
${
|
|
45
|
+
${S.map(T=>` - ${T}`).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
Install cursor-agent:
|
|
@@ -51,59 +51,59 @@ 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
|
|
55
|
-
\u25C6 Model: ${p||"auto"}${
|
|
56
|
-
`);let
|
|
57
|
-
${
|
|
58
|
-
`)}catch{}let
|
|
54
|
+
Test with: agent --version`);let v=new de(e),b=null;if(s){let T=`zibby-result-${Date.now()}.json`;b=Y(r,".zibby","tmp",T);let x=Y(r,".zibby","tmp");Oe(x)||qt(x,{recursive:!0}),v.addStructuredOutput(s,b)}let A=process.env.CURSOR_API_KEY,P=A?` | key: ***${A.slice(-4)}`:" | key: not set";console.log(`
|
|
55
|
+
\u25C6 Model: ${p||"auto"}${P}
|
|
56
|
+
`);let C=(await import("chalk")).default,I=v.getUserPrompt();console.log(`
|
|
57
|
+
${C.bold("Prompt sent to LLM:")}`),console.log(C.dim("\u2500".repeat(60))),console.log(C.dim(I)),console.log(C.dim("\u2500".repeat(60)));let R=v.build(),D=v.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(R),m.debug(`[Agent] User prompt: ${D.userPromptLength} chars, System instructions: ${D.systemInstructionsLength} chars (${D.instructionCount} blocks), Full: ${D.fullPromptLength} chars, model: ${p||"auto"}`),m.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 N,_=null;try{let T=l||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);N=await this._spawnWithStreaming(w,E,r,a,null,T,h,f)}catch(T){_=T}let O=N?.stdout||"";if(s){let T=typeof s.parse=="function",x=null,M=!!(b&&Oe(b));if(b&&m.info(`[Agent] Result file: ${M?"present":"missing"} at ${b}`),M)try{let $=Xt(b,"utf-8").trim();x=JSON.parse($),m.info(`[Agent] Parsed JSON from result file OK (${$.length} chars) \u2192 object ready for validation`),_&&m.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch($){m.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${$.message}`)}else if(_)m.warn(`[Agent] Result file missing at ${b} (agent process error \u2014 may still recover if strictMode repairs)`);else throw m.error(`\u274C [Agent] Result file was never created at ${b}`),new Error(`Agent did not write required result file at ${b}`);if(x&&T)try{let $=s.parse(x);return m.info("\u2705 [Agent] Zod validation passed for structured result file"),d&&m.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:O,structured:$}}catch($){let B=$.issues?$.issues.map(L=>` - ${L.path.join(".")}: ${L.message}`).join(`
|
|
59
59
|
`):$.message?.slice(0,400);if(m.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
|
|
60
|
-
${
|
|
61
|
-
${JSON.stringify(
|
|
62
|
-
${
|
|
60
|
+
${B}`),m.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
|
+
${B}
|
|
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:$})}else{if(
|
|
66
|
-
`),r=null;for(let n of t){let s=n.trim();if(s)try{let o=JSON.parse(s);if(o.type==="assistant"&&o.message?.content){let l=o.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 o=r?.headless,l=
|
|
67
|
-
`;if(
|
|
68
|
-
`)){let
|
|
69
|
-
${d.slice(-2e3)}`),
|
|
70
|
-
`).filter(B=>B.trim());y
|
|
71
|
-
`).filter(
|
|
65
|
+
Enable strictMode in .zibby.config.js for automatic repair.`,{cause:$})}else{if(x)return m.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),d&&m.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:O,structured:x};M&&m.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(d&&!_){let $=N.parsedText,B=x?JSON.stringify(x):$;m.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${B.length} chars in)`);try{let L=await zt(B,s);if(T){let F=s.parse(L.structured);return m.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:O,structured:F}}return{raw:O,...L}}catch(L){if(m.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${L.message}`),x)return m.warn("[Agent] Using agent's original result file as fallback"),{raw:O,structured:x}}}if(_)throw _;let U=M?x==null?"file existed but JSON.parse failed \u2014 see WARN log above":T?"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 m.error(`\u274C [Agent] No validated structured output: ${U}`),m.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(O)||N?.parsedText||O}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 o=JSON.parse(s);if(o.type==="assistant"&&o.message?.content){let l=o.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 o=r?.headless,l=Y(Ce(),".cursor"),c=Y(l,"mcp.json"),a={};if(Oe(c))try{a=JSON.parse(Xt(c,"utf-8"))}catch{}let u=a.mcpServers||{},f=r?.paths?.output||_n,d=Y(t||process.cwd(),f,En),p=Array.isArray(n)?n.map(h=>Zt(h)).filter(Boolean):[...vn()].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,o)));if(e){let h=Zt("browser");h&&typeof h.resolve=="function"&&!g.has(h.serverName)&&this._ensureSkillConfigured(u,h,e,d,"execute_live",o)}if(Object.keys(u).length===0)return m.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=Yt(t||process.cwd()),S=Y(h,".cursor","mcp.json");return Wt(S,y,"utf8"),m.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${h} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:h}}return Oe(l)||qt(l,{recursive:!0}),Wt(c,y,"utf8"),m.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,n,s=null,o){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:o}):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 f=u?.env||{},d=t.sessionEnvKey?{[t.sessionEnvKey]:n}:{};e[c].env={...e[c].env||{},...f,...d},m.debug(`[MCP] Updated ${c} session \u2192 ${r}`);return}if(c)return;let a=t.resolve({sessionPath:r,nodeName:s,headless:o});a&&(e[l]={...a,...t.sessionEnvKey&&{env:{...a.env||{},[t.sessionEnvKey]:n}}},m.debug(`[MCP] Configured ${l}`))}_spawnWithStreaming(e,t,r,n,s=null,o=null,l=null,c=null){return new Promise((a,u)=>{let f=Date.now(),d="",p="",g=Date.now(),y=0,h=!1,S=null,w=!1,v=!1,b=null;if(o)try{b=Y($n(String(o)),Tn)}catch{b=null}let A=!1,P=()=>{A||(A=!0,Ht(l))},C={...process.env};l&&(C.HOME=l,process.platform==="win32"&&(C.USERPROFILE=l),m.debug(`[Agent] cursor-agent HOME=${l} (isolated MCP config)`));let I=In(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:C,...c&&{signal:c}});m.debug(`[Agent] PID: ${I.pid}`);let R=null,D=()=>{h||v||(h=!0,S="aborted",m.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),R=setTimeout(()=>{if(!v){m.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{I.kill("SIGKILL")}catch{}}},5e3))};c&&(c.aborted?D():c.addEventListener("abort",D,{once:!0})),I.stdin.on("error",x=>{x.code!=="EPIPE"&&m.warn(`[Agent] stdin error: ${x.message}`)}),I.stdout.on("error",x=>{x.code!=="EPIPE"&&m.warn(`[Agent] stdout error: ${x.message}`)}),I.stderr.on("error",x=>{x.code!=="EPIPE"&&m.warn(`[Agent] stderr error: ${x.message}`)}),s?(I.stdin.write(s,x=>{x&&x.code!=="EPIPE"&&m.warn(`[Agent] Failed to write to stdin: ${x.message}`),I.stdin.end()}),m.debug(`[Agent] Prompt also piped to stdin (${s.length} chars)`)):I.stdin.end();let E=null;b&&(E=setInterval(()=>{if(!(h||v))try{if(Oe(b)){h=!0,S="aborted";try{An(b)}catch{}m.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),I.kill("SIGTERM"),setTimeout(()=>{I.killed||I.kill("SIGKILL")},2e3)}}catch{}},600));let N=new Set,_=new Date(f).toISOString().replace(/\.\d+Z$/,""),O=setInterval(()=>{let x=Math.round((Date.now()-f)/1e3),M=Math.round((Date.now()-g)/1e3),U=[];try{let B=Math.ceil(x/60)+1,L=ee(`find "${r}" -type f -mmin -${B} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(L)for(let F of L.split(`
|
|
68
|
+
`)){let Q=F.replace(`${r}/`,"");N.has(Q)||(N.add(Q),U.push(Q))}}catch{}let $="";U.length>0&&($=` | \u{1F4C1} new: ${U.map(L=>L.split("/").pop()).join(", ")}`),N.size>0&&($+=` | \u{1F4E6} total: ${N.size} files`),m.debug(`\u{1F493} [Agent] Running for ${x}s | ${y} lines output${$}`),y===0&&x>=30&&N.size===0&&(x<35&&m.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",m.error(`\u274C [Agent] No response after ${x}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),I.kill("SIGTERM"),setTimeout(()=>{I.killed||I.kill("SIGKILL")},3e3)))},3e4),k=setTimeout(()=>{h=!0,S=S||"timeout";let x=Math.round((Date.now()-f)/1e3);m.error(`\u23F1\uFE0F [Agent] Timeout after ${x}s \u2014 killing process (PID: ${I.pid})`),d.trim()&&m.warn(`\u{1F4E4} [Agent] Partial output (${d.length} chars) before timeout:
|
|
69
|
+
${d.slice(-2e3)}`),I.kill("SIGTERM"),setTimeout(()=>{I.killed||I.kill("SIGKILL")},5e3)},n),T=new H;T.onToolCall=(x,M)=>{let U=x,$=M;if(x==="mcpToolCall"&&M?.name)U=M.name.replace(/^mcp_+[^_]+_+/,""),U.includes("-")&&U.split("-")[0]===U.split("-")[1]&&(U=U.split("-")[0]),$=M.args??M.input??M;else{if(x==="readToolCall"||x==="editToolCall"||x==="writeToolCall")return;(x.startsWith("mcp__")||x.includes("ToolCall"))&&(U=x.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(U.includes("memory")?Z.stepMemory(`Tool: ${U}`):Z.stepTool(`Tool: ${U}`),$!=null&&typeof $=="object"&&Object.keys($).length>0&&!v){let L=JSON.stringify($),F=L.length>100?`${L.substring(0,100)}...`:L;console.log(` Input: ${F}`)}},I.stdout.on("data",x=>{let M=x.toString();d+=M,g=Date.now(),w||(w=!0);let U=T.processChunk(M);U&&!v&&process.stdout.write(U);let $=M.split(`
|
|
70
|
+
`).filter(B=>B.trim());y+=$.length}),I.stderr.on("data",x=>{let M=x.toString();p+=M,g=Date.now(),w||(w=!0);let U=M.split(`
|
|
71
|
+
`).filter($=>$.trim());for(let $ of U)m.warn(`\u26A0\uFE0F [Agent stderr] ${$}`)}),I.on("close",(x,M)=>{if(v=!0,P(),clearTimeout(k),clearInterval(O),E&&clearInterval(E),R&&clearTimeout(R),c&&!c.aborted)try{c.removeEventListener("abort",D)}catch{}T.flush();let U=Math.round((Date.now()-f)/1e3);if(m.debug(`[Agent] Exited: code=${x}, signal=${M}, elapsed=${U}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 ${U}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(
|
|
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
74
|
Stderr: ${p.slice(-1e3)}`:""}${d.trim()?`
|
|
75
|
-
Stdout (last 500 chars): ${d.slice(-500)}`:""}`));return}let
|
|
75
|
+
Stdout (last 500 chars): ${d.slice(-500)}`:""}`));return}let $=T.getResult(),B=$?JSON.stringify($,null,2):T.getRawText()||d||"";a({stdout:d||p||"",parsedText:B})}),I.on("error",x=>{if(P(),clearTimeout(k),clearInterval(O),E&&clearInterval(E),R&&clearTimeout(R),c&&!c.aborted)try{c.removeEventListener("abort",D)}catch{}u(new Error(`Cursor Agent spawn error: ${x.message}
|
|
76
76
|
Binary: ${e}
|
|
77
77
|
This usually means the binary is not in PATH. Try:
|
|
78
|
-
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};import{AgentStrategy as
|
|
79
|
-
\u25C6 Model: ${g}${
|
|
80
|
-
`);let
|
|
81
|
-
${
|
|
82
|
-
\u25C6 Model: ${
|
|
83
|
-
`);let
|
|
84
|
-
${
|
|
85
|
-
${$}`,"schema_instruction","append");let
|
|
86
|
-
${$}`,"json_instruction","append")}let
|
|
87
|
-
\u25C6 Model: ${
|
|
88
|
-
`);let
|
|
89
|
-
${
|
|
90
|
-
${
|
|
91
|
-
${
|
|
92
|
-
`,"utf-8");let u=
|
|
93
|
-
`,"utf-8")}catch{}return m.debug(`[Gemini] Created isolated config with ${Object.keys(a.mcpServers||{}).length} MCP servers`),m.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(a.mcpServers||{}),null,2)}`),n}};import{AgentStrategy as
|
|
94
|
-
|
|
95
|
-
[truncated for size budget]`}function
|
|
96
|
-
`);p=w.pop();for(let
|
|
97
|
-
`)||"",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){m.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
|
|
98
|
-
|
|
99
|
-
[tool result truncated for size]`}function
|
|
78
|
+
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};import{AgentStrategy as Pn,getSkill as On}from"@zibby/agent-workflow";import{query as Cn}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as Rn}from"zod-to-json-schema";var re=class extends Pn{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||m.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:o=[],skills:l=null,sessionPath:c=null,nodeName:a=null,timeout:u,config:f={},signal:d=null}=t,p=r;(!p||p==="auto")&&(m.debug(`Model is '${p||"undefined"}', using default: ${j.CLAUDE}`),p=j.CLAUDE);let g=ct[p]||p;ct[p]&&p!==g&&m.debug(`Mapped model: ${p} \u2192 ${g}`);let y=[z("ANTHROPIC_API_KEY"),z("CLAUDE_CODE_OAUTH_TOKEN"),z("ANTHROPIC_AUTH_TOKEN")];try{m.debug(`Invoking Claude Agent SDK with model: ${g}, skills: ${JSON.stringify(l)}`);let h=process.env.ANTHROPIC_API_KEY,S=h?` | key: ***${h.slice(-4)}`:" | key: not set";console.log(`
|
|
79
|
+
\u25C6 Model: ${g}${S}
|
|
80
|
+
`);let w=(await import("chalk")).default;console.log(`
|
|
81
|
+
${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{allowedTools:v,mcpServers:b}=this._resolveSkills(l,{sessionPath:c,workspace:n,nodeName:a});try{let A={cwd:n,allowedTools:v,permissionMode:"bypassPermissions",model:g,...Object.keys(b).length>0&&{mcpServers:b}};if(s){let O=typeof s.parse=="function"?Rn(s,{target:"openApi3"}):s;A.outputFormat={type:"json_schema",schema:O},m.debug("Structured output enforced via SDK outputFormat")}m.debug(`Agent SDK options: ${JSON.stringify({cwd:A.cwd,toolCount:v.length,permissionMode:A.permissionMode,model:A.model,hasOutputFormat:!!A.outputFormat})}`);let P="",C=0,I=[];m.debug("Starting Claude Agent SDK query stream");let R;try{R=Cn({prompt:e,options:A})}catch(_){throw m.error(`Failed to initialize Claude Agent SDK: ${_.message}`),_}let D=null,E=0,N=3;if(d?.aborted){let _=new Error("Aborted via signal");throw _.name="AbortError",_}try{for await(let _ of R){if(d?.aborted){let k=new Error("Aborted via signal");throw k.name="AbortError",k}if(I.push(_),_.type==="error"||_.error){let k=_.error?.message||_.error||_.message||"Unknown API error";throw new Error(typeof k=="string"?k:JSON.stringify(k))}let O=JSON.stringify(_.message?.content||_.text||"").slice(0,200);if(O===D){if(E++,E>=N){let k=(_.message?.content?.[0]?.text||_.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${E}x repeated): ${k}`)}}else D=O,E=1;if(_.type==="assistant"||_.constructor?.name==="AssistantMessage"){let k=_.message?.content||_.content||[];for(let T of k)if(T.type==="thinking"&&T.thinking)console.log(`${T.thinking.substring(0,200)}${T.thinking.length>200?"...":""}`);else if(T.type==="text"&&T.text)P+=T.text,T.text.length<500?console.log(`${T.text}`):console.log(`${T.text.substring(0,200)}... (${T.text.length} chars)`);else if(T.type==="tool_use"){C++,T.name.includes("memory")?Z.stepMemory(`Tool: ${T.name}`):Z.stepTool(`Tool: ${T.name}`);let M=JSON.stringify(T.input).substring(0,100);console.log(` Input: ${M}${JSON.stringify(T.input).length>100?"...":""}`)}}else if(!(_.type==="user"&&_.tool_use_result)){if(_.type==="result"||_.constructor?.name==="ResultMessage"){let k=_.result||_.text||_.content||P;if(s){if(_.structured_output){m.debug("Using SDK native structured_output");let x=typeof s.parse=="function"?s.parse(_.structured_output):_.structured_output;return{raw:k,structured:x}}if(k){let T=this._extractJson(k,s);if(T)return{raw:k,structured:T}}m.warn(`Could not extract structured output \u2014 returning raw text (${(k||"").length} chars)`)}return k||""}}}if(m.warn(`Agent SDK ended without result. Collected ${I.length} messages`),P.length>0)return m.debug("Returning accumulated text from messages"),P;throw new Error("Claude Agent SDK query ended without result")}catch(_){throw m.error(`Error during query stream: ${_.message}`),_}}catch(A){throw m.error("Claude Agent SDK call failed",{error:A.message}),A}}finally{for(let h of y)h.dispose()}}_resolveSkills(e,t){if(e===null)return m.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return m.debug("Default IDE skills for code generation"),{allowedTools:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};let r=[],n={};for(let s of e){let o=On(s);if(!o){m.warn(`Unknown skill "${s}" \u2014 skipping`);continue}if(o.allowedTools&&r.push(...o.allowedTools),typeof o.resolve=="function"){let l=o.resolve(t);l&&(n[o.serverName]=l,m.debug(`MCP: ${o.serverName} \u2192 ${l.command} ${l.args[0]}`))}}return{allowedTools:r,mcpServers:n}}_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 o=JSON.parse(s);if(typeof o!="object"||o===null)continue;return typeof t.parse=="function"?t.parse(o):o}catch{}return null}};import{AgentStrategy as Nn,getSkill as kn}from"@zibby/agent-workflow";import{execSync as Mn}from"node:child_process";import{zodToJsonSchema as Ln}from"zod-to-json-schema";var ne=class extends Nn{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 m.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return Mn("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return m.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:o=null,sessionPath:l=null,nodeName:c=null,timeout:a,config:u={},signal:f=null}=t,d=[z("OPENAI_API_KEY"),z("CODEX_API_KEY")];try{let{Codex:p}=await import("@openai/codex-sdk"),g=r;(!g||g==="auto")&&(m.debug(`Model is '${g||"undefined"}', using default: ${j.CODEX}`),g=j.CODEX);let y=ut[g]||g;ut[g]&&g!==y&&m.debug(`Mapped model: ${g} \u2192 ${y}`),m.debug(`Invoking Codex SDK with model: ${y}, skills: ${JSON.stringify(o)}`);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(`
|
|
82
|
+
\u25C6 Model: ${y}${S}
|
|
83
|
+
`);let w=(await import("chalk")).default;console.log(`
|
|
84
|
+
${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 v=this._resolveSkillsToMcp(o,{sessionPath:l,workspace:n,nodeName:c}),b={};Object.keys(v).length>0&&(b.mcp_servers=v,m.debug(`[Codex] MCP servers: ${Object.keys(v).join(", ")}`));let P=new p({...Object.keys(b).length>0&&{config:b}}).startThread({workingDirectory:n,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),C=s&&typeof s.parse=="function",I={};if(s)try{let R=C?Ln(s,{target:"openAi"}):s;I.outputSchema=R,m.debug("Structured output via SDK outputSchema")}catch(R){m.warn(`[Codex] Schema conversion failed, will extract from text: ${R.message}`)}if(f?.aborted){let R=new Error("Aborted via signal");throw R.name="AbortError",R}try{let{events:R}=await P.runStreamed(e,I),D=0,E="";for await(let N of R){if(f?.aborted){let O=new Error("Aborted via signal");throw O.name="AbortError",O}let _=N.type;if(_==="item.completed"){let O=N.item,k=O?.type;if(k==="mcp_tool_call"){D++;let T=`${O.server}/${O.tool}`;if(Z.stepTool(`Tool: ${T}`),O.arguments){let x=JSON.stringify(O.arguments),M=x.length>100?`${x.substring(0,100)}...`:x;console.log(` Input: ${M}`)}}else if(k==="tool_call"||k==="function_call"||k==="command_execution"){D++;let T=O.name||O.tool||O.command||"unknown";Z.stepTool(`Tool: ${T}`)}else k==="agent_message"&&(E=O.text||"",E.length<500?console.log(E):console.log(`${E.substring(0,200)}... (${E.length} chars)`))}else _==="turn.completed"?m.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(N.usage||{})}`):m.debug(`[Codex] Event: ${_} ${JSON.stringify(N).slice(0,300)}`)}if(m.debug(`[Codex] Last agent message (${E.length} chars): ${E.slice(0,500)}`),s){if(!E)throw new Error("Codex agent returned no response");let N=JSON.parse(E),_=C?s.parse(N):N;return m.debug("\u2705 [Codex] Structured output validated"),{raw:E,structured:_}}return E||""}catch(R){let D=R.message||String(R);throw m.error(`\u274C [Codex] SDK call failed: ${D}`),D.includes("exited with code")&&(m.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),m.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),R}}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=kn(n);if(!s){m.warn(`[Codex] Unknown skill "${n}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let o=s.resolve(t);if(!o)continue;let l=s.serverName||n,c={command:o.command};o.args?.length&&(c.args=o.args),o.env&&Object.keys(o.env).length>0&&(c.env=o.env),r[l]=c,m.debug(`[Codex] MCP: ${l} \u2192 ${o.command} ${(o.args||[]).join(" ")}`)}return r}};import{AgentStrategy as Dn,getSkill as Un}from"@zibby/agent-workflow";import{execSync as Bn,spawn as Fn}from"node:child_process";import{zodToJsonSchema as jn}from"zod-to-json-schema";import{existsSync as er,mkdirSync as tr,readFileSync as rr,rmSync as Gn,writeFileSync as nr}from"node:fs";import{join as se}from"node:path";function zn(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,s=!1,o=!1,l=-1;for(let c=r;c<e.length;c++){let a=e[c];if(s){o?o=!1:a==="\\"?o=!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 Kn(i){let e=String(i||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return zn(e)}}function Jn(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 oe=class extends Dn{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 m.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return Bn("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return m.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:o=null,sessionPath:l=null,nodeName:c=null,timeout:a=600*1e3,signal:u=null}=t,f=[z("GEMINI_API_KEY"),z("GOOGLE_API_KEY")];try{let d=r;(!d||d==="auto")&&(d=j.GEMINI);let p=Gt[d]||d,g=String(process.env.GEMINI_API_KEY||"").trim(),y=String(process.env.GOOGLE_API_KEY||"").trim(),h=this._resolveSkillsToMcp(o,{sessionPath:l,workspace:n,nodeName:c}),S=Object.keys(h).length>0,w=new de(e),v=s&&typeof s.parse=="function",b=null;if(s){let $;try{let B=v?jn(s,{target:"openAi"}):s;$=JSON.stringify(B,null,2)}catch{$="{}"}if(S){w.addSystemInstruction(`Write valid JSON that matches this schema:
|
|
85
|
+
${$}`,"schema_instruction","append");let B=`zibby-result-${Date.now()}.json`,L=se(n,".zibby","tmp");b=se(L,B),tr(L,{recursive:!0}),w.addStructuredOutput(s,b)}else w.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
|
|
86
|
+
${$}`,"json_instruction","append")}let A=w.build(),P=w.getUserPrompt(),C=w.getStats(),I=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),R=I?` | key: ***${I.slice(-4)}`:" | key: not set";console.log(`
|
|
87
|
+
\u25C6 Model: ${p||"auto"}${R}
|
|
88
|
+
`);let D=(await import("chalk")).default;console.log(`
|
|
89
|
+
${D.bold("Prompt sent to LLM:")}`),console.log(D.dim("\u2500".repeat(60))),console.log(D.dim(P)),console.log(D.dim("\u2500".repeat(60)));let E=this._createGeminiConfigDir(n,h),N=["--output-format","json"];p&&p!=="auto"&&N.push("--model",p);let _=Object.keys(h);if(_.length>0){N.push("--approval-mode","yolo");for(let $ of _)N.push("--allowed-mcp-server-names",$);m.info(`[Gemini] Enabling MCP servers: ${_.join(", ")}`)}else o&&o.length>0&&m.warn(`[Gemini] Skills requested but no MCP servers configured: ${o.join(", ")}`);N.push("-p",A);let O={...process.env,GEMINI_CLI_HOME:E};g?(O.GEMINI_API_KEY=g,delete O.GOOGLE_API_KEY):y&&(O.GOOGLE_API_KEY=y,delete O.GEMINI_API_KEY),m.debug(`[Gemini] Command: gemini ${N.slice(0,8).join(" ")}... (${N.length} total args)`),m.debug(`[Gemini] User prompt: ${C.userPromptLength} chars, System instructions: ${C.systemInstructionsLength} chars (${C.instructionCount} blocks), Full: ${C.fullPromptLength} chars`),m.debug(`[Gemini] Config home: ${E}`),m.debug(`[Gemini] GEMINI_CLI_HOME env: ${O.GEMINI_CLI_HOME}`);let k="",T=null;try{k=await new Promise((B,L)=>{let F=Fn("gemini",N,{cwd:n,env:O,stdio:["ignore","pipe","pipe"],...u&&{signal:u}}),Q="",Bt="",at=!1,$e=null,lt=!1,Ft=setTimeout(()=>{try{F.kill("SIGTERM")}catch{}},a),ze=()=>{lt||at||(lt=!0,$e=setTimeout(()=>{if(!at)try{F.kill("SIGKILL")}catch{}},5e3))};u&&(u.aborted?ze():u.addEventListener("abort",ze,{once:!0})),F.stdout.on("data",X=>{Q+=X.toString()}),F.stderr.on("data",X=>{Bt+=X.toString()}),F.on("error",X=>{if(clearTimeout(Ft),$e&&clearTimeout($e),u&&!u.aborted)try{u.removeEventListener("abort",ze)}catch{}L(X)}),F.on("close",X=>{if(at=!0,clearTimeout(Ft),$e&&clearTimeout($e),u&&!u.aborted)try{u.removeEventListener("abort",ze)}catch{}if(lt){let jt=new Error("Aborted via signal");return jt.name="AbortError",L(jt)}if(X===0)return B(Q.trim());L(new Error(`gemini failed with code ${X}: ${(Bt||Q).trim()}`))})})}catch($){T=$}finally{try{Gn(E,{recursive:!0,force:!0})}catch{}}let x=Jn(k).trim();if(!s){if(T)throw T;return x}if(b){let $=er(b);if(m.info(`[Gemini] Result file: ${$?"present":"missing"} at ${b}`),$)try{let B=rr(b,"utf-8").trim(),L=JSON.parse(B),F=v?s.parse(L):L;return m.info("[Gemini] Structured output recovered from result file"),{raw:x,structured:F}}catch(B){m.warn(`[Gemini] Result file parse/validation failed: ${B.message}`)}else T||m.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let M=null;if(s){let $=new H;$.zodSchema=s,$.processChunk(x),$.flush(),M=$.getResult()}if(m.info(`[Gemini] Raw stdout length: ${k.length} chars`),m.info(`[Gemini] Extracted text length: ${x.length} chars`),m.info(`[Gemini] StreamParser result: ${M?"extracted":"null"}`),M||(x.length<2e3?m.info(`[Gemini] Raw text preview:
|
|
90
|
+
${x}`):m.info(`[Gemini] Raw text preview (first 1000 chars):
|
|
91
|
+
${x.slice(0,1e3)}`),M=Kn(x)),!M)throw T||(m.error("[Gemini] Failed to extract valid JSON from output"),m.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 U=v?s.parse(M):M;return{raw:x,structured:U}}finally{for(let d of f)d.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let s=Un(n);if(!s||typeof s.resolve!="function")continue;let o=s.resolve(t);if(!o)continue;let l=s.cursorKey||s.serverName||n,c={command:o.command};o.args?.length&&(c.args=o.args),o.env&&Object.keys(o.env).length>0&&(c.env=o.env),o.cwd&&(c.cwd=o.cwd),r[l]=c}return r}_createGeminiConfigDir(e,t){let r=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,n=se(e||process.cwd(),".zibby","tmp",`gemini-home-${r}`),s=se(n,".gemini");tr(s,{recursive:!0});let o=se(s,"settings.json"),l={},c=se(process.env.HOME||"",".gemini","settings.json");if(er(c))try{l=JSON.parse(rr(c,"utf-8"))}catch{l={}}let a={...l,mcpServers:{...l.mcpServers&&typeof l.mcpServers=="object"?l.mcpServers:{},...t||{}}};nr(o,`${JSON.stringify(a,null,2)}
|
|
92
|
+
`,"utf-8");let u=se(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{nr(u,`${JSON.stringify(a,null,2)}
|
|
93
|
+
`,"utf-8")}catch{}return m.debug(`[Gemini] Created isolated config with ${Object.keys(a.mcpServers||{}).length} MCP servers`),m.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(a.mcpServers||{}),null,2)}`),n}};import{AgentStrategy as ss,getSkill as qe}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 ie=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 He(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)}
|
|
94
|
+
|
|
95
|
+
[truncated for size budget]`}function ft(i,e=0){if(!i||typeof i!="object"||e>8)return i;if(Array.isArray(i))return i.map(r=>ft(r,e+1));let t={};for(let[r,n]of Object.entries(i))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=ft(n,e+1));return t}function Yn(i=[]){return i.map(e=>({...e,function:{...e.function,description:Ze(e.function?.description||"",180),parameters:ft(e.function?.parameters||{type:"object",properties:{}})}}))}function sr(i){let e=new Set;for(let n of i)if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let s of n.tool_calls)e.add(s.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(c=>r.has(c.id)))return n;let{tool_calls:o,...l}=n;return{...l,content:l.content||""}})}function dt(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)?Yn(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 s=!1;for(;He(n)>t&&n.messages.length>2;)n.messages.splice(1,1),s=!0;if(s&&(n.messages=sr(n.messages)),He(n)>t&&n.messages.length>0&&(n.messages[0]={...n.messages[0],content:Ze(n.messages[0].content,6e3)},s=!0),He(n)>t){let o=n.messages.find(c=>c.role==="system")||n.messages[0],l=n.messages.slice(-2);n.messages=sr([o,...l].filter(Boolean).map((c,a)=>({...c,content:Ze(c.content,a===0?4e3:8e3)}))),s=!0}return{body:n,meta:{bytes:He(n),trimmed:s,maxBytes:t,messageCount:n.messages.length}}}var or=i=>Buffer.byteLength(JSON.stringify(i),"utf8"),he=class extends Re{async fetchCompletion(e,t,r={}){let n=or(e),{body:s,meta:o}=dt(e,r.payloadCompaction);r.onBudget?.({streaming:!1,beforeBytes:n,meta:o});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=or(n),{body:o,meta:l}=dt(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(o),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 f=u.body.getReader(),d=new TextDecoder,p="",g="",y=new Map;for(;;){let{done:h,value:S}=await f.read();if(h)break;p+=d.decode(S,{stream:!0});let w=p.split(`
|
|
96
|
+
`);p=w.pop();for(let v of w){if(!v.startsWith("data: "))continue;let b=v.slice(6).trim();if(b==="[DONE]")continue;let A;try{A=JSON.parse(b)}catch{continue}let P=A.choices?.[0]?.delta;if(P&&(P.content&&(g+=P.content,r.onToken&&r.onToken(P.content)),P.tool_calls))for(let C of P.tool_calls){let I=C.index??0;y.has(I)||y.set(I,{id:"",name:"",args:""});let R=y.get(I);C.id&&(R.id=C.id),C.function?.name&&(R.name=C.function.name),C.function?.arguments!=null&&(R.args+=C.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 Hn}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Zn}from"@modelcontextprotocol/sdk/client/stdio.js";var Ne=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;m.debug(`[MCP] Starting ${e}: ${r} ${n.join(" ")}`);let o=new Zn({command:r,args:n,env:{...process.env,...s}}),l=new Hn({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await l.connect(o);let c={client:l,transport:o,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`);m.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(`
|
|
97
|
+
`)||"",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){m.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 Wn,readFileSync as Xn}from"node:fs";import{join as qn}from"node:path";import{homedir as Vn}from"node:os";function Qn(){try{let i=qn(Vn(),".zibby","config.json");return Wn(i)?JSON.parse(Xn(i,"utf-8")):{}}catch{return{}}}function We(i){return String(i||"").replace(/\/v1\/?$/,"")}function es(i,e){let t=process.env.OPENAI_PROXY_URL;if(t)return We(t);if(i==="session")return e.proxyUrl?We(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 We(r||"https://api.openai.com")}return We(t||"")}function mt(){let i=Qn(),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",s=process.env.OPENAI_PROXY_URL,o="session";r==="byok"||r==="local"||r==="session"?o=r:e?o="session":t?o="byok":s&&n&&(o="local");let l=es(o,i),c={"Content-Type":"application/json"};if(o==="session"){if(!e)return{ok:!1,mode:o,reason:"missing_session_token"};c.Authorization=`Bearer ${e}`}else if(o==="byok"){if(!t)return{ok:!1,mode:o,reason:"missing_openai_api_key"};c.Authorization=`Bearer ${t}`}else if(o==="local"){if(!l)return{ok:!1,mode:o,reason:"missing_openai_proxy_url"};!n&&t&&(c.Authorization=`Bearer ${t}`)}return l?{ok:!0,mode:o,baseUrl:l,headers:c,tokenPreview:c.Authorization?`***${c.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:o,reason:"missing_base_url"}}function Xe(i,e){let t=String(i??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
|
|
98
|
+
|
|
99
|
+
[tool result truncated for size]`}function ts(i,e){if(typeof i=="string")return Xe(i,e);try{return Xe(JSON.stringify(i),e)}catch{return Xe(String(i),e)}}function ir(i){let e=new Set;for(let n of i)if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let s of n.tool_calls)e.add(s.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(c=>r.has(c.id)))return n;let{tool_calls:o,...l}=n;return{...l,content:l.content||""}})}function rs(i){let e=Array.isArray(i?.messages)?i.messages:[],t=e.find(s=>s.role==="system"),r=e.slice(-4).map(s=>({...s,content:Xe(s.content,s.role==="tool"?1200:2500)}));r=ir(r);let n={...i,messages:[t,...r].filter(Boolean)};return delete n.tools,n}async function ns({body:i,streaming:e,auth:t,options:r,fetchCompletion:n,fetchStreamingCompletion:s,onFallbackLog:o}){try{return e?await s(i,t,r):await n(i,t,r)}catch(l){let c=String(l?.message||l||"");if(!/proxy error 413|payload too large/i.test(c))throw l;let a=rs(i);return typeof o=="function"&&o(i,a),{data:e?await s(a,t,r):await n(a,t,r),fallback:a}}}async function ar({body:i,auth:e,options:t,streaming:r,toolContext:n,activeSkills:s,round:o,verbose:l,dependencies:c,config:a={}}){let u=a.maxToolResultChars||3e3,{fetchCompletion:f,fetchStreamingCompletion:d,onFallbackLog:p,hasToolCalls:g,getTextContent:y,parseToolCalls:h,buildAssistantMessage:S,buildToolResultMessage:w,executeTool:v,onToolCallLog:b,injectTools:A}=c;Array.isArray(i?.messages)&&(i.messages=ir(i.messages));let P=await ns({body:i,streaming:r,auth:e,options:t,fetchCompletion:f,fetchStreamingCompletion:d,onFallbackLog:p}),C=P?.data||P;if(!g(C))return{done:!0,text:y(C),body:P?.fallback||i};let I=h(C),R=P?.fallback||i;R.messages.push(S(C)),l&&typeof b=="function"&&b(I);let D=await Promise.all(I.map((E,N)=>(typeof t.onToolCall=="function"&&t.onToolCall(E.name,E.args,{round:o,index:N,total:I.length}),v(E,n))));for(let E=0;E<I.length;E++){let _=I[E].name==="get_skill_context"?typeof D[E]=="string"?D[E]:JSON.stringify(D[E]):ts(D[E],u);R.messages.push(w(I[E].id,_))}return typeof t.onToolCall=="function"&&t.onToolCall(null),A(R,s),{done:!1,body:R}}var os=j.ASSISTANT,is=15,gt="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 lr={maxBytes:49e3,systemMaxChars:12e3},ye=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",as=i=>Buffer.byteLength(JSON.stringify(i),"utf8");function Ve(i){return Array.isArray(i)?new Set(i.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function ls(i){return Array.isArray(i)?i.map(e=>String(e||"").trim()).filter(Boolean):[]}var ae=class extends ss{#e;#t;#r=new Ne;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new ie,this.#t=e.completionProvider||new he):(this.#e=e||new ie,this.#t=new he)}canHandle(e){return mt().ok}async invoke(e,t={}){let r=z("OPENAI_API_KEY");try{let n=t.model&&t.model!=="auto"?t.model:os,s=mt();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 o=t.messages||[{role:"user",content:e}],l=s.baseUrl,c=ye();if(c?await this.#m(o,n,l,s.tokenPreview||"none"):m.debug(`[Assistant] ${l} | model: ${n} | messages: ${o.length}`),t.schema)return this.#c(n,o,s,t);let a=t.activeSkills||[],u=this.#p(t),f=this.#f(a,u),d=this.#d(f),p=this.#u(t),g={...t,payloadCompaction:p},y={activeSkills:f,options:g,executionRegistry:d,capabilityPolicy:u},h=!!t.stream,S={model:n,messages:[...o],stream:!1};this.#s(S,f,u);for(let w=0;w<is;w++){if(t.signal?.aborted){let b=new Error("Aborted via signal");throw b.name="AbortError",b}let v=await ar({body:S,auth:s,options:g,streaming:h,toolContext:y,activeSkills:f,round:w,verbose:c,dependencies:{fetchCompletion:this.#o.bind(this),fetchStreamingCompletion:this.#l.bind(this),onFallbackLog:(b,A)=>{ye()&&console.log(`413 fallback: messages ${b.messages.length} -> ${A.messages.length}, bytes=${as(A)}`)},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,A)=>this.#e.buildToolResultMessage(b,A),executeTool:(b,A)=>this.#a(b,A),onToolCallLog:async b=>{let A=(await import("chalk")).default;console.log(A.dim(` ${b.map(P=>`${P.name}(${JSON.stringify(P.args).slice(0,80)})`).join(", ")}`))},injectTools:(b,A)=>this.#s(b,A,u)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(v.done)return v.text;S.messages=v.body.messages,v.body.tools?S.tools=v.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 o=qe(s);if(o?.tools?.length)for(let l of o.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(gt,t)&&r.push({name:gt,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:o}=t;if(!this.#n(e.name,o))return`Tool "${e.name}" blocked by policy`;if(e.name===gt){let a=String(e.args?.skillId||"").trim();if(!a)return JSON.stringify({error:"skillId is required"});if(!r.includes(a))return JSON.stringify({error:`Skill "${a}" is not active`,activeSkills:r});let u=qe(a);if(!u)return JSON.stringify({error:`Skill "${a}" not found`});let f=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:f||""});return ye()&&(console.log(`
|
|
100
100
|
\u{1F4D6} get_skill_context("${a}") \u2192 ${p.length} chars (fragment: ${f.length} chars)`),console.log(` tools: [${d.join(", ")}]`),console.log(` fragment preview: ${f.slice(0,200).replace(/\n/g,"\\n")}\u2026
|
|
101
|
-
`)),p}let l=s?.get(e.name)||null;if(!l)return`Unknown tool: ${e.name}`;let c=
|
|
101
|
+
`)),p}let l=s?.get(e.name)||null;if(!l)return`Unknown tool: ${e.name}`;let c=qe(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#l(e,t,r){return this.#t.fetchStreamingCompletion(e,t,{...r,onBudget:({beforeBytes:n,meta:s})=>{ye()&&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})=>{ye()&&console.log(`payload bytes before=${n} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#c(e,t,r,n){let{zodToJsonSchema:s}=await import("zod-to-json-schema"),o=typeof n.schema?.parse=="function",l=o?s(n.schema):n.schema;delete l.$schema,Se(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),f=JSON.parse(u),d=o?n.schema.parse(f):f;return{raw:u,structured:d}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||lr.maxBytes),systemMaxChars:Number(t.systemMaxChars||lr.systemMaxChars)}}#p(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:Ve(t.allowTools||e.allowTools),denyTools:Ve(t.denyTools||e.denyTools),denyPrefixes:ls(t.denyPrefixes||e.denyToolPrefixes),includeSkills:Ve(t.includeSkills||e.includeSkills),excludeSkills:Ve(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=qe(n);if(!s?.tools?.length)continue;let o=typeof s.handleToolCall=="function"?"handler":s.serverName&&typeof s.resolve=="function"?"mcp":null;if(o)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:o})}}}if(r.length>0&&ye()){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(`
|
|
102
102
|
\u25C6 Model: ${t} | proxy: ${r} | token: ${n||"none"}
|
|
103
|
-
`);let s=(await import("chalk")).default;console.log(s.bold("Prompt sent to LLM:")),console.log(s.dim("\u2500".repeat(60)));let o=!1;for(let l of e)if(l.role==="system")console.log(s.dim(`[System] ${l.content||""}`));else{o||(console.log(s.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),o=!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
|
|
104
|
-
`;
|
|
105
|
-
`)){let n=r.trim();if(n)try{t.push(JSON.parse(n))}catch{}}return t}import{existsSync as
|
|
106
|
-
`,"utf8")}catch(n){console.warn(`[zibby run-state] ${n.message}`)}}function
|
|
103
|
+
`);let s=(await import("chalk")).default;console.log(s.bold("Prompt sent to LLM:")),console.log(s.dim("\u2500".repeat(60)));let o=!1;for(let l of e)if(l.role==="system")console.log(s.dim(`[System] ${l.content||""}`));else{o||(console.log(s.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),o=!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 cr=!1;function ht(){cr||(ke(new ae),ke(new te),ke(new re),ke(new ne),ke(new oe),cr=!0)}import{existsSync as Le,readdirSync as br,statSync as bs}from"fs";import{join as K,relative as bt,sep as Me,resolve as le}from"path";import{appendFileSync as cs,readFileSync as us,existsSync as ur,mkdirSync as ps}from"node:fs";import{join as Qe}from"node:path";import{DEFAULT_OUTPUT_BASE as pr}from"@zibby/agent-workflow";var fr="run-index.jsonl";function dr(i,e=pr){let t=Qe(i,e);return Qe(t,fr)}function et(i){if(!i||!i.sessionId)return;let e=i.cwd||process.cwd(),t=i.outputBase||pr,r=Qe(e,t);ur(r)||ps(r,{recursive:!0});let n=Qe(r,fr),s=`${JSON.stringify(i)}
|
|
104
|
+
`;cs(n,s,"utf8")}function mr(i){if(!i||!ur(i))return[];let e;try{e=us(i,"utf8")}catch{return[]}let t=[];for(let r of e.split(`
|
|
105
|
+
`)){let n=r.trim();if(n)try{t.push(JSON.parse(n))}catch{}}return t}import{existsSync as fs,mkdirSync as ds,readFileSync as ms,readdirSync as dl,statSync as ml,writeFileSync as gs}from"node:fs";import{join as hs}from"node:path";var ys="zibby-run-state.json";function gr(i){return hs(i,ys)}function yt(i){if(!i||typeof i!="string")return null;let e=gr(i);if(!fs(e))return null;try{let t=ms(e,"utf8"),r=JSON.parse(t);return r&&typeof r=="object"?r:null}catch{return null}}function tt(i,e){if(!i||typeof i!="string")return;try{ds(i,{recursive:!0})}catch{return}let r={...yt(i)||{v:1},...e,v:1,updatedAt:Date.now()};try{gs(gr(i),`${JSON.stringify(r)}
|
|
106
|
+
`,"utf8")}catch(n){console.warn(`[zibby run-state] ${n.message}`)}}function Ss(i){return i?.recordKind==="progress"}function hr(i){let e=Number(i)||0;return e<=0?0:e<1e12?e*1e3:e}function yr(i,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}=i||{};if(!s)return!1;let o=hr(s.ts);if(t>0&&o>0&&r-o>t)return!1;if(!n)return o>0;let l=hr(n.ts);return o>l}function Sr(i){let e=new Map;for(let t of i||[]){if(!t?.sessionId)continue;let r=e.get(t.sessionId);r||(r={summary:null,progress:null});let n=Number(t.ts)||0;Ss(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 ce,SESSIONS_DIR as wt}from"@zibby/agent-workflow";var St=Object.freeze(["preflight","execute_live","generate_script"]);function xt(i){let e=process.env.ZIBBY_STUDIO_TEST_CASE_ID;return e!=null&&String(e).trim()!==""?String(e).trim():i!=null?String(i):""}var ws=[K("generate_script","generated-test.spec.js"),K("generate_script","generated-test.spec.ts"),K("generate_script","playwright.spec.ts"),K("generate_script","test.spec.ts")];function xs(i){let e=[K(i,"execute_live","videos"),K(i,"execute_live"),i];for(let t of e){if(!Le(t))continue;let r;try{r=br(t)}catch{continue}let n=r.find(s=>s.endsWith(".webm"));if(n)return K(t,n)}return null}function _s(i){let e=[K(i,"execute_live","events.json"),K(i,"events.json")];for(let t of e)if(Le(t))return t;return null}function Es(i){for(let e of ws){let t=K(i,e);if(Le(t))return t}return null}function Ts(i){return!i||!Le(i)?{videoPathAbs:null,eventsPathAbs:null,scriptPathAbs:null}:{videoPathAbs:xs(i),eventsPathAbs:_s(i),scriptPathAbs:Es(i)}}function wr(i){let e=i.cwd||process.cwd(),t=i.outputBase||ce,s=((i.result||{}).state||{}).sessionPath;if(!s||typeof s!="string")return null;let o=s.split(/[/\\]/).filter(Boolean).pop();if(!o)return null;let{videoPathAbs:l,eventsPathAbs:c,scriptPathAbs:a}=Ts(s),u=d=>{if(!d)return null;try{return bt(e,d).split(Me).join("/")}catch{return null}},f=null;if(i.specPath)try{let d=le(e,i.specPath);f=bt(e,d).split(Me).join("/")}catch{f=String(i.specPath).split(Me).join("/")}return{v:1,recordKind:"summary",ts:Date.now(),sessionId:o,status:i.status??(i.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:f,source:process.env.ZIBBY_RUN_SOURCE||"cli",studioTestCaseId:xt(o)||null,errorMessage:i.errorMessage||null}}function xr({cwd:i,config:e,result:t,success:r,specPath:n,errorMessage:s}){try{let o=wr({cwd:i||process.cwd(),result:t,success:r,outputBase:e?.paths?.output||ce,specPath:n,errorMessage:s});o&&(et(o),o.sessionPathAbs&&tt(o.sessionPathAbs,{sessionId:o.sessionId,studioTestCaseId:o.studioTestCaseId||o.sessionId,status:o.status,activeNode:null,activeStageIndex:null,errorMessage:o.errorMessage||null,runSource:o.source||"cli",cwd:o.cwd,outputBase:o.outputBase,sessionPathAbs:o.sessionPathAbs}))}catch(o){console.warn(`[zibby browser-test run-index] ${o.message}`)}}function vs({sessionPath:i,sessionId:e,cwd:t,outputBase:r=ce}={}){let n=t||process.cwd(),s=r||ce,o=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 le(c);let a=i&&String(i).trim();if(a)return le(a);let u=process.env.ZIBBY_SESSIONS_ROOT&&String(process.env.ZIBBY_SESSIONS_ROOT).trim();return u&&o?le(K(u,o)):process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim()?le(String(process.env.ZIBBY_SESSION_PATH).trim()):le(K(n,s,wt,o||"invalid"))}function Is(i){try{let e=i?.currentNode;if(!e||!St.includes(e))return;let t=i.sessionPath,r=i.sessionId||t&&String(t).split(/[/\\]/).filter(Boolean).pop()||null;if(!r)return;let n=i.cwd||process.cwd(),s=i.outputBase||ce,o=St.indexOf(e),l=i?.specPath!=null?String(i.specPath).trim():"",c=i?.taskDescription!=null?String(i.taskDescription):"",a=null;if(l)try{let f=le(n,l);a=bt(n,f).split(Me).join("/")}catch{a=l.split(Me).join("/")}let u=vs({sessionPath:t,sessionId:r,cwd:n,outputBase:s});et({v:1,recordKind:"progress",ts:Date.now(),sessionId:r,cwd:n,outputBase:s,sessionPathAbs:u,activeNode:e,activeStageIndex:o,specRel:a,taskDescription:c||null,studioTestCaseId:xt(r)||null,source:process.env.ZIBBY_RUN_SOURCE||"cli"}),tt(u,{sessionId:r,studioTestCaseId:xt(r)||r,status:"running",activeNode:e,activeStageIndex:o,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 _r({cwd:i,config:e}={}){let t=i||process.cwd(),r=e?.paths?.output||ce;return n=>{Is({cwd:n?.cwd||t,outputBase:n?.outputBase||r,sessionPath:n?.sessionPath,sessionId:n?.sessionId,currentNode:n?.currentNode,specPath:n?.specPath,taskDescription:n?.taskDescription})}}function Er(i={}){try{let e=i.cwd||process.cwd(),t=i.config?.paths?.output||i.outputBase||ce,r=dr(e,t),n=mr(r),s=Sr(n),o=new Set,l=i.errorMessage||"Run stopped (SIGINT/SIGTERM) before a normal summary was written.",c=(f,d)=>{if(!f||!d||o.has(f))return;o.add(f);let p=wr({cwd:e,outputBase:t,result:{state:{sessionPath:d}},success:!1,specPath:null,status:"interrupted",errorMessage:l});p&&(et(p),tt(d,{sessionId:f,studioTestCaseId:p.studioTestCaseId||f,status:"interrupted",activeNode:null,activeStageIndex:null,errorMessage:p.errorMessage||null,runSource:p.source||"cli",cwd:e,outputBase:t,sessionPathAbs:d}))};for(let[f,d]of s){if(!yr(d))continue;let p=d.progress;if(!p)continue;let g=String(f),y=p.sessionPathAbs&&String(p.sessionPathAbs)||K(e,t,wt,g);c(g,y)}let a=K(e,t,wt);if(!Le(a))return;let u;try{u=br(a)}catch{return}for(let f of u){let d=K(a,f),p;try{p=bs(d)}catch{continue}if(!p.isDirectory())continue;let g=yt(d);!g||g.status!=="running"||c(String(f),d)}}catch(e){console.warn(`[zibby browser-test run-index interrupt] ${e.message}`)}}function rt(i){xr(i)}function _t(i){Er(i)}function Tr(i){return _r(i)}import{spawn as Rs}from"node:child_process";import{mkdirSync as Ir,existsSync as Ns,writeFileSync as ks}from"node:fs";import{join as It}from"node:path";import{ContextLoader as Ms,WorkflowGraph as Ls,Node as Ds,WorkflowState as Us,DEFAULT_OUTPUT_BASE as Ar,SESSIONS_DIR as Bs,SESSION_INFO_FILE as Fs}from"@zibby/agent-workflow";import{exec as As}from"node:child_process";import{promisify as $s}from"node:util";import{existsSync as Ps}from"node:fs";import{join as Et}from"node:path";import{homedir as Tt}from"node:os";var vr=$s(As);async function vt(){try{return await vr("cursor-agent --version"),"cursor-agent"}catch{let e=[Et(Tt(),".local","bin","cursor-agent"),Et(Tt(),".cursor","bin","cursor-agent"),Et(Tt(),".cursor-agent","bin","cursor-agent")];for(let t of e)if(Ps(t))try{return await vr(`"${t}" --version`),t}catch{}return null}}async function Os(){return await vt()!==null}function Cs(){return`
|
|
107
107
|
\u274C cursor-agent CLI not found!
|
|
108
108
|
|
|
109
109
|
To use the Cursor agent, install it from:
|
|
@@ -120,7 +120,7 @@ After installation:
|
|
|
120
120
|
2. Or restart your terminal/shell
|
|
121
121
|
|
|
122
122
|
Then retry your command.
|
|
123
|
-
`}var
|
|
123
|
+
`}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 H.extractResult(e)}async initialize(e){this.adapter=e,e&&!e.isConnected()&&await e.connect()}buildGraph(){throw new Error("buildGraph() must be implemented by subclass")}async onComplete(e){}async run(e,t={}){let r=this.buildGraph(),n=typeof e=="object"&&!Array.isArray(e)?{input:e,...e,...t}:{input:e,...t};return await r.run(this,n)}async executeNode(e,t){let{prompt:r,outputSchema:n,model:s}=e,o=typeof r=="function"?r(t):r;console.log(`
|
|
124
124
|
\u{1F4DD} Prompt:
|
|
125
125
|
${o}
|
|
126
126
|
`);let l=await this.executePrompt(o,t.cwd,3e5,s);console.log(`
|
|
@@ -129,14 +129,14 @@ ${l}
|
|
|
129
129
|
`);let c=null;if(n)try{if(c=i.extractJsonFromStream(l),!c)throw new Error("No valid result JSON found in output");console.log(`
|
|
130
130
|
\u2705 Parsed Output:
|
|
131
131
|
${JSON.stringify(c,null,2)}
|
|
132
|
-
`)}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 o=this.agentCommand;if(o==="cursor-agent"){let l=await
|
|
133
|
-
\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
|
|
132
|
+
`)}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 o=this.agentCommand;if(o==="cursor-agent"){let l=await vt();l&&(o=l)}return new Promise((l,c)=>{let a="",u=this.buildArgs(e,s);n&&u.push("--model",n);let f={...process.env},d=Rs(o,u,{cwd:t,env:f,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),p=setTimeout(()=>{console.log(`
|
|
133
|
+
\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(`
|
|
134
134
|
|
|
135
|
-
\u{1F6D1} Interrupted by user (Ctrl+C)`),S(),c(new Error("Interrupted by user"))};process.on("SIGINT",w);let
|
|
135
|
+
\u{1F6D1} Interrupted by user (Ctrl+C)`),S(),c(new Error("Interrupted by user"))};process.on("SIGINT",w);let v=new H;d.stdout.on("data",b=>{let A=b.toString();a+=A;let P=v.processChunk(A);P&&(process.stdout.write(P,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),y=Date.now(),g+=P.length)}),d.on("close",b=>{process.off("SIGINT",w),clearTimeout(p),clearInterval(h);let A=v.flush();A&&process.stdout.write(A),a=v.getRawText();let P=v.getResult();b===0?l({raw:a,extracted:P}):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 o=r.sessionPath,l=r.sessionTimestamp,c=r.config||{};if(!o){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 v=c.paths?.output||Ar;o=It(s,v,Bs,w),Ns(o)||Ir(o,{recursive:!0})}let a=c.paths?.output||Ar,u=It(s,a,Fs);Ir(It(s,a),{recursive:!0}),ks(u,JSON.stringify({sessionPath:o,sessionTimestamp:l||o.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
|
|
136
136
|
${"=".repeat(80)}`),console.log(`\u{1F3AF} SINGLE NODE EXECUTION: ${e}`),console.log(`\u{1F4C1} Session: ${o.split("/").pop()}${r.sessionPath?" (reusing)":""}`),console.log(`${"=".repeat(80)}
|
|
137
|
-
`);let f=await
|
|
137
|
+
`);let f=await Ms.loadContext(r.specPath||"",s,r.contextConfig||{}),d=new Us({...r,sessionPath:o,sessionTimestamp:l,context:f}),g=await new Ds(n).execute(this,d);return console.log(`
|
|
138
138
|
${"=".repeat(80)}`),console.log(`\u2705 Node ${e} completed`),console.log(`${"=".repeat(80)}
|
|
139
|
-
`),{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
|
|
139
|
+
`),{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 js(i,e={}){let t=new be(e);return t.buildGraph=function(){let r=new Ls;return i(r),r},e.onComplete&&(t.onComplete=e.onComplete),t}import{WorkflowGraph as np,resolveWorkflowSession as sp,generateWorkflowSessionId as op,clearInheritedSessionEnvForFreshRun as ip,shouldTrustInheritedSessionEnv as ap,readPinnedSessionPathFromEnv as lp,syncProcessEnvToSession as cp}from"@zibby/agent-workflow";import{writeFileSync as $r,existsSync as Gs,mkdirSync as zs}from"node:fs";import{join as At}from"node:path";var $t=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 s=At(r,"title.txt");$r(s,n,"utf-8"),m.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,o=typeof n.scriptPath=="string"&&n.scriptPath.trim().length>0;if(!(!s&&!o))try{let l=At(t,r);Gs(l)||zs(l,{recursive:!0});let c=At(l,"result.json");$r(c,JSON.stringify(n,null,2),"utf-8"),m.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(([,o])=>o&&typeof o=="object"&&o.success!==void 0),n=r.length>0&&r.every(([,o])=>o.success),s=r.some(([,o])=>o.success===!1);if(n)m.info("Workflow completed successfully."),t&&m.info(`Output: ${t}`);else if(s){let o=r.filter(([,l])=>!l.success).map(([l])=>l);m.info(`Workflow completed with failures in: ${o.join(", ")}`),t&&m.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 fp}from"zod/v3";import{AgentStrategy as Js}from"@zibby/agent-workflow";var Pr=[new ae,new te,new re,new ne,new oe];function Or(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");m.debug(`Agent selection: requested=${r}`);let n=Pr.find(s=>s.getName()===r);if(!n)throw new Error(`Unknown agent '${r}'. Available: ${Pr.map(s=>s.getName()).join(", ")}`);if(m.debug(`Checking if ${r} can handle this environment...`),!n.canHandle(i)){let o={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. ${o}`)}return m.debug(`Using agent: ${n.getName()}`),n}async function Ks(i,e={},t={}){try{await import("@zibby/skills")}catch{}let r=Or(e),n=e.state?.config||t.config||{},s=n.models||{},o=t.nodeName&&s[t.nodeName]||null,l=s.default||null,c=r.name,a=n.agent?.[c]?.model||null,u=o||l||a||t.model||null,f={...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=f.skills||[],p=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&&(p+=`
|
|
140
140
|
|
|
141
141
|
${h.join(`
|
|
142
142
|
|
|
@@ -148,13 +148,13 @@ ${h.join(`
|
|
|
148
148
|
|
|
149
149
|
${g}
|
|
150
150
|
`),m.debug(`Prompt length: ${p.length} chars`),process.env.STAGE!=="prod"&&m.debug(`Full prompt:
|
|
151
|
-
${p}`),r.invoke(p,f)}import{SKILLS as
|
|
152
|
-
`);let s=
|
|
153
|
-
\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
|
|
154
|
-
`),new Promise((e,t)=>{let r=
|
|
155
|
-
`),new Promise((e,t)=>{let r=
|
|
151
|
+
${p}`),r.invoke(p,f)}import{SKILLS as Sp}from"@zibby/agent-workflow";import{registerSkill as wp,getSkill as xp,hasSkill as _p,getAllSkills as Ep,listSkillIds as Tp}from"@zibby/agent-workflow";var Ys={READ_FILE:"read_file",WRITE_FILE:"write_file",LIST_DIRECTORY:"list_directory",RUN_COMMAND:"run_command",OPEN_URL:"open_url",WAIT:"wait"},Hs={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"},Zs={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"},Ws={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"},Xs={GENERATE:"run_generate",TEST:"run_test",STATUS:"run_status",CANCEL:"run_cancel",WAIT:"run_wait",ARTIFACTS:"run_artifacts",LIST_SPECS:"list_specs"},qs={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"},Vs={STORE:"memory_store",RECALL:"memory_recall",BRIEF:"memory_brief",END_SESSION:"memory_end_session",TASK_LOG:"task_log",TASK_HISTORY:"task_history"},Qs={INSTALL:"install_skill",UNINSTALL:"uninstall_skill",LIST_AVAILABLE:"list_available_skills"},ec={...Ys,...Hs,...Zs,...Ws,...Xs,...qs,...Vs,...Qs};import{existsSync as eo,readFileSync as to}from"node:fs";import{homedir as ro}from"node:os";import{join as no}from"node:path";var nt=new Map;function so(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let i=no(ro(),".zibby","config.json");return eo(i)&&JSON.parse(to(i,"utf-8")).sessionToken||null}catch{return null}}function oo(){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 io(i){let e=Date.now(),t=nt.get(i);if(t&&t.expiresAt>e)return t.data;let r=so();if(!r)throw new Error("No session token. Run `zibby login` first.");let n=`${oo()}/integrations/token/${i}`,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(`${i} 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 ${i} token (${s.status}): ${c}`)}let o=await s.json();if(!o||typeof o!="object")throw new Error(`Invalid response from ${i} token endpoint: expected object, got ${typeof o}`);if(i==="jira"){if(!o.token||typeof o.token!="string")throw new Error(`Invalid jira token response: token is ${typeof o.token}, expected string`);if(!o.cloudId)throw new Error("Invalid jira token response: missing cloudId")}else if(i==="github"&&(!o.token||typeof o.token!="string"))throw new Error(`Invalid github token response: token is ${typeof o.token}, expected string`);let l=((o.expiresInSec||3e3)-120)*1e3;return nt.set(i,{data:o,expiresAt:e+l}),o}function ao(i){i?nt.delete(i):nt.clear()}import{readdir as lo,access as Cr,copyFile as co,constants as Rr}from"fs/promises";import{join as st,relative as uo}from"node:path";async function po(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...
|
|
152
|
+
`);let s=st(r,e),o=st(r,t);try{let l=await lo(s),c=0;for(let a of l){if(a.startsWith("."))continue;let u=st(s,a,"video.webm");try{await Cr(u,Rr.F_OK)}catch{continue}let f=a.replace(/-chromium$/,"").replace(/-firefox$/,"").replace(/-webkit$/,""),d=await fo(o,f);if(d){let p=d.replace(/\.spec\.(js|ts)$/,".spec.webm");await co(u,p),n&&console.log(`\u2705 ${uo(r,p)}`),c++}else n&&console.log(`\u26A0\uFE0F Could not find test file for: ${a}`)}return n&&(console.log(`
|
|
153
|
+
\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 fo(i,e){let t=e.split("-");for(let r=t.length;r>0;r--){let s=t.slice(0,r).join("/");for(let o of["js","ts"]){let l=st(i,`${s}.spec.${o}`);try{return await Cr(l,Rr.F_OK),l}catch{}}}return null}var De=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 Nr(){let i=process.env.ZIBBY_API_KEY;return new De(i)}import{execSync as mo}from"node:child_process";import{existsSync as go,mkdirSync as ho}from"node:fs";import{join as yo}from"node:path";async function So(i={}){let{baseDir:e="/workspace/repos",repos:t=null,depth:r=1,branch:n=null}=i,s=process.env.REPOS;if(!s)throw new Error("REPOS environment variable not set. Are you running in a Zibby workflow container?");let o;try{o=JSON.parse(s)}catch(a){throw new Error(`Failed to parse REPOS env var: ${a.message}`,{cause:a})}if(!Array.isArray(o)||o.length===0)throw new Error("No repositories configured for this project");let l=t?o.filter(a=>t.includes(a.name)):o;if(l.length===0)throw new Error(`No matching repositories found. Available: ${o.map(a=>a.name).join(", ")}`);go(e)||ho(e,{recursive:!0});let c={};return await Promise.all(l.map(async a=>{let u=a.provider||"github",f=u==="gitlab"?process.env.GITLAB_TOKEN:process.env.GITHUB_TOKEN;if(!f){console.error(`${u.toUpperCase()}_TOKEN not set, skipping ${a.name}`),c[a.name]=null;return}let d=a.name.replace(/\//g,"-"),p=yo(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:${f}@`):y=g.replace(/^https:\/\//,`https://x-access-token:${f}@`);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{mo(S,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),console.log(`Repository ${a.name} cloned successfully`),c[a.name]=p}catch(w){let v=w.message.replace(f,"***").replace(y,g);console.error(`Failed to clone ${a.name}: ${v}`),c[a.name]=null}})),c}import{spawn as kr}from"node:child_process";import{readFileSync as bo,writeFileSync as wo,existsSync as ot}from"node:fs";import{homedir as Mr}from"node:os";import{join as we}from"node:path";async function xo(){let i=we(Mr(),".local/share/cursor-agent/versions");if(!ot(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...
|
|
154
|
+
`),new Promise((e,t)=>{let r=we(__dirname,"../../scripts/patch-cursor-mcp.py");if(!ot(r)){t(new Error("Patch script not found"));return}let n=kr("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 _o(){let i=we(Mr(),".local/share/cursor-agent/versions");if(!ot(i))return{patched:!1,installed:!1};try{let e=en("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 ot(r)?{patched:bo(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 Eo(i){return console.log(`\u{1F511} Getting MCP approval keys...
|
|
155
|
+
`),new Promise((e,t)=>{let r=kr("cursor-agent",["mcp","list"],{cwd:i,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 o=To(n);e({success:!0,keys:o,output:n})}else t(new Error(`Failed to get approval keys (exit code ${s})`))}),r.on("error",s=>{t(s)})})}function To(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 vo(i,e){let t=we(i,".cursor/projects"),r=we(t,"mcp-approvals.json");wo(r,JSON.stringify(e,null,2)),console.log(`
|
|
156
156
|
\u2705 Saved approval keys to: ${r}
|
|
157
|
-
`)}import{DEFAULT_OUTPUT_BASE as
|
|
157
|
+
`)}import{DEFAULT_OUTPUT_BASE as Np,SESSIONS_DIR as kp,SESSION_INFO_FILE as Mp,RESULT_FILE as Lp,RAW_OUTPUT_FILE as Dp,EVENTS_FILE as Up,CI_ENV_VARS as Bp}from"@zibby/agent-workflow";var Lr=`
|
|
158
158
|
const style = document.createElement('style');
|
|
159
159
|
style.textContent = \`
|
|
160
160
|
@keyframes zibby-ripple {
|
|
@@ -215,7 +215,7 @@ ${p}`),r.invoke(p,f)}import{SKILLS as cp}from"@zibby/agent-workflow";import{regi
|
|
|
215
215
|
setTimeout(() => ripple.remove(), 600);
|
|
216
216
|
}
|
|
217
217
|
};
|
|
218
|
-
`;function
|
|
218
|
+
`;function Io(i){return i.addInitScript(Lr)}function Ao(){return`
|
|
219
219
|
async function showRipple(page, locator) {
|
|
220
220
|
const box = await locator.boundingBox().catch(() => null);
|
|
221
221
|
if (box) {
|
|
@@ -228,10 +228,10 @@ async function showRipple(page, locator) {
|
|
|
228
228
|
}, { x, y }).catch(() => {});
|
|
229
229
|
}
|
|
230
230
|
}
|
|
231
|
-
`.trim()}var
|
|
231
|
+
`.trim()}var Ue=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]}
|
|
232
232
|
${n.slice(1).map(o=>` .or(${o})`).join(`
|
|
233
233
|
`)};`}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:o}=e,l=`element${t}`,c=this.generate(e,l),a=this.generateActionMethod(r,l,n);return`${c}
|
|
234
|
-
${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:o}=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 Be from"fs/promises";var
|
|
234
|
+
${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:o}=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 Be from"fs/promises";var Pt=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"),o=JSON.parse(s(t,"utf-8")),l=o.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';
|
|
235
235
|
import { test, expect } from '@playwright/test';
|
|
236
236
|
|
|
237
237
|
`;a+=`test('${n}', async ({ page }) => {
|
|
@@ -247,53 +247,53 @@ import { test, expect } from '@playwright/test';
|
|
|
247
247
|
|
|
248
248
|
`,u++}a+=`});
|
|
249
249
|
`;let{dirname:f}=await import("path"),{mkdirSync:d}=await import("fs");return d(f(e),{recursive:!0}),await Be.writeFile(e,a,"utf-8"),console.log(`[TestPostProcessor] \u2705 Generated test with ${o.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 Be.readFile(e,"utf-8");n.includes("ZibbyRuntime")||(n=`import { ZibbyRuntime } from '@zibby/core';
|
|
250
|
-
${n}`);for(let s=0;s<t.length;s++){let o=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:o.name||`Action ${s}`,action:o.method==="type"?"fill":o.method,value:a[3].trim().replace(/^['"]|['"]$/g,""),strategies:o.strategies||[]},f=`await ZibbyRuntime.step(page, ${JSON.stringify(u,null,2)});`;n=n.replace(a[0],f)}return await Be.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 Be.readFile(e,"utf-8"),s=this.buildSelectorMap(r);return n=this.replaceSimpleSelectors(n,s),await Be.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=
|
|
251
|
-
await ${d}.${u}(${f})`}}return o});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as
|
|
252
|
-
`),s=[],o=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 f of a.snapshot.accessibility)f.ref&&u.set(f.ref,f);o.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 f=a.params.selector,d=a.params.text||a.params.value||"",p=[],g=null,y=null,h=null,S=f.match(/aria-ref=([a-z0-9]+)/i);if(S&&a.snapshotName){let T=S[1],x=o.get(a.snapshotName);if(x&&x.has(T)){let A=x.get(T);g=A.name||null,y=A.role||null,h=A.label||null,console.log(`[TraceParser] \u2705 Found ACTUAL element data: text="${g}", role="${y}"`)}}let w=f.match(/internal:text="([^"]+)"/i),b=f.match(/internal:label="([^"]+)"/i),v=f.match(/internal:placeholder="([^"]+)"/i),N=f.match(/internal:role=([^ ]+)/i),P=f.match(/internal:describe="([^"]+)"/i),k=f.match(/name="([^"]+)"/i);if(w){p.push({type:"text",text:w[1]});let T=w[1].split(" ");T.length>1&&(p.push({type:"text",text:T[0],fuzzy:!0}),p.push({type:"text",text:T[T.length-1],fuzzy:!0}))}if(b&&p.push({type:"label",label:b[1]}),v&&p.push({type:"placeholder",placeholder:v[1]}),g){p.unshift({type:"text",text:g,source:"accessibility-tree"});let T=g.split(" ");T.length>1&&p.push({type:"text",text:T[0],fuzzy:!0,source:"accessibility-tree"})}if(y||N){let T=y||N[1],x=g||(k?k[1]:w?w[1]:null);p.unshift({type:"role",role:T,name:x,source:g?"accessibility-tree":"selector"})}if(h&&p.unshift({type:"label",label:h,source:"accessibility-tree"}),P){let T=P[1],x=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],A=null,R=T;for(let E of x)if(T.toLowerCase().endsWith(` ${E}`)){A=E.replace(" ",""),R=T.substring(0,T.length-E.length-1);break}if(A){p.push({type:"role",role:A,name:R});let E=R.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:E}),p.push({type:"text",text:R});let O=R.split(" ");O.length>1&&(p.push({type:"text",text:O[0],fuzzy:!0}),p.push({type:"text",text:O.slice(0,2).join(" "),fuzzy:!0}))}else{let E=T.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:E}),p.push({type:"text",text:T})}}let _=this.extractDOMStrategies(f,l,w?.[1]||P?.[1],a.pageId);p.push(..._);let C=this.extractStructuralContext(f);(C.parent||C.sibling)&&p.forEach(T=>{["role","text","label","testid"].includes(T.type)&&(C.parent&&(T.parent=C.parent),C.sibling&&(T.sibling=C.sibling))}),p.push({type:"css",value:f});let M=g||w?w[1]:P?P[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${s.length}`;s.push({method:u,name:M,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 o=t.get(n);if(!o)return s;let l=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${l}`,"i"),a=o.match(c);a&&s.push({type:"testid",value:a[1],priority:"high"});let u=new RegExp(`class=["']([^"']+)["'][^>]*>[^<]*${l}`,"gi"),f=o.matchAll(u);for(let g of f){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=o.match(d);p&&!p[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&s.push({type:"id",value:p[1],priority:"high"})}catch(o){console.warn(`[TraceParser] DOM extraction failed: ${o.message}`)}return s}static extractStructuralContext(e){let t={parent:null,sibling:null},r=e.split(">>").map(o=>o.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 Ot=class{static async step(e,t){let{name:r,action:n,value:s,strategies:o,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,o,r);if(!a)throw new Error(`[Zibby] \u274C Failed to find "${r}" using ${o.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(o=>setTimeout(o,500)))}catch{}}static async performActionWithRetry(e,t,r,n,s=3){for(let o=1;o<=s;o++)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(o===s)throw l;console.log(`[Zibby] \u26A0\uFE0F Action failed (attempt ${o}/${s}), retrying...`),await new Promise(c=>setTimeout(c,1e3*o))}}static async findBestMatch(e,t,r){let s=Date.now(),o=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(o)).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 o=await e.boundingBox();o&&o.y<1e3&&(n+=10)}catch{}try{let o=await e.evaluate(l=>{let c=0,a=l;for(;a;)a.tagName==="IFRAME"&&c++,a=a.parentElement;return c});n-=o*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 Ct=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}"]`,o=Date.now();for(;Date.now()-o<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}"]`,o=Date.now();for(;Date.now()-o<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}"]`,o=Date.now();for(;Date.now()-o<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 f=c.tagName.toLowerCase();return f==="button"||f==="a"||c.getAttribute("role")==="button"?(c.textContent||"").trim().slice(0,50):c.title?c.title:f==="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 f=c.closest('header, nav, main, footer, aside, [role="banner"], [role="navigation"], [role="main"], [role="contentinfo"]');if(f){let y=f.tagName.toLowerCase(),h=f.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||"",f=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,f,d,p,g,y,h].join("|"),w=5381;for(let b=0;b<S.length;b++)w=(w<<5)+w^S.charCodeAt(b);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(", "),o=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),f=u,d=o.get(f)||0;d>0&&(u=`${f}-${d}`),o.set(f,d+1),c.setAttribute("data-zibby-id",u),l++}),console.log(`[Zibby] Injected ${l} stable IDs`)})}catch{}}};var Po=8,Oo=1,Co=64;function Ro(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 ko,writeFileSync as Br,existsSync as Mo}from"node:fs";import{join as Ur}from"node:path";var j=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 No}from"node:fs";import{join as Dr}from"node:path";var le=class extends j{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=Dr(e,"traces"),r=Dr(e,"trace.zip");if(No(r))try{this.traceData=await Ue.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 o=s.actualText||this._extractTextFromSelector(s.selector),l=s.actualRole,c=s.actualAriaLabel;return o||l||c?(console.log(`[TraceTextEnricher] \u2705 Event ${n}: text="${o}", role="${l}", label="${c}"`),{traceActualText:o,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 Lo(i){let e=Ur(i,"events.json"),t=Ur(i,"events-enriched.json");if(!Mo(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(ko(e,"utf-8")),n=new le,s=0,o=0;for(let l of r)try{let c=await n.enrich(l,{sessionPath:i});c&&(l.enrichedData={...l.enrichedData||{},...c},s++)}catch(c){console.log(`[PostProcess] Failed to enrich event ${l.id}: ${c.message}`),o++}return s>0&&(Br(t,JSON.stringify(r,null,2)),Br(e,JSON.stringify(r,null,2)),console.log(`[PostProcess] \u2705 Enriched ${s} events (${o} failed)`)),{enriched:s,failed:o}}catch(r){return console.log(`[PostProcess] \u274C Failed to post-process events: ${r.message}`),{enriched:0,failed:0}}}import{spawn as Do}from"node:child_process";import{existsSync as Bo}from"node:fs";import{dirname as Uo,resolve as Fr,relative as Fo}from"node:path";var ot=new Map,Fe=8,jr={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 ${Fe} 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=(ot.get(r)||0)+1;if(ot.set(r,n),n>Fe)return{success:!1,executionCount:n,maxReached:!0,error:`Maximum ${Fe} executions reached. Stop retrying and return your best result.`};let s=e?.projectRoot||process.cwd(),o=Fr(s,i),l=Fo(s,o);return l.startsWith("..")||Fr(o)!==o&&l.includes("..")?{success:!1,executionCount:n,error:"Path traversal detected: scriptPath must be within the project root."}:Bo(o)?new Promise(c=>{let a=Uo(o),u=Do("npx",["playwright","test",o,"--reporter=line"],{cwd:s,env:{...process.env,FORCE_COLOR:"0"}}),f="",d="";u.stdout.on("data",g=>{f+=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:f.slice(-2e3),stderr:d.slice(-1e3)})},6e4);u.on("close",g=>{clearTimeout(p);let h=`${f}
|
|
250
|
+
${n}`);for(let s=0;s<t.length;s++){let o=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:o.name||`Action ${s}`,action:o.method==="type"?"fill":o.method,value:a[3].trim().replace(/^['"]|['"]$/g,""),strategies:o.strategies||[]},f=`await ZibbyRuntime.step(page, ${JSON.stringify(u,null,2)});`;n=n.replace(a[0],f)}return await Be.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 Be.readFile(e,"utf-8"),s=this.buildSelectorMap(r);return n=this.replaceSimpleSelectors(n,s),await Be.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=Ue.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,o=>{for(let[l,c]of t.entries())if(o.includes(l.split(":")[1])){let a=o.match(/\.(fill|click|type)\(([^)]*)\)/);if(a){let[,u,f]=a,d="element";return`const ${d} = ${c};
|
|
251
|
+
await ${d}.${u}(${f})`}}return o});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as $o,existsSync as Dr,readdirSync as Ur}from"node:fs";import{join as Ot}from"node:path";import{execSync as Po}from"node:child_process";import{tmpdir as Oo}from"node:os";var Fe=class{static async parseTraceZip(e){let t;if(e.endsWith(".zip")&&Dr(e)){let r=Ot(Oo(),`trace-${Date.now()}`);Po(`unzip -q "${e}" -d "${r}"`,{stdio:"pipe"});let s=Ur(r).find(o=>o.endsWith(".trace"));if(!s)throw new Error("No .trace file found in zip");t=Ot(r,s)}else if(Dr(e)){let n=Ur(e).find(s=>s.endsWith(".trace"));if(!n)throw new Error("No .trace file found");t=Ot(e,n)}else throw new Error(`Trace not found at ${e}`);try{let n=$o(t,"utf-8").trim().split(`
|
|
252
|
+
`),s=[],o=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 f of a.snapshot.accessibility)f.ref&&u.set(f.ref,f);o.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 f=a.params.selector,d=a.params.text||a.params.value||"",p=[],g=null,y=null,h=null,S=f.match(/aria-ref=([a-z0-9]+)/i);if(S&&a.snapshotName){let E=S[1],N=o.get(a.snapshotName);if(N&&N.has(E)){let _=N.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=f.match(/internal:text="([^"]+)"/i),v=f.match(/internal:label="([^"]+)"/i),b=f.match(/internal:placeholder="([^"]+)"/i),A=f.match(/internal:role=([^ ]+)/i),P=f.match(/internal:describe="([^"]+)"/i),C=f.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(v&&p.push({type:"label",label:v[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||A){let E=y||A[1],N=g||(C?C[1]:w?w[1]:null);p.unshift({type:"role",role:E,name:N,source:g?"accessibility-tree":"selector"})}if(h&&p.unshift({type:"label",label:h,source:"accessibility-tree"}),P){let E=P[1],N=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],_=null,O=E;for(let k of N)if(E.toLowerCase().endsWith(` ${k}`)){_=k.replace(" ",""),O=E.substring(0,E.length-k.length-1);break}if(_){p.push({type:"role",role:_,name:O});let k=O.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:k}),p.push({type:"text",text:O});let T=O.split(" ");T.length>1&&(p.push({type:"text",text:T[0],fuzzy:!0}),p.push({type:"text",text:T.slice(0,2).join(" "),fuzzy:!0}))}else{let k=E.replace(/\s*\([^)]+\)\s*$/,"");p.push({type:"text",text:k}),p.push({type:"text",text:E})}}let I=this.extractDOMStrategies(f,l,w?.[1]||P?.[1],a.pageId);p.push(...I);let R=this.extractStructuralContext(f);(R.parent||R.sibling)&&p.forEach(E=>{["role","text","label","testid"].includes(E.type)&&(R.parent&&(E.parent=R.parent),R.sibling&&(E.sibling=R.sibling))}),p.push({type:"css",value:f});let D=g||w?w[1]:P?P[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 o=t.get(n);if(!o)return s;let l=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${l}`,"i"),a=o.match(c);a&&s.push({type:"testid",value:a[1],priority:"high"});let u=new RegExp(`class=["']([^"']+)["'][^>]*>[^<]*${l}`,"gi"),f=o.matchAll(u);for(let g of f){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=o.match(d);p&&!p[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&s.push({type:"id",value:p[1],priority:"high"})}catch(o){console.warn(`[TraceParser] DOM extraction failed: ${o.message}`)}return s}static extractStructuralContext(e){let t={parent:null,sibling:null},r=e.split(">>").map(o=>o.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 Ct=class{static async step(e,t){let{name:r,action:n,value:s,strategies:o,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,o,r);if(!a)throw new Error(`[Zibby] \u274C Failed to find "${r}" using ${o.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(o=>setTimeout(o,500)))}catch{}}static async performActionWithRetry(e,t,r,n,s=3){for(let o=1;o<=s;o++)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(o===s)throw l;console.log(`[Zibby] \u26A0\uFE0F Action failed (attempt ${o}/${s}), retrying...`),await new Promise(c=>setTimeout(c,1e3*o))}}static async findBestMatch(e,t,r){let s=Date.now(),o=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(o)).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 o=await e.boundingBox();o&&o.y<1e3&&(n+=10)}catch{}try{let o=await e.evaluate(l=>{let c=0,a=l;for(;a;)a.tagName==="IFRAME"&&c++,a=a.parentElement;return c});n-=o*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 Rt=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}"]`,o=Date.now();for(;Date.now()-o<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}"]`,o=Date.now();for(;Date.now()-o<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}"]`,o=Date.now();for(;Date.now()-o<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 f=c.tagName.toLowerCase();return f==="button"||f==="a"||c.getAttribute("role")==="button"?(c.textContent||"").trim().slice(0,50):c.title?c.title:f==="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 f=c.closest('header, nav, main, footer, aside, [role="banner"], [role="navigation"], [role="main"], [role="contentinfo"]');if(f){let y=f.tagName.toLowerCase(),h=f.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||"",f=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,f,d,p,g,y,h].join("|"),w=5381;for(let v=0;v<S.length;v++)w=(w<<5)+w^S.charCodeAt(v);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(", "),o=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),f=u,d=o.get(f)||0;d>0&&(u=`${f}-${d}`),o.set(f,d+1),c.setAttribute("data-zibby-id",u),l++}),console.log(`[Zibby] Injected ${l} stable IDs`)})}catch{}}};var Co=8,Ro=1,No=64;function ko(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 Lo,writeFileSync as Fr,existsSync as Do}from"node:fs";import{join as jr}from"node:path";var G=class{constructor(e={}){this.config=e,this.enabled=e.enabled!==!1,this.priority=e.priority||50}getName(){throw new Error("EventEnricher.getName() must be implemented")}canEnrich(e){return this.enabled}async enrich(e,t){throw new Error("EventEnricher.enrich() must be implemented")}handleError(e,t){return console.warn(`[${this.getName()}] Enrichment failed for event ${t.type}:`,e.message),null}};import{existsSync as Mo}from"node:fs";import{join as Br}from"node:path";var ue=class extends G{constructor(e={}){super(e),this.priority=190,this.traceData=null}getName(){return"TraceText"}getPriority(){return this.priority}async loadTrace(e){if(this.traceData)return;let t=Br(e,"traces"),r=Br(e,"trace.zip");if(Mo(r))try{this.traceData=await Fe.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 o=s.actualText||this._extractTextFromSelector(s.selector),l=s.actualRole,c=s.actualAriaLabel;return o||l||c?(console.log(`[TraceTextEnricher] \u2705 Event ${n}: text="${o}", role="${l}", label="${c}"`),{traceActualText:o,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 Uo(i){let e=jr(i,"events.json"),t=jr(i,"events-enriched.json");if(!Do(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(Lo(e,"utf-8")),n=new ue,s=0,o=0;for(let l of r)try{let c=await n.enrich(l,{sessionPath:i});c&&(l.enrichedData={...l.enrichedData||{},...c},s++)}catch(c){console.log(`[PostProcess] Failed to enrich event ${l.id}: ${c.message}`),o++}return s>0&&(Fr(t,JSON.stringify(r,null,2)),Fr(e,JSON.stringify(r,null,2)),console.log(`[PostProcess] \u2705 Enriched ${s} events (${o} failed)`)),{enriched:s,failed:o}}catch(r){return console.log(`[PostProcess] \u274C Failed to post-process events: ${r.message}`),{enriched:0,failed:0}}}import{spawn as Bo}from"node:child_process";import{existsSync as Fo}from"node:fs";import{dirname as jo,resolve as Gr,relative as Go}from"node:path";var it=new Map,je=8,zr={name:"run_playwright_test",description:`Run a Playwright test file and return results. Use this after writing a test to verify it works. If it fails, fix the issues and run again. Maximum ${je} attempts per session.`,inputSchema:{type:"object",properties:{scriptPath:{type:"string",description:"Path to the Playwright test file (e.g., tests/login.spec.js)"}},required:["scriptPath"]},async execute({scriptPath:i},e){let r=`${e?.sessionId||"default"}:${i}`,n=(it.get(r)||0)+1;if(it.set(r,n),n>je)return{success:!1,executionCount:n,maxReached:!0,error:`Maximum ${je} executions reached. Stop retrying and return your best result.`};let s=e?.projectRoot||process.cwd(),o=Gr(s,i),l=Go(s,o);return l.startsWith("..")||Gr(o)!==o&&l.includes("..")?{success:!1,executionCount:n,error:"Path traversal detected: scriptPath must be within the project root."}:Fo(o)?new Promise(c=>{let a=jo(o),u=Bo("npx",["playwright","test",o,"--reporter=line"],{cwd:s,env:{...process.env,FORCE_COLOR:"0"}}),f="",d="";u.stdout.on("data",g=>{f+=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:f.slice(-2e3),stderr:d.slice(-1e3)})},6e4);u.on("close",g=>{clearTimeout(p);let h=`${f}
|
|
253
253
|
${d}`.split(`
|
|
254
|
-
`),S="",w=null;for(let
|
|
255
|
-
`;for(let
|
|
256
|
-
`}if(
|
|
254
|
+
`),S="",w=null;for(let v=0;v<h.length;v++){let b=h[v];if(b.includes("Error:")||b.includes("error:")||b.includes("\u2718")){S+=`${b}
|
|
255
|
+
`;for(let A=v+1;A<Math.min(v+5,h.length);A++)S+=`${h[A]}
|
|
256
|
+
`}if(b.includes("at ")&&b.includes(".spec.")){let A=b.match(/:(\d+):\d+/);A&&(w=parseInt(A[1]))}}c(g===0?{success:!0,executionCount:n,message:"All tests passed!",output:f.slice(-500)}:{success:!1,executionCount:n,remainingAttempts:je-n,error:S.slice(0,1500)||"Test failed (see output)",failedAtLine:w,stdout:f.slice(-1500),stderr:d.slice(-500),hint:n<je?"Fix the error and run again.":"Last attempt - make your best fix."})}),u.on("error",g=>{clearTimeout(p),c({success:!1,executionCount:n,error:`Failed to run test: ${g.message}`})})}):{success:!1,executionCount:n,error:`Test file not found: ${o}. Make sure you wrote the file first using the write tool.`}},resetCount(i){for(let e of it.keys())e.startsWith(`${i}:`)&&it.delete(e)}};function zo(i){zr.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 Kr,writeFileSync as Ko}from"node:fs";var xe=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(Kr(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`,o=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(Kr(s,"utf-8")).filter(u=>["navigate","type","fill","click","select_option"].includes(u.type)),a=`import { test, expect } from '@playwright/test';
|
|
257
257
|
`;a+=`import { ZibbyRuntime } from '@zibby/core';
|
|
258
258
|
|
|
259
259
|
`,a+=`test('${o}', async ({ page }) => {
|
|
260
260
|
`,a+=` const timestamp = Date.now();
|
|
261
261
|
|
|
262
|
-
`;for(let u of c){let f=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,
|
|
262
|
+
`;for(let u of c){let f=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,v=S||f,b=S||this._extractName(f),A=w||this._extractRole(f),P=p?" [accessibility-tree]":h?" [live]":" [AI]";if(u.type==="navigate")a+=` await page.goto('${u.data.params.url}');
|
|
263
263
|
|
|
264
264
|
`;else if(u.type==="click")a+=` // ${f}${S?` (actual: "${S}")${P}`:""}
|
|
265
265
|
`,a+=` await ZibbyRuntime.step(page, {
|
|
266
266
|
`,a+=` name: '${this._escapeString(f)}',
|
|
267
267
|
`,a+=` action: 'click',
|
|
268
268
|
`,a+=` strategies: [
|
|
269
|
-
`,a+=` { type: 'role', role: '${
|
|
270
|
-
`,a+=` { type: 'text', text: '${this._escapeString(
|
|
269
|
+
`,a+=` { type: 'role', role: '${A}', name: '${this._escapeString(b)}' },
|
|
270
|
+
`,a+=` { type: 'text', text: '${this._escapeString(b)}' }
|
|
271
271
|
`,a+=` ]
|
|
272
272
|
`,a+=` });
|
|
273
273
|
|
|
274
|
-
`;else if(u.type==="fill"||u.type==="type"){let
|
|
274
|
+
`;else if(u.type==="fill"||u.type==="type"){let C=u.data.params.text;a+=` // ${f}${S?` (actual: "${S}")${P}`:""}
|
|
275
275
|
`,a+=` await ZibbyRuntime.step(page, {
|
|
276
276
|
`,a+=` name: '${this._escapeString(f)}',
|
|
277
277
|
`,a+=` action: 'fill',
|
|
278
|
-
`,a+=` value: '${this._escapeString(
|
|
278
|
+
`,a+=` value: '${this._escapeString(C)}',
|
|
279
279
|
`,a+=` strategies: [
|
|
280
|
-
`,a+=` { type: 'role', role: '${
|
|
281
|
-
`,a+=` { type: 'attributes', placeholder: '${this._escapeString(
|
|
280
|
+
`,a+=` { type: 'role', role: '${A}', name: '${this._escapeString(b)}' },
|
|
281
|
+
`,a+=` { type: 'attributes', placeholder: '${this._escapeString(b)}' }
|
|
282
282
|
`,a+=` ]
|
|
283
283
|
`,a+=` });
|
|
284
284
|
|
|
285
|
-
`}else if(u.type==="select_option"){let
|
|
285
|
+
`}else if(u.type==="select_option"){let C=u.data.params.values,I=Array.isArray(C)?C[0]:C;a+=` // ${f}${S?` (actual: "${S}")${P}`:""}
|
|
286
286
|
`,a+=` await ZibbyRuntime.step(page, {
|
|
287
287
|
`,a+=` name: '${this._escapeString(f)}',
|
|
288
288
|
`,a+=` action: 'select',
|
|
289
|
-
`,a+=` value: '${this._escapeString(
|
|
289
|
+
`,a+=` value: '${this._escapeString(I)}',
|
|
290
290
|
`,a+=` strategies: [
|
|
291
|
-
`,a+=` { type: 'role', role: 'combobox', name: '${this._escapeString(
|
|
291
|
+
`,a+=` { type: 'role', role: 'combobox', name: '${this._escapeString(b)}' }
|
|
292
292
|
`,a+=` ]
|
|
293
293
|
`,a+=` });
|
|
294
294
|
|
|
295
295
|
`}}return a+=`});
|
|
296
|
-
`,
|
|
296
|
+
`,Ko(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 Jr,writeFileSync as Jo}from"node:fs";var _e=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(Jr(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`,o=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(Jr(s,"utf-8")).filter(d=>["navigate","type","fill","click","select_option","select"].includes(d.type)),a=`import { test, expect } from '@playwright/test';
|
|
297
297
|
`;a+=`import { StableIdRuntime } from '@zibby/core';
|
|
298
298
|
|
|
299
299
|
`,a+=`test('${o}', async ({ page }) => {
|
|
@@ -308,17 +308,17 @@ ${d}`.split(`
|
|
|
308
308
|
`}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)}');
|
|
309
309
|
`:a+=` await page.locator('select').selectOption('${this._escapeString(S)}');
|
|
310
310
|
`}}return a+=`});
|
|
311
|
-
`,
|
|
311
|
+
`,Jo(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 Nt=class{constructor(){this.strategies=[new _e,new xe],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(`
|
|
312
312
|
\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(`
|
|
313
|
-
\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}},
|
|
313
|
+
\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}},Yo=new Nt;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 Ho}from"node:child_process";import{existsSync as Zo}from"node:fs";var Te=class extends Ee{getName(){return"Playwright JSON Reporter"}getPriority(){return 100}canVerify(e){let{testFilePath:t}=e;return Zo(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}`,o=Ho(s,{cwd:r,encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:n+1e4}),c=JSON.parse(o).stats||{};return{success:c.unexpected===0,passed:c.expected||0,failed:c.unexpected||0,error:null,errorDetails:null}}catch(s){let o=s.stdout||s.stderr||s.message;try{let l=JSON.parse(o),c=l.stats||{},a="Test execution failed";if(l.suites&&l.suites.length>0){let f=l.suites[0];if(f.specs&&f.specs.length>0){let d=f.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")||o.includes("Executable doesn't exist")||o.includes("npx playwright install");return{success:!1,passed:c.expected||0,failed:c.unexpected||0,error:a,errorDetails:a,isEnvironmentError:u}}catch{let c=o.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")||o.includes("Executable doesn't exist")||o.includes("npx playwright install");return{success:!1,passed:0,failed:1,error:a,errorDetails:a,isEnvironmentError:u}}}}};var kt=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(`
|
|
314
314
|
\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(`
|
|
315
|
-
\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}},
|
|
315
|
+
\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}},Wo=new kt;var V=class{constructor(e={}){this.enrichers=[],this.config=e,this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}register(e){return this.enrichers.push(e),this.enrichers.sort((t,r)=>r.getPriority()-t.getPriority()),this}unregister(e){return this.enrichers=this.enrichers.filter(t=>t.getName()!==e),this}get(e){return this.enrichers.find(t=>t.getName()===e)}setEnabled(e,t){let r=this.get(e);return r&&(r.enabled=t),this}async enrich(e,t){this.stats.totalEvents++;let r={...e},n=[],s=[],o=[];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),o.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:o}},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(`
|
|
316
316
|
\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(`
|
|
317
|
-
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
|
|
317
|
+
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 G{getName(){return"PositionEnricher"}getPriority(){return 90}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:n}=t,s=await n.boundingBox();if(!s)return null;let o=await r.evaluate(()=>({scrollX:window.scrollX,scrollY:window.scrollY,width:window.innerWidth,height:window.innerHeight})),l=s.y>=o.scrollY&&s.y+s.height<=o.scrollY+o.height&&s.x>=0&&s.x+s.width<=o.width;return{position:{boundingBox:s,viewport:o,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 Yr from"node:crypto";var pe=class extends G{getName(){return"AccessibilityEnricher"}getPriority(){return 100}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:n}=t,s=await r.accessibility.snapshot(),o=await this.findAxNode(n,s);if(!o)return null;let l=await this.getAxContext(o,s),c=this.hashAxSubtree(o),a=this.hashAxPath(l.path);return{accessibility:{role:o.role,name:o.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 o=this.calculateLevel(e,t,s,n+1);if(o>=0)return o}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 o=this.buildPath(e,t,s,[...n,{role:r.role,name:r.name}]);if(o)return o}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 Yr.createHash("md5").update(t).digest("hex").substring(0,12)}hashAxPath(e){let t=e.map(r=>`${r.role}:${r.name}`).join("/");return Yr.createHash("md5").update(t).digest("hex").substring(0,12)}};var fe=class extends G{constructor(e={}){super(e),this.pendingRequests=new Set,this.setupNetworkTracking=!1}getName(){return"PageStateEnricher"}getPriority(){return 95}canEnrich(e){return this.enabled&&e.page}async setupTracking(e){this.setupNetworkTracking||(e.on("request",t=>{["document","xhr","fetch"].includes(t.resourceType())&&this.pendingRequests.add(t.url())}),e.on("requestfinished",t=>{this.pendingRequests.delete(t.url())}),e.on("requestfailed",t=>{this.pendingRequests.delete(t.url())}),this.setupNetworkTracking=!0)}async enrich(e,t){try{let{page:r}=t;await this.setupTracking(r);let n=await r.evaluate(()=>({readyState:document.readyState,domContentLoaded:document.readyState!=="loading",loadComplete:document.readyState==="complete",url:document.location.href})),s=await this.checkDOMStability(r);return{page:{networkIdle:this.pendingRequests.size===0,pendingRequests:this.pendingRequests.size,domStable:s,...n}}}catch(r){return this.handleError(r,e)}}async checkDOMStability(e,t=500){try{return await e.evaluate(n=>new Promise(s=>{let o,l=0,c=new MutationObserver(()=>{l++,clearTimeout(o),o=setTimeout(()=>{c.disconnect(),s(l===0)},n)});c.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),o=setTimeout(()=>{c.disconnect(),s(!0)},n)}),t)}catch{return!1}}reset(){this.pendingRequests.clear(),this.setupNetworkTracking=!1}};var Ie=class extends G{getName(){return"DOMEnricher"}getPriority(){return 85}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{element:r}=t,n=await r.evaluate(s=>{let o=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(v=>v.tagName===y.tagName);if(w.length>1){let v=w.indexOf(y)+1;h+=`:nth-child(${v})`}}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},f=0,d=s.parentElement;for(;d;)f++,d=d.parentElement;return{path:o(s),xpath:l(s),depth:f,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 Ge=class extends G{constructor(e={}){super(e),this.priority=200}getName(){return"MCPRef"}getPriority(){return this.priority}async enrich(e,t){let r=e.data?.params?.ref,n=e.data?.params?.element;if(!r&&!n)return null;let s=null,o=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,o=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:o,actualLabel:l,recordedSelector:s||n}}};function Mt(i={}){let e=new V(i);return i.enableMCPRef!==!1&&e.register(new Ge(i)),i.enableTraceText!==!1&&e.register(new ue(i)),i.enableAccessibility!==!1&&e.register(new pe(i)),i.enablePageState!==!1&&e.register(new fe(i)),i.enablePosition!==!1&&e.register(new ve(i)),i.enableDOM!==!1&&e.register(new Ie(i)),e}function Lt(i={}){let e=new V(i);return e.register(new pe(i)),e.register(new fe(i)),e}function Xo(i,e={}){let t=new V(e);for(let r of i)t.register(r);return t}import{readFileSync as qo,writeFileSync as Dt}from"node:fs";import{join as Hr}from"node:path";async function Vo(i,e={}){let t=Hr(i,"events.json"),r=Hr(i,"trace.zip");try{let n=JSON.parse(qo(t,"utf-8")),s=n.map(l=>({...l,_enrichmentNote:"Full enrichment requires live Playwright access. Use EnrichmentPipeline during test execution."})),o=`${t}.backup`;return Dt(o,JSON.stringify(n,null,2)),Dt(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 Ut=class{constructor(e={}){this.pipeline=e.minimal?Lt(e):Mt(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){Dt(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()}};ht();var Vr=i=>{i?.message?.includes("Connection closed")||i?.message?.includes("MCP error -32000")||i?.code===-32e3||console.error("Unhandled rejection:",i)};process.listeners("unhandledRejection").includes(Vr)||process.on("unhandledRejection",Vr);async function oi(i,e={}){let{agent:t,mcp:r,headless:n,cwd:s=process.cwd(),specPath:o,sessionPath:l,sessionTimestamp:c,...a}=e,u=Zr(i,"utf-8"),f=null,{agent:d,error:p}=await li(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:
|
|
318
318
|
zibby init
|
|
319
319
|
|
|
320
|
-
This will create .zibby/graph.mjs with your workflow definition.`);await g.initialize(f);let y=!1,h=()=>{if(!y)try{
|
|
320
|
+
This will create .zibby/graph.mjs with your workflow definition.`);await g.initialize(f);let y=!1,h=()=>{if(!y)try{_t({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(`
|
|
321
321
|
\u{1F3AF} Running Single Node: ${e.singleNode} (Framework Mode)
|
|
322
|
-
`);let
|
|
322
|
+
`);let I=g.calculateOutputPath(o||i),R=g.buildGraph(),D={};for(let[_,O]of R.nodes.entries())D[_]=O.config||O;let E={};if(e.sessionId){let _=e.sessionId,O=e.paths?.output||ei;if(_==="last"){let M=Ae(s,O,qr);if(Wr(M)){let{readdirSync:U,statSync:$}=await import("fs"),B=U(M).filter(L=>$(Ae(M,L)).isDirectory()).map(L=>({name:L,time:$(Ae(M,L)).mtimeMs})).sort((L,F)=>F.time-L.time);B.length>0?(_=B[0].name,console.log(`\u{1F4C2} Using latest session: ${_}`)):console.log(`\u26A0\uFE0F No sessions found in ${M}`)}}let k=Ae(s,O,qr,_),T=Ae(k,"execute_live"),x=Ae(T,ti);Wr(x)?(console.log(`\u{1F4C2} Loading session: ${_}`),E={sessionPath:k,execute_live_output:JSON.parse(Zr(x,"utf-8"))}):console.log(`\u26A0\uFE0F Session not found: ${k}`)}let N=await g.runSingleNode(e.singleNode,D,{testSpec:u,outputPath:I,cwd:s||process.cwd(),contextConfig:e.contextConfig,specPath:o||i,config:e,...E});return typeof g.onComplete=="function"&&await g.onComplete(N),rt({cwd:s,config:e,result:N,success:!0,specPath:o||i}),N}let S;typeof e.onPipelineProgress=="function"?S=e.onPipelineProgress:e.runIndex?.pipelineProgress!==!1&&(S=Tr({cwd:s||process.cwd(),config:e}));let w=s||process.cwd(),v=l!=null&&String(l).trim()!==""?(()=>{let I=String(l).trim();try{return Qo(I)?Xr(I):Xr(w,I)}catch{return I}})():void 0,b=si(),A=v??b;ni();let P=ri({cwd:w,config:e,traceFrom:"runTest",initialState:{sessionPath:A,sessionTimestamp:c}}),C;try{C=await g.run(u,{testSpec:u,specPath:o||i,cwd:w,config:e,sessionPath:P.sessionPath,sessionTimestamp:P.sessionTimestamp,...S?{onPipelineProgress:S}:{}})}catch(I){throw typeof I?.message=="string"&&I.message.includes("Interrupted by user")&&_t({cwd:s||process.cwd(),config:e}),y||rt({cwd:s,config:e,result:I?.partialResult||{},success:!1,specPath:o||i,errorMessage:I?.message}),I}return rt({cwd:s,config:e,result:C,success:!0,specPath:o||i}),C}finally{process.off("SIGINT",h),process.off("SIGTERM",h),await g.cleanup()}}function ii(i){return i.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function ai(i,e){if(i[e])return i[e];let t=ii(e);if(i[t])return i[t];let r=`${t}Workflow`;return i[r]?i[r]:null}async function ep(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 s=await import(r(n).href),o=Object.keys(s).filter(c=>c!=="default"&&typeof s[c]=="function"&&s[c].prototype instanceof be),l=s.BrowserTestAutomationAgent?"BrowserTestAutomationAgent":s.CursorAgent?"CursorAgent":s.default?"default":o[0]||null;return{available:o,default:l,error:null}}catch(e){return{available:[],default:null,error:e.message}}}async function li(i,e){try{let{join:t}=await import("path"),{existsSync:r}=await import("fs"),{pathToFileURL:n}=await import("url"),s=t(i,".zibby/graph.mjs");if(!r(s))return{agent:null,error:null};let o=await import(n(s).href),l=e.workflow,c;if(l){if(c=ai(o,l),!c){let u=Object.keys(o).filter(f=>f!=="default"&&typeof o[f]=="function");throw new Error(`Workflow "${l}" not found.
|
|
323
323
|
Available workflows: ${u.join(", ")}
|
|
324
|
-
Supported formats: QuickSmokeWorkflow, QuickSmoke, quick-smoke`)}let a=Object.keys(o).find(u=>o[u]===c);console.log(`\u2713 Using workflow: ${a} (from --workflow ${l})`)}else{if(c=o.BrowserTestAutomationAgent||o.CursorAgent||o.default,!c){let a=Object.keys(o).filter(u=>u!=="default"&&typeof o[u]=="function"&&o[u].prototype instanceof
|
|
324
|
+
Supported formats: QuickSmokeWorkflow, QuickSmoke, quick-smoke`)}let a=Object.keys(o).find(u=>o[u]===c);console.log(`\u2713 Using workflow: ${a} (from --workflow ${l})`)}else{if(c=o.BrowserTestAutomationAgent||o.CursorAgent||o.default,!c){let a=Object.keys(o).filter(u=>u!=="default"&&typeof o[u]=="function"&&o[u].prototype instanceof be);a.length>0&&(c=o[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 Qr=class{constructor(e={}){this.config=e}async run(e){return oi(e.spec||e.specPath,{...this.config,...e})}};export{tn as AGENT_TYPES,ec as ALL_TOOLS,pe as AccessibilityEnricher,Js as AgentStrategy,ae as AssistantStrategy,Vs as CHAT_MEMORY_TOOLS,Bp as CI_ENV_VARS,rn as CORE_LOG_LEVELS,Ys as CORE_TOOLS,re as ClaudeAgentStrategy,ne as CodexAgentStrategy,te as CursorAgentStrategy,Co as DEFAULT_MAX_CONCURRENT_RUNS,j as DEFAULT_MODELS,Np as DEFAULT_OUTPUT_BASE,Ie as DOMEnricher,Up as EVENTS_FILE,V as EnrichmentPipeline,G as EventEnricher,Zs as GITHUB_TOOLS,oe as GeminiAgentStrategy,Hs as JIRA_TOOLS,J as LOG_LEVELS,Ut as LiveEnrichmentRecorder,Ke as Logger,No as MAX_MAX_CONCURRENT_RUNS,xe as MCPRefStrategy,qs as MEMORY_TOOLS,Ro as MIN_MAX_CONCURRENT_RUNS,Ne as McpClientManager,ie as OpenAIToolProvider,fe as PageStateEnricher,Te as PlaywrightJsonVerificationStrategy,ve as PositionEnricher,Dp as RAW_OUTPUT_FILE,Lp as RESULT_FILE,Lr as RIPPLE_EFFECT_SCRIPT,Xs as RUNNER_TOOLS,$t as ResultHandler,kp as SESSIONS_DIR,Mp as SESSION_INFO_FILE,Sp as SKILLS,Qs as SKILL_TOOLS,Ws as SLACK_TOOLS,Ue as SelectorGenerator,Rt as StableIdRuntime,_e as StableIdStrategy,H as StreamingParser,Qr as TestAutomation,q as TestGenerationStrategy,Pt as TestPostProcessor,Ee as TestVerificationStrategy,ge as ToolCallProvider,Fe as TraceParser,be as WorkflowAgent,np as WorkflowGraph,Ct as ZibbyRuntime,De as ZibbyUploader,Os as checkCursorAgentInstalled,_o as checkCursorAgentPatched,ip as clearInheritedSessionEnvForFreshRun,ao as clearTokenCache,So as cloneRepo,Xo as createCustomPipeline,Mt as createDefaultPipeline,Lt as createMinimalPipeline,Nr as createUploader,Vo as enrichRecordedEvents,Ao as generateRippleHelperCode,op as generateWorkflowSessionId,Or as getAgentStrategy,Ep as getAllSkills,Eo as getApprovalKeys,Cs as getCursorAgentInstallInstructions,xp as getSkill,_p as hasSkill,Io as injectRippleEffect,Ks as invokeAgent,Tp as listSkillIds,ep as listWorkflows,m as logger,po as organizeVideos,xo as patchCursorAgentForCI,z as pickFromPool,Uo as postProcessEvents,lp as readPinnedSessionPathFromEnv,ht as registerBuiltInStrategies,wp as registerSkill,zo as resetExecutionCount,io as resolveIntegrationToken,ko as resolveMaxParallelRuns,sp as resolveWorkflowSession,zr as runPlaywrightTestTool,oi as runTest,vo as saveApprovalKeys,ap as shouldTrustInheritedSessionEnv,cp as syncProcessEnvToSession,Yo as testGenerationManager,Wo as testVerificationManager,Z as timeline,js as workflow,fp as z};
|