@zibby/core 0.1.41 → 0.1.42

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,20 @@
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(`
1
+ var xo=Object.defineProperty;var B=(i,e)=>()=>(i&&(e=i(i=0)),e);var Pe=(i,e)=>{for(var t in e)xo(i,t,{get:e[t],enumerable:!0})};var q,Ne=B(()=>{q=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],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
- ${t.join(`
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===`
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],u=n[l],p=u&&typeof u=="object"?u.args??u.input??u: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,u=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)&&(u++,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,Re,H,Me,Ot,ye=B(()=>{Q=".zibby/output",Re="sessions",H=".session-info.json",Me=".zibby-studio-stop",Ot=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"]});var bt={};Pe(bt,{WorkflowState:()=>He});import{WorkflowState as He}from"@zibby/workflow";var Ze=B(()=>{});import{OutputParser as $t,SchemaTypes as rr}from"@zibby/workflow";var xt=B(()=>{});import Se from"chalk";var Z,Xe,c,X=B(()=>{Z={debug:0,info:1,warn:2,error:3,silent:4},Xe=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)}},c=new Xe});import F from"chalk";function kt(i){return i<1e3?`${i}ms`:`${(i/1e3).toFixed(1)}s`}function Nt(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+=Ct,e.col=Pt,e.lineStart=!1),l===`
7
5
  `?(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
- ${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(`
6
+ ${Ct}`,e.col=Pt))}return i(n,o,s)}}var Co,_e,Po,Tt,Ve,At,vt,qe,Ct,Pt,Qe,U,ce=B(()=>{Co="__WORKFLOW_GRAPH_LOG__",_e=F.gray("\u2502"),Po=F.gray("\u250C"),Tt=F.gray("\u2514"),Ve=F.green("\u25C6"),At=F.hex("#c084fc")("\u25C6"),vt=F.hex("#2dd4bf")("\u25C6"),qe=F.red("\u25C6"),Ct=`${_e} `,Pt=2;Qe=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=Nt(this._origStdoutWrite,e),process.stderr.write=Nt(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
9
7
  `),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
10
8
  `),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=`${Do}${JSON.stringify(e)}
9
+ `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Co}${JSON.stringify(e)}
12
10
  `;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
13
11
  `),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
14
12
  `)):process.stdout.write.bind(process.stdout)(`${e} ${t}
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`
13
+ `)}step(e){this._origStdoutWrite?this._writeDot(Ve,e):process.stdout.write.bind(process.stdout)(`${_e} ${Ve} ${e}
14
+ `)}stepTool(e){this._origStdoutWrite?this._writeDot(At,e):process.stdout.write.bind(process.stdout)(`${_e} ${At} ${e}
15
+ `)}stepMemory(e){let t=F.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(vt,t):process.stdout.write.bind(process.stdout)(`${_e} ${vt} ${t}
16
+ `)}stepFail(e){this._origStdoutWrite?this._writeDot(qe,F.red(e)):process.stdout.write.bind(process.stdout)(`${_e} ${qe} ${F.red(e)}
17
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Po} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:o,details:s}=t;if(s)for(let n of s)this._rawWrite(`${Ve} ${n}`);let r=o?F.dim(` ${kt(o)}`):"";this._rawWrite(`${Tt} ${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(` ${kt(s)}`):"";this._rawWrite(`${qe} ${F.red(t)}`),this._rawWrite(`${Tt} ${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 Qe});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 G,et,tt,Rt,Le,se=B(()=>{G={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"},et={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"},tt={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"},Rt={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},Le={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4}});var ot={};Pe(ot,{getAllSkills:()=>st,getSkill:()=>j,hasSkill:()=>No,listSkillIds:()=>Ro,registerSkill:()=>ko});import{registerSkill as ko,getSkill as j,hasSkill as No,getAllSkills as st,listSkillIds as Ro}from"@zibby/workflow";var te=B(()=>{});import{zodToJsonSchema as Mo}from"zod-to-json-schema";var De,Mt=B(()=>{De=class{static generateFileOutputInstructions(e,t){let o;typeof e?.parse=="function"?o=Mo(e,{target:"openApi3"}):o=e;let s=this._buildExample(o);return`
20
18
  \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
19
  \u{1F6A8} MANDATORY: WRITE RESULT TO FILE \u{1F6A8}
22
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
@@ -36,9 +34,9 @@ JSON types (strict \u2014 validators reject wrong types):
36
34
  - Use true/false without quotes for booleans.
37
35
  - Use unquoted null where a field may be null.
38
36
 
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+=`
37
+ Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(e){if(!e)return{};let t=e.type;if(t==="object"&&e.properties){let 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 ue,rt=B(()=>{Mt();ue=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
38
 
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
39
+ ${e}`:this.userPrompt=e,this}addSkillHints(e){return e&&this.systemInstructions.push({type:"skill_hints",content:e,position:"prepend"}),this}addStructuredOutput(e,t){if(e&&t){let o=De.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
40
  \u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
43
41
  \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
42
 
@@ -46,15 +44,15 @@ ${e.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:t,p
46
44
 
47
45
  `),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
46
 
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] ...
47
+ `)}getStats(){let e=this.userPrompt.length,t=this.build().length;return{userPromptLength:e,fullPromptLength:t,systemInstructionsLength:t-e,instructionCount:this.systemInstructions.length,instructionTypes:this.systemInstructions.map(o=>o.type)}}clone(){let e=new i(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}}});import Lo from"axios";import{homedir as Do}from"node:os";import{join as Bo}from"node:path";import{existsSync as Uo,readFileSync as Jo}from"node:fs";import{toJSONSchema as Fo}from"zod";function Go(){if(process.env.OPENAI_PROXY_TOKEN)return c.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return c.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let i=Bo(Do(),".zibby","config.json");if(Uo(i)){let e=JSON.parse(Jo(i,"utf-8"));if(e.sessionToken)return c.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(i){c.debug(`[Auth] Could not read zibby login session: ${i.message}`)}return null}function jo(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function pe(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(pe)}else"additionalProperties"in i||(i.additionalProperties=!0);i.type==="array"&&i.items&&pe(i.items),i.anyOf&&i.anyOf.forEach(pe),i.oneOf&&i.oneOf.forEach(pe),i.allOf&&i.allOf.forEach(pe)}}async function Lt(i,e){c.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=Go();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=jo();c.info(`\u{1F517} Using OpenAI proxy: ${o}`);let s=Fo(e),r=s;if(s.$ref&&s.definitions){let p=s.$ref.split("/").pop();r=s.definitions[p]||s,c.debug(`Extracted schema from $ref: ${p}`)}delete r.$schema,pe(r);let n=4e5,a=i;i.length>n&&(c.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${i.length} chars) exceeds limit, keeping last ${n} chars`),a=`... [truncated early content] ...
50
48
  ${i.slice(-n)}`);let l=`Extract and format the following information into structured JSON matching the schema.
51
49
 
52
50
  RAW CONTENT:
53
51
  ${a}
54
52
 
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.
53
+ Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,u={model:G.OPENAI_POSTPROCESSING,messages:[{role:"user",content:l}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:r,strict:!0}}};c.info(`\u{1F4E4} Sending to OpenAI proxy: model=${G.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(r.properties||{}).join(", ")}`),c.debug(` Schema size: ${JSON.stringify(r).length} chars`),c.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 Lo.post(o,u,{headers:p,timeout:Le.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!g)throw new Error("OpenAI proxy returned empty response");let S=JSON.parse(g);return c.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 c.error(`\u274C OpenAI proxy request failed: ${f}`),c.error(` Status: ${f}`),c.error(` Response: ${JSON.stringify(g,null,2)}`),f===401||f===403?new Error(`Authentication failed for OpenAI proxy.
56
54
  Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
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.
55
+ Response: ${JSON.stringify(g)}`,{cause:p}):new Error(`Failed to format Cursor output: ${g?.error?.message||"Unknown error"}`,{cause:p})}throw c.error(`\u274C OpenAI proxy request failed: ${p.message}`),new Error(`Failed to format output: ${p.message}`,{cause:p})}}var Dt=B(()=>{X();se()});import{copyFileSync as Ko,existsSync as nt,lstatSync as Yo,mkdirSync as Bt,rmSync as Wo,symlinkSync as zo,unlinkSync as Ho}from"node:fs";import{join as ee}from"node:path";import{homedir as Zo}from"node:os";import{randomBytes as Xo}from"node:crypto";function Ut(i){return!(!i||typeof i!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function Jt(i){let e=ee(i||process.cwd(),".zibby","tmp");Bt(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${Xo(4).toString("hex")}`,o=ee(e,`cursor-agent-home-${t}`),s=ee(o,".cursor");Bt(s,{recursive:!0});let r=Zo(),n=ee(r,".cursor");if(nt(n))for(let a of Vo){let l=ee(n,a);if(nt(l))try{Ko(l,ee(s,a))}catch{}}if(process.platform==="darwin"){let a=ee(r,"Library");if(nt(a))try{zo(a,ee(o,"Library"))}catch{}}return o}function Ft(i){if(!(!i||typeof i!="string"))try{let e=ee(i,"Library");try{Yo(e).isSymbolicLink()&&Ho(e)}catch{}Wo(i,{recursive:!0,force:!0})}catch{}}var Vo,Gt=B(()=>{Vo=["cli-config.json","config.json","auth.json","argv.json"]});import{spawn as qo,execSync as re}from"node:child_process";import{writeFileSync as jt,readFileSync as Kt,mkdirSync as Yt,existsSync as we,accessSync as Wt,constants as zt,unlinkSync as Qo}from"node:fs";import{join as z,resolve as es}from"node:path";import{homedir as Ee}from"node:os";var Ie,Ht=B(()=>{oe();X();se();ye();te();Ne();rt();Dt();ce();Gt();Ie=class extends K{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[z(Ee(),".local","bin","cursor-agent"),z(Ee(),".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("/")){Wt(o,zt.X_OK);let s=re(`"${o}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return c.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 c.debug(`[Cursor] Found '${o}' in PATH at ${s} (version: ${r.trim().slice(0,50)})`),!0}}catch{continue}return c.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:u=Le.CURSOR_AGENT_DEFAULT,config:p={}}=t,f=p?.agent?.strictMode||!1,g=t.model??p?.agent?.cursor?.model??G.CURSOR;c.debug(`[Cursor] Invoking (model: ${g}, timeout: ${u/1e3}s, skills: ${JSON.stringify(n)})`);let h=(this._setupMcpConfig(a,o,p,n,l)||{}).isolatedMcpHome??null,C=[z(Ee(),".local","bin","cursor-agent"),z(Ee(),".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("/"))Wt(m,zt.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,c.debug(`[Agent] Using binary: ${m}`);break}catch(O){c.debug(`[Agent] Binary '${m}' check failed: ${O.message}`);continue}if(!y)throw new Error(`Cursor Agent CLI not found or not working.
58
56
 
59
57
  Checked paths:
60
58
  ${C.map(m=>` - ${m}`).join(`
@@ -66,56 +64,56 @@ Install cursor-agent:
66
64
  Then add to PATH:
67
65
  echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
68
66
 
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:
67
+ Test with: agent --version`);let $=new ue(e),d=null;if(r){let m=`zibby-result-${Date.now()}.json`;d=z(o,".zibby","tmp",m);let O=z(o,".zibby","tmp");we(O)||Yt(O,{recursive:!0}),$.addStructuredOutput(r,d)}let w=process.env.CURSOR_API_KEY,I=w?` | key: ***${w.slice(-4)}`:" | key: not set";console.log(`
68
+ \u25C6 Model: ${g||"auto"}${I}
69
+ `);let b=(await import("chalk")).default,x=$.getUserPrompt();console.log(`
70
+ ${b.bold("Prompt sent to LLM:")}`),console.log(b.dim("\u2500".repeat(60))),console.log(b.dim(x)),console.log(b.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),c.debug(`[Agent] User prompt: ${P.userPromptLength} chars, System instructions: ${P.systemInstructionsLength} chars (${P.instructionCount} blocks), Full: ${P.fullPromptLength} chars, model: ${g||"auto"}`),c.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)
71
+ `)}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,u,null,m,h)}catch(m){_=m}let k=M?.stdout||"";if(r){let m=typeof r.parse=="function",O=null,A=!!(d&&we(d));if(d&&c.info(`[Agent] Result file: ${A?"present":"missing"} at ${d}`),A)try{let v=Kt(d,"utf-8").trim();O=JSON.parse(v),c.info(`[Agent] Parsed JSON from result file OK (${v.length} chars) \u2192 object ready for validation`),_&&c.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(v){c.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${v.message}`)}else if(_)c.warn(`[Agent] Result file missing at ${d} (agent process error \u2014 may still recover if strictMode repairs)`);else throw c.error(`\u274C [Agent] Result file was never created at ${d}`),new Error(`Agent did not write required result file at ${d}`);if(O&&m)try{let v=r.parse(O);return c.info("\u2705 [Agent] Zod validation passed for structured result file"),f&&c.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(`
72
+ `):v.message?.slice(0,400);if(c.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
73
+ ${R}`),c.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
74
+ ${JSON.stringify(O,null,2).slice(0,500)}`),!f)throw new Error(`Agent output failed schema validation:
77
75
  ${R}
78
76
 
79
77
  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()?`
78
+ Enable strictMode in .zibby.config.js for automatic repair.`,{cause:v})}else{if(O)return c.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),f&&c.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:k,structured:O};A&&c.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(f&&!_){let v=M.parsedText,R=O?JSON.stringify(O):v;c.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${R.length} chars in)`);try{let L=await Lt(R,r);if(m){let D=r.parse(L.structured);return c.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:k,structured:D}}return{raw:k,...L}}catch(L){if(c.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${L.message}`),O)return c.warn("[Agent] Using agent's original result file as fallback"),{raw:k,structured:O}}}if(_)throw _;let J=A?O==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 c.error(`\u274C [Agent] No validated structured output: ${J}`),c.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(`
79
+ `),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(u=>u.type==="text"&&u.text).map(u=>u.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(Ee(),".cursor"),l=z(a,"mcp.json"),u={};if(we(l))try{u=JSON.parse(Kt(l,"utf-8"))}catch{}let p=u.mcpServers||{},f=o?.paths?.output||Q,g=z(t||process.cwd(),f,H),S=Array.isArray(s)?s.map(y=>j(y)).filter(Boolean):[...st()].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=j("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 c.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let C=`${JSON.stringify({mcpServers:p},null,2)}
80
+ `;if(Ut(e)){let y=Jt(t||process.cwd()),$=z(y,".cursor","mcp.json");return jt($,C,"utf8"),c.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${y} | servers: ${Object.keys(p).join(", ")}`),{isolatedMcpHome:y}}return we(a)||Yt(a,{recursive:!0}),jt(l,C,"utf8"),c.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},c.debug(`[MCP] Updated ${l} session \u2192 ${o}`);return}if(l)return;let u=t.resolve({sessionPath:o,nodeName:r,headless:n});u&&(e[a]={...u,...t.sessionEnvKey&&{env:{...u.env||{},[t.sessionEnvKey]:s}}},c.debug(`[MCP] Configured ${a}`))}_spawnWithStreaming(e,t,o,s,r=null,n=null,a=null){return new Promise((l,u)=>{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(es(String(n)),Me)}catch{w=null}let I=!1,b=()=>{I||(I=!0,Ft(a))},x={...process.env};a&&(x.HOME=a,process.platform==="win32"&&(x.USERPROFILE=a),c.debug(`[Agent] cursor-agent HOME=${a} (isolated MCP config)`));let E=qo(e,t,{cwd:o,shell:!1,stdio:["pipe","pipe","pipe"],env:x});c.debug(`[Agent] PID: ${E.pid}`),E.stdin.on("error",m=>{m.code!=="EPIPE"&&c.warn(`[Agent] stdin error: ${m.message}`)}),E.stdout.on("error",m=>{m.code!=="EPIPE"&&c.warn(`[Agent] stdout error: ${m.message}`)}),E.stderr.on("error",m=>{m.code!=="EPIPE"&&c.warn(`[Agent] stderr error: ${m.message}`)}),r?(E.stdin.write(r,m=>{m&&m.code!=="EPIPE"&&c.warn(`[Agent] Failed to write to stdin: ${m.message}`),E.stdin.end()}),c.debug(`[Agent] Prompt also piped to stdin (${r.length} chars)`)):E.stdin.end();let P=null;w&&(P=setInterval(()=>{if(!(C||d))try{if(we(w)){C=!0,y="studio-stop";try{Qo(w)}catch{}c.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),O=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(`
81
+ `)){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`),c.debug(`\u{1F493} [Agent] Running for ${m}s | ${h} lines output${J}`),h===0&&m>=30&&T.size===0&&(m<35&&c.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",c.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);c.error(`\u23F1\uFE0F [Agent] Timeout after ${m}s \u2014 killing process (PID: ${E.pid})`),f.trim()&&c.warn(`\u{1F4E4} [Agent] Partial output (${f.length} chars) before timeout:
82
+ ${f.slice(-2e3)}`),E.kill("SIGTERM"),setTimeout(()=>{E.killed||E.kill("SIGKILL")},5e3)},s),N=new q;N.onToolCall=(m,O)=>{let A=m,J=O;if(m==="mcpToolCall"&&O?.name)A=O.name.replace(/^mcp_+[^_]+_+/,""),A.includes("-")&&A.split("-")[0]===A.split("-")[1]&&(A=A.split("-")[0]),J=O.args??O.input??O;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 O=m.toString();f+=O,S=Date.now(),$||($=!0);let A=N.processChunk(O);A&&!d&&process.stdout.write(A);let J=O.split(`
83
+ `).filter(v=>v.trim());h+=J.length}),E.stderr.on("data",m=>{let O=m.toString();g+=O,S=Date.now(),$||($=!0);let A=O.split(`
84
+ `).filter(J=>J.trim());for(let J of A)c.warn(`\u26A0\uFE0F [Agent stderr] ${J}`)}),E.on("close",(m,O)=>{d=!0,b(),clearTimeout(k),clearInterval(_),P&&clearInterval(P),N.flush();let A=Math.round((Date.now()-p)/1e3);if(c.debug(`[Agent] Exited: code=${m}, signal=${O}, elapsed=${A}s, output=${f.length} chars`),C){if(y==="studio-stop"){u(new Error("Stopped from Zibby Studio"));return}u(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()?`
87
85
  Partial output (last 500 chars):
88
- ${f.slice(-500)}`:"No output captured."}`));return}if(m!==0){c(new Error(`Cursor Agent failed: exit code ${m}, signal ${b}. ${g.trim()?`
86
+ ${f.slice(-500)}`:"No output captured."}`));return}if(m!==0){u(new Error(`Cursor Agent failed: exit code ${m}, signal ${O}. ${g.trim()?`
89
87
  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}
88
+ 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=>{b(),clearTimeout(k),clearInterval(_),P&&clearInterval(P),u(new Error(`Cursor Agent spawn error: ${m.message}
91
89
  Binary: ${e}
92
90
  This usually means the binary is not in PATH. Try:
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(`
91
+ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}}});import{query as ts}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as os}from"zod-to-json-schema";var Oe,Zt=B(()=>{oe();X();ce();se();te();Oe=class extends K{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!process.env.ANTHROPIC_API_KEY;return t||c.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:u=null,timeout:p,config:f={}}=t,g=o;(!g||g==="auto")&&(c.debug(`Model is '${g||"undefined"}', using default: ${G.CLAUDE}`),g=G.CLAUDE);let S=et[g]||g;et[g]&&g!==S&&c.debug(`Mapped model: ${g} \u2192 ${S}`),c.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
92
  \u25C6 Model: ${S}${C}
95
93
  `);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(`
94
+ ${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:u});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"?os(r,{target:"openApi3"}):r;w.outputFormat={type:"json_schema",schema:k},c.debug("Structured output enforced via SDK outputFormat")}c.debug(`Agent SDK options: ${JSON.stringify({cwd:w.cwd,toolCount:$.length,permissionMode:w.permissionMode,model:w.model,hasOutputFormat:!!w.outputFormat})}`);let I="",b=0,x=[];c.debug("Starting Claude Agent SDK query stream");let E;try{E=ts({prompt:e,options:w})}catch(_){throw c.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)I+=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"){b++,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||I;if(r){if(_.structured_output){c.debug("Using SDK native structured_output");let O=typeof r.parse=="function"?r.parse(_.structured_output):_.structured_output;return{raw:N,structured:O}}if(N){let m=this._extractJson(N,r);if(m)return{raw:N,structured:m}}c.warn(`Could not extract structured output \u2014 returning raw text (${(N||"").length} chars)`)}return N||""}}}if(c.warn(`Agent SDK ended without result. Collected ${x.length} messages`),I.length>0)return c.debug("Returning accumulated text from messages"),I;throw new Error("Claude Agent SDK query ended without result")}catch(_){throw c.error(`Error during query stream: ${_.message}`),_}}catch(w){throw c.error("Claude Agent SDK call failed",{error:w.message}),w}}_resolveSkills(e,t){if(e===null)return c.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return c.debug("Default IDE skills for code generation"),{allowedTools:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};let o=[],s={};for(let r of e){let n=j(r);if(!n){c.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,c.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 ss}from"node:child_process";import{zodToJsonSchema as rs}from"zod-to-json-schema";var be,Xt=B(()=>{oe();X();ce();se();te();be=class extends K{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.CODEX_API_KEY))return c.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return ss("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return c.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:u,config:p={}}=t,{Codex:f}=await import("@openai/codex-sdk"),g=o;(!g||g==="auto")&&(c.debug(`Model is '${g||"undefined"}', using default: ${G.CODEX}`),g=G.CODEX);let S=tt[g]||g;tt[g]&&g!==S&&c.debug(`Mapped model: ${g} \u2192 ${S}`),c.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
95
  \u25C6 Model: ${S}${C}
98
96
  `);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(`
97
+ ${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=$,c.debug(`[Codex] MCP servers: ${Object.keys($).join(", ")}`));let I=new f({...Object.keys(d).length>0&&{config:d}}).startThread({workingDirectory:s,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),b=r&&typeof r.parse=="function",x={};if(r)try{let E=b?rs(r,{target:"openAi"}):r;x.outputSchema=E,c.debug("Structured output via SDK outputSchema")}catch(E){c.warn(`[Codex] Schema conversion failed, will extract from text: ${E.message}`)}try{let{events:E}=await I.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 O=JSON.stringify(k.arguments),A=O.length>100?`${O.substring(0,100)}...`:O;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"?c.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(M.usage||{})}`):c.debug(`[Codex] Event: ${_} ${JSON.stringify(M).slice(0,300)}`)}if(c.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),_=b?r.parse(M):M;return c.debug("\u2705 [Codex] Structured output validated"),{raw:T,structured:_}}return T||""}catch(E){let P=E.message||String(E);throw c.error(`\u274C [Codex] SDK call failed: ${P}`),P.includes("exited with code")&&(c.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),c.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=j(s);if(!r){c.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,c.debug(`[Codex] MCP: ${a} \u2192 ${n.command} ${(n.args||[]).join(" ")}`)}return o}}});import{execSync as ns,spawn as is}from"node:child_process";import{zodToJsonSchema as as}from"zod-to-json-schema";import{existsSync as Vt,mkdirSync as qt,readFileSync as Qt,rmSync as ls,writeFileSync as eo}from"node:fs";import{join as ne}from"node:path";function cs(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 u=e[l];if(r){n?n=!1:u==="\\"?n=!0:u==='"'&&(r=!1);continue}if(u==='"'){r=!0;continue}if(u==="{"){s===0&&(a=l),s+=1;continue}if(u==="}"){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 us(i){let e=String(i||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return cs(e)}}function ps(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 $e,to=B(()=>{oe();X();se();te();rt();Ne();$e=class extends K{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY))return c.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return ns("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return c.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:u=600*1e3}=t,p=o;(!p||p==="auto")&&(p=G.GEMINI);let f=Rt[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 ue(e),$=r&&typeof r.parse=="function",d=null;if(r){let v;try{let R=$?as(r,{target:"openAi"}):r;v=JSON.stringify(R,null,2)}catch{v="{}"}if(C){y.addSystemInstruction(`Write valid JSON that matches this schema:
98
+ ${v}`,"schema_instruction","append");let R=`zibby-result-${Date.now()}.json`,L=ne(s,".zibby","tmp");d=ne(L,R),qt(L,{recursive:!0}),y.addStructuredOutput(r,d)}else y.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
99
+ ${v}`,"json_instruction","append")}let w=y.build(),I=y.getUserPrompt(),b=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
100
  \u25C6 Model: ${f||"auto"}${E}
103
101
  `);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(`
102
+ ${P.bold("Prompt sent to LLM:")}`),console.log(P.dim("\u2500".repeat(60))),console.log(P.dim(I)),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);c.info(`[Gemini] Enabling MCP servers: ${_.join(", ")}`)}else n&&n.length>0&&c.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),c.debug(`[Gemini] Command: gemini ${M.slice(0,8).join(" ")}... (${M.length} total args)`),c.debug(`[Gemini] User prompt: ${b.userPromptLength} chars, System instructions: ${b.systemInstructionsLength} chars (${b.instructionCount} blocks), Full: ${b.fullPromptLength} chars`),c.debug(`[Gemini] Config home: ${T}`),c.debug(`[Gemini] GEMINI_CLI_HOME env: ${k.GEMINI_CLI_HOME}`);let N="",m=null;try{N=await new Promise((R,L)=>{let D=is("gemini",M,{cwd:s,env:k,stdio:["ignore","pipe","pipe"]}),V="",le="",W=setTimeout(()=>{try{D.kill("SIGTERM")}catch{}},u);D.stdout.on("data",Y=>{V+=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(V.trim());L(new Error(`gemini failed with code ${Y}: ${(le||V).trim()}`))})})}catch(v){m=v}finally{try{ls(T,{recursive:!0,force:!0})}catch{}}let O=ps(N).trim();if(!r){if(m)throw m;return O}if(d){let v=Vt(d);if(c.info(`[Gemini] Result file: ${v?"present":"missing"} at ${d}`),v)try{let R=Qt(d,"utf-8").trim(),L=JSON.parse(R),D=$?r.parse(L):L;return c.info("[Gemini] Structured output recovered from result file"),{raw:O,structured:D}}catch(R){c.warn(`[Gemini] Result file parse/validation failed: ${R.message}`)}else m||c.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let A=null;if(r){let v=new q;v.zodSchema=r,v.processChunk(O),v.flush(),A=v.getResult()}if(c.info(`[Gemini] Raw stdout length: ${N.length} chars`),c.info(`[Gemini] Extracted text length: ${O.length} chars`),c.info(`[Gemini] StreamParser result: ${A?"extracted":"null"}`),A||(O.length<2e3?c.info(`[Gemini] Raw text preview:
103
+ ${O}`):c.info(`[Gemini] Raw text preview (first 1000 chars):
104
+ ${O.slice(0,1e3)}`),A=us(O)),!A)throw m||(c.error("[Gemini] Failed to extract valid JSON from output"),c.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:O,structured:J}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let o={};for(let s of e){let r=j(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");qt(r,{recursive:!0});let n=ne(r,"settings.json"),a={},l=ne(process.env.HOME||"",".gemini","settings.json");if(Vt(l))try{a=JSON.parse(Qt(l,"utf-8"))}catch{a={}}let u={...a,mcpServers:{...a.mcpServers&&typeof a.mcpServers=="object"?a.mcpServers:{},...t||{}}};eo(n,`${JSON.stringify(u,null,2)}
105
+ `,"utf-8");let p=ne(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{eo(p,`${JSON.stringify(u,null,2)}
106
+ `,"utf-8")}catch{}return c.debug(`[Gemini] Created isolated config with ${Object.keys(u.mcpServers||{}).length} MCP servers`),c.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(u.mcpServers||{}),null,2)}`),s}}});var xe,it=B(()=>{xe=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 fe,oo=B(()=>{it();fe=class extends xe{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 Te,at=B(()=>{Te=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 Be(i){return Buffer.byteLength(JSON.stringify(i),"utf8")}function Ue(i,e){let t=String(i||"");if(t.length<=e)return t;let o=Math.max(0,e-28);return`${t.slice(0,o)}
107
+
108
+ [truncated for size budget]`}function lt(i,e=0){if(!i||typeof i!="object"||e>8)return i;if(Array.isArray(i))return i.map(o=>lt(o,e+1));let t={};for(let[o,s]of Object.entries(i))o==="description"||o==="title"||o==="examples"||o==="default"||(t[o]=lt(s,e+1));return t}function fs(i=[]){return i.map(e=>({...e,function:{...e.function,description:Ue(e.function?.description||"",180),parameters:lt(e.function?.parameters||{type:"object",properties:{}})}}))}function so(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 ct(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)?fs(i.tools):i.tools};s.messages.length>0&&s.messages[0]?.role==="system"&&(s.messages[0]={...s.messages[0],content:Ue(s.messages[0].content,o)});let r=!1;for(;Be(s)>t&&s.messages.length>2;)s.messages.splice(1,1),r=!0;if(r&&(s.messages=so(s.messages)),Be(s)>t&&s.messages.length>0&&(s.messages[0]={...s.messages[0],content:Ue(s.messages[0].content,6e3)},r=!0),Be(s)>t){let n=s.messages.find(l=>l.role==="system")||s.messages[0],a=s.messages.slice(-2);s.messages=so([n,...a].filter(Boolean).map((l,u)=>({...l,content:Ue(l.content,u===0?4e3:8e3)}))),r=!0}return{body:s,meta:{bytes:Be(s),trimmed:r,maxBytes:t,messageCount:s.messages.length}}}var ro=B(()=>{});var no,de,io=B(()=>{at();ro();no=i=>Buffer.byteLength(JSON.stringify(i),"utf8"),de=class extends Te{async fetchCompletion(e,t,o={}){let s=no(e),{body:r,meta:n}=ct(e,o.payloadCompaction);o.onBudget?.({streaming:!1,beforeBytes:s,meta:n});let a=this.#e(o),l=`${t.baseUrl}${o.chatCompletionsPath||"/v1/chat/completions"}`,u=await fetch(l,{method:"POST",headers:t.headers,body:JSON.stringify(r),signal:a});if(!u.ok){let p=await u.text();throw u.status===401||u.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${u.status}: ${p}`)}return u.json()}async fetchStreamingCompletion(e,t,o={}){let s={...e,stream:!0},r=no(s),{body:n,meta:a}=ct(s,o.payloadCompaction);o.onBudget?.({streaming:!0,beforeBytes:r,meta:a});let l=this.#e(o),u=`${t.baseUrl}${o.chatCompletionsPath||"/v1/chat/completions"}`,p=await fetch(u,{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(`
109
+ `);S=d.pop();for(let w of d){if(!w.startsWith("data: "))continue;let I=w.slice(6).trim();if(I==="[DONE]")continue;let b;try{b=JSON.parse(I)}catch{continue}let x=b.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 ao=B(()=>{it();oo();at();io()});import{Client as ds}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as ms}from"@modelcontextprotocol/sdk/client/stdio.js";var Je,lo=B(()=>{X();Je=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;c.debug(`[MCP] Starting ${e}: ${o} ${s.join(" ")}`);let n=new ms({command:o,args:s,env:{...process.env,...r}}),a=new ds({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`);c.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(`
110
+ `)||"",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){c.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 gs,readFileSync as hs}from"node:fs";import{join as ys}from"node:path";import{homedir as Ss}from"node:os";function _s(){try{let i=ys(Ss(),".zibby","config.json");return gs(i)?JSON.parse(hs(i,"utf-8")):{}}catch{return{}}}function Fe(i){return String(i||"").replace(/\/v1\/?$/,"")}function ws(i,e){let t=process.env.OPENAI_PROXY_URL;if(t)return Fe(t);if(i==="session")return e.proxyUrl?Fe(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 Fe(o||"https://api.openai.com")}return Fe(t||"")}function ut(){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=ws(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 co=B(()=>{});function Ge(i,e){let t=String(i??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
111
+
112
+ [tool result truncated for size]`}function Es(i,e){if(typeof i=="string")return Ge(i,e);try{return Ge(JSON.stringify(i),e)}catch{return Ge(String(i),e)}}function uo(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 Is(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=uo(o);let s={...i,messages:[t,...o].filter(Boolean)};return delete s.tools,s}async function Os({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 u=Is(i);return typeof n=="function"&&n(i,u),{data:e?await r(u,t,o):await s(u,t,o),fallback:u}}}async function po({body:i,auth:e,options:t,streaming:o,toolContext:s,activeSkills:r,round:n,verbose:a,dependencies:l,config:u={}}){let p=u.maxToolResultChars||3e3,{fetchCompletion:f,fetchStreamingCompletion:g,onFallbackLog:S,hasToolCalls:h,getTextContent:C,parseToolCalls:y,buildAssistantMessage:$,buildToolResultMessage:d,executeTool:w,onToolCallLog:I,injectTools:b}=l;Array.isArray(i?.messages)&&(i.messages=uo(i.messages));let x=await Os({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 I=="function"&&I(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[_]):Es(M[_],p);T.messages.push(d(P[_].id,N))}return typeof t.onToolCall=="function"&&t.onToolCall(null),b(T,r),{done:!1,body:T}}var fo=B(()=>{});function ge(i){!i||typeof i!="object"||(i.type==="object"&&i.properties&&(i.required=Object.keys(i.properties),i.additionalProperties=!1,Object.values(i.properties).forEach(ge)),i.type==="array"&&i.items&&ge(i.items),i.anyOf&&i.anyOf.forEach(ge),i.oneOf&&i.oneOf.forEach(ge),i.allOf&&i.allOf.forEach(ge))}function je(i){return Array.isArray(i)?new Set(i.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function Ts(i){return Array.isArray(i)?i.map(e=>String(e||"").trim()).filter(Boolean):[]}var bs,$s,pt,mo,me,xs,Ae,go=B(()=>{oe();X();se();ao();lo();te();co();fo();bs=G.ASSISTANT,$s=15,pt="get_skill_context";mo={maxBytes:49e3,systemMaxChars:12e3},me=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",xs=i=>Buffer.byteLength(JSON.stringify(i),"utf8");Ae=class extends K{#e;#t;#o=new Je;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new fe,this.#t=e.completionProvider||new de):(this.#e=e||new fe,this.#t=new de)}canHandle(e){return ut().ok}async invoke(e,t={}){let o=t.model&&t.model!=="auto"?t.model:bs,s=ut();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=me();if(a?await this.#m(r,o,n,s.tokenPreview||"none"):c.debug(`[Assistant] ${n} | model: ${o} | messages: ${r.length}`),t.schema)return this.#c(o,r,s,t);let l=t.activeSkills||[],u=this.#p(t),p=this.#f(l,u),f=this.#d(p),g=this.#u(t),S={...t,payloadCompaction:g},h={activeSkills:p,options:S,executionRegistry:f,capabilityPolicy:u},C=!!t.stream,y={model:o,messages:[...r],stream:!1};this.#r(y,p,u);for(let $=0;$<$s;$++){if(t.signal?.aborted)throw new Error("Aborted");let d=await po({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,I)=>{me()&&console.log(`413 fallback: messages ${w.messages.length} -> ${I.messages.length}, bytes=${xs(I)}`)},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,I)=>this.#e.buildToolResultMessage(w,I),executeTool:(w,I)=>this.#a(w,I),onToolCallLog:async w=>{let I=(await import("chalk")).default;console.log(I.dim(` ${w.map(b=>`${b.name}(${JSON.stringify(b.args).slice(0,80)})`).join(", ")}`))},injectTools:(w,I)=>this.#r(w,I,u)},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=j(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(pt,t)&&o.push({name:pt,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===pt){let u=String(e.args?.skillId||"").trim();if(!u)return JSON.stringify({error:"skillId is required"});if(!o.includes(u))return JSON.stringify({error:`Skill "${u}" is not active`,activeSkills:o});let p=j(u);if(!p)return JSON.stringify({error:`Skill "${u}" not found`});let f=typeof p.promptFragment=="function"?p.promptFragment():p.promptFragment||"",g=(p.tools||[]).map(h=>h.name),S=JSON.stringify({skillId:u,description:p.description||"",toolNames:g,promptFragment:f||""});return me()&&(console.log(`
113
+ \u{1F4D6} get_skill_context("${u}") \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
114
+ `)),S}let a=r?.get(e.name)||null;if(!a)return`Unknown tool: ${e.name}`;let l=j(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(u){return`Error in ${e.name}: ${u.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 u=await this.#o.callTool(l.serverName,e.name,e.args);return u.text||(u.isError?"Tool call failed":"Done")}catch(u){return`MCP error (${l.serverName}): ${u.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})=>{me()&&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})=>{me()&&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,ge(a);let l={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:a,strict:!0}}},u=await this.#n(l,o,s),p=this.#e.getTextContent(u),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||mo.maxBytes),systemMaxChars:Number(t.systemMaxChars||mo.systemMaxChars)}}#p(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:je(t.allowTools||e.allowTools),denyTools:je(t.denyTools||e.denyTools),denyPrefixes:Ts(t.denyPrefixes||e.denyToolPrefixes),includeSkills:je(t.includeSkills||e.includeSkills),excludeSkills:je(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=j(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&&me()){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(`
117
115
  \u25C6 Model: ${t} | proxy: ${o} | token: ${s||"none"}
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+=`
116
+ `);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",u=a.content?.length>200?`${a.content.slice(0,200)}...`:a.content||"";console.log(r.dim(`[${l}] ${u}`))}console.log(r.dim("\u2500".repeat(60)))}}});var ft={};Pe(ft,{AgentStrategy:()=>K,AssistantStrategy:()=>Ae,ClaudeAgentStrategy:()=>Oe,CodexAgentStrategy:()=>be,CursorAgentStrategy:()=>Ie,GeminiAgentStrategy:()=>$e,getAgentStrategy:()=>yo,invokeAgent:()=>As});function yo(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");c.debug(`Agent selection: requested=${o}`);let s=ho.find(r=>r.getName()===o);if(!s)throw new Error(`Unknown agent '${o}'. Available: ${ho.map(r=>r.getName()).join(", ")}`);if(c.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 c.debug(`Using agent: ${s.getName()}`),s}async function As(i,e={},t={}){try{await import("@zibby/skills")}catch{}let o=yo(e),s=e.state?.config||t.config||{},r=s.models||{},n=t.nodeName&&r[t.nodeName]||null,a=r.default||null,l=o.name,u=s.agent?.[l]?.model||null,p=n||a||u||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(),ot)),y=g.map($=>{let d=C($)?.promptFragment;return typeof d=="function"?d():d}).filter(Boolean);y.length>0&&(S+=`
119
117
 
120
118
  ${y.join(`
121
119
 
@@ -126,20 +124,16 @@ ${y.join(`
126
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
127
125
 
128
126
  ${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}
127
+ `),c.debug(`Prompt length: ${S.length} chars`),process.env.STAGE!=="prod"&&c.debug(`Full prompt:
128
+ ${S}`),o.invoke(S,f)}var ho,dt=B(()=>{Ht();Zt();Xt();to();go();X();oe();ho=[new Ae,new Ie,new Oe,new be,new $e]});var wo={};Pe(wo,{ConditionalNode:()=>ve,Node:()=>ie});import{writeFileSync as mt,readFileSync as So,existsSync as _o,mkdirSync as vs}from"node:fs";import{join as gt,dirname as Cs}from"node:path";import Ke from"chalk";var ie,ve,ht=B(()=>{xt();X();ce();ye();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 $t(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"){c.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?(c.debug("Validating return value against outputSchema..."),{success:!0,output:this.outputSchema.parse(f),raw:null}):{success:!0,output:f,raw:null}}catch(f){return c.error(`\u274C Node '${this.name}' execution failed: ${f.message}`),f.name==="ZodError"&&c.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}
131
129
 
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(`
135
-
136
- ---
137
-
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(`
130
+ ${r}`);let a=o(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let f=gt(u,H);if(_o(f)){let S=JSON.parse(So(f,"utf-8"));S.currentNode=this.name,mt(f,JSON.stringify(S,null,2),"utf-8")}let g=gt(u,"..",H);if(_o(g))try{let S=JSON.parse(So(g,"utf-8"));S.currentNode=this.name,mt(g,JSON.stringify(S,null,2),"utf-8")}catch{}}}catch(f){c.debug(`Could not update session info: ${f.message}`)}let p=null;for(let f=0;f<=this.retries;f++)try{c.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:u,config:S,nodeName:this.name,timeout:this.config?.timeout||3e5},y=e?._coreInvokeAgent;y||(y=(await Promise.resolve().then(()=>(dt(),ft))).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),u)try{let I=gt(u,this.name,"raw_stream_output.txt");vs(Cs(I),{recursive:!0}),mt(I,typeof d=="string"?d:JSON.stringify(d),"utf-8")}catch(I){c.debug(`Could not save raw output: ${I.message}`)}if(this.isZodSchema&&w){console.log(`
131
+ \u{1F50D} ${Ke.cyan("Validated output:")} ${Ke.white(JSON.stringify(w,null,2))}`);let I=w;if(typeof this.onComplete=="function")try{I=await this.onComplete(o(),w)}catch(b){c.warn(`onComplete hook failed: ${b.message}`)}return{success:!0,output:I,raw:d}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:d}),raw:d}}catch(I){throw new Error(`onComplete failed: ${I.message}`,{cause:I})}if(this.parser){let I=this.parser.parse(d);return console.log(`
132
+ \u{1F50D} ${Ke.cyan("Parsed output:")} ${Ke.white(JSON.stringify(I,null,2))}`),U.step("Output parsed"),{success:!0,output:I,raw:d}}return{success:!0,output:d,raw:d}}catch(g){p=g,f<this.retries&&c.info(`Node '${this.name}' failed, retrying (${f+1}/${this.retries})...`)}return{success:!1,error:p.message,raw:null}}},ve=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 Fs}from"node:child_process";import{mkdirSync as $o,existsSync as Gs,writeFileSync as js}from"node:fs";import{join as St}from"node:path";import{ContextLoader as ke}from"@zibby/workflow";Ne();import{exec as To}from"node:child_process";import{promisify as Ao}from"node:util";import{existsSync as vo}from"node:fs";import{join as We}from"node:path";import{homedir as ze}from"node:os";var Et=Ao(To);async function It(){try{return await Et("cursor-agent --version"),"cursor-agent"}catch{let e=[We(ze(),".local","bin","cursor-agent"),We(ze(),".cursor","bin","cursor-agent"),We(ze(),".cursor-agent","bin","cursor-agent")];for(let t of e)if(vo(t))try{return await Et(`"${t}" --version`),t}catch{}return null}}ye();Ze();ht();ye();ce();import{mkdirSync as Oo,existsSync as yt,writeFileSync as Eo,unlinkSync as Ps}from"node:fs";import{join as ae,resolve as bo}from"node:path";import{config as ks}from"dotenv";import{zodToJsonSchema as Io}from"zod-to-json-schema";import Ns from"handlebars";function Rs({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 u=(new Error("session trace").stack||"").split(`
139
133
  `).slice(2,14).join(`
140
134
  `);console.log(`[zibby:session] stack (${i}):
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(`
135
+ ${u}`)}}function Ms(){return process.env.ZIBBY_RUN_SOURCE==="studio"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function Ls(){if(process.env.ZIBBY_RUN_SOURCE!=="studio")return;let i=process.env.ZIBBY_SESSION_PATH;if(!(i==null||String(i).trim()===""))try{return bo(String(i).trim())}catch{return String(i).trim()}}function Ds(){Ms()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Bs({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 Us(i={}){let e=Ot.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 Js({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 u=bo(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,n="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),r==null&&(r=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,n="ZIBBY_SESSION_ID";else{let f=e.sessionId!=null?String(e.sessionId).trim():"";f&&f!=="last"?(a=f,n="config.sessionId"):(a=Us(e),n="generated")}r=r??Date.now();let p=e.paths?.output||Q;s=ae(i,p,Re,a)}let l=!yt(s);return l&&Oo(s,{recursive:!0}),(l||n!=="initialState.sessionPath")&&Rs({traceFrom:o,sessionId:a,sessionPath:s,idSource:n,mkdirFresh:l}),Bs({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:r}}var Ye=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 ve({...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],u=n;n=()=>l(t,u,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,u={};l&&typeof n.execute=="function"&&(u.customCode=n.execute.toString());let p=this.nodePrompts.get(r);if(p&&(u.prompt=p),typeof n.customExecute=="function"&&(u.executeCode=n.customExecute.toString()),n.outputSchema)try{if(typeof n.outputSchema._def<"u"){let S=Io(n.outputSchema,{target:"openApi3"}),h=this._flattenJsonSchemaToVariables(S);u.outputSchema={jsonSchema:S,variables:h}}else u.outputSchema={schema:n.outputSchema}}catch(g){console.warn(`Failed to convert schema for ${r}:`,g.message)}let f=(this.resolvedToolsMap||{})[r];f?.toolIds&&(u.tools=f.toolIds),Object.keys(u).length>0&&(t[r]=u)}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),u=n.labels||{};for(let p of l){let f={source:r,target:p,data:{conditionalCode:a}};u[p]&&(f.label=u[p]),o.push(f)}}let s=null;if(this.stateSchema)try{s=Io(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,u=!r.includes(n);if(o.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(n),optional:u}),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(u=>u?.passed===!0).length;if(r.some(u=>u?.passed!==void 0)){let u=n-a;o.push(`${s}: ${a}/${n} passed${u?`, ${u} 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();ks({path:ae(o,".env")});let s=t.config||{};if(!s||Object.keys(s).length===0)try{let b=ae(o,".zibby.config.js");yt(b)&&(s=(await import(b)).default||{})}catch{}process.env.EXECUTION_ID&&!s.agent?.strictMode&&(s.agent={...s.agent,strictMode:!0});let r=t.agentType;if(!r){let b=s?.agent;b?.provider?r=b.provider:b?.gemini?r="gemini":b?.claude?r="claude":b?.cursor?r="cursor":b?.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 b=this.stateSchema.safeParse(t);if(!b.success){let x=b.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=Ls(),l=t.sessionPath||a;l||Ds();let{sessionPath:u,sessionTimestamp:p,sessionId:f}=Js({cwd:o,config:s,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:t.sessionTimestamp}});U.step(`Session ${f}`);let g=await ke.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 He({...t,config:s,agentType:r,outputPath:S,sessionPath:u,sessionTimestamp:p,context:g,resolvedTools:this.resolvedToolsMap||{}}),C=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(te(),ot)),$=new Set;for(let[,b]of this.nodes)for(let x of b.config?.skills||[])$.add(x);for(let b of $){let x=y(b);if(typeof x?.middleware=="function")try{let E=await x.middleware();typeof E=="function"&&C.set(b,E)}catch{}}let d=this.entryPoint,w=[];for(;d&&d!=="END";){let b=ae(u,Me);if(yt(b)){console.warn(`
136
+ \u{1F6D1} Studio stop requested \u2014 ending workflow.`);try{Ps(b)}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:u,sessionTimestamp:p,currentNode:d,createdAt:new Date().toISOString(),config:h.get("config")}),P=ae(u,H);Eo(P,E,"utf-8");let T=h.get("config")?.paths?.output||Q,M=ae(o,T,H);Oo(ae(o,T),{recursive:!0});try{Eo(M,E,"utf-8")}catch{}let _=t.onPipelineProgress;if(typeof _=="function")try{_({cwd:o,sessionPath:u,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(),O=this.nodePrompts.get(d);if(!this._invokeAgent){let R=await Promise.resolve().then(()=>(dt(),ft));this._invokeAgent=R.invokeAgent}let A=this._invokeAgent,v={state:h,invokeAgent:async(R={},L={})=>{let D=L.prompt||"";if(O)try{D=Ns.compile(O,{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 V={state:h.getAll(),images:L.images||[]},le={model:L.model||h.get("model"),workspace:h.get("workspace"),schema:L.schema,...L};return A(D,V,le)},_coreInvokeAgent:A,agent:e,nodeId:d,promptTemplate:O,getPromptTemplate:()=>O,...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 V=Date.now()-m;if(w.push({node:d,success:D.success,duration:V,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 he=x.config?.retries||0,wt=`${d}_retries`,Ce=h.getAll()[wt]||0;if(Ce<he){U.stepInfo(`Retrying (attempt ${Ce+1}/${he})`),h.update({[wt]:Ce+1,[`${d}_raw`]:D.raw});continue}throw U.nodeFailed(d,D.error,{duration:V}),new Error(`Node '${d}' failed after ${Ce} attempts: ${D.error}`)}h.update({[d]:D.output});let le=this._summarizeNodeOutput(d,D.output);U.nodeComplete(d,{duration:V,details:le});let W=this.edges.get(d);if(!W)d="END";else if(W.conditional){let Y=h.getAll(),he=W.routes(Y);U.route(d,he),d=he}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 I={success:!0,state:h.getAll(),executionLog:w};return e&&typeof e.onComplete=="function"&&await e.onComplete(I),I}};var _t=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 q.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(`
143
137
  \u{1F4DD} Prompt:
144
138
  ${n}
145
139
  `);let a=await this.executePrompt(n,t.cwd,3e5,r);console.log(`
@@ -148,11 +142,11 @@ ${a}
148
142
  `);let l=null;if(s)try{if(l=i.extractJsonFromStream(a),!l)throw new Error("No valid result JSON found in output");console.log(`
149
143
  \u2705 Parsed Output:
150
144
  ${JSON.stringify(l,null,2)}
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(`
145
+ `)}catch(u){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${u.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 It();a&&(n=a)}return new Promise((a,l)=>{let u="",p=this.buildArgs(e,r);s&&p.push("--model",s);let f={...process.env},g=Fs(n,p,{cwd:t,env:f,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),S=setTimeout(()=>{console.log(`
146
+ \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(u.length>h)h=u.length,C=Date.now();else{let I=Date.now()-C;I>1e4&&console.log(`\u23F3 AI agent is thinking... (${Math.floor(I/1e3)}s, ${u.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(`
153
147
 
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(`
148
+ \u{1F6D1} Interrupted by user (Ctrl+C)`),$(),l(new Error("Interrupted by user"))};process.on("SIGINT",d);let w=new q;g.stdout.on("data",I=>{let b=I.toString();u+=b;let x=w.processChunk(b);x&&(process.stdout.write(x,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),C=Date.now(),h+=x.length)}),g.on("close",I=>{process.off("SIGINT",d),clearTimeout(S),clearInterval(y);let b=w.flush();b&&process.stdout.write(b),u=w.getRawText();let x=w.getResult();I===0?a({raw:u,extracted:x}):l(new Error(`Agent exited with code ${I}`))}),g.on("error",I=>{process.off("SIGINT",d),clearTimeout(S),clearInterval(y),l(new Error(`Failed to spawn agent: ${I.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,I=w?`${w}_${d}`:d;a=a||Date.now();let b=l.paths?.output||Q;n=St(r,b,Re,I),Gs(n)||$o(n,{recursive:!0})}let u=l.paths?.output||Q,p=St(r,u,H);$o(St(r,u),{recursive:!0}),js(p,JSON.stringify({sessionPath:n,sessionTimestamp:a||n.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
155
149
  ${"=".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)}
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(`
150
+ `);let f=await ke.loadContext(o.specPath||"",r,o.contextConfig||{}),{Node:g}=await Promise.resolve().then(()=>(ht(),wo)),{WorkflowState:S}=await Promise.resolve().then(()=>(Ze(),bt)),h=new S({...o,sessionPath:n,sessionTimestamp:a,context:f}),y=await new g(s).execute(this,h);return console.log(`
157
151
  ${"=".repeat(80)}`),console.log(`\u2705 Node ${e} completed`),console.log(`${"=".repeat(80)}
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};
152
+ `),{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 Ai(i,e={}){let t=new _t(e);return t.buildGraph=function(){let o=new Ye;return i(o),o},e.onComplete&&(t.onComplete=e.onComplete),t}export{_t as WorkflowAgent,Ai as workflow};