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