@zibby/core 0.1.38 → 0.1.41

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.
@@ -1,22 +1,22 @@
1
- var vo=Object.defineProperty;var R=(i,e)=>()=>(i&&(e=i(i=0)),e);var Pe=(i,e)=>{for(var t in e)vo(i,t,{get:e[t],enumerable:!0})};var X,Re=R(()=>{X=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(`
1
+ var Po=Object.defineProperty;var B=(i,e)=>()=>(i&&(e=i(i=0)),e);var Re=(i,e)=>{for(var t in e)Po(i,t,{get:e[t],enumerable:!0})};var V,Me=B(()=>{V=class i{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(e){if(!e)return null;this.buffer+=e;let t=this.buffer.split(`
2
2
  `);this.buffer=t.pop()||"";let o="";for(let s of t)if(s.trim())try{let r=JSON.parse(s);this._emitToolCalls(r);let n=this.extractText(r);if(n){if(this.rawText&&n.startsWith(this.rawText)){let a=n.substring(this.rawText.length);this.rawText=n,o+=a}else(!this.rawText.includes(n)||n.length<20)&&(this.rawText+=n,o+=n);this.tryExtractResult(this.rawText)}else this.isValidResult(r)&&(this.rawText+=`${s}
3
3
  `,o+=`${s}
4
- `,this.extractedResult=r)}catch{if(s.includes('"text"')||s.includes('"content"')){let n=s.match(/"text"\s*:\s*"([^"]*)/),a=s.match(/"content"\s*:\s*"([^"]*)/),l=n?n[1]:a?a[1]:null;l&&!this.rawText.includes(l)&&(o+=l,this.rawText+=l)}}return o||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let o=this.extractText(t);o&&(this.rawText+=o,e+=o,this.tryExtractResult(o))}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=(n,a)=>{if(!n)return;let l=`${n}:${JSON.stringify(a??{})}`;this._lastToolEmit!==l&&(this._lastToolEmit=l,this.onToolCall(n,a??void 0))},o=n=>{if(n!=null){if(typeof n=="object"&&!Array.isArray(n))return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,o(e.input??e.arguments));return}let n=e.tool_call;if(n&&typeof n=="object"&&!Array.isArray(n)){let a=Object.keys(n);if(a.length===1){let l=a[0],c=n[l],f=c&&typeof c=="object"?c.args??c.input??c:void 0;t(l,o(f))}return}return}if(Array.isArray(e.tool_calls)){for(let n of e.tool_calls)t(n.name,o(n.input??n.arguments));return}let s=e.message??e;if(Array.isArray(s?.tool_calls)){for(let n of s.tool_calls)t(n.name,o(n.input??n.arguments));return}let r=s?.content??e.content;if(Array.isArray(r))for(let n of r)(n.type==="tool_use"||n.type==="tool_call")&&n.name&&t(n.name,o(n.input??n.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(o=>o.type==="text"&&o.text).map(o=>o.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=[],o=/```json\s*\n?([\s\S]*?)\n?```/g,s;for(;(s=o.exec(e))!==null;){let p=s[1].trim();try{JSON.parse(p),t.push({text:p,source:"markdown"})}catch{}}let r=0,n=0;for(;r<e.length&&(r=e.indexOf("{",r),r!==-1);){let p=0,d=r;for(let _=r;_<e.length;_++)if(e[_]==="{")p++;else if(e[_]==="}"&&(p--,p===0)){d=_,t.push({text:e.substring(r,d+1),source:"brace"}),n++;break}r=d+1}let a=this.extractedResult,l=a?JSON.stringify(a).length:0,c=0,f=-1;for(let p=0;p<t.length;p++){let d=t[p];try{let _=d.text.replace(/,(\s*[}\]])/g,"$1"),h=JSON.parse(_);this.isValidResult(h)&&(c++,l=JSON.stringify(h).length,a=h,f=p)}catch{}}a&&(this.extractedResult=a)}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 o=new i;o.zodSchema=t,o.processChunk(e),o.flush();let s=o.getResult();return!s&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),s}}});var q,Me,W,Le,At,he=R(()=>{q=".zibby/output",Me="sessions",W=".session-info.json",Le=".zibby-studio-stop",At=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"]});var vt={};Pe(vt,{WorkflowState:()=>ye});function qe(i){if(Ro.has(i))throw new Error(`Invalid state key: "${i}"`)}var Ro,ye,Ve=R(()=>{Ro=new Set(["__proto__","constructor","prototype"]);ye=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){qe(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let o of t)qe(o);this._history.push({...this._state});for(let o of t)this._state[o]=e[o]}append(e,t){qe(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}}});var De,Ct=R(()=>{De=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let o=e.match(/\{[\s\S]*\}/);return o?this.validate(JSON.parse(o[0])):this.validate({result:e.trim()})}validate(e){let t=[];for(let[o,s]of Object.entries(this.schema)){if(s.required&&!(o in e)&&t.push(`Missing required field: ${o}`),o in e&&s.type){let r=typeof e[o];r!==s.type&&t.push(`Field '${o}' expected ${s.type}, got ${r}`)}if(s.validate&&o in e){let r=s.validate(e[o]);r&&t.push(`Field '${o}': ${r}`)}}if(t.length>0)throw new Error(`Output validation failed:
4
+ `,this.extractedResult=r)}catch{if(s.includes('"text"')||s.includes('"content"')){let n=s.match(/"text"\s*:\s*"([^"]*)/),a=s.match(/"content"\s*:\s*"([^"]*)/),l=n?n[1]:a?a[1]:null;l&&!this.rawText.includes(l)&&(o+=l,this.rawText+=l)}}return o||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let o=this.extractText(t);o&&(this.rawText+=o,e+=o,this.tryExtractResult(o))}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=(n,a)=>{if(!n)return;let l=`${n}:${JSON.stringify(a??{})}`;this._lastToolEmit!==l&&(this._lastToolEmit=l,this.onToolCall(n,a??void 0))},o=n=>{if(n!=null){if(typeof n=="object"&&!Array.isArray(n))return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,o(e.input??e.arguments));return}let n=e.tool_call;if(n&&typeof n=="object"&&!Array.isArray(n)){let a=Object.keys(n);if(a.length===1){let l=a[0],c=n[l],p=c&&typeof c=="object"?c.args??c.input??c:void 0;t(l,o(p))}return}return}if(Array.isArray(e.tool_calls)){for(let n of e.tool_calls)t(n.name,o(n.input??n.arguments));return}let s=e.message??e;if(Array.isArray(s?.tool_calls)){for(let n of s.tool_calls)t(n.name,o(n.input??n.arguments));return}let r=s?.content??e.content;if(Array.isArray(r))for(let n of r)(n.type==="tool_use"||n.type==="tool_call")&&n.name&&t(n.name,o(n.input??n.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(o=>o.type==="text"&&o.text).map(o=>o.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=[],o=/```json\s*\n?([\s\S]*?)\n?```/g,s;for(;(s=o.exec(e))!==null;){let f=s[1].trim();try{JSON.parse(f),t.push({text:f,source:"markdown"})}catch{}}let r=0,n=0;for(;r<e.length&&(r=e.indexOf("{",r),r!==-1);){let f=0,g=r;for(let S=r;S<e.length;S++)if(e[S]==="{")f++;else if(e[S]==="}"&&(f--,f===0)){g=S,t.push({text:e.substring(r,g+1),source:"brace"}),n++;break}r=g+1}let a=this.extractedResult,l=a?JSON.stringify(a).length:0,c=0,p=-1;for(let f=0;f<t.length;f++){let g=t[f];try{let S=g.text.replace(/,(\s*[}\]])/g,"$1"),h=JSON.parse(S);this.isValidResult(h)&&(c++,l=JSON.stringify(h).length,a=h,p=f)}catch{}}a&&(this.extractedResult=a)}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 o=new i;o.zodSchema=t,o.processChunk(e),o.flush();let s=o.getResult();return!s&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),s}}});var Q,Le,H,De,vt,Se=B(()=>{Q=".zibby/output",Le="sessions",H=".session-info.json",De=".zibby-studio-stop",vt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"]});var Ct={};Re(Ct,{WorkflowState:()=>_e});function Ve(i){if(Lo.has(i))throw new Error(`Invalid state key: "${i}"`)}var Lo,_e,Qe=B(()=>{Lo=new Set(["__proto__","constructor","prototype"]);_e=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){Ve(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let o of t)Ve(o);this._history.push({...this._state});for(let o of t)this._state[o]=e[o]}append(e,t){Ve(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}}});var Be,Pt=B(()=>{Be=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let o=e.match(/\{[\s\S]*\}/);return o?this.validate(JSON.parse(o[0])):this.validate({result:e.trim()})}validate(e){let t=[];for(let[o,s]of Object.entries(this.schema)){if(s.required&&!(o in e)&&t.push(`Missing required field: ${o}`),o in e&&s.type){let r=typeof e[o];r!==s.type&&t.push(`Field '${o}' expected ${s.type}, got ${r}`)}if(s.validate&&o in e){let r=s.validate(e[o]);r&&t.push(`Field '${o}': ${r}`)}}if(t.length>0)throw new Error(`Output validation failed:
5
5
  ${t.join(`
6
- `)}`);return e}}});import Se from"chalk";var z,Qe,u,H=R(()=>{z={debug:0,info:1,warn:2,error:3,silent:4},Qe=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return z.debug;if(process.env.ZIBBY_VERBOSE==="true")return z.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in z?z[e]:z.info}_shouldLog(e){return z[e]>=this._level}_formatMessage(e,t,o={}){let s=new Date().toISOString(),n=`${this._getPrefix(e)} ${t}`;return Object.keys(o).length>0&&(n+=Se.dim(` ${JSON.stringify(o)}`)),n}_getPrefix(e){return{debug:Se.gray("[DEBUG]"),info:Se.cyan("[INFO]"),warn:Se.yellow("[WARN]"),error:Se.red("\u274C [ERROR]")}[e]||""}debug(e,t){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,t))}info(e,t){this._shouldLog("info")&&console.log(this._formatMessage("info",e,t))}warn(e,t){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,t))}error(e,t){this._shouldLog("error")&&console.error(this._formatMessage("error",e,t))}setLevel(e){e in z&&(this._level=z[e])}getLevel(){return Object.keys(z).find(e=>z[e]===this._level)}},u=new Qe});import U from"chalk";function Lt(i){return i<1e3?`${i}ms`:`${(i/1e3).toFixed(1)}s`}function Dt(i,e){return(t,o,s)=>{if(typeof t!="string")return i(t,o,s);let r=process.stdout.columns||120,n="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(n+=Rt,e.col=Mt,e.lineStart=!1),l===`
6
+ `)}`);return e}}});import we from"chalk";var Z,et,u,X=B(()=>{Z={debug:0,info:1,warn:2,error:3,silent:4},et=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return Z.debug;if(process.env.ZIBBY_VERBOSE==="true")return Z.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in Z?Z[e]:Z.info}_shouldLog(e){return Z[e]>=this._level}_formatMessage(e,t,o={}){let s=new Date().toISOString(),n=`${this._getPrefix(e)} ${t}`;return Object.keys(o).length>0&&(n+=we.dim(` ${JSON.stringify(o)}`)),n}_getPrefix(e){return{debug:we.gray("[DEBUG]"),info:we.cyan("[INFO]"),warn:we.yellow("[WARN]"),error:we.red("\u274C [ERROR]")}[e]||""}debug(e,t){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,t))}info(e,t){this._shouldLog("info")&&console.log(this._formatMessage("info",e,t))}warn(e,t){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,t))}error(e,t){this._shouldLog("error")&&console.error(this._formatMessage("error",e,t))}setLevel(e){e in Z&&(this._level=Z[e])}getLevel(){return Object.keys(Z).find(e=>Z[e]===this._level)}},u=new et});import F from"chalk";function Dt(i){return i<1e3?`${i}ms`:`${(i/1e3).toFixed(1)}s`}function Bt(i,e){return(t,o,s)=>{if(typeof t!="string")return i(t,o,s);let r=process.stdout.columns||120,n="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(n+=Mt,e.col=Lt,e.lineStart=!1),l===`
7
7
  `?(n+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,n+=l):e.inEsc?(n+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,n+=l,e.col>=r&&(n+=`
8
- ${Rt}`,e.col=Mt))}return i(n,o,s)}}var Mo,_e,Lo,kt,et,Nt,Pt,tt,Rt,Mt,ot,L,ae=R(()=>{Mo="__WORKFLOW_GRAPH_LOG__",_e=U.gray("\u2502"),Lo=U.gray("\u250C"),kt=U.gray("\u2514"),et=U.green("\u25C6"),Nt=U.hex("#c084fc")("\u25C6"),Pt=U.hex("#2dd4bf")("\u25C6"),tt=U.red("\u25C6"),Rt=`${_e} `,Mt=2;ot=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null;let e=String(process.env.ZIBBY_RUN_SOURCE||"").trim().toLowerCase(),t=String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1";this._emitWorkflowGraphMarkers=t||e==="studio"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=Dt(this._origStdoutWrite,e),process.stderr.write=Dt(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
8
+ ${Mt}`,e.col=Lt))}return i(n,o,s)}}var Do,Ee,Bo,kt,tt,Nt,Rt,ot,Mt,Lt,st,U,ue=B(()=>{Do="__WORKFLOW_GRAPH_LOG__",Ee=F.gray("\u2502"),Bo=F.gray("\u250C"),kt=F.gray("\u2514"),tt=F.green("\u25C6"),Nt=F.hex("#c084fc")("\u25C6"),Rt=F.hex("#2dd4bf")("\u25C6"),ot=F.red("\u25C6"),Mt=`${Ee} `,Lt=2;st=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null;let e=String(process.env.ZIBBY_RUN_SOURCE||"").trim().toLowerCase(),t=String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1";this._emitWorkflowGraphMarkers=t||e==="studio"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=Bt(this._origStdoutWrite,e),process.stderr.write=Bt(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
9
9
  `),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
10
10
  `),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
11
- `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Mo}${JSON.stringify(e)}
11
+ `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Do}${JSON.stringify(e)}
12
12
  `;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
13
13
  `),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
14
14
  `)):process.stdout.write.bind(process.stdout)(`${e} ${t}
15
- `)}step(e){this._origStdoutWrite?this._writeDot(et,e):process.stdout.write.bind(process.stdout)(`${_e} ${et} ${e}
16
- `)}stepTool(e){this._origStdoutWrite?this._writeDot(Nt,e):process.stdout.write.bind(process.stdout)(`${_e} ${Nt} ${e}
17
- `)}stepMemory(e){let t=U.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(Pt,t):process.stdout.write.bind(process.stdout)(`${_e} ${Pt} ${t}
18
- `)}stepFail(e){this._origStdoutWrite?this._writeDot(tt,U.red(e)):process.stdout.write.bind(process.stdout)(`${_e} ${tt} ${U.red(e)}
19
- `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Lo} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:o,details:s}=t;if(s)for(let n of s)this._rawWrite(`${et} ${n}`);let r=o?U.dim(` ${Lt(o)}`):"";this._rawWrite(`${kt} ${U.green("done")}${r}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,o={}){this._stopIntercepting();let{duration:s}=o,r=s?U.dim(` ${Lt(s)}`):"";this._rawWrite(`${tt} ${U.red(t)}`),this._rawWrite(`${kt} ${U.red("failed")}${r}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(U.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){this._rawWrite(U.green.bold("\u2713 Workflow completed"))}},L=new ot});var J,ee=R(()=>{J=class{constructor(e,t,o=0){this.name=e,this.description=t,this.priority=o}async invoke(e,t={}){throw new Error("AgentStrategy.invoke() must be implemented by subclass")}canHandle(e){throw new Error("AgentStrategy.canHandle() must be implemented by subclass")}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var j,st,rt,Bt,Be,te=R(()=>{j={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"},st={auto:"claude-sonnet-4-6","sonnet-4.6":"claude-sonnet-4-6","sonnet-4-6":"claude-sonnet-4-6","opus-4.6":"claude-opus-4-6","opus-4-6":"claude-opus-4-6","sonnet-4.5":"claude-sonnet-4-5-20250929","sonnet-4-5":"claude-sonnet-4-5-20250929","opus-4.5":"claude-opus-4-20250514","opus-4-5":"claude-opus-4-20250514","claude-sonnet-4-6":"claude-sonnet-4-6","claude-opus-4-6":"claude-opus-4-6","claude-sonnet-4-5-20250929":"claude-sonnet-4-5-20250929","claude-opus-4-20250514":"claude-opus-4-20250514"},rt={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"},Bt={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},Be={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4}});var it={};Pe(it,{getAllSkills:()=>nt,getSkill:()=>F,hasSkill:()=>Bo,listSkillIds:()=>Uo,registerSkill:()=>Do});function Do(i){if(!i||typeof i.id!="string")throw new Error("Skill definition must include a string id");we.set(i.id,Object.freeze({...i}))}function F(i){return we.get(i)||null}function Bo(i){return we.has(i)}function nt(){return new Map(we)}function Uo(){return Array.from(we.keys())}var we,Q=R(()=>{we=new Map});import{zodToJsonSchema as jo}from"zod-to-json-schema";var le,at=R(()=>{le=class{static generateFileOutputInstructions(e,t){let o;typeof e?.parse=="function"?o=jo(e,{target:"openApi3"}):o=e;let s=this._buildExample(o);return`
15
+ `)}step(e){this._origStdoutWrite?this._writeDot(tt,e):process.stdout.write.bind(process.stdout)(`${Ee} ${tt} ${e}
16
+ `)}stepTool(e){this._origStdoutWrite?this._writeDot(Nt,e):process.stdout.write.bind(process.stdout)(`${Ee} ${Nt} ${e}
17
+ `)}stepMemory(e){let t=F.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(Rt,t):process.stdout.write.bind(process.stdout)(`${Ee} ${Rt} ${t}
18
+ `)}stepFail(e){this._origStdoutWrite?this._writeDot(ot,F.red(e)):process.stdout.write.bind(process.stdout)(`${Ee} ${ot} ${F.red(e)}
19
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Bo} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:o,details:s}=t;if(s)for(let n of s)this._rawWrite(`${tt} ${n}`);let r=o?F.dim(` ${Dt(o)}`):"";this._rawWrite(`${kt} ${F.green("done")}${r}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,o={}){this._stopIntercepting();let{duration:s}=o,r=s?F.dim(` ${Dt(s)}`):"";this._rawWrite(`${ot} ${F.red(t)}`),this._rawWrite(`${kt} ${F.red("failed")}${r}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(F.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){this._rawWrite(F.green.bold("\u2713 Workflow completed"))}},U=new st});var K,oe=B(()=>{K=class{constructor(e,t,o=0){this.name=e,this.description=t,this.priority=o}async invoke(e,t={}){throw new Error("AgentStrategy.invoke() must be implemented by subclass")}canHandle(e){throw new Error("AgentStrategy.canHandle() must be implemented by subclass")}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var J,rt,nt,Ut,Ue,se=B(()=>{J={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"},rt={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"},nt={auto:"o4-mini","o4-mini":"o4-mini",o3:"o3","o3-mini":"o3-mini","codex-mini":"codex-mini-latest","gpt-4o":"gpt-4o","gpt-4o-mini":"gpt-4o-mini","gpt-5.2-codex":"gpt-5.2-codex","gpt-5.2":"gpt-5.2","gpt-5.3":"gpt-5.3","gpt-5.4":"gpt-5.4"},Ut={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},Ue={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4}});var at={};Re(at,{getAllSkills:()=>it,getSkill:()=>G,hasSkill:()=>jo,listSkillIds:()=>Fo,registerSkill:()=>Uo});function Uo(i){if(!i||typeof i.id!="string")throw new Error("Skill definition must include a string id");Oe.set(i.id,Object.freeze({...i}))}function G(i){return Oe.get(i)||null}function jo(i){return Oe.has(i)}function it(){return new Map(Oe)}function Fo(){return Array.from(Oe.keys())}var Oe,te=B(()=>{Oe=new Map});import{zodToJsonSchema as Jo}from"zod-to-json-schema";var je,jt=B(()=>{je=class{static generateFileOutputInstructions(e,t){let o;typeof e?.parse=="function"?o=Jo(e,{target:"openApi3"}):o=e;let s=this._buildExample(o);return`
20
20
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
21
21
  \u{1F6A8} MANDATORY: WRITE RESULT TO FILE \u{1F6A8}
22
22
  \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
@@ -36,18 +36,28 @@ JSON types (strict \u2014 validators reject wrong types):
36
36
  - Use true/false without quotes for booleans.
37
37
  - Use unquoted null where a field may be null.
38
38
 
39
- 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 o={};for(let[s,r]of Object.entries(e.properties))o[s]=this._buildExample(r);return o}if(t==="array"&&e.items)return[this._buildExample(e.items)];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 o=e.oneOf?.find(s=>s.type!=="null")||e.anyOf?.find(s=>s.type!=="null");return o?this._buildExample(o):null}return"<value>"}}});import Fo from"axios";import{homedir as Jo}from"node:os";import{join as Go}from"node:path";import{existsSync as Ko,readFileSync as Yo}from"node:fs";import{toJSONSchema as Wo}from"zod";function zo(){if(process.env.OPENAI_PROXY_TOKEN)return u.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return u.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let i=Go(Jo(),".zibby","config.json");if(Ko(i)){let e=JSON.parse(Yo(i,"utf-8"));if(e.sessionToken)return u.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(i){u.debug(`[Auth] Could not read zibby login session: ${i.message}`)}return null}function Ho(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function ce(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(ce)}else"additionalProperties"in i||(i.additionalProperties=!0);i.type==="array"&&i.items&&ce(i.items),i.anyOf&&i.anyOf.forEach(ce),i.oneOf&&i.oneOf.forEach(ce),i.allOf&&i.allOf.forEach(ce)}}async function Ut(i,e){u.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=zo();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 o=Ho();u.info(`\u{1F517} Using OpenAI proxy: ${o}`);let s=Wo(e),r=s;if(s.$ref&&s.definitions){let f=s.$ref.split("/").pop();r=s.definitions[f]||s,u.debug(`Extracted schema from $ref: ${f}`)}delete r.$schema,ce(r);let n=4e5,a=i;i.length>n&&(u.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${i.length} chars) exceeds limit, keeping last ${n} chars`),a=`... [truncated early content] ...
39
+ 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 o={};for(let[s,r]of Object.entries(e.properties))o[s]=this._buildExample(r);return o}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 o=e.oneOf?.find(s=>s.type!=="null")||e.anyOf?.find(s=>s.type!=="null");return o?this._buildExample(o):null}return"<value>"}}});var pe,lt=B(()=>{jt();pe=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+=`
40
+
41
+ ${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 o=je.generateFileOutputInstructions(e,t);this.systemInstructions.push({type:"structured_output",content:o,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
42
+ \u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
43
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
44
+
45
+ ${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(`
46
+
47
+ `),position:"append"}),this}addSystemInstruction(e,t="custom",o="append"){return e&&this.systemInstructions.push({type:t,content:e,position:o}),this}getUserPrompt(){return this.userPrompt}getSystemInstructions(){return this.systemInstructions}getMetadata(){return this.metadata}build(){let e=this.systemInstructions.filter(s=>s.position==="prepend").map(s=>s.content),t=this.systemInstructions.filter(s=>s.position==="append").map(s=>s.content);return[...e,this.userPrompt,...t].filter(Boolean).join(`
48
+
49
+ `)}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(o=>o.type)}}clone(){let e=new i(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}}});import Go from"axios";import{homedir as Ko}from"node:os";import{join as Yo}from"node:path";import{existsSync as Wo,readFileSync as zo}from"node:fs";import{toJSONSchema as Ho}from"zod";function Zo(){if(process.env.OPENAI_PROXY_TOKEN)return u.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return u.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let i=Yo(Ko(),".zibby","config.json");if(Wo(i)){let e=JSON.parse(zo(i,"utf-8"));if(e.sessionToken)return u.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(i){u.debug(`[Auth] Could not read zibby login session: ${i.message}`)}return null}function Xo(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function fe(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(fe)}else"additionalProperties"in i||(i.additionalProperties=!0);i.type==="array"&&i.items&&fe(i.items),i.anyOf&&i.anyOf.forEach(fe),i.oneOf&&i.oneOf.forEach(fe),i.allOf&&i.allOf.forEach(fe)}}async function Ft(i,e){u.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=Zo();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 o=Xo();u.info(`\u{1F517} Using OpenAI proxy: ${o}`);let s=Ho(e),r=s;if(s.$ref&&s.definitions){let p=s.$ref.split("/").pop();r=s.definitions[p]||s,u.debug(`Extracted schema from $ref: ${p}`)}delete r.$schema,fe(r);let n=4e5,a=i;i.length>n&&(u.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${i.length} chars) exceeds limit, keeping last ${n} chars`),a=`... [truncated early content] ...
40
50
  ${i.slice(-n)}`);let l=`Extract and format the following information into structured JSON matching the schema.
41
51
 
42
52
  RAW CONTENT:
43
53
  ${a}
44
54
 
45
- Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,c={model:j.OPENAI_POSTPROCESSING,messages:[{role:"user",content:l}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:r,strict:!0}}};u.info(`\u{1F4E4} Sending to OpenAI proxy: model=${j.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(r.properties||{}).join(", ")}`),u.debug(` Schema size: ${JSON.stringify(r).length} chars`),u.debug(` Prompt size: ${l.length} chars`);try{let f={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(f["x-proxy-token"]=t,f["x-execution-id"]=process.env.EXECUTION_ID||""):(f.Authorization=`Bearer ${t}`,f["x-api-key"]=process.env.ZIBBY_API_KEY||"",f["x-execution-id"]=process.env.EXECUTION_ID||"");let d=(await Fo.post(o,c,{headers:f,timeout:Be.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!d)throw new Error("OpenAI proxy returned empty response");let _=JSON.parse(d);return u.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:_,raw:i}}catch(f){if(f.response){let p=f.response.status,d=f.response.data;throw u.error(`\u274C OpenAI proxy request failed: ${p}`),u.error(` Status: ${p}`),u.error(` Response: ${JSON.stringify(d,null,2)}`),p===401||p===403?new Error(`Authentication failed for OpenAI proxy.
55
+ Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,c={model:J.OPENAI_POSTPROCESSING,messages:[{role:"user",content:l}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:r,strict:!0}}};u.info(`\u{1F4E4} Sending to OpenAI proxy: model=${J.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(r.properties||{}).join(", ")}`),u.debug(` Schema size: ${JSON.stringify(r).length} chars`),u.debug(` Prompt size: ${l.length} chars`);try{let p={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(p["x-proxy-token"]=t,p["x-execution-id"]=process.env.EXECUTION_ID||""):(p.Authorization=`Bearer ${t}`,p["x-api-key"]=process.env.ZIBBY_API_KEY||"",p["x-execution-id"]=process.env.EXECUTION_ID||"");let g=(await Go.post(o,c,{headers:p,timeout:Ue.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!g)throw new Error("OpenAI proxy returned empty response");let S=JSON.parse(g);return u.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:S,raw:i}}catch(p){if(p.response){let f=p.response.status,g=p.response.data;throw u.error(`\u274C OpenAI proxy request failed: ${f}`),u.error(` Status: ${f}`),u.error(` Response: ${JSON.stringify(g,null,2)}`),f===401||f===403?new Error(`Authentication failed for OpenAI proxy.
46
56
  Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
47
- Response: ${JSON.stringify(d)}`,{cause:f}):new Error(`Failed to format Cursor output: ${d?.error?.message||"Unknown error"}`,{cause:f})}throw u.error(`\u274C OpenAI proxy request failed: ${f.message}`),new Error(`Failed to format output: ${f.message}`,{cause:f})}}var jt=R(()=>{H();te()});import{copyFileSync as Zo,existsSync as lt,lstatSync as Xo,mkdirSync as Ft,rmSync as qo,symlinkSync as Vo,unlinkSync as Qo}from"node:fs";import{join as V}from"node:path";import{homedir as es}from"node:os";import{randomBytes as ts}from"node:crypto";function Jt(i){return!(!i||typeof i!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function Gt(i){let e=V(i||process.cwd(),".zibby","tmp");Ft(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${ts(4).toString("hex")}`,o=V(e,`cursor-agent-home-${t}`),s=V(o,".cursor");Ft(s,{recursive:!0});let r=es(),n=V(r,".cursor");if(lt(n))for(let a of os){let l=V(n,a);if(lt(l))try{Zo(l,V(s,a))}catch{}}if(process.platform==="darwin"){let a=V(r,"Library");if(lt(a))try{Vo(a,V(o,"Library"))}catch{}}return o}function Kt(i){if(!(!i||typeof i!="string"))try{let e=V(i,"Library");try{Xo(e).isSymbolicLink()&&Qo(e)}catch{}qo(i,{recursive:!0,force:!0})}catch{}}var os,Yt=R(()=>{os=["cli-config.json","config.json","auth.json","argv.json"]});import{spawn as ss,execSync as oe}from"node:child_process";import{writeFileSync as Wt,readFileSync as zt,mkdirSync as Ht,existsSync as Ee,accessSync as Zt,constants as Xt,unlinkSync as rs}from"node:fs";import{join as Y,resolve as ns}from"node:path";import{homedir as Oe}from"node:os";var be,qt=R(()=>{ee();H();te();he();Q();Re();at();jt();ae();Yt();be=class extends J{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[Y(Oe(),".local","bin","cursor-agent"),Y(Oe(),".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 o of t)try{if(o.startsWith("/")){Zt(o,Xt.X_OK);let s=oe(`"${o}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return u.debug(`[Cursor] Found agent at: ${o} (version: ${s.trim().slice(0,50)})`),!0}else{let s=oe(`which ${o}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!s)continue;let r=oe(`${o} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(r&&r.length>0)return u.debug(`[Cursor] Found '${o}' in PATH at ${s} (version: ${r.trim().slice(0,50)})`),!0}}catch{continue}return u.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:o=process.cwd(),print:s=!1,schema:r=null,skills:n=null,sessionPath:a=null,nodeName:l=null,timeout:c=Be.CURSOR_AGENT_DEFAULT,config:f={}}=t,p=f?.agent?.strictMode||!1,d=t.model??f?.agent?.cursor?.model??j.CURSOR;u.debug(`[Cursor] Invoking (model: ${d}, timeout: ${c/1e3}s, skills: ${JSON.stringify(n)})`);let h=(this._setupMcpConfig(a,o,f,n,l)||{}).isolatedMcpHome??null,k=[Y(Oe(),".local","bin","cursor-agent"),Y(Oe(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],S=null;for(let I of k)try{if(I.startsWith("/"))Zt(I,Xt.X_OK),oe(`"${I}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!oe(`which ${I}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");oe(`${I} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}S=I,u.debug(`[Agent] Using binary: ${I}`);break}catch(y){u.debug(`[Agent] Binary '${I}' check failed: ${y.message}`);continue}if(!S)throw new Error(`Cursor Agent CLI not found or not working.
57
+ Response: ${JSON.stringify(g)}`,{cause:p}):new Error(`Failed to format Cursor output: ${g?.error?.message||"Unknown error"}`,{cause:p})}throw u.error(`\u274C OpenAI proxy request failed: ${p.message}`),new Error(`Failed to format output: ${p.message}`,{cause:p})}}var Jt=B(()=>{X();se()});import{copyFileSync as qo,existsSync as ct,lstatSync as Vo,mkdirSync as Gt,rmSync as Qo,symlinkSync as es,unlinkSync as ts}from"node:fs";import{join as ee}from"node:path";import{homedir as os}from"node:os";import{randomBytes as ss}from"node:crypto";function Kt(i){return!(!i||typeof i!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function Yt(i){let e=ee(i||process.cwd(),".zibby","tmp");Gt(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${ss(4).toString("hex")}`,o=ee(e,`cursor-agent-home-${t}`),s=ee(o,".cursor");Gt(s,{recursive:!0});let r=os(),n=ee(r,".cursor");if(ct(n))for(let a of rs){let l=ee(n,a);if(ct(l))try{qo(l,ee(s,a))}catch{}}if(process.platform==="darwin"){let a=ee(r,"Library");if(ct(a))try{es(a,ee(o,"Library"))}catch{}}return o}function Wt(i){if(!(!i||typeof i!="string"))try{let e=ee(i,"Library");try{Vo(e).isSymbolicLink()&&ts(e)}catch{}Qo(i,{recursive:!0,force:!0})}catch{}}var rs,zt=B(()=>{rs=["cli-config.json","config.json","auth.json","argv.json"]});import{spawn as ns,execSync as re}from"node:child_process";import{writeFileSync as Ht,readFileSync as Zt,mkdirSync as Xt,existsSync as be,accessSync as qt,constants as Vt,unlinkSync as is}from"node:fs";import{join as z,resolve as as}from"node:path";import{homedir as Ie}from"node:os";var $e,Qt=B(()=>{oe();X();se();Se();te();Me();lt();Jt();ue();zt();$e=class extends K{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[z(Ie(),".local","bin","cursor-agent"),z(Ie(),".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 o of t)try{if(o.startsWith("/")){qt(o,Vt.X_OK);let s=re(`"${o}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return u.debug(`[Cursor] Found agent at: ${o} (version: ${s.trim().slice(0,50)})`),!0}else{let s=re(`which ${o}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!s)continue;let r=re(`${o} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(r&&r.length>0)return u.debug(`[Cursor] Found '${o}' in PATH at ${s} (version: ${r.trim().slice(0,50)})`),!0}}catch{continue}return u.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:o=process.cwd(),print:s=!1,schema:r=null,skills:n=null,sessionPath:a=null,nodeName:l=null,timeout:c=Ue.CURSOR_AGENT_DEFAULT,config:p={}}=t,f=p?.agent?.strictMode||!1,g=t.model??p?.agent?.cursor?.model??J.CURSOR;u.debug(`[Cursor] Invoking (model: ${g}, timeout: ${c/1e3}s, skills: ${JSON.stringify(n)})`);let h=(this._setupMcpConfig(a,o,p,n,l)||{}).isolatedMcpHome??null,C=[z(Ie(),".local","bin","cursor-agent"),z(Ie(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],y=null;for(let m of C)try{if(m.startsWith("/"))qt(m,Vt.X_OK),re(`"${m}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!re(`which ${m}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");re(`${m} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}y=m,u.debug(`[Agent] Using binary: ${m}`);break}catch(b){u.debug(`[Agent] Binary '${m}' check failed: ${b.message}`);continue}if(!y)throw new Error(`Cursor Agent CLI not found or not working.
48
58
 
49
59
  Checked paths:
50
- ${k.map(I=>` - ${I}`).join(`
60
+ ${C.map(m=>` - ${m}`).join(`
51
61
  `)}
52
62
 
53
63
  Install cursor-agent:
@@ -56,76 +66,80 @@ Install cursor-agent:
56
66
  Then add to PATH:
57
67
  echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
58
68
 
59
- Test with: agent --version`);let b=null;if(r){let I=`zibby-result-${Date.now()}.json`;b=Y(o,".zibby","tmp",I);let y=Y(o,".zibby","tmp");Ee(y)||Ht(y,{recursive:!0});let T=le.generateFileOutputInstructions(r,b);e=`${e}
60
-
61
- ${T}`}let g=process.env.CURSOR_API_KEY,O=g?` | key: ***${g.slice(-4)}`:" | key: not set";console.log(`
62
- \u25C6 Model: ${d||"auto"}${O}
63
- `);let E=(await import("chalk")).default;console.log(`
64
- ${E.bold("Prompt sent to LLM:")}`),console.log(E.dim("\u2500".repeat(60))),console.log(E.dim(e)),console.log(E.dim("\u2500".repeat(60)));let $=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",d||"auto"];if(process.env.CURSOR_API_KEY&&$.push("--api-key",process.env.CURSOR_API_KEY),$.push(e),u.debug(`[Agent] Prompt: ${e.length} chars, model: ${d||"auto"}`),u.debug(`[Agent] Workspace: ${o}`),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)
65
- `)}catch{}let x,w=null;try{let I=a||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);x=await this._spawnWithStreaming(S,$,o,c,null,I,h)}catch(I){w=I}let v=x?.stdout||"";if(r){let I=typeof r.parse=="function",y=null,T=!!(b&&Ee(b));if(b&&u.info(`[Agent] Result file: ${T?"present":"missing"} at ${b}`),T)try{let m=zt(b,"utf-8").trim();y=JSON.parse(m),u.info(`[Agent] Parsed JSON from result file OK (${m.length} chars) \u2192 object ready for validation`),w&&u.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(m){u.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${m.message}`)}else if(w)u.warn(`[Agent] Result file missing at ${b} (agent process error \u2014 may still recover if strictMode repairs)`);else throw u.error(`\u274C [Agent] Result file was never created at ${b}`),new Error(`Agent did not write required result file at ${b}`);if(y&&I)try{let m=r.parse(y);return u.info("\u2705 [Agent] Zod validation passed for structured result file"),p&&u.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:v,structured:m}}catch(m){u.warn(`\u26A0\uFE0F [Agent] JSON parsed but Zod rejected it (wrong types/shape): ${m.message?.slice(0,400)}`)}else{if(y)return u.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),p&&u.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:v,structured:y};T&&u.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(p&&!w){let m=x.parsedText,N=y?JSON.stringify(y):m;u.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${N.length} chars in)`);try{let P=await Ut(N,r);if(I){let D=r.parse(P.structured);return u.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:v,structured:D}}return{raw:v,...P}}catch(P){if(u.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${P.message}`),y)return u.warn("[Agent] Using agent's original result file as fallback"),{raw:v,structured:y}}}if(w)throw w;let C=T?y==null?"file existed but JSON.parse failed \u2014 see WARN log above":I?"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 u.error(`\u274C [Agent] No validated structured output: ${C}`),u.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error(`Agent did not produce a valid result file at ${b}. Enable strictMode for proxy fallback.`)}if(w)throw w;return this._extractFinalResult(v)||x?.parsedText||v}_extractFinalResult(e){if(!e)return null;let t=e.split(`
66
- `),o=null;for(let s of t){let r=s.trim();if(r)try{let n=JSON.parse(r);if(n.type==="assistant"&&n.message?.content){let a=n.message.content;if(Array.isArray(a)){let l=a.filter(c=>c.type==="text"&&c.text).map(c=>c.text).join("");l&&(o=l)}else typeof a=="string"&&a&&(o=a)}}catch{}}return o?.trim()||null}_setupMcpConfig(e,t,o,s=null,r=null){let n=o?.headless,a=Y(Oe(),".cursor"),l=Y(a,"mcp.json"),c={};if(Ee(l))try{c=JSON.parse(zt(l,"utf-8"))}catch{}let f=c.mcpServers||{},p=o?.paths?.output||q,d=Y(t||process.cwd(),p,W),_=Array.isArray(s)?s.map(S=>F(S)).filter(Boolean):[...nt()].map(([,S])=>S),h=new Set;for(let S of _)typeof S.resolve=="function"&&(h.has(S.serverName)||(h.add(S.serverName),this._ensureSkillConfigured(f,S,e,d,r,n)));if(e){let S=F("browser");S&&typeof S.resolve=="function"&&!h.has(S.serverName)&&this._ensureSkillConfigured(f,S,e,d,"execute_live",n)}if(Object.keys(f).length===0)return u.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let k=`${JSON.stringify({mcpServers:f},null,2)}
67
- `;if(Jt(e)){let S=Gt(t||process.cwd()),b=Y(S,".cursor","mcp.json");return Wt(b,k,"utf8"),u.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${S} | servers: ${Object.keys(f).join(", ")}`),{isolatedMcpHome:S}}return Ee(a)||Ht(a,{recursive:!0}),Wt(l,k,"utf8"),u.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(f).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,o,s,r=null,n){let a=t.cursorKey||t.serverName,l=e[a]?a:e[t.serverName]?t.serverName:null;if(l&&o){let f=typeof t.resolve=="function"?t.resolve({sessionPath:o,nodeName:r,headless:n}):null;f?.args?e[l].args=f.args:e[l].args=(e[l].args||[]).map(_=>_.startsWith("--output-dir=")?`--output-dir=${o}`:_);let p=f?.env||{},d=t.sessionEnvKey?{[t.sessionEnvKey]:s}:{};e[l].env={...e[l].env||{},...p,...d},u.debug(`[MCP] Updated ${l} session \u2192 ${o}`);return}if(l)return;let c=t.resolve({sessionPath:o,nodeName:r,headless:n});c&&(e[a]={...c,...t.sessionEnvKey&&{env:{...c.env||{},[t.sessionEnvKey]:s}}},u.debug(`[MCP] Configured ${a}`))}_spawnWithStreaming(e,t,o,s,r=null,n=null,a=null){return new Promise((l,c)=>{let f=Date.now(),p="",d="",_=Date.now(),h=0,k=!1,S=null,b=!1,g=!1,O=null;if(n)try{O=Y(ns(String(n)),Le)}catch{O=null}let E=!1,$=()=>{E||(E=!0,Kt(a))},x={...process.env};a&&(x.HOME=a,process.platform==="win32"&&(x.USERPROFILE=a),u.debug(`[Agent] cursor-agent HOME=${a} (isolated MCP config)`));let w=ss(e,t,{cwd:o,shell:!1,stdio:["pipe","pipe","pipe"],env:x});u.debug(`[Agent] PID: ${w.pid}`),w.stdin.on("error",m=>{m.code!=="EPIPE"&&u.warn(`[Agent] stdin error: ${m.message}`)}),w.stdout.on("error",m=>{m.code!=="EPIPE"&&u.warn(`[Agent] stdout error: ${m.message}`)}),w.stderr.on("error",m=>{m.code!=="EPIPE"&&u.warn(`[Agent] stderr error: ${m.message}`)}),r?(w.stdin.write(r,m=>{m&&m.code!=="EPIPE"&&u.warn(`[Agent] Failed to write to stdin: ${m.message}`),w.stdin.end()}),u.debug(`[Agent] Prompt also piped to stdin (${r.length} chars)`)):w.stdin.end();let v=null;O&&(v=setInterval(()=>{if(!(k||g))try{if(Ee(O)){k=!0,S="studio-stop";try{rs(O)}catch{}u.warn("\u{1F6D1} Studio stop requested \u2014 terminating Cursor agent (and MCP browser session)"),w.kill("SIGTERM"),setTimeout(()=>{w.killed||w.kill("SIGKILL")},2e3)}}catch{}},600));let A=new Set,I=new Date(f).toISOString().replace(/\.\d+Z$/,""),y=setInterval(()=>{let m=Math.round((Date.now()-f)/1e3),N=Math.round((Date.now()-_)/1e3),P=[];try{let G=Math.ceil(m/60)+1,M=oe(`find "${o}" -type f -mmin -${G} -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 K of M.split(`
68
- `)){let B=K.replace(`${o}/`,"");A.has(B)||(A.add(B),P.push(B))}}catch{}let D="";P.length>0&&(D=` | \u{1F4C1} new: ${P.map(M=>M.split("/").pop()).join(", ")}`),A.size>0&&(D+=` | \u{1F4E6} total: ${A.size} files`),u.debug(`\u{1F493} [Agent] Running for ${m}s | ${h} lines output${D}`),h===0&&m>=30&&A.size===0&&(m<35&&u.warn(`\u26A0\uFE0F [Agent] No output after ${m}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),m>=60&&(k=!0,S=S||"stall",u.error(`\u274C [Agent] No response after ${m}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),w.kill("SIGTERM"),setTimeout(()=>{w.killed||w.kill("SIGKILL")},3e3)))},3e4),T=setTimeout(()=>{k=!0,S=S||"timeout";let m=Math.round((Date.now()-f)/1e3);u.error(`\u23F1\uFE0F [Agent] Timeout after ${m}s \u2014 killing process (PID: ${w.pid})`),p.trim()&&u.warn(`\u{1F4E4} [Agent] Partial output (${p.length} chars) before timeout:
69
- ${p.slice(-2e3)}`),w.kill("SIGTERM"),setTimeout(()=>{w.killed||w.kill("SIGKILL")},5e3)},s),C=new X;C.onToolCall=(m,N)=>{let P=m,D=N;if(m==="mcpToolCall"&&N?.name)P=N.name.replace(/^mcp_+[^_]+_+/,""),P.includes("-")&&P.split("-")[0]===P.split("-")[1]&&(P=P.split("-")[0]),D=N.args??N.input??N;else{if(m==="readToolCall"||m==="editToolCall"||m==="writeToolCall")return;(m.startsWith("mcp__")||m.includes("ToolCall"))&&(P=m.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(P.includes("memory")?L.stepMemory(`Tool: ${P}`):L.stepTool(`Tool: ${P}`),D!=null&&typeof D=="object"&&Object.keys(D).length>0&&!g){let M=JSON.stringify(D),K=M.length>100?`${M.substring(0,100)}...`:M;console.log(` Input: ${K}`)}},w.stdout.on("data",m=>{let N=m.toString();p+=N,_=Date.now(),b||(b=!0);let P=C.processChunk(N);P&&!g&&process.stdout.write(P);let D=N.split(`
70
- `).filter(G=>G.trim());h+=D.length}),w.stderr.on("data",m=>{let N=m.toString();d+=N,_=Date.now(),b||(b=!0);let P=N.split(`
71
- `).filter(D=>D.trim());for(let D of P)u.warn(`\u26A0\uFE0F [Agent stderr] ${D}`)}),w.on("close",(m,N)=>{g=!0,$(),clearTimeout(T),clearInterval(y),v&&clearInterval(v),C.flush();let P=Math.round((Date.now()-f)/1e3);if(u.debug(`[Agent] Exited: code=${m}, signal=${N}, elapsed=${P}s, output=${p.length} chars`),k){if(S==="studio-stop"){c(new Error("Stopped from Zibby Studio"));return}c(new Error(`Cursor Agent timed out after ${P}s (limit: ${s/1e3}s). ${h} lines produced. Last output ${Math.round((Date.now()-_)/1e3)}s ago. ${p.trim()?`
69
+ Test with: agent --version`);let $=new pe(e),d=null;if(r){let m=`zibby-result-${Date.now()}.json`;d=z(o,".zibby","tmp",m);let b=z(o,".zibby","tmp");be(b)||Xt(b,{recursive:!0}),$.addStructuredOutput(r,d)}let w=process.env.CURSOR_API_KEY,O=w?` | key: ***${w.slice(-4)}`:" | key: not set";console.log(`
70
+ \u25C6 Model: ${g||"auto"}${O}
71
+ `);let I=(await import("chalk")).default,x=$.getUserPrompt();console.log(`
72
+ ${I.bold("Prompt sent to LLM:")}`),console.log(I.dim("\u2500".repeat(60))),console.log(I.dim(x)),console.log(I.dim("\u2500".repeat(60)));let E=$.build(),P=$.getStats(),T=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",g||"auto"];if(process.env.CURSOR_API_KEY&&T.push("--api-key",process.env.CURSOR_API_KEY),T.push(E),u.debug(`[Agent] User prompt: ${P.userPromptLength} chars, System instructions: ${P.systemInstructionsLength} chars (${P.instructionCount} blocks), Full: ${P.fullPromptLength} chars, model: ${g||"auto"}`),u.debug(`[Agent] Workspace: ${o}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${g||"auto"} (from .zibby.config.js agent.cursor.model)
73
+ `)}catch{}let M,_=null;try{let m=a||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);M=await this._spawnWithStreaming(y,T,o,c,null,m,h)}catch(m){_=m}let k=M?.stdout||"";if(r){let m=typeof r.parse=="function",b=null,A=!!(d&&be(d));if(d&&u.info(`[Agent] Result file: ${A?"present":"missing"} at ${d}`),A)try{let v=Zt(d,"utf-8").trim();b=JSON.parse(v),u.info(`[Agent] Parsed JSON from result file OK (${v.length} chars) \u2192 object ready for validation`),_&&u.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(v){u.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${v.message}`)}else if(_)u.warn(`[Agent] Result file missing at ${d} (agent process error \u2014 may still recover if strictMode repairs)`);else throw u.error(`\u274C [Agent] Result file was never created at ${d}`),new Error(`Agent did not write required result file at ${d}`);if(b&&m)try{let v=r.parse(b);return u.info("\u2705 [Agent] Zod validation passed for structured result file"),f&&u.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:k,structured:v}}catch(v){let R=v.issues?v.issues.map(L=>` - ${L.path.join(".")}: ${L.message}`).join(`
74
+ `):v.message?.slice(0,400);if(u.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
75
+ ${R}`),u.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
76
+ ${JSON.stringify(b,null,2).slice(0,500)}`),!f)throw new Error(`Agent output failed schema validation:
77
+ ${R}
78
+
79
+ The agent wrote invalid data that doesn't match the required outputSchema.
80
+ Enable strictMode in .zibby.config.js for automatic repair.`,{cause:v})}else{if(b)return u.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),f&&u.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:k,structured:b};A&&u.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(f&&!_){let v=M.parsedText,R=b?JSON.stringify(b):v;u.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${R.length} chars in)`);try{let L=await Ft(R,r);if(m){let D=r.parse(L.structured);return u.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:k,structured:D}}return{raw:k,...L}}catch(L){if(u.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${L.message}`),b)return u.warn("[Agent] Using agent's original result file as fallback"),{raw:k,structured:b}}}if(_)throw _;let j=A?b==null?"file existed but JSON.parse failed \u2014 see WARN log above":m?"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 u.error(`\u274C [Agent] No validated structured output: ${j}`),u.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 ${d}. Enable strictMode for proxy fallback.`)}if(_)throw _;return this._extractFinalResult(k)||M?.parsedText||k}_extractFinalResult(e){if(!e)return null;let t=e.split(`
81
+ `),o=null;for(let s of t){let r=s.trim();if(r)try{let n=JSON.parse(r);if(n.type==="assistant"&&n.message?.content){let a=n.message.content;if(Array.isArray(a)){let l=a.filter(c=>c.type==="text"&&c.text).map(c=>c.text).join("");l&&(o=l)}else typeof a=="string"&&a&&(o=a)}}catch{}}return o?.trim()||null}_setupMcpConfig(e,t,o,s=null,r=null){let n=o?.headless,a=z(Ie(),".cursor"),l=z(a,"mcp.json"),c={};if(be(l))try{c=JSON.parse(Zt(l,"utf-8"))}catch{}let p=c.mcpServers||{},f=o?.paths?.output||Q,g=z(t||process.cwd(),f,H),S=Array.isArray(s)?s.map(y=>G(y)).filter(Boolean):[...it()].map(([,y])=>y),h=new Set;for(let y of S)typeof y.resolve=="function"&&(h.has(y.serverName)||(h.add(y.serverName),this._ensureSkillConfigured(p,y,e,g,r,n)));if(e){let y=G("browser");y&&typeof y.resolve=="function"&&!h.has(y.serverName)&&this._ensureSkillConfigured(p,y,e,g,"execute_live",n)}if(Object.keys(p).length===0)return u.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let C=`${JSON.stringify({mcpServers:p},null,2)}
82
+ `;if(Kt(e)){let y=Yt(t||process.cwd()),$=z(y,".cursor","mcp.json");return Ht($,C,"utf8"),u.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${y} | servers: ${Object.keys(p).join(", ")}`),{isolatedMcpHome:y}}return be(a)||Xt(a,{recursive:!0}),Ht(l,C,"utf8"),u.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(p).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,o,s,r=null,n){let a=t.cursorKey||t.serverName,l=e[a]?a:e[t.serverName]?t.serverName:null;if(l&&o){let p=typeof t.resolve=="function"?t.resolve({sessionPath:o,nodeName:r,headless:n}):null;p?.args?e[l].args=p.args:e[l].args=(e[l].args||[]).map(S=>S.startsWith("--output-dir=")?`--output-dir=${o}`:S);let f=p?.env||{},g=t.sessionEnvKey?{[t.sessionEnvKey]:s}:{};e[l].env={...e[l].env||{},...f,...g},u.debug(`[MCP] Updated ${l} session \u2192 ${o}`);return}if(l)return;let c=t.resolve({sessionPath:o,nodeName:r,headless:n});c&&(e[a]={...c,...t.sessionEnvKey&&{env:{...c.env||{},[t.sessionEnvKey]:s}}},u.debug(`[MCP] Configured ${a}`))}_spawnWithStreaming(e,t,o,s,r=null,n=null,a=null){return new Promise((l,c)=>{let p=Date.now(),f="",g="",S=Date.now(),h=0,C=!1,y=null,$=!1,d=!1,w=null;if(n)try{w=z(as(String(n)),De)}catch{w=null}let O=!1,I=()=>{O||(O=!0,Wt(a))},x={...process.env};a&&(x.HOME=a,process.platform==="win32"&&(x.USERPROFILE=a),u.debug(`[Agent] cursor-agent HOME=${a} (isolated MCP config)`));let E=ns(e,t,{cwd:o,shell:!1,stdio:["pipe","pipe","pipe"],env:x});u.debug(`[Agent] PID: ${E.pid}`),E.stdin.on("error",m=>{m.code!=="EPIPE"&&u.warn(`[Agent] stdin error: ${m.message}`)}),E.stdout.on("error",m=>{m.code!=="EPIPE"&&u.warn(`[Agent] stdout error: ${m.message}`)}),E.stderr.on("error",m=>{m.code!=="EPIPE"&&u.warn(`[Agent] stderr error: ${m.message}`)}),r?(E.stdin.write(r,m=>{m&&m.code!=="EPIPE"&&u.warn(`[Agent] Failed to write to stdin: ${m.message}`),E.stdin.end()}),u.debug(`[Agent] Prompt also piped to stdin (${r.length} chars)`)):E.stdin.end();let P=null;w&&(P=setInterval(()=>{if(!(C||d))try{if(be(w)){C=!0,y="studio-stop";try{is(w)}catch{}u.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 T=new Set,M=new Date(p).toISOString().replace(/\.\d+Z$/,""),_=setInterval(()=>{let m=Math.round((Date.now()-p)/1e3),b=Math.round((Date.now()-S)/1e3),A=[];try{let v=Math.ceil(m/60)+1,R=re(`find "${o}" -type f -mmin -${v} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(R)for(let L of R.split(`
83
+ `)){let D=L.replace(`${o}/`,"");T.has(D)||(T.add(D),A.push(D))}}catch{}let j="";A.length>0&&(j=` | \u{1F4C1} new: ${A.map(R=>R.split("/").pop()).join(", ")}`),T.size>0&&(j+=` | \u{1F4E6} total: ${T.size} files`),u.debug(`\u{1F493} [Agent] Running for ${m}s | ${h} lines output${j}`),h===0&&m>=30&&T.size===0&&(m<35&&u.warn(`\u26A0\uFE0F [Agent] No output after ${m}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),m>=60&&(C=!0,y=y||"stall",u.error(`\u274C [Agent] No response after ${m}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),k=setTimeout(()=>{C=!0,y=y||"timeout";let m=Math.round((Date.now()-p)/1e3);u.error(`\u23F1\uFE0F [Agent] Timeout after ${m}s \u2014 killing process (PID: ${E.pid})`),f.trim()&&u.warn(`\u{1F4E4} [Agent] Partial output (${f.length} chars) before timeout:
84
+ ${f.slice(-2e3)}`),E.kill("SIGTERM"),setTimeout(()=>{E.killed||E.kill("SIGKILL")},5e3)},s),N=new V;N.onToolCall=(m,b)=>{let A=m,j=b;if(m==="mcpToolCall"&&b?.name)A=b.name.replace(/^mcp_+[^_]+_+/,""),A.includes("-")&&A.split("-")[0]===A.split("-")[1]&&(A=A.split("-")[0]),j=b.args??b.input??b;else{if(m==="readToolCall"||m==="editToolCall"||m==="writeToolCall")return;(m.startsWith("mcp__")||m.includes("ToolCall"))&&(A=m.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(A.includes("memory")?U.stepMemory(`Tool: ${A}`):U.stepTool(`Tool: ${A}`),j!=null&&typeof j=="object"&&Object.keys(j).length>0&&!d){let R=JSON.stringify(j),L=R.length>100?`${R.substring(0,100)}...`:R;console.log(` Input: ${L}`)}},E.stdout.on("data",m=>{let b=m.toString();f+=b,S=Date.now(),$||($=!0);let A=N.processChunk(b);A&&!d&&process.stdout.write(A);let j=b.split(`
85
+ `).filter(v=>v.trim());h+=j.length}),E.stderr.on("data",m=>{let b=m.toString();g+=b,S=Date.now(),$||($=!0);let A=b.split(`
86
+ `).filter(j=>j.trim());for(let j of A)u.warn(`\u26A0\uFE0F [Agent stderr] ${j}`)}),E.on("close",(m,b)=>{d=!0,I(),clearTimeout(k),clearInterval(_),P&&clearInterval(P),N.flush();let A=Math.round((Date.now()-p)/1e3);if(u.debug(`[Agent] Exited: code=${m}, signal=${b}, elapsed=${A}s, output=${f.length} chars`),C){if(y==="studio-stop"){c(new Error("Stopped from Zibby Studio"));return}c(new Error(`Cursor Agent timed out after ${A}s (limit: ${s/1e3}s). ${h} lines produced. Last output ${Math.round((Date.now()-S)/1e3)}s ago. ${f.trim()?`
72
87
  Partial output (last 500 chars):
73
- ${p.slice(-500)}`:"No output captured."}`));return}if(m!==0){c(new Error(`Cursor Agent failed: exit code ${m}, signal ${N}. ${d.trim()?`
74
- Stderr: ${d.slice(-1e3)}`:""}${p.trim()?`
75
- Stdout (last 500 chars): ${p.slice(-500)}`:""}`));return}let D=C.getResult(),G=D?JSON.stringify(D,null,2):C.getRawText()||p||"";l({stdout:p||d||"",parsedText:G})}),w.on("error",m=>{$(),clearTimeout(T),clearInterval(y),v&&clearInterval(v),c(new Error(`Cursor Agent spawn error: ${m.message}
88
+ ${f.slice(-500)}`:"No output captured."}`));return}if(m!==0){c(new Error(`Cursor Agent failed: exit code ${m}, signal ${b}. ${g.trim()?`
89
+ Stderr: ${g.slice(-1e3)}`:""}${f.trim()?`
90
+ Stdout (last 500 chars): ${f.slice(-500)}`:""}`));return}let j=N.getResult(),v=j?JSON.stringify(j,null,2):N.getRawText()||f||"";l({stdout:f||g||"",parsedText:v})}),E.on("error",m=>{I(),clearTimeout(k),clearInterval(_),P&&clearInterval(P),c(new Error(`Cursor Agent spawn error: ${m.message}
76
91
  Binary: ${e}
77
92
  This usually means the binary is not in PATH. Try:
78
- echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}}});import{query as is}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as as}from"zod-to-json-schema";var $e,Vt=R(()=>{ee();H();ae();te();Q();$e=class extends J{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!process.env.ANTHROPIC_API_KEY;return t||u.debug("ClaudeAgentStrategy: ANTHROPIC_API_KEY not set"),t}async invoke(e,t={}){let{model:o,workspace:s=process.cwd(),schema:r=null,images:n=[],skills:a=null,sessionPath:l=null,nodeName:c=null,timeout:f,config:p={}}=t,d=o;(!d||d==="auto")&&(u.debug(`Model is '${d||"undefined"}', using default: ${j.CLAUDE}`),d=j.CLAUDE);let _=st[d]||d;st[d]&&d!==_&&u.debug(`Mapped model: ${d} \u2192 ${_}`),u.debug(`Invoking Claude Agent SDK with model: ${_}, skills: ${JSON.stringify(a)}`);let h=process.env.ANTHROPIC_API_KEY,k=h?` | key: ***${h.slice(-4)}`:" | key: not set";console.log(`
79
- \u25C6 Model: ${_}${k}
80
- `);let S=(await import("chalk")).default;console.log(`
81
- ${S.bold("Prompt sent to LLM:")}`),console.log(S.dim("\u2500".repeat(60))),console.log(S.dim(e)),console.log(S.dim("\u2500".repeat(60)));let{allowedTools:b,mcpServers:g}=this._resolveSkills(a,{sessionPath:l,workspace:s,nodeName:c});try{let O={cwd:s,allowedTools:b,permissionMode:"bypassPermissions",model:_,...Object.keys(g).length>0&&{mcpServers:g}};if(r){let T=typeof r.parse=="function"?as(r,{target:"openApi3"}):r;O.outputFormat={type:"json_schema",schema:T},u.debug("Structured output enforced via SDK outputFormat")}u.debug(`Agent SDK options: ${JSON.stringify({cwd:O.cwd,toolCount:b.length,permissionMode:O.permissionMode,model:O.model,hasOutputFormat:!!O.outputFormat})}`);let E="",$=0,x=[];u.debug("Starting Claude Agent SDK query stream");let w;try{w=is({prompt:e,options:O})}catch(y){throw u.error(`Failed to initialize Claude Agent SDK: ${y.message}`),y}let v=null,A=0,I=3;try{for await(let y of w){if(x.push(y),y.type==="error"||y.error){let C=y.error?.message||y.error||y.message||"Unknown API error";throw new Error(typeof C=="string"?C:JSON.stringify(C))}let T=JSON.stringify(y.message?.content||y.text||"").slice(0,200);if(T===v){if(A++,A>=I){let C=(y.message?.content?.[0]?.text||y.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${A}x repeated): ${C}`)}}else v=T,A=1;if(y.type==="assistant"||y.constructor?.name==="AssistantMessage"){let C=y.message?.content||y.content||[];for(let m of C)if(m.type==="thinking"&&m.thinking)console.log(`${m.thinking.substring(0,200)}${m.thinking.length>200?"...":""}`);else if(m.type==="text"&&m.text)E+=m.text,m.text.length<500?console.log(`${m.text}`):console.log(`${m.text.substring(0,200)}... (${m.text.length} chars)`);else if(m.type==="tool_use"){$++,m.name.includes("memory")?L.stepMemory(`Tool: ${m.name}`):L.stepTool(`Tool: ${m.name}`);let P=JSON.stringify(m.input).substring(0,100);console.log(` Input: ${P}${JSON.stringify(m.input).length>100?"...":""}`)}}else if(!(y.type==="user"&&y.tool_use_result)){if(y.type==="result"||y.constructor?.name==="ResultMessage"){let C=y.result||y.text||y.content||E;if(r){if(y.structured_output){u.debug("Using SDK native structured_output");let N=typeof r.parse=="function"?r.parse(y.structured_output):y.structured_output;return{raw:C,structured:N}}if(C){let m=this._extractJson(C,r);if(m)return{raw:C,structured:m}}u.warn(`Could not extract structured output \u2014 returning raw text (${(C||"").length} chars)`)}return C||""}}}if(u.warn(`Agent SDK ended without result. Collected ${x.length} messages`),E.length>0)return u.debug("Returning accumulated text from messages"),E;throw new Error("Claude Agent SDK query ended without result")}catch(y){throw u.error(`Error during query stream: ${y.message}`),y}}catch(O){throw u.error("Claude Agent SDK call failed",{error:O.message}),O}}_resolveSkills(e,t){if(e===null)return u.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return u.debug("Default IDE skills for code generation"),{allowedTools:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};let o=[],s={};for(let r of e){let n=F(r);if(!n){u.warn(`Unknown skill "${r}" \u2014 skipping`);continue}if(n.allowedTools&&o.push(...n.allowedTools),typeof n.resolve=="function"){let a=n.resolve(t);a&&(s[n.serverName]=a,u.debug(`MCP: ${n.serverName} \u2192 ${a.command} ${a.args[0]}`))}}return{allowedTools:o,mcpServers:s}}_extractJson(e,t){let o=[()=>{if(e.includes("===JSON_START===")){let s=e.indexOf("===JSON_START===")+16,r=e.indexOf("===JSON_END===");return e.substring(s,r).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 s=e.indexOf("{"),r=e.lastIndexOf("}");if(s!==-1&&r>s)return e.substring(s,r+1)}];for(let s of o)try{let r=s();if(!r)continue;let n=JSON.parse(r);if(typeof n!="object"||n===null)continue;return typeof t.parse=="function"?t.parse(n):n}catch{}return null}}});import{execSync as ls}from"node:child_process";import{zodToJsonSchema as cs}from"zod-to-json-schema";var xe,Qt=R(()=>{ee();H();ae();te();Q();xe=class extends J{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.CODEX_API_KEY))return u.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return ls("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return u.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:o,workspace:s=process.cwd(),schema:r=null,skills:n=null,sessionPath:a=null,nodeName:l=null,timeout:c,config:f={}}=t,{Codex:p}=await import("@openai/codex-sdk"),d=o;(!d||d==="auto")&&(u.debug(`Model is '${d||"undefined"}', using default: ${j.CODEX}`),d=j.CODEX);let _=rt[d]||d;rt[d]&&d!==_&&u.debug(`Mapped model: ${d} \u2192 ${_}`),u.debug(`Invoking Codex SDK with model: ${_}, skills: ${JSON.stringify(n)}`);let h=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;h&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=h);let k=h?` | key: ***${h.slice(-4)}`:" | key: not set";console.log(`
82
- \u25C6 Model: ${_}${k}
83
- `);let S=(await import("chalk")).default;console.log(`
84
- ${S.bold("Prompt sent to LLM:")}`),console.log(S.dim("\u2500".repeat(60))),console.log(S.dim(e)),console.log(S.dim("\u2500".repeat(60)));let b=this._resolveSkillsToMcp(n,{sessionPath:a,workspace:s,nodeName:l}),g={};Object.keys(b).length>0&&(g.mcp_servers=b,u.debug(`[Codex] MCP servers: ${Object.keys(b).join(", ")}`));let E=new p({...Object.keys(g).length>0&&{config:g}}).startThread({workingDirectory:s,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),$=r&&typeof r.parse=="function",x={};if(r)try{let w=$?cs(r,{target:"openAi"}):r;x.outputSchema=w,u.debug("Structured output via SDK outputSchema")}catch(w){u.warn(`[Codex] Schema conversion failed, will extract from text: ${w.message}`)}try{let{events:w}=await E.runStreamed(e,x),v=0,A="";for await(let I of w){let y=I.type;if(y==="item.completed"){let T=I.item,C=T?.type;if(C==="mcp_tool_call"){v++;let m=`${T.server}/${T.tool}`;if(L.stepTool(`Tool: ${m}`),T.arguments){let N=JSON.stringify(T.arguments),P=N.length>100?`${N.substring(0,100)}...`:N;console.log(` Input: ${P}`)}}else if(C==="tool_call"||C==="function_call"||C==="command_execution"){v++;let m=T.name||T.tool||T.command||"unknown";L.stepTool(`Tool: ${m}`)}else C==="agent_message"&&(A=T.text||"",A.length<500?console.log(A):console.log(`${A.substring(0,200)}... (${A.length} chars)`))}else y==="turn.completed"?u.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(I.usage||{})}`):u.debug(`[Codex] Event: ${y} ${JSON.stringify(I).slice(0,300)}`)}if(u.debug(`[Codex] Last agent message (${A.length} chars): ${A.slice(0,500)}`),r){if(!A)throw new Error("Codex agent returned no response");let I=JSON.parse(A),y=$?r.parse(I):I;return u.debug("\u2705 [Codex] Structured output validated"),{raw:A,structured:y}}return A||""}catch(w){let v=w.message||String(w);throw u.error(`\u274C [Codex] SDK call failed: ${v}`),v.includes("exited with code")&&(u.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),u.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),w}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let o={};for(let s of e){let r=F(s);if(!r){u.warn(`[Codex] Unknown skill "${s}" \u2014 skipping`);continue}if(typeof r.resolve!="function")continue;let n=r.resolve(t);if(!n)continue;let a=r.serverName||s,l={command:n.command};n.args?.length&&(l.args=n.args),n.env&&Object.keys(n.env).length>0&&(l.env=n.env),o[a]=l,u.debug(`[Codex] MCP: ${a} \u2192 ${n.command} ${(n.args||[]).join(" ")}`)}return o}}});import{execSync as us,spawn as fs}from"node:child_process";import{zodToJsonSchema as ps}from"zod-to-json-schema";import{existsSync as eo,mkdirSync as to,readFileSync as oo,rmSync as ds,writeFileSync as so}from"node:fs";import{join as se}from"node:path";function ms(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 o=e.indexOf("{");if(o<0)return null;let s=0,r=!1,n=!1,a=-1;for(let l=o;l<e.length;l++){let c=e[l];if(r){n?n=!1:c==="\\"?n=!0:c==='"'&&(r=!1);continue}if(c==='"'){r=!0;continue}if(c==="{"){s===0&&(a=l),s+=1;continue}if(c==="}"){if(s===0)continue;if(s-=1,s===0&&a>=0){let f=e.slice(a,l+1);try{return JSON.parse(f)}catch{a=-1}}}}return null}function gs(i){let e=String(i||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return ms(e)}}function hs(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 o=t.content.parts.map(s=>typeof s?.text=="string"?s.text:"").join("");if(o.trim())return o}}}catch{}return i}var Ie,ro=R(()=>{ee();H();te();Q();at();Re();Ie=class extends J{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY))return u.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return us("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return u.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:o,workspace:s=process.cwd(),schema:r=null,skills:n=null,sessionPath:a=null,nodeName:l=null,timeout:c=600*1e3}=t,f=o;(!f||f==="auto")&&(f=j.GEMINI);let p=Bt[f]||f,d=String(process.env.GEMINI_API_KEY||"").trim(),_=String(process.env.GOOGLE_API_KEY||"").trim(),h=this._resolveSkillsToMcp(n,{sessionPath:a,workspace:s,nodeName:l}),k=Object.keys(h).length>0,S=e,b=r&&typeof r.parse=="function",g=null;if(r){let T;try{let C=b?ps(r,{target:"openAi"}):r;T=JSON.stringify(C,null,2)}catch{T="{}"}if(k){S+=`
85
-
86
- Write valid JSON that matches this schema:
87
- ${T}`;let C=`zibby-result-${Date.now()}.json`,m=se(s,".zibby","tmp");g=se(m,C),to(m,{recursive:!0}),S+=le.generateFileOutputInstructions(r,g)}else S+=`
88
-
89
- Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
90
- ${T}`}let O=this._createGeminiConfigDir(s,h),E=["--output-format","json"];p&&p!=="auto"&&E.push("--model",p);let $=Object.keys(h);if($.length>0){E.push("--approval-mode","yolo");for(let T of $)E.push("--allowed-mcp-server-names",T);u.info(`[Gemini] Enabling MCP servers: ${$.join(", ")}`)}else n&&n.length>0&&u.warn(`[Gemini] Skills requested but no MCP servers configured: ${n.join(", ")}`);E.push("-p",S);let x={...process.env,GEMINI_CLI_HOME:O};d?(x.GEMINI_API_KEY=d,delete x.GOOGLE_API_KEY):_&&(x.GOOGLE_API_KEY=_,delete x.GEMINI_API_KEY),u.debug(`[Gemini] Command: gemini ${E.slice(0,8).join(" ")}... (${E.length} total args)`),u.debug(`[Gemini] Config home: ${O}`),u.debug(`[Gemini] GEMINI_CLI_HOME env: ${x.GEMINI_CLI_HOME}`);let w="",v=null;try{w=await new Promise((C,m)=>{let N=fs("gemini",E,{cwd:s,env:x,stdio:["ignore","pipe","pipe"]}),P="",D="",G=setTimeout(()=>{try{N.kill("SIGTERM")}catch{}},c);N.stdout.on("data",M=>{P+=M.toString()}),N.stderr.on("data",M=>{D+=M.toString()}),N.on("error",M=>{clearTimeout(G),m(M)}),N.on("close",M=>{if(clearTimeout(G),M===0)return C(P.trim());m(new Error(`gemini failed with code ${M}: ${(D||P).trim()}`))})})}catch(T){v=T}finally{try{ds(O,{recursive:!0,force:!0})}catch{}}let A=hs(w).trim();if(!r){if(v)throw v;return A}if(g){let T=eo(g);if(u.info(`[Gemini] Result file: ${T?"present":"missing"} at ${g}`),T)try{let C=oo(g,"utf-8").trim(),m=JSON.parse(C),N=b?r.parse(m):m;return u.info("[Gemini] Structured output recovered from result file"),{raw:A,structured:N}}catch(C){u.warn(`[Gemini] Result file parse/validation failed: ${C.message}`)}else v||u.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let I=null;if(r){let T=new X;T.zodSchema=r,T.processChunk(A),T.flush(),I=T.getResult()}if(u.info(`[Gemini] Raw stdout length: ${w.length} chars`),u.info(`[Gemini] Extracted text length: ${A.length} chars`),u.info(`[Gemini] StreamParser result: ${I?"extracted":"null"}`),I||(A.length<2e3?u.info(`[Gemini] Raw text preview:
91
- ${A}`):u.info(`[Gemini] Raw text preview (first 1000 chars):
92
- ${A.slice(0,1e3)}`),I=gs(A)),!I)throw v||(u.error("[Gemini] Failed to extract valid JSON from output"),u.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 y=b?r.parse(I):I;return{raw:A,structured:y}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let o={};for(let s of e){let r=F(s);if(!r||typeof r.resolve!="function")continue;let n=r.resolve(t);if(!n)continue;let a=r.cursorKey||r.serverName||s,l={command:n.command};n.args?.length&&(l.args=n.args),n.env&&Object.keys(n.env).length>0&&(l.env=n.env),n.cwd&&(l.cwd=n.cwd),o[a]=l}return o}_createGeminiConfigDir(e,t){let o=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,s=se(e||process.cwd(),".zibby","tmp",`gemini-home-${o}`),r=se(s,".gemini");to(r,{recursive:!0});let n=se(r,"settings.json"),a={},l=se(process.env.HOME||"",".gemini","settings.json");if(eo(l))try{a=JSON.parse(oo(l,"utf-8"))}catch{a={}}let c={...a,mcpServers:{...a.mcpServers&&typeof a.mcpServers=="object"?a.mcpServers:{},...t||{}}};so(n,`${JSON.stringify(c,null,2)}
93
- `,"utf-8");let f=se(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{so(f,`${JSON.stringify(c,null,2)}
94
- `,"utf-8")}catch{}return u.debug(`[Gemini] Created isolated config with ${Object.keys(c.mcpServers||{}).length} MCP servers`),u.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(c.mcpServers||{}),null,2)}`),s}}});var Te,ct=R(()=>{Te=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 ue,no=R(()=>{ct();ue=class extends Te{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(o=>({id:o.id,name:o.function.name,args:JSON.parse(o.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 Ae,ut=R(()=>{Ae=class{async fetchCompletion(e,t,o={}){throw new Error("fetchCompletion() must be implemented")}async fetchStreamingCompletion(e,t,o={}){throw new Error("fetchStreamingCompletion() must be implemented")}}});function Ue(i){return Buffer.byteLength(JSON.stringify(i),"utf8")}function je(i,e){let t=String(i||"");if(t.length<=e)return t;let o=Math.max(0,e-28);return`${t.slice(0,o)}
95
-
96
- [truncated for size budget]`}function ft(i,e=0){if(!i||typeof i!="object"||e>8)return i;if(Array.isArray(i))return i.map(o=>ft(o,e+1));let t={};for(let[o,s]of Object.entries(i))o==="description"||o==="title"||o==="examples"||o==="default"||(t[o]=ft(s,e+1));return t}function ys(i=[]){return i.map(e=>({...e,function:{...e.function,description:je(e.function?.description||"",180),parameters:ft(e.function?.parameters||{type:"object",properties:{}})}}))}function io(i){let e=new Set;for(let s of i)if(s.role==="assistant"&&Array.isArray(s.tool_calls))for(let r of s.tool_calls)e.add(r.id);let t=i.filter(s=>s.role==="tool"?e.has(s.tool_call_id):!0),o=new Set;for(let s of t)s.role==="tool"&&o.add(s.tool_call_id);return t.map(s=>{if(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.every(l=>o.has(l.id)))return s;let{tool_calls:n,...a}=s;return{...a,content:a.content||""}})}function pt(i,e={}){let t=e.maxBytes||49e3,o=e.systemMaxChars||12e3,s={...i,messages:Array.isArray(i.messages)?[...i.messages]:[],tools:Array.isArray(i.tools)?ys(i.tools):i.tools};s.messages.length>0&&s.messages[0]?.role==="system"&&(s.messages[0]={...s.messages[0],content:je(s.messages[0].content,o)});let r=!1;for(;Ue(s)>t&&s.messages.length>2;)s.messages.splice(1,1),r=!0;if(r&&(s.messages=io(s.messages)),Ue(s)>t&&s.messages.length>0&&(s.messages[0]={...s.messages[0],content:je(s.messages[0].content,6e3)},r=!0),Ue(s)>t){let n=s.messages.find(l=>l.role==="system")||s.messages[0],a=s.messages.slice(-2);s.messages=io([n,...a].filter(Boolean).map((l,c)=>({...l,content:je(l.content,c===0?4e3:8e3)}))),r=!0}return{body:s,meta:{bytes:Ue(s),trimmed:r,maxBytes:t,messageCount:s.messages.length}}}var ao=R(()=>{});var lo,fe,co=R(()=>{ut();ao();lo=i=>Buffer.byteLength(JSON.stringify(i),"utf8"),fe=class extends Ae{async fetchCompletion(e,t,o={}){let s=lo(e),{body:r,meta:n}=pt(e,o.payloadCompaction);o.onBudget?.({streaming:!1,beforeBytes:s,meta:n});let a=this.#e(o),l=`${t.baseUrl}${o.chatCompletionsPath||"/v1/chat/completions"}`,c=await fetch(l,{method:"POST",headers:t.headers,body:JSON.stringify(r),signal:a});if(!c.ok){let f=await c.text();throw c.status===401||c.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${c.status}: ${f}`)}return c.json()}async fetchStreamingCompletion(e,t,o={}){let s={...e,stream:!0},r=lo(s),{body:n,meta:a}=pt(s,o.payloadCompaction);o.onBudget?.({streaming:!0,beforeBytes:r,meta:a});let l=this.#e(o),c=`${t.baseUrl}${o.chatCompletionsPath||"/v1/chat/completions"}`,f=await fetch(c,{method:"POST",headers:t.headers,body:JSON.stringify(n),signal:l});if(!f.ok){let S=await f.text();throw f.status===401||f.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${f.status}: ${S}`)}let p=f.body.getReader(),d=new TextDecoder,_="",h="",k=new Map;for(;;){let{done:S,value:b}=await p.read();if(S)break;_+=d.decode(b,{stream:!0});let g=_.split(`
97
- `);_=g.pop();for(let O of g){if(!O.startsWith("data: "))continue;let E=O.slice(6).trim();if(E==="[DONE]")continue;let $;try{$=JSON.parse(E)}catch{continue}let x=$.choices?.[0]?.delta;if(x&&(x.content&&(h+=x.content,o.onToken&&o.onToken(x.content)),x.tool_calls))for(let w of x.tool_calls){let v=w.index??0;k.has(v)||k.set(v,{id:"",name:"",args:""});let A=k.get(v);w.id&&(A.id=w.id),w.function?.name&&(A.name=w.function.name),w.function?.arguments!=null&&(A.args+=w.function.arguments)}}}if(k.size>0){let S=[...k.entries()].sort(([b],[g])=>b-g).map(([,b])=>({id:b.id,type:"function",function:{name:b.name,arguments:b.args}}));return{choices:[{message:{role:"assistant",content:h||null,tool_calls:S}}]}}return{choices:[{message:{role:"assistant",content:h}}]}}#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}}});var uo=R(()=>{ct();no();ut();co()});import{Client as Ss}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as _s}from"@modelcontextprotocol/sdk/client/stdio.js";var Fe,fo=R(()=>{H();Fe=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:o,args:s=[],env:r={}}=t;u.debug(`[MCP] Starting ${e}: ${o} ${s.join(" ")}`);let n=new _s({command:o,args:s,env:{...process.env,...r}}),a=new Ss({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await a.connect(n);let l={client:a,transport:n,serverConfig:t};return this.#e.set(e,l),l}async callTool(e,t,o={}){let s=this.#e.get(e);if(!s)throw new Error(`MCP server "${e}" not running`);u.debug(`[MCP] ${e}.${t}(${JSON.stringify(o).slice(0,200)})`);let r=await s.client.callTool({name:t,arguments:o});return{text:r.content?.filter(a=>a.type==="text").map(a=>a.text).join(`
98
- `)||"",isError:r.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(o){u.debug(`[MCP] Error closing ${e}: ${o.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}}});import{existsSync as ws,readFileSync as Es}from"node:fs";import{join as Os}from"node:path";import{homedir as bs}from"node:os";function $s(){try{let i=Os(bs(),".zibby","config.json");return ws(i)?JSON.parse(Es(i,"utf-8")):{}}catch{return{}}}function Je(i){return String(i||"").replace(/\/v1\/?$/,"")}function xs(i,e){let t=process.env.OPENAI_PROXY_URL;if(t)return Je(t);if(i==="session")return e.proxyUrl?Je(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(i==="byok"){let o=process.env.OPENAI_BASE_URL;return Je(o||"https://api.openai.com")}return Je(t||"")}function dt(){let i=$s(),e=process.env.ZIBBY_USER_TOKEN||i.sessionToken||null,t=process.env.OPENAI_API_KEY||null,o=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),s=process.env.OPENAI_PROXY_NO_AUTH==="true",r=process.env.OPENAI_PROXY_URL,n="session";o==="byok"||o==="local"||o==="session"?n=o:e?n="session":t?n="byok":r&&s&&(n="local");let a=xs(n,i),l={"Content-Type":"application/json"};if(n==="session"){if(!e)return{ok:!1,mode:n,reason:"missing_session_token"};l.Authorization=`Bearer ${e}`}else if(n==="byok"){if(!t)return{ok:!1,mode:n,reason:"missing_openai_api_key"};l.Authorization=`Bearer ${t}`}else if(n==="local"){if(!a)return{ok:!1,mode:n,reason:"missing_openai_proxy_url"};!s&&t&&(l.Authorization=`Bearer ${t}`)}return a?{ok:!0,mode:n,baseUrl:a,headers:l,tokenPreview:l.Authorization?`***${l.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:n,reason:"missing_base_url"}}var po=R(()=>{});function Ge(i,e){let t=String(i??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
99
-
100
- [tool result truncated for size]`}function Is(i,e){if(typeof i=="string")return Ge(i,e);try{return Ge(JSON.stringify(i),e)}catch{return Ge(String(i),e)}}function mo(i){let e=new Set;for(let s of i)if(s.role==="assistant"&&Array.isArray(s.tool_calls))for(let r of s.tool_calls)e.add(r.id);let t=i.filter(s=>s.role==="tool"?e.has(s.tool_call_id):!0),o=new Set;for(let s of t)s.role==="tool"&&o.add(s.tool_call_id);return t.map(s=>{if(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.every(l=>o.has(l.id)))return s;let{tool_calls:n,...a}=s;return{...a,content:a.content||""}})}function Ts(i){let e=Array.isArray(i?.messages)?i.messages:[],t=e.find(r=>r.role==="system"),o=e.slice(-4).map(r=>({...r,content:Ge(r.content,r.role==="tool"?1200:2500)}));o=mo(o);let s={...i,messages:[t,...o].filter(Boolean)};return delete s.tools,s}async function As({body:i,streaming:e,auth:t,options:o,fetchCompletion:s,fetchStreamingCompletion:r,onFallbackLog:n}){try{return e?await r(i,t,o):await s(i,t,o)}catch(a){let l=String(a?.message||a||"");if(!/proxy error 413|payload too large/i.test(l))throw a;let c=Ts(i);return typeof n=="function"&&n(i,c),{data:e?await r(c,t,o):await s(c,t,o),fallback:c}}}async function go({body:i,auth:e,options:t,streaming:o,toolContext:s,activeSkills:r,round:n,verbose:a,dependencies:l,config:c={}}){let f=c.maxToolResultChars||3e3,{fetchCompletion:p,fetchStreamingCompletion:d,onFallbackLog:_,hasToolCalls:h,getTextContent:k,parseToolCalls:S,buildAssistantMessage:b,buildToolResultMessage:g,executeTool:O,onToolCallLog:E,injectTools:$}=l;Array.isArray(i?.messages)&&(i.messages=mo(i.messages));let x=await As({body:i,streaming:o,auth:e,options:t,fetchCompletion:p,fetchStreamingCompletion:d,onFallbackLog:_}),w=x?.data||x;if(!h(w))return{done:!0,text:k(w),body:x?.fallback||i};let v=S(w),A=x?.fallback||i;A.messages.push(b(w)),a&&typeof E=="function"&&E(v);let I=await Promise.all(v.map((y,T)=>(typeof t.onToolCall=="function"&&t.onToolCall(y.name,y.args,{round:n,index:T,total:v.length}),O(y,s))));for(let y=0;y<v.length;y++){let C=v[y].name==="get_skill_context"?typeof I[y]=="string"?I[y]:JSON.stringify(I[y]):Is(I[y],f);A.messages.push(g(v[y].id,C))}return typeof t.onToolCall=="function"&&t.onToolCall(null),$(A,r),{done:!1,body:A}}var ho=R(()=>{});function de(i){!i||typeof i!="object"||(i.type==="object"&&i.properties&&(i.required=Object.keys(i.properties),i.additionalProperties=!1,Object.values(i.properties).forEach(de)),i.type==="array"&&i.items&&de(i.items),i.anyOf&&i.anyOf.forEach(de),i.oneOf&&i.oneOf.forEach(de),i.allOf&&i.allOf.forEach(de))}function Ke(i){return Array.isArray(i)?new Set(i.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function Ns(i){return Array.isArray(i)?i.map(e=>String(e||"").trim()).filter(Boolean):[]}var vs,Cs,mt,yo,pe,ks,ve,So=R(()=>{ee();H();te();uo();fo();Q();po();ho();vs=j.ASSISTANT,Cs=15,mt="get_skill_context";yo={maxBytes:49e3,systemMaxChars:12e3},pe=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",ks=i=>Buffer.byteLength(JSON.stringify(i),"utf8");ve=class extends J{#e;#t;#o=new Fe;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new ue,this.#t=e.completionProvider||new fe):(this.#e=e||new ue,this.#t=new fe)}canHandle(e){return dt().ok}async invoke(e,t={}){let o=t.model&&t.model!=="auto"?t.model:vs,s=dt();if(!s.ok)throw s.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):s.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):s.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${s.reason}).`);let r=t.messages||[{role:"user",content:e}],n=s.baseUrl,a=pe();if(a?await this.#m(r,o,n,s.tokenPreview||"none"):u.debug(`[Assistant] ${n} | model: ${o} | messages: ${r.length}`),t.schema)return this.#c(o,r,s,t);let l=t.activeSkills||[],c=this.#f(t),f=this.#p(l,c),p=this.#d(f),d=this.#u(t),_={...t,payloadCompaction:d},h={activeSkills:f,options:_,executionRegistry:p,capabilityPolicy:c},k=!!t.stream,S={model:o,messages:[...r],stream:!1};this.#r(S,f,c);for(let b=0;b<Cs;b++){if(t.signal?.aborted)throw new Error("Aborted");let g=await go({body:S,auth:s,options:_,streaming:k,toolContext:h,activeSkills:f,round:b,verbose:a,dependencies:{fetchCompletion:this.#n.bind(this),fetchStreamingCompletion:this.#l.bind(this),onFallbackLog:(O,E)=>{pe()&&console.log(`413 fallback: messages ${O.messages.length} -> ${E.messages.length}, bytes=${ks(E)}`)},hasToolCalls:O=>this.#e.hasToolCalls(O),getTextContent:O=>this.#e.getTextContent(O),parseToolCalls:O=>this.#e.parseToolCalls(O),buildAssistantMessage:O=>this.#e.buildAssistantMessage(O),buildToolResultMessage:(O,E)=>this.#e.buildToolResultMessage(O,E),executeTool:(O,E)=>this.#a(O,E),onToolCallLog:async O=>{let E=(await import("chalk")).default;console.log(E.dim(` ${O.map($=>`${$.name}(${JSON.stringify($.args).slice(0,80)})`).join(", ")}`))},injectTools:(O,E)=>this.#r(O,E,c)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(g.done)return g.text;S.messages=g.body.messages,g.body.tools?S.tools=g.body.tools:delete S.tools}return"I hit my tool-calling limit for this turn. Please try again."}async cleanup(){await this.#o.stopAll()}#r(e,t,o=null){let s=this.#i(t,o),r=this.#e.formatTools(s);this.#e.injectToolsIntoBody(e,r)}#i(e,t=null){let o=[],s=new Set;for(let r of e){let n=F(r);if(n?.tools?.length)for(let a of n.tools)this.#s(a.name,t)&&(s.has(a.name)||(s.add(a.name),o.push({name:a.name,description:a.description,parameters:a.parameters||a.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#s(mt,t)&&o.push({name:mt,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"]}}),o}async#a(e,t){let{activeSkills:o,options:s,executionRegistry:r,capabilityPolicy:n}=t;if(!this.#s(e.name,n))return`Tool "${e.name}" blocked by policy`;if(e.name===mt){let c=String(e.args?.skillId||"").trim();if(!c)return JSON.stringify({error:"skillId is required"});if(!o.includes(c))return JSON.stringify({error:`Skill "${c}" is not active`,activeSkills:o});let f=F(c);if(!f)return JSON.stringify({error:`Skill "${c}" not found`});let p=typeof f.promptFragment=="function"?f.promptFragment():f.promptFragment||"",d=(f.tools||[]).map(h=>h.name),_=JSON.stringify({skillId:c,description:f.description||"",toolNames:d,promptFragment:p||""});return pe()&&(console.log(`
101
- \u{1F4D6} get_skill_context("${c}") \u2192 ${_.length} chars (fragment: ${p.length} chars)`),console.log(` tools: [${d.join(", ")}]`),console.log(` fragment preview: ${p.slice(0,200).replace(/\n/g,"\\n")}\u2026
102
- `)),_}let a=r?.get(e.name)||null;if(!a)return`Unknown tool: ${e.name}`;let l=F(a.skillId);if(!l)return`Skill "${a.skillId}" not found for tool "${e.name}"`;if(a.mode==="handler")try{return l.handleToolCall(e.name,e.args,t)}catch(c){return`Error in ${e.name}: ${c.message}`}if(a.mode==="mcp")try{if(!this.#o.isRunning(l.serverName)){let f=l.resolve(s);if(!f)return`Skill "${a.skillId}" is not available (cannot start server)`;await this.#o.ensureServer(l.serverName,f)}let c=await this.#o.callTool(l.serverName,e.name,e.args);return c.text||(c.isError?"Tool call failed":"Done")}catch(c){return`MCP error (${l.serverName}): ${c.message}`}return`Skill "${a.skillId}" owns tool "${e.name}" but has no execution mode`}async#l(e,t,o){return this.#t.fetchStreamingCompletion(e,t,{...o,onBudget:({beforeBytes:s,meta:r})=>{pe()&&console.log(`payload bytes (stream) before=${s} after=${r.bytes} trimmed=${r.trimmed} messages=${r.messageCount}`)}})}async#n(e,t,o){return this.#t.fetchCompletion(e,t,{...o,onBudget:({beforeBytes:s,meta:r})=>{pe()&&console.log(`payload bytes before=${s} after=${r.bytes} trimmed=${r.trimmed} messages=${r.messageCount}`)}})}async#c(e,t,o,s){let{zodToJsonSchema:r}=await import("zod-to-json-schema"),n=typeof s.schema?.parse=="function",a=n?r(s.schema):s.schema;delete a.$schema,de(a);let l={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:a,strict:!0}}},c=await this.#n(l,o,s),f=this.#e.getTextContent(c),p=JSON.parse(f),d=n?s.schema.parse(p):p;return{raw:f,structured:d}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||yo.maxBytes),systemMaxChars:Number(t.systemMaxChars||yo.systemMaxChars)}}#f(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:Ke(t.allowTools||e.allowTools),denyTools:Ke(t.denyTools||e.denyTools),denyPrefixes:Ns(t.denyPrefixes||e.denyToolPrefixes),includeSkills:Ke(t.includeSkills||e.includeSkills),excludeSkills:Ke(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#p(e,t){let o=t?.includeSkills||new Set,s=t?.excludeSkills||new Set;return o.size===0&&s.size===0?e:e.filter(r=>!(o.size>0&&!o.has(r)||s.has(r)))}#s(e,t){let o=String(e||"").trim();if(!o)return!1;let s=t?.allowTools;if(s&&s.size>0&&!s.has(o))return!1;let r=t?.denyTools;return!(r&&r.has(o)||(t?.denyPrefixes||[]).some(a=>o.startsWith(a)))}#d(e){let t=new Map,o=[];for(let s of e){let r=F(s);if(!r?.tools?.length)continue;let n=typeof r.handleToolCall=="function"?"handler":r.serverName&&typeof r.resolve=="function"?"mcp":null;if(n)for(let a of r.tools){let l=String(a?.name||"").trim();if(l){if(t.has(l)){o.push({tool:l,winner:t.get(l).skillId,skipped:s});continue}t.set(l,{skillId:s,mode:n})}}}if(o.length>0&&pe()){let s=o.slice(0,5).map(r=>`${r.tool}:${r.winner}>${r.skipped}`).join(", ");console.log(`tool registry collisions: ${s}${o.length>5?" ...":""}`)}return t}async#m(e,t,o,s){console.log(`
93
+ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}}});import{query as ls}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as cs}from"zod-to-json-schema";var xe,eo=B(()=>{oe();X();ue();se();te();xe=class extends K{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!process.env.ANTHROPIC_API_KEY;return t||u.debug("ClaudeAgentStrategy: ANTHROPIC_API_KEY not set"),t}async invoke(e,t={}){let{model:o,workspace:s=process.cwd(),schema:r=null,images:n=[],skills:a=null,sessionPath:l=null,nodeName:c=null,timeout:p,config:f={}}=t,g=o;(!g||g==="auto")&&(u.debug(`Model is '${g||"undefined"}', using default: ${J.CLAUDE}`),g=J.CLAUDE);let S=rt[g]||g;rt[g]&&g!==S&&u.debug(`Mapped model: ${g} \u2192 ${S}`),u.debug(`Invoking Claude Agent SDK with model: ${S}, skills: ${JSON.stringify(a)}`);let h=process.env.ANTHROPIC_API_KEY,C=h?` | key: ***${h.slice(-4)}`:" | key: not set";console.log(`
94
+ \u25C6 Model: ${S}${C}
95
+ `);let y=(await import("chalk")).default;console.log(`
96
+ ${y.bold("Prompt sent to LLM:")}`),console.log(y.dim("\u2500".repeat(60))),console.log(y.dim(e)),console.log(y.dim("\u2500".repeat(60)));let{allowedTools:$,mcpServers:d}=this._resolveSkills(a,{sessionPath:l,workspace:s,nodeName:c});try{let w={cwd:s,allowedTools:$,permissionMode:"bypassPermissions",model:S,...Object.keys(d).length>0&&{mcpServers:d}};if(r){let k=typeof r.parse=="function"?cs(r,{target:"openApi3"}):r;w.outputFormat={type:"json_schema",schema:k},u.debug("Structured output enforced via SDK outputFormat")}u.debug(`Agent SDK options: ${JSON.stringify({cwd:w.cwd,toolCount:$.length,permissionMode:w.permissionMode,model:w.model,hasOutputFormat:!!w.outputFormat})}`);let O="",I=0,x=[];u.debug("Starting Claude Agent SDK query stream");let E;try{E=ls({prompt:e,options:w})}catch(_){throw u.error(`Failed to initialize Claude Agent SDK: ${_.message}`),_}let P=null,T=0,M=3;try{for await(let _ of E){if(x.push(_),_.type==="error"||_.error){let N=_.error?.message||_.error||_.message||"Unknown API error";throw new Error(typeof N=="string"?N:JSON.stringify(N))}let k=JSON.stringify(_.message?.content||_.text||"").slice(0,200);if(k===P){if(T++,T>=M){let N=(_.message?.content?.[0]?.text||_.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${T}x repeated): ${N}`)}}else P=k,T=1;if(_.type==="assistant"||_.constructor?.name==="AssistantMessage"){let N=_.message?.content||_.content||[];for(let m of N)if(m.type==="thinking"&&m.thinking)console.log(`${m.thinking.substring(0,200)}${m.thinking.length>200?"...":""}`);else if(m.type==="text"&&m.text)O+=m.text,m.text.length<500?console.log(`${m.text}`):console.log(`${m.text.substring(0,200)}... (${m.text.length} chars)`);else if(m.type==="tool_use"){I++,m.name.includes("memory")?U.stepMemory(`Tool: ${m.name}`):U.stepTool(`Tool: ${m.name}`);let A=JSON.stringify(m.input).substring(0,100);console.log(` Input: ${A}${JSON.stringify(m.input).length>100?"...":""}`)}}else if(!(_.type==="user"&&_.tool_use_result)){if(_.type==="result"||_.constructor?.name==="ResultMessage"){let N=_.result||_.text||_.content||O;if(r){if(_.structured_output){u.debug("Using SDK native structured_output");let b=typeof r.parse=="function"?r.parse(_.structured_output):_.structured_output;return{raw:N,structured:b}}if(N){let m=this._extractJson(N,r);if(m)return{raw:N,structured:m}}u.warn(`Could not extract structured output \u2014 returning raw text (${(N||"").length} chars)`)}return N||""}}}if(u.warn(`Agent SDK ended without result. Collected ${x.length} messages`),O.length>0)return u.debug("Returning accumulated text from messages"),O;throw new Error("Claude Agent SDK query ended without result")}catch(_){throw u.error(`Error during query stream: ${_.message}`),_}}catch(w){throw u.error("Claude Agent SDK call failed",{error:w.message}),w}}_resolveSkills(e,t){if(e===null)return u.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return u.debug("Default IDE skills for code generation"),{allowedTools:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};let o=[],s={};for(let r of e){let n=G(r);if(!n){u.warn(`Unknown skill "${r}" \u2014 skipping`);continue}if(n.allowedTools&&o.push(...n.allowedTools),typeof n.resolve=="function"){let a=n.resolve(t);a&&(s[n.serverName]=a,u.debug(`MCP: ${n.serverName} \u2192 ${a.command} ${a.args[0]}`))}}return{allowedTools:o,mcpServers:s}}_extractJson(e,t){let o=[()=>{if(e.includes("===JSON_START===")){let s=e.indexOf("===JSON_START===")+16,r=e.indexOf("===JSON_END===");return e.substring(s,r).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 s=e.indexOf("{"),r=e.lastIndexOf("}");if(s!==-1&&r>s)return e.substring(s,r+1)}];for(let s of o)try{let r=s();if(!r)continue;let n=JSON.parse(r);if(typeof n!="object"||n===null)continue;return typeof t.parse=="function"?t.parse(n):n}catch{}return null}}});import{execSync as us}from"node:child_process";import{zodToJsonSchema as ps}from"zod-to-json-schema";var Te,to=B(()=>{oe();X();ue();se();te();Te=class extends K{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.CODEX_API_KEY))return u.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return us("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return u.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:o,workspace:s=process.cwd(),schema:r=null,skills:n=null,sessionPath:a=null,nodeName:l=null,timeout:c,config:p={}}=t,{Codex:f}=await import("@openai/codex-sdk"),g=o;(!g||g==="auto")&&(u.debug(`Model is '${g||"undefined"}', using default: ${J.CODEX}`),g=J.CODEX);let S=nt[g]||g;nt[g]&&g!==S&&u.debug(`Mapped model: ${g} \u2192 ${S}`),u.debug(`Invoking Codex SDK with model: ${S}, skills: ${JSON.stringify(n)}`);let h=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;h&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=h);let C=h?` | key: ***${h.slice(-4)}`:" | key: not set";console.log(`
97
+ \u25C6 Model: ${S}${C}
98
+ `);let y=(await import("chalk")).default;console.log(`
99
+ ${y.bold("Prompt sent to LLM:")}`),console.log(y.dim("\u2500".repeat(60))),console.log(y.dim(e)),console.log(y.dim("\u2500".repeat(60)));let $=this._resolveSkillsToMcp(n,{sessionPath:a,workspace:s,nodeName:l}),d={};Object.keys($).length>0&&(d.mcp_servers=$,u.debug(`[Codex] MCP servers: ${Object.keys($).join(", ")}`));let O=new f({...Object.keys(d).length>0&&{config:d}}).startThread({workingDirectory:s,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),I=r&&typeof r.parse=="function",x={};if(r)try{let E=I?ps(r,{target:"openAi"}):r;x.outputSchema=E,u.debug("Structured output via SDK outputSchema")}catch(E){u.warn(`[Codex] Schema conversion failed, will extract from text: ${E.message}`)}try{let{events:E}=await O.runStreamed(e,x),P=0,T="";for await(let M of E){let _=M.type;if(_==="item.completed"){let k=M.item,N=k?.type;if(N==="mcp_tool_call"){P++;let m=`${k.server}/${k.tool}`;if(U.stepTool(`Tool: ${m}`),k.arguments){let b=JSON.stringify(k.arguments),A=b.length>100?`${b.substring(0,100)}...`:b;console.log(` Input: ${A}`)}}else if(N==="tool_call"||N==="function_call"||N==="command_execution"){P++;let m=k.name||k.tool||k.command||"unknown";U.stepTool(`Tool: ${m}`)}else N==="agent_message"&&(T=k.text||"",T.length<500?console.log(T):console.log(`${T.substring(0,200)}... (${T.length} chars)`))}else _==="turn.completed"?u.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(M.usage||{})}`):u.debug(`[Codex] Event: ${_} ${JSON.stringify(M).slice(0,300)}`)}if(u.debug(`[Codex] Last agent message (${T.length} chars): ${T.slice(0,500)}`),r){if(!T)throw new Error("Codex agent returned no response");let M=JSON.parse(T),_=I?r.parse(M):M;return u.debug("\u2705 [Codex] Structured output validated"),{raw:T,structured:_}}return T||""}catch(E){let P=E.message||String(E);throw u.error(`\u274C [Codex] SDK call failed: ${P}`),P.includes("exited with code")&&(u.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),u.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 o={};for(let s of e){let r=G(s);if(!r){u.warn(`[Codex] Unknown skill "${s}" \u2014 skipping`);continue}if(typeof r.resolve!="function")continue;let n=r.resolve(t);if(!n)continue;let a=r.serverName||s,l={command:n.command};n.args?.length&&(l.args=n.args),n.env&&Object.keys(n.env).length>0&&(l.env=n.env),o[a]=l,u.debug(`[Codex] MCP: ${a} \u2192 ${n.command} ${(n.args||[]).join(" ")}`)}return o}}});import{execSync as fs,spawn as ds}from"node:child_process";import{zodToJsonSchema as ms}from"zod-to-json-schema";import{existsSync as oo,mkdirSync as so,readFileSync as ro,rmSync as gs,writeFileSync as no}from"node:fs";import{join as ne}from"node:path";function hs(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 o=e.indexOf("{");if(o<0)return null;let s=0,r=!1,n=!1,a=-1;for(let l=o;l<e.length;l++){let c=e[l];if(r){n?n=!1:c==="\\"?n=!0:c==='"'&&(r=!1);continue}if(c==='"'){r=!0;continue}if(c==="{"){s===0&&(a=l),s+=1;continue}if(c==="}"){if(s===0)continue;if(s-=1,s===0&&a>=0){let p=e.slice(a,l+1);try{return JSON.parse(p)}catch{a=-1}}}}return null}function ys(i){let e=String(i||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return hs(e)}}function Ss(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 o=t.content.parts.map(s=>typeof s?.text=="string"?s.text:"").join("");if(o.trim())return o}}}catch{}return i}var Ae,io=B(()=>{oe();X();se();te();lt();Me();Ae=class extends K{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY))return u.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return fs("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return u.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:o,workspace:s=process.cwd(),schema:r=null,skills:n=null,sessionPath:a=null,nodeName:l=null,timeout:c=600*1e3}=t,p=o;(!p||p==="auto")&&(p=J.GEMINI);let f=Ut[p]||p,g=String(process.env.GEMINI_API_KEY||"").trim(),S=String(process.env.GOOGLE_API_KEY||"").trim(),h=this._resolveSkillsToMcp(n,{sessionPath:a,workspace:s,nodeName:l}),C=Object.keys(h).length>0,y=new pe(e),$=r&&typeof r.parse=="function",d=null;if(r){let v;try{let R=$?ms(r,{target:"openAi"}):r;v=JSON.stringify(R,null,2)}catch{v="{}"}if(C){y.addSystemInstruction(`Write valid JSON that matches this schema:
100
+ ${v}`,"schema_instruction","append");let R=`zibby-result-${Date.now()}.json`,L=ne(s,".zibby","tmp");d=ne(L,R),so(L,{recursive:!0}),y.addStructuredOutput(r,d)}else y.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
101
+ ${v}`,"json_instruction","append")}let w=y.build(),O=y.getUserPrompt(),I=y.getStats(),x=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),E=x?` | key: ***${x.slice(-4)}`:" | key: not set";console.log(`
102
+ \u25C6 Model: ${f||"auto"}${E}
103
+ `);let P=(await import("chalk")).default;console.log(`
104
+ ${P.bold("Prompt sent to LLM:")}`),console.log(P.dim("\u2500".repeat(60))),console.log(P.dim(O)),console.log(P.dim("\u2500".repeat(60)));let T=this._createGeminiConfigDir(s,h),M=["--output-format","json"];f&&f!=="auto"&&M.push("--model",f);let _=Object.keys(h);if(_.length>0){M.push("--approval-mode","yolo");for(let v of _)M.push("--allowed-mcp-server-names",v);u.info(`[Gemini] Enabling MCP servers: ${_.join(", ")}`)}else n&&n.length>0&&u.warn(`[Gemini] Skills requested but no MCP servers configured: ${n.join(", ")}`);M.push("-p",w);let k={...process.env,GEMINI_CLI_HOME:T};g?(k.GEMINI_API_KEY=g,delete k.GOOGLE_API_KEY):S&&(k.GOOGLE_API_KEY=S,delete k.GEMINI_API_KEY),u.debug(`[Gemini] Command: gemini ${M.slice(0,8).join(" ")}... (${M.length} total args)`),u.debug(`[Gemini] User prompt: ${I.userPromptLength} chars, System instructions: ${I.systemInstructionsLength} chars (${I.instructionCount} blocks), Full: ${I.fullPromptLength} chars`),u.debug(`[Gemini] Config home: ${T}`),u.debug(`[Gemini] GEMINI_CLI_HOME env: ${k.GEMINI_CLI_HOME}`);let N="",m=null;try{N=await new Promise((R,L)=>{let D=ds("gemini",M,{cwd:s,env:k,stdio:["ignore","pipe","pipe"]}),q="",le="",W=setTimeout(()=>{try{D.kill("SIGTERM")}catch{}},c);D.stdout.on("data",Y=>{q+=Y.toString()}),D.stderr.on("data",Y=>{le+=Y.toString()}),D.on("error",Y=>{clearTimeout(W),L(Y)}),D.on("close",Y=>{if(clearTimeout(W),Y===0)return R(q.trim());L(new Error(`gemini failed with code ${Y}: ${(le||q).trim()}`))})})}catch(v){m=v}finally{try{gs(T,{recursive:!0,force:!0})}catch{}}let b=Ss(N).trim();if(!r){if(m)throw m;return b}if(d){let v=oo(d);if(u.info(`[Gemini] Result file: ${v?"present":"missing"} at ${d}`),v)try{let R=ro(d,"utf-8").trim(),L=JSON.parse(R),D=$?r.parse(L):L;return u.info("[Gemini] Structured output recovered from result file"),{raw:b,structured:D}}catch(R){u.warn(`[Gemini] Result file parse/validation failed: ${R.message}`)}else m||u.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let A=null;if(r){let v=new V;v.zodSchema=r,v.processChunk(b),v.flush(),A=v.getResult()}if(u.info(`[Gemini] Raw stdout length: ${N.length} chars`),u.info(`[Gemini] Extracted text length: ${b.length} chars`),u.info(`[Gemini] StreamParser result: ${A?"extracted":"null"}`),A||(b.length<2e3?u.info(`[Gemini] Raw text preview:
105
+ ${b}`):u.info(`[Gemini] Raw text preview (first 1000 chars):
106
+ ${b.slice(0,1e3)}`),A=ys(b)),!A)throw m||(u.error("[Gemini] Failed to extract valid JSON from output"),u.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error("Gemini did not return valid JSON for structured output. Enable strictMode for proxy fallback."));let j=$?r.parse(A):A;return{raw:b,structured:j}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let o={};for(let s of e){let r=G(s);if(!r||typeof r.resolve!="function")continue;let n=r.resolve(t);if(!n)continue;let a=r.cursorKey||r.serverName||s,l={command:n.command};n.args?.length&&(l.args=n.args),n.env&&Object.keys(n.env).length>0&&(l.env=n.env),n.cwd&&(l.cwd=n.cwd),o[a]=l}return o}_createGeminiConfigDir(e,t){let o=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,s=ne(e||process.cwd(),".zibby","tmp",`gemini-home-${o}`),r=ne(s,".gemini");so(r,{recursive:!0});let n=ne(r,"settings.json"),a={},l=ne(process.env.HOME||"",".gemini","settings.json");if(oo(l))try{a=JSON.parse(ro(l,"utf-8"))}catch{a={}}let c={...a,mcpServers:{...a.mcpServers&&typeof a.mcpServers=="object"?a.mcpServers:{},...t||{}}};no(n,`${JSON.stringify(c,null,2)}
107
+ `,"utf-8");let p=ne(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{no(p,`${JSON.stringify(c,null,2)}
108
+ `,"utf-8")}catch{}return u.debug(`[Gemini] Created isolated config with ${Object.keys(c.mcpServers||{}).length} MCP servers`),u.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(c.mcpServers||{}),null,2)}`),s}}});var ve,ut=B(()=>{ve=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 de,ao=B(()=>{ut();de=class extends ve{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(o=>({id:o.id,name:o.function.name,args:JSON.parse(o.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 Ce,pt=B(()=>{Ce=class{async fetchCompletion(e,t,o={}){throw new Error("fetchCompletion() must be implemented")}async fetchStreamingCompletion(e,t,o={}){throw new Error("fetchStreamingCompletion() must be implemented")}}});function Fe(i){return Buffer.byteLength(JSON.stringify(i),"utf8")}function Je(i,e){let t=String(i||"");if(t.length<=e)return t;let o=Math.max(0,e-28);return`${t.slice(0,o)}
109
+
110
+ [truncated for size budget]`}function ft(i,e=0){if(!i||typeof i!="object"||e>8)return i;if(Array.isArray(i))return i.map(o=>ft(o,e+1));let t={};for(let[o,s]of Object.entries(i))o==="description"||o==="title"||o==="examples"||o==="default"||(t[o]=ft(s,e+1));return t}function _s(i=[]){return i.map(e=>({...e,function:{...e.function,description:Je(e.function?.description||"",180),parameters:ft(e.function?.parameters||{type:"object",properties:{}})}}))}function lo(i){let e=new Set;for(let s of i)if(s.role==="assistant"&&Array.isArray(s.tool_calls))for(let r of s.tool_calls)e.add(r.id);let t=i.filter(s=>s.role==="tool"?e.has(s.tool_call_id):!0),o=new Set;for(let s of t)s.role==="tool"&&o.add(s.tool_call_id);return t.map(s=>{if(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.every(l=>o.has(l.id)))return s;let{tool_calls:n,...a}=s;return{...a,content:a.content||""}})}function dt(i,e={}){let t=e.maxBytes||49e3,o=e.systemMaxChars||12e3,s={...i,messages:Array.isArray(i.messages)?[...i.messages]:[],tools:Array.isArray(i.tools)?_s(i.tools):i.tools};s.messages.length>0&&s.messages[0]?.role==="system"&&(s.messages[0]={...s.messages[0],content:Je(s.messages[0].content,o)});let r=!1;for(;Fe(s)>t&&s.messages.length>2;)s.messages.splice(1,1),r=!0;if(r&&(s.messages=lo(s.messages)),Fe(s)>t&&s.messages.length>0&&(s.messages[0]={...s.messages[0],content:Je(s.messages[0].content,6e3)},r=!0),Fe(s)>t){let n=s.messages.find(l=>l.role==="system")||s.messages[0],a=s.messages.slice(-2);s.messages=lo([n,...a].filter(Boolean).map((l,c)=>({...l,content:Je(l.content,c===0?4e3:8e3)}))),r=!0}return{body:s,meta:{bytes:Fe(s),trimmed:r,maxBytes:t,messageCount:s.messages.length}}}var co=B(()=>{});var uo,me,po=B(()=>{pt();co();uo=i=>Buffer.byteLength(JSON.stringify(i),"utf8"),me=class extends Ce{async fetchCompletion(e,t,o={}){let s=uo(e),{body:r,meta:n}=dt(e,o.payloadCompaction);o.onBudget?.({streaming:!1,beforeBytes:s,meta:n});let a=this.#e(o),l=`${t.baseUrl}${o.chatCompletionsPath||"/v1/chat/completions"}`,c=await fetch(l,{method:"POST",headers:t.headers,body:JSON.stringify(r),signal:a});if(!c.ok){let p=await c.text();throw c.status===401||c.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${c.status}: ${p}`)}return c.json()}async fetchStreamingCompletion(e,t,o={}){let s={...e,stream:!0},r=uo(s),{body:n,meta:a}=dt(s,o.payloadCompaction);o.onBudget?.({streaming:!0,beforeBytes:r,meta:a});let l=this.#e(o),c=`${t.baseUrl}${o.chatCompletionsPath||"/v1/chat/completions"}`,p=await fetch(c,{method:"POST",headers:t.headers,body:JSON.stringify(n),signal:l});if(!p.ok){let y=await p.text();throw p.status===401||p.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${p.status}: ${y}`)}let f=p.body.getReader(),g=new TextDecoder,S="",h="",C=new Map;for(;;){let{done:y,value:$}=await f.read();if(y)break;S+=g.decode($,{stream:!0});let d=S.split(`
111
+ `);S=d.pop();for(let w of d){if(!w.startsWith("data: "))continue;let O=w.slice(6).trim();if(O==="[DONE]")continue;let I;try{I=JSON.parse(O)}catch{continue}let x=I.choices?.[0]?.delta;if(x&&(x.content&&(h+=x.content,o.onToken&&o.onToken(x.content)),x.tool_calls))for(let E of x.tool_calls){let P=E.index??0;C.has(P)||C.set(P,{id:"",name:"",args:""});let T=C.get(P);E.id&&(T.id=E.id),E.function?.name&&(T.name=E.function.name),E.function?.arguments!=null&&(T.args+=E.function.arguments)}}}if(C.size>0){let y=[...C.entries()].sort(([$],[d])=>$-d).map(([,$])=>({id:$.id,type:"function",function:{name:$.name,arguments:$.args}}));return{choices:[{message:{role:"assistant",content:h||null,tool_calls:y}}]}}return{choices:[{message:{role:"assistant",content:h}}]}}#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}}});var fo=B(()=>{ut();ao();pt();po()});import{Client as ws}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Es}from"@modelcontextprotocol/sdk/client/stdio.js";var Ge,mo=B(()=>{X();Ge=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:o,args:s=[],env:r={}}=t;u.debug(`[MCP] Starting ${e}: ${o} ${s.join(" ")}`);let n=new Es({command:o,args:s,env:{...process.env,...r}}),a=new ws({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await a.connect(n);let l={client:a,transport:n,serverConfig:t};return this.#e.set(e,l),l}async callTool(e,t,o={}){let s=this.#e.get(e);if(!s)throw new Error(`MCP server "${e}" not running`);u.debug(`[MCP] ${e}.${t}(${JSON.stringify(o).slice(0,200)})`);let r=await s.client.callTool({name:t,arguments:o});return{text:r.content?.filter(a=>a.type==="text").map(a=>a.text).join(`
112
+ `)||"",isError:r.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(o){u.debug(`[MCP] Error closing ${e}: ${o.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}}});import{existsSync as Os,readFileSync as bs}from"node:fs";import{join as Is}from"node:path";import{homedir as $s}from"node:os";function xs(){try{let i=Is($s(),".zibby","config.json");return Os(i)?JSON.parse(bs(i,"utf-8")):{}}catch{return{}}}function Ke(i){return String(i||"").replace(/\/v1\/?$/,"")}function Ts(i,e){let t=process.env.OPENAI_PROXY_URL;if(t)return Ke(t);if(i==="session")return e.proxyUrl?Ke(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(i==="byok"){let o=process.env.OPENAI_BASE_URL;return Ke(o||"https://api.openai.com")}return Ke(t||"")}function mt(){let i=xs(),e=process.env.ZIBBY_USER_TOKEN||i.sessionToken||null,t=process.env.OPENAI_API_KEY||null,o=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),s=process.env.OPENAI_PROXY_NO_AUTH==="true",r=process.env.OPENAI_PROXY_URL,n="session";o==="byok"||o==="local"||o==="session"?n=o:e?n="session":t?n="byok":r&&s&&(n="local");let a=Ts(n,i),l={"Content-Type":"application/json"};if(n==="session"){if(!e)return{ok:!1,mode:n,reason:"missing_session_token"};l.Authorization=`Bearer ${e}`}else if(n==="byok"){if(!t)return{ok:!1,mode:n,reason:"missing_openai_api_key"};l.Authorization=`Bearer ${t}`}else if(n==="local"){if(!a)return{ok:!1,mode:n,reason:"missing_openai_proxy_url"};!s&&t&&(l.Authorization=`Bearer ${t}`)}return a?{ok:!0,mode:n,baseUrl:a,headers:l,tokenPreview:l.Authorization?`***${l.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:n,reason:"missing_base_url"}}var go=B(()=>{});function Ye(i,e){let t=String(i??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
113
+
114
+ [tool result truncated for size]`}function As(i,e){if(typeof i=="string")return Ye(i,e);try{return Ye(JSON.stringify(i),e)}catch{return Ye(String(i),e)}}function ho(i){let e=new Set;for(let s of i)if(s.role==="assistant"&&Array.isArray(s.tool_calls))for(let r of s.tool_calls)e.add(r.id);let t=i.filter(s=>s.role==="tool"?e.has(s.tool_call_id):!0),o=new Set;for(let s of t)s.role==="tool"&&o.add(s.tool_call_id);return t.map(s=>{if(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.every(l=>o.has(l.id)))return s;let{tool_calls:n,...a}=s;return{...a,content:a.content||""}})}function vs(i){let e=Array.isArray(i?.messages)?i.messages:[],t=e.find(r=>r.role==="system"),o=e.slice(-4).map(r=>({...r,content:Ye(r.content,r.role==="tool"?1200:2500)}));o=ho(o);let s={...i,messages:[t,...o].filter(Boolean)};return delete s.tools,s}async function Cs({body:i,streaming:e,auth:t,options:o,fetchCompletion:s,fetchStreamingCompletion:r,onFallbackLog:n}){try{return e?await r(i,t,o):await s(i,t,o)}catch(a){let l=String(a?.message||a||"");if(!/proxy error 413|payload too large/i.test(l))throw a;let c=vs(i);return typeof n=="function"&&n(i,c),{data:e?await r(c,t,o):await s(c,t,o),fallback:c}}}async function yo({body:i,auth:e,options:t,streaming:o,toolContext:s,activeSkills:r,round:n,verbose:a,dependencies:l,config:c={}}){let p=c.maxToolResultChars||3e3,{fetchCompletion:f,fetchStreamingCompletion:g,onFallbackLog:S,hasToolCalls:h,getTextContent:C,parseToolCalls:y,buildAssistantMessage:$,buildToolResultMessage:d,executeTool:w,onToolCallLog:O,injectTools:I}=l;Array.isArray(i?.messages)&&(i.messages=ho(i.messages));let x=await Cs({body:i,streaming:o,auth:e,options:t,fetchCompletion:f,fetchStreamingCompletion:g,onFallbackLog:S}),E=x?.data||x;if(!h(E))return{done:!0,text:C(E),body:x?.fallback||i};let P=y(E),T=x?.fallback||i;T.messages.push($(E)),a&&typeof O=="function"&&O(P);let M=await Promise.all(P.map((_,k)=>(typeof t.onToolCall=="function"&&t.onToolCall(_.name,_.args,{round:n,index:k,total:P.length}),w(_,s))));for(let _=0;_<P.length;_++){let N=P[_].name==="get_skill_context"?typeof M[_]=="string"?M[_]:JSON.stringify(M[_]):As(M[_],p);T.messages.push(d(P[_].id,N))}return typeof t.onToolCall=="function"&&t.onToolCall(null),I(T,r),{done:!1,body:T}}var So=B(()=>{});function he(i){!i||typeof i!="object"||(i.type==="object"&&i.properties&&(i.required=Object.keys(i.properties),i.additionalProperties=!1,Object.values(i.properties).forEach(he)),i.type==="array"&&i.items&&he(i.items),i.anyOf&&i.anyOf.forEach(he),i.oneOf&&i.oneOf.forEach(he),i.allOf&&i.allOf.forEach(he))}function We(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 Ps,ks,gt,_o,ge,Ns,Pe,wo=B(()=>{oe();X();se();fo();mo();te();go();So();Ps=J.ASSISTANT,ks=15,gt="get_skill_context";_o={maxBytes:49e3,systemMaxChars:12e3},ge=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Ns=i=>Buffer.byteLength(JSON.stringify(i),"utf8");Pe=class extends K{#e;#t;#o=new Ge;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new de,this.#t=e.completionProvider||new me):(this.#e=e||new de,this.#t=new me)}canHandle(e){return mt().ok}async invoke(e,t={}){let o=t.model&&t.model!=="auto"?t.model:Ps,s=mt();if(!s.ok)throw s.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):s.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):s.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${s.reason}).`);let r=t.messages||[{role:"user",content:e}],n=s.baseUrl,a=ge();if(a?await this.#m(r,o,n,s.tokenPreview||"none"):u.debug(`[Assistant] ${n} | model: ${o} | messages: ${r.length}`),t.schema)return this.#c(o,r,s,t);let l=t.activeSkills||[],c=this.#p(t),p=this.#f(l,c),f=this.#d(p),g=this.#u(t),S={...t,payloadCompaction:g},h={activeSkills:p,options:S,executionRegistry:f,capabilityPolicy:c},C=!!t.stream,y={model:o,messages:[...r],stream:!1};this.#r(y,p,c);for(let $=0;$<ks;$++){if(t.signal?.aborted)throw new Error("Aborted");let d=await yo({body:y,auth:s,options:S,streaming:C,toolContext:h,activeSkills:p,round:$,verbose:a,dependencies:{fetchCompletion:this.#n.bind(this),fetchStreamingCompletion:this.#l.bind(this),onFallbackLog:(w,O)=>{ge()&&console.log(`413 fallback: messages ${w.messages.length} -> ${O.messages.length}, bytes=${Ns(O)}`)},hasToolCalls:w=>this.#e.hasToolCalls(w),getTextContent:w=>this.#e.getTextContent(w),parseToolCalls:w=>this.#e.parseToolCalls(w),buildAssistantMessage:w=>this.#e.buildAssistantMessage(w),buildToolResultMessage:(w,O)=>this.#e.buildToolResultMessage(w,O),executeTool:(w,O)=>this.#a(w,O),onToolCallLog:async w=>{let O=(await import("chalk")).default;console.log(O.dim(` ${w.map(I=>`${I.name}(${JSON.stringify(I.args).slice(0,80)})`).join(", ")}`))},injectTools:(w,O)=>this.#r(w,O,c)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(d.done)return d.text;y.messages=d.body.messages,d.body.tools?y.tools=d.body.tools:delete y.tools}return"I hit my tool-calling limit for this turn. Please try again."}async cleanup(){await this.#o.stopAll()}#r(e,t,o=null){let s=this.#i(t,o),r=this.#e.formatTools(s);this.#e.injectToolsIntoBody(e,r)}#i(e,t=null){let o=[],s=new Set;for(let r of e){let n=G(r);if(n?.tools?.length)for(let a of n.tools)this.#s(a.name,t)&&(s.has(a.name)||(s.add(a.name),o.push({name:a.name,description:a.description,parameters:a.parameters||a.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#s(gt,t)&&o.push({name:gt,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),o}async#a(e,t){let{activeSkills:o,options:s,executionRegistry:r,capabilityPolicy:n}=t;if(!this.#s(e.name,n))return`Tool "${e.name}" blocked by policy`;if(e.name===gt){let c=String(e.args?.skillId||"").trim();if(!c)return JSON.stringify({error:"skillId is required"});if(!o.includes(c))return JSON.stringify({error:`Skill "${c}" is not active`,activeSkills:o});let p=G(c);if(!p)return JSON.stringify({error:`Skill "${c}" not found`});let f=typeof p.promptFragment=="function"?p.promptFragment():p.promptFragment||"",g=(p.tools||[]).map(h=>h.name),S=JSON.stringify({skillId:c,description:p.description||"",toolNames:g,promptFragment:f||""});return ge()&&(console.log(`
115
+ \u{1F4D6} get_skill_context("${c}") \u2192 ${S.length} chars (fragment: ${f.length} chars)`),console.log(` tools: [${g.join(", ")}]`),console.log(` fragment preview: ${f.slice(0,200).replace(/\n/g,"\\n")}\u2026
116
+ `)),S}let a=r?.get(e.name)||null;if(!a)return`Unknown tool: ${e.name}`;let l=G(a.skillId);if(!l)return`Skill "${a.skillId}" not found for tool "${e.name}"`;if(a.mode==="handler")try{return l.handleToolCall(e.name,e.args,t)}catch(c){return`Error in ${e.name}: ${c.message}`}if(a.mode==="mcp")try{if(!this.#o.isRunning(l.serverName)){let p=l.resolve(s);if(!p)return`Skill "${a.skillId}" is not available (cannot start server)`;await this.#o.ensureServer(l.serverName,p)}let c=await this.#o.callTool(l.serverName,e.name,e.args);return c.text||(c.isError?"Tool call failed":"Done")}catch(c){return`MCP error (${l.serverName}): ${c.message}`}return`Skill "${a.skillId}" owns tool "${e.name}" but has no execution mode`}async#l(e,t,o){return this.#t.fetchStreamingCompletion(e,t,{...o,onBudget:({beforeBytes:s,meta:r})=>{ge()&&console.log(`payload bytes (stream) before=${s} after=${r.bytes} trimmed=${r.trimmed} messages=${r.messageCount}`)}})}async#n(e,t,o){return this.#t.fetchCompletion(e,t,{...o,onBudget:({beforeBytes:s,meta:r})=>{ge()&&console.log(`payload bytes before=${s} after=${r.bytes} trimmed=${r.trimmed} messages=${r.messageCount}`)}})}async#c(e,t,o,s){let{zodToJsonSchema:r}=await import("zod-to-json-schema"),n=typeof s.schema?.parse=="function",a=n?r(s.schema):s.schema;delete a.$schema,he(a);let l={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:a,strict:!0}}},c=await this.#n(l,o,s),p=this.#e.getTextContent(c),f=JSON.parse(p),g=n?s.schema.parse(f):f;return{raw:p,structured:g}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||_o.maxBytes),systemMaxChars:Number(t.systemMaxChars||_o.systemMaxChars)}}#p(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:We(t.allowTools||e.allowTools),denyTools:We(t.denyTools||e.denyTools),denyPrefixes:Rs(t.denyPrefixes||e.denyToolPrefixes),includeSkills:We(t.includeSkills||e.includeSkills),excludeSkills:We(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#f(e,t){let o=t?.includeSkills||new Set,s=t?.excludeSkills||new Set;return o.size===0&&s.size===0?e:e.filter(r=>!(o.size>0&&!o.has(r)||s.has(r)))}#s(e,t){let o=String(e||"").trim();if(!o)return!1;let s=t?.allowTools;if(s&&s.size>0&&!s.has(o))return!1;let r=t?.denyTools;return!(r&&r.has(o)||(t?.denyPrefixes||[]).some(a=>o.startsWith(a)))}#d(e){let t=new Map,o=[];for(let s of e){let r=G(s);if(!r?.tools?.length)continue;let n=typeof r.handleToolCall=="function"?"handler":r.serverName&&typeof r.resolve=="function"?"mcp":null;if(n)for(let a of r.tools){let l=String(a?.name||"").trim();if(l){if(t.has(l)){o.push({tool:l,winner:t.get(l).skillId,skipped:s});continue}t.set(l,{skillId:s,mode:n})}}}if(o.length>0&&ge()){let s=o.slice(0,5).map(r=>`${r.tool}:${r.winner}>${r.skipped}`).join(", ");console.log(`tool registry collisions: ${s}${o.length>5?" ...":""}`)}return t}async#m(e,t,o,s){console.log(`
103
117
  \u25C6 Model: ${t} | proxy: ${o} | token: ${s||"none"}
104
- `);let r=(await import("chalk")).default;console.log(r.bold("Prompt sent to LLM:")),console.log(r.dim("\u2500".repeat(60)));let n=!1;for(let a of e)if(a.role==="system")console.log(r.dim(`[System] ${a.content||""}`));else{n||(console.log(r.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),n=!0);let l=a.role==="user"?"Human":"AI",c=a.content?.length>200?`${a.content.slice(0,200)}...`:a.content||"";console.log(r.dim(`[${l}] ${c}`))}console.log(r.dim("\u2500".repeat(60)))}}});var gt={};Pe(gt,{AgentStrategy:()=>J,AssistantStrategy:()=>ve,ClaudeAgentStrategy:()=>$e,CodexAgentStrategy:()=>xe,CursorAgentStrategy:()=>be,GeminiAgentStrategy:()=>Ie,getAgentStrategy:()=>wo,invokeAgent:()=>Ps});function wo(i={}){let{state:e={},preferredAgent:t=null}=i,o=t||e.agentType||process.env.AGENT_TYPE;if(!o)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");u.debug(`Agent selection: requested=${o}`);let s=_o.find(r=>r.getName()===o);if(!s)throw new Error(`Unknown agent '${o}'. Available: ${_o.map(r=>r.getName()).join(", ")}`);if(u.debug(`Checking if ${o} can handle this environment...`),!s.canHandle(i)){let n={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"}[o]||"Check your environment configuration";throw new Error(`Agent '${o}' is not available. ${n}`)}return u.debug(`Using agent: ${s.getName()}`),s}async function Ps(i,e={},t={}){try{await import("@zibby/skills")}catch{}let o=wo(e),s=e.state?.config||t.config||{},r=s.models||{},n=t.nodeName&&r[t.nodeName]||null,a=r.default||null,l=o.name,c=s.agent?.[l]?.model||null,f=n||a||c||t.model||null,p={...t,model:f,workspace:e.state?.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:s},d=p.skills||[];if(d.length>0&&!t.skipPromptFragments){let{getSkill:h}=await Promise.resolve().then(()=>(Q(),it)),k=d.map(S=>{let b=h(S)?.promptFragment;return typeof b=="function"?b():b}).filter(Boolean);k.length>0&&(i+=`
118
+ `);let r=(await import("chalk")).default;console.log(r.bold("Prompt sent to LLM:")),console.log(r.dim("\u2500".repeat(60)));let n=!1;for(let a of e)if(a.role==="system")console.log(r.dim(`[System] ${a.content||""}`));else{n||(console.log(r.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),n=!0);let l=a.role==="user"?"Human":"AI",c=a.content?.length>200?`${a.content.slice(0,200)}...`:a.content||"";console.log(r.dim(`[${l}] ${c}`))}console.log(r.dim("\u2500".repeat(60)))}}});var ht={};Re(ht,{AgentStrategy:()=>K,AssistantStrategy:()=>Pe,ClaudeAgentStrategy:()=>xe,CodexAgentStrategy:()=>Te,CursorAgentStrategy:()=>$e,GeminiAgentStrategy:()=>Ae,getAgentStrategy:()=>Oo,invokeAgent:()=>Ms});function Oo(i={}){let{state:e={},preferredAgent:t=null}=i,o=t||e.agentType||process.env.AGENT_TYPE;if(!o)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");u.debug(`Agent selection: requested=${o}`);let s=Eo.find(r=>r.getName()===o);if(!s)throw new Error(`Unknown agent '${o}'. Available: ${Eo.map(r=>r.getName()).join(", ")}`);if(u.debug(`Checking if ${o} can handle this environment...`),!s.canHandle(i)){let n={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"}[o]||"Check your environment configuration";throw new Error(`Agent '${o}' is not available. ${n}`)}return u.debug(`Using agent: ${s.getName()}`),s}async function Ms(i,e={},t={}){try{await import("@zibby/skills")}catch{}let o=Oo(e),s=e.state?.config||t.config||{},r=s.models||{},n=t.nodeName&&r[t.nodeName]||null,a=r.default||null,l=o.name,c=s.agent?.[l]?.model||null,p=n||a||c||t.model||null,f={...t,model:p,workspace:e.state?.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:s},g=f.skills||[],S=i;if(g.length>0&&!t.skipPromptFragments){let{getSkill:C}=await Promise.resolve().then(()=>(te(),at)),y=g.map($=>{let d=C($)?.promptFragment;return typeof d=="function"?d():d}).filter(Boolean);y.length>0&&(S+=`
105
119
 
106
- ${k.join(`
120
+ ${y.join(`
107
121
 
108
- `)}`)}let _=e.state?._currentNodeConfig?.extraPromptInstructions?.trim();return _&&(i+=`
122
+ `)}`)}let h=e.state?._currentNodeConfig?.extraPromptInstructions?.trim();return h&&(S+=`
109
123
 
110
124
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
111
125
  \u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
112
126
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
113
127
 
114
- ${_}
115
- `),u.debug(`Prompt length: ${i.length} chars`),process.env.STAGE!=="prod"&&u.debug(`Full prompt:
116
- ${i}`),o.invoke(i,p)}var _o,ht=R(()=>{qt();Vt();Qt();ro();So();H();ee();_o=[new ve,new be,new $e,new xe,new Ie]});var bo={};Pe(bo,{ConditionalNode:()=>Ce,Node:()=>re});import{writeFileSync as yt,readFileSync as Eo,existsSync as Oo,mkdirSync as Rs}from"node:fs";import{join as St,dirname as Ms}from"node:path";import Ye from"chalk";var re,Ce,_t=R(()=>{Ct();H();ae();he();re=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new De(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){let o=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=p=>t&&typeof t.get=="function"?t.get(p):e?.[p];if(typeof this.customExecute=="function"){u.info("\u26A1 Using custom execute method (skipping LLM)");try{let p=await this.customExecute(e);return typeof p=="object"&&p!==null&&p.success===!1?{success:!1,error:p.error||"Node execution failed",raw:p.raw||null}:this.isZodSchema?(u.debug("Validating return value against outputSchema..."),{success:!0,output:this.outputSchema.parse(p),raw:null}):{success:!0,output:p,raw:null}}catch(p){return u.error(`\u274C Node '${this.name}' execution failed: ${p.message}`),p.name==="ZodError"&&u.error(`Schema validation errors: ${JSON.stringify(p.errors,null,2)}`),{success:!1,error:p.message,raw:null}}}let r=typeof this.prompt=="function"?this.prompt(o()):this.prompt,n=s("_skillHints");n&&(r=`${n}
128
+ ${h}
129
+ `),u.debug(`Prompt length: ${S.length} chars`),process.env.STAGE!=="prod"&&u.debug(`Full prompt:
130
+ ${S}`),o.invoke(S,f)}var Eo,yt=B(()=>{Qt();eo();to();io();wo();X();oe();Eo=[new Pe,new $e,new xe,new Te,new Ae]});var $o={};Re($o,{ConditionalNode:()=>ke,Node:()=>ie});import{writeFileSync as St,readFileSync as bo,existsSync as Io,mkdirSync as Ls}from"node:fs";import{join as _t,dirname as Ds}from"node:path";import ze from"chalk";var ie,ke,wt=B(()=>{Pt();X();ue();Se();ie=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new Be(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){let o=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=f=>t&&typeof t.get=="function"?t.get(f):e?.[f];if(typeof this.customExecute=="function"){u.info("\u26A1 Using custom execute method (skipping LLM)");try{let f=await this.customExecute(e);return typeof f=="object"&&f!==null&&f.success===!1?{success:!1,error:f.error||"Node execution failed",raw:f.raw||null}:this.isZodSchema?(u.debug("Validating return value against outputSchema..."),{success:!0,output:this.outputSchema.parse(f),raw:null}):{success:!0,output:f,raw:null}}catch(f){return u.error(`\u274C Node '${this.name}' execution failed: ${f.message}`),f.name==="ZodError"&&u.error(`Schema validation errors: ${JSON.stringify(f.errors,null,2)}`),{success:!1,error:f.message,raw:null}}}let r=typeof this.prompt=="function"?this.prompt(o()):this.prompt,n=s("_skillHints");n&&(r=`${n}
117
131
 
118
- ${r}`);let a=o(),l=a.cwd||process.cwd(),c=a.sessionPath;try{if(c){let p=St(c,W);if(Oo(p)){let _=JSON.parse(Eo(p,"utf-8"));_.currentNode=this.name,yt(p,JSON.stringify(_,null,2),"utf-8")}let d=St(c,"..",W);if(Oo(d))try{let _=JSON.parse(Eo(d,"utf-8"));_.currentNode=this.name,yt(d,JSON.stringify(_,null,2),"utf-8")}catch{}}}catch(p){u.debug(`Could not update session info: ${p.message}`)}let f=null;for(let p=0;p<=this.retries;p++)try{u.debug(`Node.execute attempt ${p} for '${this.name}'`);let d=o(),_=d.config||{},h={state:d},k={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:c,config:_,nodeName:this.name,timeout:this.config?.timeout||3e5},S=e?._coreInvokeAgent;S||(S=(await Promise.resolve().then(()=>(ht(),gt))).invokeAgent);let b=await S(r,h,k),g,O;if(typeof b=="string"?(g=b,O=null):b.structured?(g=b.raw||JSON.stringify(b.structured,null,2),O=b.structured):(g=b.raw||JSON.stringify(b,null,2),O=b.extracted||null),c)try{let E=St(c,this.name,"raw_stream_output.txt");Rs(Ms(E),{recursive:!0}),yt(E,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(E){u.debug(`Could not save raw output: ${E.message}`)}if(this.isZodSchema&&O){console.log(`
119
- \u{1F50D} ${Ye.cyan("Validated output:")} ${Ye.white(JSON.stringify(O,null,2))}`);let E=O;if(typeof this.onComplete=="function")try{E=await this.onComplete(o(),O)}catch($){u.warn(`onComplete hook failed: ${$.message}`)}return{success:!0,output:E,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:g}),raw:g}}catch(E){throw new Error(`onComplete failed: ${E.message}`,{cause:E})}if(this.parser){let E=this.parser.parse(g);return console.log(`
120
- \u{1F50D} ${Ye.cyan("Parsed output:")} ${Ye.white(JSON.stringify(E,null,2))}`),L.step("Output parsed"),{success:!0,output:E,raw:g}}return{success:!0,output:g,raw:g}}catch(d){f=d,p<this.retries&&u.info(`Node '${this.name}' failed, retrying (${p+1}/${this.retries})...`)}return{success:!1,error:f.message,raw:null}}},Ce=class extends re{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,t){let o=t&&typeof t.getAll=="function"?t.getAll():e;return{success:!0,output:{nextNode:this.condition(o)},raw:null}}}});import{spawn as Ws}from"node:child_process";import{mkdirSync as Ao,existsSync as zs,writeFileSync as Hs}from"node:fs";import{join as Et}from"node:path";import{existsSync as $t,readFileSync as Co}from"node:fs";import{join as He,dirname as xt}from"node:path";var ie=class{static async loadContext(e,t,o={}){let s={},r=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=xt(He(t,e));for(let l of r){let c=await this.findAndMergeContextFiles(l,a,t);if(c){let f=l.replace(/\.[^.]+$/,"").toLowerCase();s[f]=c}}}let n=o.discovery||{};for(let[a,l]of Object.entries(n))try{let c=He(t,l);if($t(c)){let f=await this.loadFile(c);s[a]=f}}catch(c){console.warn(`\u26A0\uFE0F Could not load context '${a}' from '${l}': ${c.message}`)}return s}static async findAndMergeContextFiles(e,t,o){let s=[],r=t;for(;r.startsWith(o);){let n=He(r,e);if($t(n))try{let l=await this.loadFile(n);s.unshift(l)}catch(l){console.warn(`\u26A0\uFE0F Could not load ${e} from ${n}: ${l.message}`)}let a=xt(r);if(a===r)break;r=a}return s.length===0?null:s.every(n=>typeof n=="string")?s.join(`
132
+ ${r}`);let a=o(),l=a.cwd||process.cwd(),c=a.sessionPath;try{if(c){let f=_t(c,H);if(Io(f)){let S=JSON.parse(bo(f,"utf-8"));S.currentNode=this.name,St(f,JSON.stringify(S,null,2),"utf-8")}let g=_t(c,"..",H);if(Io(g))try{let S=JSON.parse(bo(g,"utf-8"));S.currentNode=this.name,St(g,JSON.stringify(S,null,2),"utf-8")}catch{}}}catch(f){u.debug(`Could not update session info: ${f.message}`)}let p=null;for(let f=0;f<=this.retries;f++)try{u.debug(`Node.execute attempt ${f} for '${this.name}'`);let g=o(),S=g.config||{},h={state:g},C={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:c,config:S,nodeName:this.name,timeout:this.config?.timeout||3e5},y=e?._coreInvokeAgent;y||(y=(await Promise.resolve().then(()=>(yt(),ht))).invokeAgent);let $=await y(r,h,C),d,w;if(typeof $=="string"?(d=$,w=null):$.structured?(d=$.raw||JSON.stringify($.structured,null,2),w=$.structured):(d=$.raw||JSON.stringify($,null,2),w=$.extracted||null),c)try{let O=_t(c,this.name,"raw_stream_output.txt");Ls(Ds(O),{recursive:!0}),St(O,typeof d=="string"?d:JSON.stringify(d),"utf-8")}catch(O){u.debug(`Could not save raw output: ${O.message}`)}if(this.isZodSchema&&w){console.log(`
133
+ \u{1F50D} ${ze.cyan("Validated output:")} ${ze.white(JSON.stringify(w,null,2))}`);let O=w;if(typeof this.onComplete=="function")try{O=await this.onComplete(o(),w)}catch(I){u.warn(`onComplete hook failed: ${I.message}`)}return{success:!0,output:O,raw:d}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:d}),raw:d}}catch(O){throw new Error(`onComplete failed: ${O.message}`,{cause:O})}if(this.parser){let O=this.parser.parse(d);return console.log(`
134
+ \u{1F50D} ${ze.cyan("Parsed output:")} ${ze.white(JSON.stringify(O,null,2))}`),U.step("Output parsed"),{success:!0,output:O,raw:d}}return{success:!0,output:d,raw:d}}catch(g){p=g,f<this.retries&&u.info(`Node '${this.name}' failed, retrying (${f+1}/${this.retries})...`)}return{success:!1,error:p.message,raw:null}}},ke=class extends ie{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,t){let o=t&&typeof t.getAll=="function"?t.getAll():e;return{success:!0,output:{nextNode:this.condition(o)},raw:null}}}});import{spawn as Hs}from"node:child_process";import{mkdirSync as Co,existsSync as Zs,writeFileSync as Xs}from"node:fs";import{join as Ot}from"node:path";import{existsSync as $t,readFileSync as ko}from"node:fs";import{join as Ze,dirname as xt}from"node:path";var ce=class{static async loadContext(e,t,o={}){let s={},r=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=xt(Ze(t,e));for(let l of r){let c=await this.findAndMergeContextFiles(l,a,t);if(c){let p=l.replace(/\.[^.]+$/,"").toLowerCase();s[p]=c}}}let n=o.discovery||{};for(let[a,l]of Object.entries(n))try{let c=Ze(t,l);if($t(c)){let p=await this.loadFile(c);s[a]=p}}catch(c){console.warn(`\u26A0\uFE0F Could not load context '${a}' from '${l}': ${c.message}`)}return s}static async findAndMergeContextFiles(e,t,o){let s=[],r=t;for(;r.startsWith(o);){let n=Ze(r,e);if($t(n))try{let l=await this.loadFile(n);s.unshift(l)}catch(l){console.warn(`\u26A0\uFE0F Could not load ${e} from ${n}: ${l.message}`)}let a=xt(r);if(a===r)break;r=a}return s.length===0?null:s.every(n=>typeof n=="string")?s.join(`
121
135
 
122
136
  ---
123
137
 
124
- `):s.every(n=>typeof n=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=Co(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),s=await import(o(e).href);return s.default||s}return t}};Re();import{exec as ko}from"node:child_process";import{promisify as No}from"node:util";import{existsSync as Po}from"node:fs";import{join as Ze}from"node:path";import{homedir as Xe}from"node:os";var It=No(ko);async function Tt(){try{return await It("cursor-agent --version"),"cursor-agent"}catch{let e=[Ze(Xe(),".local","bin","cursor-agent"),Ze(Xe(),".cursor","bin","cursor-agent"),Ze(Xe(),".cursor-agent","bin","cursor-agent")];for(let t of e)if(Po(t))try{return await It(`"${t}" --version`),t}catch{}return null}}he();Ve();_t();he();ae();import{mkdirSync as Io,existsSync as wt,writeFileSync as $o,unlinkSync as Ls}from"node:fs";import{join as ne,resolve as To}from"node:path";import{config as Ds}from"dotenv";import{zodToJsonSchema as xo}from"zod-to-json-schema";import Bs from"handlebars";function Us({traceFrom:i,sessionId:e,sessionPath:t,idSource:o,mkdirFresh:s}){if(process.env.ZIBBY_SESSION_LOG==="0"||process.env.ZIBBY_SESSION_LOG==="false")return;let r=typeof process.ppid=="number"?process.ppid:"n/a",n=`[zibby:session] from=${i} pid=${process.pid} ppid=${r} sessionId=${e} source=${o} mkdir=${s?"yes":"no"} path=${t}`;if(console.log(n),(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 c=(new Error("session trace").stack||"").split(`
138
+ `):s.every(n=>typeof n=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=ko(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),s=await import(o(e).href);return s.default||s}return t}};Me();import{exec as No}from"node:child_process";import{promisify as Ro}from"node:util";import{existsSync as Mo}from"node:fs";import{join as Xe}from"node:path";import{homedir as qe}from"node:os";var Tt=Ro(No);async function At(){try{return await Tt("cursor-agent --version"),"cursor-agent"}catch{let e=[Xe(qe(),".local","bin","cursor-agent"),Xe(qe(),".cursor","bin","cursor-agent"),Xe(qe(),".cursor-agent","bin","cursor-agent")];for(let t of e)if(Mo(t))try{return await Tt(`"${t}" --version`),t}catch{}return null}}Se();Qe();wt();Se();ue();import{mkdirSync as Ao,existsSync as Et,writeFileSync as xo,unlinkSync as Bs}from"node:fs";import{join as ae,resolve as vo}from"node:path";import{config as Us}from"dotenv";import{zodToJsonSchema as To}from"zod-to-json-schema";import js from"handlebars";function Fs({traceFrom:i,sessionId:e,sessionPath:t,idSource:o,mkdirFresh:s}){if(process.env.ZIBBY_SESSION_LOG==="0"||process.env.ZIBBY_SESSION_LOG==="false")return;let r=typeof process.ppid=="number"?process.ppid:"n/a",n=`[zibby:session] from=${i} pid=${process.pid} ppid=${r} sessionId=${e} source=${o} mkdir=${s?"yes":"no"} path=${t}`;if(console.log(n),(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 c=(new Error("session trace").stack||"").split(`
125
139
  `).slice(2,14).join(`
126
140
  `);console.log(`[zibby:session] stack (${i}):
127
- ${c}`)}}function js(){return process.env.ZIBBY_RUN_SOURCE==="studio"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function Fs(){if(process.env.ZIBBY_RUN_SOURCE!=="studio")return;let i=process.env.ZIBBY_SESSION_PATH;if(!(i==null||String(i).trim()===""))try{return To(String(i).trim())}catch{return String(i).trim()}}function Js(){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 Ks(i={}){let e=At.map(r=>process.env[r]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,s=i.paths?.sessionPrefix;return s?`${s}_${o}`:o}function Ys({cwd:i=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let s=t.sessionPath,r=t.sessionTimestamp,n="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let c=To(String(process.env.ZIBBY_SESSION_PATH));c&&(s=c,n="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),r==null&&(r=Date.now());else{let c=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(c)a=c,n="ZIBBY_SESSION_ID";else{let p=e.sessionId!=null?String(e.sessionId).trim():"";p&&p!=="last"?(a=p,n="config.sessionId"):(a=Ks(e),n="generated")}r=r??Date.now();let f=e.paths?.output||q;s=ne(i,f,Me,a)}let l=!wt(s);return l&&Io(s,{recursive:!0}),Us({traceFrom:o,sessionId:a,sessionPath:s,idSource:n,mkdirFresh:l}),Gs({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:r}}var We=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,o={}){let s=t instanceof re?t:new re(t);return s.name=e,this.nodes.set(e,s),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}addConditionalNode(e,t){let o=new Ce({...t,name:e});return this.nodes.set(e,o),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:o}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:o}),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,o,s,r){let n=o;for(let a=e.length-1;a>=0;a--){let l=e[a],c=n;n=()=>l(t,c,s,r)}return n()}serialize(){let e=[],t={};for(let[r,n]of this.nodes){let a=this.nodeTypeMap.get(r)||r;e.push({id:r,type:a,data:{nodeType:a,label:r}});let l=n._isCustomCode||!1,c={};l&&typeof n.execute=="function"&&(c.customCode=n.execute.toString());let f=this.nodePrompts.get(r);if(f&&(c.prompt=f),typeof n.customExecute=="function"&&(c.executeCode=n.customExecute.toString()),n.outputSchema)try{if(typeof n.outputSchema._def<"u"){let _=xo(n.outputSchema,{target:"openApi3"}),h=this._flattenJsonSchemaToVariables(_);c.outputSchema={jsonSchema:_,variables:h}}else c.outputSchema={schema:n.outputSchema}}catch(d){console.warn(`Failed to convert schema for ${r}:`,d.message)}let p=(this.resolvedToolsMap||{})[r];p?.toolIds&&(c.tools=p.toolIds),Object.keys(c).length>0&&(t[r]=c)}let o=[];for(let[r,n]of this.edges)if(typeof n=="string")o.push({source:r,target:n});else if(n.conditional){let a=this.conditionalCodeMap.get(r)||n.routes.toString(),l=this._inferConditionalTargets(n.routes),c=n.labels||{};for(let f of l){let p={source:r,target:f,data:{conditionalCode:a}};c[f]&&(p.label=c[f]),o.push(p)}}let s=null;if(this.stateSchema)try{s=xo(this.stateSchema,{target:"openApi3"})}catch{s=this.stateSchema}return{nodes:e,edges:o,nodeConfigs:t,stateSchema:s}}_inferConditionalTargets(e){let t=e.toString(),o=new Set,s=/return\s+['"]([^'"]+)['"]/g,r;for(;(r=s.exec(t))!==null;)o.add(r[1]);return[...o]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");o=e.definitions[s]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],s=e.properties||{},r=e.required||[];for(let[n,a]of Object.entries(s)){let l=t?`${t}.${n}`:n,c=!r.includes(n);if(o.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(n),optional:c}),a.type==="object"&&a.properties){let f=this._flattenSchema(a,l);o.push(...f)}if(a.type==="array"&&a.items?.type==="object"&&a.items.properties){let f=this._flattenSchema(a.items,`${l}[]`);o.push(...f)}}return o}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let o=[];t.success!==void 0&&o.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,r]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof r=="string"&&r.length<=80)o.push(`${s}: ${r}`);else if(Array.isArray(r)){let n=r.length,a=r.filter(c=>c?.passed===!0).length;if(r.some(c=>c?.passed!==void 0)){let c=n-a;o.push(`${s}: ${a}/${n} passed${c?`, ${c} failed`:""}`)}else o.push(`${s}: ${n} items`)}if(o.length>=4)break}return o}async run(e,t={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let o=t.cwd||process.cwd();Ds({path:ne(o,".env")});let s=t.config||{};if(!s||Object.keys(s).length===0)try{let $=ne(o,".zibby.config.js");wt($)&&(s=(await import($)).default||{})}catch{}process.env.EXECUTION_ID&&!s.agent?.strictMode&&(s.agent={...s.agent,strictMode:!0});let r=t.agentType;if(!r){let $=s?.agent;$?.provider?r=$.provider:$?.gemini?r="gemini":$?.claude?r="claude":$?.cursor?r="cursor":$?.codex?r="codex":r=process.env.AGENT_TYPE||"cursor"}let n=t.contextConfig||e?.config?.contextConfig||e?.config?.context||s?.context||{};if(this.stateSchema){let $=this.stateSchema.safeParse(t);if(!$.success){let x=$.error.issues.map(w=>`${w.path.join(".")}: ${w.message}`);throw console.error("\u274C Initial state validation failed:"),x.forEach(w=>console.error(` - ${w}`)),new Error(`State validation failed: ${x.join(", ")}`)}L.step("State validated against schema")}let a=Fs(),l=t.sessionPath||a;l||Js();let{sessionPath:c,sessionTimestamp:f,sessionId:p}=Ys({cwd:o,config:s,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:t.sessionTimestamp}});L.step(`Session ${p}`);let d=await ie.loadContext(t.specPath||"",o,n);Object.keys(d).length>0&&L.step(`Context loaded: ${Object.keys(d).join(", ")}`);let _=t.outputPath;!_&&t.specPath&&(e?.calculateOutputPath?_=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new ye({...t,config:s,agentType:r,outputPath:_,sessionPath:c,sessionTimestamp:f,context:d,resolvedTools:this.resolvedToolsMap||{}}),k=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:S}=await Promise.resolve().then(()=>(Q(),it)),b=new Set;for(let[,$]of this.nodes)for(let x of $.config?.skills||[])b.add(x);for(let $ of b){let x=S($);if(typeof x?.middleware=="function")try{let w=await x.middleware();typeof w=="function"&&k.set($,w)}catch{}}let g=this.entryPoint,O=[];for(;g&&g!=="END";){let $=ne(c,Le);if(wt($)){console.warn(`
128
- \u{1F6D1} Studio stop requested \u2014 ending workflow.`);try{Ls($)}catch{}if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch{}return L.step("Workflow stopped by Studio"),{success:!0,state:h.getAll(),executionLog:O,stoppedByStudio:!0}}let x=this.nodes.get(g);if(!x)throw new Error(`Node '${g}' not found in graph`);let w=JSON.stringify({sessionPath:c,sessionTimestamp:f,currentNode:g,createdAt:new Date().toISOString(),config:h.get("config")}),v=ne(c,W);$o(v,w,"utf-8");let A=h.get("config")?.paths?.output||q,I=ne(o,A,W);Io(ne(o,A),{recursive:!0});try{$o(I,w,"utf-8")}catch{}let y=t.onPipelineProgress;if(typeof y=="function")try{y({cwd:o,sessionPath:c,sessionId:p,outputBase:h.get("config")?.paths?.output||q,currentNode:g})}catch{}let T=(this.resolvedToolsMap||{})[g]||null;h.set("_currentNodeTools",T);let C=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",C[g]||{}),L.nodeStart(g);let m=Date.now(),N=this.nodePrompts.get(g);if(!this._invokeAgent){let M=await Promise.resolve().then(()=>(ht(),gt));this._invokeAgent=M.invokeAgent}let P=this._invokeAgent,G={state:h,invokeAgent:async(M={},K={})=>{let B=K.prompt||"";if(N)try{B=Bs.compile(N,{noEscape:!0})(M)}catch(Z){throw console.error(`\u274C Template rendering failed for node '${g}':`,Z.message),new Error(`Template rendering failed: ${Z.message}`,{cause:Z})}else if(!B)throw new Error(`No prompt template configured for node '${g}' and no prompt provided in options`);let me={state:h.getAll(),images:K.images||[]},ze={model:K.model||h.get("model"),workspace:h.get("workspace"),schema:K.schema,...K};return P(B,me,ze)},_coreInvokeAgent:P,agent:e,nodeId:g,promptTemplate:N,getPromptTemplate:()=>N,...h.getAll()};try{let M=(x.config?.skills||[]).map(ke=>k.get(ke)).filter(Boolean),K=[...this.middleware,...M],B;K.length>0?B=await this._composeMiddleware(K,g,async()=>x.execute(G,h),h.getAll(),h):B=await x.execute(G,h);let me=Date.now()-m;if(O.push({node:g,success:B.success,duration:me,timestamp:new Date().toISOString()}),!B.success){if(String(B.error||"").includes("Stopped from Zibby Studio")){if(L.step("Workflow stopped by Studio"),h.set("stoppedByStudio",!0),e&&typeof e.cleanup=="function")try{await e.cleanup()}catch{}return{success:!0,state:h.getAll(),executionLog:O,stoppedByStudio:!0}}h.append("errors",{node:g,error:B.error});let ge=x.config?.retries||0,bt=`${g}_retries`,Ne=h.getAll()[bt]||0;if(Ne<ge){L.stepInfo(`Retrying (attempt ${Ne+1}/${ge})`),h.update({[bt]:Ne+1,[`${g}_raw`]:B.raw});continue}throw L.nodeFailed(g,B.error,{duration:me}),new Error(`Node '${g}' failed after ${Ne} attempts: ${B.error}`)}h.update({[g]:B.output});let ze=this._summarizeNodeOutput(g,B.output);L.nodeComplete(g,{duration:me,details:ze});let Z=this.edges.get(g);if(!Z)g="END";else if(Z.conditional){let ke=h.getAll(),ge=Z.routes(ke);L.route(g,ge),g=ge}else g=Z}catch(M){throw L.isInsideNode&&L.nodeFailed(g,M.message,{duration:Date.now()-m}),h.set("failed",!0),h.set("failedAt",g),M}}L.graphComplete();let E={success:!0,state:h.getAll(),executionLog:O};return e&&typeof e.onComplete=="function"&&await e.onComplete(E),E}};var Ot=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,o=!0)=>{let s=["-p",t,"--approve-mcps","--force"];return o&&(s.push("--output-format","stream-json"),s.push("--stream-partial-output")),s})}static extractJsonFromStream(e){return X.extractResult(e)}async initialize(e){this.adapter=e,e&&!e.isConnected()&&await e.connect()}buildGraph(){throw new Error("buildGraph() must be implemented by subclass")}async onComplete(e){}async run(e,t={}){let o=this.buildGraph(),s=typeof e=="object"&&!Array.isArray(e)?{input:e,...e,...t}:{input:e,...t};return await o.run(this,s)}async executeNode(e,t){let{prompt:o,outputSchema:s,model:r}=e,n=typeof o=="function"?o(t):o;console.log(`
141
+ ${c}`)}}function Js(){return process.env.ZIBBY_RUN_SOURCE==="studio"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function Gs(){if(process.env.ZIBBY_RUN_SOURCE!=="studio")return;let i=process.env.ZIBBY_SESSION_PATH;if(!(i==null||String(i).trim()===""))try{return vo(String(i).trim())}catch{return String(i).trim()}}function Ks(){Js()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Ys({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 Ws(i={}){let e=vt.map(r=>process.env[r]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,s=i.paths?.sessionPrefix;return s?`${s}_${o}`:o}function zs({cwd:i=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let s=t.sessionPath,r=t.sessionTimestamp,n="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let c=vo(String(process.env.ZIBBY_SESSION_PATH));c&&(s=c,n="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),r==null&&(r=Date.now());else{let c=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(c)a=c,n="ZIBBY_SESSION_ID";else{let f=e.sessionId!=null?String(e.sessionId).trim():"";f&&f!=="last"?(a=f,n="config.sessionId"):(a=Ws(e),n="generated")}r=r??Date.now();let p=e.paths?.output||Q;s=ae(i,p,Le,a)}let l=!Et(s);return l&&Ao(s,{recursive:!0}),Fs({traceFrom:o,sessionId:a,sessionPath:s,idSource:n,mkdirFresh:l}),Ys({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:r}}var He=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,o={}){let s=t instanceof ie?t:new ie(t);return s.name=e,this.nodes.set(e,s),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}addConditionalNode(e,t){let o=new ke({...t,name:e});return this.nodes.set(e,o),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:o}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:o}),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,o,s,r){let n=o;for(let a=e.length-1;a>=0;a--){let l=e[a],c=n;n=()=>l(t,c,s,r)}return n()}serialize(){let e=[],t={};for(let[r,n]of this.nodes){let a=this.nodeTypeMap.get(r)||r;e.push({id:r,type:a,data:{nodeType:a,label:r}});let l=n._isCustomCode||!1,c={};l&&typeof n.execute=="function"&&(c.customCode=n.execute.toString());let p=this.nodePrompts.get(r);if(p&&(c.prompt=p),typeof n.customExecute=="function"&&(c.executeCode=n.customExecute.toString()),n.outputSchema)try{if(typeof n.outputSchema._def<"u"){let S=To(n.outputSchema,{target:"openApi3"}),h=this._flattenJsonSchemaToVariables(S);c.outputSchema={jsonSchema:S,variables:h}}else c.outputSchema={schema:n.outputSchema}}catch(g){console.warn(`Failed to convert schema for ${r}:`,g.message)}let f=(this.resolvedToolsMap||{})[r];f?.toolIds&&(c.tools=f.toolIds),Object.keys(c).length>0&&(t[r]=c)}let o=[];for(let[r,n]of this.edges)if(typeof n=="string")o.push({source:r,target:n});else if(n.conditional){let a=this.conditionalCodeMap.get(r)||n.routes.toString(),l=this._inferConditionalTargets(n.routes),c=n.labels||{};for(let p of l){let f={source:r,target:p,data:{conditionalCode:a}};c[p]&&(f.label=c[p]),o.push(f)}}let s=null;if(this.stateSchema)try{s=To(this.stateSchema,{target:"openApi3"})}catch{s=this.stateSchema}return{nodes:e,edges:o,nodeConfigs:t,stateSchema:s}}_inferConditionalTargets(e){let t=e.toString(),o=new Set,s=/return\s+['"]([^'"]+)['"]/g,r;for(;(r=s.exec(t))!==null;)o.add(r[1]);return[...o]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");o=e.definitions[s]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],s=e.properties||{},r=e.required||[];for(let[n,a]of Object.entries(s)){let l=t?`${t}.${n}`:n,c=!r.includes(n);if(o.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(n),optional:c}),a.type==="object"&&a.properties){let p=this._flattenSchema(a,l);o.push(...p)}if(a.type==="array"&&a.items?.type==="object"&&a.items.properties){let p=this._flattenSchema(a.items,`${l}[]`);o.push(...p)}}return o}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let o=[];t.success!==void 0&&o.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,r]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof r=="string"&&r.length<=80)o.push(`${s}: ${r}`);else if(Array.isArray(r)){let n=r.length,a=r.filter(c=>c?.passed===!0).length;if(r.some(c=>c?.passed!==void 0)){let c=n-a;o.push(`${s}: ${a}/${n} passed${c?`, ${c} failed`:""}`)}else o.push(`${s}: ${n} items`)}if(o.length>=4)break}return o}async run(e,t={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let o=t.cwd||process.cwd();Us({path:ae(o,".env")});let s=t.config||{};if(!s||Object.keys(s).length===0)try{let I=ae(o,".zibby.config.js");Et(I)&&(s=(await import(I)).default||{})}catch{}process.env.EXECUTION_ID&&!s.agent?.strictMode&&(s.agent={...s.agent,strictMode:!0});let r=t.agentType;if(!r){let I=s?.agent;I?.provider?r=I.provider:I?.gemini?r="gemini":I?.claude?r="claude":I?.cursor?r="cursor":I?.codex?r="codex":r=process.env.AGENT_TYPE||"cursor"}let n=t.contextConfig||e?.config?.contextConfig||e?.config?.context||s?.context||{};if(this.stateSchema){let I=this.stateSchema.safeParse(t);if(!I.success){let x=I.error.issues.map(E=>`${E.path.join(".")}: ${E.message}`);throw console.error("\u274C Initial state validation failed:"),x.forEach(E=>console.error(` - ${E}`)),new Error(`State validation failed: ${x.join(", ")}`)}U.step("State validated against schema")}let a=Gs(),l=t.sessionPath||a;l||Ks();let{sessionPath:c,sessionTimestamp:p,sessionId:f}=zs({cwd:o,config:s,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:t.sessionTimestamp}});U.step(`Session ${f}`);let g=await ce.loadContext(t.specPath||"",o,n);Object.keys(g).length>0&&U.step(`Context loaded: ${Object.keys(g).join(", ")}`);let S=t.outputPath;!S&&t.specPath&&(e?.calculateOutputPath?S=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new _e({...t,config:s,agentType:r,outputPath:S,sessionPath:c,sessionTimestamp:p,context:g,resolvedTools:this.resolvedToolsMap||{}}),C=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(te(),at)),$=new Set;for(let[,I]of this.nodes)for(let x of I.config?.skills||[])$.add(x);for(let I of $){let x=y(I);if(typeof x?.middleware=="function")try{let E=await x.middleware();typeof E=="function"&&C.set(I,E)}catch{}}let d=this.entryPoint,w=[];for(;d&&d!=="END";){let I=ae(c,De);if(Et(I)){console.warn(`
142
+ \u{1F6D1} Studio stop requested \u2014 ending workflow.`);try{Bs(I)}catch{}if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch{}return U.step("Workflow stopped by Studio"),{success:!0,state:h.getAll(),executionLog:w,stoppedByStudio:!0}}let x=this.nodes.get(d);if(!x)throw new Error(`Node '${d}' not found in graph`);let E=JSON.stringify({sessionPath:c,sessionTimestamp:p,currentNode:d,createdAt:new Date().toISOString(),config:h.get("config")}),P=ae(c,H);xo(P,E,"utf-8");let T=h.get("config")?.paths?.output||Q,M=ae(o,T,H);Ao(ae(o,T),{recursive:!0});try{xo(M,E,"utf-8")}catch{}let _=t.onPipelineProgress;if(typeof _=="function")try{_({cwd:o,sessionPath:c,sessionId:f,outputBase:h.get("config")?.paths?.output||Q,currentNode:d})}catch{}let k=(this.resolvedToolsMap||{})[d]||null;h.set("_currentNodeTools",k);let N=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",N[d]||{}),U.nodeStart(d);let m=Date.now(),b=this.nodePrompts.get(d);if(!this._invokeAgent){let R=await Promise.resolve().then(()=>(yt(),ht));this._invokeAgent=R.invokeAgent}let A=this._invokeAgent,v={state:h,invokeAgent:async(R={},L={})=>{let D=L.prompt||"";if(b)try{D=js.compile(b,{noEscape:!0})(R)}catch(W){throw console.error(`\u274C Template rendering failed for node '${d}':`,W.message),new Error(`Template rendering failed: ${W.message}`,{cause:W})}else if(!D)throw new Error(`No prompt template configured for node '${d}' and no prompt provided in options`);let q={state:h.getAll(),images:L.images||[]},le={model:L.model||h.get("model"),workspace:h.get("workspace"),schema:L.schema,...L};return A(D,q,le)},_coreInvokeAgent:A,agent:e,nodeId:d,promptTemplate:b,getPromptTemplate:()=>b,...h.getAll()};try{let R=(x.config?.skills||[]).map(Y=>C.get(Y)).filter(Boolean),L=[...this.middleware,...R],D;L.length>0?D=await this._composeMiddleware(L,d,async()=>x.execute(v,h),h.getAll(),h):D=await x.execute(v,h);let q=Date.now()-m;if(w.push({node:d,success:D.success,duration:q,timestamp:new Date().toISOString()}),!D.success){if(String(D.error||"").includes("Stopped from Zibby Studio")){if(U.step("Workflow stopped by Studio"),h.set("stoppedByStudio",!0),e&&typeof e.cleanup=="function")try{await e.cleanup()}catch{}return{success:!0,state:h.getAll(),executionLog:w,stoppedByStudio:!0}}h.append("errors",{node:d,error:D.error});let ye=x.config?.retries||0,It=`${d}_retries`,Ne=h.getAll()[It]||0;if(Ne<ye){U.stepInfo(`Retrying (attempt ${Ne+1}/${ye})`),h.update({[It]:Ne+1,[`${d}_raw`]:D.raw});continue}throw U.nodeFailed(d,D.error,{duration:q}),new Error(`Node '${d}' failed after ${Ne} attempts: ${D.error}`)}h.update({[d]:D.output});let le=this._summarizeNodeOutput(d,D.output);U.nodeComplete(d,{duration:q,details:le});let W=this.edges.get(d);if(!W)d="END";else if(W.conditional){let Y=h.getAll(),ye=W.routes(Y);U.route(d,ye),d=ye}else d=W}catch(R){throw U.isInsideNode&&U.nodeFailed(d,R.message,{duration:Date.now()-m}),h.set("failed",!0),h.set("failedAt",d),R}}U.graphComplete();let O={success:!0,state:h.getAll(),executionLog:w};return e&&typeof e.onComplete=="function"&&await e.onComplete(O),O}};var bt=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,o=!0)=>{let s=["-p",t,"--approve-mcps","--force"];return o&&(s.push("--output-format","stream-json"),s.push("--stream-partial-output")),s})}static extractJsonFromStream(e){return V.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 o=this.buildGraph(),s=typeof e=="object"&&!Array.isArray(e)?{input:e,...e,...t}:{input:e,...t};return await o.run(this,s)}async executeNode(e,t){let{prompt:o,outputSchema:s,model:r}=e,n=typeof o=="function"?o(t):o;console.log(`
129
143
  \u{1F4DD} Prompt:
130
144
  ${n}
131
145
  `);let a=await this.executePrompt(n,t.cwd,3e5,r);console.log(`
@@ -134,11 +148,11 @@ ${a}
134
148
  `);let l=null;if(s)try{if(l=i.extractJsonFromStream(a),!l)throw new Error("No valid result JSON found in output");console.log(`
135
149
  \u2705 Parsed Output:
136
150
  ${JSON.stringify(l,null,2)}
137
- `)}catch(c){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${c.message}`)}return{success:!0,output:l,raw:a}}async cleanup(){this.adapter&&this.adapter.isConnected()&&await this.adapter.disconnect()}async executePrompt(e,t=process.cwd(),o=3e5,s=null,r=!0){let n=this.agentCommand;if(n==="cursor-agent"){let a=await Tt();a&&(n=a)}return new Promise((a,l)=>{let c="",f=this.buildArgs(e,r);s&&f.push("--model",s);let p={...process.env},d=Ws(n,f,{cwd:t,env:p,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),_=setTimeout(()=>{console.log(`
138
- \u23F1\uFE0F Timeout reached (${o/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 ${o/1e3}s. The agent may be stuck or waiting for user input.`))},o),h=0,k=Date.now(),S=setInterval(()=>{if(c.length>h)h=c.length,k=Date.now();else{let E=Date.now()-k;E>1e4&&console.log(`\u23F3 AI agent is thinking... (${Math.floor(E/1e3)}s, ${c.length} bytes so far)`)}},1e4),b=()=>{clearTimeout(_),clearInterval(S),d&&!d.killed&&(d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},2e3))},g=()=>{console.log(`
151
+ `)}catch(c){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${c.message}`)}return{success:!0,output:l,raw:a}}async cleanup(){this.adapter&&this.adapter.isConnected()&&await this.adapter.disconnect()}async executePrompt(e,t=process.cwd(),o=3e5,s=null,r=!0){let n=this.agentCommand;if(n==="cursor-agent"){let a=await At();a&&(n=a)}return new Promise((a,l)=>{let c="",p=this.buildArgs(e,r);s&&p.push("--model",s);let f={...process.env},g=Hs(n,p,{cwd:t,env:f,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),S=setTimeout(()=>{console.log(`
152
+ \u23F1\uFE0F Timeout reached (${o/1e3}s) - killing agent...`),g.kill("SIGTERM"),setTimeout(()=>{g.killed||(console.log("\u26A0\uFE0F Forcing kill (SIGKILL)..."),g.kill("SIGKILL"))},2e3),l(new Error(`Agent timed out after ${o/1e3}s. The agent may be stuck or waiting for user input.`))},o),h=0,C=Date.now(),y=setInterval(()=>{if(c.length>h)h=c.length,C=Date.now();else{let O=Date.now()-C;O>1e4&&console.log(`\u23F3 AI agent is thinking... (${Math.floor(O/1e3)}s, ${c.length} bytes so far)`)}},1e4),$=()=>{clearTimeout(S),clearInterval(y),g&&!g.killed&&(g.kill("SIGTERM"),setTimeout(()=>{g.killed||g.kill("SIGKILL")},2e3))},d=()=>{console.log(`
139
153
 
140
- \u{1F6D1} Interrupted by user (Ctrl+C)`),b(),l(new Error("Interrupted by user"))};process.on("SIGINT",g);let O=new X;d.stdout.on("data",E=>{let $=E.toString();c+=$;let x=O.processChunk($);x&&(process.stdout.write(x,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),k=Date.now(),h+=x.length)}),d.on("close",E=>{process.off("SIGINT",g),clearTimeout(_),clearInterval(S);let $=O.flush();$&&process.stdout.write($),c=O.getRawText();let x=O.getResult();E===0?a({raw:c,extracted:x}):l(new Error(`Agent exited with code ${E}`))}),d.on("error",E=>{process.off("SIGINT",g),clearTimeout(_),clearInterval(S),l(new Error(`Failed to spawn agent: ${E.message}`))})})}async runSingleNode(e,t,o){let s=t[e];if(!s)throw new Error(`Unknown node: ${e}. Available nodes: ${Object.keys(t).join(", ")}`);let{cwd:r}=o;if(!r)throw new Error("cwd is required for single node execution");let n=o.sessionPath,a=o.sessionTimestamp,l=o.config||{};if(!n){let g=process.env.CI_JOB_ID||process.env.GITHUB_RUN_ID||process.env.CIRCLE_WORKFLOW_ID||process.env.BUILD_ID||Date.now().toString(),O=l.paths?.sessionPrefix,E=O?`${O}_${g}`:g;a=a||Date.now();let $=l.paths?.output||q;n=Et(r,$,Me,E),zs(n)||Ao(n,{recursive:!0})}let c=l.paths?.output||q,f=Et(r,c,W);Ao(Et(r,c),{recursive:!0}),Hs(f,JSON.stringify({sessionPath:n,sessionTimestamp:a||n.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
154
+ \u{1F6D1} Interrupted by user (Ctrl+C)`),$(),l(new Error("Interrupted by user"))};process.on("SIGINT",d);let w=new V;g.stdout.on("data",O=>{let I=O.toString();c+=I;let x=w.processChunk(I);x&&(process.stdout.write(x,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),C=Date.now(),h+=x.length)}),g.on("close",O=>{process.off("SIGINT",d),clearTimeout(S),clearInterval(y);let I=w.flush();I&&process.stdout.write(I),c=w.getRawText();let x=w.getResult();O===0?a({raw:c,extracted:x}):l(new Error(`Agent exited with code ${O}`))}),g.on("error",O=>{process.off("SIGINT",d),clearTimeout(S),clearInterval(y),l(new Error(`Failed to spawn agent: ${O.message}`))})})}async runSingleNode(e,t,o){let s=t[e];if(!s)throw new Error(`Unknown node: ${e}. Available nodes: ${Object.keys(t).join(", ")}`);let{cwd:r}=o;if(!r)throw new Error("cwd is required for single node execution");let n=o.sessionPath,a=o.sessionTimestamp,l=o.config||{};if(!n){let d=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,O=w?`${w}_${d}`:d;a=a||Date.now();let I=l.paths?.output||Q;n=Ot(r,I,Le,O),Zs(n)||Co(n,{recursive:!0})}let c=l.paths?.output||Q,p=Ot(r,c,H);Co(Ot(r,c),{recursive:!0}),Xs(p,JSON.stringify({sessionPath:n,sessionTimestamp:a||n.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
141
155
  ${"=".repeat(80)}`),console.log(`\u{1F3AF} SINGLE NODE EXECUTION: ${e}`),console.log(`\u{1F4C1} Session: ${n.split("/").pop()}${o.sessionPath?" (reusing)":""}`),console.log(`${"=".repeat(80)}
142
- `);let p=await ie.loadContext(o.specPath||"",r,o.contextConfig||{}),{Node:d}=await Promise.resolve().then(()=>(_t(),bo)),{WorkflowState:_}=await Promise.resolve().then(()=>(Ve(),vt)),h=new _({...o,sessionPath:n,sessionTimestamp:a,context:p}),S=await new d(s).execute(this,h);return console.log(`
156
+ `);let f=await ce.loadContext(o.specPath||"",r,o.contextConfig||{}),{Node:g}=await Promise.resolve().then(()=>(wt(),$o)),{WorkflowState:S}=await Promise.resolve().then(()=>(Qe(),Ct)),h=new S({...o,sessionPath:n,sessionTimestamp:a,context:f}),y=await new g(s).execute(this,h);return console.log(`
143
157
  ${"=".repeat(80)}`),console.log(`\u2705 Node ${e} completed`),console.log(`${"=".repeat(80)}
144
- `),{success:!0,output:S.output,outputPath:o.outputPath,state:S}}calculateOutputPath(e){let{specs:t,generated:o}=this.paths;if(!e)return`${o}/generated-test.spec.js`;let s=e.replace(new RegExp(`^${t}/`),"").replace(/\.[^.]+$/,".spec.js");return`${o}/${s}`.replace(/\/+/g,"/")}};function Ai(i,e={}){let t=new Ot(e);return t.buildGraph=function(){let o=new We;return i(o),o},e.onComplete&&(t.onComplete=e.onComplete),t}export{Ot as WorkflowAgent,Ai as workflow};
158
+ `),{success:!0,output:y.output,outputPath:o.outputPath,state:y}}calculateOutputPath(e){let{specs:t,generated:o}=this.paths;if(!e)return`${o}/generated-test.spec.js`;let s=e.replace(new RegExp(`^${t}/`),"").replace(/\.[^.]+$/,".spec.js");return`${o}/${s}`.replace(/\/+/g,"/")}};function ki(i,e={}){let t=new bt(e);return t.buildGraph=function(){let o=new He;return i(o),o},e.onComplete&&(t.onComplete=e.onComplete),t}export{bt as WorkflowAgent,ki as workflow};