@zibby/core 0.1.48 → 0.2.0

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.
Files changed (41) hide show
  1. package/dist/index.js +100 -100
  2. package/dist/package.json +2 -2
  3. package/dist/register-built-in-strategies.js +52 -52
  4. package/dist/strategies/assistant-strategy.js +1 -1
  5. package/dist/strategies/claude-strategy.js +3 -3
  6. package/dist/strategies/codex-strategy.js +3 -3
  7. package/dist/strategies/cursor-strategy.js +30 -30
  8. package/dist/strategies/gemini-strategy.js +13 -13
  9. package/dist/strategies/index.js +57 -57
  10. package/dist/templates/browser-test-automation/README.md +136 -0
  11. package/dist/templates/browser-test-automation/chat.mjs +36 -0
  12. package/dist/templates/browser-test-automation/graph.mjs +54 -0
  13. package/dist/templates/browser-test-automation/nodes/execute-live.mjs +222 -0
  14. package/dist/templates/browser-test-automation/nodes/generate-script.mjs +97 -0
  15. package/dist/templates/browser-test-automation/nodes/index.mjs +3 -0
  16. package/dist/templates/browser-test-automation/nodes/preflight.mjs +59 -0
  17. package/dist/templates/browser-test-automation/nodes/utils.mjs +297 -0
  18. package/dist/templates/browser-test-automation/pipeline-ids.js +12 -0
  19. package/dist/templates/browser-test-automation/result-handler.mjs +327 -0
  20. package/dist/templates/browser-test-automation/run-index.mjs +418 -0
  21. package/dist/templates/browser-test-automation/run_test.json +358 -0
  22. package/dist/templates/code-analysis/graph.js +72 -0
  23. package/dist/templates/code-analysis/index.js +18 -0
  24. package/dist/templates/code-analysis/nodes/analyze-ticket-node.js +204 -0
  25. package/dist/templates/code-analysis/nodes/create-pr-node.js +175 -0
  26. package/dist/templates/code-analysis/nodes/finalize-node.js +118 -0
  27. package/dist/templates/code-analysis/nodes/generate-code-node.js +425 -0
  28. package/dist/templates/code-analysis/nodes/generate-test-cases-node.js +376 -0
  29. package/dist/templates/code-analysis/nodes/services/prMetaService.js +86 -0
  30. package/dist/templates/code-analysis/nodes/setup-node.js +142 -0
  31. package/dist/templates/code-analysis/prompts/analyze-ticket.md +181 -0
  32. package/dist/templates/code-analysis/prompts/generate-code.md +33 -0
  33. package/dist/templates/code-analysis/prompts/generate-test-cases.md +110 -0
  34. package/dist/templates/code-analysis/state.js +40 -0
  35. package/dist/templates/code-implementation/graph.js +35 -0
  36. package/dist/templates/code-implementation/index.js +7 -0
  37. package/dist/templates/code-implementation/state.js +14 -0
  38. package/dist/templates/global-setup.js +56 -0
  39. package/dist/templates/index.js +94 -0
  40. package/dist/templates/register-nodes.js +24 -0
  41. package/package.json +2 -2
@@ -4,7 +4,7 @@ import{AgentStrategy as he,getSkill as F}from"@zibby/agent-workflow";import R fr
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 re}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as ie}from"@modelcontextprotocol/sdk/client/stdio.js";var D=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 ie({command:s,args:o,env:{...process.env,...r}}),i=new re({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
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{existsSync as le,readFileSync as ae}from"node:fs";import{join as ce}from"node:path";import{homedir as ue}from"node:os";function fe(){try{let n=ce(ue(),".zibby","config.json");return le(n)?JSON.parse(ae(n,"utf-8")):{}}catch{return{}}}function j(n){return String(n||"").replace(/\/v1\/?$/,"")}function me(n,e){let t=process.env.OPENAI_PROXY_URL;if(t)return j(t);if(n==="session")return e.proxyUrl?j(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 j(s||"https://api.openai.com")}return j(t||"")}function V(){let n=fe(),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=me(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 z(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 de(n,e){if(typeof n=="string")return z(n,e);try{return z(JSON.stringify(n),e)}catch{return z(String(n),e)}}function Q(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 ge(n){let e=Array.isArray(n?.messages)?n.messages:[],t=e.find(r=>r.role==="system"),s=e.slice(-4).map(r=>({...r,content:z(r.content,r.role==="tool"?1200:2500)}));s=Q(s);let o={...n,messages:[t,...s].filter(Boolean)};return delete o.tools,o}async function pe({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=ge(n);return typeof l=="function"&&l(n,c),{data:e?await r(c,t,s):await o(c,t,s),fallback:c}}}async function ee({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=Q(n.messages));let T=await pe({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 I=await Promise.all(b.map((_,H)=>(typeof t.onToolCall=="function"&&t.onToolCall(_.name,_.args,{round:l,index:H,total:b.length}),f(_,o))));for(let _=0;_<b.length;_++){let se=b[_].name==="get_skill_context"?typeof I[_]=="string"?I[_]:JSON.stringify(I[_]):de(I[_],u);k.messages.push(h(b[_].id,se))}return typeof t.onToolCall=="function"&&t.onToolCall(null),C(k,r),{done:!1,body:k}}var ye=K.ASSISTANT,_e=15,Z="get_skill_context";function v(n){!n||typeof n!="object"||(n.type==="object"&&n.properties&&(n.required=Object.keys(n.properties),n.additionalProperties=!1,Object.values(n.properties).forEach(v)),n.type==="array"&&n.items&&v(n.items),n.anyOf&&n.anyOf.forEach(v),n.oneOf&&n.oneOf.forEach(v),n.allOf&&n.allOf.forEach(v))}var te={maxBytes:49e3,systemMaxChars:12e3},B=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Se=n=>Buffer.byteLength(JSON.stringify(n),"utf8");function J(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 oe=class extends he{#e;#t;#o=new D;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=B();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 ee({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)=>{B()&&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=F(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=F(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 B()&&(console.log(`
7
+ [tool result truncated for size]`}function de(n,e){if(typeof n=="string")return z(n,e);try{return z(JSON.stringify(n),e)}catch{return z(String(n),e)}}function Q(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 ge(n){let e=Array.isArray(n?.messages)?n.messages:[],t=e.find(r=>r.role==="system"),s=e.slice(-4).map(r=>({...r,content:z(r.content,r.role==="tool"?1200:2500)}));s=Q(s);let o={...n,messages:[t,...s].filter(Boolean)};return delete o.tools,o}async function pe({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=ge(n);return typeof l=="function"&&l(n,c),{data:e?await r(c,t,s):await o(c,t,s),fallback:c}}}async function ee({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=Q(n.messages));let T=await pe({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 I=await Promise.all(b.map((_,H)=>(typeof t.onToolCall=="function"&&t.onToolCall(_.name,_.args,{round:l,index:H,total:b.length}),f(_,o))));for(let _=0;_<b.length;_++){let se=b[_].name==="get_skill_context"?typeof I[_]=="string"?I[_]:JSON.stringify(I[_]):de(I[_],u);k.messages.push(h(b[_].id,se))}return typeof t.onToolCall=="function"&&t.onToolCall(null),C(k,r),{done:!1,body:k}}var ye=K.ASSISTANT,_e=15,Z="get_skill_context";function v(n){!n||typeof n!="object"||(n.type==="object"&&n.properties&&(n.required=Object.keys(n.properties),n.additionalProperties=!1,Object.values(n.properties).forEach(v)),n.type==="array"&&n.items&&v(n.items),n.anyOf&&n.anyOf.forEach(v),n.oneOf&&n.oneOf.forEach(v),n.allOf&&n.allOf.forEach(v))}var te={maxBytes:49e3,systemMaxChars:12e3},B=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Se=n=>Buffer.byteLength(JSON.stringify(n),"utf8");function J(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 oe=class extends he{#e;#t;#o=new D;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=B();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){let f=new Error("Aborted via signal");throw f.name="AbortError",f}let h=await ee({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)=>{B()&&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=F(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=F(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 B()&&(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
9
  `)),S}let i=r?.get(e.name)||null;if(!i)return`Unknown tool: ${e.name}`;let a=F(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})=>{B()&&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})=>{B()&&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,v(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||te.maxBytes),systemMaxChars:Number(t.systemMaxChars||te.systemMaxChars)}}#f(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:J(t.allowTools||e.allowTools),denyTools:J(t.denyTools||e.denyTools),denyPrefixes:Te(t.denyPrefixes||e.denyToolPrefixes),includeSkills:J(t.includeSkills||e.includeSkills),excludeSkills:J(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=F(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&&B()){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"}
@@ -1,4 +1,4 @@
1
- import{AgentStrategy as G,getSkill as K}from"@zibby/agent-workflow";import{query as J}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as F}from"zod-to-json-schema";import f from"chalk";var c={debug:0,info:1,warn:2,error:3,silent:4},O=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 e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in c?c[e]:c.info}_shouldLog(e){return c[e]>=this._level}_formatMessage(e,s,a={}){let i=new Date().toISOString(),l=`${this._getPrefix(e)} ${s}`;return Object.keys(a).length>0&&(l+=f.dim(` ${JSON.stringify(a)}`)),l}_getPrefix(e){return{debug:f.gray("[DEBUG]"),info:f.cyan("[INFO]"),warn:f.yellow("[WARN]"),error:f.red("\u274C [ERROR]")}[e]||""}debug(e,s){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,s))}info(e,s){this._shouldLog("info")&&console.log(this._formatMessage("info",e,s))}warn(e,s){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,s))}error(e,s){this._shouldLog("error")&&console.error(this._formatMessage("error",e,s))}setLevel(e){e in c&&(this._level=c[e])}getLevel(){return Object.keys(c).find(e=>c[e]===this._level)}},r=new O;import{timeline as A,Timeline as H,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as X}from"@zibby/agent-workflow";var y={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"};var w={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 V={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var $=class extends G{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let s=!!process.env.ANTHROPIC_API_KEY;return s||r.debug("ClaudeAgentStrategy: ANTHROPIC_API_KEY not set"),s}async invoke(e,s={}){let{model:a,workspace:i=process.cwd(),schema:n=null,images:l=[],skills:p=null,sessionPath:v=null,nodeName:R=null,timeout:B,config:Z={}}=s,g=a;(!g||g==="auto")&&(r.debug(`Model is '${g||"undefined"}', using default: ${y.CLAUDE}`),g=y.CLAUDE);let m=w[g]||g;w[g]&&g!==m&&r.debug(`Mapped model: ${g} \u2192 ${m}`),r.debug(`Invoking Claude Agent SDK with model: ${m}, skills: ${JSON.stringify(p)}`);let L=process.env.ANTHROPIC_API_KEY,C=L?` | key: ***${L.slice(-4)}`:" | key: not set";console.log(`
2
- \u25C6 Model: ${m}${C}
1
+ import{AgentStrategy as K,getSkill as J}from"@zibby/agent-workflow";import{query as F}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as B}from"zod-to-json-schema";import f from"chalk";var a={debug:0,info:1,warn:2,error:3,silent:4},A=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return a.debug;if(process.env.ZIBBY_VERBOSE==="true")return a.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in a?a[e]:a.info}_shouldLog(e){return a[e]>=this._level}_formatMessage(e,r,c={}){let l=new Date().toISOString(),u=`${this._getPrefix(e)} ${r}`;return Object.keys(c).length>0&&(u+=f.dim(` ${JSON.stringify(c)}`)),u}_getPrefix(e){return{debug:f.gray("[DEBUG]"),info:f.cyan("[INFO]"),warn:f.yellow("[WARN]"),error:f.red("\u274C [ERROR]")}[e]||""}debug(e,r){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,r))}info(e,r){this._shouldLog("info")&&console.log(this._formatMessage("info",e,r))}warn(e,r){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,r))}error(e,r){this._shouldLog("error")&&console.error(this._formatMessage("error",e,r))}setLevel(e){e in a&&(this._level=a[e])}getLevel(){return Object.keys(a).find(e=>a[e]===this._level)}},s=new A;import{timeline as O,Timeline as X,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as V}from"@zibby/agent-workflow";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 y={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 z={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var D=class extends K{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let r=!!process.env.ANTHROPIC_API_KEY;return r||s.debug("ClaudeAgentStrategy: ANTHROPIC_API_KEY not set"),r}async invoke(e,r={}){let{model:c,workspace:l=process.cwd(),schema:n=null,images:u=[],skills:p=null,sessionPath:R=null,nodeName:C=null,timeout:Z,config:j={},signal:L=null}=r,g=c;(!g||g==="auto")&&(s.debug(`Model is '${g||"undefined"}', using default: ${w.CLAUDE}`),g=w.CLAUDE);let m=y[g]||g;y[g]&&g!==m&&s.debug(`Mapped model: ${g} \u2192 ${m}`),s.debug(`Invoking Claude Agent SDK with model: ${m}, skills: ${JSON.stringify(p)}`);let M=process.env.ANTHROPIC_API_KEY,k=M?` | key: ***${M.slice(-4)}`:" | key: not set";console.log(`
2
+ \u25C6 Model: ${m}${k}
3
3
  `);let h=(await import("chalk")).default;console.log(`
4
- ${h.bold("Prompt sent to LLM:")}`),console.log(h.dim("\u2500".repeat(60))),console.log(h.dim(e)),console.log(h.dim("\u2500".repeat(60)));let{allowedTools:M,mcpServers:T}=this._resolveSkills(p,{sessionPath:v,workspace:i,nodeName:R});try{let d={cwd:i,allowedTools:M,permissionMode:"bypassPermissions",model:m,...Object.keys(T).length>0&&{mcpServers:T}};if(n){let E=typeof n.parse=="function"?F(n,{target:"openApi3"}):n;d.outputFormat={type:"json_schema",schema:E},r.debug("Structured output enforced via SDK outputFormat")}r.debug(`Agent SDK options: ${JSON.stringify({cwd:d.cwd,toolCount:M.length,permissionMode:d.permissionMode,model:d.model,hasOutputFormat:!!d.outputFormat})}`);let _="",k=0,x=[];r.debug("Starting Claude Agent SDK query stream");let I;try{I=J({prompt:e,options:d})}catch(t){throw r.error(`Failed to initialize Claude Agent SDK: ${t.message}`),t}let N=null,S=0,P=3;try{for await(let t of I){if(x.push(t),t.type==="error"||t.error){let u=t.error?.message||t.error||t.message||"Unknown API error";throw new Error(typeof u=="string"?u:JSON.stringify(u))}let E=JSON.stringify(t.message?.content||t.text||"").slice(0,200);if(E===N){if(S++,S>=P){let u=(t.message?.content?.[0]?.text||t.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${S}x repeated): ${u}`)}}else N=E,S=1;if(t.type==="assistant"||t.constructor?.name==="AssistantMessage"){let u=t.message?.content||t.content||[];for(let o of u)if(o.type==="thinking"&&o.thinking)console.log(`${o.thinking.substring(0,200)}${o.thinking.length>200?"...":""}`);else if(o.type==="text"&&o.text)_+=o.text,o.text.length<500?console.log(`${o.text}`):console.log(`${o.text.substring(0,200)}... (${o.text.length} chars)`);else if(o.type==="tool_use"){k++,o.name.includes("memory")?A.stepMemory(`Tool: ${o.name}`):A.stepTool(`Tool: ${o.name}`);let U=JSON.stringify(o.input).substring(0,100);console.log(` Input: ${U}${JSON.stringify(o.input).length>100?"...":""}`)}}else if(!(t.type==="user"&&t.tool_use_result)){if(t.type==="result"||t.constructor?.name==="ResultMessage"){let u=t.result||t.text||t.content||_;if(n){if(t.structured_output){r.debug("Using SDK native structured_output");let D=typeof n.parse=="function"?n.parse(t.structured_output):t.structured_output;return{raw:u,structured:D}}if(u){let o=this._extractJson(u,n);if(o)return{raw:u,structured:o}}r.warn(`Could not extract structured output \u2014 returning raw text (${(u||"").length} chars)`)}return u||""}}}if(r.warn(`Agent SDK ended without result. Collected ${x.length} messages`),_.length>0)return r.debug("Returning accumulated text from messages"),_;throw new Error("Claude Agent SDK query ended without result")}catch(t){throw r.error(`Error during query stream: ${t.message}`),t}}catch(d){throw r.error("Claude Agent SDK call failed",{error:d.message}),d}}_resolveSkills(e,s){if(e===null)return r.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return r.debug("Default IDE skills for code generation"),{allowedTools:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};let a=[],i={};for(let n of e){let l=K(n);if(!l){r.warn(`Unknown skill "${n}" \u2014 skipping`);continue}if(l.allowedTools&&a.push(...l.allowedTools),typeof l.resolve=="function"){let p=l.resolve(s);p&&(i[l.serverName]=p,r.debug(`MCP: ${l.serverName} \u2192 ${p.command} ${p.args[0]}`))}}return{allowedTools:a,mcpServers:i}}_extractJson(e,s){let a=[()=>{if(e.includes("===JSON_START===")){let i=e.indexOf("===JSON_START===")+16,n=e.indexOf("===JSON_END===");return e.substring(i,n).trim()}},()=>e.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!e.startsWith("{"))return e.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>e.trim(),()=>{let i=e.indexOf("{"),n=e.lastIndexOf("}");if(i!==-1&&n>i)return e.substring(i,n+1)}];for(let i of a)try{let n=i();if(!n)continue;let l=JSON.parse(n);if(typeof l!="object"||l===null)continue;return typeof s.parse=="function"?s.parse(l):l}catch{}return null}};export{$ as ClaudeAgentStrategy};
4
+ ${h.bold("Prompt sent to LLM:")}`),console.log(h.dim("\u2500".repeat(60))),console.log(h.dim(e)),console.log(h.dim("\u2500".repeat(60)));let{allowedTools:T,mcpServers:x}=this._resolveSkills(p,{sessionPath:R,workspace:l,nodeName:C});try{let d={cwd:l,allowedTools:T,permissionMode:"bypassPermissions",model:m,...Object.keys(x).length>0&&{mcpServers:x}};if(n){let S=typeof n.parse=="function"?B(n,{target:"openApi3"}):n;d.outputFormat={type:"json_schema",schema:S},s.debug("Structured output enforced via SDK outputFormat")}s.debug(`Agent SDK options: ${JSON.stringify({cwd:d.cwd,toolCount:T.length,permissionMode:d.permissionMode,model:d.model,hasOutputFormat:!!d.outputFormat})}`);let _="",P=0,b=[];s.debug("Starting Claude Agent SDK query stream");let I;try{I=F({prompt:e,options:d})}catch(t){throw s.error(`Failed to initialize Claude Agent SDK: ${t.message}`),t}let N=null,E=0,U=3;if(L?.aborted){let t=new Error("Aborted via signal");throw t.name="AbortError",t}try{for await(let t of I){if(L?.aborted){let i=new Error("Aborted via signal");throw i.name="AbortError",i}if(b.push(t),t.type==="error"||t.error){let i=t.error?.message||t.error||t.message||"Unknown API error";throw new Error(typeof i=="string"?i:JSON.stringify(i))}let S=JSON.stringify(t.message?.content||t.text||"").slice(0,200);if(S===N){if(E++,E>=U){let i=(t.message?.content?.[0]?.text||t.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${E}x repeated): ${i}`)}}else N=S,E=1;if(t.type==="assistant"||t.constructor?.name==="AssistantMessage"){let i=t.message?.content||t.content||[];for(let o of i)if(o.type==="thinking"&&o.thinking)console.log(`${o.thinking.substring(0,200)}${o.thinking.length>200?"...":""}`);else if(o.type==="text"&&o.text)_+=o.text,o.text.length<500?console.log(`${o.text}`):console.log(`${o.text.substring(0,200)}... (${o.text.length} chars)`);else if(o.type==="tool_use"){P++,o.name.includes("memory")?O.stepMemory(`Tool: ${o.name}`):O.stepTool(`Tool: ${o.name}`);let G=JSON.stringify(o.input).substring(0,100);console.log(` Input: ${G}${JSON.stringify(o.input).length>100?"...":""}`)}}else if(!(t.type==="user"&&t.tool_use_result)){if(t.type==="result"||t.constructor?.name==="ResultMessage"){let i=t.result||t.text||t.content||_;if(n){if(t.structured_output){s.debug("Using SDK native structured_output");let v=typeof n.parse=="function"?n.parse(t.structured_output):t.structured_output;return{raw:i,structured:v}}if(i){let o=this._extractJson(i,n);if(o)return{raw:i,structured:o}}s.warn(`Could not extract structured output \u2014 returning raw text (${(i||"").length} chars)`)}return i||""}}}if(s.warn(`Agent SDK ended without result. Collected ${b.length} messages`),_.length>0)return s.debug("Returning accumulated text from messages"),_;throw new Error("Claude Agent SDK query ended without result")}catch(t){throw s.error(`Error during query stream: ${t.message}`),t}}catch(d){throw s.error("Claude Agent SDK call failed",{error:d.message}),d}}_resolveSkills(e,r){if(e===null)return s.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return s.debug("Default IDE skills for code generation"),{allowedTools:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};let c=[],l={};for(let n of e){let u=J(n);if(!u){s.warn(`Unknown skill "${n}" \u2014 skipping`);continue}if(u.allowedTools&&c.push(...u.allowedTools),typeof u.resolve=="function"){let p=u.resolve(r);p&&(l[u.serverName]=p,s.debug(`MCP: ${u.serverName} \u2192 ${p.command} ${p.args[0]}`))}}return{allowedTools:c,mcpServers:l}}_extractJson(e,r){let c=[()=>{if(e.includes("===JSON_START===")){let l=e.indexOf("===JSON_START===")+16,n=e.indexOf("===JSON_END===");return e.substring(l,n).trim()}},()=>e.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!e.startsWith("{"))return e.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>e.trim(),()=>{let l=e.indexOf("{"),n=e.lastIndexOf("}");if(l!==-1&&n>l)return e.substring(l,n+1)}];for(let l of c)try{let n=l();if(!n)continue;let u=JSON.parse(n);if(typeof u!="object"||u===null)continue;return typeof r.parse=="function"?r.parse(u):u}catch{}return null}};export{D as ClaudeAgentStrategy};
@@ -1,4 +1,4 @@
1
- import{AgentStrategy as K,getSkill as U}from"@zibby/agent-workflow";import{execSync as G}from"node:child_process";import{zodToJsonSchema as X}from"zod-to-json-schema";import E from"chalk";var i={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 i.debug;if(process.env.ZIBBY_VERBOSE==="true")return i.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in i?i[e]:i.info}_shouldLog(e){return i[e]>=this._level}_formatMessage(e,t,u={}){let d=new Date().toISOString(),n=`${this._getPrefix(e)} ${t}`;return Object.keys(u).length>0&&(n+=E.dim(` ${JSON.stringify(u)}`)),n}_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 i&&(this._level=i[e])}getLevel(){return Object.keys(i).find(e=>i[e]===this._level)}},o=new L;import{timeline as y,Timeline as Z,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as H}from"@zibby/agent-workflow";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 $={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 q={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var P=class extends K{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.CODEX_API_KEY))return o.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return G("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return o.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:u,workspace:d=process.cwd(),schema:s=null,skills:n=null,sessionPath:h=null,nodeName:p=null,timeout:Y,config:j={}}=t,{Codex:b}=await import("@openai/codex-sdk"),c=u;(!c||c==="auto")&&(o.debug(`Model is '${c||"undefined"}', using default: ${w.CODEX}`),c=w.CODEX);let x=$[c]||c;$[c]&&c!==x&&o.debug(`Mapped model: ${c} \u2192 ${x}`),o.debug(`Invoking Codex SDK with model: ${x}, skills: ${JSON.stringify(n)}`);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 k=O?` | key: ***${O.slice(-4)}`:" | key: not set";console.log(`
2
- \u25C6 Model: ${x}${k}
1
+ import{AgentStrategy as U,getSkill as G}from"@zibby/agent-workflow";import{execSync as X}from"node:child_process";import{zodToJsonSchema as Y}from"zod-to-json-schema";import E from"chalk";var l={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 l.debug;if(process.env.ZIBBY_VERBOSE==="true")return l.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in l?l[e]:l.info}_shouldLog(e){return l[e]>=this._level}_formatMessage(e,t,u={}){let d=new Date().toISOString(),n=`${this._getPrefix(e)} ${t}`;return Object.keys(u).length>0&&(n+=E.dim(` ${JSON.stringify(u)}`)),n}_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 l&&(this._level=l[e])}getLevel(){return Object.keys(l).find(e=>l[e]===this._level)}},o=new L;import{timeline as w,Timeline as H,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as q}from"@zibby/agent-workflow";var y={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"};var b={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 z={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var P=class extends U{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.CODEX_API_KEY))return o.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return X("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return o.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:u,workspace:d=process.cwd(),schema:s=null,skills:n=null,sessionPath:h=null,nodeName:p=null,timeout:j,config:B={},signal:$=null}=t,{Codex:k}=await import("@openai/codex-sdk"),a=u;(!a||a==="auto")&&(o.debug(`Model is '${a||"undefined"}', using default: ${y.CODEX}`),a=y.CODEX);let x=b[a]||a;b[a]&&a!==x&&o.debug(`Mapped model: ${a} \u2192 ${x}`),o.debug(`Invoking Codex SDK with model: ${x}, skills: ${JSON.stringify(n)}`);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 T=O?` | key: ***${O.slice(-4)}`:" | key: not set";console.log(`
2
+ \u25C6 Model: ${x}${T}
3
3
  `);let v=(await import("chalk")).default;console.log(`
4
- ${v.bold("Prompt sent to LLM:")}`),console.log(v.dim("\u2500".repeat(60))),console.log(v.dim(e)),console.log(v.dim("\u2500".repeat(60)));let S=this._resolveSkillsToMcp(n,{sessionPath:h,workspace:d,nodeName:p}),C={};Object.keys(S).length>0&&(C.mcp_servers=S,o.debug(`[Codex] MCP servers: ${Object.keys(S).join(", ")}`));let T=new b({...Object.keys(C).length>0&&{config:C}}).startThread({workingDirectory:d,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),M=s&&typeof s.parse=="function",D={};if(s)try{let l=M?X(s,{target:"openAi"}):s;D.outputSchema=l,o.debug("Structured output via SDK outputSchema")}catch(l){o.warn(`[Codex] Schema conversion failed, will extract from text: ${l.message}`)}try{let{events:l}=await T.runStreamed(e,D),m=0,r="";for await(let g of l){let f=g.type;if(f==="item.completed"){let a=g.item,_=a?.type;if(_==="mcp_tool_call"){m++;let A=`${a.server}/${a.tool}`;if(y.stepTool(`Tool: ${A}`),a.arguments){let I=JSON.stringify(a.arguments),R=I.length>100?`${I.substring(0,100)}...`:I;console.log(` Input: ${R}`)}}else if(_==="tool_call"||_==="function_call"||_==="command_execution"){m++;let A=a.name||a.tool||a.command||"unknown";y.stepTool(`Tool: ${A}`)}else _==="agent_message"&&(r=a.text||"",r.length<500?console.log(r):console.log(`${r.substring(0,200)}... (${r.length} chars)`))}else f==="turn.completed"?o.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(g.usage||{})}`):o.debug(`[Codex] Event: ${f} ${JSON.stringify(g).slice(0,300)}`)}if(o.debug(`[Codex] Last agent message (${r.length} chars): ${r.slice(0,500)}`),s){if(!r)throw new Error("Codex agent returned no response");let g=JSON.parse(r),f=M?s.parse(g):g;return o.debug("\u2705 [Codex] Structured output validated"),{raw:r,structured:f}}return r||""}catch(l){let m=l.message||String(l);throw o.error(`\u274C [Codex] SDK call failed: ${m}`),m.includes("exited with code")&&(o.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),o.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),l}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let u={};for(let d of e){let s=U(d);if(!s){o.warn(`[Codex] Unknown skill "${d}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let n=s.resolve(t);if(!n)continue;let h=s.serverName||d,p={command:n.command};n.args?.length&&(p.args=n.args),n.env&&Object.keys(n.env).length>0&&(p.env=n.env),u[h]=p,o.debug(`[Codex] MCP: ${h} \u2192 ${n.command} ${(n.args||[]).join(" ")}`)}return u}};export{P as CodexAgentStrategy};
4
+ ${v.bold("Prompt sent to LLM:")}`),console.log(v.dim("\u2500".repeat(60))),console.log(v.dim(e)),console.log(v.dim("\u2500".repeat(60)));let S=this._resolveSkillsToMcp(n,{sessionPath:h,workspace:d,nodeName:p}),A={};Object.keys(S).length>0&&(A.mcp_servers=S,o.debug(`[Codex] MCP servers: ${Object.keys(S).join(", ")}`));let R=new k({...Object.keys(A).length>0&&{config:A}}).startThread({workingDirectory:d,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),M=s&&typeof s.parse=="function",D={};if(s)try{let r=M?Y(s,{target:"openAi"}):s;D.outputSchema=r,o.debug("Structured output via SDK outputSchema")}catch(r){o.warn(`[Codex] Schema conversion failed, will extract from text: ${r.message}`)}if($?.aborted){let r=new Error("Aborted via signal");throw r.name="AbortError",r}try{let{events:r}=await R.runStreamed(e,D),m=0,c="";for await(let g of r){if($?.aborted){let i=new Error("Aborted via signal");throw i.name="AbortError",i}let f=g.type;if(f==="item.completed"){let i=g.item,_=i?.type;if(_==="mcp_tool_call"){m++;let C=`${i.server}/${i.tool}`;if(w.stepTool(`Tool: ${C}`),i.arguments){let I=JSON.stringify(i.arguments),K=I.length>100?`${I.substring(0,100)}...`:I;console.log(` Input: ${K}`)}}else if(_==="tool_call"||_==="function_call"||_==="command_execution"){m++;let C=i.name||i.tool||i.command||"unknown";w.stepTool(`Tool: ${C}`)}else _==="agent_message"&&(c=i.text||"",c.length<500?console.log(c):console.log(`${c.substring(0,200)}... (${c.length} chars)`))}else f==="turn.completed"?o.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(g.usage||{})}`):o.debug(`[Codex] Event: ${f} ${JSON.stringify(g).slice(0,300)}`)}if(o.debug(`[Codex] Last agent message (${c.length} chars): ${c.slice(0,500)}`),s){if(!c)throw new Error("Codex agent returned no response");let g=JSON.parse(c),f=M?s.parse(g):g;return o.debug("\u2705 [Codex] Structured output validated"),{raw:c,structured:f}}return c||""}catch(r){let m=r.message||String(r);throw o.error(`\u274C [Codex] SDK call failed: ${m}`),m.includes("exited with code")&&(o.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),o.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),r}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let u={};for(let d of e){let s=G(d);if(!s){o.warn(`[Codex] Unknown skill "${d}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let n=s.resolve(t);if(!n)continue;let h=s.serverName||d,p={command:n.command};n.args?.length&&(p.args=n.args),n.env&&Object.keys(n.env).length>0&&(p.env=n.env),u[h]=p,o.debug(`[Codex] MCP: ${h} \u2192 ${n.command} ${(n.args||[]).join(" ")}`)}return u}};export{P as CodexAgentStrategy};
@@ -1,7 +1,7 @@
1
- import{AgentStrategy as Rt,DEFAULT_OUTPUT_BASE as Pt,SESSION_INFO_FILE as Ct,STUDIO_STOP_REQUEST_FILE as Nt,getAllSkills as kt,getSkill as it}from"@zibby/agent-workflow";import{spawn as Lt,execSync as M}from"node:child_process";import{writeFileSync as lt,readFileSync as at,mkdirSync as ut,existsSync as H,accessSync as ct,constants as pt,unlinkSync as Ut}from"node:fs";import{join as v,resolve as Mt}from"node:path";import{homedir as Y}from"node:os";import K from"chalk";var C={debug:0,info:1,warn:2,error:3,silent:4},q=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(),n=`${this._getPrefix(t)} ${e}`;return Object.keys(r).length>0&&(n+=K.dim(` ${JSON.stringify(r)}`)),n}_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)}},o=new q;var G={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"};var W={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var Z=class l{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 a=JSON.parse(s);this._emitToolCalls(a);let n=this.extractText(a);if(n){if(this.rawText&&n.startsWith(this.rawText)){let u=n.substring(this.rawText.length);this.rawText=n,r+=u}else(!this.rawText.includes(n)||n.length<20)&&(this.rawText+=n,r+=n);this.tryExtractResult(this.rawText)}else this.isValidResult(a)&&(this.rawText+=`${s}
1
+ import{AgentStrategy as Nt,DEFAULT_OUTPUT_BASE as kt,SESSION_INFO_FILE as Lt,STUDIO_STOP_REQUEST_FILE as Mt,getAllSkills as Ut,getSkill as ut}from"@zibby/agent-workflow";import{spawn as Dt,execSync as F}from"node:child_process";import{writeFileSync as ct,readFileSync as pt,mkdirSync as ft,existsSync as H,accessSync as dt,constants as gt,unlinkSync as Bt}from"node:fs";import{join as v,resolve as Ft}from"node:path";import{homedir as Y}from"node:os";import G from"chalk";var N={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 N.debug;if(process.env.ZIBBY_VERBOSE==="true")return N.info;let t=process.env.LOG_LEVEL?.toLowerCase();return t&&t in N?N[t]:N.info}_shouldLog(t){return N[t]>=this._level}_formatMessage(t,e,r={}){let s=new Date().toISOString(),n=`${this._getPrefix(t)} ${e}`;return Object.keys(r).length>0&&(n+=G.dim(` ${JSON.stringify(r)}`)),n}_getPrefix(t){return{debug:G.gray("[DEBUG]"),info:G.cyan("[INFO]"),warn:G.yellow("[WARN]"),error:G.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 N&&(this._level=N[t])}getLevel(){return Object.keys(N).find(t=>N[t]===this._level)}},o=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 W={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var Z=class i{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 l=JSON.parse(s);this._emitToolCalls(l);let n=this.extractText(l);if(n){if(this.rawText&&n.startsWith(this.rawText)){let a=n.substring(this.rawText.length);this.rawText=n,r+=a}else(!this.rawText.includes(n)||n.length<20)&&(this.rawText+=n,r+=n);this.tryExtractResult(this.rawText)}else this.isValidResult(l)&&(this.rawText+=`${s}
3
3
  `,r+=`${s}
4
- `,this.extractedResult=a)}catch{if(s.includes('"text"')||s.includes('"content"')){let n=s.match(/"text"\s*:\s*"([^"]*)/),u=s.match(/"content"\s*:\s*"([^"]*)/),p=n?n[1]:u?u[1]:null;p&&!this.rawText.includes(p)&&(r+=p,this.rawText+=p)}}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=(n,u)=>{if(!n)return;let p=`${n}:${JSON.stringify(u??{})}`;this._lastToolEmit!==p&&(this._lastToolEmit=p,this.onToolCall(n,u??void 0))},r=n=>{if(n!=null){if(typeof n=="object"&&!Array.isArray(n))return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return}}};if(t.type==="tool_use"||t.type==="tool_call"){if(t.name){e(t.name,r(t.input??t.arguments));return}let n=t.tool_call;if(n&&typeof n=="object"&&!Array.isArray(n)){let u=Object.keys(n);if(u.length===1){let p=u[0],g=n[p],c=g&&typeof g=="object"?g.args??g.input??g:void 0;e(p,r(c))}return}return}if(Array.isArray(t.tool_calls)){for(let n of t.tool_calls)e(n.name,r(n.input??n.arguments));return}let s=t.message??t;if(Array.isArray(s?.tool_calls)){for(let n of s.tool_calls)e(n.name,r(n.input??n.arguments));return}let a=s?.content??t.content;if(Array.isArray(a))for(let n of a)(n.type==="tool_use"||n.type==="tool_call")&&n.name&&e(n.name,r(n.input??n.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 a=0,n=0;for(;a<t.length&&(a=t.indexOf("{",a),a!==-1);){let f=0,m=a;for(let E=a;E<t.length;E++)if(t[E]==="{")f++;else if(t[E]==="}"&&(f--,f===0)){m=E,e.push({text:t.substring(a,m+1),source:"brace"}),n++;break}a=m+1}let u=this.extractedResult,p=u?JSON.stringify(u).length:0,g=0,c=-1;for(let f=0;f<e.length;f++){let m=e[f];try{let E=m.text.replace(/,(\s*[}\]])/g,"$1"),A=JSON.parse(E);this.isValidResult(A)&&(g++,p=JSON.stringify(A).length,u=A,c=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 l;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 dt}from"zod-to-json-schema";var X=class{static generateFileOutputInstructions(t,e){let r;typeof t?.parse=="function"?r=dt(t,{target:"openApi3"}):r=t;let s=this._buildExample(r);return`
4
+ `,this.extractedResult=l)}catch{if(s.includes('"text"')||s.includes('"content"')){let n=s.match(/"text"\s*:\s*"([^"]*)/),a=s.match(/"content"\s*:\s*"([^"]*)/),u=n?n[1]:a?a[1]:null;u&&!this.rawText.includes(u)&&(r+=u,this.rawText+=u)}}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=(n,a)=>{if(!n)return;let u=`${n}:${JSON.stringify(a??{})}`;this._lastToolEmit!==u&&(this._lastToolEmit=u,this.onToolCall(n,a??void 0))},r=n=>{if(n!=null){if(typeof n=="object"&&!Array.isArray(n))return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return}}};if(t.type==="tool_use"||t.type==="tool_call"){if(t.name){e(t.name,r(t.input??t.arguments));return}let n=t.tool_call;if(n&&typeof n=="object"&&!Array.isArray(n)){let a=Object.keys(n);if(a.length===1){let u=a[0],h=n[u],p=h&&typeof h=="object"?h.args??h.input??h:void 0;e(u,r(p))}return}return}if(Array.isArray(t.tool_calls)){for(let n of t.tool_calls)e(n.name,r(n.input??n.arguments));return}let s=t.message??t;if(Array.isArray(s?.tool_calls)){for(let n of s.tool_calls)e(n.name,r(n.input??n.arguments));return}let l=s?.content??t.content;if(Array.isArray(l))for(let n of l)(n.type==="tool_use"||n.type==="tool_call")&&n.name&&e(n.name,r(n.input??n.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 m=s[1].trim();try{JSON.parse(m),e.push({text:m,source:"markdown"})}catch{}}let l=0,n=0;for(;l<t.length&&(l=t.indexOf("{",l),l!==-1);){let m=0,d=l;for(let y=l;y<t.length;y++)if(t[y]==="{")m++;else if(t[y]==="}"&&(m--,m===0)){d=y,e.push({text:t.substring(l,d+1),source:"brace"}),n++;break}l=d+1}let a=this.extractedResult,u=a?JSON.stringify(a).length:0,h=0,p=-1;for(let m=0;m<e.length;m++){let d=e[m];try{let y=d.text.replace(/,(\s*[}\]])/g,"$1"),w=JSON.parse(y);this.isValidResult(w)&&(h++,u=JSON.stringify(w).length,a=w,p=m)}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 i;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 ht}from"zod-to-json-schema";var X=class{static generateFileOutputInstructions(t,e){let r;typeof t?.parse=="function"?r=ht(t,{target:"openApi3"}):r=t;let s=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
@@ -21,7 +21,7 @@ JSON types (strict \u2014 validators reject wrong types):
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,a]of Object.entries(t.properties))r[s]=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(s=>s.type!=="null")||t.anyOf?.find(s=>s.type!=="null");return r?this._buildExample(r):null}return"<value>"}};var V=class l{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[s,l]of Object.entries(t.properties))r[s]=this._buildExample(l);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 V=class i{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=X.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
@@ -31,18 +31,18 @@ ${t.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:e,p
31
31
 
32
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(`
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 l(this.userPrompt);return t.systemInstructions=[...this.systemInstructions],t.metadata={...this.metadata},t}};import gt from"axios";import{homedir as mt}from"node:os";import{join as ht}from"node:path";import{existsSync as yt,readFileSync as Ot}from"node:fs";import{toJSONSchema as Et}from"zod";function St(){if(process.env.OPENAI_PROXY_TOKEN)return o.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return o.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let l=ht(mt(),".zibby","config.json");if(yt(l)){let t=JSON.parse(Ot(l,"utf-8"));if(t.sessionToken)return o.debug("[Auth] Using session token from zibby login"),t.sessionToken}}catch(l){o.debug(`[Auth] Could not read zibby login session: ${l.message}`)}return null}function _t(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function B(l){if(!(typeof l!="object"||l===null)){if(Object.keys(l).length===0){l.type="object",l.additionalProperties=!0;return}if(l.type||(l.properties?l.type="object":l.items&&(l.type="array")),l.type==="object")if(l.properties){for(let[t,e]of Object.entries(l.properties))e.type==="object"&&e.additionalProperties&&e.additionalProperties!==!1&&(!e.properties||Object.keys(e.properties).length===0)&&(l.properties[t]={type:["object","null"]});l.additionalProperties=!1,l.required=Object.keys(l.properties),Object.values(l.properties).forEach(B)}else"additionalProperties"in l||(l.additionalProperties=!0);l.type==="array"&&l.items&&B(l.items),l.anyOf&&l.anyOf.forEach(B),l.oneOf&&l.oneOf.forEach(B),l.allOf&&l.allOf.forEach(B)}}async function et(l,t){o.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let e=St();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=_t();o.info(`\u{1F517} Using OpenAI proxy: ${r}`);let s=Et(t),a=s;if(s.$ref&&s.definitions){let c=s.$ref.split("/").pop();a=s.definitions[c]||s,o.debug(`Extracted schema from $ref: ${c}`)}delete a.$schema,B(a);let n=4e5,u=l;l.length>n&&(o.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${l.length} chars) exceeds limit, keeping last ${n} chars`),u=`... [truncated early content] ...
35
- ${l.slice(-n)}`);let p=`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 i(this.userPrompt);return t.systemInstructions=[...this.systemInstructions],t.metadata={...this.metadata},t}};import yt from"axios";import{homedir as Ot}from"node:os";import{join as Et}from"node:path";import{existsSync as St,readFileSync as _t}from"node:fs";import{toJSONSchema as bt}from"zod";function At(){if(process.env.OPENAI_PROXY_TOKEN)return o.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return o.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let i=Et(Ot(),".zibby","config.json");if(St(i)){let t=JSON.parse(_t(i,"utf-8"));if(t.sessionToken)return o.debug("[Auth] Using session token from zibby login"),t.sessionToken}}catch(i){o.debug(`[Auth] Could not read zibby login session: ${i.message}`)}return null}function It(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function J(i){if(!(typeof i!="object"||i===null)){if(Object.keys(i).length===0){i.type="object",i.additionalProperties=!0;return}if(i.type||(i.properties?i.type="object":i.items&&(i.type="array")),i.type==="object")if(i.properties){for(let[t,e]of Object.entries(i.properties))e.type==="object"&&e.additionalProperties&&e.additionalProperties!==!1&&(!e.properties||Object.keys(e.properties).length===0)&&(i.properties[t]={type:["object","null"]});i.additionalProperties=!1,i.required=Object.keys(i.properties),Object.values(i.properties).forEach(J)}else"additionalProperties"in i||(i.additionalProperties=!0);i.type==="array"&&i.items&&J(i.items),i.anyOf&&i.anyOf.forEach(J),i.oneOf&&i.oneOf.forEach(J),i.allOf&&i.allOf.forEach(J)}}async function ot(i,t){o.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let e=At();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=It();o.info(`\u{1F517} Using OpenAI proxy: ${r}`);let s=bt(t),l=s;if(s.$ref&&s.definitions){let p=s.$ref.split("/").pop();l=s.definitions[p]||s,o.debug(`Extracted schema from $ref: ${p}`)}delete l.$schema,J(l);let n=4e5,a=i;i.length>n&&(o.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${i.length} chars) exceeds limit, keeping last ${n} chars`),a=`... [truncated early content] ...
35
+ ${i.slice(-n)}`);let u=`Extract and format the following information into structured JSON matching the schema.
36
36
 
37
37
  RAW CONTENT:
38
- ${u}
38
+ ${a}
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:G.OPENAI_POSTPROCESSING,messages:[{role:"user",content:p}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:a,strict:!0}}};o.info(`\u{1F4E4} Sending to OpenAI proxy: model=${G.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(a.properties||{}).join(", ")}`),o.debug(` Schema size: ${JSON.stringify(a).length} chars`),o.debug(` Prompt size: ${p.length} chars`);try{let c={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(c["x-proxy-token"]=e,c["x-execution-id"]=process.env.EXECUTION_ID||""):(c.Authorization=`Bearer ${e}`,c["x-api-key"]=process.env.ZIBBY_API_KEY||"",c["x-execution-id"]=process.env.EXECUTION_ID||"");let m=(await gt.post(r,g,{headers:c,timeout:W.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!m)throw new Error("OpenAI proxy returned empty response");let E=JSON.parse(m);return o.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:E,raw:l}}catch(c){if(c.response){let f=c.response.status,m=c.response.data;throw o.error(`\u274C OpenAI proxy request failed: ${f}`),o.error(` Status: ${f}`),o.error(` Response: ${JSON.stringify(m,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.`,h={model:z.OPENAI_POSTPROCESSING,messages:[{role:"user",content:u}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:l,strict:!0}}};o.info(`\u{1F4E4} Sending to OpenAI proxy: model=${z.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(l.properties||{}).join(", ")}`),o.debug(` Schema size: ${JSON.stringify(l).length} chars`),o.debug(` Prompt size: ${u.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 d=(await yt.post(r,h,{headers:p,timeout:W.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!d)throw new Error("OpenAI proxy returned empty response");let y=JSON.parse(d);return o.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:y,raw:i}}catch(p){if(p.response){let m=p.response.status,d=p.response.data;throw o.error(`\u274C OpenAI proxy request failed: ${m}`),o.error(` Status: ${m}`),o.error(` Response: ${JSON.stringify(d,null,2)}`),m===401||m===403?new Error(`Authentication failed for OpenAI proxy.
41
41
  Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
42
- Response: ${JSON.stringify(m)}`,{cause:c}):new Error(`Failed to format Cursor output: ${m?.error?.message||"Unknown error"}`,{cause:c})}throw o.error(`\u274C OpenAI proxy request failed: ${c.message}`),new Error(`Failed to format output: ${c.message}`,{cause:c})}}import{timeline as Q,Timeline as re,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as ne}from"@zibby/agent-workflow";import{copyFileSync as bt,existsSync as tt,lstatSync as At,mkdirSync as rt,rmSync as xt,symlinkSync as It,unlinkSync as Tt}from"node:fs";import{join as k}from"node:path";import{homedir as wt}from"node:os";import{randomBytes as $t}from"node:crypto";var vt=["cli-config.json","config.json","auth.json","argv.json"];function nt(l){return!(!l||typeof l!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function st(l){let t=k(l||process.cwd(),".zibby","tmp");rt(t,{recursive:!0});let e=`${process.pid}-${Date.now()}-${$t(4).toString("hex")}`,r=k(t,`cursor-agent-home-${e}`),s=k(r,".cursor");rt(s,{recursive:!0});let a=wt(),n=k(a,".cursor");if(tt(n))for(let u of vt){let p=k(n,u);if(tt(p))try{bt(p,k(s,u))}catch{}}if(process.platform==="darwin"){let u=k(a,"Library");if(tt(u))try{It(u,k(r,"Library"))}catch{}}return r}function ot(l){if(!(!l||typeof l!="string"))try{let t=k(l,"Library");try{At(t).isSymbolicLink()&&Tt(t)}catch{}xt(l,{recursive:!0,force:!0})}catch{}}var ft=class extends Rt{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(t){let e=[v(Y(),".local","bin","cursor-agent"),v(Y(),".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("/")){ct(r,pt.X_OK);let s=M(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return o.debug(`[Cursor] Found agent at: ${r} (version: ${s.trim().slice(0,50)})`),!0}else{let s=M(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!s)continue;let a=M(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(a&&a.length>0)return o.debug(`[Cursor] Found '${r}' in PATH at ${s} (version: ${a.trim().slice(0,50)})`),!0}}catch{continue}return o.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:a=null,skills:n=null,sessionPath:u=null,nodeName:p=null,timeout:g=W.CURSOR_AGENT_DEFAULT,config:c={}}=e,f=c?.agent?.strictMode||!1,m=e.model??c?.agent?.cursor?.model??G.CURSOR;o.debug(`[Cursor] Invoking (model: ${m}, timeout: ${g/1e3}s, skills: ${JSON.stringify(n)})`);let A=(this._setupMcpConfig(u,r,c,n,p)||{}).isolatedMcpHome??null,I=[v(Y(),".local","bin","cursor-agent"),v(Y(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],h=null;for(let i of I)try{if(i.startsWith("/"))ct(i,pt.X_OK),M(`"${i}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!M(`which ${i}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");M(`${i} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}h=i,o.debug(`[Agent] Using binary: ${i}`);break}catch(d){o.debug(`[Agent] Binary '${i}' check failed: ${d.message}`);continue}if(!h)throw new Error(`Cursor Agent CLI not found or not working.
42
+ Response: ${JSON.stringify(d)}`,{cause:p}):new Error(`Failed to format Cursor output: ${d?.error?.message||"Unknown error"}`,{cause:p})}throw o.error(`\u274C OpenAI proxy request failed: ${p.message}`),new Error(`Failed to format output: ${p.message}`,{cause:p})}}import{timeline as rt,Timeline as se,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as ie}from"@zibby/agent-workflow";import{copyFileSync as Tt,existsSync as nt,lstatSync as xt,mkdirSync as st,rmSync as wt,symlinkSync as $t,unlinkSync as vt}from"node:fs";import{join as L}from"node:path";import{homedir as Rt}from"node:os";import{randomBytes as Pt}from"node:crypto";var Ct=["cli-config.json","config.json","auth.json","argv.json"];function it(i){return!(!i||typeof i!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function lt(i){let t=L(i||process.cwd(),".zibby","tmp");st(t,{recursive:!0});let e=`${process.pid}-${Date.now()}-${Pt(4).toString("hex")}`,r=L(t,`cursor-agent-home-${e}`),s=L(r,".cursor");st(s,{recursive:!0});let l=Rt(),n=L(l,".cursor");if(nt(n))for(let a of Ct){let u=L(n,a);if(nt(u))try{Tt(u,L(s,a))}catch{}}if(process.platform==="darwin"){let a=L(l,"Library");if(nt(a))try{$t(a,L(r,"Library"))}catch{}}return r}function at(i){if(!(!i||typeof i!="string"))try{let t=L(i,"Library");try{xt(t).isSymbolicLink()&&vt(t)}catch{}wt(i,{recursive:!0,force:!0})}catch{}}var mt=class extends Nt{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(t){let e=[v(Y(),".local","bin","cursor-agent"),v(Y(),".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("/")){dt(r,gt.X_OK);let s=F(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return o.debug(`[Cursor] Found agent at: ${r} (version: ${s.trim().slice(0,50)})`),!0}else{let s=F(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!s)continue;let l=F(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(l&&l.length>0)return o.debug(`[Cursor] Found '${r}' in PATH at ${s} (version: ${l.trim().slice(0,50)})`),!0}}catch{continue}return o.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:l=null,skills:n=null,sessionPath:a=null,nodeName:u=null,timeout:h=W.CURSOR_AGENT_DEFAULT,config:p={},signal:m=null}=e,d=p?.agent?.strictMode||!1,y=e.model??p?.agent?.cursor?.model??z.CURSOR;o.debug(`[Cursor] Invoking (model: ${y}, timeout: ${h/1e3}s, skills: ${JSON.stringify(n)})`);let R=(this._setupMcpConfig(a,r,p,n,u)||{}).isolatedMcpHome??null,g=[v(Y(),".local","bin","cursor-agent"),v(Y(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],T=null;for(let E of g)try{if(E.startsWith("/"))dt(E,gt.X_OK),F(`"${E}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!F(`which ${E}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");F(`${E} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}T=E,o.debug(`[Agent] Using binary: ${E}`);break}catch(_){o.debug(`[Agent] Binary '${E}' check failed: ${_.message}`);continue}if(!T)throw new Error(`Cursor Agent CLI not found or not working.
43
43
 
44
44
  Checked paths:
45
- ${I.map(i=>` - ${i}`).join(`
45
+ ${g.map(E=>` - ${E}`).join(`
46
46
  `)}
47
47
 
48
48
  Install cursor-agent:
@@ -51,28 +51,28 @@ Install cursor-agent:
51
51
  Then add to PATH:
52
52
  echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
53
53
 
54
- Test with: agent --version`);let T=new V(t),b=null;if(a){let i=`zibby-result-${Date.now()}.json`;b=v(r,".zibby","tmp",i);let d=v(r,".zibby","tmp");H(d)||ut(d,{recursive:!0}),T.addStructuredOutput(a,b)}let L=process.env.CURSOR_API_KEY,j=L?` | key: ***${L.slice(-4)}`:" | key: not set";console.log(`
55
- \u25C6 Model: ${m||"auto"}${j}
56
- `);let U=(await import("chalk")).default,F=T.getUserPrompt();console.log(`
57
- ${U.bold("Prompt sent to LLM:")}`),console.log(U.dim("\u2500".repeat(60))),console.log(U.dim(F)),console.log(U.dim("\u2500".repeat(60)));let O=T.build(),R=T.getStats(),N=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",m||"auto"];if(process.env.CURSOR_API_KEY&&N.push("--api-key",process.env.CURSOR_API_KEY),N.push(O),o.debug(`[Agent] User prompt: ${R.userPromptLength} chars, System instructions: ${R.systemInstructionsLength} chars (${R.instructionCount} blocks), Full: ${R.fullPromptLength} chars, model: ${m||"auto"}`),o.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${m||"auto"} (from .zibby.config.js agent.cursor.model)
58
- `)}catch{}let J,w=null;try{let i=u||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);J=await this._spawnWithStreaming(h,N,r,g,null,i,A)}catch(i){w=i}let P=J?.stdout||"";if(a){let i=typeof a.parse=="function",d=null,y=!!(b&&H(b));if(b&&o.info(`[Agent] Result file: ${y?"present":"missing"} at ${b}`),y)try{let S=at(b,"utf-8").trim();d=JSON.parse(S),o.info(`[Agent] Parsed JSON from result file OK (${S.length} chars) \u2192 object ready for validation`),w&&o.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(S){o.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${S.message}`)}else if(w)o.warn(`[Agent] Result file missing at ${b} (agent process error \u2014 may still recover if strictMode repairs)`);else throw o.error(`\u274C [Agent] Result file was never created at ${b}`),new Error(`Agent did not write required result file at ${b}`);if(d&&i)try{let S=a.parse(d);return o.info("\u2705 [Agent] Zod validation passed for structured result file"),f&&o.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:P,structured:S}}catch(S){let x=S.issues?S.issues.map($=>` - ${$.path.join(".")}: ${$.message}`).join(`
59
- `):S.message?.slice(0,400);if(o.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
60
- ${x}`),o.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
61
- ${JSON.stringify(d,null,2).slice(0,500)}`),!f)throw new Error(`Agent output failed schema validation:
62
- ${x}
54
+ Test with: agent --version`);let k=new V(t),b=null;if(l){let E=`zibby-result-${Date.now()}.json`;b=v(r,".zibby","tmp",E);let _=v(r,".zibby","tmp");H(_)||ft(_,{recursive:!0}),k.addStructuredOutput(l,b)}let M=process.env.CURSOR_API_KEY,j=M?` | key: ***${M.slice(-4)}`:" | key: not set";console.log(`
55
+ \u25C6 Model: ${y||"auto"}${j}
56
+ `);let B=(await import("chalk")).default,K=k.getUserPrompt();console.log(`
57
+ ${B.bold("Prompt sent to LLM:")}`),console.log(B.dim("\u2500".repeat(60))),console.log(B.dim(K)),console.log(B.dim("\u2500".repeat(60)));let O=k.build(),P=k.getStats(),U=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",y||"auto"];if(process.env.CURSOR_API_KEY&&U.push("--api-key",process.env.CURSOR_API_KEY),U.push(O),o.debug(`[Agent] User prompt: ${P.userPromptLength} chars, System instructions: ${P.systemInstructionsLength} chars (${P.instructionCount} blocks), Full: ${P.fullPromptLength} chars, model: ${y||"auto"}`),o.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${y||"auto"} (from .zibby.config.js agent.cursor.model)
58
+ `)}catch{}let C,x=null;try{let E=a||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);C=await this._spawnWithStreaming(T,U,r,h,null,E,R,m)}catch(E){x=E}let D=C?.stdout||"";if(l){let E=typeof l.parse=="function",_=null,c=!!(b&&H(b));if(b&&o.info(`[Agent] Result file: ${c?"present":"missing"} at ${b}`),c)try{let f=pt(b,"utf-8").trim();_=JSON.parse(f),o.info(`[Agent] Parsed JSON from result file OK (${f.length} chars) \u2192 object ready for validation`),x&&o.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(f){o.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${f.message}`)}else if(x)o.warn(`[Agent] Result file missing at ${b} (agent process error \u2014 may still recover if strictMode repairs)`);else throw o.error(`\u274C [Agent] Result file was never created at ${b}`),new Error(`Agent did not write required result file at ${b}`);if(_&&E)try{let f=l.parse(_);return o.info("\u2705 [Agent] Zod validation passed for structured result file"),d&&o.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:D,structured:f}}catch(f){let S=f.issues?f.issues.map(I=>` - ${I.path.join(".")}: ${I.message}`).join(`
59
+ `):f.message?.slice(0,400);if(o.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
60
+ ${S}`),o.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
61
+ ${JSON.stringify(_,null,2).slice(0,500)}`),!d)throw new Error(`Agent output failed schema validation:
62
+ ${S}
63
63
 
64
64
  The agent wrote invalid data that doesn't match the required outputSchema.
65
- Enable strictMode in .zibby.config.js for automatic repair.`,{cause:S})}else{if(d)return o.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),f&&o.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:P,structured:d};y&&o.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(f&&!w){let S=J.parsedText,x=d?JSON.stringify(d):S;o.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${x.length} chars in)`);try{let $=await et(x,a);if(i){let z=a.parse($.structured);return o.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:P,structured:z}}return{raw:P,...$}}catch($){if(o.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${$.message}`),d)return o.warn("[Agent] Using agent's original result file as fallback"),{raw:P,structured:d}}}if(w)throw w;let _=y?d==null?"file existed but JSON.parse failed \u2014 see WARN log above":i?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw o.error(`\u274C [Agent] No validated structured output: ${_}`),o.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error(`Agent did not produce a valid result file at ${b}. Enable strictMode for proxy fallback.`)}if(w)throw w;return this._extractFinalResult(P)||J?.parsedText||P}_extractFinalResult(t){if(!t)return null;let e=t.split(`
66
- `),r=null;for(let s of e){let a=s.trim();if(a)try{let n=JSON.parse(a);if(n.type==="assistant"&&n.message?.content){let u=n.message.content;if(Array.isArray(u)){let p=u.filter(g=>g.type==="text"&&g.text).map(g=>g.text).join("");p&&(r=p)}else typeof u=="string"&&u&&(r=u)}}catch{}}return r?.trim()||null}_setupMcpConfig(t,e,r,s=null,a=null){let n=r?.headless,u=v(Y(),".cursor"),p=v(u,"mcp.json"),g={};if(H(p))try{g=JSON.parse(at(p,"utf-8"))}catch{}let c=g.mcpServers||{},f=r?.paths?.output||Pt,m=v(e||process.cwd(),f,Ct),E=Array.isArray(s)?s.map(h=>it(h)).filter(Boolean):[...kt()].map(([,h])=>h),A=new Set;for(let h of E)typeof h.resolve=="function"&&(A.has(h.serverName)||(A.add(h.serverName),this._ensureSkillConfigured(c,h,t,m,a,n)));if(t){let h=it("browser");h&&typeof h.resolve=="function"&&!A.has(h.serverName)&&this._ensureSkillConfigured(c,h,t,m,"execute_live",n)}if(Object.keys(c).length===0)return o.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let I=`${JSON.stringify({mcpServers:c},null,2)}
67
- `;if(nt(t)){let h=st(e||process.cwd()),T=v(h,".cursor","mcp.json");return lt(T,I,"utf8"),o.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${h} | servers: ${Object.keys(c).join(", ")}`),{isolatedMcpHome:h}}return H(u)||ut(u,{recursive:!0}),lt(p,I,"utf8"),o.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(c).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(t,e,r,s,a=null,n){let u=e.cursorKey||e.serverName,p=t[u]?u:t[e.serverName]?e.serverName:null;if(p&&r){let c=typeof e.resolve=="function"?e.resolve({sessionPath:r,nodeName:a,headless:n}):null;c?.args?t[p].args=c.args:t[p].args=(t[p].args||[]).map(E=>E.startsWith("--output-dir=")?`--output-dir=${r}`:E);let f=c?.env||{},m=e.sessionEnvKey?{[e.sessionEnvKey]:s}:{};t[p].env={...t[p].env||{},...f,...m},o.debug(`[MCP] Updated ${p} session \u2192 ${r}`);return}if(p)return;let g=e.resolve({sessionPath:r,nodeName:a,headless:n});g&&(t[u]={...g,...e.sessionEnvKey&&{env:{...g.env||{},[e.sessionEnvKey]:s}}},o.debug(`[MCP] Configured ${u}`))}_spawnWithStreaming(t,e,r,s,a=null,n=null,u=null){return new Promise((p,g)=>{let c=Date.now(),f="",m="",E=Date.now(),A=0,I=!1,h=null,T=!1,b=!1,L=null;if(n)try{L=v(Mt(String(n)),Nt)}catch{L=null}let j=!1,U=()=>{j||(j=!0,ot(u))},F={...process.env};u&&(F.HOME=u,process.platform==="win32"&&(F.USERPROFILE=u),o.debug(`[Agent] cursor-agent HOME=${u} (isolated MCP config)`));let O=Lt(t,e,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:F});o.debug(`[Agent] PID: ${O.pid}`),O.stdin.on("error",i=>{i.code!=="EPIPE"&&o.warn(`[Agent] stdin error: ${i.message}`)}),O.stdout.on("error",i=>{i.code!=="EPIPE"&&o.warn(`[Agent] stdout error: ${i.message}`)}),O.stderr.on("error",i=>{i.code!=="EPIPE"&&o.warn(`[Agent] stderr error: ${i.message}`)}),a?(O.stdin.write(a,i=>{i&&i.code!=="EPIPE"&&o.warn(`[Agent] Failed to write to stdin: ${i.message}`),O.stdin.end()}),o.debug(`[Agent] Prompt also piped to stdin (${a.length} chars)`)):O.stdin.end();let R=null;L&&(R=setInterval(()=>{if(!(I||b))try{if(H(L)){I=!0,h="studio-stop";try{Ut(L)}catch{}o.warn("\u{1F6D1} Studio stop requested \u2014 terminating Cursor agent (and MCP browser session)"),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},2e3)}}catch{}},600));let N=new Set,J=new Date(c).toISOString().replace(/\.\d+Z$/,""),w=setInterval(()=>{let i=Math.round((Date.now()-c)/1e3),d=Math.round((Date.now()-E)/1e3),y=[];try{let S=Math.ceil(i/60)+1,x=M(`find "${r}" -type f -mmin -${S} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(x)for(let $ of x.split(`
68
- `)){let z=$.replace(`${r}/`,"");N.has(z)||(N.add(z),y.push(z))}}catch{}let _="";y.length>0&&(_=` | \u{1F4C1} new: ${y.map(x=>x.split("/").pop()).join(", ")}`),N.size>0&&(_+=` | \u{1F4E6} total: ${N.size} files`),o.debug(`\u{1F493} [Agent] Running for ${i}s | ${A} lines output${_}`),A===0&&i>=30&&N.size===0&&(i<35&&o.warn(`\u26A0\uFE0F [Agent] No output after ${i}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),i>=60&&(I=!0,h=h||"stall",o.error(`\u274C [Agent] No response after ${i}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},3e3)))},3e4),P=setTimeout(()=>{I=!0,h=h||"timeout";let i=Math.round((Date.now()-c)/1e3);o.error(`\u23F1\uFE0F [Agent] Timeout after ${i}s \u2014 killing process (PID: ${O.pid})`),f.trim()&&o.warn(`\u{1F4E4} [Agent] Partial output (${f.length} chars) before timeout:
69
- ${f.slice(-2e3)}`),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},5e3)},s),D=new Z;D.onToolCall=(i,d)=>{let y=i,_=d;if(i==="mcpToolCall"&&d?.name)y=d.name.replace(/^mcp_+[^_]+_+/,""),y.includes("-")&&y.split("-")[0]===y.split("-")[1]&&(y=y.split("-")[0]),_=d.args??d.input??d;else{if(i==="readToolCall"||i==="editToolCall"||i==="writeToolCall")return;(i.startsWith("mcp__")||i.includes("ToolCall"))&&(y=i.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(y.includes("memory")?Q.stepMemory(`Tool: ${y}`):Q.stepTool(`Tool: ${y}`),_!=null&&typeof _=="object"&&Object.keys(_).length>0&&!b){let x=JSON.stringify(_),$=x.length>100?`${x.substring(0,100)}...`:x;console.log(` Input: ${$}`)}},O.stdout.on("data",i=>{let d=i.toString();f+=d,E=Date.now(),T||(T=!0);let y=D.processChunk(d);y&&!b&&process.stdout.write(y);let _=d.split(`
70
- `).filter(S=>S.trim());A+=_.length}),O.stderr.on("data",i=>{let d=i.toString();m+=d,E=Date.now(),T||(T=!0);let y=d.split(`
71
- `).filter(_=>_.trim());for(let _ of y)o.warn(`\u26A0\uFE0F [Agent stderr] ${_}`)}),O.on("close",(i,d)=>{b=!0,U(),clearTimeout(P),clearInterval(w),R&&clearInterval(R),D.flush();let y=Math.round((Date.now()-c)/1e3);if(o.debug(`[Agent] Exited: code=${i}, signal=${d}, elapsed=${y}s, output=${f.length} chars`),I){if(h==="studio-stop"){g(new Error("Stopped from Zibby Studio"));return}g(new Error(`Cursor Agent timed out after ${y}s (limit: ${s/1e3}s). ${A} lines produced. Last output ${Math.round((Date.now()-E)/1e3)}s ago. ${f.trim()?`
65
+ Enable strictMode in .zibby.config.js for automatic repair.`,{cause:f})}else{if(_)return o.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),d&&o.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:D,structured:_};c&&o.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(d&&!x){let f=C.parsedText,S=_?JSON.stringify(_):f;o.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${S.length} chars in)`);try{let I=await ot(S,l);if(E){let $=l.parse(I.structured);return o.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:D,structured:$}}return{raw:D,...I}}catch(I){if(o.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${I.message}`),_)return o.warn("[Agent] Using agent's original result file as fallback"),{raw:D,structured:_}}}if(x)throw x;let A=c?_==null?"file existed but JSON.parse failed \u2014 see WARN log above":E?"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 o.error(`\u274C [Agent] No validated structured output: ${A}`),o.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error(`Agent did not produce a valid result file at ${b}. Enable strictMode for proxy fallback.`)}if(x)throw x;return this._extractFinalResult(D)||C?.parsedText||D}_extractFinalResult(t){if(!t)return null;let e=t.split(`
66
+ `),r=null;for(let s of e){let l=s.trim();if(l)try{let n=JSON.parse(l);if(n.type==="assistant"&&n.message?.content){let a=n.message.content;if(Array.isArray(a)){let u=a.filter(h=>h.type==="text"&&h.text).map(h=>h.text).join("");u&&(r=u)}else typeof a=="string"&&a&&(r=a)}}catch{}}return r?.trim()||null}_setupMcpConfig(t,e,r,s=null,l=null){let n=r?.headless,a=v(Y(),".cursor"),u=v(a,"mcp.json"),h={};if(H(u))try{h=JSON.parse(pt(u,"utf-8"))}catch{}let p=h.mcpServers||{},m=r?.paths?.output||kt,d=v(e||process.cwd(),m,Lt),y=Array.isArray(s)?s.map(g=>ut(g)).filter(Boolean):[...Ut()].map(([,g])=>g),w=new Set;for(let g of y)typeof g.resolve=="function"&&(w.has(g.serverName)||(w.add(g.serverName),this._ensureSkillConfigured(p,g,t,d,l,n)));if(t){let g=ut("browser");g&&typeof g.resolve=="function"&&!w.has(g.serverName)&&this._ensureSkillConfigured(p,g,t,d,"execute_live",n)}if(Object.keys(p).length===0)return o.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let R=`${JSON.stringify({mcpServers:p},null,2)}
67
+ `;if(it(t)){let g=lt(e||process.cwd()),T=v(g,".cursor","mcp.json");return ct(T,R,"utf8"),o.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${g} | servers: ${Object.keys(p).join(", ")}`),{isolatedMcpHome:g}}return H(a)||ft(a,{recursive:!0}),ct(u,R,"utf8"),o.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(p).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(t,e,r,s,l=null,n){let a=e.cursorKey||e.serverName,u=t[a]?a:t[e.serverName]?e.serverName:null;if(u&&r){let p=typeof e.resolve=="function"?e.resolve({sessionPath:r,nodeName:l,headless:n}):null;p?.args?t[u].args=p.args:t[u].args=(t[u].args||[]).map(y=>y.startsWith("--output-dir=")?`--output-dir=${r}`:y);let m=p?.env||{},d=e.sessionEnvKey?{[e.sessionEnvKey]:s}:{};t[u].env={...t[u].env||{},...m,...d},o.debug(`[MCP] Updated ${u} session \u2192 ${r}`);return}if(u)return;let h=e.resolve({sessionPath:r,nodeName:l,headless:n});h&&(t[a]={...h,...e.sessionEnvKey&&{env:{...h.env||{},[e.sessionEnvKey]:s}}},o.debug(`[MCP] Configured ${a}`))}_spawnWithStreaming(t,e,r,s,l=null,n=null,a=null,u=null){return new Promise((h,p)=>{let m=Date.now(),d="",y="",w=Date.now(),R=0,g=!1,T=null,k=!1,b=!1,M=null;if(n)try{M=v(Ft(String(n)),Mt)}catch{M=null}let j=!1,B=()=>{j||(j=!0,at(a))},K={...process.env};a&&(K.HOME=a,process.platform==="win32"&&(K.USERPROFILE=a),o.debug(`[Agent] cursor-agent HOME=${a} (isolated MCP config)`));let O=Dt(t,e,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:K,...u&&{signal:u}});o.debug(`[Agent] PID: ${O.pid}`);let P=null,U=()=>{g||b||(g=!0,T="aborted",o.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),P=setTimeout(()=>{if(!b){o.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{O.kill("SIGKILL")}catch{}}},5e3))};u&&(u.aborted?U():u.addEventListener("abort",U,{once:!0})),O.stdin.on("error",c=>{c.code!=="EPIPE"&&o.warn(`[Agent] stdin error: ${c.message}`)}),O.stdout.on("error",c=>{c.code!=="EPIPE"&&o.warn(`[Agent] stdout error: ${c.message}`)}),O.stderr.on("error",c=>{c.code!=="EPIPE"&&o.warn(`[Agent] stderr error: ${c.message}`)}),l?(O.stdin.write(l,c=>{c&&c.code!=="EPIPE"&&o.warn(`[Agent] Failed to write to stdin: ${c.message}`),O.stdin.end()}),o.debug(`[Agent] Prompt also piped to stdin (${l.length} chars)`)):O.stdin.end();let C=null;M&&(C=setInterval(()=>{if(!(g||b))try{if(H(M)){g=!0,T="studio-stop";try{Bt(M)}catch{}o.warn("\u{1F6D1} Studio stop requested \u2014 terminating Cursor agent (and MCP browser session)"),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},2e3)}}catch{}},600));let x=new Set,D=new Date(m).toISOString().replace(/\.\d+Z$/,""),q=setInterval(()=>{let c=Math.round((Date.now()-m)/1e3),A=Math.round((Date.now()-w)/1e3),f=[];try{let I=Math.ceil(c/60)+1,$=F(`find "${r}" -type f -mmin -${I} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if($)for(let Q of $.split(`
68
+ `)){let tt=Q.replace(`${r}/`,"");x.has(tt)||(x.add(tt),f.push(tt))}}catch{}let S="";f.length>0&&(S=` | \u{1F4C1} new: ${f.map($=>$.split("/").pop()).join(", ")}`),x.size>0&&(S+=` | \u{1F4E6} total: ${x.size} files`),o.debug(`\u{1F493} [Agent] Running for ${c}s | ${R} lines output${S}`),R===0&&c>=30&&x.size===0&&(c<35&&o.warn(`\u26A0\uFE0F [Agent] No output after ${c}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),c>=60&&(g=!0,T=T||"stall",o.error(`\u274C [Agent] No response after ${c}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},3e3)))},3e4),E=setTimeout(()=>{g=!0,T=T||"timeout";let c=Math.round((Date.now()-m)/1e3);o.error(`\u23F1\uFE0F [Agent] Timeout after ${c}s \u2014 killing process (PID: ${O.pid})`),d.trim()&&o.warn(`\u{1F4E4} [Agent] Partial output (${d.length} chars) before timeout:
69
+ ${d.slice(-2e3)}`),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},5e3)},s),_=new Z;_.onToolCall=(c,A)=>{let f=c,S=A;if(c==="mcpToolCall"&&A?.name)f=A.name.replace(/^mcp_+[^_]+_+/,""),f.includes("-")&&f.split("-")[0]===f.split("-")[1]&&(f=f.split("-")[0]),S=A.args??A.input??A;else{if(c==="readToolCall"||c==="editToolCall"||c==="writeToolCall")return;(c.startsWith("mcp__")||c.includes("ToolCall"))&&(f=c.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(f.includes("memory")?rt.stepMemory(`Tool: ${f}`):rt.stepTool(`Tool: ${f}`),S!=null&&typeof S=="object"&&Object.keys(S).length>0&&!b){let $=JSON.stringify(S),Q=$.length>100?`${$.substring(0,100)}...`:$;console.log(` Input: ${Q}`)}},O.stdout.on("data",c=>{let A=c.toString();d+=A,w=Date.now(),k||(k=!0);let f=_.processChunk(A);f&&!b&&process.stdout.write(f);let S=A.split(`
70
+ `).filter(I=>I.trim());R+=S.length}),O.stderr.on("data",c=>{let A=c.toString();y+=A,w=Date.now(),k||(k=!0);let f=A.split(`
71
+ `).filter(S=>S.trim());for(let S of f)o.warn(`\u26A0\uFE0F [Agent stderr] ${S}`)}),O.on("close",(c,A)=>{if(b=!0,B(),clearTimeout(E),clearInterval(q),C&&clearInterval(C),P&&clearTimeout(P),u&&!u.aborted)try{u.removeEventListener("abort",U)}catch{}_.flush();let f=Math.round((Date.now()-m)/1e3);if(o.debug(`[Agent] Exited: code=${c}, signal=${A}, elapsed=${f}s, output=${d.length} chars`),g){if(T==="studio-stop"){p(new Error("Stopped from Zibby Studio"));return}if(T==="aborted"){let $=new Error("Aborted via signal");$.name="AbortError",p($);return}p(new Error(`Cursor Agent timed out after ${f}s (limit: ${s/1e3}s). ${R} lines produced. Last output ${Math.round((Date.now()-w)/1e3)}s ago. ${d.trim()?`
72
72
  Partial output (last 500 chars):
73
- ${f.slice(-500)}`:"No output captured."}`));return}if(i!==0){g(new Error(`Cursor Agent failed: exit code ${i}, signal ${d}. ${m.trim()?`
74
- Stderr: ${m.slice(-1e3)}`:""}${f.trim()?`
75
- Stdout (last 500 chars): ${f.slice(-500)}`:""}`));return}let _=D.getResult(),S=_?JSON.stringify(_,null,2):D.getRawText()||f||"";p({stdout:f||m||"",parsedText:S})}),O.on("error",i=>{U(),clearTimeout(P),clearInterval(w),R&&clearInterval(R),g(new Error(`Cursor Agent spawn error: ${i.message}
73
+ ${d.slice(-500)}`:"No output captured."}`));return}if(c!==0){p(new Error(`Cursor Agent failed: exit code ${c}, signal ${u}. ${y.trim()?`
74
+ Stderr: ${y.slice(-1e3)}`:""}${d.trim()?`
75
+ Stdout (last 500 chars): ${d.slice(-500)}`:""}`));return}let S=_.getResult(),I=S?JSON.stringify(S,null,2):_.getRawText()||d||"";h({stdout:d||y||"",parsedText:I})}),O.on("error",c=>{if(B(),clearTimeout(E),clearInterval(q),C&&clearInterval(C),P&&clearTimeout(P),u&&!u.aborted)try{u.removeEventListener("abort",U)}catch{}p(new Error(`Cursor Agent spawn error: ${c.message}
76
76
  Binary: ${t}
77
77
  This usually means the binary is not in PATH. Try:
78
- echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};export{ft as CursorAgentStrategy};
78
+ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};export{mt as CursorAgentStrategy};
@@ -1,4 +1,4 @@
1
- import{AgentStrategy as nt,getSkill as it}from"@zibby/agent-workflow";import{execSync as ot,spawn as lt}from"node:child_process";import{zodToJsonSchema as ut}from"zod-to-json-schema";import{existsSync as H,mkdirSync as q,readFileSync as X,rmSync as ct,writeFileSync as Z}from"node:fs";import{join as N}from"node:path";import G from"chalk";var h={debug:0,info:1,warn:2,error:3,silent:4},F=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return h.debug;if(process.env.ZIBBY_VERBOSE==="true")return h.info;let t=process.env.LOG_LEVEL?.toLowerCase();return t&&t in h?h[t]:h.info}_shouldLog(t){return h[t]>=this._level}_formatMessage(t,e,s={}){let n=new Date().toISOString(),r=`${this._getPrefix(t)} ${e}`;return Object.keys(s).length>0&&(r+=G.dim(` ${JSON.stringify(s)}`)),r}_getPrefix(t){return{debug:G.gray("[DEBUG]"),info:G.cyan("[INFO]"),warn:G.yellow("[WARN]"),error:G.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 h&&(this._level=h[t])}getLevel(){return Object.keys(h).find(t=>h[t]===this._level)}},u=new F;var B={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 W={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},ht={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};import{zodToJsonSchema as st}from"zod-to-json-schema";var M=class{static generateFileOutputInstructions(t,e){let s;typeof t?.parse=="function"?s=st(t,{target:"openApi3"}):s=t;let n=this._buildExample(s);return`
1
+ import{AgentStrategy as ct,getSkill as ft}from"@zibby/agent-workflow";import{execSync as pt,spawn as mt}from"node:child_process";import{zodToJsonSchema as dt}from"zod-to-json-schema";import{existsSync as tt,mkdirSync as et,readFileSync as rt,rmSync as ht,writeFileSync as st}from"node:fs";import{join as T}from"node:path";import P from"chalk";var g={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 g.debug;if(process.env.ZIBBY_VERBOSE==="true")return g.info;let t=process.env.LOG_LEVEL?.toLowerCase();return t&&t in g?g[t]:g.info}_shouldLog(t){return g[t]>=this._level}_formatMessage(t,e,s={}){let n=new Date().toISOString(),r=`${this._getPrefix(t)} ${e}`;return Object.keys(s).length>0&&(r+=P.dim(` ${JSON.stringify(s)}`)),r}_getPrefix(t){return{debug:P.gray("[DEBUG]"),info:P.cyan("[INFO]"),warn:P.yellow("[WARN]"),error:P.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 g&&(this._level=g[t])}getLevel(){return Object.keys(g).find(t=>g[t]===this._level)}},u=new B;var j={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"};var Q={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},_t={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};import{zodToJsonSchema as at}from"zod-to-json-schema";var k=class{static generateFileOutputInstructions(t,e){let s;typeof t?.parse=="function"?s=at(t,{target:"openApi3"}):s=t;let n=this._buildExample(s);return`
2
2
  \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
3
3
  \u{1F6A8} MANDATORY: WRITE RESULT TO FILE \u{1F6A8}
4
4
  \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
@@ -18,9 +18,9 @@ JSON types (strict \u2014 validators reject wrong types):
18
18
  - Use true/false without quotes for booleans.
19
19
  - Use unquoted null where a field may be null.
20
20
 
21
- 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 s={};for(let[n,i]of Object.entries(t.properties))s[n]=this._buildExample(i);return s}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 s=t.oneOf?.find(n=>n.type!=="null")||t.anyOf?.find(n=>n.type!=="null");return s?this._buildExample(s):null}return"<value>"}};var $=class p{constructor(t=""){this.userPrompt=t,this.systemInstructions=[],this.metadata={}}setUserPrompt(t){return this.userPrompt=t,this}appendUserPrompt(t){return this.userPrompt?this.userPrompt+=`
21
+ 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 s={};for(let[n,i]of Object.entries(t.properties))s[n]=this._buildExample(i);return s}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 s=t.oneOf?.find(n=>n.type!=="null")||t.anyOf?.find(n=>n.type!=="null");return s?this._buildExample(s):null}return"<value>"}};var C=class m{constructor(t=""){this.userPrompt=t,this.systemInstructions=[],this.metadata={}}setUserPrompt(t){return this.userPrompt=t,this}appendUserPrompt(t){return this.userPrompt?this.userPrompt+=`
22
22
 
23
- ${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 s=M.generateFileOutputInstructions(t,e);this.systemInstructions.push({type:"structured_output",content:s,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
23
+ ${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 s=k.generateFileOutputInstructions(t,e);this.systemInstructions.push({type:"structured_output",content:s,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
24
24
  \u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
25
25
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
26
26
 
@@ -28,16 +28,16 @@ ${t.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:e,p
28
28
 
29
29
  `),position:"append"}),this}addSystemInstruction(t,e="custom",s="append"){return t&&this.systemInstructions.push({type:e,content:t,position:s}),this}getUserPrompt(){return this.userPrompt}getSystemInstructions(){return this.systemInstructions}getMetadata(){return this.metadata}build(){let t=this.systemInstructions.filter(n=>n.position==="prepend").map(n=>n.content),e=this.systemInstructions.filter(n=>n.position==="append").map(n=>n.content);return[...t,this.userPrompt,...e].filter(Boolean).join(`
30
30
 
31
- `)}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(s=>s.type)}}clone(){let t=new p(this.userPrompt);return t.systemInstructions=[...this.systemInstructions],t.metadata={...this.metadata},t}};var L=class p{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(`
31
+ `)}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(s=>s.type)}}clone(){let t=new m(this.userPrompt);return t.systemInstructions=[...this.systemInstructions],t.metadata={...this.metadata},t}};var J=class m{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(`
32
32
  `);this.buffer=e.pop()||"";let s="";for(let n of e)if(n.trim())try{let i=JSON.parse(n);this._emitToolCalls(i);let r=this.extractText(i);if(r){if(this.rawText&&r.startsWith(this.rawText)){let o=r.substring(this.rawText.length);this.rawText=r,s+=o}else(!this.rawText.includes(r)||r.length<20)&&(this.rawText+=r,s+=r);this.tryExtractResult(this.rawText)}else this.isValidResult(i)&&(this.rawText+=`${n}
33
33
  `,s+=`${n}
34
- `,this.extractedResult=i)}catch{if(n.includes('"text"')||n.includes('"content"')){let r=n.match(/"text"\s*:\s*"([^"]*)/),o=n.match(/"content"\s*:\s*"([^"]*)/),l=r?r[1]:o?o[1]:null;l&&!this.rawText.includes(l)&&(s+=l,this.rawText+=l)}}return s||null}flush(){if(!this.buffer.trim())return null;let t="";try{let e=JSON.parse(this.buffer);this._emitToolCalls(e);let s=this.extractText(e);s&&(this.rawText+=s,t+=s,this.tryExtractResult(s))}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=(r,o)=>{if(!r)return;let l=`${r}:${JSON.stringify(o??{})}`;this._lastToolEmit!==l&&(this._lastToolEmit=l,this.onToolCall(r,o??void 0))},s=r=>{if(r!=null){if(typeof r=="object"&&!Array.isArray(r))return r;if(typeof r=="string")try{return JSON.parse(r)}catch{return}}};if(t.type==="tool_use"||t.type==="tool_call"){if(t.name){e(t.name,s(t.input??t.arguments));return}let r=t.tool_call;if(r&&typeof r=="object"&&!Array.isArray(r)){let o=Object.keys(r);if(o.length===1){let l=o[0],c=r[l],m=c&&typeof c=="object"?c.args??c.input??c:void 0;e(l,s(m))}return}return}if(Array.isArray(t.tool_calls)){for(let r of t.tool_calls)e(r.name,s(r.input??r.arguments));return}let n=t.message??t;if(Array.isArray(n?.tool_calls)){for(let r of n.tool_calls)e(r.name,s(r.input??r.arguments));return}let i=n?.content??t.content;if(Array.isArray(i))for(let r of i)(r.type==="tool_use"||r.type==="tool_call")&&r.name&&e(r.name,s(r.input??r.arguments))}extractText(t){if(t.type==="assistant"&&t.message?.content){let e=t.message.content;if(Array.isArray(e))return e.filter(s=>s.type==="text"&&s.text).map(s=>s.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=[],s=/```json\s*\n?([\s\S]*?)\n?```/g,n;for(;(n=s.exec(t))!==null;){let f=n[1].trim();try{JSON.parse(f),e.push({text:f,source:"markdown"})}catch{}}let i=0,r=0;for(;i<t.length&&(i=t.indexOf("{",i),i!==-1);){let f=0,g=i;for(let d=i;d<t.length;d++)if(t[d]==="{")f++;else if(t[d]==="}"&&(f--,f===0)){g=d,e.push({text:t.substring(i,g+1),source:"brace"}),r++;break}i=g+1}let o=this.extractedResult,l=o?JSON.stringify(o).length:0,c=0,m=-1;for(let f=0;f<e.length;f++){let g=e[f];try{let d=g.text.replace(/,(\s*[}\]])/g,"$1"),E=JSON.parse(d);this.isValidResult(E)&&(c++,l=JSON.stringify(E).length,o=E,m=f)}catch{}}o&&(this.extractedResult=o)}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 s=new p;s.zodSchema=e,s.processChunk(t),s.flush();let n=s.getResult();return!n&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",t?.length||0,"chars"),n}};function at(p){if(!p)return null;let t=String(p),e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);if(e?.[1])try{return JSON.parse(e[1].trim())}catch{}let s=t.indexOf("{");if(s<0)return null;let n=0,i=!1,r=!1,o=-1;for(let l=s;l<t.length;l++){let c=t[l];if(i){r?r=!1:c==="\\"?r=!0:c==='"'&&(i=!1);continue}if(c==='"'){i=!0;continue}if(c==="{"){n===0&&(o=l),n+=1;continue}if(c==="}"){if(n===0)continue;if(n-=1,n===0&&o>=0){let m=t.slice(o,l+1);try{return JSON.parse(m)}catch{o=-1}}}}return null}function ft(p){let t=String(p||"").trim();if(!t)return null;try{return JSON.parse(t)}catch{return at(t)}}function pt(p){try{let t=JSON.parse(p);if(typeof t=="string")return t;if(typeof t?.response=="string")return t.response;if(typeof t?.text=="string")return t.text;if(typeof t?.output=="string")return t.output;if(Array.isArray(t?.candidates)&&t.candidates.length>0){let e=t.candidates[0];if(typeof e?.content=="string")return e.content;if(Array.isArray(e?.content?.parts)){let s=e.content.parts.map(n=>typeof n?.text=="string"?n.text:"").join("");if(s.trim())return s}}}catch{}return p}var j=class extends nt{constructor(){super("gemini","Gemini (Google)",70)}canHandle(t){if(!!!(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY))return u.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return ot("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return u.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(t,e={}){let{model:s,workspace:n=process.cwd(),schema:i=null,skills:r=null,sessionPath:o=null,nodeName:l=null,timeout:c=600*1e3}=e,m=s;(!m||m==="auto")&&(m=B.GEMINI);let f=W[m]||m,g=String(process.env.GEMINI_API_KEY||"").trim(),d=String(process.env.GOOGLE_API_KEY||"").trim(),E=this._resolveSkillsToMcp(r,{sessionPath:o,workspace:n,nodeName:l}),K=Object.keys(E).length>0,x=new $(t),k=i&&typeof i.parse=="function",b=null;if(i){let a;try{let S=k?ut(i,{target:"openAi"}):i;a=JSON.stringify(S,null,2)}catch{a="{}"}if(K){x.addSystemInstruction(`Write valid JSON that matches this schema:
35
- ${a}`,"schema_instruction","append");let S=`zibby-result-${Date.now()}.json`,O=N(n,".zibby","tmp");b=N(O,S),q(O,{recursive:!0}),x.addStructuredOutput(i,b)}else x.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
36
- ${a}`,"json_instruction","append")}let Q=x.build(),tt=x.getUserPrompt(),P=x.getStats(),Y=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),et=Y?` | key: ***${Y.slice(-4)}`:" | key: not set";console.log(`
37
- \u25C6 Model: ${f||"auto"}${et}
38
- `);let R=(await import("chalk")).default;console.log(`
39
- ${R.bold("Prompt sent to LLM:")}`),console.log(R.dim("\u2500".repeat(60))),console.log(R.dim(tt)),console.log(R.dim("\u2500".repeat(60)));let C=this._createGeminiConfigDir(n,E),I=["--output-format","json"];f&&f!=="auto"&&I.push("--model",f);let J=Object.keys(E);if(J.length>0){I.push("--approval-mode","yolo");for(let a of J)I.push("--allowed-mcp-server-names",a);u.info(`[Gemini] Enabling MCP servers: ${J.join(", ")}`)}else r&&r.length>0&&u.warn(`[Gemini] Skills requested but no MCP servers configured: ${r.join(", ")}`);I.push("-p",Q);let v={...process.env,GEMINI_CLI_HOME:C};g?(v.GEMINI_API_KEY=g,delete v.GOOGLE_API_KEY):d&&(v.GOOGLE_API_KEY=d,delete v.GEMINI_API_KEY),u.debug(`[Gemini] Command: gemini ${I.slice(0,8).join(" ")}... (${I.length} total args)`),u.debug(`[Gemini] User prompt: ${P.userPromptLength} chars, System instructions: ${P.systemInstructionsLength} chars (${P.instructionCount} blocks), Full: ${P.fullPromptLength} chars`),u.debug(`[Gemini] Config home: ${C}`),u.debug(`[Gemini] GEMINI_CLI_HOME env: ${v.GEMINI_CLI_HOME}`);let D="",A=null;try{D=await new Promise((S,O)=>{let T=lt("gemini",I,{cwd:n,env:v,stdio:["ignore","pipe","pipe"]}),U="",z="",V=setTimeout(()=>{try{T.kill("SIGTERM")}catch{}},c);T.stdout.on("data",_=>{U+=_.toString()}),T.stderr.on("data",_=>{z+=_.toString()}),T.on("error",_=>{clearTimeout(V),O(_)}),T.on("close",_=>{if(clearTimeout(V),_===0)return S(U.trim());O(new Error(`gemini failed with code ${_}: ${(z||U).trim()}`))})})}catch(a){A=a}finally{try{ct(C,{recursive:!0,force:!0})}catch{}}let y=pt(D).trim();if(!i){if(A)throw A;return y}if(b){let a=H(b);if(u.info(`[Gemini] Result file: ${a?"present":"missing"} at ${b}`),a)try{let S=X(b,"utf-8").trim(),O=JSON.parse(S),T=k?i.parse(O):O;return u.info("[Gemini] Structured output recovered from result file"),{raw:y,structured:T}}catch(S){u.warn(`[Gemini] Result file parse/validation failed: ${S.message}`)}else A||u.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let w=null;if(i){let a=new L;a.zodSchema=i,a.processChunk(y),a.flush(),w=a.getResult()}if(u.info(`[Gemini] Raw stdout length: ${D.length} chars`),u.info(`[Gemini] Extracted text length: ${y.length} chars`),u.info(`[Gemini] StreamParser result: ${w?"extracted":"null"}`),w||(y.length<2e3?u.info(`[Gemini] Raw text preview:
34
+ `,this.extractedResult=i)}catch{if(n.includes('"text"')||n.includes('"content"')){let r=n.match(/"text"\s*:\s*"([^"]*)/),o=n.match(/"content"\s*:\s*"([^"]*)/),l=r?r[1]:o?o[1]:null;l&&!this.rawText.includes(l)&&(s+=l,this.rawText+=l)}}return s||null}flush(){if(!this.buffer.trim())return null;let t="";try{let e=JSON.parse(this.buffer);this._emitToolCalls(e);let s=this.extractText(e);s&&(this.rawText+=s,t+=s,this.tryExtractResult(s))}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=(r,o)=>{if(!r)return;let l=`${r}:${JSON.stringify(o??{})}`;this._lastToolEmit!==l&&(this._lastToolEmit=l,this.onToolCall(r,o??void 0))},s=r=>{if(r!=null){if(typeof r=="object"&&!Array.isArray(r))return r;if(typeof r=="string")try{return JSON.parse(r)}catch{return}}};if(t.type==="tool_use"||t.type==="tool_call"){if(t.name){e(t.name,s(t.input??t.arguments));return}let r=t.tool_call;if(r&&typeof r=="object"&&!Array.isArray(r)){let o=Object.keys(r);if(o.length===1){let l=o[0],a=r[l],c=a&&typeof a=="object"?a.args??a.input??a:void 0;e(l,s(c))}return}return}if(Array.isArray(t.tool_calls)){for(let r of t.tool_calls)e(r.name,s(r.input??r.arguments));return}let n=t.message??t;if(Array.isArray(n?.tool_calls)){for(let r of n.tool_calls)e(r.name,s(r.input??r.arguments));return}let i=n?.content??t.content;if(Array.isArray(i))for(let r of i)(r.type==="tool_use"||r.type==="tool_call")&&r.name&&e(r.name,s(r.input??r.arguments))}extractText(t){if(t.type==="assistant"&&t.message?.content){let e=t.message.content;if(Array.isArray(e))return e.filter(s=>s.type==="text"&&s.text).map(s=>s.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=[],s=/```json\s*\n?([\s\S]*?)\n?```/g,n;for(;(n=s.exec(t))!==null;){let f=n[1].trim();try{JSON.parse(f),e.push({text:f,source:"markdown"})}catch{}}let i=0,r=0;for(;i<t.length&&(i=t.indexOf("{",i),i!==-1);){let f=0,d=i;for(let h=i;h<t.length;h++)if(t[h]==="{")f++;else if(t[h]==="}"&&(f--,f===0)){d=h,e.push({text:t.substring(i,d+1),source:"brace"}),r++;break}i=d+1}let o=this.extractedResult,l=o?JSON.stringify(o).length:0,a=0,c=-1;for(let f=0;f<e.length;f++){let d=e[f];try{let h=d.text.replace(/,(\s*[}\]])/g,"$1"),w=JSON.parse(h);this.isValidResult(w)&&(a++,l=JSON.stringify(w).length,o=w,c=f)}catch{}}o&&(this.extractedResult=o)}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 s=new m;s.zodSchema=e,s.processChunk(t),s.flush();let n=s.getResult();return!n&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",t?.length||0,"chars"),n}};function gt(m){if(!m)return null;let t=String(m),e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);if(e?.[1])try{return JSON.parse(e[1].trim())}catch{}let s=t.indexOf("{");if(s<0)return null;let n=0,i=!1,r=!1,o=-1;for(let l=s;l<t.length;l++){let a=t[l];if(i){r?r=!1:a==="\\"?r=!0:a==='"'&&(i=!1);continue}if(a==='"'){i=!0;continue}if(a==="{"){n===0&&(o=l),n+=1;continue}if(a==="}"){if(n===0)continue;if(n-=1,n===0&&o>=0){let c=t.slice(o,l+1);try{return JSON.parse(c)}catch{o=-1}}}}return null}function yt(m){let t=String(m||"").trim();if(!t)return null;try{return JSON.parse(t)}catch{return gt(t)}}function St(m){try{let t=JSON.parse(m);if(typeof t=="string")return t;if(typeof t?.response=="string")return t.response;if(typeof t?.text=="string")return t.text;if(typeof t?.output=="string")return t.output;if(Array.isArray(t?.candidates)&&t.candidates.length>0){let e=t.candidates[0];if(typeof e?.content=="string")return e.content;if(Array.isArray(e?.content?.parts)){let s=e.content.parts.map(n=>typeof n?.text=="string"?n.text:"").join("");if(s.trim())return s}}}catch{}return m}var nt=class extends ct{constructor(){super("gemini","Gemini (Google)",70)}canHandle(t){if(!!!(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY))return u.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return pt("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return u.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(t,e={}){let{model:s,workspace:n=process.cwd(),schema:i=null,skills:r=null,sessionPath:o=null,nodeName:l=null,timeout:a=600*1e3,signal:c=null}=e,f=s;(!f||f==="auto")&&(f=j.GEMINI);let d=Q[f]||f,h=String(process.env.GEMINI_API_KEY||"").trim(),w=String(process.env.GOOGLE_API_KEY||"").trim(),R=this._resolveSkillsToMcp(r,{sessionPath:o,workspace:n,nodeName:l}),W=Object.keys(R).length>0,b=new C(t),D=i&&typeof i.parse=="function",N=null;if(i){let p;try{let S=D?dt(i,{target:"openAi"}):i;p=JSON.stringify(S,null,2)}catch{p="{}"}if(W){b.addSystemInstruction(`Write valid JSON that matches this schema:
35
+ ${p}`,"schema_instruction","append");let S=`zibby-result-${Date.now()}.json`,E=T(n,".zibby","tmp");N=T(E,S),et(E,{recursive:!0}),b.addStructuredOutput(i,N)}else b.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
36
+ ${p}`,"json_instruction","append")}let it=b.build(),ot=b.getUserPrompt(),M=b.getStats(),H=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),lt=H?` | key: ***${H.slice(-4)}`:" | key: not set";console.log(`
37
+ \u25C6 Model: ${d||"auto"}${lt}
38
+ `);let L=(await import("chalk")).default;console.log(`
39
+ ${L.bold("Prompt sent to LLM:")}`),console.log(L.dim("\u2500".repeat(60))),console.log(L.dim(ot)),console.log(L.dim("\u2500".repeat(60)));let U=this._createGeminiConfigDir(n,R),x=["--output-format","json"];d&&d!=="auto"&&x.push("--model",d);let K=Object.keys(R);if(K.length>0){x.push("--approval-mode","yolo");for(let p of K)x.push("--allowed-mcp-server-names",p);u.info(`[Gemini] Enabling MCP servers: ${K.join(", ")}`)}else r&&r.length>0&&u.warn(`[Gemini] Skills requested but no MCP servers configured: ${r.join(", ")}`);x.push("-p",it);let v={...process.env,GEMINI_CLI_HOME:U};h?(v.GEMINI_API_KEY=h,delete v.GOOGLE_API_KEY):w&&(v.GOOGLE_API_KEY=w,delete v.GEMINI_API_KEY),u.debug(`[Gemini] Command: gemini ${x.slice(0,8).join(" ")}... (${x.length} total args)`),u.debug(`[Gemini] User prompt: ${M.userPromptLength} chars, System instructions: ${M.systemInstructionsLength} chars (${M.instructionCount} blocks), Full: ${M.fullPromptLength} chars`),u.debug(`[Gemini] Config home: ${U}`),u.debug(`[Gemini] GEMINI_CLI_HOME env: ${v.GEMINI_CLI_HOME}`);let F="",A=null;try{F=await new Promise((S,E)=>{let O=mt("gemini",x,{cwd:n,env:v,stdio:["ignore","pipe","pipe"],...c&&{signal:c}}),Y="",q="",z=!1,G=null,V=!1,X=setTimeout(()=>{try{O.kill("SIGTERM")}catch{}},a),$=()=>{V||z||(V=!0,G=setTimeout(()=>{if(!z)try{O.kill("SIGKILL")}catch{}},5e3))};c&&(c.aborted?$():c.addEventListener("abort",$,{once:!0})),O.stdout.on("data",_=>{Y+=_.toString()}),O.stderr.on("data",_=>{q+=_.toString()}),O.on("error",_=>{if(clearTimeout(X),G&&clearTimeout(G),c&&!c.aborted)try{c.removeEventListener("abort",$)}catch{}E(_)}),O.on("close",_=>{if(z=!0,clearTimeout(X),G&&clearTimeout(G),c&&!c.aborted)try{c.removeEventListener("abort",$)}catch{}if(V){let Z=new Error("Aborted via signal");return Z.name="AbortError",E(Z)}if(_===0)return S(Y.trim());E(new Error(`gemini failed with code ${_}: ${(q||Y).trim()}`))})})}catch(p){A=p}finally{try{ht(U,{recursive:!0,force:!0})}catch{}}let y=St(F).trim();if(!i){if(A)throw A;return y}if(N){let p=tt(N);if(u.info(`[Gemini] Result file: ${p?"present":"missing"} at ${N}`),p)try{let S=rt(N,"utf-8").trim(),E=JSON.parse(S),O=D?i.parse(E):E;return u.info("[Gemini] Structured output recovered from result file"),{raw:y,structured:O}}catch(S){u.warn(`[Gemini] Result file parse/validation failed: ${S.message}`)}else A||u.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let I=null;if(i){let p=new J;p.zodSchema=i,p.processChunk(y),p.flush(),I=p.getResult()}if(u.info(`[Gemini] Raw stdout length: ${F.length} chars`),u.info(`[Gemini] Extracted text length: ${y.length} chars`),u.info(`[Gemini] StreamParser result: ${I?"extracted":"null"}`),I||(y.length<2e3?u.info(`[Gemini] Raw text preview:
40
40
  ${y}`):u.info(`[Gemini] Raw text preview (first 1000 chars):
41
- ${y.slice(0,1e3)}`),w=ft(y)),!w)throw A||(u.error("[Gemini] Failed to extract valid JSON from output"),u.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error("Gemini did not return valid JSON for structured output. Enable strictMode for proxy fallback."));let rt=k?i.parse(w):w;return{raw:y,structured:rt}}_resolveSkillsToMcp(t,e={}){if(!Array.isArray(t)||t.length===0)return{};let s={};for(let n of t){let i=it(n);if(!i||typeof i.resolve!="function")continue;let r=i.resolve(e);if(!r)continue;let o=i.cursorKey||i.serverName||n,l={command:r.command};r.args?.length&&(l.args=r.args),r.env&&Object.keys(r.env).length>0&&(l.env=r.env),r.cwd&&(l.cwd=r.cwd),s[o]=l}return s}_createGeminiConfigDir(t,e){let s=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,n=N(t||process.cwd(),".zibby","tmp",`gemini-home-${s}`),i=N(n,".gemini");q(i,{recursive:!0});let r=N(i,"settings.json"),o={},l=N(process.env.HOME||"",".gemini","settings.json");if(H(l))try{o=JSON.parse(X(l,"utf-8"))}catch{o={}}let c={...o,mcpServers:{...o.mcpServers&&typeof o.mcpServers=="object"?o.mcpServers:{},...e||{}}};Z(r,`${JSON.stringify(c,null,2)}
42
- `,"utf-8");let m=N(t||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{Z(m,`${JSON.stringify(c,null,2)}
43
- `,"utf-8")}catch{}return u.debug(`[Gemini] Created isolated config with ${Object.keys(c.mcpServers||{}).length} MCP servers`),u.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(c.mcpServers||{}),null,2)}`),n}};export{j as GeminiAgentStrategy};
41
+ ${y.slice(0,1e3)}`),I=yt(y)),!I)throw A||(u.error("[Gemini] Failed to extract valid JSON from output"),u.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error("Gemini did not return valid JSON for structured output. Enable strictMode for proxy fallback."));let ut=D?i.parse(I):I;return{raw:y,structured:ut}}_resolveSkillsToMcp(t,e={}){if(!Array.isArray(t)||t.length===0)return{};let s={};for(let n of t){let i=ft(n);if(!i||typeof i.resolve!="function")continue;let r=i.resolve(e);if(!r)continue;let o=i.cursorKey||i.serverName||n,l={command:r.command};r.args?.length&&(l.args=r.args),r.env&&Object.keys(r.env).length>0&&(l.env=r.env),r.cwd&&(l.cwd=r.cwd),s[o]=l}return s}_createGeminiConfigDir(t,e){let s=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,n=T(t||process.cwd(),".zibby","tmp",`gemini-home-${s}`),i=T(n,".gemini");et(i,{recursive:!0});let r=T(i,"settings.json"),o={},l=T(process.env.HOME||"",".gemini","settings.json");if(tt(l))try{o=JSON.parse(rt(l,"utf-8"))}catch{o={}}let a={...o,mcpServers:{...o.mcpServers&&typeof o.mcpServers=="object"?o.mcpServers:{},...e||{}}};st(r,`${JSON.stringify(a,null,2)}
42
+ `,"utf-8");let c=T(t||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{st(c,`${JSON.stringify(a,null,2)}
43
+ `,"utf-8")}catch{}return u.debug(`[Gemini] Created isolated config with ${Object.keys(a.mcpServers||{}).length} MCP servers`),u.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(a.mcpServers||{}),null,2)}`),n}};export{nt as GeminiAgentStrategy};