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