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