@zibby/core 0.1.41 → 0.1.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
- var U=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}};import M from"chalk";var w={debug:0,info:1,warn:2,error:3,silent:4},G=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(),l=`${this._getPrefix(e)} ${t}`;return Object.keys(s).length>0&&(l+=M.dim(` ${JSON.stringify(s)}`)),l}_getPrefix(e){return{debug:M.gray("[DEBUG]"),info:M.cyan("[INFO]"),warn:M.yellow("[WARN]"),error:M.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)}},O=new G;var q={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"};var Ee={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var R=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 $=class extends R{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 I=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 D(n){return Buffer.byteLength(JSON.stringify(n),"utf8")}function j(n,e){let t=String(n||"");if(t.length<=e)return t;let s=Math.max(0,e-28);return`${t.slice(0,s)}
1
+ var U=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}};import R from"chalk";var w={debug:0,info:1,warn:2,error:3,silent:4},G=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(),l=`${this._getPrefix(e)} ${t}`;return Object.keys(s).length>0&&(l+=R.dim(` ${JSON.stringify(s)}`)),l}_getPrefix(e){return{debug:R.gray("[DEBUG]"),info:R.cyan("[INFO]"),warn:R.yellow("[WARN]"),error:R.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)}},O=new G;var q={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"};var Ae={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var I=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 $=class extends I{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 L=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 D(n){return Buffer.byteLength(JSON.stringify(n),"utf8")}function j(n,e){let t=String(n||"");if(t.length<=e)return t;let s=Math.max(0,e-28);return`${t.slice(0,s)}
2
2
 
3
- [truncated for size budget]`}function X(n,e=0){if(!n||typeof n!="object"||e>8)return n;if(Array.isArray(n))return n.map(s=>X(s,e+1));let t={};for(let[s,o]of Object.entries(n))s==="description"||s==="title"||s==="examples"||s==="default"||(t[s]=X(o,e+1));return t}function re(n=[]){return n.map(e=>({...e,function:{...e.function,description:j(e.function?.description||"",180),parameters:X(e.function?.parameters||{type:"object",properties:{}})}}))}function W(n){let e=new Set;for(let o of n)if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)e.add(r.id);let t=n.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(a=>s.has(a.id)))return o;let{tool_calls:l,...i}=o;return{...i,content:i.content||""}})}function H(n,e={}){let t=e.maxBytes||49e3,s=e.systemMaxChars||12e3,o={...n,messages:Array.isArray(n.messages)?[...n.messages]:[],tools:Array.isArray(n.tools)?re(n.tools):n.tools};o.messages.length>0&&o.messages[0]?.role==="system"&&(o.messages[0]={...o.messages[0],content:j(o.messages[0].content,s)});let r=!1;for(;D(o)>t&&o.messages.length>2;)o.messages.splice(1,1),r=!0;if(r&&(o.messages=W(o.messages)),D(o)>t&&o.messages.length>0&&(o.messages[0]={...o.messages[0],content:j(o.messages[0].content,6e3)},r=!0),D(o)>t){let l=o.messages.find(a=>a.role==="system")||o.messages[0],i=o.messages.slice(-2);o.messages=W([l,...i].filter(Boolean).map((a,c)=>({...a,content:j(a.content,c===0?4e3:8e3)}))),r=!0}return{body:o,meta:{bytes:D(o),trimmed:r,maxBytes:t,messageCount:o.messages.length}}}var Q=n=>Buffer.byteLength(JSON.stringify(n),"utf8"),P=class extends I{async fetchCompletion(e,t,s={}){let o=Q(e),{body:r,meta:l}=H(e,s.payloadCompaction);s.onBudget?.({streaming:!1,beforeBytes:o,meta:l});let i=this.#e(s),a=`${t.baseUrl}${s.chatCompletionsPath||"/v1/chat/completions"}`,c=await fetch(a,{method:"POST",headers:t.headers,body:JSON.stringify(r),signal:i});if(!c.ok){let u=await c.text();throw c.status===401||c.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${c.status}: ${u}`)}return c.json()}async fetchStreamingCompletion(e,t,s={}){let o={...e,stream:!0},r=Q(o),{body:l,meta:i}=H(o,s.payloadCompaction);s.onBudget?.({streaming:!0,beforeBytes:r,meta:i});let a=this.#e(s),c=`${t.baseUrl}${s.chatCompletionsPath||"/v1/chat/completions"}`,u=await fetch(c,{method:"POST",headers:t.headers,body:JSON.stringify(l),signal:a});if(!u.ok){let d=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}: ${d}`)}let p=u.body.getReader(),x=new TextDecoder,S="",A="",E=new Map;for(;;){let{done:d,value:g}=await p.read();if(d)break;S+=x.decode(g,{stream:!0});let h=S.split(`
3
+ [truncated for size budget]`}function X(n,e=0){if(!n||typeof n!="object"||e>8)return n;if(Array.isArray(n))return n.map(s=>X(s,e+1));let t={};for(let[s,o]of Object.entries(n))s==="description"||s==="title"||s==="examples"||s==="default"||(t[s]=X(o,e+1));return t}function re(n=[]){return n.map(e=>({...e,function:{...e.function,description:j(e.function?.description||"",180),parameters:X(e.function?.parameters||{type:"object",properties:{}})}}))}function W(n){let e=new Set;for(let o of n)if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)e.add(r.id);let t=n.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(a=>s.has(a.id)))return o;let{tool_calls:l,...i}=o;return{...i,content:i.content||""}})}function H(n,e={}){let t=e.maxBytes||49e3,s=e.systemMaxChars||12e3,o={...n,messages:Array.isArray(n.messages)?[...n.messages]:[],tools:Array.isArray(n.tools)?re(n.tools):n.tools};o.messages.length>0&&o.messages[0]?.role==="system"&&(o.messages[0]={...o.messages[0],content:j(o.messages[0].content,s)});let r=!1;for(;D(o)>t&&o.messages.length>2;)o.messages.splice(1,1),r=!0;if(r&&(o.messages=W(o.messages)),D(o)>t&&o.messages.length>0&&(o.messages[0]={...o.messages[0],content:j(o.messages[0].content,6e3)},r=!0),D(o)>t){let l=o.messages.find(a=>a.role==="system")||o.messages[0],i=o.messages.slice(-2);o.messages=W([l,...i].filter(Boolean).map((a,c)=>({...a,content:j(a.content,c===0?4e3:8e3)}))),r=!0}return{body:o,meta:{bytes:D(o),trimmed:r,maxBytes:t,messageCount:o.messages.length}}}var Q=n=>Buffer.byteLength(JSON.stringify(n),"utf8"),P=class extends L{async fetchCompletion(e,t,s={}){let o=Q(e),{body:r,meta:l}=H(e,s.payloadCompaction);s.onBudget?.({streaming:!1,beforeBytes:o,meta:l});let i=this.#e(s),a=`${t.baseUrl}${s.chatCompletionsPath||"/v1/chat/completions"}`,c=await fetch(a,{method:"POST",headers:t.headers,body:JSON.stringify(r),signal:i});if(!c.ok){let u=await c.text();throw c.status===401||c.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${c.status}: ${u}`)}return c.json()}async fetchStreamingCompletion(e,t,s={}){let o={...e,stream:!0},r=Q(o),{body:l,meta:i}=H(o,s.payloadCompaction);s.onBudget?.({streaming:!0,beforeBytes:r,meta:i});let a=this.#e(s),c=`${t.baseUrl}${s.chatCompletionsPath||"/v1/chat/completions"}`,u=await fetch(c,{method:"POST",headers:t.headers,body:JSON.stringify(l),signal:a});if(!u.ok){let d=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}: ${d}`)}let p=u.body.getReader(),x=new TextDecoder,S="",A="",E=new Map;for(;;){let{done:d,value:g}=await p.read();if(d)break;S+=x.decode(g,{stream:!0});let h=S.split(`
4
4
  `);S=h.pop();for(let f of h){if(!f.startsWith("data: "))continue;let m=f.slice(6).trim();if(m==="[DONE]")continue;let C;try{C=JSON.parse(m)}catch{continue}let T=C.choices?.[0]?.delta;if(T&&(T.content&&(A+=T.content,s.onToken&&s.onToken(T.content)),T.tool_calls))for(let y of T.tool_calls){let b=y.index??0;E.has(b)||E.set(b,{id:"",name:"",args:""});let k=E.get(b);y.id&&(k.id=y.id),y.function?.name&&(k.name=y.function.name),y.function?.arguments!=null&&(k.args+=y.function.arguments)}}}if(E.size>0){let d=[...E.entries()].sort(([g],[h])=>g-h).map(([,g])=>({id:g.id,type:"function",function:{name:g.name,arguments:g.args}}));return{choices:[{message:{role:"assistant",content:A||null,tool_calls:d}}]}}return{choices:[{message:{role:"assistant",content:A}}]}}#e(e={}){let t=[e.signal,e.timeout?AbortSignal.timeout(e.timeout):null].filter(Boolean);return t.length>1?AbortSignal.any(t):t[0]||void 0}};import{Client as ie}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as le}from"@modelcontextprotocol/sdk/client/stdio.js";var z=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;O.debug(`[MCP] Starting ${e}: ${s} ${o.join(" ")}`);let l=new le({command:s,args:o,env:{...process.env,...r}}),i=new ie({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await i.connect(l);let a={client:i,transport:l,serverConfig:t};return this.#e.set(e,a),a}async callTool(e,t,s={}){let o=this.#e.get(e);if(!o)throw new Error(`MCP server "${e}" not running`);O.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(i=>i.type==="text").map(i=>i.text).join(`
5
- `)||"",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){O.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)))}};var ae=new Map;function L(n){return ae.get(n)||null}import{existsSync as ce,readFileSync as ue}from"node:fs";import{join as fe}from"node:path";import{homedir as me}from"node:os";function de(){try{let n=fe(me(),".zibby","config.json");return ce(n)?JSON.parse(ue(n,"utf-8")):{}}catch{return{}}}function F(n){return String(n||"").replace(/\/v1\/?$/,"")}function ge(n,e){let t=process.env.OPENAI_PROXY_URL;if(t)return F(t);if(n==="session")return e.proxyUrl?F(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(n==="byok"){let s=process.env.OPENAI_BASE_URL;return F(s||"https://api.openai.com")}return F(t||"")}function V(){let n=de(),e=process.env.ZIBBY_USER_TOKEN||n.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,l="session";s==="byok"||s==="local"||s==="session"?l=s:e?l="session":t?l="byok":r&&o&&(l="local");let i=ge(l,n),a={"Content-Type":"application/json"};if(l==="session"){if(!e)return{ok:!1,mode:l,reason:"missing_session_token"};a.Authorization=`Bearer ${e}`}else if(l==="byok"){if(!t)return{ok:!1,mode:l,reason:"missing_openai_api_key"};a.Authorization=`Bearer ${t}`}else if(l==="local"){if(!i)return{ok:!1,mode:l,reason:"missing_openai_proxy_url"};!o&&t&&(a.Authorization=`Bearer ${t}`)}return i?{ok:!0,mode:l,baseUrl:i,headers:a,tokenPreview:a.Authorization?`***${a.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:l,reason:"missing_base_url"}}function J(n,e){let t=String(n??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
5
+ `)||"",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){O.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{registerSkill as Ge,getSkill as M,hasSkill as Xe,getAllSkills as He,listSkillIds as Ve}from"@zibby/workflow";import{existsSync as ae,readFileSync as ce}from"node:fs";import{join as ue}from"node:path";import{homedir as fe}from"node:os";function me(){try{let n=ue(fe(),".zibby","config.json");return ae(n)?JSON.parse(ce(n,"utf-8")):{}}catch{return{}}}function F(n){return String(n||"").replace(/\/v1\/?$/,"")}function de(n,e){let t=process.env.OPENAI_PROXY_URL;if(t)return F(t);if(n==="session")return e.proxyUrl?F(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(n==="byok"){let s=process.env.OPENAI_BASE_URL;return F(s||"https://api.openai.com")}return F(t||"")}function V(){let n=me(),e=process.env.ZIBBY_USER_TOKEN||n.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,l="session";s==="byok"||s==="local"||s==="session"?l=s:e?l="session":t?l="byok":r&&o&&(l="local");let i=de(l,n),a={"Content-Type":"application/json"};if(l==="session"){if(!e)return{ok:!1,mode:l,reason:"missing_session_token"};a.Authorization=`Bearer ${e}`}else if(l==="byok"){if(!t)return{ok:!1,mode:l,reason:"missing_openai_api_key"};a.Authorization=`Bearer ${t}`}else if(l==="local"){if(!i)return{ok:!1,mode:l,reason:"missing_openai_proxy_url"};!o&&t&&(a.Authorization=`Bearer ${t}`)}return i?{ok:!0,mode:l,baseUrl:i,headers:a,tokenPreview:a.Authorization?`***${a.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:l,reason:"missing_base_url"}}function J(n,e){let t=String(n??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
6
6
 
7
- [tool result truncated for size]`}function pe(n,e){if(typeof n=="string")return J(n,e);try{return J(JSON.stringify(n),e)}catch{return J(String(n),e)}}function ee(n){let e=new Set;for(let o of n)if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)e.add(r.id);let t=n.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(a=>s.has(a.id)))return o;let{tool_calls:l,...i}=o;return{...i,content:i.content||""}})}function he(n){let e=Array.isArray(n?.messages)?n.messages:[],t=e.find(r=>r.role==="system"),s=e.slice(-4).map(r=>({...r,content:J(r.content,r.role==="tool"?1200:2500)}));s=ee(s);let o={...n,messages:[t,...s].filter(Boolean)};return delete o.tools,o}async function ye({body:n,streaming:e,auth:t,options:s,fetchCompletion:o,fetchStreamingCompletion:r,onFallbackLog:l}){try{return e?await r(n,t,s):await o(n,t,s)}catch(i){let a=String(i?.message||i||"");if(!/proxy error 413|payload too large/i.test(a))throw i;let c=he(n);return typeof l=="function"&&l(n,c),{data:e?await r(c,t,s):await o(c,t,s),fallback:c}}}async function te({body:n,auth:e,options:t,streaming:s,toolContext:o,activeSkills:r,round:l,verbose:i,dependencies:a,config:c={}}){let u=c.maxToolResultChars||3e3,{fetchCompletion:p,fetchStreamingCompletion:x,onFallbackLog:S,hasToolCalls:A,getTextContent:E,parseToolCalls:d,buildAssistantMessage:g,buildToolResultMessage:h,executeTool:f,onToolCallLog:m,injectTools:C}=a;Array.isArray(n?.messages)&&(n.messages=ee(n.messages));let T=await ye({body:n,streaming:s,auth:e,options:t,fetchCompletion:p,fetchStreamingCompletion:x,onFallbackLog:S}),y=T?.data||T;if(!A(y))return{done:!0,text:E(y),body:T?.fallback||n};let b=d(y),k=T?.fallback||n;k.messages.push(g(y)),i&&typeof m=="function"&&m(b);let N=await Promise.all(b.map((_,K)=>(typeof t.onToolCall=="function"&&t.onToolCall(_.name,_.args,{round:l,index:K,total:b.length}),f(_,o))));for(let _=0;_<b.length;_++){let ne=b[_].name==="get_skill_context"?typeof N[_]=="string"?N[_]:JSON.stringify(N[_]):pe(N[_],u);k.messages.push(h(b[_].id,ne))}return typeof t.onToolCall=="function"&&t.onToolCall(null),C(k,r),{done:!1,body:k}}var _e=q.ASSISTANT,Se=15,Z="get_skill_context";function B(n){!n||typeof n!="object"||(n.type==="object"&&n.properties&&(n.required=Object.keys(n.properties),n.additionalProperties=!1,Object.values(n.properties).forEach(B)),n.type==="array"&&n.items&&B(n.items),n.anyOf&&n.anyOf.forEach(B),n.oneOf&&n.oneOf.forEach(B),n.allOf&&n.allOf.forEach(B))}var oe={maxBytes:49e3,systemMaxChars:12e3},v=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Te=n=>Buffer.byteLength(JSON.stringify(n),"utf8");function Y(n){return Array.isArray(n)?new Set(n.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function xe(n){return Array.isArray(n)?n.map(e=>String(e||"").trim()).filter(Boolean):[]}var se=class extends U{#e;#t;#o=new z;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new $,this.#t=e.completionProvider||new P):(this.#e=e||new $,this.#t=new P)}canHandle(e){return V().ok}async invoke(e,t={}){let s=t.model&&t.model!=="auto"?t.model:_e,o=V();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}],l=o.baseUrl,i=v();if(i?await this.#g(r,s,l,o.tokenPreview||"none"):O.debug(`[Assistant] ${l} | model: ${s} | messages: ${r.length}`),t.schema)return this.#c(s,r,o,t);let a=t.activeSkills||[],c=this.#f(t),u=this.#m(a,c),p=this.#d(u),x=this.#u(t),S={...t,payloadCompaction:x},A={activeSkills:u,options:S,executionRegistry:p,capabilityPolicy:c},E=!!t.stream,d={model:s,messages:[...r],stream:!1};this.#n(d,u,c);for(let g=0;g<Se;g++){if(t.signal?.aborted)throw new Error("Aborted");let h=await te({body:d,auth:o,options:S,streaming:E,toolContext:A,activeSkills:u,round:g,verbose:i,dependencies:{fetchCompletion:this.#r.bind(this),fetchStreamingCompletion:this.#a.bind(this),onFallbackLog:(f,m)=>{v()&&console.log(`413 fallback: messages ${f.messages.length} -> ${m.messages.length}, bytes=${Te(m)}`)},hasToolCalls:f=>this.#e.hasToolCalls(f),getTextContent:f=>this.#e.getTextContent(f),parseToolCalls:f=>this.#e.parseToolCalls(f),buildAssistantMessage:f=>this.#e.buildAssistantMessage(f),buildToolResultMessage:(f,m)=>this.#e.buildToolResultMessage(f,m),executeTool:(f,m)=>this.#l(f,m),onToolCallLog:async f=>{let m=(await import("chalk")).default;console.log(m.dim(` ${f.map(C=>`${C.name}(${JSON.stringify(C.args).slice(0,80)})`).join(", ")}`))},injectTools:(f,m)=>this.#n(f,m,c)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(h.done)return h.text;d.messages=h.body.messages,h.body.tools?d.tools=h.body.tools:delete d.tools}return"I hit my tool-calling limit for this turn. Please try again."}async cleanup(){await this.#o.stopAll()}#n(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 l=L(r);if(l?.tools?.length)for(let i of l.tools)this.#s(i.name,t)&&(o.has(i.name)||(o.add(i.name),s.push({name:i.name,description:i.description,parameters:i.parameters||i.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#s(Z,t)&&s.push({name:Z,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),s}async#l(e,t){let{activeSkills:s,options:o,executionRegistry:r,capabilityPolicy:l}=t;if(!this.#s(e.name,l))return`Tool "${e.name}" blocked by policy`;if(e.name===Z){let c=String(e.args?.skillId||"").trim();if(!c)return JSON.stringify({error:"skillId is required"});if(!s.includes(c))return JSON.stringify({error:`Skill "${c}" is not active`,activeSkills:s});let u=L(c);if(!u)return JSON.stringify({error:`Skill "${c}" not found`});let p=typeof u.promptFragment=="function"?u.promptFragment():u.promptFragment||"",x=(u.tools||[]).map(A=>A.name),S=JSON.stringify({skillId:c,description:u.description||"",toolNames:x,promptFragment:p||""});return v()&&(console.log(`
7
+ [tool result truncated for size]`}function ge(n,e){if(typeof n=="string")return J(n,e);try{return J(JSON.stringify(n),e)}catch{return J(String(n),e)}}function ee(n){let e=new Set;for(let o of n)if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)e.add(r.id);let t=n.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(a=>s.has(a.id)))return o;let{tool_calls:l,...i}=o;return{...i,content:i.content||""}})}function pe(n){let e=Array.isArray(n?.messages)?n.messages:[],t=e.find(r=>r.role==="system"),s=e.slice(-4).map(r=>({...r,content:J(r.content,r.role==="tool"?1200:2500)}));s=ee(s);let o={...n,messages:[t,...s].filter(Boolean)};return delete o.tools,o}async function he({body:n,streaming:e,auth:t,options:s,fetchCompletion:o,fetchStreamingCompletion:r,onFallbackLog:l}){try{return e?await r(n,t,s):await o(n,t,s)}catch(i){let a=String(i?.message||i||"");if(!/proxy error 413|payload too large/i.test(a))throw i;let c=pe(n);return typeof l=="function"&&l(n,c),{data:e?await r(c,t,s):await o(c,t,s),fallback:c}}}async function te({body:n,auth:e,options:t,streaming:s,toolContext:o,activeSkills:r,round:l,verbose:i,dependencies:a,config:c={}}){let u=c.maxToolResultChars||3e3,{fetchCompletion:p,fetchStreamingCompletion:x,onFallbackLog:S,hasToolCalls:A,getTextContent:E,parseToolCalls:d,buildAssistantMessage:g,buildToolResultMessage:h,executeTool:f,onToolCallLog:m,injectTools:C}=a;Array.isArray(n?.messages)&&(n.messages=ee(n.messages));let T=await he({body:n,streaming:s,auth:e,options:t,fetchCompletion:p,fetchStreamingCompletion:x,onFallbackLog:S}),y=T?.data||T;if(!A(y))return{done:!0,text:E(y),body:T?.fallback||n};let b=d(y),k=T?.fallback||n;k.messages.push(g(y)),i&&typeof m=="function"&&m(b);let N=await Promise.all(b.map((_,K)=>(typeof t.onToolCall=="function"&&t.onToolCall(_.name,_.args,{round:l,index:K,total:b.length}),f(_,o))));for(let _=0;_<b.length;_++){let ne=b[_].name==="get_skill_context"?typeof N[_]=="string"?N[_]:JSON.stringify(N[_]):ge(N[_],u);k.messages.push(h(b[_].id,ne))}return typeof t.onToolCall=="function"&&t.onToolCall(null),C(k,r),{done:!1,body:k}}var ye=q.ASSISTANT,_e=15,Z="get_skill_context";function B(n){!n||typeof n!="object"||(n.type==="object"&&n.properties&&(n.required=Object.keys(n.properties),n.additionalProperties=!1,Object.values(n.properties).forEach(B)),n.type==="array"&&n.items&&B(n.items),n.anyOf&&n.anyOf.forEach(B),n.oneOf&&n.oneOf.forEach(B),n.allOf&&n.allOf.forEach(B))}var oe={maxBytes:49e3,systemMaxChars:12e3},v=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Se=n=>Buffer.byteLength(JSON.stringify(n),"utf8");function Y(n){return Array.isArray(n)?new Set(n.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function Te(n){return Array.isArray(n)?n.map(e=>String(e||"").trim()).filter(Boolean):[]}var se=class extends U{#e;#t;#o=new z;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new $,this.#t=e.completionProvider||new P):(this.#e=e||new $,this.#t=new P)}canHandle(e){return V().ok}async invoke(e,t={}){let s=t.model&&t.model!=="auto"?t.model:ye,o=V();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}],l=o.baseUrl,i=v();if(i?await this.#g(r,s,l,o.tokenPreview||"none"):O.debug(`[Assistant] ${l} | model: ${s} | messages: ${r.length}`),t.schema)return this.#c(s,r,o,t);let a=t.activeSkills||[],c=this.#f(t),u=this.#m(a,c),p=this.#d(u),x=this.#u(t),S={...t,payloadCompaction:x},A={activeSkills:u,options:S,executionRegistry:p,capabilityPolicy:c},E=!!t.stream,d={model:s,messages:[...r],stream:!1};this.#n(d,u,c);for(let g=0;g<_e;g++){if(t.signal?.aborted)throw new Error("Aborted");let h=await te({body:d,auth:o,options:S,streaming:E,toolContext:A,activeSkills:u,round:g,verbose:i,dependencies:{fetchCompletion:this.#r.bind(this),fetchStreamingCompletion:this.#a.bind(this),onFallbackLog:(f,m)=>{v()&&console.log(`413 fallback: messages ${f.messages.length} -> ${m.messages.length}, bytes=${Se(m)}`)},hasToolCalls:f=>this.#e.hasToolCalls(f),getTextContent:f=>this.#e.getTextContent(f),parseToolCalls:f=>this.#e.parseToolCalls(f),buildAssistantMessage:f=>this.#e.buildAssistantMessage(f),buildToolResultMessage:(f,m)=>this.#e.buildToolResultMessage(f,m),executeTool:(f,m)=>this.#l(f,m),onToolCallLog:async f=>{let m=(await import("chalk")).default;console.log(m.dim(` ${f.map(C=>`${C.name}(${JSON.stringify(C.args).slice(0,80)})`).join(", ")}`))},injectTools:(f,m)=>this.#n(f,m,c)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(h.done)return h.text;d.messages=h.body.messages,h.body.tools?d.tools=h.body.tools:delete d.tools}return"I hit my tool-calling limit for this turn. Please try again."}async cleanup(){await this.#o.stopAll()}#n(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 l=M(r);if(l?.tools?.length)for(let i of l.tools)this.#s(i.name,t)&&(o.has(i.name)||(o.add(i.name),s.push({name:i.name,description:i.description,parameters:i.parameters||i.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#s(Z,t)&&s.push({name:Z,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),s}async#l(e,t){let{activeSkills:s,options:o,executionRegistry:r,capabilityPolicy:l}=t;if(!this.#s(e.name,l))return`Tool "${e.name}" blocked by policy`;if(e.name===Z){let c=String(e.args?.skillId||"").trim();if(!c)return JSON.stringify({error:"skillId is required"});if(!s.includes(c))return JSON.stringify({error:`Skill "${c}" is not active`,activeSkills:s});let u=M(c);if(!u)return JSON.stringify({error:`Skill "${c}" not found`});let p=typeof u.promptFragment=="function"?u.promptFragment():u.promptFragment||"",x=(u.tools||[]).map(A=>A.name),S=JSON.stringify({skillId:c,description:u.description||"",toolNames:x,promptFragment:p||""});return v()&&(console.log(`
8
8
  \u{1F4D6} get_skill_context("${c}") \u2192 ${S.length} chars (fragment: ${p.length} chars)`),console.log(` tools: [${x.join(", ")}]`),console.log(` fragment preview: ${p.slice(0,200).replace(/\n/g,"\\n")}\u2026
9
- `)),S}let i=r?.get(e.name)||null;if(!i)return`Unknown tool: ${e.name}`;let a=L(i.skillId);if(!a)return`Skill "${i.skillId}" not found for tool "${e.name}"`;if(i.mode==="handler")try{return a.handleToolCall(e.name,e.args,t)}catch(c){return`Error in ${e.name}: ${c.message}`}if(i.mode==="mcp")try{if(!this.#o.isRunning(a.serverName)){let u=a.resolve(o);if(!u)return`Skill "${i.skillId}" is not available (cannot start server)`;await this.#o.ensureServer(a.serverName,u)}let c=await this.#o.callTool(a.serverName,e.name,e.args);return c.text||(c.isError?"Tool call failed":"Done")}catch(c){return`MCP error (${a.serverName}): ${c.message}`}return`Skill "${i.skillId}" owns tool "${e.name}" but has no execution mode`}async#a(e,t,s){return this.#t.fetchStreamingCompletion(e,t,{...s,onBudget:({beforeBytes:o,meta:r})=>{v()&&console.log(`payload bytes (stream) before=${o} after=${r.bytes} trimmed=${r.trimmed} messages=${r.messageCount}`)}})}async#r(e,t,s){return this.#t.fetchCompletion(e,t,{...s,onBudget:({beforeBytes:o,meta:r})=>{v()&&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"),l=typeof o.schema?.parse=="function",i=l?r(o.schema):o.schema;delete i.$schema,B(i);let a={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:i,strict:!0}}},c=await this.#r(a,s,o),u=this.#e.getTextContent(c),p=JSON.parse(u),x=l?o.schema.parse(p):p;return{raw:u,structured:x}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||oe.maxBytes),systemMaxChars:Number(t.systemMaxChars||oe.systemMaxChars)}}#f(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:Y(t.allowTools||e.allowTools),denyTools:Y(t.denyTools||e.denyTools),denyPrefixes:xe(t.denyPrefixes||e.denyToolPrefixes),includeSkills:Y(t.includeSkills||e.includeSkills),excludeSkills:Y(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#m(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(i=>s.startsWith(i)))}#d(e){let t=new Map,s=[];for(let o of e){let r=L(o);if(!r?.tools?.length)continue;let l=typeof r.handleToolCall=="function"?"handler":r.serverName&&typeof r.resolve=="function"?"mcp":null;if(l)for(let i of r.tools){let a=String(i?.name||"").trim();if(a){if(t.has(a)){s.push({tool:a,winner:t.get(a).skillId,skipped:o});continue}t.set(a,{skillId:o,mode:l})}}}if(s.length>0&&v()){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#g(e,t,s,o){console.log(`
9
+ `)),S}let i=r?.get(e.name)||null;if(!i)return`Unknown tool: ${e.name}`;let a=M(i.skillId);if(!a)return`Skill "${i.skillId}" not found for tool "${e.name}"`;if(i.mode==="handler")try{return a.handleToolCall(e.name,e.args,t)}catch(c){return`Error in ${e.name}: ${c.message}`}if(i.mode==="mcp")try{if(!this.#o.isRunning(a.serverName)){let u=a.resolve(o);if(!u)return`Skill "${i.skillId}" is not available (cannot start server)`;await this.#o.ensureServer(a.serverName,u)}let c=await this.#o.callTool(a.serverName,e.name,e.args);return c.text||(c.isError?"Tool call failed":"Done")}catch(c){return`MCP error (${a.serverName}): ${c.message}`}return`Skill "${i.skillId}" owns tool "${e.name}" but has no execution mode`}async#a(e,t,s){return this.#t.fetchStreamingCompletion(e,t,{...s,onBudget:({beforeBytes:o,meta:r})=>{v()&&console.log(`payload bytes (stream) before=${o} after=${r.bytes} trimmed=${r.trimmed} messages=${r.messageCount}`)}})}async#r(e,t,s){return this.#t.fetchCompletion(e,t,{...s,onBudget:({beforeBytes:o,meta:r})=>{v()&&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"),l=typeof o.schema?.parse=="function",i=l?r(o.schema):o.schema;delete i.$schema,B(i);let a={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:i,strict:!0}}},c=await this.#r(a,s,o),u=this.#e.getTextContent(c),p=JSON.parse(u),x=l?o.schema.parse(p):p;return{raw:u,structured:x}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||oe.maxBytes),systemMaxChars:Number(t.systemMaxChars||oe.systemMaxChars)}}#f(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:Y(t.allowTools||e.allowTools),denyTools:Y(t.denyTools||e.denyTools),denyPrefixes:Te(t.denyPrefixes||e.denyToolPrefixes),includeSkills:Y(t.includeSkills||e.includeSkills),excludeSkills:Y(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#m(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(i=>s.startsWith(i)))}#d(e){let t=new Map,s=[];for(let o of e){let r=M(o);if(!r?.tools?.length)continue;let l=typeof r.handleToolCall=="function"?"handler":r.serverName&&typeof r.resolve=="function"?"mcp":null;if(l)for(let i of r.tools){let a=String(i?.name||"").trim();if(a){if(t.has(a)){s.push({tool:a,winner:t.get(a).skillId,skipped:o});continue}t.set(a,{skillId:o,mode:l})}}}if(s.length>0&&v()){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#g(e,t,s,o){console.log(`
10
10
  \u25C6 Model: ${t} | proxy: ${s} | token: ${o||"none"}
11
11
  `);let r=(await import("chalk")).default;console.log(r.bold("Prompt sent to LLM:")),console.log(r.dim("\u2500".repeat(60)));let l=!1;for(let i of e)if(i.role==="system")console.log(r.dim(`[System] ${i.content||""}`));else{l||(console.log(r.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),l=!0);let a=i.role==="user"?"Human":"AI",c=i.content?.length>200?`${i.content.slice(0,200)}...`:i.content||"";console.log(r.dim(`[${a}] ${c}`))}console.log(r.dim("\u2500".repeat(60)))}};export{se as AssistantStrategy};
@@ -1,17 +1,17 @@
1
- var A=class{constructor(t,e,n=0){this.name=t,this.description=e,this.priority=n}async invoke(t,e={}){throw new Error("AgentStrategy.invoke() must be implemented by subclass")}canHandle(t){throw new Error("AgentStrategy.canHandle() must be implemented by subclass")}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}};import{query as rt}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as ot}from"zod-to-json-schema";import S from"chalk";var f={debug:0,info:1,warn:2,error:3,silent:4},L=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return f.debug;if(process.env.ZIBBY_VERBOSE==="true")return f.info;let t=process.env.LOG_LEVEL?.toLowerCase();return t&&t in f?f[t]:f.info}_shouldLog(t){return f[t]>=this._level}_formatMessage(t,e,n={}){let i=new Date().toISOString(),s=`${this._getPrefix(t)} ${e}`;return Object.keys(n).length>0&&(s+=S.dim(` ${JSON.stringify(n)}`)),s}_getPrefix(t){return{debug:S.gray("[DEBUG]"),info:S.cyan("[INFO]"),warn:S.yellow("[WARN]"),error:S.red("\u274C [ERROR]")}[t]||""}debug(t,e){this._shouldLog("debug")&&console.log(this._formatMessage("debug",t,e))}info(t,e){this._shouldLog("info")&&console.log(this._formatMessage("info",t,e))}warn(t,e){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",t,e))}error(t,e){this._shouldLog("error")&&console.error(this._formatMessage("error",t,e))}setLevel(t){t in f&&(this._level=f[t])}getLevel(){return Object.keys(f).find(t=>f[t]===this._level)}},l=new L;import c from"chalk";var Q="__WORKFLOW_GRAPH_LOG__",w=c.gray("\u2502"),tt=c.gray("\u250C"),G=c.gray("\u2514"),x=c.green("\u25C6"),U=c.hex("#c084fc")("\u25C6"),F=c.hex("#2dd4bf")("\u25C6"),I=c.red("\u25C6"),K=`${w} `,J=2;function B(d){return d<1e3?`${d}ms`:`${(d/1e3).toFixed(1)}s`}function Z(d,t){return(e,n,i)=>{if(typeof e!="string")return d(e,n,i);let o=process.stdout.columns||120,s="";for(let p=0;p<e.length;p++){let g=e[p];t.lineStart&&(s+=K,t.col=J,t.lineStart=!1),g===`
2
- `?(s+=g,t.lineStart=!0,t.col=0,t.inEsc=!1):g==="\x1B"?(t.inEsc=!0,s+=g):t.inEsc?(s+=g,(g>="A"&&g<="Z"||g>="a"&&g<="z")&&(t.inEsc=!1)):(t.col++,s+=g,t.col>=o&&(s+=`
3
- ${K}`,t.col=J))}return d(s,n,i)}}var M=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null;let t=String(process.env.ZIBBY_RUN_SOURCE||"").trim().toLowerCase(),e=String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1";this._emitWorkflowGraphMarkers=e||t==="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 t={lineStart:!0,col:0,inEsc:!1},e={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=e,process.stdout.write=Z(this._origStdoutWrite,t),process.stderr.write=Z(this._origStderrWrite,e)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
1
+ var A=class{constructor(t,e,n=0){this.name=t,this.description=e,this.priority=n}async invoke(t,e={}){throw new Error("AgentStrategy.invoke() must be implemented by subclass")}canHandle(t){throw new Error("AgentStrategy.canHandle() must be implemented by subclass")}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}};import{query as et}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as rt}from"zod-to-json-schema";import S from"chalk";var _={debug:0,info:1,warn:2,error:3,silent:4},L=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return _.debug;if(process.env.ZIBBY_VERBOSE==="true")return _.info;let t=process.env.LOG_LEVEL?.toLowerCase();return t&&t in _?_[t]:_.info}_shouldLog(t){return _[t]>=this._level}_formatMessage(t,e,n={}){let i=new Date().toISOString(),s=`${this._getPrefix(t)} ${e}`;return Object.keys(n).length>0&&(s+=S.dim(` ${JSON.stringify(n)}`)),s}_getPrefix(t){return{debug:S.gray("[DEBUG]"),info:S.cyan("[INFO]"),warn:S.yellow("[WARN]"),error:S.red("\u274C [ERROR]")}[t]||""}debug(t,e){this._shouldLog("debug")&&console.log(this._formatMessage("debug",t,e))}info(t,e){this._shouldLog("info")&&console.log(this._formatMessage("info",t,e))}warn(t,e){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",t,e))}error(t,e){this._shouldLog("error")&&console.error(this._formatMessage("error",t,e))}setLevel(t){t in _&&(this._level=_[t])}getLevel(){return Object.keys(_).find(t=>_[t]===this._level)}},u=new L;import c from"chalk";var Q="__WORKFLOW_GRAPH_LOG__",w=c.gray("\u2502"),tt=c.gray("\u250C"),G=c.gray("\u2514"),I=c.green("\u25C6"),U=c.hex("#c084fc")("\u25C6"),F=c.hex("#2dd4bf")("\u25C6"),M=c.red("\u25C6"),K=`${w} `,J=2;function B(g){return g<1e3?`${g}ms`:`${(g/1e3).toFixed(1)}s`}function Z(g,t){return(e,n,i)=>{if(typeof e!="string")return g(e,n,i);let o=process.stdout.columns||120,s="";for(let d=0;d<e.length;d++){let p=e[d];t.lineStart&&(s+=K,t.col=J,t.lineStart=!1),p===`
2
+ `?(s+=p,t.lineStart=!0,t.col=0,t.inEsc=!1):p==="\x1B"?(t.inEsc=!0,s+=p):t.inEsc?(s+=p,(p>="A"&&p<="Z"||p>="a"&&p<="z")&&(t.inEsc=!1)):(t.col++,s+=p,t.col>=o&&(s+=`
3
+ ${K}`,t.col=J))}return g(s,n,i)}}var W=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null;let t=String(process.env.ZIBBY_RUN_SOURCE||"").trim().toLowerCase(),e=String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1";this._emitWorkflowGraphMarkers=e||t==="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 t={lineStart:!0,col:0,inEsc:!1},e={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=e,process.stdout.write=Z(this._origStdoutWrite,t),process.stderr.write=Z(this._origStderrWrite,e)}_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(t){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${t}
6
6
  `)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${Q}${JSON.stringify(t)}
7
7
  `;this._origStdoutWrite?this._origStdoutWrite(e):process.stdout.write(e)}_writeDot(t,e){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
8
8
  `),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${t} ${e}
9
9
  `)):process.stdout.write.bind(process.stdout)(`${t} ${e}
10
- `)}step(t){this._origStdoutWrite?this._writeDot(x,t):process.stdout.write.bind(process.stdout)(`${w} ${x} ${t}
10
+ `)}step(t){this._origStdoutWrite?this._writeDot(I,t):process.stdout.write.bind(process.stdout)(`${w} ${I} ${t}
11
11
  `)}stepTool(t){this._origStdoutWrite?this._writeDot(U,t):process.stdout.write.bind(process.stdout)(`${w} ${U} ${t}
12
12
  `)}stepMemory(t){let e=c.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(F,e):process.stdout.write.bind(process.stdout)(`${w} ${F} ${e}
13
- `)}stepFail(t){this._origStdoutWrite?this._writeDot(I,c.red(t)):process.stdout.write.bind(process.stdout)(`${w} ${I} ${c.red(t)}
14
- `)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${tt} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:n,details:i}=e;if(i)for(let s of i)this._rawWrite(`${x} ${s}`);let o=n?c.dim(` ${B(n)}`):"";this._rawWrite(`${G} ${c.green("done")}${o}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,n={}){this._stopIntercepting();let{duration:i}=n,o=i?c.dim(` ${B(i)}`):"";this._rawWrite(`${I} ${c.red(e)}`),this._rawWrite(`${G} ${c.red("failed")}${o}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(c.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){this._rawWrite(c.green.bold("\u2713 Workflow completed"))}},b=new M;var W={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"};var D={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"};var dt={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var et=new Map;function H(d){return et.get(d)||null}var Y=class extends A{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(t){let e=!!process.env.ANTHROPIC_API_KEY;return e||l.debug("ClaudeAgentStrategy: ANTHROPIC_API_KEY not set"),e}async invoke(t,e={}){let{model:n,workspace:i=process.cwd(),schema:o=null,images:s=[],skills:p=null,sessionPath:g=null,nodeName:j=null,timeout:st,config:it={}}=e,_=n;(!_||_==="auto")&&(l.debug(`Model is '${_||"undefined"}', using default: ${W.CLAUDE}`),_=W.CLAUDE);let m=D[_]||_;D[_]&&_!==m&&l.debug(`Mapped model: ${_} \u2192 ${m}`),l.debug(`Invoking Claude Agent SDK with model: ${m}, skills: ${JSON.stringify(p)}`);let T=process.env.ANTHROPIC_API_KEY,q=T?` | key: ***${T.slice(-4)}`:" | key: not set";console.log(`
13
+ `)}stepFail(t){this._origStdoutWrite?this._writeDot(M,c.red(t)):process.stdout.write.bind(process.stdout)(`${w} ${M} ${c.red(t)}
14
+ `)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${tt} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:n,details:i}=e;if(i)for(let s of i)this._rawWrite(`${I} ${s}`);let o=n?c.dim(` ${B(n)}`):"";this._rawWrite(`${G} ${c.green("done")}${o}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,n={}){this._stopIntercepting();let{duration:i}=n,o=i?c.dim(` ${B(i)}`):"";this._rawWrite(`${M} ${c.red(e)}`),this._rawWrite(`${G} ${c.red("failed")}${o}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(c.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){this._rawWrite(c.green.bold("\u2713 Workflow completed"))}},b=new W;var x={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"};var D={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"};var at={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};import{registerSkill as _t,getSkill as H,hasSkill as ft,getAllSkills as ht,listSkillIds as mt}from"@zibby/workflow";var Y=class extends A{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(t){let e=!!process.env.ANTHROPIC_API_KEY;return e||u.debug("ClaudeAgentStrategy: ANTHROPIC_API_KEY not set"),e}async invoke(t,e={}){let{model:n,workspace:i=process.cwd(),schema:o=null,images:s=[],skills:d=null,sessionPath:p=null,nodeName:j=null,timeout:ot,config:st={}}=e,f=n;(!f||f==="auto")&&(u.debug(`Model is '${f||"undefined"}', using default: ${x.CLAUDE}`),f=x.CLAUDE);let m=D[f]||f;D[f]&&f!==m&&u.debug(`Mapped model: ${f} \u2192 ${m}`),u.debug(`Invoking Claude Agent SDK with model: ${m}, skills: ${JSON.stringify(d)}`);let T=process.env.ANTHROPIC_API_KEY,q=T?` | key: ***${T.slice(-4)}`:" | key: not set";console.log(`
15
15
  \u25C6 Model: ${m}${q}
16
16
  `);let E=(await import("chalk")).default;console.log(`
17
- ${E.bold("Prompt sent to LLM:")}`),console.log(E.dim("\u2500".repeat(60))),console.log(E.dim(t)),console.log(E.dim("\u2500".repeat(60)));let{allowedTools:N,mcpServers:R}=this._resolveSkills(p,{sessionPath:g,workspace:i,nodeName:j});try{let h={cwd:i,allowedTools:N,permissionMode:"bypassPermissions",model:m,...Object.keys(R).length>0&&{mcpServers:R}};if(o){let y=typeof o.parse=="function"?ot(o,{target:"openApi3"}):o;h.outputFormat={type:"json_schema",schema:y},l.debug("Structured output enforced via SDK outputFormat")}l.debug(`Agent SDK options: ${JSON.stringify({cwd:h.cwd,toolCount:N.length,permissionMode:h.permissionMode,model:h.model,hasOutputFormat:!!h.outputFormat})}`);let $="",X=0,k=[];l.debug("Starting Claude Agent SDK query stream");let P;try{P=rt({prompt:t,options:h})}catch(r){throw l.error(`Failed to initialize Claude Agent SDK: ${r.message}`),r}let v=null,O=0,V=3;try{for await(let r of P){if(k.push(r),r.type==="error"||r.error){let a=r.error?.message||r.error||r.message||"Unknown API error";throw new Error(typeof a=="string"?a:JSON.stringify(a))}let y=JSON.stringify(r.message?.content||r.text||"").slice(0,200);if(y===v){if(O++,O>=V){let a=(r.message?.content?.[0]?.text||r.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${O}x repeated): ${a}`)}}else v=y,O=1;if(r.type==="assistant"||r.constructor?.name==="AssistantMessage"){let a=r.message?.content||r.content||[];for(let u of a)if(u.type==="thinking"&&u.thinking)console.log(`${u.thinking.substring(0,200)}${u.thinking.length>200?"...":""}`);else if(u.type==="text"&&u.text)$+=u.text,u.text.length<500?console.log(`${u.text}`):console.log(`${u.text.substring(0,200)}... (${u.text.length} chars)`);else if(u.type==="tool_use"){X++,u.name.includes("memory")?b.stepMemory(`Tool: ${u.name}`):b.stepTool(`Tool: ${u.name}`);let z=JSON.stringify(u.input).substring(0,100);console.log(` Input: ${z}${JSON.stringify(u.input).length>100?"...":""}`)}}else if(!(r.type==="user"&&r.tool_use_result)){if(r.type==="result"||r.constructor?.name==="ResultMessage"){let a=r.result||r.text||r.content||$;if(o){if(r.structured_output){l.debug("Using SDK native structured_output");let C=typeof o.parse=="function"?o.parse(r.structured_output):r.structured_output;return{raw:a,structured:C}}if(a){let u=this._extractJson(a,o);if(u)return{raw:a,structured:u}}l.warn(`Could not extract structured output \u2014 returning raw text (${(a||"").length} chars)`)}return a||""}}}if(l.warn(`Agent SDK ended without result. Collected ${k.length} messages`),$.length>0)return l.debug("Returning accumulated text from messages"),$;throw new Error("Claude Agent SDK query ended without result")}catch(r){throw l.error(`Error during query stream: ${r.message}`),r}}catch(h){throw l.error("Claude Agent SDK call failed",{error:h.message}),h}}_resolveSkills(t,e){if(t===null)return l.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(t)||t.length===0)return l.debug("Default IDE skills for code generation"),{allowedTools:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};let n=[],i={};for(let o of t){let s=H(o);if(!s){l.warn(`Unknown skill "${o}" \u2014 skipping`);continue}if(s.allowedTools&&n.push(...s.allowedTools),typeof s.resolve=="function"){let p=s.resolve(e);p&&(i[s.serverName]=p,l.debug(`MCP: ${s.serverName} \u2192 ${p.command} ${p.args[0]}`))}}return{allowedTools:n,mcpServers:i}}_extractJson(t,e){let n=[()=>{if(t.includes("===JSON_START===")){let i=t.indexOf("===JSON_START===")+16,o=t.indexOf("===JSON_END===");return t.substring(i,o).trim()}},()=>t.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!t.startsWith("{"))return t.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>t.trim(),()=>{let i=t.indexOf("{"),o=t.lastIndexOf("}");if(i!==-1&&o>i)return t.substring(i,o+1)}];for(let i of n)try{let o=i();if(!o)continue;let s=JSON.parse(o);if(typeof s!="object"||s===null)continue;return typeof e.parse=="function"?e.parse(s):s}catch{}return null}};export{Y as ClaudeAgentStrategy};
17
+ ${E.bold("Prompt sent to LLM:")}`),console.log(E.dim("\u2500".repeat(60))),console.log(E.dim(t)),console.log(E.dim("\u2500".repeat(60)));let{allowedTools:k,mcpServers:N}=this._resolveSkills(d,{sessionPath:p,workspace:i,nodeName:j});try{let h={cwd:i,allowedTools:k,permissionMode:"bypassPermissions",model:m,...Object.keys(N).length>0&&{mcpServers:N}};if(o){let y=typeof o.parse=="function"?rt(o,{target:"openApi3"}):o;h.outputFormat={type:"json_schema",schema:y},u.debug("Structured output enforced via SDK outputFormat")}u.debug(`Agent SDK options: ${JSON.stringify({cwd:h.cwd,toolCount:k.length,permissionMode:h.permissionMode,model:h.model,hasOutputFormat:!!h.outputFormat})}`);let $="",X=0,R=[];u.debug("Starting Claude Agent SDK query stream");let P;try{P=et({prompt:t,options:h})}catch(r){throw u.error(`Failed to initialize Claude Agent SDK: ${r.message}`),r}let v=null,O=0,V=3;try{for await(let r of P){if(R.push(r),r.type==="error"||r.error){let a=r.error?.message||r.error||r.message||"Unknown API error";throw new Error(typeof a=="string"?a:JSON.stringify(a))}let y=JSON.stringify(r.message?.content||r.text||"").slice(0,200);if(y===v){if(O++,O>=V){let a=(r.message?.content?.[0]?.text||r.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${O}x repeated): ${a}`)}}else v=y,O=1;if(r.type==="assistant"||r.constructor?.name==="AssistantMessage"){let a=r.message?.content||r.content||[];for(let l of a)if(l.type==="thinking"&&l.thinking)console.log(`${l.thinking.substring(0,200)}${l.thinking.length>200?"...":""}`);else if(l.type==="text"&&l.text)$+=l.text,l.text.length<500?console.log(`${l.text}`):console.log(`${l.text.substring(0,200)}... (${l.text.length} chars)`);else if(l.type==="tool_use"){X++,l.name.includes("memory")?b.stepMemory(`Tool: ${l.name}`):b.stepTool(`Tool: ${l.name}`);let z=JSON.stringify(l.input).substring(0,100);console.log(` Input: ${z}${JSON.stringify(l.input).length>100?"...":""}`)}}else if(!(r.type==="user"&&r.tool_use_result)){if(r.type==="result"||r.constructor?.name==="ResultMessage"){let a=r.result||r.text||r.content||$;if(o){if(r.structured_output){u.debug("Using SDK native structured_output");let C=typeof o.parse=="function"?o.parse(r.structured_output):r.structured_output;return{raw:a,structured:C}}if(a){let l=this._extractJson(a,o);if(l)return{raw:a,structured:l}}u.warn(`Could not extract structured output \u2014 returning raw text (${(a||"").length} chars)`)}return a||""}}}if(u.warn(`Agent SDK ended without result. Collected ${R.length} messages`),$.length>0)return u.debug("Returning accumulated text from messages"),$;throw new Error("Claude Agent SDK query ended without result")}catch(r){throw u.error(`Error during query stream: ${r.message}`),r}}catch(h){throw u.error("Claude Agent SDK call failed",{error:h.message}),h}}_resolveSkills(t,e){if(t===null)return u.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(t)||t.length===0)return u.debug("Default IDE skills for code generation"),{allowedTools:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};let n=[],i={};for(let o of t){let s=H(o);if(!s){u.warn(`Unknown skill "${o}" \u2014 skipping`);continue}if(s.allowedTools&&n.push(...s.allowedTools),typeof s.resolve=="function"){let d=s.resolve(e);d&&(i[s.serverName]=d,u.debug(`MCP: ${s.serverName} \u2192 ${d.command} ${d.args[0]}`))}}return{allowedTools:n,mcpServers:i}}_extractJson(t,e){let n=[()=>{if(t.includes("===JSON_START===")){let i=t.indexOf("===JSON_START===")+16,o=t.indexOf("===JSON_END===");return t.substring(i,o).trim()}},()=>t.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!t.startsWith("{"))return t.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>t.trim(),()=>{let i=t.indexOf("{"),o=t.lastIndexOf("}");if(i!==-1&&o>i)return t.substring(i,o+1)}];for(let i of n)try{let o=i();if(!o)continue;let s=JSON.parse(o);if(typeof s!="object"||s===null)continue;return typeof e.parse=="function"?e.parse(s):s}catch{}return null}};export{Y as ClaudeAgentStrategy};
@@ -1,6 +1,6 @@
1
- var v=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}};import{execSync as te}from"node:child_process";import{zodToJsonSchema as oe}from"zod-to-json-schema";import E from"chalk";var u={debug:0,info:1,warn:2,error:3,silent:4},b=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return u.debug;if(process.env.ZIBBY_VERBOSE==="true")return u.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in u?u[e]:u.info}_shouldLog(e){return u[e]>=this._level}_formatMessage(e,t,r={}){let c=new Date().toISOString(),o=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(o+=E.dim(` ${JSON.stringify(r)}`)),o}_getPrefix(e){return{debug:E.gray("[DEBUG]"),info:E.cyan("[INFO]"),warn:E.yellow("[WARN]"),error:E.red("\u274C [ERROR]")}[e]||""}debug(e,t){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,t))}info(e,t){this._shouldLog("info")&&console.log(this._formatMessage("info",e,t))}warn(e,t){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,t))}error(e,t){this._shouldLog("error")&&console.error(this._formatMessage("error",e,t))}setLevel(e){e in u&&(this._level=u[e])}getLevel(){return Object.keys(u).find(e=>u[e]===this._level)}},i=new b;import n from"chalk";var q="__WORKFLOW_GRAPH_LOG__",$=n.gray("\u2502"),Q=n.gray("\u250C"),G=n.gray("\u2514"),C=n.green("\u25C6"),K=n.hex("#c084fc")("\u25C6"),U=n.hex("#2dd4bf")("\u25C6"),M=n.red("\u25C6"),Y=`${$} `,F=2;function X(d){return d<1e3?`${d}ms`:`${(d/1e3).toFixed(1)}s`}function B(d,e){return(t,r,c)=>{if(typeof t!="string")return d(t,r,c);let s=process.stdout.columns||120,o="";for(let f=0;f<t.length;f++){let l=t[f];e.lineStart&&(o+=Y,e.col=F,e.lineStart=!1),l===`
1
+ var v=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}};import{execSync as ee}from"node:child_process";import{zodToJsonSchema as te}from"zod-to-json-schema";import w from"chalk";var u={debug:0,info:1,warn:2,error:3,silent:4},b=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return u.debug;if(process.env.ZIBBY_VERBOSE==="true")return u.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in u?u[e]:u.info}_shouldLog(e){return u[e]>=this._level}_formatMessage(e,t,r={}){let c=new Date().toISOString(),o=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(o+=w.dim(` ${JSON.stringify(r)}`)),o}_getPrefix(e){return{debug:w.gray("[DEBUG]"),info:w.cyan("[INFO]"),warn:w.yellow("[WARN]"),error:w.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 u&&(this._level=u[e])}getLevel(){return Object.keys(u).find(e=>u[e]===this._level)}},i=new b;import n from"chalk";var q="__WORKFLOW_GRAPH_LOG__",$=n.gray("\u2502"),Q=n.gray("\u250C"),G=n.gray("\u2514"),C=n.green("\u25C6"),K=n.hex("#c084fc")("\u25C6"),U=n.hex("#2dd4bf")("\u25C6"),P=n.red("\u25C6"),Y=`${$} `,F=2;function X(a){return a<1e3?`${a}ms`:`${(a/1e3).toFixed(1)}s`}function B(a,e){return(t,r,c)=>{if(typeof t!="string")return a(t,r,c);let s=process.stdout.columns||120,o="";for(let f=0;f<t.length;f++){let l=t[f];e.lineStart&&(o+=Y,e.col=F,e.lineStart=!1),l===`
2
2
  `?(o+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,o+=l):e.inEsc?(o+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,o+=l,e.col>=s&&(o+=`
3
- ${Y}`,e.col=F))}return d(o,r,c)}}var P=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=B(this._origStdoutWrite,e),process.stderr.write=B(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
3
+ ${Y}`,e.col=F))}return a(o,r,c)}}var D=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=B(this._origStdoutWrite,e),process.stderr.write=B(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=`${q}${JSON.stringify(e)}
@@ -10,8 +10,8 @@ ${Y}`,e.col=F))}return d(o,r,c)}}var P=class{constructor(){this._currentNode=nul
10
10
  `)}step(e){this._origStdoutWrite?this._writeDot(C,e):process.stdout.write.bind(process.stdout)(`${$} ${C} ${e}
11
11
  `)}stepTool(e){this._origStdoutWrite?this._writeDot(K,e):process.stdout.write.bind(process.stdout)(`${$} ${K} ${e}
12
12
  `)}stepMemory(e){let t=n.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(U,t):process.stdout.write.bind(process.stdout)(`${$} ${U} ${t}
13
- `)}stepFail(e){this._origStdoutWrite?this._writeDot(M,n.red(e)):process.stdout.write.bind(process.stdout)(`${$} ${M} ${n.red(e)}
14
- `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Q} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:c}=t;if(c)for(let o of c)this._rawWrite(`${C} ${o}`);let s=r?n.dim(` ${X(r)}`):"";this._rawWrite(`${G} ${n.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:c}=r,s=c?n.dim(` ${X(c)}`):"";this._rawWrite(`${M} ${n.red(t)}`),this._rawWrite(`${G} ${n.red("failed")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(n.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){this._rawWrite(n.green.bold("\u2713 Workflow completed"))}},D=new P;var k={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"};var N={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"};var ue={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var ee=new Map;function j(d){return ee.get(d)||null}var J=class extends v{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.CODEX_API_KEY))return i.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return te("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return i.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:r,workspace:c=process.cwd(),schema:s=null,skills:o=null,sessionPath:f=null,nodeName:l=null,timeout:re,config:se={}}=t,{Codex:H}=await import("@openai/codex-sdk"),p=r;(!p||p==="auto")&&(i.debug(`Model is '${p||"undefined"}', using default: ${k.CODEX}`),p=k.CODEX);let x=N[p]||p;N[p]&&p!==x&&i.debug(`Mapped model: ${p} \u2192 ${x}`),i.debug(`Invoking Codex SDK with model: ${x}, skills: ${JSON.stringify(o)}`);let O=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;O&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=O);let V=O?` | key: ***${O.slice(-4)}`:" | key: not set";console.log(`
15
- \u25C6 Model: ${x}${V}
13
+ `)}stepFail(e){this._origStdoutWrite?this._writeDot(P,n.red(e)):process.stdout.write.bind(process.stdout)(`${$} ${P} ${n.red(e)}
14
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Q} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:c}=t;if(c)for(let o of c)this._rawWrite(`${C} ${o}`);let s=r?n.dim(` ${X(r)}`):"";this._rawWrite(`${G} ${n.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:c}=r,s=c?n.dim(` ${X(c)}`):"";this._rawWrite(`${P} ${n.red(t)}`),this._rawWrite(`${G} ${n.red("failed")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(n.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){this._rawWrite(n.green.bold("\u2713 Workflow completed"))}},M=new D;var k={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"};var N={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"};var ae={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};import{registerSkill as _e,getSkill as j,hasSkill as fe,getAllSkills as he,listSkillIds as me}from"@zibby/workflow";var J=class extends v{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.CODEX_API_KEY))return i.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return ee("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return i.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:r,workspace:c=process.cwd(),schema:s=null,skills:o=null,sessionPath:f=null,nodeName:l=null,timeout:oe,config:re={}}=t,{Codex:H}=await import("@openai/codex-sdk"),p=r;(!p||p==="auto")&&(i.debug(`Model is '${p||"undefined"}', using default: ${k.CODEX}`),p=k.CODEX);let O=N[p]||p;N[p]&&p!==O&&i.debug(`Mapped model: ${p} \u2192 ${O}`),i.debug(`Invoking Codex SDK with model: ${O}, skills: ${JSON.stringify(o)}`);let x=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;x&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=x);let V=x?` | key: ***${x.slice(-4)}`:" | key: not set";console.log(`
15
+ \u25C6 Model: ${O}${V}
16
16
  `);let I=(await import("chalk")).default;console.log(`
17
- ${I.bold("Prompt sent to LLM:")}`),console.log(I.dim("\u2500".repeat(60))),console.log(I.dim(e)),console.log(I.dim("\u2500".repeat(60)));let y=this._resolveSkillsToMcp(o,{sessionPath:f,workspace:c,nodeName:l}),A={};Object.keys(y).length>0&&(A.mcp_servers=y,i.debug(`[Codex] MCP servers: ${Object.keys(y).join(", ")}`));let Z=new H({...Object.keys(A).length>0&&{config:A}}).startThread({workingDirectory:c,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),R=s&&typeof s.parse=="function",T={};if(s)try{let g=R?oe(s,{target:"openAi"}):s;T.outputSchema=g,i.debug("Structured output via SDK outputSchema")}catch(g){i.warn(`[Codex] Schema conversion failed, will extract from text: ${g.message}`)}try{let{events:g}=await Z.runStreamed(e,T),m=0,a="";for await(let h of g){let S=h.type;if(S==="item.completed"){let _=h.item,w=_?.type;if(w==="mcp_tool_call"){m++;let L=`${_.server}/${_.tool}`;if(D.stepTool(`Tool: ${L}`),_.arguments){let W=JSON.stringify(_.arguments),z=W.length>100?`${W.substring(0,100)}...`:W;console.log(` Input: ${z}`)}}else if(w==="tool_call"||w==="function_call"||w==="command_execution"){m++;let L=_.name||_.tool||_.command||"unknown";D.stepTool(`Tool: ${L}`)}else w==="agent_message"&&(a=_.text||"",a.length<500?console.log(a):console.log(`${a.substring(0,200)}... (${a.length} chars)`))}else S==="turn.completed"?i.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(h.usage||{})}`):i.debug(`[Codex] Event: ${S} ${JSON.stringify(h).slice(0,300)}`)}if(i.debug(`[Codex] Last agent message (${a.length} chars): ${a.slice(0,500)}`),s){if(!a)throw new Error("Codex agent returned no response");let h=JSON.parse(a),S=R?s.parse(h):h;return i.debug("\u2705 [Codex] Structured output validated"),{raw:a,structured:S}}return a||""}catch(g){let m=g.message||String(g);throw i.error(`\u274C [Codex] SDK call failed: ${m}`),m.includes("exited with code")&&(i.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),i.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),g}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let c of e){let s=j(c);if(!s){i.warn(`[Codex] Unknown skill "${c}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let o=s.resolve(t);if(!o)continue;let f=s.serverName||c,l={command:o.command};o.args?.length&&(l.args=o.args),o.env&&Object.keys(o.env).length>0&&(l.env=o.env),r[f]=l,i.debug(`[Codex] MCP: ${f} \u2192 ${o.command} ${(o.args||[]).join(" ")}`)}return r}};export{J as CodexAgentStrategy};
17
+ ${I.bold("Prompt sent to LLM:")}`),console.log(I.dim("\u2500".repeat(60))),console.log(I.dim(e)),console.log(I.dim("\u2500".repeat(60)));let L=this._resolveSkillsToMcp(o,{sessionPath:f,workspace:c,nodeName:l}),A={};Object.keys(L).length>0&&(A.mcp_servers=L,i.debug(`[Codex] MCP servers: ${Object.keys(L).join(", ")}`));let Z=new H({...Object.keys(A).length>0&&{config:A}}).startThread({workingDirectory:c,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),R=s&&typeof s.parse=="function",T={};if(s)try{let g=R?te(s,{target:"openAi"}):s;T.outputSchema=g,i.debug("Structured output via SDK outputSchema")}catch(g){i.warn(`[Codex] Schema conversion failed, will extract from text: ${g.message}`)}try{let{events:g}=await Z.runStreamed(e,T),m=0,d="";for await(let h of g){let S=h.type;if(S==="item.completed"){let _=h.item,E=_?.type;if(E==="mcp_tool_call"){m++;let y=`${_.server}/${_.tool}`;if(M.stepTool(`Tool: ${y}`),_.arguments){let W=JSON.stringify(_.arguments),z=W.length>100?`${W.substring(0,100)}...`:W;console.log(` Input: ${z}`)}}else if(E==="tool_call"||E==="function_call"||E==="command_execution"){m++;let y=_.name||_.tool||_.command||"unknown";M.stepTool(`Tool: ${y}`)}else E==="agent_message"&&(d=_.text||"",d.length<500?console.log(d):console.log(`${d.substring(0,200)}... (${d.length} chars)`))}else S==="turn.completed"?i.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(h.usage||{})}`):i.debug(`[Codex] Event: ${S} ${JSON.stringify(h).slice(0,300)}`)}if(i.debug(`[Codex] Last agent message (${d.length} chars): ${d.slice(0,500)}`),s){if(!d)throw new Error("Codex agent returned no response");let h=JSON.parse(d),S=R?s.parse(h):h;return i.debug("\u2705 [Codex] Structured output validated"),{raw:d,structured:S}}return d||""}catch(g){let m=g.message||String(g);throw i.error(`\u274C [Codex] SDK call failed: ${m}`),m.includes("exited with code")&&(i.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),i.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),g}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let c of e){let s=j(c);if(!s){i.warn(`[Codex] Unknown skill "${c}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let o=s.resolve(t);if(!o)continue;let f=s.serverName||c,l={command:o.command};o.args?.length&&(l.args=o.args),o.env&&Object.keys(o.env).length>0&&(l.env=o.env),r[f]=l,i.debug(`[Codex] MCP: ${f} \u2192 ${o.command} ${(o.args||[]).join(" ")}`)}return r}};export{J as CodexAgentStrategy};
@@ -1,7 +1,7 @@
1
- var V=class{constructor(t,e,r=0){this.name=t,this.description=e,this.priority=r}async invoke(t,e={}){throw new Error("AgentStrategy.invoke() must be implemented by subclass")}canHandle(t){throw new Error("AgentStrategy.canHandle() must be implemented by subclass")}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}};import{spawn as Vt,execSync as D}from"node:child_process";import{writeFileSync as $t,readFileSync as xt,mkdirSync as At,existsSync as Y,accessSync as Tt,constants as Rt,unlinkSync as Xt}from"node:fs";import{join as v,resolve as qt}from"node:path";import{homedir as j}from"node:os";import K from"chalk";var C={debug:0,info:1,warn:2,error:3,silent:4},et=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return C.debug;if(process.env.ZIBBY_VERBOSE==="true")return C.info;let t=process.env.LOG_LEVEL?.toLowerCase();return t&&t in C?C[t]:C.info}_shouldLog(t){return C[t]>=this._level}_formatMessage(t,e,r={}){let s=new Date().toISOString(),o=`${this._getPrefix(t)} ${e}`;return Object.keys(r).length>0&&(o+=K.dim(` ${JSON.stringify(r)}`)),o}_getPrefix(t){return{debug:K.gray("[DEBUG]"),info:K.cyan("[INFO]"),warn:K.yellow("[WARN]"),error:K.red("\u274C [ERROR]")}[t]||""}debug(t,e){this._shouldLog("debug")&&console.log(this._formatMessage("debug",t,e))}info(t,e){this._shouldLog("info")&&console.log(this._formatMessage("info",t,e))}warn(t,e){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",t,e))}error(t,e){this._shouldLog("error")&&console.error(this._formatMessage("error",t,e))}setLevel(t){t in C&&(this._level=C[t])}getLevel(){return Object.keys(C).find(t=>C[t]===this._level)}},i=new et;var z={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"};var X={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var ut=".zibby/output";var at=".session-info.json",ct=".zibby-studio-stop";var pt=new Map;function rt(n){return pt.get(n)||null}function ft(){return new Map(pt)}var q=class n{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(t){if(!t)return null;this.buffer+=t;let e=this.buffer.split(`
2
- `);this.buffer=e.pop()||"";let r="";for(let s of e)if(s.trim())try{let u=JSON.parse(s);this._emitToolCalls(u);let o=this.extractText(u);if(o){if(this.rawText&&o.startsWith(this.rawText)){let a=o.substring(this.rawText.length);this.rawText=o,r+=a}else(!this.rawText.includes(o)||o.length<20)&&(this.rawText+=o,r+=o);this.tryExtractResult(this.rawText)}else this.isValidResult(u)&&(this.rawText+=`${s}
3
- `,r+=`${s}
4
- `,this.extractedResult=u)}catch{if(s.includes('"text"')||s.includes('"content"')){let o=s.match(/"text"\s*:\s*"([^"]*)/),a=s.match(/"content"\s*:\s*"([^"]*)/),c=o?o[1]:a?a[1]:null;c&&!this.rawText.includes(c)&&(r+=c,this.rawText+=c)}}return r||null}flush(){if(!this.buffer.trim())return null;let t="";try{let e=JSON.parse(this.buffer);this._emitToolCalls(e);let r=this.extractText(e);r&&(this.rawText+=r,t+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,t+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",t||null}_emitToolCalls(t){if(!this.onToolCall)return;let e=(o,a)=>{if(!o)return;let c=`${o}:${JSON.stringify(a??{})}`;this._lastToolEmit!==c&&(this._lastToolEmit=c,this.onToolCall(o,a??void 0))},r=o=>{if(o!=null){if(typeof o=="object"&&!Array.isArray(o))return o;if(typeof o=="string")try{return JSON.parse(o)}catch{return}}};if(t.type==="tool_use"||t.type==="tool_call"){if(t.name){e(t.name,r(t.input??t.arguments));return}let o=t.tool_call;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=Object.keys(o);if(a.length===1){let c=a[0],g=o[c],p=g&&typeof g=="object"?g.args??g.input??g:void 0;e(c,r(p))}return}return}if(Array.isArray(t.tool_calls)){for(let o of t.tool_calls)e(o.name,r(o.input??o.arguments));return}let s=t.message??t;if(Array.isArray(s?.tool_calls)){for(let o of s.tool_calls)e(o.name,r(o.input??o.arguments));return}let u=s?.content??t.content;if(Array.isArray(u))for(let o of u)(o.type==="tool_use"||o.type==="tool_call")&&o.name&&e(o.name,r(o.input??o.arguments))}extractText(t){if(t.type==="assistant"&&t.message?.content){let e=t.message.content;if(Array.isArray(e))return e.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return t.type==="thinking"&&t.text||t.text?t.text:t.content&&typeof t.content=="string"?t.content:t.delta?t.delta:null}tryExtractResult(t){if(!t||typeof t!="string")return;let e=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,s;for(;(s=r.exec(t))!==null;){let f=s[1].trim();try{JSON.parse(f),e.push({text:f,source:"markdown"})}catch{}}let u=0,o=0;for(;u<t.length&&(u=t.indexOf("{",u),u!==-1);){let f=0,h=u;for(let S=u;S<t.length;S++)if(t[S]==="{")f++;else if(t[S]==="}"&&(f--,f===0)){h=S,e.push({text:t.substring(u,h+1),source:"brace"}),o++;break}u=h+1}let a=this.extractedResult,c=a?JSON.stringify(a).length:0,g=0,p=-1;for(let f=0;f<e.length;f++){let h=e[f];try{let S=h.text.replace(/,(\s*[}\]])/g,"$1"),b=JSON.parse(S);this.isValidResult(b)&&(g++,c=JSON.stringify(b).length,a=b,p=f)}catch{}}a&&(this.extractedResult=a)}isValidResult(t){if(!t||typeof t!="object"||Array.isArray(t)||t.session_id||t.timestamp_ms||t.type||t.call_id||t.tool_call||t.result&&typeof t.result=="object"&&(t.result.success&&typeof t.result.success=="object"||t.result.error&&typeof t.result.error=="object")||t.args&&typeof t.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(t),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(t,e=null){let r=new n;r.zodSchema=e,r.processChunk(t),r.flush();let s=r.getResult();return!s&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",t?.length||0,"chars"),s}};import{zodToJsonSchema as Pt}from"zod-to-json-schema";var Q=class{static generateFileOutputInstructions(t,e){let r;typeof t?.parse=="function"?r=Pt(t,{target:"openApi3"}):r=t;let s=this._buildExample(r);return`
1
+ var V=class{constructor(t,e,r=0){this.name=t,this.description=e,this.priority=r}async invoke(t,e={}){throw new Error("AgentStrategy.invoke() must be implemented by subclass")}canHandle(t){throw new Error("AgentStrategy.canHandle() must be implemented by subclass")}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}};import{spawn as Zt,execSync as D}from"node:child_process";import{writeFileSync as bt,readFileSync as $t,mkdirSync as xt,existsSync as Y,accessSync as At,constants as Tt,unlinkSync as Vt}from"node:fs";import{join as v,resolve as Xt}from"node:path";import{homedir as j}from"node:os";import K from"chalk";var C={debug:0,info:1,warn:2,error:3,silent:4},et=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return C.debug;if(process.env.ZIBBY_VERBOSE==="true")return C.info;let t=process.env.LOG_LEVEL?.toLowerCase();return t&&t in C?C[t]:C.info}_shouldLog(t){return C[t]>=this._level}_formatMessage(t,e,r={}){let o=new Date().toISOString(),s=`${this._getPrefix(t)} ${e}`;return Object.keys(r).length>0&&(s+=K.dim(` ${JSON.stringify(r)}`)),s}_getPrefix(t){return{debug:K.gray("[DEBUG]"),info:K.cyan("[INFO]"),warn:K.yellow("[WARN]"),error:K.red("\u274C [ERROR]")}[t]||""}debug(t,e){this._shouldLog("debug")&&console.log(this._formatMessage("debug",t,e))}info(t,e){this._shouldLog("info")&&console.log(this._formatMessage("info",t,e))}warn(t,e){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",t,e))}error(t,e){this._shouldLog("error")&&console.error(this._formatMessage("error",t,e))}setLevel(t){t in C&&(this._level=C[t])}getLevel(){return Object.keys(C).find(t=>C[t]===this._level)}},i=new et;var z={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"};var X={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var at=".zibby/output";var ut=".session-info.json",ct=".zibby-studio-stop";import{registerSkill as ne,getSkill as rt,hasSkill as ie,getAllSkills as pt,listSkillIds as le}from"@zibby/workflow";var q=class n{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(t){if(!t)return null;this.buffer+=t;let e=this.buffer.split(`
2
+ `);this.buffer=e.pop()||"";let r="";for(let o of e)if(o.trim())try{let a=JSON.parse(o);this._emitToolCalls(a);let s=this.extractText(a);if(s){if(this.rawText&&s.startsWith(this.rawText)){let u=s.substring(this.rawText.length);this.rawText=s,r+=u}else(!this.rawText.includes(s)||s.length<20)&&(this.rawText+=s,r+=s);this.tryExtractResult(this.rawText)}else this.isValidResult(a)&&(this.rawText+=`${o}
3
+ `,r+=`${o}
4
+ `,this.extractedResult=a)}catch{if(o.includes('"text"')||o.includes('"content"')){let s=o.match(/"text"\s*:\s*"([^"]*)/),u=o.match(/"content"\s*:\s*"([^"]*)/),c=s?s[1]:u?u[1]:null;c&&!this.rawText.includes(c)&&(r+=c,this.rawText+=c)}}return r||null}flush(){if(!this.buffer.trim())return null;let t="";try{let e=JSON.parse(this.buffer);this._emitToolCalls(e);let r=this.extractText(e);r&&(this.rawText+=r,t+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,t+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",t||null}_emitToolCalls(t){if(!this.onToolCall)return;let e=(s,u)=>{if(!s)return;let c=`${s}:${JSON.stringify(u??{})}`;this._lastToolEmit!==c&&(this._lastToolEmit=c,this.onToolCall(s,u??void 0))},r=s=>{if(s!=null){if(typeof s=="object"&&!Array.isArray(s))return s;if(typeof s=="string")try{return JSON.parse(s)}catch{return}}};if(t.type==="tool_use"||t.type==="tool_call"){if(t.name){e(t.name,r(t.input??t.arguments));return}let s=t.tool_call;if(s&&typeof s=="object"&&!Array.isArray(s)){let u=Object.keys(s);if(u.length===1){let c=u[0],g=s[c],p=g&&typeof g=="object"?g.args??g.input??g:void 0;e(c,r(p))}return}return}if(Array.isArray(t.tool_calls)){for(let s of t.tool_calls)e(s.name,r(s.input??s.arguments));return}let o=t.message??t;if(Array.isArray(o?.tool_calls)){for(let s of o.tool_calls)e(s.name,r(s.input??s.arguments));return}let a=o?.content??t.content;if(Array.isArray(a))for(let s of a)(s.type==="tool_use"||s.type==="tool_call")&&s.name&&e(s.name,r(s.input??s.arguments))}extractText(t){if(t.type==="assistant"&&t.message?.content){let e=t.message.content;if(Array.isArray(e))return e.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return t.type==="thinking"&&t.text||t.text?t.text:t.content&&typeof t.content=="string"?t.content:t.delta?t.delta:null}tryExtractResult(t){if(!t||typeof t!="string")return;let e=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,o;for(;(o=r.exec(t))!==null;){let f=o[1].trim();try{JSON.parse(f),e.push({text:f,source:"markdown"})}catch{}}let a=0,s=0;for(;a<t.length&&(a=t.indexOf("{",a),a!==-1);){let f=0,h=a;for(let S=a;S<t.length;S++)if(t[S]==="{")f++;else if(t[S]==="}"&&(f--,f===0)){h=S,e.push({text:t.substring(a,h+1),source:"brace"}),s++;break}a=h+1}let u=this.extractedResult,c=u?JSON.stringify(u).length:0,g=0,p=-1;for(let f=0;f<e.length;f++){let h=e[f];try{let S=h.text.replace(/,(\s*[}\]])/g,"$1"),b=JSON.parse(S);this.isValidResult(b)&&(g++,c=JSON.stringify(b).length,u=b,p=f)}catch{}}u&&(this.extractedResult=u)}isValidResult(t){if(!t||typeof t!="object"||Array.isArray(t)||t.session_id||t.timestamp_ms||t.type||t.call_id||t.tool_call||t.result&&typeof t.result=="object"&&(t.result.success&&typeof t.result.success=="object"||t.result.error&&typeof t.result.error=="object")||t.args&&typeof t.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(t),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(t,e=null){let r=new n;r.zodSchema=e,r.processChunk(t),r.flush();let o=r.getResult();return!o&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",t?.length||0,"chars"),o}};import{zodToJsonSchema as vt}from"zod-to-json-schema";var Q=class{static generateFileOutputInstructions(t,e){let r;typeof t?.parse=="function"?r=vt(t,{target:"openApi3"}):r=t;let o=this._buildExample(r);return`
5
5
  \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
6
6
  \u{1F6A8} MANDATORY: WRITE RESULT TO FILE \u{1F6A8}
7
7
  \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
@@ -14,14 +14,14 @@ DO NOT just output JSON to stdout. The file MUST exist when you finish.
14
14
  DO NOT skip this step. The workflow WILL FAIL if the file is missing.
15
15
 
16
16
  Required JSON structure:
17
- ${JSON.stringify(s,null,2)}
17
+ ${JSON.stringify(o,null,2)}
18
18
 
19
19
  JSON types (strict \u2014 validators reject wrong types):
20
20
  - Use bare JSON numbers for numeric fields (e.g. 3000). Do NOT quote them as strings (wrong: "3000").
21
21
  - Use true/false without quotes for booleans.
22
22
  - Use unquoted null where a field may be null.
23
23
 
24
- Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(t){if(!t)return{};let e=t.type;if(e==="object"&&t.properties){let r={};for(let[s,u]of Object.entries(t.properties))r[s]=this._buildExample(u);return r}if(e==="array"&&t.items)return[this._buildExample(t.items)];if(t.enum&&Array.isArray(t.enum)&&t.enum.length>0)return`<${t.enum.join("|")}>`;if(e==="string")return"<string>";if(e==="number"||e==="integer")return 0;if(e==="boolean")return!1;if(t.description)return`<${t.description}>`;if(t.nullable||t.oneOf||t.anyOf){let r=t.oneOf?.find(s=>s.type!=="null")||t.anyOf?.find(s=>s.type!=="null");return r?this._buildExample(r):null}return"<value>"}};var tt=class n{constructor(t=""){this.userPrompt=t,this.systemInstructions=[],this.metadata={}}setUserPrompt(t){return this.userPrompt=t,this}appendUserPrompt(t){return this.userPrompt?this.userPrompt+=`
24
+ Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(t){if(!t)return{};let e=t.type;if(e==="object"&&t.properties){let r={};for(let[o,a]of Object.entries(t.properties))r[o]=this._buildExample(a);return r}if(e==="array"&&t.items)return[this._buildExample(t.items)];if(t.enum&&Array.isArray(t.enum)&&t.enum.length>0)return`<${t.enum.join("|")}>`;if(e==="string")return"<string>";if(e==="number"||e==="integer")return 0;if(e==="boolean")return!1;if(t.description)return`<${t.description}>`;if(t.nullable||t.oneOf||t.anyOf){let r=t.oneOf?.find(o=>o.type!=="null")||t.anyOf?.find(o=>o.type!=="null");return r?this._buildExample(r):null}return"<value>"}};var tt=class n{constructor(t=""){this.userPrompt=t,this.systemInstructions=[],this.metadata={}}setUserPrompt(t){return this.userPrompt=t,this}appendUserPrompt(t){return this.userPrompt?this.userPrompt+=`
25
25
 
26
26
  ${t}`:this.userPrompt=t,this}addSkillHints(t){return t&&this.systemInstructions.push({type:"skill_hints",content:t,position:"prepend"}),this}addStructuredOutput(t,e){if(t&&e){let r=Q.generateFileOutputInstructions(t,e);this.systemInstructions.push({type:"structured_output",content:r,position:"append"}),this.metadata.structuredOutputPath=e}return this}addExtraInstructions(t){if(t?.trim()){let e=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
27
27
  \u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
@@ -29,30 +29,30 @@ ${t}`:this.userPrompt=t,this}addSkillHints(t){return t&&this.systemInstructions.
29
29
 
30
30
  ${t.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:e,position:"append"})}return this}addSkillFragments(t){return t&&t.length>0&&this.systemInstructions.push({type:"skill_fragments",content:t.join(`
31
31
 
32
- `),position:"append"}),this}addSystemInstruction(t,e="custom",r="append"){return t&&this.systemInstructions.push({type:e,content:t,position:r}),this}getUserPrompt(){return this.userPrompt}getSystemInstructions(){return this.systemInstructions}getMetadata(){return this.metadata}build(){let t=this.systemInstructions.filter(s=>s.position==="prepend").map(s=>s.content),e=this.systemInstructions.filter(s=>s.position==="append").map(s=>s.content);return[...t,this.userPrompt,...e].filter(Boolean).join(`
32
+ `),position:"append"}),this}addSystemInstruction(t,e="custom",r="append"){return t&&this.systemInstructions.push({type:e,content:t,position:r}),this}getUserPrompt(){return this.userPrompt}getSystemInstructions(){return this.systemInstructions}getMetadata(){return this.metadata}build(){let t=this.systemInstructions.filter(o=>o.position==="prepend").map(o=>o.content),e=this.systemInstructions.filter(o=>o.position==="append").map(o=>o.content);return[...t,this.userPrompt,...e].filter(Boolean).join(`
33
33
 
34
- `)}getStats(){let t=this.userPrompt.length,e=this.build().length;return{userPromptLength:t,fullPromptLength:e,systemInstructionsLength:e-t,instructionCount:this.systemInstructions.length,instructionTypes:this.systemInstructions.map(r=>r.type)}}clone(){let t=new n(this.userPrompt);return t.systemInstructions=[...this.systemInstructions],t.metadata={...this.metadata},t}};import Nt from"axios";import{homedir as Ct}from"node:os";import{join as Lt}from"node:path";import{existsSync as kt,readFileSync as Ut}from"node:fs";import{toJSONSchema as Mt}from"zod";function Dt(){if(process.env.OPENAI_PROXY_TOKEN)return i.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return i.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let n=Lt(Ct(),".zibby","config.json");if(kt(n)){let t=JSON.parse(Ut(n,"utf-8"));if(t.sessionToken)return i.debug("[Auth] Using session token from zibby login"),t.sessionToken}}catch(n){i.debug(`[Auth] Could not read zibby login session: ${n.message}`)}return null}function Wt(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function F(n){if(!(typeof n!="object"||n===null)){if(Object.keys(n).length===0){n.type="object",n.additionalProperties=!0;return}if(n.type||(n.properties?n.type="object":n.items&&(n.type="array")),n.type==="object")if(n.properties){for(let[t,e]of Object.entries(n.properties))e.type==="object"&&e.additionalProperties&&e.additionalProperties!==!1&&(!e.properties||Object.keys(e.properties).length===0)&&(n.properties[t]={type:["object","null"]});n.additionalProperties=!1,n.required=Object.keys(n.properties),Object.values(n.properties).forEach(F)}else"additionalProperties"in n||(n.additionalProperties=!0);n.type==="array"&&n.items&&F(n.items),n.anyOf&&n.anyOf.forEach(F),n.oneOf&&n.oneOf.forEach(F),n.allOf&&n.allOf.forEach(F)}}async function dt(n,t){i.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let e=Dt();if(!e)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=Wt();i.info(`\u{1F517} Using OpenAI proxy: ${r}`);let s=Mt(t),u=s;if(s.$ref&&s.definitions){let p=s.$ref.split("/").pop();u=s.definitions[p]||s,i.debug(`Extracted schema from $ref: ${p}`)}delete u.$schema,F(u);let o=4e5,a=n;n.length>o&&(i.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${n.length} chars) exceeds limit, keeping last ${o} chars`),a=`... [truncated early content] ...
35
- ${n.slice(-o)}`);let c=`Extract and format the following information into structured JSON matching the schema.
34
+ `)}getStats(){let t=this.userPrompt.length,e=this.build().length;return{userPromptLength:t,fullPromptLength:e,systemInstructionsLength:e-t,instructionCount:this.systemInstructions.length,instructionTypes:this.systemInstructions.map(r=>r.type)}}clone(){let t=new n(this.userPrompt);return t.systemInstructions=[...this.systemInstructions],t.metadata={...this.metadata},t}};import Pt from"axios";import{homedir as Nt}from"node:os";import{join as Ct}from"node:path";import{existsSync as Lt,readFileSync as kt}from"node:fs";import{toJSONSchema as Ut}from"zod";function Mt(){if(process.env.OPENAI_PROXY_TOKEN)return i.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return i.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let n=Ct(Nt(),".zibby","config.json");if(Lt(n)){let t=JSON.parse(kt(n,"utf-8"));if(t.sessionToken)return i.debug("[Auth] Using session token from zibby login"),t.sessionToken}}catch(n){i.debug(`[Auth] Could not read zibby login session: ${n.message}`)}return null}function Dt(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function F(n){if(!(typeof n!="object"||n===null)){if(Object.keys(n).length===0){n.type="object",n.additionalProperties=!0;return}if(n.type||(n.properties?n.type="object":n.items&&(n.type="array")),n.type==="object")if(n.properties){for(let[t,e]of Object.entries(n.properties))e.type==="object"&&e.additionalProperties&&e.additionalProperties!==!1&&(!e.properties||Object.keys(e.properties).length===0)&&(n.properties[t]={type:["object","null"]});n.additionalProperties=!1,n.required=Object.keys(n.properties),Object.values(n.properties).forEach(F)}else"additionalProperties"in n||(n.additionalProperties=!0);n.type==="array"&&n.items&&F(n.items),n.anyOf&&n.anyOf.forEach(F),n.oneOf&&n.oneOf.forEach(F),n.allOf&&n.allOf.forEach(F)}}async function ft(n,t){i.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let e=Mt();if(!e)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=Dt();i.info(`\u{1F517} Using OpenAI proxy: ${r}`);let o=Ut(t),a=o;if(o.$ref&&o.definitions){let p=o.$ref.split("/").pop();a=o.definitions[p]||o,i.debug(`Extracted schema from $ref: ${p}`)}delete a.$schema,F(a);let s=4e5,u=n;n.length>s&&(i.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${n.length} chars) exceeds limit, keeping last ${s} chars`),u=`... [truncated early content] ...
35
+ ${n.slice(-s)}`);let c=`Extract and format the following information into structured JSON matching the schema.
36
36
 
37
37
  RAW CONTENT:
38
- ${a}
38
+ ${u}
39
39
 
40
- 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.`,g={model:z.OPENAI_POSTPROCESSING,messages:[{role:"user",content:c}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:u,strict:!0}}};i.info(`\u{1F4E4} Sending to OpenAI proxy: model=${z.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(u.properties||{}).join(", ")}`),i.debug(` Schema size: ${JSON.stringify(u).length} chars`),i.debug(` Prompt size: ${c.length} chars`);try{let p={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(p["x-proxy-token"]=e,p["x-execution-id"]=process.env.EXECUTION_ID||""):(p.Authorization=`Bearer ${e}`,p["x-api-key"]=process.env.ZIBBY_API_KEY||"",p["x-execution-id"]=process.env.EXECUTION_ID||"");let h=(await Nt.post(r,g,{headers:p,timeout:X.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!h)throw new Error("OpenAI proxy returned empty response");let S=JSON.parse(h);return i.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:S,raw:n}}catch(p){if(p.response){let f=p.response.status,h=p.response.data;throw i.error(`\u274C OpenAI proxy request failed: ${f}`),i.error(` Status: ${f}`),i.error(` Response: ${JSON.stringify(h,null,2)}`),f===401||f===403?new Error(`Authentication failed for OpenAI proxy.
40
+ 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.`,g={model:z.OPENAI_POSTPROCESSING,messages:[{role:"user",content:c}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:a,strict:!0}}};i.info(`\u{1F4E4} Sending to OpenAI proxy: model=${z.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(a.properties||{}).join(", ")}`),i.debug(` Schema size: ${JSON.stringify(a).length} chars`),i.debug(` Prompt size: ${c.length} chars`);try{let p={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(p["x-proxy-token"]=e,p["x-execution-id"]=process.env.EXECUTION_ID||""):(p.Authorization=`Bearer ${e}`,p["x-api-key"]=process.env.ZIBBY_API_KEY||"",p["x-execution-id"]=process.env.EXECUTION_ID||"");let h=(await Pt.post(r,g,{headers:p,timeout:X.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!h)throw new Error("OpenAI proxy returned empty response");let S=JSON.parse(h);return i.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:S,raw:n}}catch(p){if(p.response){let f=p.response.status,h=p.response.data;throw i.error(`\u274C OpenAI proxy request failed: ${f}`),i.error(` Status: ${f}`),i.error(` Response: ${JSON.stringify(h,null,2)}`),f===401||f===403?new Error(`Authentication failed for OpenAI proxy.
41
41
  Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
42
- Response: ${JSON.stringify(h)}`,{cause:p}):new Error(`Failed to format Cursor output: ${h?.error?.message||"Unknown error"}`,{cause:p})}throw i.error(`\u274C OpenAI proxy request failed: ${p.message}`),new Error(`Failed to format output: ${p.message}`,{cause:p})}}import w from"chalk";var Ft="__WORKFLOW_GRAPH_LOG__",H=w.gray("\u2502"),Bt=w.gray("\u250C"),gt=w.gray("\u2514"),ot=w.green("\u25C6"),ht=w.hex("#c084fc")("\u25C6"),mt=w.hex("#2dd4bf")("\u25C6"),st=w.red("\u25C6"),_t=`${H} `,yt=2;function St(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function Ot(n,t){return(e,r,s)=>{if(typeof e!="string")return n(e,r,s);let u=process.stdout.columns||120,o="";for(let a=0;a<e.length;a++){let c=e[a];t.lineStart&&(o+=_t,t.col=yt,t.lineStart=!1),c===`
43
- `?(o+=c,t.lineStart=!0,t.col=0,t.inEsc=!1):c==="\x1B"?(t.inEsc=!0,o+=c):t.inEsc?(o+=c,(c>="A"&&c<="Z"||c>="a"&&c<="z")&&(t.inEsc=!1)):(t.col++,o+=c,t.col>=u&&(o+=`
44
- ${_t}`,t.col=yt))}return n(o,r,s)}}var nt=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null;let t=String(process.env.ZIBBY_RUN_SOURCE||"").trim().toLowerCase(),e=String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1";this._emitWorkflowGraphMarkers=e||t==="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 t={lineStart:!0,col:0,inEsc:!1},e={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=e,process.stdout.write=Ot(this._origStdoutWrite,t),process.stderr.write=Ot(this._origStderrWrite,e)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
42
+ Response: ${JSON.stringify(h)}`,{cause:p}):new Error(`Failed to format Cursor output: ${h?.error?.message||"Unknown error"}`,{cause:p})}throw i.error(`\u274C OpenAI proxy request failed: ${p.message}`),new Error(`Failed to format output: ${p.message}`,{cause:p})}}import w from"chalk";var Wt="__WORKFLOW_GRAPH_LOG__",H=w.gray("\u2502"),Ft=w.gray("\u250C"),dt=w.gray("\u2514"),st=w.green("\u25C6"),gt=w.hex("#c084fc")("\u25C6"),ht=w.hex("#2dd4bf")("\u25C6"),ot=w.red("\u25C6"),mt=`${H} `,_t=2;function yt(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function St(n,t){return(e,r,o)=>{if(typeof e!="string")return n(e,r,o);let a=process.stdout.columns||120,s="";for(let u=0;u<e.length;u++){let c=e[u];t.lineStart&&(s+=mt,t.col=_t,t.lineStart=!1),c===`
43
+ `?(s+=c,t.lineStart=!0,t.col=0,t.inEsc=!1):c==="\x1B"?(t.inEsc=!0,s+=c):t.inEsc?(s+=c,(c>="A"&&c<="Z"||c>="a"&&c<="z")&&(t.inEsc=!1)):(t.col++,s+=c,t.col>=a&&(s+=`
44
+ ${mt}`,t.col=_t))}return n(s,r,o)}}var nt=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null;let t=String(process.env.ZIBBY_RUN_SOURCE||"").trim().toLowerCase(),e=String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1";this._emitWorkflowGraphMarkers=e||t==="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 t={lineStart:!0,col:0,inEsc:!1},e={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=e,process.stdout.write=St(this._origStdoutWrite,t),process.stderr.write=St(this._origStderrWrite,e)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
45
45
  `),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
46
46
  `),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(t){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${t}
47
- `)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${Ft}${JSON.stringify(t)}
47
+ `)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${Wt}${JSON.stringify(t)}
48
48
  `;this._origStdoutWrite?this._origStdoutWrite(e):process.stdout.write(e)}_writeDot(t,e){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
49
49
  `),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${t} ${e}
50
50
  `)):process.stdout.write.bind(process.stdout)(`${t} ${e}
51
- `)}step(t){this._origStdoutWrite?this._writeDot(ot,t):process.stdout.write.bind(process.stdout)(`${H} ${ot} ${t}
52
- `)}stepTool(t){this._origStdoutWrite?this._writeDot(ht,t):process.stdout.write.bind(process.stdout)(`${H} ${ht} ${t}
53
- `)}stepMemory(t){let e=w.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(mt,e):process.stdout.write.bind(process.stdout)(`${H} ${mt} ${e}
54
- `)}stepFail(t){this._origStdoutWrite?this._writeDot(st,w.red(t)):process.stdout.write.bind(process.stdout)(`${H} ${st} ${w.red(t)}
55
- `)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Bt} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:r,details:s}=e;if(s)for(let o of s)this._rawWrite(`${ot} ${o}`);let u=r?w.dim(` ${St(r)}`):"";this._rawWrite(`${gt} ${w.green("done")}${u}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,r={}){this._stopIntercepting();let{duration:s}=r,u=s?w.dim(` ${St(s)}`):"";this._rawWrite(`${st} ${w.red(e)}`),this._rawWrite(`${gt} ${w.red("failed")}${u}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(w.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){this._rawWrite(w.green.bold("\u2713 Workflow completed"))}},it=new nt;import{copyFileSync as Jt,existsSync as lt,lstatSync as Gt,mkdirSync as Et,rmSync as Kt,symlinkSync as zt,unlinkSync as Ht}from"node:fs";import{join as k}from"node:path";import{homedir as Yt}from"node:os";import{randomBytes as jt}from"node:crypto";var Zt=["cli-config.json","config.json","auth.json","argv.json"];function wt(n){return!(!n||typeof n!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function It(n){let t=k(n||process.cwd(),".zibby","tmp");Et(t,{recursive:!0});let e=`${process.pid}-${Date.now()}-${jt(4).toString("hex")}`,r=k(t,`cursor-agent-home-${e}`),s=k(r,".cursor");Et(s,{recursive:!0});let u=Yt(),o=k(u,".cursor");if(lt(o))for(let a of Zt){let c=k(o,a);if(lt(c))try{Jt(c,k(s,a))}catch{}}if(process.platform==="darwin"){let a=k(u,"Library");if(lt(a))try{zt(a,k(r,"Library"))}catch{}}return r}function bt(n){if(!(!n||typeof n!="string"))try{let t=k(n,"Library");try{Gt(t).isSymbolicLink()&&Ht(t)}catch{}Kt(n,{recursive:!0,force:!0})}catch{}}var vt=class extends V{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(t){let e=[v(j(),".local","bin","cursor-agent"),v(j(),".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 e)try{if(r.startsWith("/")){Tt(r,Rt.X_OK);let s=D(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return i.debug(`[Cursor] Found agent at: ${r} (version: ${s.trim().slice(0,50)})`),!0}else{let s=D(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!s)continue;let u=D(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(u&&u.length>0)return i.debug(`[Cursor] Found '${r}' in PATH at ${s} (version: ${u.trim().slice(0,50)})`),!0}}catch{continue}return i.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(t,e={}){let{workspace:r=process.cwd(),print:s=!1,schema:u=null,skills:o=null,sessionPath:a=null,nodeName:c=null,timeout:g=X.CURSOR_AGENT_DEFAULT,config:p={}}=e,f=p?.agent?.strictMode||!1,h=e.model??p?.agent?.cursor?.model??z.CURSOR;i.debug(`[Cursor] Invoking (model: ${h}, timeout: ${g/1e3}s, skills: ${JSON.stringify(o)})`);let b=(this._setupMcpConfig(a,r,p,o,c)||{}).isolatedMcpHome??null,x=[v(j(),".local","bin","cursor-agent"),v(j(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],m=null;for(let l of x)try{if(l.startsWith("/"))Tt(l,Rt.X_OK),D(`"${l}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!D(`which ${l}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");D(`${l} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}m=l,i.debug(`[Agent] Using binary: ${l}`);break}catch(d){i.debug(`[Agent] Binary '${l}' check failed: ${d.message}`);continue}if(!m)throw new Error(`Cursor Agent CLI not found or not working.
51
+ `)}step(t){this._origStdoutWrite?this._writeDot(st,t):process.stdout.write.bind(process.stdout)(`${H} ${st} ${t}
52
+ `)}stepTool(t){this._origStdoutWrite?this._writeDot(gt,t):process.stdout.write.bind(process.stdout)(`${H} ${gt} ${t}
53
+ `)}stepMemory(t){let e=w.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(ht,e):process.stdout.write.bind(process.stdout)(`${H} ${ht} ${e}
54
+ `)}stepFail(t){this._origStdoutWrite?this._writeDot(ot,w.red(t)):process.stdout.write.bind(process.stdout)(`${H} ${ot} ${w.red(t)}
55
+ `)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Ft} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:r,details:o}=e;if(o)for(let s of o)this._rawWrite(`${st} ${s}`);let a=r?w.dim(` ${yt(r)}`):"";this._rawWrite(`${dt} ${w.green("done")}${a}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,r={}){this._stopIntercepting();let{duration:o}=r,a=o?w.dim(` ${yt(o)}`):"";this._rawWrite(`${ot} ${w.red(e)}`),this._rawWrite(`${dt} ${w.red("failed")}${a}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(w.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){this._rawWrite(w.green.bold("\u2713 Workflow completed"))}},it=new nt;import{copyFileSync as Bt,existsSync as lt,lstatSync as Jt,mkdirSync as Ot,rmSync as Gt,symlinkSync as Kt,unlinkSync as zt}from"node:fs";import{join as k}from"node:path";import{homedir as Ht}from"node:os";import{randomBytes as Yt}from"node:crypto";var jt=["cli-config.json","config.json","auth.json","argv.json"];function Et(n){return!(!n||typeof n!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function wt(n){let t=k(n||process.cwd(),".zibby","tmp");Ot(t,{recursive:!0});let e=`${process.pid}-${Date.now()}-${Yt(4).toString("hex")}`,r=k(t,`cursor-agent-home-${e}`),o=k(r,".cursor");Ot(o,{recursive:!0});let a=Ht(),s=k(a,".cursor");if(lt(s))for(let u of jt){let c=k(s,u);if(lt(c))try{Bt(c,k(o,u))}catch{}}if(process.platform==="darwin"){let u=k(a,"Library");if(lt(u))try{Kt(u,k(r,"Library"))}catch{}}return r}function It(n){if(!(!n||typeof n!="string"))try{let t=k(n,"Library");try{Jt(t).isSymbolicLink()&&zt(t)}catch{}Gt(n,{recursive:!0,force:!0})}catch{}}var Rt=class extends V{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(t){let e=[v(j(),".local","bin","cursor-agent"),v(j(),".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 e)try{if(r.startsWith("/")){At(r,Tt.X_OK);let o=D(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(o&&o.length>0)return i.debug(`[Cursor] Found agent at: ${r} (version: ${o.trim().slice(0,50)})`),!0}else{let o=D(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!o)continue;let a=D(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(a&&a.length>0)return i.debug(`[Cursor] Found '${r}' in PATH at ${o} (version: ${a.trim().slice(0,50)})`),!0}}catch{continue}return i.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(t,e={}){let{workspace:r=process.cwd(),print:o=!1,schema:a=null,skills:s=null,sessionPath:u=null,nodeName:c=null,timeout:g=X.CURSOR_AGENT_DEFAULT,config:p={}}=e,f=p?.agent?.strictMode||!1,h=e.model??p?.agent?.cursor?.model??z.CURSOR;i.debug(`[Cursor] Invoking (model: ${h}, timeout: ${g/1e3}s, skills: ${JSON.stringify(s)})`);let b=(this._setupMcpConfig(u,r,p,s,c)||{}).isolatedMcpHome??null,x=[v(j(),".local","bin","cursor-agent"),v(j(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],m=null;for(let l of x)try{if(l.startsWith("/"))At(l,Tt.X_OK),D(`"${l}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!D(`which ${l}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");D(`${l} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}m=l,i.debug(`[Agent] Using binary: ${l}`);break}catch(d){i.debug(`[Agent] Binary '${l}' check failed: ${d.message}`);continue}if(!m)throw new Error(`Cursor Agent CLI not found or not working.
56
56
 
57
57
  Checked paths:
58
58
  ${x.map(l=>` - ${l}`).join(`
@@ -64,28 +64,28 @@ Install cursor-agent:
64
64
  Then add to PATH:
65
65
  echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
66
66
 
67
- Test with: agent --version`);let A=new tt(t),I=null;if(u){let l=`zibby-result-${Date.now()}.json`;I=v(r,".zibby","tmp",l);let d=v(r,".zibby","tmp");Y(d)||At(d,{recursive:!0}),A.addStructuredOutput(u,I)}let U=process.env.CURSOR_API_KEY,Z=U?` | key: ***${U.slice(-4)}`:" | key: not set";console.log(`
67
+ Test with: agent --version`);let A=new tt(t),I=null;if(a){let l=`zibby-result-${Date.now()}.json`;I=v(r,".zibby","tmp",l);let d=v(r,".zibby","tmp");Y(d)||xt(d,{recursive:!0}),A.addStructuredOutput(a,I)}let U=process.env.CURSOR_API_KEY,Z=U?` | key: ***${U.slice(-4)}`:" | key: not set";console.log(`
68
68
  \u25C6 Model: ${h||"auto"}${Z}
69
69
  `);let M=(await import("chalk")).default,B=A.getUserPrompt();console.log(`
70
70
  ${M.bold("Prompt sent to LLM:")}`),console.log(M.dim("\u2500".repeat(60))),console.log(M.dim(B)),console.log(M.dim("\u2500".repeat(60)));let y=A.build(),P=A.getStats(),L=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",h||"auto"];if(process.env.CURSOR_API_KEY&&L.push("--api-key",process.env.CURSOR_API_KEY),L.push(y),i.debug(`[Agent] User prompt: ${P.userPromptLength} chars, System instructions: ${P.systemInstructionsLength} chars (${P.instructionCount} blocks), Full: ${P.fullPromptLength} chars, model: ${h||"auto"}`),i.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${h||"auto"} (from .zibby.config.js agent.cursor.model)
71
- `)}catch{}let J,T=null;try{let l=a||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);J=await this._spawnWithStreaming(m,L,r,g,null,l,b)}catch(l){T=l}let N=J?.stdout||"";if(u){let l=typeof u.parse=="function",d=null,_=!!(I&&Y(I));if(I&&i.info(`[Agent] Result file: ${_?"present":"missing"} at ${I}`),_)try{let O=xt(I,"utf-8").trim();d=JSON.parse(O),i.info(`[Agent] Parsed JSON from result file OK (${O.length} chars) \u2192 object ready for validation`),T&&i.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(O){i.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${O.message}`)}else if(T)i.warn(`[Agent] Result file missing at ${I} (agent process error \u2014 may still recover if strictMode repairs)`);else throw i.error(`\u274C [Agent] Result file was never created at ${I}`),new Error(`Agent did not write required result file at ${I}`);if(d&&l)try{let O=u.parse(d);return i.info("\u2705 [Agent] Zod validation passed for structured result file"),f&&i.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:N,structured:O}}catch(O){let $=O.issues?O.issues.map(R=>` - ${R.path.join(".")}: ${R.message}`).join(`
71
+ `)}catch{}let J,T=null;try{let l=u||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);J=await this._spawnWithStreaming(m,L,r,g,null,l,b)}catch(l){T=l}let N=J?.stdout||"";if(a){let l=typeof a.parse=="function",d=null,_=!!(I&&Y(I));if(I&&i.info(`[Agent] Result file: ${_?"present":"missing"} at ${I}`),_)try{let O=$t(I,"utf-8").trim();d=JSON.parse(O),i.info(`[Agent] Parsed JSON from result file OK (${O.length} chars) \u2192 object ready for validation`),T&&i.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(O){i.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${O.message}`)}else if(T)i.warn(`[Agent] Result file missing at ${I} (agent process error \u2014 may still recover if strictMode repairs)`);else throw i.error(`\u274C [Agent] Result file was never created at ${I}`),new Error(`Agent did not write required result file at ${I}`);if(d&&l)try{let O=a.parse(d);return i.info("\u2705 [Agent] Zod validation passed for structured result file"),f&&i.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:N,structured:O}}catch(O){let $=O.issues?O.issues.map(R=>` - ${R.path.join(".")}: ${R.message}`).join(`
72
72
  `):O.message?.slice(0,400);if(i.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
73
73
  ${$}`),i.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
74
74
  ${JSON.stringify(d,null,2).slice(0,500)}`),!f)throw new Error(`Agent output failed schema validation:
75
75
  ${$}
76
76
 
77
77
  The agent wrote invalid data that doesn't match the required outputSchema.
78
- Enable strictMode in .zibby.config.js for automatic repair.`,{cause:O})}else{if(d)return i.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),f&&i.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:N,structured:d};_&&i.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(f&&!T){let O=J.parsedText,$=d?JSON.stringify(d):O;i.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${$.length} chars in)`);try{let R=await dt($,u);if(l){let G=u.parse(R.structured);return i.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:N,structured:G}}return{raw:N,...R}}catch(R){if(i.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${R.message}`),d)return i.warn("[Agent] Using agent's original result file as fallback"),{raw:N,structured:d}}}if(T)throw T;let E=_?d==null?"file existed but JSON.parse failed \u2014 see WARN log above":l?"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 i.error(`\u274C [Agent] No validated structured output: ${E}`),i.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 ${I}. Enable strictMode for proxy fallback.`)}if(T)throw T;return this._extractFinalResult(N)||J?.parsedText||N}_extractFinalResult(t){if(!t)return null;let e=t.split(`
79
- `),r=null;for(let s of e){let u=s.trim();if(u)try{let o=JSON.parse(u);if(o.type==="assistant"&&o.message?.content){let a=o.message.content;if(Array.isArray(a)){let c=a.filter(g=>g.type==="text"&&g.text).map(g=>g.text).join("");c&&(r=c)}else typeof a=="string"&&a&&(r=a)}}catch{}}return r?.trim()||null}_setupMcpConfig(t,e,r,s=null,u=null){let o=r?.headless,a=v(j(),".cursor"),c=v(a,"mcp.json"),g={};if(Y(c))try{g=JSON.parse(xt(c,"utf-8"))}catch{}let p=g.mcpServers||{},f=r?.paths?.output||ut,h=v(e||process.cwd(),f,at),S=Array.isArray(s)?s.map(m=>rt(m)).filter(Boolean):[...ft()].map(([,m])=>m),b=new Set;for(let m of S)typeof m.resolve=="function"&&(b.has(m.serverName)||(b.add(m.serverName),this._ensureSkillConfigured(p,m,t,h,u,o)));if(t){let m=rt("browser");m&&typeof m.resolve=="function"&&!b.has(m.serverName)&&this._ensureSkillConfigured(p,m,t,h,"execute_live",o)}if(Object.keys(p).length===0)return i.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let x=`${JSON.stringify({mcpServers:p},null,2)}
80
- `;if(wt(t)){let m=It(e||process.cwd()),A=v(m,".cursor","mcp.json");return $t(A,x,"utf8"),i.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${m} | servers: ${Object.keys(p).join(", ")}`),{isolatedMcpHome:m}}return Y(a)||At(a,{recursive:!0}),$t(c,x,"utf8"),i.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(p).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(t,e,r,s,u=null,o){let a=e.cursorKey||e.serverName,c=t[a]?a:t[e.serverName]?e.serverName:null;if(c&&r){let p=typeof e.resolve=="function"?e.resolve({sessionPath:r,nodeName:u,headless:o}):null;p?.args?t[c].args=p.args:t[c].args=(t[c].args||[]).map(S=>S.startsWith("--output-dir=")?`--output-dir=${r}`:S);let f=p?.env||{},h=e.sessionEnvKey?{[e.sessionEnvKey]:s}:{};t[c].env={...t[c].env||{},...f,...h},i.debug(`[MCP] Updated ${c} session \u2192 ${r}`);return}if(c)return;let g=e.resolve({sessionPath:r,nodeName:u,headless:o});g&&(t[a]={...g,...e.sessionEnvKey&&{env:{...g.env||{},[e.sessionEnvKey]:s}}},i.debug(`[MCP] Configured ${a}`))}_spawnWithStreaming(t,e,r,s,u=null,o=null,a=null){return new Promise((c,g)=>{let p=Date.now(),f="",h="",S=Date.now(),b=0,x=!1,m=null,A=!1,I=!1,U=null;if(o)try{U=v(qt(String(o)),ct)}catch{U=null}let Z=!1,M=()=>{Z||(Z=!0,bt(a))},B={...process.env};a&&(B.HOME=a,process.platform==="win32"&&(B.USERPROFILE=a),i.debug(`[Agent] cursor-agent HOME=${a} (isolated MCP config)`));let y=Vt(t,e,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:B});i.debug(`[Agent] PID: ${y.pid}`),y.stdin.on("error",l=>{l.code!=="EPIPE"&&i.warn(`[Agent] stdin error: ${l.message}`)}),y.stdout.on("error",l=>{l.code!=="EPIPE"&&i.warn(`[Agent] stdout error: ${l.message}`)}),y.stderr.on("error",l=>{l.code!=="EPIPE"&&i.warn(`[Agent] stderr error: ${l.message}`)}),u?(y.stdin.write(u,l=>{l&&l.code!=="EPIPE"&&i.warn(`[Agent] Failed to write to stdin: ${l.message}`),y.stdin.end()}),i.debug(`[Agent] Prompt also piped to stdin (${u.length} chars)`)):y.stdin.end();let P=null;U&&(P=setInterval(()=>{if(!(x||I))try{if(Y(U)){x=!0,m="studio-stop";try{Xt(U)}catch{}i.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 L=new Set,J=new Date(p).toISOString().replace(/\.\d+Z$/,""),T=setInterval(()=>{let l=Math.round((Date.now()-p)/1e3),d=Math.round((Date.now()-S)/1e3),_=[];try{let O=Math.ceil(l/60)+1,$=D(`find "${r}" -type f -mmin -${O} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if($)for(let R of $.split(`
78
+ Enable strictMode in .zibby.config.js for automatic repair.`,{cause:O})}else{if(d)return i.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),f&&i.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:N,structured:d};_&&i.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(f&&!T){let O=J.parsedText,$=d?JSON.stringify(d):O;i.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${$.length} chars in)`);try{let R=await ft($,a);if(l){let G=a.parse(R.structured);return i.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:N,structured:G}}return{raw:N,...R}}catch(R){if(i.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${R.message}`),d)return i.warn("[Agent] Using agent's original result file as fallback"),{raw:N,structured:d}}}if(T)throw T;let E=_?d==null?"file existed but JSON.parse failed \u2014 see WARN log above":l?"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 i.error(`\u274C [Agent] No validated structured output: ${E}`),i.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 ${I}. Enable strictMode for proxy fallback.`)}if(T)throw T;return this._extractFinalResult(N)||J?.parsedText||N}_extractFinalResult(t){if(!t)return null;let e=t.split(`
79
+ `),r=null;for(let o of e){let a=o.trim();if(a)try{let s=JSON.parse(a);if(s.type==="assistant"&&s.message?.content){let u=s.message.content;if(Array.isArray(u)){let c=u.filter(g=>g.type==="text"&&g.text).map(g=>g.text).join("");c&&(r=c)}else typeof u=="string"&&u&&(r=u)}}catch{}}return r?.trim()||null}_setupMcpConfig(t,e,r,o=null,a=null){let s=r?.headless,u=v(j(),".cursor"),c=v(u,"mcp.json"),g={};if(Y(c))try{g=JSON.parse($t(c,"utf-8"))}catch{}let p=g.mcpServers||{},f=r?.paths?.output||at,h=v(e||process.cwd(),f,ut),S=Array.isArray(o)?o.map(m=>rt(m)).filter(Boolean):[...pt()].map(([,m])=>m),b=new Set;for(let m of S)typeof m.resolve=="function"&&(b.has(m.serverName)||(b.add(m.serverName),this._ensureSkillConfigured(p,m,t,h,a,s)));if(t){let m=rt("browser");m&&typeof m.resolve=="function"&&!b.has(m.serverName)&&this._ensureSkillConfigured(p,m,t,h,"execute_live",s)}if(Object.keys(p).length===0)return i.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let x=`${JSON.stringify({mcpServers:p},null,2)}
80
+ `;if(Et(t)){let m=wt(e||process.cwd()),A=v(m,".cursor","mcp.json");return bt(A,x,"utf8"),i.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${m} | servers: ${Object.keys(p).join(", ")}`),{isolatedMcpHome:m}}return Y(u)||xt(u,{recursive:!0}),bt(c,x,"utf8"),i.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(p).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(t,e,r,o,a=null,s){let u=e.cursorKey||e.serverName,c=t[u]?u:t[e.serverName]?e.serverName:null;if(c&&r){let p=typeof e.resolve=="function"?e.resolve({sessionPath:r,nodeName:a,headless:s}):null;p?.args?t[c].args=p.args:t[c].args=(t[c].args||[]).map(S=>S.startsWith("--output-dir=")?`--output-dir=${r}`:S);let f=p?.env||{},h=e.sessionEnvKey?{[e.sessionEnvKey]:o}:{};t[c].env={...t[c].env||{},...f,...h},i.debug(`[MCP] Updated ${c} session \u2192 ${r}`);return}if(c)return;let g=e.resolve({sessionPath:r,nodeName:a,headless:s});g&&(t[u]={...g,...e.sessionEnvKey&&{env:{...g.env||{},[e.sessionEnvKey]:o}}},i.debug(`[MCP] Configured ${u}`))}_spawnWithStreaming(t,e,r,o,a=null,s=null,u=null){return new Promise((c,g)=>{let p=Date.now(),f="",h="",S=Date.now(),b=0,x=!1,m=null,A=!1,I=!1,U=null;if(s)try{U=v(Xt(String(s)),ct)}catch{U=null}let Z=!1,M=()=>{Z||(Z=!0,It(u))},B={...process.env};u&&(B.HOME=u,process.platform==="win32"&&(B.USERPROFILE=u),i.debug(`[Agent] cursor-agent HOME=${u} (isolated MCP config)`));let y=Zt(t,e,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:B});i.debug(`[Agent] PID: ${y.pid}`),y.stdin.on("error",l=>{l.code!=="EPIPE"&&i.warn(`[Agent] stdin error: ${l.message}`)}),y.stdout.on("error",l=>{l.code!=="EPIPE"&&i.warn(`[Agent] stdout error: ${l.message}`)}),y.stderr.on("error",l=>{l.code!=="EPIPE"&&i.warn(`[Agent] stderr error: ${l.message}`)}),a?(y.stdin.write(a,l=>{l&&l.code!=="EPIPE"&&i.warn(`[Agent] Failed to write to stdin: ${l.message}`),y.stdin.end()}),i.debug(`[Agent] Prompt also piped to stdin (${a.length} chars)`)):y.stdin.end();let P=null;U&&(P=setInterval(()=>{if(!(x||I))try{if(Y(U)){x=!0,m="studio-stop";try{Vt(U)}catch{}i.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 L=new Set,J=new Date(p).toISOString().replace(/\.\d+Z$/,""),T=setInterval(()=>{let l=Math.round((Date.now()-p)/1e3),d=Math.round((Date.now()-S)/1e3),_=[];try{let O=Math.ceil(l/60)+1,$=D(`find "${r}" -type f -mmin -${O} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if($)for(let R of $.split(`
81
81
  `)){let G=R.replace(`${r}/`,"");L.has(G)||(L.add(G),_.push(G))}}catch{}let E="";_.length>0&&(E=` | \u{1F4C1} new: ${_.map($=>$.split("/").pop()).join(", ")}`),L.size>0&&(E+=` | \u{1F4E6} total: ${L.size} files`),i.debug(`\u{1F493} [Agent] Running for ${l}s | ${b} lines output${E}`),b===0&&l>=30&&L.size===0&&(l<35&&i.warn(`\u26A0\uFE0F [Agent] No output after ${l}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),l>=60&&(x=!0,m=m||"stall",i.error(`\u274C [Agent] No response after ${l}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),N=setTimeout(()=>{x=!0,m=m||"timeout";let l=Math.round((Date.now()-p)/1e3);i.error(`\u23F1\uFE0F [Agent] Timeout after ${l}s \u2014 killing process (PID: ${y.pid})`),f.trim()&&i.warn(`\u{1F4E4} [Agent] Partial output (${f.length} chars) before timeout:
82
- ${f.slice(-2e3)}`),y.kill("SIGTERM"),setTimeout(()=>{y.killed||y.kill("SIGKILL")},5e3)},s),W=new q;W.onToolCall=(l,d)=>{let _=l,E=d;if(l==="mcpToolCall"&&d?.name)_=d.name.replace(/^mcp_+[^_]+_+/,""),_.includes("-")&&_.split("-")[0]===_.split("-")[1]&&(_=_.split("-")[0]),E=d.args??d.input??d;else{if(l==="readToolCall"||l==="editToolCall"||l==="writeToolCall")return;(l.startsWith("mcp__")||l.includes("ToolCall"))&&(_=l.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(_.includes("memory")?it.stepMemory(`Tool: ${_}`):it.stepTool(`Tool: ${_}`),E!=null&&typeof E=="object"&&Object.keys(E).length>0&&!I){let $=JSON.stringify(E),R=$.length>100?`${$.substring(0,100)}...`:$;console.log(` Input: ${R}`)}},y.stdout.on("data",l=>{let d=l.toString();f+=d,S=Date.now(),A||(A=!0);let _=W.processChunk(d);_&&!I&&process.stdout.write(_);let E=d.split(`
82
+ ${f.slice(-2e3)}`),y.kill("SIGTERM"),setTimeout(()=>{y.killed||y.kill("SIGKILL")},5e3)},o),W=new q;W.onToolCall=(l,d)=>{let _=l,E=d;if(l==="mcpToolCall"&&d?.name)_=d.name.replace(/^mcp_+[^_]+_+/,""),_.includes("-")&&_.split("-")[0]===_.split("-")[1]&&(_=_.split("-")[0]),E=d.args??d.input??d;else{if(l==="readToolCall"||l==="editToolCall"||l==="writeToolCall")return;(l.startsWith("mcp__")||l.includes("ToolCall"))&&(_=l.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(_.includes("memory")?it.stepMemory(`Tool: ${_}`):it.stepTool(`Tool: ${_}`),E!=null&&typeof E=="object"&&Object.keys(E).length>0&&!I){let $=JSON.stringify(E),R=$.length>100?`${$.substring(0,100)}...`:$;console.log(` Input: ${R}`)}},y.stdout.on("data",l=>{let d=l.toString();f+=d,S=Date.now(),A||(A=!0);let _=W.processChunk(d);_&&!I&&process.stdout.write(_);let E=d.split(`
83
83
  `).filter(O=>O.trim());b+=E.length}),y.stderr.on("data",l=>{let d=l.toString();h+=d,S=Date.now(),A||(A=!0);let _=d.split(`
84
- `).filter(E=>E.trim());for(let E of _)i.warn(`\u26A0\uFE0F [Agent stderr] ${E}`)}),y.on("close",(l,d)=>{I=!0,M(),clearTimeout(N),clearInterval(T),P&&clearInterval(P),W.flush();let _=Math.round((Date.now()-p)/1e3);if(i.debug(`[Agent] Exited: code=${l}, signal=${d}, elapsed=${_}s, output=${f.length} chars`),x){if(m==="studio-stop"){g(new Error("Stopped from Zibby Studio"));return}g(new Error(`Cursor Agent timed out after ${_}s (limit: ${s/1e3}s). ${b} lines produced. Last output ${Math.round((Date.now()-S)/1e3)}s ago. ${f.trim()?`
84
+ `).filter(E=>E.trim());for(let E of _)i.warn(`\u26A0\uFE0F [Agent stderr] ${E}`)}),y.on("close",(l,d)=>{I=!0,M(),clearTimeout(N),clearInterval(T),P&&clearInterval(P),W.flush();let _=Math.round((Date.now()-p)/1e3);if(i.debug(`[Agent] Exited: code=${l}, signal=${d}, elapsed=${_}s, output=${f.length} chars`),x){if(m==="studio-stop"){g(new Error("Stopped from Zibby Studio"));return}g(new Error(`Cursor Agent timed out after ${_}s (limit: ${o/1e3}s). ${b} lines produced. Last output ${Math.round((Date.now()-S)/1e3)}s ago. ${f.trim()?`
85
85
  Partial output (last 500 chars):
86
86
  ${f.slice(-500)}`:"No output captured."}`));return}if(l!==0){g(new Error(`Cursor Agent failed: exit code ${l}, signal ${d}. ${h.trim()?`
87
87
  Stderr: ${h.slice(-1e3)}`:""}${f.trim()?`
88
88
  Stdout (last 500 chars): ${f.slice(-500)}`:""}`));return}let E=W.getResult(),O=E?JSON.stringify(E,null,2):W.getRawText()||f||"";c({stdout:f||h||"",parsedText:O})}),y.on("error",l=>{M(),clearTimeout(N),clearInterval(T),P&&clearInterval(P),g(new Error(`Cursor Agent spawn error: ${l.message}
89
89
  Binary: ${t}
90
90
  This usually means the binary is not in PATH. Try:
91
- echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};export{vt as CursorAgentStrategy};
91
+ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};export{Rt as CursorAgentStrategy};