@zibby/core 0.1.38 → 0.1.40

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