@zibby/core 0.5.8 → 0.5.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/backend-client.js +1 -1
- package/dist/index.js +30 -30
- package/dist/package.json +4 -4
- package/package.json +4 -4
package/dist/backend-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as
|
|
1
|
+
import{existsSync as w,readFileSync as _}from"node:fs";import{homedir as E}from"node:os";import{join as b}from"node:path";var f=new Map,u={github:"GITHUB_TOKEN",gitlab:"GITLAB_TOKEN"};function p(){let e=process.env.ZIBBY_SELF_HOST;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function l(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let e=b(E(),".zibby","config.json");return w(e)&&JSON.parse(_(e,"utf-8")).sessionToken||null}catch{return null}}function d(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app"}async function g(e){if(p()){let a=u[e];if(a&&process.env[a])return{token:process.env[a]}}let c=Date.now(),n=f.get(e);if(n&&n.expiresAt>c)return n.data;let r=l();if(!r)throw new Error("No session token. Run `zibby login` first.");let s=`${d()}/integrations/token/${e}`,o=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!o.ok){let a=await o.text().catch(()=>"");throw o.status===404?new Error(`${e} is not connected. Connect it at https://studio.zibby.dev/integrations`):o.status===401||o.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Failed to resolve ${e} token (${o.status}): ${a}`)}let t=await o.json();if(!t||typeof t!="object")throw new Error(`Invalid response from ${e} token endpoint: expected object, got ${typeof t}`);if(e==="jira"){if(!t.token||typeof t.token!="string")throw new Error(`Invalid jira token response: token is ${typeof t.token}, expected string`);if(!t.cloudId)throw new Error("Invalid jira token response: missing cloudId")}else if(e==="github"&&(!t.token||typeof t.token!="string"))throw new Error(`Invalid github token response: token is ${typeof t.token}, expected string`);let h=((t.expiresInSec||3e3)-120)*1e3;return f.set(e,{data:t,expiresAt:c+h}),t}function T(e){e?f.delete(e):f.clear()}var i=null;async function v(){let e=Date.now();if(i&&i.expiresAt>e)return i.data;if(p()){let n={};for(let[r,s]of Object.entries(u))n[r]=!!process.env[s];return i={data:n,expiresAt:e+6e4},n}let c=l();if(!c)return{};try{let n=await fetch(`${d()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${c}`}});if(!n.ok)return{};let r=await n.json(),s={};if(r&&typeof r=="object")for(let[o,t]of Object.entries(r))t&&typeof t=="object"&&"connected"in t&&(s[o]=!!t.connected);return i={data:s,expiresAt:e+6e4},s}catch{return{}}}function A(){i=null}export{A as clearConnectedCache,T as clearTokenCache,v as getConnectedIntegrations,g as resolveIntegrationToken};
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var rn=Object.defineProperty;var nn=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var on=(s,e)=>()=>(s&&(e=s(s=0)),e);var sn=(s,e)=>{for(var t in e)rn(s,t,{get:e[t],enumerable:!0})};var nr={};sn(nr,{zodToJson:()=>ne});import{z as rr}from"zod";import{zodToJsonSchema as Dn}from"zod-to-json-schema";function ne(s,e={target:"openApi3"}){if(!s)return null;if(typeof rr?.toJSONSchema=="function")try{return rr.toJSONSchema(s)}catch{}try{return Dn(s,e)}catch{return null}}var Me=on(()=>{});import{readFileSync as Zr,existsSync as Xr}from"node:fs";import{join as Ie,resolve as qr,isAbsolute as
|
|
1
|
+
var rn=Object.defineProperty;var nn=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var on=(s,e)=>()=>(s&&(e=s(s=0)),e);var sn=(s,e)=>{for(var t in e)rn(s,t,{get:e[t],enumerable:!0})};var nr={};sn(nr,{zodToJson:()=>ne});import{z as rr}from"zod";import{zodToJsonSchema as Dn}from"zod-to-json-schema";function ne(s,e={target:"openApi3"}){if(!s)return null;if(typeof rr?.toJSONSchema=="function")try{return rr.toJSONSchema(s)}catch{}try{return Dn(s,e)}catch{return null}}var Me=on(()=>{});import{readFileSync as Zr,existsSync as Xr}from"node:fs";import{join as Ie,resolve as qr,isAbsolute as ei}from"node:path";import{DEFAULT_OUTPUT_BASE as ti,SESSIONS_DIR as Qr,RESULT_FILE as ri,resolveWorkflowSession as ni,clearInheritedSessionEnvForFreshRun as oi,readPinnedSessionPathFromEnv as si}from"@zibby/agent-workflow";import{registerStrategy as je}from"@zibby/agent-workflow";import{AgentStrategy as Cn,DEFAULT_OUTPUT_BASE as Pn,SESSION_INFO_FILE as kn,STOP_REQUEST_FILE as Nn,getAllSkills as Rn,getSkill as Zt}from"@zibby/agent-workflow";import{spawn as Ln,execSync as te}from"node:child_process";import{writeFileSync as Xt,readFileSync as qt,mkdirSync as Qt,existsSync as Re,accessSync as er,constants as tr,unlinkSync as Mn}from"node:fs";import{join as V,resolve as Un}from"node:path";import{homedir as Le}from"node:os";import Pe from"chalk";var H={debug:0,info:1,warn:2,error:3,silent:4},We=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return H.debug;if(process.env.ZIBBY_VERBOSE==="true")return H.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in H?H[e]:H.info}_shouldLog(e){return H[e]>=this._level}_formatMessage(e,t,r={}){let n=new Date().toISOString(),i=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(i+=Pe.dim(` ${JSON.stringify(r)}`)),i}_getPrefix(e){return{debug:Pe.gray("[DEBUG]"),info:Pe.cyan("[INFO]"),warn:Pe.yellow("[WARN]"),error:Pe.red("\u274C [ERROR]")}[e]||""}debug(e,t){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,t))}info(e,t){this._shouldLog("info")&&console.log(this._formatMessage("info",e,t))}warn(e,t){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,t))}error(e,t){this._shouldLog("error")&&console.error(this._formatMessage("error",e,t))}setLevel(e){e in H&&(this._level=H[e])}getLevel(){return Object.keys(H).find(e=>H[e]===this._level)}},p=new We;var ke=[{alias:"auto",canonicalId:"claude-sonnet-4-6",vendor:"claude",label:"Claude \xB7 Sonnet 4.6",family:"claude-sonnet-4",pickerVisible:!0,isDefault:!0},{alias:"opus-4.8",canonicalId:"claude-opus-4-8",vendor:"claude",label:"Claude \xB7 Opus 4.8",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-8",canonicalId:"claude-opus-4-8",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.8"},{alias:"sonnet-4.8",canonicalId:"claude-sonnet-4-8",vendor:"claude",label:"Claude \xB7 Sonnet 4.8",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-8",canonicalId:"claude-sonnet-4-8",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.8"},{alias:"opus-4.7",canonicalId:"claude-opus-4-7",vendor:"claude",label:"Claude \xB7 Opus 4.7",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-7",canonicalId:"claude-opus-4-7",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.7"},{alias:"sonnet-4.7",canonicalId:"claude-sonnet-4-7",vendor:"claude",label:"Claude \xB7 Sonnet 4.7",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-7",canonicalId:"claude-sonnet-4-7",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.7"},{alias:"sonnet-4.6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"auto"},{alias:"sonnet-4-6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"auto"},{alias:"opus-4.6",canonicalId:"claude-opus-4-6",vendor:"claude",label:"Claude \xB7 Opus 4.6",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-6",canonicalId:"claude-opus-4-6",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.6"},{alias:"sonnet-4.5",canonicalId:"claude-sonnet-4-5-20250929",vendor:"claude",label:"Claude \xB7 Sonnet 4.5",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-5",canonicalId:"claude-sonnet-4-5-20250929",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.5"},{alias:"opus-4.5",canonicalId:"claude-opus-4-5-20251101",vendor:"claude",label:"Claude \xB7 Opus 4.5",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-5",canonicalId:"claude-opus-4-5-20251101",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.5"},{alias:"haiku-4.5",canonicalId:"claude-haiku-4-5-20251001",vendor:"claude",label:"Claude \xB7 Haiku 4.5",family:"claude-haiku-4"},{alias:"haiku-4-5",canonicalId:"claude-haiku-4-5-20251001",vendor:"claude",family:"claude-haiku-4",aliasOf:"haiku-4.5"},{alias:"claude-opus-4-8",canonicalId:"claude-opus-4-8",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.8"},{alias:"claude-sonnet-4-8",canonicalId:"claude-sonnet-4-8",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.8"},{alias:"claude-opus-4-7",canonicalId:"claude-opus-4-7",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.7"},{alias:"claude-sonnet-4-7",canonicalId:"claude-sonnet-4-7",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.7"},{alias:"claude-sonnet-4-6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"auto"},{alias:"claude-opus-4-6",canonicalId:"claude-opus-4-6",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.6"},{alias:"claude-sonnet-4-5-20250929",canonicalId:"claude-sonnet-4-5-20250929",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.5"},{alias:"claude-opus-4-5-20251101",canonicalId:"claude-opus-4-5-20251101",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.5"},{alias:"claude-haiku-4-5-20251001",canonicalId:"claude-haiku-4-5-20251001",vendor:"claude",family:"claude-haiku-4",aliasOf:"haiku-4.5"},{alias:"claude-opus-4-20250514",canonicalId:"claude-opus-4-20250514",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.5"},{alias:"auto",canonicalId:"o4-mini",vendor:"codex",label:"Codex \xB7 o4-mini",family:"o4-mini",isDefault:!0},{alias:"o4-mini",canonicalId:"o4-mini",vendor:"codex",label:"Codex \xB7 o4-mini",family:"o4-mini",pickerVisible:!0},{alias:"o3",canonicalId:"o3",vendor:"codex",family:"o3"},{alias:"o3-mini",canonicalId:"o3-mini",vendor:"codex",family:"o3-mini"},{alias:"codex-mini",canonicalId:"codex-mini-latest",vendor:"codex",family:"codex-mini"},{alias:"gpt-4o",canonicalId:"gpt-4o",vendor:"codex",label:"Codex \xB7 GPT-4o",family:"gpt-4o",pickerVisible:!0},{alias:"gpt-4o-mini",canonicalId:"gpt-4o-mini",vendor:"codex",label:"Codex \xB7 GPT-4o mini",family:"gpt-4o-mini",pickerVisible:!0},{alias:"gpt-5.2-codex",canonicalId:"gpt-5.2-codex",vendor:"codex",label:"Codex \xB7 GPT-5.2",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.2",canonicalId:"gpt-5.2",vendor:"codex",label:"Codex \xB7 GPT-5.2 base",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.3",canonicalId:"gpt-5.3",vendor:"codex",label:"Codex \xB7 GPT-5.3",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.3-codex",canonicalId:"gpt-5.3-codex",vendor:"codex",family:"gpt-5"},{alias:"gpt-5.4",canonicalId:"gpt-5.4",vendor:"codex",label:"Codex \xB7 GPT-5.4",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.5",canonicalId:"gpt-5.5",vendor:"codex",label:"Codex \xB7 GPT-5.5",family:"gpt-5",pickerVisible:!0},{alias:"auto",canonicalId:"gemini-3-pro",vendor:"gemini",label:"Gemini \xB7 3 Pro",family:"gemini-3",isDefault:!0},{alias:"gemini-3-pro",canonicalId:"gemini-3-pro",vendor:"gemini",label:"Gemini \xB7 3 Pro",family:"gemini-3",pickerVisible:!0},{alias:"gemini-3-flash",canonicalId:"gemini-3-flash",vendor:"gemini",label:"Gemini \xB7 3 Flash",family:"gemini-3",pickerVisible:!0},{alias:"gemini-2.5-pro",canonicalId:"gemini-2.5-pro",vendor:"gemini",label:"Gemini \xB7 2.5 Pro",family:"gemini-2.5",pickerVisible:!0},{alias:"gemini-2.5-flash",canonicalId:"gemini-2.5-flash",vendor:"gemini",label:"Gemini \xB7 2.5 Flash",family:"gemini-2.5",pickerVisible:!0}];function Ne(s){let e={};for(let t of ke)t.vendor===s&&(e[t.alias]=t.canonicalId);return e}function an(s){if(!s||typeof s!="string")return null;let e=s.toLowerCase();for(let t of ke)if(t.alias.toLowerCase()===e)return t.family??null;for(let t of ke)if(t.canonicalId.toLowerCase()===e)return t.family??null;return null}function Gt(s){let e=String(s||"").match(/(\d+(?:\.\d+)?)/);return e?parseFloat(e[1]):0}function Kt(s){let e=String(s||"").toLowerCase();return/\b(base|mini)\b/.test(e)?0:/\b(opus|pro)\b/.test(e)?2:1}function ln(s,e){let t=Gt(e.label)-Gt(s.label);if(t!==0)return t;let r=Kt(e.label)-Kt(s.label);return r!==0?r:s.label.localeCompare(e.label)}function cn(){let s=[],e=new Map;for(let r of ke)r.pickerVisible&&(e.has(r.vendor)||(e.set(r.vendor,[]),s.push(r.vendor)),e.get(r.vendor).push({value:`${r.vendor}:${r.alias}`,label:r.label||`${r.vendor}:${r.alias}`,vendor:r.vendor,alias:r.alias,isDefault:!!r.isDefault}));let t=[];for(let r of s)t.push(...e.get(r).sort(ln));return t}var J={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-3-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"},un={ASSISTANT:"assistant",CLAUDE:"claude",CURSOR:"cursor",CODEX:"codex",GEMINI:"gemini"},pn={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error",SILENT:"silent"},Ze=Ne("claude"),Xe=Ne("codex"),pt=Ne("gemini"),qe={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var W=class s{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(e){if(!e)return null;this.buffer+=e;let t=this.buffer.split(`
|
|
2
2
|
`);this.buffer=t.pop()||"";let r="";for(let n of t)if(n.trim())try{let o=JSON.parse(n);this._emitToolCalls(o);let i=this.extractText(o);if(i){if(this.rawText&&i.startsWith(this.rawText)){let c=i.substring(this.rawText.length);this.rawText=i,r+=c}else(!this.rawText.includes(i)||i.length<20)&&(this.rawText+=i,r+=i);this.tryExtractResult(this.rawText)}else this.isValidResult(o)&&(this.rawText+=`${n}
|
|
3
3
|
`,r+=`${n}
|
|
4
|
-
`,this.extractedResult=o)}catch{if(n.includes('"text"')||n.includes('"content"')){let i=n.match(/"text"\s*:\s*"([^"]*)/),c=n.match(/"content"\s*:\s*"([^"]*)/),a=i?i[1]:c?c[1]:null;a&&!this.rawText.includes(a)&&(r+=a,this.rawText+=a)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(i,c)=>{if(!i)return;let a=`${i}:${JSON.stringify(c??{})}`;this._lastToolEmit!==a&&(this._lastToolEmit=a,this.onToolCall(i,c??void 0))},r=i=>{if(i!=null){if(typeof i=="object"&&!Array.isArray(i))return i;if(typeof i=="string")try{return JSON.parse(i)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,r(e.input??e.arguments));return}let i=e.tool_call;if(i&&typeof i=="object"&&!Array.isArray(i)){let c=Object.keys(i);if(c.length===1){let a=c[0],l=i[a],u=l&&typeof l=="object"?l.args??l.input??l:void 0;t(a,r(u))}return}return}if(Array.isArray(e.tool_calls)){for(let i of e.tool_calls)t(i.name,r(i.input??i.arguments));return}let n=e.message??e;if(Array.isArray(n?.tool_calls)){for(let i of n.tool_calls)t(i.name,r(i.input??i.arguments));return}let o=n?.content??e.content;if(Array.isArray(o))for(let i of o)(i.type==="tool_use"||i.type==="tool_call")&&i.name&&t(i.name,r(i.input??i.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return e.type==="thinking"&&e.text||e.text?e.text:e.content&&typeof e.content=="string"?e.content:e.delta?e.delta:null}tryExtractResult(e){if(!e||typeof e!="string")return;let t=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,n;for(;(n=r.exec(e))!==null;){let m=n[1].trim();try{JSON.parse(m),t.push({text:m,source:"markdown"})}catch{}}let o=0,i=0;for(;o<e.length&&(o=e.indexOf("{",o),o!==-1);){let m=0,d=o;for(let f=o;f<e.length;f++)if(e[f]==="{")m++;else if(e[f]==="}"&&(m--,m===0)){d=f,t.push({text:e.substring(o,d+1),source:"brace"}),i++;break}o=d+1}let c=this.extractedResult,a=c?JSON.stringify(c).length:0,l=0,u=-1;for(let m=0;m<t.length;m++){let d=t[m];try{let f=d.text.replace(/,(\s*[}\]])/g,"$1"),g=JSON.parse(f);this.isValidResult(g)&&(l++,a=JSON.stringify(g).length,c=g,u=m)}catch{}}c&&(this.extractedResult=c)}isValidResult(e){if(!e||typeof e!="object"||Array.isArray(e)||e.session_id||e.timestamp_ms||e.type||e.call_id||e.tool_call||e.result&&typeof e.result=="object"&&(e.result.success&&typeof e.result.success=="object"||e.result.error&&typeof e.result.error=="object")||e.args&&typeof e.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(e),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(e,t=null){let r=new s;r.zodSchema=t,r.processChunk(e),r.flush();let n=r.getResult();return!n&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),n}};import{z as
|
|
4
|
+
`,this.extractedResult=o)}catch{if(n.includes('"text"')||n.includes('"content"')){let i=n.match(/"text"\s*:\s*"([^"]*)/),c=n.match(/"content"\s*:\s*"([^"]*)/),a=i?i[1]:c?c[1]:null;a&&!this.rawText.includes(a)&&(r+=a,this.rawText+=a)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(i,c)=>{if(!i)return;let a=`${i}:${JSON.stringify(c??{})}`;this._lastToolEmit!==a&&(this._lastToolEmit=a,this.onToolCall(i,c??void 0))},r=i=>{if(i!=null){if(typeof i=="object"&&!Array.isArray(i))return i;if(typeof i=="string")try{return JSON.parse(i)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,r(e.input??e.arguments));return}let i=e.tool_call;if(i&&typeof i=="object"&&!Array.isArray(i)){let c=Object.keys(i);if(c.length===1){let a=c[0],l=i[a],u=l&&typeof l=="object"?l.args??l.input??l:void 0;t(a,r(u))}return}return}if(Array.isArray(e.tool_calls)){for(let i of e.tool_calls)t(i.name,r(i.input??i.arguments));return}let n=e.message??e;if(Array.isArray(n?.tool_calls)){for(let i of n.tool_calls)t(i.name,r(i.input??i.arguments));return}let o=n?.content??e.content;if(Array.isArray(o))for(let i of o)(i.type==="tool_use"||i.type==="tool_call")&&i.name&&t(i.name,r(i.input??i.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return e.type==="thinking"&&e.text||e.text?e.text:e.content&&typeof e.content=="string"?e.content:e.delta?e.delta:null}tryExtractResult(e){if(!e||typeof e!="string")return;let t=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,n;for(;(n=r.exec(e))!==null;){let m=n[1].trim();try{JSON.parse(m),t.push({text:m,source:"markdown"})}catch{}}let o=0,i=0;for(;o<e.length&&(o=e.indexOf("{",o),o!==-1);){let m=0,d=o;for(let f=o;f<e.length;f++)if(e[f]==="{")m++;else if(e[f]==="}"&&(m--,m===0)){d=f,t.push({text:e.substring(o,d+1),source:"brace"}),i++;break}o=d+1}let c=this.extractedResult,a=c?JSON.stringify(c).length:0,l=0,u=-1;for(let m=0;m<t.length;m++){let d=t[m];try{let f=d.text.replace(/,(\s*[}\]])/g,"$1"),g=JSON.parse(f);this.isValidResult(g)&&(l++,a=JSON.stringify(g).length,c=g,u=m)}catch{}}c&&(this.extractedResult=c)}isValidResult(e){if(!e||typeof e!="object"||Array.isArray(e)||e.session_id||e.timestamp_ms||e.type||e.call_id||e.tool_call||e.result&&typeof e.result=="object"&&(e.result.success&&typeof e.result.success=="object"||e.result.error&&typeof e.result.error=="object")||e.args&&typeof e.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(e),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(e,t=null){let r=new s;r.zodSchema=t,r.processChunk(e),r.flush();let n=r.getResult();return!n&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),n}};import{z as Jt}from"zod";import{zodToJsonSchema as fn}from"zod-to-json-schema";function dn(s){if(!s)return null;if(typeof Jt?.toJSONSchema=="function")try{return Jt.toJSONSchema(s)}catch{}try{return fn(s,{target:"openApi3"})}catch{return null}}var Qe=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=dn(e):r=e;let n=this._buildExample(r);return`
|
|
5
5
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
6
6
|
\u{1F6A8} MANDATORY: WRITE RESULT TO FILE \u{1F6A8}
|
|
7
7
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
@@ -37,9 +37,9 @@ ${s.slice(-i)}`);let a=`Extract and format the following information into struct
|
|
|
37
37
|
RAW CONTENT:
|
|
38
38
|
${c}
|
|
39
39
|
|
|
40
|
-
Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,l={model:
|
|
40
|
+
Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,l={model:J.OPENAI_POSTPROCESSING,messages:[{role:"user",content:a}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:o,strict:!0}}};p.info(`\u{1F4E4} Sending to OpenAI proxy: model=${J.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(o.properties||{}).join(", ")}`),p.debug(` Schema size: ${JSON.stringify(o).length} chars`),p.debug(` Prompt size: ${a.length} chars`);try{let u={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(u["x-proxy-token"]=t,u["x-execution-id"]=process.env.EXECUTION_ID||""):(u.Authorization=`Bearer ${t}`,u["x-api-key"]=process.env.ZIBBY_API_KEY||"",u["x-execution-id"]=process.env.EXECUTION_ID||"");let d=(await mn.post(r,l,{headers:u,timeout:qe.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!d)throw new Error("OpenAI proxy returned empty response");let f=JSON.parse(d);return p.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:f,raw:s}}catch(u){if(u.response){let m=u.response.status,d=u.response.data;throw p.error(`\u274C OpenAI proxy request failed: ${m}`),p.error(` Status: ${m}`),p.error(` Response: ${JSON.stringify(d,null,2)}`),m===401||m===403?new Error(`Authentication failed for OpenAI proxy.
|
|
41
41
|
Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
|
|
42
|
-
Response: ${JSON.stringify(d)}`,{cause:u}):new Error(`Failed to format Cursor output: ${d?.error?.message||"Unknown error"}`,{cause:u})}throw p.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}function Y(s){let e=`${s}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let r=t.split(/[,\n]+/).map(i=>i.trim()).filter(Boolean);if(r.length===0)return{picked:null,count:0,dispose:()=>{}};let n=r[Math.floor(Math.random()*r.length)],o=process.env[s];return process.env[s]=n,p.debug(`[auth-pool] ${s}: picked 1 of ${r.length} from pool (***${n.slice(-4)})`),{picked:n,count:r.length,dispose(){o===void 0?delete process.env[s]:process.env[s]=o}}}import{timeline as Z,Timeline as
|
|
42
|
+
Response: ${JSON.stringify(d)}`,{cause:u}):new Error(`Failed to format Cursor output: ${d?.error?.message||"Unknown error"}`,{cause:u})}throw p.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}function Y(s){let e=`${s}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let r=t.split(/[,\n]+/).map(i=>i.trim()).filter(Boolean);if(r.length===0)return{picked:null,count:0,dispose:()=>{}};let n=r[Math.floor(Math.random()*r.length)],o=process.env[s];return process.env[s]=n,p.debug(`[auth-pool] ${s}: picked 1 of ${r.length} from pool (***${n.slice(-4)})`),{picked:n,count:r.length,dispose(){o===void 0?delete process.env[s]:process.env[s]=o}}}import{timeline as Z,Timeline as Ri,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as Li}from"@zibby/agent-workflow";import{copyFileSync as _n,existsSync as ft,lstatSync as En,mkdirSync as Yt,rmSync as vn,symlinkSync as Tn,unlinkSync as An}from"node:fs";import{join as X}from"node:path";import{homedir as $n}from"node:os";import{randomBytes as In}from"node:crypto";var On=["cli-config.json","config.json","auth.json","argv.json"];function Ht(s){return!(!s||typeof s!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function Vt(s){let e=X(s||process.cwd(),".zibby","tmp");Yt(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${In(4).toString("hex")}`,r=X(e,`cursor-agent-home-${t}`),n=X(r,".cursor");Yt(n,{recursive:!0});let o=$n(),i=X(o,".cursor");if(ft(i))for(let c of On){let a=X(i,c);if(ft(a))try{_n(a,X(n,c))}catch{}}if(process.platform==="darwin"){let c=X(o,"Library");if(ft(c))try{Tn(c,X(r,"Library"))}catch{}}return r}function Wt(s){if(!(!s||typeof s!="string"))try{let e=X(s,"Library");try{En(e).isSymbolicLink()&&An(e)}catch{}vn(s,{recursive:!0,force:!0})}catch{}}var re=class extends Cn{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[V(Le(),".local","bin","cursor-agent"),V(Le(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"];for(let r of t)try{if(r.startsWith("/")){er(r,tr.X_OK);let n=te(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(n&&n.length>0)return p.debug(`[Cursor] Found agent at: ${r} (version: ${n.trim().slice(0,50)})`),!0}else{let n=te(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!n)continue;let o=te(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(o&&o.length>0)return p.debug(`[Cursor] Found '${r}' in PATH at ${n} (version: ${o.trim().slice(0,50)})`),!0}}catch{continue}return p.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:r=process.cwd(),print:n=!1,schema:o=null,skills:i=null,sessionPath:c=null,nodeName:a=null,timeout:l=qe.CURSOR_AGENT_DEFAULT,config:u={},signal:m=null}=t,d=u?.agent?.strictMode||!1,f=t.model??u?.agent?.cursor?.model??J.CURSOR,g=Y("CURSOR_API_KEY");try{p.debug(`[Cursor] Invoking (model: ${f}, timeout: ${l/1e3}s, skills: ${JSON.stringify(i)})`);let h=(this._setupMcpConfig(c,r,u,i,a)||{}).isolatedMcpHome??null,b=[V(Le(),".local","bin","cursor-agent"),V(Le(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"],w=null;for(let k of b)try{if(k.startsWith("/"))er(k,tr.X_OK),te(`"${k}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!te(`which ${k}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");te(`${k} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}w=k,p.debug(`[Agent] Using binary: ${k}`);break}catch(x){p.debug(`[Agent] Binary '${k}' check failed: ${x.message}`);continue}if(!w)throw new Error(`Cursor Agent CLI not found or not working.
|
|
43
43
|
|
|
44
44
|
Checked paths:
|
|
45
45
|
${b.map(k=>` - ${k}`).join(`
|
|
@@ -75,12 +75,12 @@ Stderr: ${f.slice(-1e3)}`:""}${d.trim()?`
|
|
|
75
75
|
Stdout (last 500 chars): ${d.slice(-500)}`:""}`));return}let A=k.getResult(),_=A?JSON.stringify(A,null,2):k.getRawText()||d||"";l({stdout:d||f||"",parsedText:_})}),T.on("error",x=>{if(R(),clearTimeout(B),clearInterval(P),E&&clearInterval(E),O&&clearTimeout(O),a&&!a.aborted)try{a.removeEventListener("abort",U)}catch{}u(new Error(`Cursor Agent spawn error: ${x.message}
|
|
76
76
|
Binary: ${e}
|
|
77
77
|
This usually means the binary is not in PATH. Try:
|
|
78
|
-
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};Me();import{AgentStrategy as Fn,getSkill as jn}from"@zibby/agent-workflow";import{query as Bn}from"@anthropic-ai/claude-agent-sdk";import{writeFileSync as dt,mkdirSync as mt,existsSync as or,readFileSync as sr}from"fs";import{homedir as ir}from"os";import{join as ge}from"path";var oe=class extends Fn{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!process.env.ANTHROPIC_API_KEY||!!process.env.ANTHROPIC_API_KEY_POOL,r=!!process.env.CLAUDE_CODE_OAUTH_TOKEN||!!process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,n=!!process.env.ANTHROPIC_AUTH_TOKEN||!!process.env.ANTHROPIC_AUTH_TOKEN_POOL,o=t||r||n;return o||p.debug("ClaudeAgentStrategy: no credentials. Set one of ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_AUTH_TOKEN (or a *_POOL variant for multi-token rotation)."),o}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:o=null,images:i=[],skills:c=null,sessionPath:a=null,nodeName:l=null,timeout:u,config:m={},signal:d=null,sessionId:f,resume:g,forkSession:y,sessionStore:h}=t,b=r;(!b||b==="auto")&&(p.debug(`Model is '${b||"undefined"}', using default: ${
|
|
78
|
+
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};Me();import{AgentStrategy as Fn,getSkill as jn}from"@zibby/agent-workflow";import{query as Bn}from"@anthropic-ai/claude-agent-sdk";import{writeFileSync as dt,mkdirSync as mt,existsSync as or,readFileSync as sr}from"fs";import{homedir as ir}from"os";import{join as ge}from"path";var oe=class extends Fn{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!process.env.ANTHROPIC_API_KEY||!!process.env.ANTHROPIC_API_KEY_POOL,r=!!process.env.CLAUDE_CODE_OAUTH_TOKEN||!!process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,n=!!process.env.ANTHROPIC_AUTH_TOKEN||!!process.env.ANTHROPIC_AUTH_TOKEN_POOL,o=t||r||n;return o||p.debug("ClaudeAgentStrategy: no credentials. Set one of ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_AUTH_TOKEN (or a *_POOL variant for multi-token rotation)."),o}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:o=null,images:i=[],skills:c=null,sessionPath:a=null,nodeName:l=null,timeout:u,config:m={},signal:d=null,sessionId:f,resume:g,forkSession:y,sessionStore:h}=t,b=r;(!b||b==="auto")&&(p.debug(`Model is '${b||"undefined"}', using default: ${J.CLAUDE}`),b=J.CLAUDE);let w=Ze[b]||b;Ze[b]&&b!==w&&p.debug(`Mapped model: ${b} \u2192 ${w}`);let v=[Y("ANTHROPIC_API_KEY"),Y("CLAUDE_CODE_OAUTH_TOKEN"),Y("ANTHROPIC_AUTH_TOKEN")];try{p.debug(`Invoking Claude Agent SDK with model: ${w}, skills: ${JSON.stringify(c)}`);let S=process.env.CLAUDE_CODE_OAUTH_TOKEN,I=process.env.ANTHROPIC_API_KEY,R=process.env.ANTHROPIC_AUTH_TOKEN;process.env.CLAUDE_CODE_CREDENTIALS_JSON?Jn(process.env.CLAUDE_CODE_CREDENTIALS_JSON):S&&Kn(S,process.env.__ZIBBY_CLAUDE_PLAN);let N=process.env.__ZIBBY_CLAUDE_PLAN,T=N?N.charAt(0).toUpperCase()+N.slice(1):null,O;S?O=T?`Claude ${T} plan \xB7 ***${S.slice(-4)}`:`Subscription \xB7 ***${S.slice(-4)}`:I?O=`API key \xB7 ***${I.slice(-4)}`:R?O=`Bearer \xB7 ***${R.slice(-4)}`:O="NONE \u2014 request will fail";let U=(await import("chalk")).default;console.log(""),console.log(` ${U.cyan("\u25C6")} ${U.bold(w)}`),console.log(` ${U.dim("Auth: ")}${O}`),console.log(` ${U.dim("Workdir: ")}${n}`),console.log(""),console.log(U.bold("Prompt sent to LLM:")),console.log(U.dim("\u2500".repeat(60))),console.log(U.dim(e)),console.log(U.dim("\u2500".repeat(60)));let{allowedTools:E,mcpServers:C}=this._resolveSkills(c,{sessionPath:a,workspace:n,nodeName:l});try{let $={cwd:n,allowedTools:E,settings:{permissions:{allow:["Bash(*)","Read(*)","Write(*)","Edit(*)","MultiEdit(*)","NotebookEdit(*)","Grep(*)","Glob(*)","WebFetch(*)","WebSearch(*)","Task(*)","TodoWrite(*)","Skill(*)"]}},model:w,...Object.keys(C).length>0&&{mcpServers:C},...f&&{sessionId:f},...g&&{resume:g},...y&&{forkSession:!0},...h&&{sessionStore:h}};if(o){let L=typeof o.parse=="function"?ne(o):o;$.outputFormat={type:"json_schema",schema:L},p.debug("Structured output enforced via SDK outputFormat")}p.debug(`Agent SDK options: ${JSON.stringify({cwd:$.cwd,toolCount:E.length,permissionMode:$.permissionMode,model:$.model,hasOutputFormat:!!$.outputFormat})}`);let P="",B=0,k=[];p.debug("Starting Claude Agent SDK query stream");let x;try{x=Bn({prompt:e,options:$})}catch(_){throw p.error(`Failed to initialize Claude Agent SDK: ${_.message}`),_}let M=null,j=0,A=3;if(d?.aborted){let _=new Error("Aborted via signal");throw _.name="AbortError",_}try{for await(let _ of x){if(d?.aborted){let D=new Error("Aborted via signal");throw D.name="AbortError",D}if(k.push(_),_.type==="system"&&_.subtype==="init"){let D=_.mcp_servers||[];if(D.length>0){let F=D.map(G=>`${G.name}=${G.status}${G.error?` (${String(G.error).slice(0,120)})`:""}`).join(", ");p.info(`[mcp] SDK init \u2014 ${D.length} server(s): ${F}`);for(let G of D)G.status!=="connected"&&p.warn(`[mcp] server '${G.name}' did not connect: status=${G.status}`,{name:G.name,status:G.status,error:G.error})}else Object.keys(C||{}).length>0&&p.warn(`[mcp] SDK init returned no mcp_servers despite passing ${Object.keys(C).length} server(s) \u2014 SDK version may not expose this field, or config was dropped`);if(Array.isArray(_.tools)){let F=_.tools.filter(G=>G.startsWith("mcp__"));F.length>0?p.info(`[mcp] tools visible to model: ${F.join(", ")}`):Object.keys(C||{}).length>0&&p.warn("[mcp] no mcp__* tools in model's tool list \u2014 MCP servers configured but tools didn't reach the prompt")}}if(_.type==="error"||_.error){let D=_.error?.message||_.error||_.message||"Unknown API error";try{p.error("SDK error event raw payload",{fullMessage:JSON.stringify(_,null,2)})}catch{}throw new Error(typeof D=="string"?D:JSON.stringify(D))}let L=JSON.stringify(_.message?.content||_.text||"").slice(0,200);if(L===M){if(j++,j>=A){let D=(_.message?.content?.[0]?.text||_.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${j}x repeated): ${D}`)}}else M=L,j=1;if(_.type==="assistant"||_.constructor?.name==="AssistantMessage"){let D=_.message?.content||_.content||[];for(let F of D)if(F.type==="thinking"&&F.thinking)console.log(`${F.thinking.substring(0,200)}${F.thinking.length>200?"...":""}`);else if(F.type==="text"&&F.text)P+=F.text,F.text.length<500?console.log(`${F.text}`):console.log(`${F.text.substring(0,200)}... (${F.text.length} chars)`);else if(F.type==="tool_use"){B++,F.name.includes("memory")?Z.stepMemory(`Tool: ${F.name}`):Z.stepTool(`Tool: ${F.name}`);let Oe=JSON.stringify(F.input).substring(0,100);console.log(` Input: ${Oe}${JSON.stringify(F.input).length>100?"...":""}`)}}else if(!(_.type==="user"&&_.tool_use_result)){if(_.type==="result"||_.constructor?.name==="ResultMessage"){let D=_.result||_.text||_.content||P;try{Gn({message:_,sessionPath:a,nodeName:l,model:b,toolCallCount:B})}catch(F){p.debug(`usage.json write failed: ${F.message}`)}if(o){if(_.structured_output){p.debug("Using SDK native structured_output");let G=typeof o.parse=="function"?o.parse(_.structured_output):_.structured_output;return{raw:D,structured:G}}if(D){let F=this._extractJson(D,o);if(F)return{raw:D,structured:F}}p.warn(`Could not extract structured output \u2014 returning raw text (${(D||"").length} chars)`)}return D||""}}}if(p.warn(`Agent SDK ended without result. Collected ${k.length} messages`),P.length>0)return p.debug("Returning accumulated text from messages"),P;throw new Error("Claude Agent SDK query ended without result")}catch(_){let L={message:_?.message,name:_?.name,code:_?.code,cause:_?.cause?.message||_?.cause,stack:_?.stack?.split(`
|
|
79
79
|
`).slice(0,5).join(`
|
|
80
|
-
`),stringified:(()=>{try{return JSON.stringify(_,Object.getOwnPropertyNames(Object(_)))}catch{return String(_)}})()};throw p.error(`Error during query stream: ${_?.message||_}`,L),_}}catch($){throw p.error("Claude Agent SDK call failed",{message:$?.message,name:$?.name,code:$?.code,cause:$?.cause?.message||$?.cause}),$}}finally{for(let S of v)S.dispose()}}_resolveSkills(e,t){let r=["Read","Write","Edit","Bash","Grep","Glob"];if(e===null)return p.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return p.debug("Default IDE skills for code generation"),{allowedTools:[...r],mcpServers:{}};let n=[...r],o={};for(let i of e){let c=jn(i);if(!c){p.warn(`Unknown skill "${i}" \u2014 skipping`);continue}if(c.allowedTools&&n.push(...c.allowedTools),typeof c.resolve=="function"){let a=c.resolve(t);a&&(o[c.serverName]=a,p.debug(`MCP: ${c.serverName} \u2192 ${a.command} ${a.args[0]}`))}}return{allowedTools:n,mcpServers:o}}_extractJson(e,t){let r=[()=>{if(e.includes("===JSON_START===")){let n=e.indexOf("===JSON_START===")+16,o=e.indexOf("===JSON_END===");return e.substring(n,o).trim()}},()=>e.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!e.startsWith("{"))return e.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>e.trim(),()=>{let n=e.indexOf("{"),o=e.lastIndexOf("}");if(n!==-1&&o>n)return e.substring(n,o+1)}];for(let n of r)try{let o=n();if(!o)continue;let i=JSON.parse(o);if(typeof i!="object"||i===null)continue;return typeof t.parse=="function"?t.parse(i):i}catch{}return null}};function Gn({message:s,sessionPath:e,nodeName:t,model:r,toolCallCount:n}){if(!e||!t)return;let o=s?.usage||s?.message?.usage||{},i=Ue(o.input_tokens,o.inputTokens),c=Ue(o.output_tokens,o.outputTokens),a=Ue(o.cache_read_input_tokens,o.cacheReadInputTokens),l=Ue(o.cache_creation_input_tokens,o.cacheCreationInputTokens),u=Ue(s?.duration_ms,s?.durationMs),m={model:r||null,input_tokens:i,output_tokens:c,cache_read_tokens:a,cache_creation_tokens:l,tool_call_count:typeof n=="number"?n:null,duration_ms:u,captured_at:new Date().toISOString()},d=ge(e,t);try{mt(d,{recursive:!0})}catch{}dt(ge(d,"usage.json"),JSON.stringify(m,null,2),"utf-8")}function Ue(...s){for(let e of s){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e)))return Number(e)}return null}function
|
|
80
|
+
`),stringified:(()=>{try{return JSON.stringify(_,Object.getOwnPropertyNames(Object(_)))}catch{return String(_)}})()};throw p.error(`Error during query stream: ${_?.message||_}`,L),_}}catch($){throw p.error("Claude Agent SDK call failed",{message:$?.message,name:$?.name,code:$?.code,cause:$?.cause?.message||$?.cause}),$}}finally{for(let S of v)S.dispose()}}_resolveSkills(e,t){let r=["Read","Write","Edit","Bash","Grep","Glob"];if(e===null)return p.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return p.debug("Default IDE skills for code generation"),{allowedTools:[...r],mcpServers:{}};let n=[...r],o={};for(let i of e){let c=jn(i);if(!c){p.warn(`Unknown skill "${i}" \u2014 skipping`);continue}if(c.allowedTools&&n.push(...c.allowedTools),typeof c.resolve=="function"){let a=c.resolve(t);a&&(o[c.serverName]=a,p.debug(`MCP: ${c.serverName} \u2192 ${a.command} ${a.args[0]}`))}}return{allowedTools:n,mcpServers:o}}_extractJson(e,t){let r=[()=>{if(e.includes("===JSON_START===")){let n=e.indexOf("===JSON_START===")+16,o=e.indexOf("===JSON_END===");return e.substring(n,o).trim()}},()=>e.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!e.startsWith("{"))return e.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>e.trim(),()=>{let n=e.indexOf("{"),o=e.lastIndexOf("}");if(n!==-1&&o>n)return e.substring(n,o+1)}];for(let n of r)try{let o=n();if(!o)continue;let i=JSON.parse(o);if(typeof i!="object"||i===null)continue;return typeof t.parse=="function"?t.parse(i):i}catch{}return null}};function Gn({message:s,sessionPath:e,nodeName:t,model:r,toolCallCount:n}){if(!e||!t)return;let o=s?.usage||s?.message?.usage||{},i=Ue(o.input_tokens,o.inputTokens),c=Ue(o.output_tokens,o.outputTokens),a=Ue(o.cache_read_input_tokens,o.cacheReadInputTokens),l=Ue(o.cache_creation_input_tokens,o.cacheCreationInputTokens),u=Ue(s?.duration_ms,s?.durationMs),m={model:r||null,input_tokens:i,output_tokens:c,cache_read_tokens:a,cache_creation_tokens:l,tool_call_count:typeof n=="number"?n:null,duration_ms:u,captured_at:new Date().toISOString()},d=ge(e,t);try{mt(d,{recursive:!0})}catch{}dt(ge(d,"usage.json"),JSON.stringify(m,null,2),"utf-8")}function Ue(...s){for(let e of s){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e)))return Number(e)}return null}function Kn(s,e){let t=ge(ir(),".claude"),r=ge(t,".credentials.json"),n={claudeAiOauth:{accessToken:s,...e?{subscriptionType:String(e).toLowerCase()}:{}}};try{if(or(r)&&JSON.parse(sr(r,"utf-8"))?.claudeAiOauth?.accessToken===s)return;mt(t,{recursive:!0}),dt(r,JSON.stringify(n,null,2),"utf-8"),p.debug(`Wrote Claude Code OAuth credentials to ${r}`)}catch(o){p.warn(`Could not write ${r}: ${o.message} \u2014 Claude SDK may fail to authenticate.`)}}function Jn(s){let e=ge(ir(),".claude"),t=ge(e,".credentials.json"),r;try{r=JSON.parse(s)}catch(n){p.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${n.message}`);return}if(!r?.claudeAiOauth?.accessToken){p.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if(or(t)){let n=JSON.parse(sr(t,"utf-8"));if(n?.claudeAiOauth?.accessToken===r.claudeAiOauth.accessToken&&n?.claudeAiOauth?.expiresAt===r.claudeAiOauth.expiresAt)return}mt(e,{recursive:!0}),dt(t,JSON.stringify(r,null,2),"utf-8"),p.debug(`Wrote full Claude Code credentials blob to ${t}`)}catch(n){p.warn(`Could not write ${t}: ${n.message} \u2014 Claude SDK may fail to authenticate.`)}}Me();import{AgentStrategy as zn,getSkill as Yn}from"@zibby/agent-workflow";import{execSync as Hn}from"node:child_process";var se=class extends zn{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY_POOL||process.env.CODEX_API_KEY||process.env.CODEX_API_KEY_POOL))return p.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return Hn("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return p.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:o=null,skills:i=null,sessionPath:c=null,nodeName:a=null,timeout:l,config:u={},signal:m=null}=t,d=[Y("OPENAI_API_KEY"),Y("CODEX_API_KEY")];try{let{Codex:f}=await import("@openai/codex-sdk"),g=r;(!g||g==="auto")&&(p.debug(`Model is '${g||"undefined"}', using default: ${J.CODEX}`),g=J.CODEX);let y=Xe[g]||g;Xe[g]&&g!==y&&p.debug(`Mapped model: ${g} \u2192 ${y}`),p.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
81
|
\u25C6 Model: ${y}${b}
|
|
82
82
|
`);let w=(await import("chalk")).default;console.log(`
|
|
83
|
-
${w.bold("Prompt sent to LLM:")}`),console.log(w.dim("\u2500".repeat(60))),console.log(w.dim(e)),console.log(w.dim("\u2500".repeat(60)));let v=this._resolveSkillsToMcp(i,{sessionPath:c,workspace:n,nodeName:a}),S={};Object.keys(v).length>0&&(S.mcp_servers=v,p.debug(`[Codex] MCP servers: ${Object.keys(v).join(", ")}`));let R=new f({...Object.keys(S).length>0&&{config:S}}).startThread({workingDirectory:n,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),N=o&&typeof o.parse=="function",T={};if(o)try{let O=N?ne(o,{target:"openAi"}):o;T.outputSchema=O,p.debug("Structured output via SDK outputSchema")}catch(O){p.warn(`[Codex] Schema conversion failed, will extract from text: ${O.message}`)}if(m?.aborted){let O=new Error("Aborted via signal");throw O.name="AbortError",O}try{let{events:O}=await R.runStreamed(e,T),U=0,E="";for await(let C of O){if(m?.aborted){let P=new Error("Aborted via signal");throw P.name="AbortError",P}let $=C.type;if($==="item.completed"){let P=C.item,B=P?.type;if(B==="mcp_tool_call"){U++;let k=`${P.server}/${P.tool}`;if(Z.stepTool(`Tool: ${k}`),P.arguments){let x=JSON.stringify(P.arguments),M=x.length>100?`${x.substring(0,100)}...`:x;console.log(` Input: ${M}`)}}else if(B==="tool_call"||B==="function_call"||B==="command_execution"){U++;let k=P.name||P.tool||P.command||"unknown";Z.stepTool(`Tool: ${k}`)}else B==="agent_message"&&(E=P.text||"",E.length<500?console.log(E):console.log(`${E.substring(0,200)}... (${E.length} chars)`))}else $==="turn.completed"?p.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(C.usage||{})}`):p.debug(`[Codex] Event: ${$} ${JSON.stringify(C).slice(0,300)}`)}if(p.debug(`[Codex] Last agent message (${E.length} chars): ${E.slice(0,500)}`),o){if(!E)throw new Error("Codex agent returned no response");let C=JSON.parse(E),$=N?o.parse(C):C;return p.debug("\u2705 [Codex] Structured output validated"),{raw:E,structured:$}}return E||""}catch(O){let U=O.message||String(O);throw p.error(`\u274C [Codex] SDK call failed: ${U}`),U.includes("exited with code")&&(p.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),p.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),O}}finally{for(let f of d)f.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let o=Yn(n);if(!o){p.warn(`[Codex] Unknown skill "${n}" \u2014 skipping`);continue}if(typeof o.resolve!="function")continue;let i=o.resolve(t);if(!i)continue;let c=o.serverName||n,a={command:i.command};i.args?.length&&(a.args=i.args),i.env&&Object.keys(i.env).length>0&&(a.env=i.env),r[c]=a,p.debug(`[Codex] MCP: ${c} \u2192 ${i.command} ${(i.args||[]).join(" ")}`)}return r}};Me();import{AgentStrategy as Vn,getSkill as Wn}from"@zibby/agent-workflow";import{execSync as Zn,spawn as Xn}from"node:child_process";import{existsSync as ar,mkdirSync as lr,readFileSync as cr,rmSync as qn,writeFileSync as ur}from"node:fs";import{join as ie}from"node:path";function Qn(s){if(!s)return null;let e=String(s),t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t?.[1])try{return JSON.parse(t[1].trim())}catch{}let r=e.indexOf("{");if(r<0)return null;let n=0,o=!1,i=!1,c=-1;for(let a=r;a<e.length;a++){let l=e[a];if(o){i?i=!1:l==="\\"?i=!0:l==='"'&&(o=!1);continue}if(l==='"'){o=!0;continue}if(l==="{"){n===0&&(c=a),n+=1;continue}if(l==="}"){if(n===0)continue;if(n-=1,n===0&&c>=0){let u=e.slice(c,a+1);try{return JSON.parse(u)}catch{c=-1}}}}return null}function eo(s){let e=String(s||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return Qn(e)}}function to(s){try{let e=JSON.parse(s);if(typeof e=="string")return e;if(typeof e?.response=="string")return e.response;if(typeof e?.text=="string")return e.text;if(typeof e?.output=="string")return e.output;if(Array.isArray(e?.candidates)&&e.candidates.length>0){let t=e.candidates[0];if(typeof t?.content=="string")return t.content;if(Array.isArray(t?.content?.parts)){let r=t.content.parts.map(n=>typeof n?.text=="string"?n.text:"").join("");if(r.trim())return r}}}catch{}return s}var ae=class extends Vn{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GEMINI_API_KEY_POOL||process.env.GOOGLE_API_KEY||process.env.GOOGLE_API_KEY_POOL))return p.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return Zn("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return p.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:o=null,skills:i=null,sessionPath:c=null,nodeName:a=null,timeout:l=600*1e3,signal:u=null}=t,m=[Y("GEMINI_API_KEY"),Y("GOOGLE_API_KEY")];try{let d=r;(!d||d==="auto")&&(d=
|
|
83
|
+
${w.bold("Prompt sent to LLM:")}`),console.log(w.dim("\u2500".repeat(60))),console.log(w.dim(e)),console.log(w.dim("\u2500".repeat(60)));let v=this._resolveSkillsToMcp(i,{sessionPath:c,workspace:n,nodeName:a}),S={};Object.keys(v).length>0&&(S.mcp_servers=v,p.debug(`[Codex] MCP servers: ${Object.keys(v).join(", ")}`));let R=new f({...Object.keys(S).length>0&&{config:S}}).startThread({workingDirectory:n,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),N=o&&typeof o.parse=="function",T={};if(o)try{let O=N?ne(o,{target:"openAi"}):o;T.outputSchema=O,p.debug("Structured output via SDK outputSchema")}catch(O){p.warn(`[Codex] Schema conversion failed, will extract from text: ${O.message}`)}if(m?.aborted){let O=new Error("Aborted via signal");throw O.name="AbortError",O}try{let{events:O}=await R.runStreamed(e,T),U=0,E="";for await(let C of O){if(m?.aborted){let P=new Error("Aborted via signal");throw P.name="AbortError",P}let $=C.type;if($==="item.completed"){let P=C.item,B=P?.type;if(B==="mcp_tool_call"){U++;let k=`${P.server}/${P.tool}`;if(Z.stepTool(`Tool: ${k}`),P.arguments){let x=JSON.stringify(P.arguments),M=x.length>100?`${x.substring(0,100)}...`:x;console.log(` Input: ${M}`)}}else if(B==="tool_call"||B==="function_call"||B==="command_execution"){U++;let k=P.name||P.tool||P.command||"unknown";Z.stepTool(`Tool: ${k}`)}else B==="agent_message"&&(E=P.text||"",E.length<500?console.log(E):console.log(`${E.substring(0,200)}... (${E.length} chars)`))}else $==="turn.completed"?p.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(C.usage||{})}`):p.debug(`[Codex] Event: ${$} ${JSON.stringify(C).slice(0,300)}`)}if(p.debug(`[Codex] Last agent message (${E.length} chars): ${E.slice(0,500)}`),o){if(!E)throw new Error("Codex agent returned no response");let C=JSON.parse(E),$=N?o.parse(C):C;return p.debug("\u2705 [Codex] Structured output validated"),{raw:E,structured:$}}return E||""}catch(O){let U=O.message||String(O);throw p.error(`\u274C [Codex] SDK call failed: ${U}`),U.includes("exited with code")&&(p.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),p.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),O}}finally{for(let f of d)f.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let n of e){let o=Yn(n);if(!o){p.warn(`[Codex] Unknown skill "${n}" \u2014 skipping`);continue}if(typeof o.resolve!="function")continue;let i=o.resolve(t);if(!i)continue;let c=o.serverName||n,a={command:i.command};i.args?.length&&(a.args=i.args),i.env&&Object.keys(i.env).length>0&&(a.env=i.env),r[c]=a,p.debug(`[Codex] MCP: ${c} \u2192 ${i.command} ${(i.args||[]).join(" ")}`)}return r}};Me();import{AgentStrategy as Vn,getSkill as Wn}from"@zibby/agent-workflow";import{execSync as Zn,spawn as Xn}from"node:child_process";import{existsSync as ar,mkdirSync as lr,readFileSync as cr,rmSync as qn,writeFileSync as ur}from"node:fs";import{join as ie}from"node:path";function Qn(s){if(!s)return null;let e=String(s),t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t?.[1])try{return JSON.parse(t[1].trim())}catch{}let r=e.indexOf("{");if(r<0)return null;let n=0,o=!1,i=!1,c=-1;for(let a=r;a<e.length;a++){let l=e[a];if(o){i?i=!1:l==="\\"?i=!0:l==='"'&&(o=!1);continue}if(l==='"'){o=!0;continue}if(l==="{"){n===0&&(c=a),n+=1;continue}if(l==="}"){if(n===0)continue;if(n-=1,n===0&&c>=0){let u=e.slice(c,a+1);try{return JSON.parse(u)}catch{c=-1}}}}return null}function eo(s){let e=String(s||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return Qn(e)}}function to(s){try{let e=JSON.parse(s);if(typeof e=="string")return e;if(typeof e?.response=="string")return e.response;if(typeof e?.text=="string")return e.text;if(typeof e?.output=="string")return e.output;if(Array.isArray(e?.candidates)&&e.candidates.length>0){let t=e.candidates[0];if(typeof t?.content=="string")return t.content;if(Array.isArray(t?.content?.parts)){let r=t.content.parts.map(n=>typeof n?.text=="string"?n.text:"").join("");if(r.trim())return r}}}catch{}return s}var ae=class extends Vn{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GEMINI_API_KEY_POOL||process.env.GOOGLE_API_KEY||process.env.GOOGLE_API_KEY_POOL))return p.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return Zn("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return p.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:r,workspace:n=process.cwd(),schema:o=null,skills:i=null,sessionPath:c=null,nodeName:a=null,timeout:l=600*1e3,signal:u=null}=t,m=[Y("GEMINI_API_KEY"),Y("GOOGLE_API_KEY")];try{let d=r;(!d||d==="auto")&&(d=J.GEMINI);let f=pt[d]||d,g=String(process.env.GEMINI_API_KEY||"").trim(),y=String(process.env.GOOGLE_API_KEY||"").trim(),h=this._resolveSkillsToMcp(i,{sessionPath:c,workspace:n,nodeName:a}),b=Object.keys(h).length>0,w=new de(e),v=o&&typeof o.parse=="function",S=null;if(o){let A;try{let _=v?ne(o,{target:"openAi"}):o;A=JSON.stringify(_,null,2)}catch{A="{}"}if(b){w.addSystemInstruction(`Write valid JSON that matches this schema:
|
|
84
84
|
${A}`,"schema_instruction","append");let _=`zibby-result-${Date.now()}.json`,L=ie(n,".zibby","tmp");S=ie(L,_),lr(L,{recursive:!0}),w.addStructuredOutput(o,S)}else w.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
|
|
85
85
|
${A}`,"json_instruction","append")}let I=w.build(),R=w.getUserPrompt(),N=w.getStats(),T=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),O=T?` | key: ***${T.slice(-4)}`:" | key: not set";console.log(`
|
|
86
86
|
\u25C6 Model: ${f||"auto"}${O}
|
|
@@ -95,7 +95,7 @@ ${x.slice(0,1e3)}`),M=eo(x)),!M)throw k||(p.error("[Gemini] Failed to extract va
|
|
|
95
95
|
`);f=w.pop();for(let v of w){if(!v.startsWith("data: "))continue;let S=v.slice(6).trim();if(S==="[DONE]")continue;let I;try{I=JSON.parse(S)}catch{continue}let R=I.choices?.[0]?.delta;if(R&&(R.content&&(g+=R.content,r.onToken&&r.onToken(R.content)),R.tool_calls))for(let N of R.tool_calls){let T=N.index??0;y.has(T)||y.set(T,{id:"",name:"",args:""});let O=y.get(T);N.id&&(O.id=N.id),N.function?.name&&(O.name=N.function.name),N.function?.arguments!=null&&(O.args+=N.function.arguments)}}}if(y.size>0){let h=[...y.entries()].sort(([b],[w])=>b-w).map(([,b])=>({id:b.id,type:"function",function:{name:b.name,arguments:b.args}}));return{choices:[{message:{role:"assistant",content:g||null,tool_calls:h}}]}}return{choices:[{message:{role:"assistant",content:g}}]}}#e(e={}){let t=[e.signal,e.timeout?AbortSignal.timeout(e.timeout):null].filter(Boolean);return t.length>1?AbortSignal.any(t):t[0]||void 0}};import{Client as no}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as oo}from"@modelcontextprotocol/sdk/client/stdio.js";var Fe=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:r,args:n=[],env:o={}}=t;p.debug(`[MCP] Starting ${e}: ${r} ${n.join(" ")}`);let i=new oo({command:r,args:n,env:{...process.env,...o}}),c=new no({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await c.connect(i);let a={client:c,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`);p.debug(`[MCP] ${e}.${t}(${JSON.stringify(r).slice(0,200)})`);let o=await n.client.callTool({name:t,arguments:r});return{text:o.content?.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
96
96
|
`)||"",isError:o.isError||!1}}isRunning(e){return this.#e.has(e)}async stopServer(e){let t=this.#e.get(e);if(t){try{await t.client.close()}catch(r){p.debug(`[MCP] Error closing ${e}: ${r.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}};import{existsSync as so,readFileSync as io}from"node:fs";import{join as ao}from"node:path";import{homedir as lo}from"node:os";function co(){try{let s=ao(lo(),".zibby","config.json");return so(s)?JSON.parse(io(s,"utf-8")):{}}catch{return{}}}function rt(s){return String(s||"").replace(/\/v1\/?$/,"")}function uo(s,e){let t=process.env.OPENAI_PROXY_URL;if(t)return rt(t);if(s==="session")return e.proxyUrl?rt(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(s==="byok"){let r=process.env.OPENAI_BASE_URL;return rt(r||"https://api.openai.com")}return rt(t||"")}function yt(){let s=co(),e=process.env.ZIBBY_USER_TOKEN||s.sessionToken||null,t=process.env.OPENAI_API_KEY||null,r=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),n=process.env.OPENAI_PROXY_NO_AUTH==="true",o=process.env.OPENAI_PROXY_URL,i="session";r==="byok"||r==="local"||r==="session"?i=r:e?i="session":t?i="byok":o&&n&&(i="local");let c=uo(i,s),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(!c)return{ok:!1,mode:i,reason:"missing_openai_proxy_url"};!n&&t&&(a.Authorization=`Bearer ${t}`)}return c?{ok:!0,mode:i,baseUrl:c,headers:a,tokenPreview:a.Authorization?`***${a.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:i,reason:"missing_base_url"}}function nt(s,e){let t=String(s??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
|
|
97
97
|
|
|
98
|
-
[tool result truncated for size]`}function po(s,e){if(typeof s=="string")return nt(s,e);try{return nt(JSON.stringify(s),e)}catch{return nt(String(s),e)}}function dr(s){let e=new Set;for(let n of s)if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let o of n.tool_calls)e.add(o.id);let t=s.filter(n=>n.role==="tool"?e.has(n.tool_call_id):!0),r=new Set;for(let n of t)n.role==="tool"&&r.add(n.tool_call_id);return t.map(n=>{if(n.role!=="assistant"||!Array.isArray(n.tool_calls)||n.tool_calls.every(a=>r.has(a.id)))return n;let{tool_calls:i,...c}=n;return{...c,content:c.content||""}})}function fo(s){let e=Array.isArray(s?.messages)?s.messages:[],t=e.find(o=>o.role==="system"),r=e.slice(-4).map(o=>({...o,content:nt(o.content,o.role==="tool"?1200:2500)}));r=dr(r);let n={...s,messages:[t,...r].filter(Boolean)};return delete n.tools,n}async function mo({body:s,streaming:e,auth:t,options:r,fetchCompletion:n,fetchStreamingCompletion:o,onFallbackLog:i}){try{return e?await o(s,t,r):await n(s,t,r)}catch(c){let a=String(c?.message||c||"");if(!/proxy error 413|payload too large/i.test(a))throw c;let l=fo(s);return typeof i=="function"&&i(s,l),{data:e?await o(l,t,r):await n(l,t,r),fallback:l}}}async function mr({body:s,auth:e,options:t,streaming:r,toolContext:n,activeSkills:o,round:i,verbose:c,dependencies:a,config:l={}}){let u=l.maxToolResultChars||3e3,{fetchCompletion:m,fetchStreamingCompletion:d,onFallbackLog:f,hasToolCalls:g,getTextContent:y,parseToolCalls:h,buildAssistantMessage:b,buildToolResultMessage:w,executeTool:v,onToolCallLog:S,injectTools:I}=a;Array.isArray(s?.messages)&&(s.messages=dr(s.messages));let R=await mo({body:s,streaming:r,auth:e,options:t,fetchCompletion:m,fetchStreamingCompletion:d,onFallbackLog:f}),N=R?.data||R;if(!g(N))return{done:!0,text:y(N),body:R?.fallback||s};let T=h(N),O=R?.fallback||s;O.messages.push(b(N)),c&&typeof S=="function"&&S(T);let U=await Promise.all(T.map((E,C)=>(typeof t.onToolCall=="function"&&t.onToolCall(E.name,E.args,{round:i,index:C,total:T.length}),v(E,n))));for(let E=0;E<T.length;E++){let $=T[E].name==="get_skill_context"?typeof U[E]=="string"?U[E]:JSON.stringify(U[E]):po(U[E],u);O.messages.push(w(T[E].id,$))}return typeof t.onToolCall=="function"&&t.onToolCall(null),I(O,o),{done:!1,body:O}}var ho=
|
|
98
|
+
[tool result truncated for size]`}function po(s,e){if(typeof s=="string")return nt(s,e);try{return nt(JSON.stringify(s),e)}catch{return nt(String(s),e)}}function dr(s){let e=new Set;for(let n of s)if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let o of n.tool_calls)e.add(o.id);let t=s.filter(n=>n.role==="tool"?e.has(n.tool_call_id):!0),r=new Set;for(let n of t)n.role==="tool"&&r.add(n.tool_call_id);return t.map(n=>{if(n.role!=="assistant"||!Array.isArray(n.tool_calls)||n.tool_calls.every(a=>r.has(a.id)))return n;let{tool_calls:i,...c}=n;return{...c,content:c.content||""}})}function fo(s){let e=Array.isArray(s?.messages)?s.messages:[],t=e.find(o=>o.role==="system"),r=e.slice(-4).map(o=>({...o,content:nt(o.content,o.role==="tool"?1200:2500)}));r=dr(r);let n={...s,messages:[t,...r].filter(Boolean)};return delete n.tools,n}async function mo({body:s,streaming:e,auth:t,options:r,fetchCompletion:n,fetchStreamingCompletion:o,onFallbackLog:i}){try{return e?await o(s,t,r):await n(s,t,r)}catch(c){let a=String(c?.message||c||"");if(!/proxy error 413|payload too large/i.test(a))throw c;let l=fo(s);return typeof i=="function"&&i(s,l),{data:e?await o(l,t,r):await n(l,t,r),fallback:l}}}async function mr({body:s,auth:e,options:t,streaming:r,toolContext:n,activeSkills:o,round:i,verbose:c,dependencies:a,config:l={}}){let u=l.maxToolResultChars||3e3,{fetchCompletion:m,fetchStreamingCompletion:d,onFallbackLog:f,hasToolCalls:g,getTextContent:y,parseToolCalls:h,buildAssistantMessage:b,buildToolResultMessage:w,executeTool:v,onToolCallLog:S,injectTools:I}=a;Array.isArray(s?.messages)&&(s.messages=dr(s.messages));let R=await mo({body:s,streaming:r,auth:e,options:t,fetchCompletion:m,fetchStreamingCompletion:d,onFallbackLog:f}),N=R?.data||R;if(!g(N))return{done:!0,text:y(N),body:R?.fallback||s};let T=h(N),O=R?.fallback||s;O.messages.push(b(N)),c&&typeof S=="function"&&S(T);let U=await Promise.all(T.map((E,C)=>(typeof t.onToolCall=="function"&&t.onToolCall(E.name,E.args,{round:i,index:C,total:T.length}),v(E,n))));for(let E=0;E<T.length;E++){let $=T[E].name==="get_skill_context"?typeof U[E]=="string"?U[E]:JSON.stringify(U[E]):po(U[E],u);O.messages.push(w(T[E].id,$))}return typeof t.onToolCall=="function"&&t.onToolCall(null),I(O,o),{done:!1,body:O}}var ho=J.ASSISTANT,yo=15,bt="get_skill_context";function Se(s){!s||typeof s!="object"||(s.type==="object"&&s.properties&&(s.required=Object.keys(s.properties),s.additionalProperties=!1,Object.values(s.properties).forEach(Se)),s.type==="array"&&s.items&&Se(s.items),s.anyOf&&s.anyOf.forEach(Se),s.oneOf&&s.oneOf.forEach(Se),s.allOf&&s.allOf.forEach(Se))}var gr={maxBytes:49e3,systemMaxChars:12e3},be=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",bo=s=>Buffer.byteLength(JSON.stringify(s),"utf8");function st(s){return Array.isArray(s)?new Set(s.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function So(s){return Array.isArray(s)?s.map(e=>String(e||"").trim()).filter(Boolean):[]}var ce=class extends go{#e;#t;#r=new Fe;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new le,this.#t=e.completionProvider||new ye):(this.#e=e||new le,this.#t=new ye)}canHandle(e){return yt().ok}async invoke(e,t={}){let r=Y("OPENAI_API_KEY");try{let n=t.model&&t.model!=="auto"?t.model:ho,o=yt();if(!o.ok)throw o.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):o.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):o.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${o.reason}).`);let i=t.messages||[{role:"user",content:e}],c=o.baseUrl,a=be();if(a?await this.#m(i,n,c,o.tokenPreview||"none"):p.debug(`[Assistant] ${c} | model: ${n} | messages: ${i.length}`),t.schema)return this.#c(n,i,o,t);let l=t.activeSkills||[],u=this.#p(t),m=this.#f(l,u),d=this.#d(m),f=this.#u(t),g={...t,payloadCompaction:f},y={activeSkills:m,options:g,executionRegistry:d,capabilityPolicy:u},h=!!t.stream,b={model:n,messages:[...i],stream:!1};this.#o(b,m,u);for(let w=0;w<yo;w++){if(t.signal?.aborted){let S=new Error("Aborted via signal");throw S.name="AbortError",S}let v=await mr({body:b,auth:o,options:g,streaming:h,toolContext:y,activeSkills:m,round:w,verbose:a,dependencies:{fetchCompletion:this.#s.bind(this),fetchStreamingCompletion:this.#l.bind(this),onFallbackLog:(S,I)=>{be()&&console.log(`413 fallback: messages ${S.messages.length} -> ${I.messages.length}, bytes=${bo(I)}`)},hasToolCalls:S=>this.#e.hasToolCalls(S),getTextContent:S=>this.#e.getTextContent(S),parseToolCalls:S=>this.#e.parseToolCalls(S),buildAssistantMessage:S=>this.#e.buildAssistantMessage(S),buildToolResultMessage:(S,I)=>this.#e.buildToolResultMessage(S,I),executeTool:(S,I)=>this.#a(S,I),onToolCallLog:async S=>{let I=(await import("chalk")).default;console.log(I.dim(` ${S.map(R=>`${R.name}(${JSON.stringify(R.args).slice(0,80)})`).join(", ")}`))},injectTools:(S,I)=>this.#o(S,I,u)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(v.done)return v.text;b.messages=v.body.messages,v.body.tools?b.tools=v.body.tools:delete b.tools}return"I hit my tool-calling limit for this turn. Please try again."}finally{r.dispose()}}async cleanup(){await this.#r.stopAll()}#o(e,t,r=null){let n=this.#i(t,r),o=this.#e.formatTools(n);this.#e.injectToolsIntoBody(e,o)}#i(e,t=null){let r=[],n=new Set;for(let o of e){let i=ot(o);if(i?.tools?.length)for(let c of i.tools)this.#n(c.name,t)&&(n.has(c.name)||(n.add(c.name),r.push({name:c.name,description:c.description,parameters:c.parameters||c.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#n(bt,t)&&r.push({name:bt,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),r}async#a(e,t){let{activeSkills:r,options:n,executionRegistry:o,capabilityPolicy:i}=t;if(!this.#n(e.name,i))return`Tool "${e.name}" blocked by policy`;if(e.name===bt){let l=String(e.args?.skillId||"").trim();if(!l)return JSON.stringify({error:"skillId is required"});if(!r.includes(l))return JSON.stringify({error:`Skill "${l}" is not active`,activeSkills:r});let u=ot(l);if(!u)return JSON.stringify({error:`Skill "${l}" not found`});let m=typeof u.promptFragment=="function"?u.promptFragment():u.promptFragment||"",d=(u.tools||[]).map(g=>g.name),f=JSON.stringify({skillId:l,description:u.description||"",toolNames:d,promptFragment:m||""});return be()&&(console.log(`
|
|
99
99
|
\u{1F4D6} get_skill_context("${l}") \u2192 ${f.length} chars (fragment: ${m.length} chars)`),console.log(` tools: [${d.join(", ")}]`),console.log(` fragment preview: ${m.slice(0,200).replace(/\n/g,"\\n")}\u2026
|
|
100
100
|
`)),f}let c=o?.get(e.name)||null;if(!c)return`Unknown tool: ${e.name}`;let a=ot(c.skillId);if(!a)return`Skill "${c.skillId}" not found for tool "${e.name}"`;if(c.mode==="handler")try{return a.handleToolCall(e.name,e.args,t)}catch(l){return`Error in ${e.name}: ${l.message}`}if(c.mode==="mcp")try{if(!this.#r.isRunning(a.serverName)){let u=a.resolve(n);if(!u)return`Skill "${c.skillId}" is not available (cannot start server)`;await this.#r.ensureServer(a.serverName,u)}let l=await this.#r.callTool(a.serverName,e.name,e.args);return l.text||(l.isError?"Tool call failed":"Done")}catch(l){return`MCP error (${a.serverName}): ${l.message}`}return`Skill "${c.skillId}" owns tool "${e.name}" but has no execution mode`}async#l(e,t,r){return this.#t.fetchStreamingCompletion(e,t,{...r,onBudget:({beforeBytes:n,meta:o})=>{be()&&console.log(`payload bytes (stream) before=${n} after=${o.bytes} trimmed=${o.trimmed} messages=${o.messageCount}`)}})}async#s(e,t,r){return this.#t.fetchCompletion(e,t,{...r,onBudget:({beforeBytes:n,meta:o})=>{be()&&console.log(`payload bytes before=${n} after=${o.bytes} trimmed=${o.trimmed} messages=${o.messageCount}`)}})}async#c(e,t,r,n){let{zodToJson:o}=await Promise.resolve().then(()=>(Me(),nr)),i=typeof n.schema?.parse=="function",c=i?o(n.schema,{}):n.schema;delete c.$schema,Se(c);let a={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:c,strict:!0}}},l=await this.#s(a,r,n),u=this.#e.getTextContent(l),m=JSON.parse(u),d=i?n.schema.parse(m):m;return{raw:u,structured:d}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||gr.maxBytes),systemMaxChars:Number(t.systemMaxChars||gr.systemMaxChars)}}#p(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:st(t.allowTools||e.allowTools),denyTools:st(t.denyTools||e.denyTools),denyPrefixes:So(t.denyPrefixes||e.denyToolPrefixes),includeSkills:st(t.includeSkills||e.includeSkills),excludeSkills:st(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#f(e,t){let r=t?.includeSkills||new Set,n=t?.excludeSkills||new Set;return r.size===0&&n.size===0?e:e.filter(o=>!(r.size>0&&!r.has(o)||n.has(o)))}#n(e,t){let r=String(e||"").trim();if(!r)return!1;let n=t?.allowTools;if(n&&n.size>0&&!n.has(r))return!1;let o=t?.denyTools;return!(o&&o.has(r)||(t?.denyPrefixes||[]).some(c=>r.startsWith(c)))}#d(e){let t=new Map,r=[];for(let n of e){let o=ot(n);if(!o?.tools?.length)continue;let i=typeof o.handleToolCall=="function"?"handler":o.serverName&&typeof o.resolve=="function"?"mcp":null;if(i)for(let c of o.tools){let a=String(c?.name||"").trim();if(a){if(t.has(a)){r.push({tool:a,winner:t.get(a).skillId,skipped:n});continue}t.set(a,{skillId:n,mode:i})}}}if(r.length>0&&be()){let n=r.slice(0,5).map(o=>`${o.tool}:${o.winner}>${o.skipped}`).join(", ");console.log(`tool registry collisions: ${n}${r.length>5?" ...":""}`)}return t}async#m(e,t,r,n){console.log(`
|
|
101
101
|
\u25C6 Model: ${t} | proxy: ${r} | token: ${n||"none"}
|
|
@@ -132,7 +132,7 @@ ${JSON.stringify(a,null,2)}
|
|
|
132
132
|
${"=".repeat(80)}`),console.log(`\u{1F3AF} SINGLE NODE EXECUTION: ${e}`),console.log(`\u{1F4C1} Session: ${i.split("/").pop()}${r.sessionPath?" (reusing)":""}`),console.log(`${"=".repeat(80)}
|
|
133
133
|
`);let m=await Io.loadContext(r.specPath||"",o,r.contextConfig||{}),d=new Po({...r,sessionPath:i,sessionTimestamp:c,context:m}),g=await new Co(n).execute(this,d);return console.log(`
|
|
134
134
|
${"=".repeat(80)}`),console.log(`\u2705 Node ${e} completed`),console.log(`${"=".repeat(80)}
|
|
135
|
-
`),{success:!0,output:g.output,outputPath:r.outputPath,state:g}}calculateOutputPath(e){let{specs:t,generated:r}=this.paths;if(!e)return`${r}/generated-test.spec.js`;let n=e.replace(new RegExp(`^${t}/`),"").replace(/\.[^.]+$/,".spec.js");return`${r}/${n}`.replace(/\/+/g,"/")}};function Ro(s,e={}){let t=new we(e);return t.buildGraph=function(){let r=new Oo;return s(r),r},e.onComplete&&(t.onComplete=e.onComplete),t}import{WorkflowGraph as
|
|
135
|
+
`),{success:!0,output:g.output,outputPath:r.outputPath,state:g}}calculateOutputPath(e){let{specs:t,generated:r}=this.paths;if(!e)return`${r}/generated-test.spec.js`;let n=e.replace(new RegExp(`^${t}/`),"").replace(/\.[^.]+$/,".spec.js");return`${r}/${n}`.replace(/\/+/g,"/")}};function Ro(s,e={}){let t=new we(e);return t.buildGraph=function(){let r=new Oo;return s(r),r},e.onComplete&&(t.onComplete=e.onComplete),t}import{WorkflowGraph as yp,resolveWorkflowSession as bp,generateWorkflowSessionId as Sp,clearInheritedSessionEnvForFreshRun as wp,shouldTrustInheritedSessionEnv as xp,readPinnedSessionPathFromEnv as _p,syncProcessEnvToSession as Ep}from"@zibby/agent-workflow";import{writeFileSync as xr,existsSync as Lo,mkdirSync as Mo}from"node:fs";import{join as vt}from"node:path";var Tt=class s{static saveTitle(e,t){let r=e.state.sessionPath;if(!r)return;let n=s._findInState(e.state,"title")||s._findInState(e.state,"result");if(!(!n||typeof n!="string"))try{let o=vt(r,"title.txt");xr(o,n,"utf-8"),p.info(`Saved title to session: "${n}"`)}catch(o){console.warn("\u26A0\uFE0F Could not save title file:",o.message)}}static _findInState(e,t){for(let[,r]of Object.entries(e))if(r&&typeof r=="object"&&r[t]!==void 0)return r[t]}static async saveExecutionData(e){let t=e.state.sessionPath;if(t)for(let[r,n]of Object.entries(e.state)){if(!n||typeof n!="object")continue;let o=Array.isArray(n.actions)&&n.actions.length>0,i=typeof n.scriptPath=="string"&&n.scriptPath.trim().length>0;if(!(!o&&!i))try{let c=vt(t,r);Lo(c)||Mo(c,{recursive:!0});let a=vt(c,"result.json");xr(a,JSON.stringify(n,null,2),"utf-8"),p.info(`Saved execution data to ${r} folder`),await this.onNodeSaved(c,n)}catch(c){console.warn(`\u26A0\uFE0F Could not save execution data for ${r}:`,c.message)}}}static async onNodeSaved(e,t){}static logResult(e,t){let r=Object.entries(e.state).filter(([,i])=>i&&typeof i=="object"&&i.success!==void 0),n=r.length>0&&r.every(([,i])=>i.success),o=r.some(([,i])=>i.success===!1);if(n)p.info("Workflow completed successfully."),t&&p.info(`Output: ${t}`);else if(o){let i=r.filter(([,c])=>!c.success).map(([c])=>c);p.info(`Workflow completed with failures in: ${i.join(", ")}`),t&&p.info(`Output: ${t}`)}return n}static handle(e,t,r){return this.saveTitle(e,t),this.saveExecutionData(e),this.logResult(e,r)}};import{z as Ap}from"zod/v3";import{AgentStrategy as Do}from"@zibby/agent-workflow";var _r=[new ce,new re,new oe,new se,new ae];function Er(s={}){let{state:e={},preferredAgent:t=null}=s,r=t||e.agentType||process.env.AGENT_TYPE;if(!r)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");p.debug(`Agent selection: requested=${r}`);let n=_r.find(o=>o.getName()===r);if(!n)throw new Error(`Unknown agent '${r}'. Available: ${_r.map(o=>o.getName()).join(", ")}`);if(p.debug(`Checking if ${r} can handle this environment...`),!n.canHandle(s)){let i={assistant:"Run `zibby login` to authenticate",claude:"Set ANTHROPIC_API_KEY in .env",cursor:"Install cursor-agent CLI or set CURSOR_API_KEY",codex:"Install codex CLI (npm i -g @openai/codex) and set OPENAI_API_KEY in .env",gemini:"Install gemini CLI (npm i -g @google/gemini-cli) and set GEMINI_API_KEY in .env"}[r]||"Check your environment configuration";throw new Error(`Agent '${r}' is not available. ${i}`)}return p.debug(`Using agent: ${n.getName()}`),n}async function Uo(s,e={},t={}){try{await import("@zibby/skills")}catch{}let r=Er(e),n=e.state?.config||t.config||{},o=n.models||{},i=t.nodeName&&o[t.nodeName]||null,c=o.default||null,a=r.name,l=n.agent?.[a]?.model||null,u=i||c||l||t.model||null,m={...t,model:u,workspace:e.state?.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:n},d=m.skills||[],f=s;if(d.length>0&&!t.skipPromptFragments){let{getSkill:y}=await import("@zibby/agent-workflow"),h=d.map(b=>{let w=y(b)?.promptFragment;return typeof w=="function"?w():w}).filter(Boolean);h.length>0&&(f+=`
|
|
136
136
|
|
|
137
137
|
${h.join(`
|
|
138
138
|
|
|
@@ -144,13 +144,13 @@ ${h.join(`
|
|
|
144
144
|
|
|
145
145
|
${g}
|
|
146
146
|
`),p.debug(`Prompt length: ${f.length} chars`),process.env.STAGE!=="prod"&&p.debug(`Full prompt:
|
|
147
|
-
${f}`),r.invoke(f,m)}import{SKILLS as
|
|
148
|
-
`);let o=at(r,e),i=at(r,t);try{let c=await
|
|
149
|
-
\u{1F3AC} Organized ${a} video(s)`),console.log(`\u{1F4C2} Videos are now next to their test files in ${t}/`)),{movedCount:a,success:!0}}catch(c){return n&&console.error("\u274C Error organizing videos:",c.message),{movedCount:0,success:!1,error:c.message}}}async function
|
|
150
|
-
`),new Promise((e,t)=>{let r=xe(__dirname,"../../scripts/patch-cursor-mcp.py");if(!lt(r)){t(new Error("Patch script not found"));return}let n=Mr("python3",[r],{stdio:"inherit"});n.on("close",o=>{o===0?e({success:!0}):t(new Error(`Patch failed with code ${o}`))}),n.on("error",o=>{t(o)})})}function
|
|
151
|
-
`),new Promise((e,t)=>{let r=Mr("cursor-agent",["mcp","list"],{cwd:s,stdio:"pipe"}),n="";r.stdout.on("data",o=>{n+=o.toString(),process.stdout.write(o)}),r.stderr.on("data",o=>{process.stderr.write(o)}),r.on("close",o=>{if(o===0){let i=
|
|
147
|
+
${f}`),r.invoke(f,m)}import{SKILLS as kp}from"@zibby/agent-workflow";import{registerSkill as Rp,getSkill as Lp,hasSkill as Mp,getAllSkills as Up,listSkillIds as Dp}from"@zibby/agent-workflow";var Fo={READ_FILE:"read_file",WRITE_FILE:"write_file",LIST_DIRECTORY:"list_directory",RUN_COMMAND:"run_command",OPEN_URL:"open_url",WAIT:"wait"},jo={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"},Bo={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"},Go={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"},Ko={GENERATE:"run_generate",TEST:"run_test",STATUS:"run_status",CANCEL:"run_cancel",WAIT:"run_wait",ARTIFACTS:"run_artifacts",LIST_SPECS:"list_specs"},Jo={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"},zo={STORE:"memory_store",RECALL:"memory_recall",BRIEF:"memory_brief",END_SESSION:"memory_end_session",TASK_LOG:"task_log",TASK_HISTORY:"task_history"},Yo={INSTALL:"install_skill",UNINSTALL:"uninstall_skill",LIST_AVAILABLE:"list_available_skills"},Kl={...Fo,...jo,...Bo,...Go,...Ko,...Jo,...zo,...Yo};import{existsSync as Ho,readFileSync as Vo}from"node:fs";import{homedir as Wo}from"node:os";import{join as Zo}from"node:path";var it=new Map,Xo={github:"GITHUB_TOKEN",gitlab:"GITLAB_TOKEN"};function qo(){let s=process.env.ZIBBY_SELF_HOST;return s!=null&&s!==""&&s!=="0"&&s.toLowerCase()!=="false"}function Qo(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let s=Zo(Wo(),".zibby","config.json");return Ho(s)&&JSON.parse(Vo(s,"utf-8")).sessionToken||null}catch{return null}}function es(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app"}async function ts(s){if(qo()){let a=Xo[s];if(a&&process.env[a])return{token:process.env[a]}}let e=Date.now(),t=it.get(s);if(t&&t.expiresAt>e)return t.data;let r=Qo();if(!r)throw new Error("No session token. Run `zibby login` first.");let n=`${es()}/integrations/token/${s}`,o=await fetch(n,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!o.ok){let a=await o.text().catch(()=>"");throw o.status===404?new Error(`${s} is not connected. Connect it at https://studio.zibby.dev/integrations`):o.status===401||o.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Failed to resolve ${s} token (${o.status}): ${a}`)}let i=await o.json();if(!i||typeof i!="object")throw new Error(`Invalid response from ${s} token endpoint: expected object, got ${typeof i}`);if(s==="jira"){if(!i.token||typeof i.token!="string")throw new Error(`Invalid jira token response: token is ${typeof i.token}, expected string`);if(!i.cloudId)throw new Error("Invalid jira token response: missing cloudId")}else if(s==="github"&&(!i.token||typeof i.token!="string"))throw new Error(`Invalid github token response: token is ${typeof i.token}, expected string`);let c=((i.expiresInSec||3e3)-120)*1e3;return it.set(s,{data:i,expiresAt:e+c}),i}function rs(s){s?it.delete(s):it.clear()}import{readdir as ns,access as vr,copyFile as os,constants as Tr}from"fs/promises";import{join as at,relative as ss}from"node:path";async function is(s={}){let{testResultsDir:e="test-results",testsDir:t="tests",projectRoot:r=process.cwd(),verbose:n=!0}=s;n&&console.log(`\u{1F3A5} Organizing test videos...
|
|
148
|
+
`);let o=at(r,e),i=at(r,t);try{let c=await ns(o),a=0;for(let l of c){if(l.startsWith("."))continue;let u=at(o,l,"video.webm");try{await vr(u,Tr.F_OK)}catch{continue}let m=l.replace(/-chromium$/,"").replace(/-firefox$/,"").replace(/-webkit$/,""),d=await as(i,m);if(d){let f=d.replace(/\.spec\.(js|ts)$/,".spec.webm");await os(u,f),n&&console.log(`\u2705 ${ss(r,f)}`),a++}else n&&console.log(`\u26A0\uFE0F Could not find test file for: ${l}`)}return n&&(console.log(`
|
|
149
|
+
\u{1F3AC} Organized ${a} video(s)`),console.log(`\u{1F4C2} Videos are now next to their test files in ${t}/`)),{movedCount:a,success:!0}}catch(c){return n&&console.error("\u274C Error organizing videos:",c.message),{movedCount:0,success:!1,error:c.message}}}async function as(s,e){let t=e.split("-");for(let r=t.length;r>0;r--){let o=t.slice(0,r).join("/");for(let i of["js","ts"]){let c=at(s,`${o}.spec.${i}`);try{return await vr(c,Tr.F_OK),c}catch{}}}return null}var Be=class{constructor(e,t={}){this.apiKey=e,this.baseUrl=t.baseUrl||process.env.ZIBBY_API_URL||"https://api-prod.zibby.app",this.enabled=!!e}isEnabled(){return this.enabled}};function Ar(){let s=process.env.ZIBBY_API_KEY;return new Be(s)}import{execSync as ls}from"node:child_process";import{existsSync as cs,mkdirSync as us}from"node:fs";import{join as ps}from"node:path";async function fs(s={}){let{baseDir:e="/workspace/repos",repos:t=null,depth:r=1,branch:n=null}=s,o=process.env.REPOS;if(!o)throw new Error("REPOS environment variable not set. Are you running in a Zibby workflow container?");let i;try{i=JSON.parse(o)}catch(l){throw new Error(`Failed to parse REPOS env var: ${l.message}`,{cause:l})}if(!Array.isArray(i)||i.length===0)throw new Error("No repositories configured for this project");let c=t?i.filter(l=>t.includes(l.name)):i;if(c.length===0)throw new Error(`No matching repositories found. Available: ${i.map(l=>l.name).join(", ")}`);cs(e)||us(e,{recursive:!0});let a={};return await Promise.all(c.map(async l=>{let u=l.provider||"github",m=u==="gitlab"?process.env.GITLAB_TOKEN:process.env.GITHUB_TOKEN;if(!m){console.error(`${u.toUpperCase()}_TOKEN not set, skipping ${l.name}`),a[l.name]=null;return}let d=l.name.replace(/\//g,"-"),f=ps(e,d),g=l.cloneUrl||l.url;if(!g){console.error(`Repository "${l.name}" has no clone URL`),a[l.name]=null;return}let y;u==="gitlab"?y=g.replace(/^https:\/\//,`https://oauth2:${m}@`):y=g.replace(/^https:\/\//,`https://x-access-token:${m}@`);let h=["clone"];r>0&&h.push("--depth",r.toString()),n&&h.push("--branch",n),h.push(y,f);let b=`git ${h.join(" ")}`;console.log(`Cloning ${l.name} (${u}) to ${f}...`);try{ls(b,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),console.log(`Repository ${l.name} cloned successfully`),a[l.name]=f}catch(w){let v=w.message.replace(m,"***").replace(y,g);console.error(`Failed to clone ${l.name}: ${v}`),a[l.name]=null}})),a}var $r=/^(?:[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 ds(s){return typeof s=="string"&&$r.test(s)}var Ir=ds;function ms(s){if(!Ir(s))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(s.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(s.slice(9,13),16))>>>8,e&255,(e=parseInt(s.slice(14,18),16))>>>8,e&255,(e=parseInt(s.slice(19,23),16))>>>8,e&255,(e=parseInt(s.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}var At=ms;var K=[];for(let s=0;s<256;++s)K.push((s+256).toString(16).slice(1));function Or(s,e=0){return(K[s[e+0]]+K[s[e+1]]+K[s[e+2]]+K[s[e+3]]+"-"+K[s[e+4]]+K[s[e+5]]+"-"+K[s[e+6]]+K[s[e+7]]+"-"+K[s[e+8]]+K[s[e+9]]+"-"+K[s[e+10]]+K[s[e+11]]+K[s[e+12]]+K[s[e+13]]+K[s[e+14]]+K[s[e+15]]).toLowerCase()}function gs(s){s=unescape(encodeURIComponent(s));let e=new Uint8Array(s.length);for(let t=0;t<s.length;++t)e[t]=s.charCodeAt(t);return e}var Cr="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Pr="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function $t(s,e,t,r,n,o){let i=typeof t=="string"?gs(t):t,c=typeof r=="string"?At(r):r;if(typeof r=="string"&&(r=At(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(c),a.set(i,c.length),a=e(a),a[6]=a[6]&15|s,a[8]=a[8]&63|128,n){if(o=o||0,o<0||o+16>n.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);for(let l=0;l<16;++l)n[o+l]=a[l];return n}return Or(a)}import{createHash as hs}from"crypto";function ys(s){return Array.isArray(s)?s=Buffer.from(s):typeof s=="string"&&(s=Buffer.from(s,"utf8")),hs("sha1").update(s).digest()}var kr=ys;function It(s,e,t,r){return $t(80,kr,s,e,t,r)}It.DNS=Cr;It.URL=Pr;var Ot=It;var Nr="@zibby/core ZibbySessionStore/1",Ge=class{constructor({apiUrl:e,apiKey:t,workflowUuid:r,fetchImpl:n=globalThis.fetch}){if(!e)throw new Error("ZibbySessionStore: apiUrl is required");if(!t)throw new Error("ZibbySessionStore: apiKey is required");if(!r)throw new Error("ZibbySessionStore: workflowUuid is required");this._apiUrl=String(e).replace(/\/+$/,""),this._apiKey=t,this._workflowUuid=r,this._fetch=n}async append(e,t){if(!Array.isArray(t)||t.length===0)return;let r=`${this._apiUrl}/workflows/${encodeURIComponent(this._workflowUuid)}/sessions/${encodeURIComponent(e.sessionId)}/append`,n=await this._fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this._apiKey}`,"Content-Type":"application/json","User-Agent":Nr},body:JSON.stringify({entries:t})});if(!n.ok)throw new Error(`ZibbySessionStore.append HTTP ${n.status}`)}async load(e){let t=`${this._apiUrl}/workflows/${encodeURIComponent(this._workflowUuid)}/sessions/${encodeURIComponent(e.sessionId)}`,r;try{r=await this._fetch(t,{method:"GET",headers:{Authorization:`Bearer ${this._apiKey}`,"User-Agent":Nr}})}catch{return null}if(r.status===404||!r.ok)return null;let n;try{n=await r.json()}catch{return null}let o=Array.isArray(n?.entries)?n.entries:null;return o&&o.length>0?o:null}};var bs="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Rr=new Set;function Ss(){return(process.env.PROGRESS_API_URL||process.env.ZIBBY_API_BASE||"").replace(/\/executions\/?$/,"").replace(/\/+$/,"")}function Lr({namespace:s=bs}={}){return{id:"session",description:"Persist agent conversation state across invocations (Claude-only in v1)",envKeys:[],tools:[],invokeAgentOptions(e,t){let r=e?.conversationId,n=e?.workflowUuid;if(!r||!n)return null;let o=t?.agentType;if(o&&o!=="claude")return Rr.has(o)||(console.warn(`[SKILLS.SESSION] agent type '${o}' does not support native sessions \u2014 node running stateless`),Rr.add(o)),null;let i=Ot(`${n}:${r}`,s),c=Ss(),a=process.env.PROJECT_API_TOKEN||process.env.ZIBBY_USER_TOKEN,l=null;if(c&&a)try{l=new Ge({apiUrl:c,apiKey:a,workflowUuid:n})}catch(d){console.warn(`[SKILLS.SESSION] failed to build SessionStore: ${d.message}`),l=null}return e.resetConversation?{sessionId:i,resume:i,forkSession:!0,...l&&{sessionStore:l}}:e.hasPriorSession?{resume:i,...l&&{sessionStore:l}}:{sessionId:i,...l&&{sessionStore:l}}}}}import{spawn as Mr}from"node:child_process";import{readFileSync as ws,writeFileSync as xs,existsSync as lt}from"node:fs";import{homedir as Ur}from"node:os";import{join as xe}from"node:path";async function _s(){let s=xe(Ur(),".local/share/cursor-agent/versions");if(!lt(s))throw new Error(`cursor-agent not found at ${s}. Please install cursor-agent first.`);return console.log(`\u{1F527} Patching cursor-agent for CI/CD...
|
|
150
|
+
`),new Promise((e,t)=>{let r=xe(__dirname,"../../scripts/patch-cursor-mcp.py");if(!lt(r)){t(new Error("Patch script not found"));return}let n=Mr("python3",[r],{stdio:"inherit"});n.on("close",o=>{o===0?e({success:!0}):t(new Error(`Patch failed with code ${o}`))}),n.on("error",o=>{t(o)})})}function Es(){let s=xe(Ur(),".local/share/cursor-agent/versions");if(!lt(s))return{patched:!1,installed:!1};try{let e=nn("fs").readdirSync(s);if(e.length===0)return{patched:!1,installed:!1};let t=e.sort().reverse()[0],r=xe(s,t,"index.js");return lt(r)?{patched:ws(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 vs(s){return console.log(`\u{1F511} Getting MCP approval keys...
|
|
151
|
+
`),new Promise((e,t)=>{let r=Mr("cursor-agent",["mcp","list"],{cwd:s,stdio:"pipe"}),n="";r.stdout.on("data",o=>{n+=o.toString(),process.stdout.write(o)}),r.stderr.on("data",o=>{process.stderr.write(o)}),r.on("close",o=>{if(o===0){let i=Ts(n);e({success:!0,keys:i,output:n})}else t(new Error(`Failed to get approval keys (exit code ${o})`))}),r.on("error",o=>{t(o)})})}function Ts(s){let e={},t=/🔑 APPROVAL KEY:\s+(\S+)\s+=>\s+(\S+)/g,r;for(;(r=t.exec(s))!==null;)e[r[1]]=r[2];return e}function As(s,e){let t=xe(s,".cursor/projects"),r=xe(t,"mcp-approvals.json");xs(r,JSON.stringify(e,null,2)),console.log(`
|
|
152
152
|
\u2705 Saved approval keys to: ${r}
|
|
153
|
-
`)}import{DEFAULT_OUTPUT_BASE as
|
|
153
|
+
`)}import{DEFAULT_OUTPUT_BASE as Zp,SESSIONS_DIR as Xp,SESSION_INFO_FILE as qp,RESULT_FILE as Qp,RAW_OUTPUT_FILE as ef,EVENTS_FILE as tf,CI_ENV_VARS as rf}from"@zibby/agent-workflow";var Dr=`
|
|
154
154
|
const style = document.createElement('style');
|
|
155
155
|
style.textContent = \`
|
|
156
156
|
@keyframes zibby-ripple {
|
|
@@ -211,7 +211,7 @@ ${f}`),r.invoke(f,m)}import{SKILLS as Cp}from"@zibby/agent-workflow";import{regi
|
|
|
211
211
|
setTimeout(() => ripple.remove(), 600);
|
|
212
212
|
}
|
|
213
213
|
};
|
|
214
|
-
`;function
|
|
214
|
+
`;function $s(s){return s.addInitScript(Dr)}function Is(){return`
|
|
215
215
|
async function showRipple(page, locator) {
|
|
216
216
|
const box = await locator.boundingBox().catch(() => null);
|
|
217
217
|
if (box) {
|
|
@@ -224,10 +224,10 @@ async function showRipple(page, locator) {
|
|
|
224
224
|
}, { x, y }).catch(() => {});
|
|
225
225
|
}
|
|
226
226
|
}
|
|
227
|
-
`.trim()}var
|
|
227
|
+
`.trim()}var Ke=class{static generate(e,t="element"){let{selectors:r}=e;if(!r||typeof r!="object")return this.generateFallbackSelector(e,t);let n=[];return r.role&&n.push(this.generateRoleSelector(r.role)),r.attributes&&n.push(this.generateAttributeSelector(r.attributes)),r.partialMatch&&n.push(this.generatePartialMatchSelector(r.partialMatch)),r.structure&&n.push(this.generateStructuralSelector(r.structure)),n.length===0?this.generateFallbackSelector(e,t):n.length===1?`const ${t} = ${n[0]};`:`const ${t} = ${n[0]}
|
|
228
228
|
${n.slice(1).map(i=>` .or(${i})`).join(`
|
|
229
229
|
`)};`}static generateRoleSelector(e){let{role:t,name:r}=e;if(!t)return null;if(r){let n=this.escapeRegex(r);return`page.getByRole('${t}', { name: /${n}/i })`}return`page.getByRole('${t}')`}static generateAttributeSelector(e){if(!e||typeof e!="object")return null;let t=Object.entries(e).filter(([n,o])=>o!=null).map(([n,o])=>n==="placeholder"||n==="aria-label"?n==="placeholder"?`page.getByPlaceholder('${this.escapeString(o)}')`:`page.locator('[${n}="${this.escapeString(o)}"]')`:`[${n}="${this.escapeString(o)}"]`);if(e.placeholder)return`page.getByPlaceholder('${this.escapeString(e.placeholder)}')`;let r=t.filter(n=>!n.startsWith("page.")).join("");return r?`page.locator('${r}')`:null}static generatePartialMatchSelector(e){if(!e||typeof e!="object")return null;let t=Object.entries(e).filter(([r,n])=>n!==void 0).map(([r,n])=>{let o=n.replace(/^\^/,"");return`[${r}^="${this.escapeString(o)}"]`});return t.length>0?`page.locator('${t.join("")}')`:null}static generateStructuralSelector(e){return!e||typeof e!="string"?null:`page.locator('${this.escapeString(e)}')`}static generateFallbackSelector(e,t){let{description:r,type:n}=e;if(n==="fill"||n==="type")return`const ${t} = page.locator('input').first();`;if(n==="click"){if(r.toLowerCase().includes("button"))return`const ${t} = page.locator('button').first();`;if(r.toLowerCase().includes("link"))return`const ${t} = page.locator('a').first();`}return`const ${t} = page.locator('body');`}static escapeString(e){return typeof e!="string"?String(e):e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/"/g,'\\"')}static escapeRegex(e){return typeof e!="string"?String(e):e.replace(/[.*+?^${}()[\]\\]/g,"\\$&")}static generateActionCode(e,t){let{type:r,value:n,description:o,selectors:i}=e,c=`element${t}`,a=this.generate(e,c),l=this.generateActionMethod(r,c,n);return`${a}
|
|
230
|
-
${l}`}static generateActionMethod(e,t,r){switch(e){case"fill":case"type":return`await ${t}.fill('${this.escapeString(r||"")}');`;case"click":return`await ${t}.click();`;case"navigate":return`await page.goto('${this.escapeString(r||"")}');`;case"wait":return`await page.waitForTimeout(${parseInt(r)||2e3});`;default:return`// Unknown action type: ${e}`}}static generateAssertionCode(e,t){let{description:r,expected:n,actual:o,passed:i}=e;return r.toLowerCase().includes("url")?`await expect(page).toHaveURL(/${this.escapeRegex(o)}/);`:r.toLowerCase().includes("visible")?"await expect(page.locator('body')).toBeVisible();":`// ${r}`}};import
|
|
230
|
+
${l}`}static generateActionMethod(e,t,r){switch(e){case"fill":case"type":return`await ${t}.fill('${this.escapeString(r||"")}');`;case"click":return`await ${t}.click();`;case"navigate":return`await page.goto('${this.escapeString(r||"")}');`;case"wait":return`await page.waitForTimeout(${parseInt(r)||2e3});`;default:return`// Unknown action type: ${e}`}}static generateAssertionCode(e,t){let{description:r,expected:n,actual:o,passed:i}=e;return r.toLowerCase().includes("url")?`await expect(page).toHaveURL(/${this.escapeRegex(o)}/);`:r.toLowerCase().includes("visible")?"await expect(page.locator('body')).toBeVisible();":`// ${r}`}};import Je from"fs/promises";var Ct=class{static async generateFromEvents(e,t,r,n){try{console.log("[TestPostProcessor] \u{1F3AF} Generating test from events.json (100% accurate)");let{readFileSync:o}=await import("fs"),i=JSON.parse(o(t,"utf-8")),c=i.filter(f=>["navigate","type","fill","click","select_option"].includes(f.type)),a=c.filter(f=>f.type!=="navigate");console.log(`[TestPostProcessor] Found ${c.length} action events, ${r.length} trace actions`);let l=`import { ZibbyRuntime } from '@zibby/core';
|
|
231
231
|
import { test, expect } from '@playwright/test';
|
|
232
232
|
|
|
233
233
|
`;l+=`test('${n}', async ({ page }) => {
|
|
@@ -242,14 +242,14 @@ import { test, expect } from '@playwright/test';
|
|
|
242
242
|
`,u++}else if(f.type==="select_option"){let{element:g,values:y}=f.data.params,h=r[u]?.strategies||[],b={name:g,action:"selectOption",value:Array.isArray(y)?y[0]:y,strategies:h};l+=` await ZibbyRuntime.step(page, ${JSON.stringify(b,null,2)});
|
|
243
243
|
|
|
244
244
|
`,u++}l+=`});
|
|
245
|
-
`;let{dirname:m}=await import("path"),{mkdirSync:d}=await import("fs");return d(m(e),{recursive:!0}),await
|
|
246
|
-
${n}`);for(let o=0;o<t.length;o++){let i=t[o],c=`element${o}`,a=new RegExp(`const ${c}\\b\\s*=\\s*page\\.[^;]+;(\\s*await ${c}\\.waitFor\\([^)]*\\);)?\\s*await ${c}\\.(click|fill|type|selectOption|pressSequentially)\\(([^)]*)\\);`,"s"),l=n.match(a);if(!l)continue;let u={name:i.name||`Action ${o}`,action:i.method==="type"?"fill":i.method,value:l[3].trim().replace(/^['"]|['"]$/g,""),strategies:i.strategies||[]},m=`await ZibbyRuntime.step(page, ${JSON.stringify(u,null,2)});`;n=n.replace(l[0],m)}return await
|
|
247
|
-
await ${d}.${u}(${m})`}}return i});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as
|
|
248
|
-
`),o=[],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||"",f=[],g=null,y=null,h=null,b=m.match(/aria-ref=([a-z0-9]+)/i);if(b&&l.snapshotName){let E=b[1],C=i.get(l.snapshotName);if(C&&C.has(E)){let $=C.get(E);g=$.name||null,y=$.role||null,h=$.label||null,console.log(`[TraceParser] \u2705 Found ACTUAL element data: text="${g}", role="${y}"`)}}let w=m.match(/internal:text="([^"]+)"/i),v=m.match(/internal:label="([^"]+)"/i),S=m.match(/internal:placeholder="([^"]+)"/i),I=m.match(/internal:role=([^ ]+)/i),R=m.match(/internal:describe="([^"]+)"/i),N=m.match(/name="([^"]+)"/i);if(w){f.push({type:"text",text:w[1]});let E=w[1].split(" ");E.length>1&&(f.push({type:"text",text:E[0],fuzzy:!0}),f.push({type:"text",text:E[E.length-1],fuzzy:!0}))}if(v&&f.push({type:"label",label:v[1]}),S&&f.push({type:"placeholder",placeholder:S[1]}),g){f.unshift({type:"text",text:g,source:"accessibility-tree"});let E=g.split(" ");E.length>1&&f.push({type:"text",text:E[0],fuzzy:!0,source:"accessibility-tree"})}if(y||I){let E=y||I[1],C=g||(N?N[1]:w?w[1]:null);f.unshift({type:"role",role:E,name:C,source:g?"accessibility-tree":"selector"})}if(h&&f.unshift({type:"label",label:h,source:"accessibility-tree"}),R){let E=R[1],C=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],$=null,P=E;for(let B of C)if(E.toLowerCase().endsWith(` ${B}`)){$=B.replace(" ",""),P=E.substring(0,E.length-B.length-1);break}if($){f.push({type:"role",role:$,name:P});let B=P.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:B}),f.push({type:"text",text:P});let k=P.split(" ");k.length>1&&(f.push({type:"text",text:k[0],fuzzy:!0}),f.push({type:"text",text:k.slice(0,2).join(" "),fuzzy:!0}))}else{let B=E.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:B}),f.push({type:"text",text:E})}}let T=this.extractDOMStrategies(m,c,w?.[1]||R?.[1],l.pageId);f.push(...T);let O=this.extractStructuralContext(m);(O.parent||O.sibling)&&f.forEach(E=>{["role","text","label","testid"].includes(E.type)&&(O.parent&&(E.parent=O.parent),O.sibling&&(E.sibling=O.sibling))}),f.push({type:"css",value:m});let U=g||w?w[1]:R?R[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${o.length}`;o.push({method:u,name:U,action:u==="type"?"fill":u,value:d,strategies:f,timestamp:l.startTime,actualText:g,actualRole:y,actualAriaLabel:h})}}}catch{}return o}catch(r){throw new Error(`Failed to parse trace: ${r.message}`,{cause:r})}}static extractDOMStrategies(e,t,r,n){let o=[];if(!t||t.size===0||!r)return o;try{let i=t.get(n);if(!i)return o;let c=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),l=i.match(a);l&&o.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&&(o.push({type:"class",value:y.join("."),priority:"medium"}),y.length===1&&o.push({type:"class",value:y[0],priority:"medium"}))}let d=new RegExp(`id=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),f=i.match(d);f&&!f[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&o.push({type:"id",value:f[1],priority:"high"})}catch(i){console.warn(`[TraceParser] DOM extraction failed: ${i.message}`)}return o}static extractStructuralContext(e){let t={parent:null,sibling:null},r=e.split(">>").map(i=>i.trim());if(r.length>1){let c=r[r.length-2].replace(/internal:text="[^"]+"\s*/gi,"").replace(/internal:role=\S+\s*/gi,"").replace(/internal:label="[^"]+"\s*/gi,"").trim();c&&(c.match(/^(form|section|nav|header|aside|main|article)\b/)||c.includes("[")||c.match(/[#.]\w/))&&(t.parent=c)}let o=r[r.length-1].match(/([^+~]+)\s*[+~]\s*(.+)/);return o&&(t.sibling=o[1].trim()),t}};var kt=class{static async step(e,t){let{name:r,action:n,value:o,strategies:i,options:c={timeout:1e4},enrichedData: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,o,3),console.log(`[Zibby] \u2728 Step "${r}" completed.`)}static async waitForPageStability(e,t=1e4){try{await e.waitForLoadState("networkidle",{timeout:3e3}).catch(()=>{}),await e.evaluate(()=>new Promise(r=>{let n,o=new MutationObserver(()=>{clearTimeout(n),n=setTimeout(()=>{o.disconnect(),r()},500)});o.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),n=setTimeout(()=>{o.disconnect(),r()},500)})).catch(()=>{})}catch{}}static async verifyPosition(e,t){try{let r=await e.boundingBox();if(!r)return;let n=Math.abs(r.x-t.x),o=Math.abs(r.y-t.y);(n>50||o>50)&&(console.log(`[Zibby] \u26A0\uFE0F Element moved: expected (${t.x}, ${t.y}), got (${r.x}, ${r.y})`),await new Promise(i=>setTimeout(i,500)))}catch{}}static async performActionWithRetry(e,t,r,n,o=3){for(let i=1;i<=o;i++)try{r==="click"?await t.click():r==="fill"?await t.fill(n||""):r==="type"?await t.pressSequentially(n||""):r==="selectOption"&&await t.selectOption(n||"");return}catch(c){if(i===o)throw c;console.log(`[Zibby] \u26A0\uFE0F Action failed (attempt ${i}/${o}), retrying...`),await new Promise(a=>setTimeout(a,1e3*i))}}static async findBestMatch(e,t,r){let o=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 b=await this.scoreCandidate(g,l,e);return{element:g,strategy:l,score:b,strategyIdx:u,elIdx:y}}catch{return null}}))).filter(g=>g!==null)}catch{return[]}}),c=(await Promise.all(i)).flat();if(c.length===0)return console.log(`[Zibby] \u274C No visible candidates found for "${r}"`),null;c.sort((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 Nt=class{static async beforeEach(e){await this.injectStableIds(e),e.on("load",async()=>{await this.injectStableIds(e)})}static async afterNavigation(e){await e.waitForLoadState("domcontentloaded").catch(()=>{}),await this.injectStableIds(e)}static async clickWithRetry(e,t,r={}){let n=r.timeout||1e4,o=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let c=e.locator(o);if(await c.count()>0)try{await c.click({timeout:2e3});return}catch(a){if(a.message.includes("intercepts pointer")){await c.click({force:!0});return}}await e.waitForTimeout(200)}throw new Error(`Element ${o} not found after ${n}ms`)}static async fillWithRetry(e,t,r,n=1e4){let o=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let c=e.locator(o);if(await c.count()>0){await c.fill(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${o} not found after ${n}ms`)}static async selectWithRetry(e,t,r,n=1e4){let o=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let c=e.locator(o);if(await c.count()>0){await c.selectOption(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${o} not found after ${n}ms`)}static async injectStableIds(e){try{await e.evaluate(()=>{function t(a){if(a.getAttribute("aria-label"))return a.getAttribute("aria-label").trim();let l=a.getAttribute("aria-labelledby");if(l){let d=document.getElementById(l);if(d)return d.textContent.trim()}if(a.id){let d=document.querySelector(`label[for="${a.id}"]`);if(d)return d.textContent.trim()}let u=a.closest("label");if(u){let d=u.cloneNode(!0);d.querySelectorAll("input, select, textarea").forEach(g=>g.remove());let f=d.textContent.trim();if(f)return f}if(a.placeholder)return a.placeholder;let m=a.tagName.toLowerCase();return m==="button"||m==="a"||a.getAttribute("role")==="button"?(a.textContent||"").trim().slice(0,50):a.title?a.title:m==="input"&&(a.type==="submit"||a.type==="button")&&a.value||""}function r(a){let l=[],u=a.closest("form");if(u)if(u.id)l.push(`form#${u.id}`);else if(u.name)l.push(`form[name=${u.name}]`);else if(u.action)try{let y=new URL(u.action,window.location.origin).pathname;l.push(`form[action=${y}]`)}catch{l.push(`form[action=${u.getAttribute("action")}]`)}else{let y=document.querySelectorAll("form"),h=Array.from(y).indexOf(u);l.push(`form:nth(${h})`)}let m=a.closest('header, nav, main, footer, aside, [role="banner"], [role="navigation"], [role="main"], [role="contentinfo"]');if(m){let y=m.tagName.toLowerCase(),h=m.getAttribute("role");l.push(h||y)}let d=a.closest('section, article, [role="region"]');if(d){let y=d.querySelector("h1, h2, h3, h4, h5, h6");y&&l.push(`section:${y.textContent.trim().slice(0,30)}`)}let f=a.closest("fieldset");if(f){let y=f.querySelector("legend");y&&l.push(`fieldset:${y.textContent.trim()}`)}let g=a.closest('dialog, [role="dialog"], [role="alertdialog"]');if(g){let y=g.querySelector('[role="heading"], h1, h2, h3');y?l.push(`dialog:${y.textContent.trim().slice(0,30)}`):l.push("dialog")}return l.join("/")}function n(a){let l=a.tagName.toLowerCase(),u=a.id||"",m=a.name||"",d=a.type||"",f=a.getAttribute("role")||"",g="";if(a.href)try{g=new URL(a.href,window.location.origin).pathname.slice(0,50)}catch{g=a.getAttribute("href")?.slice(0,50)||""}let y=t(a).slice(0,50).replace(/\s+/g," "),h=r(a),b=[l,u,m,d,f,g,y,h].join("|"),w=5381;for(let v=0;v<b.length;v++)w=(w<<5)+w^b.charCodeAt(v);return`zibby-${(w>>>0).toString(36)}`}let o=["button","a","input","select","textarea","label[for]",'[role="button"]','[role="link"]','[role="textbox"]','[role="checkbox"]','[role="radio"]','[role="combobox"]','[role="menuitem"]','[role="tab"]','[role="option"]','[role="switch"]','[role="slider"]',"[onclick]","[data-action]"].join(", "),i=new Map,c=0;document.querySelectorAll(o).forEach(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 Cs=8,Ps=1,ks=64;function Ns(s){if(!s||typeof s!="object")return 8;let e=s.parallel;if(!e||typeof e!="object")return 8;let t=e.maxConcurrentRuns??e.maxConcurrent,r=Number(t);if(!Number.isFinite(r))return 8;let n=Math.floor(r);return n<1?8:Math.min(64,n)}import{readFileSync as Ls,writeFileSync as Gr,existsSync as Ms}from"node:fs";import{join as Jr}from"node:path";var z=class{constructor(e={}){this.config=e,this.enabled=e.enabled!==!1,this.priority=e.priority||50}getName(){throw new Error("EventEnricher.getName() must be implemented")}canEnrich(e){return this.enabled}async enrich(e,t){throw new Error("EventEnricher.enrich() must be implemented")}handleError(e,t){return console.warn(`[${this.getName()}] Enrichment failed for event ${t.type}:`,e.message),null}};import{existsSync as Rs}from"node:fs";import{join as Br}from"node:path";var ue=class extends z{constructor(e={}){super(e),this.priority=190,this.traceData=null}getName(){return"TraceText"}getPriority(){return this.priority}async loadTrace(e){if(this.traceData)return;let t=Br(e,"traces"),r=Br(e,"trace.zip");if(Rs(r))try{this.traceData=await ze.parseTraceZip(r),console.log(`[TraceTextEnricher] \u2705 Loaded trace with ${this.traceData.length} actions`)}catch(n){console.log(`[TraceTextEnricher] \u26A0\uFE0F Failed to parse trace: ${n.message}`)}}async enrich(e,t){let r=e.data?.params?.ref,n=e.id;if(r===void 0&&n===void 0||(!this.traceData&&t.sessionPath&&await this.loadTrace(t.sessionPath),!this.traceData))return null;let o=this.traceData[n];if(!o)return console.log(`[TraceTextEnricher] \u26A0\uFE0F No trace action for event ${n}`),null;let i=o.actualText||this._extractTextFromSelector(o.selector),c=o.actualRole,a=o.actualAriaLabel;return i||c||a?(console.log(`[TraceTextEnricher] \u2705 Event ${n}: text="${i}", role="${c}", label="${a}"`),{traceActualText:i,traceActualRole:c,traceActualAriaLabel:a,traceSelector:o.selector,traceStrategies:o.strategies}):null}_extractTextFromSelector(e){if(!e)return null;let t=e.match(/internal:label="([^"]+)"/);if(t)return t[1];let r=e.match(/internal:text="([^"]+)"/);if(r)return r[1];let n=e.match(/getByText\(['"]([^'"]+)['"]\)/);if(n)return n[1];let o=e.match(/name:\s*['"]([^'"]+)['"]/);return o?o[1]:null}};async function Us(s){let e=Jr(s,"events.json"),t=Jr(s,"events-enriched.json");if(!Ms(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(Ls(e,"utf-8")),n=new ue,o=0,i=0;for(let c of r)try{let a=await n.enrich(c,{sessionPath:s});a&&(c.enrichedData={...c.enrichedData||{},...a},o++)}catch(a){console.log(`[PostProcess] Failed to enrich event ${c.id}: ${a.message}`),i++}return o>0&&(Gr(t,JSON.stringify(r,null,2)),Gr(e,JSON.stringify(r,null,2)),console.log(`[PostProcess] \u2705 Enriched ${o} events (${i} failed)`)),{enriched:o,failed:i}}catch(r){return console.log(`[PostProcess] \u274C Failed to post-process events: ${r.message}`),{enriched:0,failed:0}}}import{spawn as Ds}from"node:child_process";import{existsSync as Fs}from"node:fs";import{dirname as js,resolve as Kr,relative as Bs}from"node:path";var ct=new Map,Ye=8,zr={name:"run_playwright_test",description:`Run a Playwright test file and return results. Use this after writing a test to verify it works. If it fails, fix the issues and run again. Maximum ${Ye} attempts per session.`,inputSchema:{type:"object",properties:{scriptPath:{type:"string",description:"Path to the Playwright test file (e.g., tests/login.spec.js)"}},required:["scriptPath"]},async execute({scriptPath:s},e){let r=`${e?.sessionId||"default"}:${s}`,n=(ct.get(r)||0)+1;if(ct.set(r,n),n>Ye)return{success:!1,executionCount:n,maxReached:!0,error:`Maximum ${Ye} executions reached. Stop retrying and return your best result.`};let o=e?.projectRoot||process.cwd(),i=Kr(o,s),c=Bs(o,i);return c.startsWith("..")||Kr(i)!==i&&c.includes("..")?{success:!1,executionCount:n,error:"Path traversal detected: scriptPath must be within the project root."}:Fs(i)?new Promise(a=>{let l=js(i),u=Ds("npx",["playwright","test",i,"--reporter=line"],{cwd:o,env:{...process.env,FORCE_COLOR:"0"}}),m="",d="";u.stdout.on("data",g=>{m+=g.toString()}),u.stderr.on("data",g=>{d+=g.toString()});let f=setTimeout(()=>{u.kill("SIGTERM"),a({success:!1,executionCount:n,error:"Test timed out after 60 seconds",stdout:m.slice(-2e3),stderr:d.slice(-1e3)})},6e4);u.on("close",g=>{clearTimeout(f);let h=`${m}
|
|
245
|
+
`;let{dirname:m}=await import("path"),{mkdirSync:d}=await import("fs");return d(m(e),{recursive:!0}),await Je.writeFile(e,l,"utf-8"),console.log(`[TestPostProcessor] \u2705 Generated test with ${i.filter(f=>["type","fill","click","select_option"].includes(f.type)).length} actions`),!0}catch(o){return console.warn("[TestPostProcessor] Failed to generate from events:",o.message),!1}}static async enhanceSelectorsWithTrace(e,t,r){try{console.log("[TestPostProcessor] \u{1F6E1}\uFE0F Applying Zibby Safe Action Wrappers...");let n=await Je.readFile(e,"utf-8");n.includes("ZibbyRuntime")||(n=`import { ZibbyRuntime } from '@zibby/core';
|
|
246
|
+
${n}`);for(let o=0;o<t.length;o++){let i=t[o],c=`element${o}`,a=new RegExp(`const ${c}\\b\\s*=\\s*page\\.[^;]+;(\\s*await ${c}\\.waitFor\\([^)]*\\);)?\\s*await ${c}\\.(click|fill|type|selectOption|pressSequentially)\\(([^)]*)\\);`,"s"),l=n.match(a);if(!l)continue;let u={name:i.name||`Action ${o}`,action:i.method==="type"?"fill":i.method,value:l[3].trim().replace(/^['"]|['"]$/g,""),strategies:i.strategies||[]},m=`await ZibbyRuntime.step(page, ${JSON.stringify(u,null,2)});`;n=n.replace(l[0],m)}return await Je.writeFile(e,n,"utf-8"),console.log("[TestPostProcessor] \u2705 Successfully converted test to Resilient Zibby format"),!0}catch(n){return console.warn("[TestPostProcessor] Failed to apply safe wrappers:",n.message),!1}}static async enhanceSelectors(e,t){try{let{actions:r=[]}=t;if(!r.length)return!1;let n=await Je.readFile(e,"utf-8"),o=this.buildSelectorMap(r);return n=this.replaceSimpleSelectors(n,o),await Je.writeFile(e,n,"utf-8"),!0}catch(r){return console.warn("Failed to enhance selectors:",r),!1}}static buildSelectorMap(e){let t=new Map;for(let r=0;r<e.length;r++){let n=e[r];if(!n.selectors||n.type==="navigate")continue;let o=`element${r}`,c=Ke.generate(n,o).match(/= (.+);/s);if(c){let a=c[1].trim(),l=`${n.type}:${this.normalizeDescription(n.description)}`;t.set(l,a),n.selectors.role&&t.set(`role:${n.selectors.role.name}`,a),n.selectors.attributes?.placeholder&&t.set(`placeholder:${n.selectors.attributes.placeholder}`,a)}}return t}static replaceSimpleSelectors(e,t){let r=e,n=[/await page\.(getByRole|getByPlaceholder|getByText|getByLabel|locator)\([^)]+\)\.(fill|click|type)\([^)]*\)/g];for(let o of n)r=r.replace(o,i=>{for(let[c,a]of t.entries())if(i.includes(c.split(":")[1])){let l=i.match(/\.(fill|click|type)\(([^)]*)\)/);if(l){let[,u,m]=l,d="element";return`const ${d} = ${a};
|
|
247
|
+
await ${d}.${u}(${m})`}}return i});return r}static normalizeDescription(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}};import{readFileSync as Os,existsSync as Fr,readdirSync as jr}from"node:fs";import{join as Pt}from"node:path";import{execSync as Cs}from"node:child_process";import{tmpdir as Ps}from"node:os";var ze=class{static async parseTraceZip(e){let t;if(e.endsWith(".zip")&&Fr(e)){let r=Pt(Ps(),`trace-${Date.now()}`);Cs(`unzip -q "${e}" -d "${r}"`,{stdio:"pipe"});let o=jr(r).find(i=>i.endsWith(".trace"));if(!o)throw new Error("No .trace file found in zip");t=Pt(r,o)}else if(Fr(e)){let n=jr(e).find(o=>o.endsWith(".trace"));if(!n)throw new Error("No .trace file found");t=Pt(e,n)}else throw new Error(`Trace not found at ${e}`);try{let n=Os(t,"utf-8").trim().split(`
|
|
248
|
+
`),o=[],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||"",f=[],g=null,y=null,h=null,b=m.match(/aria-ref=([a-z0-9]+)/i);if(b&&l.snapshotName){let E=b[1],C=i.get(l.snapshotName);if(C&&C.has(E)){let $=C.get(E);g=$.name||null,y=$.role||null,h=$.label||null,console.log(`[TraceParser] \u2705 Found ACTUAL element data: text="${g}", role="${y}"`)}}let w=m.match(/internal:text="([^"]+)"/i),v=m.match(/internal:label="([^"]+)"/i),S=m.match(/internal:placeholder="([^"]+)"/i),I=m.match(/internal:role=([^ ]+)/i),R=m.match(/internal:describe="([^"]+)"/i),N=m.match(/name="([^"]+)"/i);if(w){f.push({type:"text",text:w[1]});let E=w[1].split(" ");E.length>1&&(f.push({type:"text",text:E[0],fuzzy:!0}),f.push({type:"text",text:E[E.length-1],fuzzy:!0}))}if(v&&f.push({type:"label",label:v[1]}),S&&f.push({type:"placeholder",placeholder:S[1]}),g){f.unshift({type:"text",text:g,source:"accessibility-tree"});let E=g.split(" ");E.length>1&&f.push({type:"text",text:E[0],fuzzy:!0,source:"accessibility-tree"})}if(y||I){let E=y||I[1],C=g||(N?N[1]:w?w[1]:null);f.unshift({type:"role",role:E,name:C,source:g?"accessibility-tree":"selector"})}if(h&&f.unshift({type:"label",label:h,source:"accessibility-tree"}),R){let E=R[1],C=["link","button","textbox","menuitem","submenu","combobox","checkbox","radio","tab","treeitem","menu item"],$=null,P=E;for(let B of C)if(E.toLowerCase().endsWith(` ${B}`)){$=B.replace(" ",""),P=E.substring(0,E.length-B.length-1);break}if($){f.push({type:"role",role:$,name:P});let B=P.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:B}),f.push({type:"text",text:P});let k=P.split(" ");k.length>1&&(f.push({type:"text",text:k[0],fuzzy:!0}),f.push({type:"text",text:k.slice(0,2).join(" "),fuzzy:!0}))}else{let B=E.replace(/\s*\([^)]+\)\s*$/,"");f.push({type:"text",text:B}),f.push({type:"text",text:E})}}let T=this.extractDOMStrategies(m,c,w?.[1]||R?.[1],l.pageId);f.push(...T);let O=this.extractStructuralContext(m);(O.parent||O.sibling)&&f.forEach(E=>{["role","text","label","testid"].includes(E.type)&&(O.parent&&(E.parent=O.parent),O.sibling&&(E.sibling=O.sibling))}),f.push({type:"css",value:m});let U=g||w?w[1]:R?R[1].replace(/\s*\([^)]+\)\s*$/,""):`Action ${o.length}`;o.push({method:u,name:U,action:u==="type"?"fill":u,value:d,strategies:f,timestamp:l.startTime,actualText:g,actualRole:y,actualAriaLabel:h})}}}catch{}return o}catch(r){throw new Error(`Failed to parse trace: ${r.message}`,{cause:r})}}static extractDOMStrategies(e,t,r,n){let o=[];if(!t||t.size===0||!r)return o;try{let i=t.get(n);if(!i)return o;let c=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`data-testid=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),l=i.match(a);l&&o.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&&(o.push({type:"class",value:y.join("."),priority:"medium"}),y.length===1&&o.push({type:"class",value:y[0],priority:"medium"}))}let d=new RegExp(`id=["']([^"']+)["'][^>]*>[^<]*${c}`,"i"),f=i.match(d);f&&!f[1].match(/^(root|app|\d+|[a-f0-9-]{20,})$/i)&&o.push({type:"id",value:f[1],priority:"high"})}catch(i){console.warn(`[TraceParser] DOM extraction failed: ${i.message}`)}return o}static extractStructuralContext(e){let t={parent:null,sibling:null},r=e.split(">>").map(i=>i.trim());if(r.length>1){let c=r[r.length-2].replace(/internal:text="[^"]+"\s*/gi,"").replace(/internal:role=\S+\s*/gi,"").replace(/internal:label="[^"]+"\s*/gi,"").trim();c&&(c.match(/^(form|section|nav|header|aside|main|article)\b/)||c.includes("[")||c.match(/[#.]\w/))&&(t.parent=c)}let o=r[r.length-1].match(/([^+~]+)\s*[+~]\s*(.+)/);return o&&(t.sibling=o[1].trim()),t}};var kt=class{static async step(e,t){let{name:r,action:n,value:o,strategies:i,options:c={timeout:1e4},enrichedData: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,o,3),console.log(`[Zibby] \u2728 Step "${r}" completed.`)}static async waitForPageStability(e,t=1e4){try{await e.waitForLoadState("networkidle",{timeout:3e3}).catch(()=>{}),await e.evaluate(()=>new Promise(r=>{let n,o=new MutationObserver(()=>{clearTimeout(n),n=setTimeout(()=>{o.disconnect(),r()},500)});o.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),n=setTimeout(()=>{o.disconnect(),r()},500)})).catch(()=>{})}catch{}}static async verifyPosition(e,t){try{let r=await e.boundingBox();if(!r)return;let n=Math.abs(r.x-t.x),o=Math.abs(r.y-t.y);(n>50||o>50)&&(console.log(`[Zibby] \u26A0\uFE0F Element moved: expected (${t.x}, ${t.y}), got (${r.x}, ${r.y})`),await new Promise(i=>setTimeout(i,500)))}catch{}}static async performActionWithRetry(e,t,r,n,o=3){for(let i=1;i<=o;i++)try{r==="click"?await t.click():r==="fill"?await t.fill(n||""):r==="type"?await t.pressSequentially(n||""):r==="selectOption"&&await t.selectOption(n||"");return}catch(c){if(i===o)throw c;console.log(`[Zibby] \u26A0\uFE0F Action failed (attempt ${i}/${o}), retrying...`),await new Promise(a=>setTimeout(a,1e3*i))}}static async findBestMatch(e,t,r){let o=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 b=await this.scoreCandidate(g,l,e);return{element:g,strategy:l,score:b,strategyIdx:u,elIdx:y}}catch{return null}}))).filter(g=>g!==null)}catch{return[]}}),c=(await Promise.all(i)).flat();if(c.length===0)return console.log(`[Zibby] \u274C No visible candidates found for "${r}"`),null;c.sort((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 Nt=class{static async beforeEach(e){await this.injectStableIds(e),e.on("load",async()=>{await this.injectStableIds(e)})}static async afterNavigation(e){await e.waitForLoadState("domcontentloaded").catch(()=>{}),await this.injectStableIds(e)}static async clickWithRetry(e,t,r={}){let n=r.timeout||1e4,o=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let c=e.locator(o);if(await c.count()>0)try{await c.click({timeout:2e3});return}catch(a){if(a.message.includes("intercepts pointer")){await c.click({force:!0});return}}await e.waitForTimeout(200)}throw new Error(`Element ${o} not found after ${n}ms`)}static async fillWithRetry(e,t,r,n=1e4){let o=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let c=e.locator(o);if(await c.count()>0){await c.fill(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${o} not found after ${n}ms`)}static async selectWithRetry(e,t,r,n=1e4){let o=`[data-zibby-id="${t}"]`,i=Date.now();for(;Date.now()-i<n;){await this.injectStableIds(e);let c=e.locator(o);if(await c.count()>0){await c.selectOption(r);return}await e.waitForTimeout(200)}throw new Error(`Element ${o} not found after ${n}ms`)}static async injectStableIds(e){try{await e.evaluate(()=>{function t(a){if(a.getAttribute("aria-label"))return a.getAttribute("aria-label").trim();let l=a.getAttribute("aria-labelledby");if(l){let d=document.getElementById(l);if(d)return d.textContent.trim()}if(a.id){let d=document.querySelector(`label[for="${a.id}"]`);if(d)return d.textContent.trim()}let u=a.closest("label");if(u){let d=u.cloneNode(!0);d.querySelectorAll("input, select, textarea").forEach(g=>g.remove());let f=d.textContent.trim();if(f)return f}if(a.placeholder)return a.placeholder;let m=a.tagName.toLowerCase();return m==="button"||m==="a"||a.getAttribute("role")==="button"?(a.textContent||"").trim().slice(0,50):a.title?a.title:m==="input"&&(a.type==="submit"||a.type==="button")&&a.value||""}function r(a){let l=[],u=a.closest("form");if(u)if(u.id)l.push(`form#${u.id}`);else if(u.name)l.push(`form[name=${u.name}]`);else if(u.action)try{let y=new URL(u.action,window.location.origin).pathname;l.push(`form[action=${y}]`)}catch{l.push(`form[action=${u.getAttribute("action")}]`)}else{let y=document.querySelectorAll("form"),h=Array.from(y).indexOf(u);l.push(`form:nth(${h})`)}let m=a.closest('header, nav, main, footer, aside, [role="banner"], [role="navigation"], [role="main"], [role="contentinfo"]');if(m){let y=m.tagName.toLowerCase(),h=m.getAttribute("role");l.push(h||y)}let d=a.closest('section, article, [role="region"]');if(d){let y=d.querySelector("h1, h2, h3, h4, h5, h6");y&&l.push(`section:${y.textContent.trim().slice(0,30)}`)}let f=a.closest("fieldset");if(f){let y=f.querySelector("legend");y&&l.push(`fieldset:${y.textContent.trim()}`)}let g=a.closest('dialog, [role="dialog"], [role="alertdialog"]');if(g){let y=g.querySelector('[role="heading"], h1, h2, h3');y?l.push(`dialog:${y.textContent.trim().slice(0,30)}`):l.push("dialog")}return l.join("/")}function n(a){let l=a.tagName.toLowerCase(),u=a.id||"",m=a.name||"",d=a.type||"",f=a.getAttribute("role")||"",g="";if(a.href)try{g=new URL(a.href,window.location.origin).pathname.slice(0,50)}catch{g=a.getAttribute("href")?.slice(0,50)||""}let y=t(a).slice(0,50).replace(/\s+/g," "),h=r(a),b=[l,u,m,d,f,g,y,h].join("|"),w=5381;for(let v=0;v<b.length;v++)w=(w<<5)+w^b.charCodeAt(v);return`zibby-${(w>>>0).toString(36)}`}let o=["button","a","input","select","textarea","label[for]",'[role="button"]','[role="link"]','[role="textbox"]','[role="checkbox"]','[role="radio"]','[role="combobox"]','[role="menuitem"]','[role="tab"]','[role="option"]','[role="switch"]','[role="slider"]',"[onclick]","[data-action]"].join(", "),i=new Map,c=0;document.querySelectorAll(o).forEach(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 ks=8,Ns=1,Rs=64;function Ls(s){if(!s||typeof s!="object")return 8;let e=s.parallel;if(!e||typeof e!="object")return 8;let t=e.maxConcurrentRuns??e.maxConcurrent,r=Number(t);if(!Number.isFinite(r))return 8;let n=Math.floor(r);return n<1?8:Math.min(64,n)}import{readFileSync as Us,writeFileSync as Gr,existsSync as Ds}from"node:fs";import{join as Kr}from"node:path";var z=class{constructor(e={}){this.config=e,this.enabled=e.enabled!==!1,this.priority=e.priority||50}getName(){throw new Error("EventEnricher.getName() must be implemented")}canEnrich(e){return this.enabled}async enrich(e,t){throw new Error("EventEnricher.enrich() must be implemented")}handleError(e,t){return console.warn(`[${this.getName()}] Enrichment failed for event ${t.type}:`,e.message),null}};import{existsSync as Ms}from"node:fs";import{join as Br}from"node:path";var ue=class extends z{constructor(e={}){super(e),this.priority=190,this.traceData=null}getName(){return"TraceText"}getPriority(){return this.priority}async loadTrace(e){if(this.traceData)return;let t=Br(e,"traces"),r=Br(e,"trace.zip");if(Ms(r))try{this.traceData=await ze.parseTraceZip(r),console.log(`[TraceTextEnricher] \u2705 Loaded trace with ${this.traceData.length} actions`)}catch(n){console.log(`[TraceTextEnricher] \u26A0\uFE0F Failed to parse trace: ${n.message}`)}}async enrich(e,t){let r=e.data?.params?.ref,n=e.id;if(r===void 0&&n===void 0||(!this.traceData&&t.sessionPath&&await this.loadTrace(t.sessionPath),!this.traceData))return null;let o=this.traceData[n];if(!o)return console.log(`[TraceTextEnricher] \u26A0\uFE0F No trace action for event ${n}`),null;let i=o.actualText||this._extractTextFromSelector(o.selector),c=o.actualRole,a=o.actualAriaLabel;return i||c||a?(console.log(`[TraceTextEnricher] \u2705 Event ${n}: text="${i}", role="${c}", label="${a}"`),{traceActualText:i,traceActualRole:c,traceActualAriaLabel:a,traceSelector:o.selector,traceStrategies:o.strategies}):null}_extractTextFromSelector(e){if(!e)return null;let t=e.match(/internal:label="([^"]+)"/);if(t)return t[1];let r=e.match(/internal:text="([^"]+)"/);if(r)return r[1];let n=e.match(/getByText\(['"]([^'"]+)['"]\)/);if(n)return n[1];let o=e.match(/name:\s*['"]([^'"]+)['"]/);return o?o[1]:null}};async function Fs(s){let e=Kr(s,"events.json"),t=Kr(s,"events-enriched.json");if(!Ds(e))return console.log("[PostProcess] No events.json found"),{enriched:0,failed:0};try{let r=JSON.parse(Us(e,"utf-8")),n=new ue,o=0,i=0;for(let c of r)try{let a=await n.enrich(c,{sessionPath:s});a&&(c.enrichedData={...c.enrichedData||{},...a},o++)}catch(a){console.log(`[PostProcess] Failed to enrich event ${c.id}: ${a.message}`),i++}return o>0&&(Gr(t,JSON.stringify(r,null,2)),Gr(e,JSON.stringify(r,null,2)),console.log(`[PostProcess] \u2705 Enriched ${o} events (${i} failed)`)),{enriched:o,failed:i}}catch(r){return console.log(`[PostProcess] \u274C Failed to post-process events: ${r.message}`),{enriched:0,failed:0}}}import{spawn as js}from"node:child_process";import{existsSync as Bs}from"node:fs";import{dirname as Gs,resolve as Jr,relative as Ks}from"node:path";var ct=new Map,Ye=8,zr={name:"run_playwright_test",description:`Run a Playwright test file and return results. Use this after writing a test to verify it works. If it fails, fix the issues and run again. Maximum ${Ye} attempts per session.`,inputSchema:{type:"object",properties:{scriptPath:{type:"string",description:"Path to the Playwright test file (e.g., tests/login.spec.js)"}},required:["scriptPath"]},async execute({scriptPath:s},e){let r=`${e?.sessionId||"default"}:${s}`,n=(ct.get(r)||0)+1;if(ct.set(r,n),n>Ye)return{success:!1,executionCount:n,maxReached:!0,error:`Maximum ${Ye} executions reached. Stop retrying and return your best result.`};let o=e?.projectRoot||process.cwd(),i=Jr(o,s),c=Ks(o,i);return c.startsWith("..")||Jr(i)!==i&&c.includes("..")?{success:!1,executionCount:n,error:"Path traversal detected: scriptPath must be within the project root."}:Bs(i)?new Promise(a=>{let l=Gs(i),u=js("npx",["playwright","test",i,"--reporter=line"],{cwd:o,env:{...process.env,FORCE_COLOR:"0"}}),m="",d="";u.stdout.on("data",g=>{m+=g.toString()}),u.stderr.on("data",g=>{d+=g.toString()});let f=setTimeout(()=>{u.kill("SIGTERM"),a({success:!1,executionCount:n,error:"Test timed out after 60 seconds",stdout:m.slice(-2e3),stderr:d.slice(-1e3)})},6e4);u.on("close",g=>{clearTimeout(f);let h=`${m}
|
|
249
249
|
${d}`.split(`
|
|
250
250
|
`),b="",w=null;for(let v=0;v<h.length;v++){let S=h[v];if(S.includes("Error:")||S.includes("error:")||S.includes("\u2718")){b+=`${S}
|
|
251
251
|
`;for(let I=v+1;I<Math.min(v+5,h.length);I++)b+=`${h[I]}
|
|
252
|
-
`}if(S.includes("at ")&&S.includes(".spec.")){let I=S.match(/:(\d+):\d+/);I&&(w=parseInt(I[1]))}}a(g===0?{success:!0,executionCount:n,message:"All tests passed!",output:m.slice(-500)}:{success:!1,executionCount:n,remainingAttempts:Ye-n,error:b.slice(0,1500)||"Test failed (see output)",failedAtLine:w,stdout:m.slice(-1500),stderr:d.slice(-500),hint:n<Ye?"Fix the error and run again.":"Last attempt - make your best fix."})}),u.on("error",g=>{clearTimeout(f),a({success:!1,executionCount:n,error:`Failed to run test: ${g.message}`})})}):{success:!1,executionCount:n,error:`Test file not found: ${i}. Make sure you wrote the file first using the write tool.`}},resetCount(s){for(let e of ct.keys())e.startsWith(`${s}:`)&&ct.delete(e)}};function
|
|
252
|
+
`}if(S.includes("at ")&&S.includes(".spec.")){let I=S.match(/:(\d+):\d+/);I&&(w=parseInt(I[1]))}}a(g===0?{success:!0,executionCount:n,message:"All tests passed!",output:m.slice(-500)}:{success:!1,executionCount:n,remainingAttempts:Ye-n,error:b.slice(0,1500)||"Test failed (see output)",failedAtLine:w,stdout:m.slice(-1500),stderr:d.slice(-500),hint:n<Ye?"Fix the error and run again.":"Last attempt - make your best fix."})}),u.on("error",g=>{clearTimeout(f),a({success:!1,executionCount:n,error:`Failed to run test: ${g.message}`})})}):{success:!1,executionCount:n,error:`Test file not found: ${i}. Make sure you wrote the file first using the write tool.`}},resetCount(s){for(let e of ct.keys())e.startsWith(`${s}:`)&&ct.delete(e)}};function Js(s){zr.resetCount(s)}var Q=class{async generate(e){throw new Error("TestGenerationStrategy.generate() must be implemented")}canGenerate(e){throw new Error("TestGenerationStrategy.canGenerate() must be implemented")}getName(){throw new Error("TestGenerationStrategy.getName() must be implemented")}getPriority(){return 0}};import{readFileSync as Yr,writeFileSync as zs}from"node:fs";var _e=class extends Q{constructor(){super("mcp-ref","MCP Reference Replay (Exact 1:1)",200)}canGenerate(e){let t=e.eventsPath||`${e.sessionPath}/execute_live/events.json`;try{return JSON.parse(Yr(t,"utf-8")).some(o=>o.data?.params?.element)?(console.log("[MCPRefStrategy] \u2705 MCP element descriptions available"),!0):(console.log("[MCPRefStrategy] \u274C No MCP element descriptions found in events"),!1)}catch(r){return console.log("[MCPRefStrategy] \u274C Failed to read events:",r.message),!1}}getName(){return"MCP Reference Replay (Exact 1:1)"}getPriority(){return 200}async generate(e){let{testFilePath:t,sessionPath:r,state:n}=e,o=`${r}/execute_live/events.json`,i=n?.title||"Generated Test";console.log("[MCPRefStrategy] \u{1F3AF} Generating test using MCP element descriptions (1:1 replay)"),console.log(`[MCPRefStrategy] events: ${o}`),console.log(`[MCPRefStrategy] output: ${t}`);let a=JSON.parse(Yr(o,"utf-8")).filter(u=>["navigate","type","fill","click","select_option"].includes(u.type)),l=`import { test, expect } from '@playwright/test';
|
|
253
253
|
`;l+=`import { ZibbyRuntime } from '@zibby/core';
|
|
254
254
|
|
|
255
255
|
`,l+=`test('${i}', async ({ page }) => {
|
|
@@ -289,7 +289,7 @@ ${d}`.split(`
|
|
|
289
289
|
`,l+=` });
|
|
290
290
|
|
|
291
291
|
`}}return l+=`});
|
|
292
|
-
`,
|
|
292
|
+
`,zs(t,l),console.log(`[MCPRefStrategy] \u2705 Generated test with ${a.length} actions using MCP descriptions`),{success:!0,testPath:t,method:"MCP Reference Replay (1:1)",actionsGenerated:a.length}}_extractRole(e){let t=e.toLowerCase();return t.includes("button")?"button":t.includes("textbox")?"textbox":t.includes("link")?"link":t.includes("checkbox")?"checkbox":t.includes("radio")?"radio":t.includes("combobox")?"combobox":t.includes("heading")?"heading":"button"}_extractName(e){return e.replace(/\s+(button|textbox|link|checkbox|radio|combobox)$/i,"").trim()}_escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}};import{readFileSync as Hr,writeFileSync as Ys}from"node:fs";var Ee=class extends Q{constructor(){super("stable-id","Stable ID Injection (Experimental)",300)}canGenerate(e){let t=e.eventsPath||`${e.sessionPath}/execute_live/events.json`;try{return JSON.parse(Hr(t,"utf-8")).some(o=>o.stableId||o.data?.stableId)?(console.log("[StableIdStrategy] \u2705 Stable IDs available"),!0):(console.log("[StableIdStrategy] \u274C No stable IDs found in events"),!1)}catch(r){return console.log("[StableIdStrategy] \u274C Failed to read events:",r.message),!1}}getName(){return"Stable ID Injection (Experimental)"}getPriority(){return 300}async generate(e){let{testFilePath:t,sessionPath:r,state:n}=e,o=`${r}/execute_live/events.json`,i=n?.title||"Generated Test";console.log("[StableIdStrategy] \u{1F3AF} Generating test using stable IDs"),console.log(`[StableIdStrategy] events: ${o}`),console.log(`[StableIdStrategy] output: ${t}`);let a=JSON.parse(Hr(o,"utf-8")).filter(d=>["navigate","type","fill","click","select_option","select"].includes(d.type)),l=`import { test, expect } from '@playwright/test';
|
|
293
293
|
`;l+=`import { StableIdRuntime } from '@zibby/core';
|
|
294
294
|
|
|
295
295
|
`,l+=`test('${i}', async ({ page }) => {
|
|
@@ -304,17 +304,17 @@ ${d}`.split(`
|
|
|
304
304
|
`}else if(f.type==="select_option"||f.type==="select"){u=!1;let h=f.data?.values||f.data?.params?.values,b=Array.isArray(h)?h[0]:h||"";g?l+=` await StableIdRuntime.selectWithRetry(page, '${g}', '${this._escapeString(b)}');
|
|
305
305
|
`:l+=` await page.locator('select').selectOption('${this._escapeString(b)}');
|
|
306
306
|
`}}return l+=`});
|
|
307
|
-
`,
|
|
307
|
+
`,Ys(t,l),console.log(`[StableIdStrategy] \u2705 Generated test with ${a.length} actions using stable IDs`),{success:!0,testPath:t,method:"Stable ID Injection (Experimental)",actionsGenerated:a.length}}_escapeString(e){return e.replace(/'/g,"\\'").replace(/\n/g,"\\n")}_generateSemanticSelector(e){let t=e.toLowerCase(),r="locator",n=e;return t.includes("button")?(r="button",n=e.replace(/\s*button\s*/gi,"").trim()):t.includes("link")?(r="link",n=e.replace(/\s*link\s*/gi,"").trim()):t.includes("textbox")?(r="textbox",n=e.replace(/\s*textbox\s*/gi,"").trim()):t.includes("checkbox")?(r="checkbox",n=e.replace(/\s*checkbox\s*/gi,"").trim()):(t.includes("combobox")||t.includes("dropdown")||t.includes("select"))&&(r="combobox",n=e.replace(/\s*(combobox|dropdown|select)\s*/gi,"").trim()),r!=="locator"&&n?`page.getByRole('${r}', { name: '${this._escapeString(n)}' })`:`page.getByText('${this._escapeString(e)}')`}};var Rt=class{constructor(){this.strategies=[new Ee,new _e],this.strategies.sort((e,t)=>t.getPriority()-e.getPriority())}registerStrategy(e){this.strategies.push(e),this.strategies.sort((t,r)=>r.getPriority()-t.getPriority())}async generate(e){console.log(`
|
|
308
308
|
\u{1F4CB} Available generation strategies (${this.strategies.length}):`),this.strategies.forEach(t=>{let r=t.canGenerate(e);console.log(` ${r?"\u2713":"\u2717"} ${t.getName()} (priority: ${t.getPriority()})`)});for(let t of this.strategies)if(t.canGenerate(e))return console.log(`
|
|
309
|
-
\u{1F3AF} Selected: ${t.getName()}`),t.generate(e);throw new Error("No generation strategy available for this context")}getStrategy(e){return this.strategies.find(t=>t.getName().includes(e))||null}},
|
|
309
|
+
\u{1F3AF} Selected: ${t.getName()}`),t.generate(e);throw new Error("No generation strategy available for this context")}getStrategy(e){return this.strategies.find(t=>t.getName().includes(e))||null}},Hs=new Rt;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 Vs}from"node:child_process";import{existsSync as Ws}from"node:fs";var Te=class extends ve{getName(){return"Playwright JSON Reporter"}getPriority(){return 100}canVerify(e){let{testFilePath:t}=e;return Ws(t)}async verify(e){let{testFilePath:t,cwd:r,timeout:n=3e4}=e;try{console.log(`\u{1F9EA} Running test: ${t}`);let o=`npx playwright test ${t} --reporter=json --timeout=${n}`,i=Vs(o,{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(o){let i=o.stdout||o.stderr||o.message;try{let c=JSON.parse(i),a=c.stats||{},l="Test execution failed";if(c.suites&&c.suites.length>0){let m=c.suites[0];if(m.specs&&m.specs.length>0){let d=m.specs[0];if(d.tests&&d.tests.length>0){let f=d.tests[0];if(f.results&&f.results.length>0){let g=f.results[0];g.error&&(l=g.error.message||l)}}}}let u=l.includes("Executable doesn't exist")||l.includes("browserType.launch")||l.includes("Please run the following command")||l.includes("npx playwright install")||i.includes("Executable doesn't exist")||i.includes("npx playwright install");return{success:!1,passed:a.expected||0,failed:a.unexpected||0,error:l,errorDetails:l,isEnvironmentError:u}}catch{let a=i.match(/Error: (.+)/),l=a?a[1]:"Test execution failed",u=l.includes("Executable doesn't exist")||l.includes("browserType.launch")||l.includes("Please run the following command")||l.includes("npx playwright install")||i.includes("Executable doesn't exist")||i.includes("npx playwright install");return{success:!1,passed:0,failed:1,error:l,errorDetails:l,isEnvironmentError:u}}}}};var Lt=class{constructor(){this.strategies=[new Te],this.strategies.sort((e,t)=>t.getPriority()-e.getPriority())}registerStrategy(e){this.strategies.push(e),this.strategies.sort((t,r)=>r.getPriority()-t.getPriority())}async verify(e){console.log(`
|
|
310
310
|
\u{1F4CB} Available verification strategies (${this.strategies.length}):`),this.strategies.forEach(t=>{let r=t.canVerify(e);console.log(` ${r?"\u2713":"\u2717"} ${t.getName()} (priority: ${t.getPriority()})`)});for(let t of this.strategies)if(t.canVerify(e))return console.log(`
|
|
311
|
-
\u{1F3AF} Selected: ${t.getName()}`),t.verify(e);throw new Error("No verification strategy available for this context")}getStrategy(e){return this.strategies.find(t=>t.getName().includes(e))||null}},
|
|
311
|
+
\u{1F3AF} Selected: ${t.getName()}`),t.verify(e);throw new Error("No verification strategy available for this context")}getStrategy(e){return this.strategies.find(t=>t.getName().includes(e))||null}},Zs=new Lt;var ee=class{constructor(e={}){this.enrichers=[],this.config=e,this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}register(e){return this.enrichers.push(e),this.enrichers.sort((t,r)=>r.getPriority()-t.getPriority()),this}unregister(e){return this.enrichers=this.enrichers.filter(t=>t.getName()!==e),this}get(e){return this.enrichers.find(t=>t.getName()===e)}setEnabled(e,t){let r=this.get(e);return r&&(r.enabled=t),this}async enrich(e,t){this.stats.totalEvents++;let r={...e},n=[],o=[],i=[];for(let c of this.enrichers)try{if(!c.canEnrich(t)){o.push(c.getName());continue}let a=Date.now(),l=await c.enrich(e,t),u=Date.now()-a;l?(Object.assign(r,l),n.push({name:c.getName(),duration:u})):o.push(c.getName())}catch(a){console.warn(`[EnrichmentPipeline] ${c.getName()} failed:`,a.message),i.push(c.getName()),this.stats.errors[c.getName()]=(this.stats.errors[c.getName()]||0)+1}return r._enrichment={version:"1.0",timestamp:new Date().toISOString(),enrichers:{run:n,skipped:o,failed:i}},n.length>0?this.stats.enrichedEvents++:this.stats.skippedEvents++,r}async enrichBatch(e,t){let r=[];for(let n of e){let o=await this.enrich(n,t);r.push(o)}return r}getStats(){return{...this.stats,enrichers:this.enrichers.map(e=>({name:e.getName(),enabled:e.enabled,priority:e.getPriority(),errors:this.stats.errors[e.getName()]||0}))}}resetStats(){this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}logStatus(){console.log(`
|
|
312
312
|
\u{1F4CA} Enrichment Pipeline Status:`),console.log(` Total events: ${this.stats.totalEvents}`),console.log(` Enriched: ${this.stats.enrichedEvents}`),console.log(` Skipped: ${this.stats.skippedEvents}`),console.log(`
|
|
313
|
-
Registered enrichers (${this.enrichers.length}):`);for(let e of this.enrichers){let t=e.enabled?"\u2713":"\u2717",r=this.stats.errors[e.getName()]||0,n=r>0?` (${r} errors)`:"";console.log(` ${t} ${e.getName()} (priority: ${e.getPriority()})${n}`)}console.log()}};var Ae=class extends z{getName(){return"PositionEnricher"}getPriority(){return 90}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:n}=t,o=await n.boundingBox();if(!o)return null;let i=await r.evaluate(()=>({scrollX:window.scrollX,scrollY:window.scrollY,width:window.innerWidth,height:window.innerHeight})),c=o.y>=i.scrollY&&o.y+o.height<=i.scrollY+i.height&&o.x>=0&&o.x+o.width<=i.width;return{position:{boundingBox:o,viewport:i,inViewport:c,centerPoint:{x:Math.round(o.x+o.width/2),y:Math.round(o.y+o.height/2)}}}}catch(r){return this.handleError(r,e)}}};import Vr from"node:crypto";var pe=class extends z{getName(){return"AccessibilityEnricher"}getPriority(){return 100}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:n}=t,o=await r.accessibility.snapshot(),i=await this.findAxNode(n,o);if(!i)return null;let c=await this.getAxContext(i,o),a=this.hashAxSubtree(i),l=this.hashAxPath(c.path);return{accessibility:{role:i.role,name:i.name||"",level:c.level,parent:c.parent,siblings:c.siblings,axTreeHash:a,axPathHash:l}}}catch(r){return this.handleError(r,e)}}async findAxNode(e,t){let r=await e.evaluate(n=>({role:n.getAttribute("role")||n.tagName.toLowerCase(),name:n.getAttribute("aria-label")||n.textContent?.trim()||"",tagName:n.tagName.toLowerCase()}));return this.searchAxTree(t,r)}searchAxTree(e,t){if(!e)return null;if(e.role===t.role&&(e.name||"").includes(t.name.substring(0,20)))return e;if(e.children)for(let r of e.children){let n=this.searchAxTree(r,t);if(n)return n}return null}getAxContext(e,t){let r={level:0,parent:null,siblings:[],path:[]},n=this.findParent(e,t);return n&&(r.parent={role:n.role,name:n.name},r.siblings=(n.children||[]).filter(o=>o!==e).map(o=>({role:o.role,name:o.name})).slice(0,3)),r.level=this.calculateLevel(e,t),r.path=this.buildPath(e,t),r}findParent(e,t,r=t){if(!r||!r.children)return null;if(r.children.includes(e))return r;for(let n of r.children){let o=this.findParent(e,t,n);if(o)return o}return null}calculateLevel(e,t,r=t,n=0){if(r===e)return n;if(r.children)for(let o of r.children){let i=this.calculateLevel(e,t,o,n+1);if(i>=0)return i}return-1}buildPath(e,t,r=t,n=[]){if(r===e)return[...n,{role:r.role,name:r.name}];if(r.children)for(let o of r.children){let i=this.buildPath(e,t,o,[...n,{role:r.role,name:r.name}]);if(i)return i}return null}hashAxSubtree(e){let t=JSON.stringify({role:e.role,name:e.name,children:(e.children||[]).map(r=>({role:r.role,name:r.name}))});return Vr.createHash("md5").update(t).digest("hex").substring(0,12)}hashAxPath(e){let t=e.map(r=>`${r.role}:${r.name}`).join("/");return Vr.createHash("md5").update(t).digest("hex").substring(0,12)}};var fe=class extends z{constructor(e={}){super(e),this.pendingRequests=new Set,this.setupNetworkTracking=!1}getName(){return"PageStateEnricher"}getPriority(){return 95}canEnrich(e){return this.enabled&&e.page}async setupTracking(e){this.setupNetworkTracking||(e.on("request",t=>{["document","xhr","fetch"].includes(t.resourceType())&&this.pendingRequests.add(t.url())}),e.on("requestfinished",t=>{this.pendingRequests.delete(t.url())}),e.on("requestfailed",t=>{this.pendingRequests.delete(t.url())}),this.setupNetworkTracking=!0)}async enrich(e,t){try{let{page:r}=t;await this.setupTracking(r);let n=await r.evaluate(()=>({readyState:document.readyState,domContentLoaded:document.readyState!=="loading",loadComplete:document.readyState==="complete",url:document.location.href})),o=await this.checkDOMStability(r);return{page:{networkIdle:this.pendingRequests.size===0,pendingRequests:this.pendingRequests.size,domStable:o,...n}}}catch(r){return this.handleError(r,e)}}async checkDOMStability(e,t=500){try{return await e.evaluate(n=>new Promise(o=>{let i,c=0,a=new MutationObserver(()=>{c++,clearTimeout(i),i=setTimeout(()=>{a.disconnect(),o(c===0)},n)});a.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),i=setTimeout(()=>{a.disconnect(),o(!0)},n)}),t)}catch{return!1}}reset(){this.pendingRequests.clear(),this.setupNetworkTracking=!1}};var $e=class extends z{getName(){return"DOMEnricher"}getPriority(){return 85}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{element:r}=t,n=await r.evaluate(o=>{let i=f=>{let g=[],y=f;for(;y&&y!==document.body;){let h=y.tagName.toLowerCase(),b=y.parentElement;if(b){let w=Array.from(b.children).filter(v=>v.tagName===y.tagName);if(w.length>1){let v=w.indexOf(y)+1;h+=`:nth-child(${v})`}}g.unshift(h),y=y.parentElement}return`body > ${g.join(" > ")}`},c=f=>{let g=[],y=f;for(;y&&y!==document.body;){let h=1,b=y.previousSibling;for(;b;)b.nodeType===1&&b.tagName===y.tagName&&h++,b=b.previousSibling;let w=y.tagName.toLowerCase();g.unshift(`${w}[${h}]`),y=y.parentElement}return`/html/body/${g.join("/")}`},a={};for(let f of o.attributes)a[f.name]=f.value;let l=window.getComputedStyle(o),u={display:l.display,visibility:l.visibility,opacity:l.opacity,pointerEvents:l.pointerEvents},m=0,d=o.parentElement;for(;d;)m++,d=d.parentElement;return{path:i(o),xpath:c(o),depth:m,parent:o.parentElement?o.parentElement.tagName.toLowerCase():null,tagName:o.tagName.toLowerCase(),attributes:a,state:{visible:l.display!=="none"&&l.visibility!=="hidden",enabled:!o.disabled,focused:document.activeElement===o,...u}}});return{dom:{path:n.path,xpath:n.xpath,depth:n.depth,parent:n.parent,selector:this.buildSmartSelector(n)},attributes:n.attributes,state:n.state}}catch(r){return this.handleError(r,e)}}buildSmartSelector(e){let t=e.tagName;if(e.attributes.id)return`#${e.attributes.id}`;if(e.attributes["data-test-id"])return`[data-test-id="${e.attributes["data-test-id"]}"]`;if(e.attributes.class){let r=e.attributes.class.split(" ").filter(n=>n&&!n.match(/^(active|focus|hover|disabled)/));r.length>0&&(t+=`.${r.slice(0,2).join(".")}`)}return e.parent&&(t=`${e.parent} > ${t}`),t}};var He=class extends z{constructor(e={}){super(e),this.priority=200}getName(){return"MCPRef"}getPriority(){return this.priority}async enrich(e,t){let r=e.data?.params?.ref,n=e.data?.params?.element;if(!r&&!n)return null;let o=null,i=null,c=null;if(t?.element)try{let a=await t.element.evaluate(l=>({text:l.textContent?.trim()||"",innerText:l.innerText?.trim()||"",value:l.value||"",label:l.getAttribute("aria-label")||l.getAttribute("label")||"",role:l.getAttribute("role")||l.tagName.toLowerCase(),placeholder:l.getAttribute("placeholder")||"",title:l.getAttribute("title")||""}));o=a.text||a.innerText||a.value||a.placeholder,i=a.role,c=a.label||a.title,console.log(`[MCPRefEnricher] \u2705 Captured actual text: "${o}" (AI said: "${n}")`)}catch(a){console.log(`[MCPRefEnricher] \u26A0\uFE0F Could not extract actual text: ${a.message}`)}return{mcpRef:r,mcpElement:n,actualText:o,actualRole:i,actualLabel:c,recordedSelector:o||n}}};function Mt(s={}){let e=new ee(s);return s.enableMCPRef!==!1&&e.register(new He(s)),s.enableTraceText!==!1&&e.register(new ue(s)),s.enableAccessibility!==!1&&e.register(new pe(s)),s.enablePageState!==!1&&e.register(new fe(s)),s.enablePosition!==!1&&e.register(new Ae(s)),s.enableDOM!==!1&&e.register(new $e(s)),e}function Ut(s={}){let e=new ee(s);return e.register(new pe(s)),e.register(new fe(s)),e}function
|
|
313
|
+
Registered enrichers (${this.enrichers.length}):`);for(let e of this.enrichers){let t=e.enabled?"\u2713":"\u2717",r=this.stats.errors[e.getName()]||0,n=r>0?` (${r} errors)`:"";console.log(` ${t} ${e.getName()} (priority: ${e.getPriority()})${n}`)}console.log()}};var Ae=class extends z{getName(){return"PositionEnricher"}getPriority(){return 90}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:n}=t,o=await n.boundingBox();if(!o)return null;let i=await r.evaluate(()=>({scrollX:window.scrollX,scrollY:window.scrollY,width:window.innerWidth,height:window.innerHeight})),c=o.y>=i.scrollY&&o.y+o.height<=i.scrollY+i.height&&o.x>=0&&o.x+o.width<=i.width;return{position:{boundingBox:o,viewport:i,inViewport:c,centerPoint:{x:Math.round(o.x+o.width/2),y:Math.round(o.y+o.height/2)}}}}catch(r){return this.handleError(r,e)}}};import Vr from"node:crypto";var pe=class extends z{getName(){return"AccessibilityEnricher"}getPriority(){return 100}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{page:r,element:n}=t,o=await r.accessibility.snapshot(),i=await this.findAxNode(n,o);if(!i)return null;let c=await this.getAxContext(i,o),a=this.hashAxSubtree(i),l=this.hashAxPath(c.path);return{accessibility:{role:i.role,name:i.name||"",level:c.level,parent:c.parent,siblings:c.siblings,axTreeHash:a,axPathHash:l}}}catch(r){return this.handleError(r,e)}}async findAxNode(e,t){let r=await e.evaluate(n=>({role:n.getAttribute("role")||n.tagName.toLowerCase(),name:n.getAttribute("aria-label")||n.textContent?.trim()||"",tagName:n.tagName.toLowerCase()}));return this.searchAxTree(t,r)}searchAxTree(e,t){if(!e)return null;if(e.role===t.role&&(e.name||"").includes(t.name.substring(0,20)))return e;if(e.children)for(let r of e.children){let n=this.searchAxTree(r,t);if(n)return n}return null}getAxContext(e,t){let r={level:0,parent:null,siblings:[],path:[]},n=this.findParent(e,t);return n&&(r.parent={role:n.role,name:n.name},r.siblings=(n.children||[]).filter(o=>o!==e).map(o=>({role:o.role,name:o.name})).slice(0,3)),r.level=this.calculateLevel(e,t),r.path=this.buildPath(e,t),r}findParent(e,t,r=t){if(!r||!r.children)return null;if(r.children.includes(e))return r;for(let n of r.children){let o=this.findParent(e,t,n);if(o)return o}return null}calculateLevel(e,t,r=t,n=0){if(r===e)return n;if(r.children)for(let o of r.children){let i=this.calculateLevel(e,t,o,n+1);if(i>=0)return i}return-1}buildPath(e,t,r=t,n=[]){if(r===e)return[...n,{role:r.role,name:r.name}];if(r.children)for(let o of r.children){let i=this.buildPath(e,t,o,[...n,{role:r.role,name:r.name}]);if(i)return i}return null}hashAxSubtree(e){let t=JSON.stringify({role:e.role,name:e.name,children:(e.children||[]).map(r=>({role:r.role,name:r.name}))});return Vr.createHash("md5").update(t).digest("hex").substring(0,12)}hashAxPath(e){let t=e.map(r=>`${r.role}:${r.name}`).join("/");return Vr.createHash("md5").update(t).digest("hex").substring(0,12)}};var fe=class extends z{constructor(e={}){super(e),this.pendingRequests=new Set,this.setupNetworkTracking=!1}getName(){return"PageStateEnricher"}getPriority(){return 95}canEnrich(e){return this.enabled&&e.page}async setupTracking(e){this.setupNetworkTracking||(e.on("request",t=>{["document","xhr","fetch"].includes(t.resourceType())&&this.pendingRequests.add(t.url())}),e.on("requestfinished",t=>{this.pendingRequests.delete(t.url())}),e.on("requestfailed",t=>{this.pendingRequests.delete(t.url())}),this.setupNetworkTracking=!0)}async enrich(e,t){try{let{page:r}=t;await this.setupTracking(r);let n=await r.evaluate(()=>({readyState:document.readyState,domContentLoaded:document.readyState!=="loading",loadComplete:document.readyState==="complete",url:document.location.href})),o=await this.checkDOMStability(r);return{page:{networkIdle:this.pendingRequests.size===0,pendingRequests:this.pendingRequests.size,domStable:o,...n}}}catch(r){return this.handleError(r,e)}}async checkDOMStability(e,t=500){try{return await e.evaluate(n=>new Promise(o=>{let i,c=0,a=new MutationObserver(()=>{c++,clearTimeout(i),i=setTimeout(()=>{a.disconnect(),o(c===0)},n)});a.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),i=setTimeout(()=>{a.disconnect(),o(!0)},n)}),t)}catch{return!1}}reset(){this.pendingRequests.clear(),this.setupNetworkTracking=!1}};var $e=class extends z{getName(){return"DOMEnricher"}getPriority(){return 85}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,t){try{let{element:r}=t,n=await r.evaluate(o=>{let i=f=>{let g=[],y=f;for(;y&&y!==document.body;){let h=y.tagName.toLowerCase(),b=y.parentElement;if(b){let w=Array.from(b.children).filter(v=>v.tagName===y.tagName);if(w.length>1){let v=w.indexOf(y)+1;h+=`:nth-child(${v})`}}g.unshift(h),y=y.parentElement}return`body > ${g.join(" > ")}`},c=f=>{let g=[],y=f;for(;y&&y!==document.body;){let h=1,b=y.previousSibling;for(;b;)b.nodeType===1&&b.tagName===y.tagName&&h++,b=b.previousSibling;let w=y.tagName.toLowerCase();g.unshift(`${w}[${h}]`),y=y.parentElement}return`/html/body/${g.join("/")}`},a={};for(let f of o.attributes)a[f.name]=f.value;let l=window.getComputedStyle(o),u={display:l.display,visibility:l.visibility,opacity:l.opacity,pointerEvents:l.pointerEvents},m=0,d=o.parentElement;for(;d;)m++,d=d.parentElement;return{path:i(o),xpath:c(o),depth:m,parent:o.parentElement?o.parentElement.tagName.toLowerCase():null,tagName:o.tagName.toLowerCase(),attributes:a,state:{visible:l.display!=="none"&&l.visibility!=="hidden",enabled:!o.disabled,focused:document.activeElement===o,...u}}});return{dom:{path:n.path,xpath:n.xpath,depth:n.depth,parent:n.parent,selector:this.buildSmartSelector(n)},attributes:n.attributes,state:n.state}}catch(r){return this.handleError(r,e)}}buildSmartSelector(e){let t=e.tagName;if(e.attributes.id)return`#${e.attributes.id}`;if(e.attributes["data-test-id"])return`[data-test-id="${e.attributes["data-test-id"]}"]`;if(e.attributes.class){let r=e.attributes.class.split(" ").filter(n=>n&&!n.match(/^(active|focus|hover|disabled)/));r.length>0&&(t+=`.${r.slice(0,2).join(".")}`)}return e.parent&&(t=`${e.parent} > ${t}`),t}};var He=class extends z{constructor(e={}){super(e),this.priority=200}getName(){return"MCPRef"}getPriority(){return this.priority}async enrich(e,t){let r=e.data?.params?.ref,n=e.data?.params?.element;if(!r&&!n)return null;let o=null,i=null,c=null;if(t?.element)try{let a=await t.element.evaluate(l=>({text:l.textContent?.trim()||"",innerText:l.innerText?.trim()||"",value:l.value||"",label:l.getAttribute("aria-label")||l.getAttribute("label")||"",role:l.getAttribute("role")||l.tagName.toLowerCase(),placeholder:l.getAttribute("placeholder")||"",title:l.getAttribute("title")||""}));o=a.text||a.innerText||a.value||a.placeholder,i=a.role,c=a.label||a.title,console.log(`[MCPRefEnricher] \u2705 Captured actual text: "${o}" (AI said: "${n}")`)}catch(a){console.log(`[MCPRefEnricher] \u26A0\uFE0F Could not extract actual text: ${a.message}`)}return{mcpRef:r,mcpElement:n,actualText:o,actualRole:i,actualLabel:c,recordedSelector:o||n}}};function Mt(s={}){let e=new ee(s);return s.enableMCPRef!==!1&&e.register(new He(s)),s.enableTraceText!==!1&&e.register(new ue(s)),s.enableAccessibility!==!1&&e.register(new pe(s)),s.enablePageState!==!1&&e.register(new fe(s)),s.enablePosition!==!1&&e.register(new Ae(s)),s.enableDOM!==!1&&e.register(new $e(s)),e}function Ut(s={}){let e=new ee(s);return e.register(new pe(s)),e.register(new fe(s)),e}function Xs(s,e={}){let t=new ee(e);for(let r of s)t.register(r);return t}import{readFileSync as qs,writeFileSync as Dt}from"node:fs";import{join as Wr}from"node:path";async function Qs(s,e={}){let t=Wr(s,"events.json"),r=Wr(s,"trace.zip");try{let n=JSON.parse(qs(t,"utf-8")),o=n.map(c=>({...c,_enrichmentNote:"Full enrichment requires live Playwright access. Use EnrichmentPipeline during test execution."})),i=`${t}.backup`;return Dt(i,JSON.stringify(n,null,2)),Dt(t,JSON.stringify(o,null,2)),{enrichedCount:o.length,skippedCount:0,errors:[]}}catch(n){return console.error("[EnrichmentIntegration] Failed to enrich events:",n.message),{enrichedCount:0,skippedCount:0,errors:[n.message]}}}var Ft=class{constructor(e={}){this.pipeline=e.minimal?Ut(e):Mt(e),this.events=[],this.config=e}async recordEvent(e,t,r){let n={id:this.events.length,type:e,timestamp:new Date().toISOString(),data:t},o=await this.pipeline.enrich(n,{...r,event:n});return this.events.push(o),o}saveEvents(e){Dt(e,JSON.stringify(this.events,null,2)),console.log(`[LiveEnrichment] Saved ${this.events.length} enriched events to ${e}`),this.pipeline.logStatus()}getStats(){return this.pipeline.getStats()}};St();var en=s=>{s?.message?.includes("Connection closed")||s?.message?.includes("MCP error -32000")||s?.code===-32e3||console.error("Unhandled rejection:",s)};process.listeners("unhandledRejection").includes(en)||process.on("unhandledRejection",en);async function ii(s,e={}){let{agent:t,mcp:r,headless:n,cwd:o=process.cwd(),specPath:i,sessionPath:c,sessionTimestamp:a,...l}=e,u=Zr(s,"utf-8"),m=null,{agent:d,error:f}=await ci(o,l),g=d;if(!g&&e.fallbackAgentModule){let b=e.fallbackAgentModule,w=b.BrowserTestAutomationAgent||b.default;w&&(g=new w(l))}if(!g&&f&&console.warn(`\u26A0\uFE0F Failed to load local agent: ${f}`),!g)throw new Error(`No agent found. Please run:
|
|
314
314
|
zibby init
|
|
315
315
|
|
|
316
316
|
This will create .zibby/graph.mjs with your workflow definition.`);await g.initialize(m);let y=!1,h=()=>{if(!y)try{o||process.cwd(),y=!0}catch(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(`
|
|
317
317
|
\u{1F3AF} Running Single Node: ${e.singleNode} (Framework Mode)
|
|
318
|
-
`);let T=g.calculateOutputPath(i||s),O=g.buildGraph(),U={};for(let[$,P]of O.nodes.entries())U[$]=P.config||P;let E={};if(e.sessionId){let $=e.sessionId,P=e.paths?.output||
|
|
318
|
+
`);let T=g.calculateOutputPath(i||s),O=g.buildGraph(),U={};for(let[$,P]of O.nodes.entries())U[$]=P.config||P;let E={};if(e.sessionId){let $=e.sessionId,P=e.paths?.output||ti;if($==="last"){let M=Ie(o,P,Qr);if(Xr(M)){let{readdirSync:j,statSync:A}=await import("fs"),_=j(M).filter(L=>A(Ie(M,L)).isDirectory()).map(L=>({name:L,time:A(Ie(M,L)).mtimeMs})).sort((L,D)=>D.time-L.time);_.length>0?($=_[0].name,console.log(`\u{1F4C2} Using latest session: ${$}`)):console.log(`\u26A0\uFE0F No sessions found in ${M}`)}}let B=Ie(o,P,Qr,$),k=Ie(B,"execute_live"),x=Ie(k,ri);Xr(x)?(console.log(`\u{1F4C2} Loading session: ${$}`),E={sessionPath:B,execute_live_output:JSON.parse(Zr(x,"utf-8"))}):console.log(`\u26A0\uFE0F Session not found: ${B}`)}let C=await g.runSingleNode(e.singleNode,U,{testSpec:u,outputPath:T,cwd:o||process.cwd(),contextConfig:e.contextConfig,specPath:i||s,config:e,...E});return typeof g.onComplete=="function"&&await g.onComplete(C),C}let b;typeof e.onPipelineProgress=="function"?b=e.onPipelineProgress:e.runIndex?.pipelineProgress!==!1&&(b=yr({cwd:o||process.cwd(),config:e}));let w=o||process.cwd(),v=c!=null&&String(c).trim()!==""?(()=>{let T=String(c).trim();try{return ei(T)?qr(T):qr(w,T)}catch{return T}})():void 0,S=si(),I=v??S;oi();let R=ni({cwd:w,config:e,traceFrom:"runTest",initialState:{sessionPath:I,sessionTimestamp:a}}),N;try{N=await g.run(u,{testSpec:u,specPath:i||s,cwd:w,config:e,sessionPath:R.sessionPath,sessionTimestamp:R.sessionTimestamp,...b?{onPipelineProgress:b}:{}})}catch(T){throw typeof T?.message=="string"&&T.message.includes("Interrupted by user")&&(o||process.cwd(),void 0),y||(T?.partialResult,T?.message,void 0),T}return N}finally{process.off("SIGINT",h),process.off("SIGTERM",h),await g.cleanup()}}function ai(s){return s.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function li(s,e){if(s[e])return s[e];let t=ai(e);if(s[t])return s[t];let r=`${t}Workflow`;return s[r]?s[r]:null}async function mp(s=process.cwd()){try{let{join:e}=await import("path"),{existsSync:t}=await import("fs"),{pathToFileURL:r}=await import("url"),n=e(s,".zibby/graph.mjs");if(!t(n))return{available:[],default:null,error:"No .zibby/graph.mjs found"};let o=await import(r(n).href),i=Object.keys(o).filter(a=>a!=="default"&&typeof o[a]=="function"&&o[a].prototype instanceof we),c=o.BrowserTestAutomationAgent?"BrowserTestAutomationAgent":o.CursorAgent?"CursorAgent":o.default?"default":i[0]||null;return{available:i,default:c,error:null}}catch(e){return{available:[],default:null,error:e.message}}}async function ci(s,e){try{let{join:t}=await import("path"),{existsSync:r}=await import("fs"),{pathToFileURL:n}=await import("url"),o=t(s,".zibby/graph.mjs");if(!r(o))return{agent:null,error:null};let i=await import(n(o).href),c=e.workflow,a;if(c){if(a=li(i,c),!a){let u=Object.keys(i).filter(m=>m!=="default"&&typeof i[m]=="function");throw new Error(`Workflow "${c}" not found.
|
|
319
319
|
Available workflows: ${u.join(", ")}
|
|
320
|
-
Supported formats: QuickSmokeWorkflow, QuickSmoke, quick-smoke`)}let l=Object.keys(i).find(u=>i[u]===a);console.log(`\u2713 Using workflow: ${l} (from --workflow ${c})`)}else{if(a=i.BrowserTestAutomationAgent||i.CursorAgent||i.default,!a){let l=Object.keys(i).filter(u=>u!=="default"&&typeof i[u]=="function"&&i[u].prototype instanceof we);l.length>0&&(a=i[l[0]],console.log(`\u2713 Using workflow: ${l[0]} (auto-detected)`))}if(!a)return{agent:null,error:"Could not find any WorkflowAgent export in local graph.js"};a.name?.includes("auto-detected")||console.log("\u2713 Using local agent from .zibby/graph.mjs")}return{agent:new a(e),error:null}}catch(t){return{agent:null,error:t.message}}}var tn=class{constructor(e={}){this.config=e}async run(e){return
|
|
320
|
+
Supported formats: QuickSmokeWorkflow, QuickSmoke, quick-smoke`)}let l=Object.keys(i).find(u=>i[u]===a);console.log(`\u2713 Using workflow: ${l} (from --workflow ${c})`)}else{if(a=i.BrowserTestAutomationAgent||i.CursorAgent||i.default,!a){let l=Object.keys(i).filter(u=>u!=="default"&&typeof i[u]=="function"&&i[u].prototype instanceof we);l.length>0&&(a=i[l[0]],console.log(`\u2713 Using workflow: ${l[0]} (auto-detected)`))}if(!a)return{agent:null,error:"Could not find any WorkflowAgent export in local graph.js"};a.name?.includes("auto-detected")||console.log("\u2713 Using local agent from .zibby/graph.mjs")}return{agent:new a(e),error:null}}catch(t){return{agent:null,error:t.message}}}var tn=class{constructor(e={}){this.config=e}async run(e){return ii(e.spec||e.specPath,{...this.config,...e})}};export{un as AGENT_TYPES,Kl as ALL_TOOLS,pe as AccessibilityEnricher,Do as AgentStrategy,ce as AssistantStrategy,zo as CHAT_MEMORY_TOOLS,rf as CI_ENV_VARS,Ze as CLAUDE_MODEL_MAP,Xe as CODEX_MODEL_MAP,pn as CORE_LOG_LEVELS,Fo as CORE_TOOLS,oe as ClaudeAgentStrategy,se as CodexAgentStrategy,re as CursorAgentStrategy,ks as DEFAULT_MAX_CONCURRENT_RUNS,J as DEFAULT_MODELS,Zp as DEFAULT_OUTPUT_BASE,$e as DOMEnricher,tf as EVENTS_FILE,ee as EnrichmentPipeline,z as EventEnricher,pt as GEMINI_MODEL_MAP,Bo as GITHUB_TOOLS,ae as GeminiAgentStrategy,jo as JIRA_TOOLS,H as LOG_LEVELS,Ft as LiveEnrichmentRecorder,We as Logger,Rs as MAX_MAX_CONCURRENT_RUNS,_e as MCPRefStrategy,Jo as MEMORY_TOOLS,Ns as MIN_MAX_CONCURRENT_RUNS,ke as MODEL_REGISTRY,Fe as McpClientManager,le as OpenAIToolProvider,fe as PageStateEnricher,Te as PlaywrightJsonVerificationStrategy,Ae as PositionEnricher,ef as RAW_OUTPUT_FILE,Qp as RESULT_FILE,Dr as RIPPLE_EFFECT_SCRIPT,Ko as RUNNER_TOOLS,Tt as ResultHandler,Xp as SESSIONS_DIR,qp as SESSION_INFO_FILE,kp as SKILLS,Yo as SKILL_TOOLS,Go as SLACK_TOOLS,Ke as SelectorGenerator,Nt as StableIdRuntime,Ee as StableIdStrategy,W as StreamingParser,tn as TestAutomation,Q as TestGenerationStrategy,Ct as TestPostProcessor,ve as TestVerificationStrategy,he as ToolCallProvider,ze as TraceParser,we as WorkflowAgent,yp as WorkflowGraph,kt as ZibbyRuntime,Be as ZibbyUploader,Ne as buildVendorModelMap,Eo as checkCursorAgentInstalled,Es as checkCursorAgentPatched,wp as clearInheritedSessionEnvForFreshRun,rs as clearTokenCache,fs as cloneRepo,Xs as createCustomPipeline,Mt as createDefaultPipeline,Ut as createMinimalPipeline,Ar as createUploader,Qs as enrichRecordedEvents,Is as generateRippleHelperCode,Sp as generateWorkflowSessionId,Er as getAgentStrategy,Up as getAllSkills,vs as getApprovalKeys,vo as getCursorAgentInstallInstructions,cn as getPickerModels,Lp as getSkill,Mp as hasSkill,$s as injectRippleEffect,Uo as invokeAgent,Dp as listSkillIds,mp as listWorkflows,p as logger,is as organizeVideos,_s as patchCursorAgentForCI,Y as pickFromPool,Fs as postProcessEvents,_p as readPinnedSessionPathFromEnv,St as registerBuiltInStrategies,Rp as registerSkill,Js as resetExecutionCount,ts as resolveIntegrationToken,Ls as resolveMaxParallelRuns,an as resolveModelFamily,bp as resolveWorkflowSession,zr as runPlaywrightTestTool,ii as runTest,As as saveApprovalKeys,Lr as sessionSkill,xp as shouldTrustInheritedSessionEnv,Ep as syncProcessEnvToSession,Hs as testGenerationManager,Zs as testVerificationManager,Z as timeline,Ro as workflow,Ap as z};
|
package/dist/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zibby/core",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.9",
|
|
4
4
|
"description": "Core test automation engine with multi-agent and multi-MCP support",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -50,10 +50,10 @@
|
|
|
50
50
|
"homepage": "https://zibby.dev",
|
|
51
51
|
"repository": {
|
|
52
52
|
"type": "git",
|
|
53
|
-
"url": "https://github.com/
|
|
53
|
+
"url": "https://github.com/ZibbyDev/zibby-agent"
|
|
54
54
|
},
|
|
55
55
|
"bugs": {
|
|
56
|
-
"url": "https://github.com/
|
|
56
|
+
"url": "https://github.com/ZibbyDev/zibby-agent/issues"
|
|
57
57
|
},
|
|
58
58
|
"files": [
|
|
59
59
|
"dist/",
|
|
@@ -69,7 +69,7 @@
|
|
|
69
69
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
70
70
|
"@openai/codex-sdk": "^0.120.0",
|
|
71
71
|
"@playwright/mcp": "^0.0.70",
|
|
72
|
-
"@zibby/agent-workflow": "^0.4.
|
|
72
|
+
"@zibby/agent-workflow": "^0.4.13",
|
|
73
73
|
"@zibby/mcp-browser": "^0.1.8",
|
|
74
74
|
"acorn": "^8.15.0",
|
|
75
75
|
"acorn-walk": "^8.3.5",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zibby/core",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.9",
|
|
4
4
|
"description": "Core test automation engine with multi-agent and multi-MCP support",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -50,10 +50,10 @@
|
|
|
50
50
|
"homepage": "https://zibby.dev",
|
|
51
51
|
"repository": {
|
|
52
52
|
"type": "git",
|
|
53
|
-
"url": "https://github.com/
|
|
53
|
+
"url": "https://github.com/ZibbyDev/zibby-agent"
|
|
54
54
|
},
|
|
55
55
|
"bugs": {
|
|
56
|
-
"url": "https://github.com/
|
|
56
|
+
"url": "https://github.com/ZibbyDev/zibby-agent/issues"
|
|
57
57
|
},
|
|
58
58
|
"files": [
|
|
59
59
|
"dist/",
|
|
@@ -69,7 +69,7 @@
|
|
|
69
69
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
70
70
|
"@openai/codex-sdk": "^0.120.0",
|
|
71
71
|
"@playwright/mcp": "^0.0.70",
|
|
72
|
-
"@zibby/agent-workflow": "^0.4.
|
|
72
|
+
"@zibby/agent-workflow": "^0.4.13",
|
|
73
73
|
"@zibby/mcp-browser": "^0.1.8",
|
|
74
74
|
"acorn": "^8.15.0",
|
|
75
75
|
"acorn-walk": "^8.3.5",
|