@zibby/core 0.5.5 → 0.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,45 +1,45 @@
1
- import{AgentStrategy as kt,DEFAULT_OUTPUT_BASE as Lt,SESSION_INFO_FILE as Mt,STOP_REQUEST_FILE as Ut,getAllSkills as Dt,getSkill as ct}from"@zibby/agent-workflow";import{spawn as Bt,execSync as F}from"node:child_process";import{writeFileSync as pt,readFileSync as ft,mkdirSync as dt,existsSync as H,accessSync as gt,constants as mt,unlinkSync as Ft}from"node:fs";import{join as $,resolve as Jt}from"node:path";import{homedir as j}from"node:os";import z from"chalk";var P={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 P.debug;if(process.env.ZIBBY_VERBOSE==="true")return P.info;let t=process.env.LOG_LEVEL?.toLowerCase();return t&&t in P?P[t]:P.info}_shouldLog(t){return P[t]>=this._level}_formatMessage(t,e,r={}){let o=new Date().toISOString(),n=`${this._getPrefix(t)} ${e}`;return Object.keys(r).length>0&&(n+=z.dim(` ${JSON.stringify(r)}`)),n}_getPrefix(t){return{debug:z.gray("[DEBUG]"),info:z.cyan("[INFO]"),warn:z.yellow("[WARN]"),error:z.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 P&&(this._level=P[t])}getLevel(){return Object.keys(P).find(t=>P[t]===this._level)}},s=new et;var Y={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-3-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"};var Z={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var X=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 o of e)if(o.trim())try{let a=JSON.parse(o);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+=`${o}
3
- `,r+=`${o}
4
- `,this.extractedResult=a)}catch{if(o.includes('"text"')||o.includes('"content"')){let n=o.match(/"text"\s*:\s*"([^"]*)/),u=o.match(/"content"\s*:\s*"([^"]*)/),c=n?n[1]:u?u[1]:null;c&&!this.rawText.includes(c)&&(r+=c,this.rawText+=c)}}return r||null}flush(){if(!this.buffer.trim())return null;let t="";try{let e=JSON.parse(this.buffer);this._emitToolCalls(e);let r=this.extractText(e);r&&(this.rawText+=r,t+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,t+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",t||null}_emitToolCalls(t){if(!this.onToolCall)return;let e=(n,u)=>{if(!n)return;let c=`${n}:${JSON.stringify(u??{})}`;this._lastToolEmit!==c&&(this._lastToolEmit=c,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 c=u[0],y=n[c],p=y&&typeof y=="object"?y.args??y.input??y:void 0;e(c,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 o=t.message??t;if(Array.isArray(o?.tool_calls)){for(let n of o.tool_calls)e(n.name,r(n.input??n.arguments));return}let a=o?.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,o;for(;(o=r.exec(t))!==null;){let g=o[1].trim();try{JSON.parse(g),e.push({text:g,source:"markdown"})}catch{}}let a=0,n=0;for(;a<t.length&&(a=t.indexOf("{",a),a!==-1);){let g=0,f=a;for(let O=a;O<t.length;O++)if(t[O]==="{")g++;else if(t[O]==="}"&&(g--,g===0)){f=O,e.push({text:t.substring(a,f+1),source:"brace"}),n++;break}a=f+1}let u=this.extractedResult,c=u?JSON.stringify(u).length:0,y=0,p=-1;for(let g=0;g<e.length;g++){let f=e[g];try{let O=f.text.replace(/,(\s*[}\]])/g,"$1"),I=JSON.parse(O);this.isValidResult(I)&&(y++,c=JSON.stringify(I).length,u=I,p=g)}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 i;r.zodSchema=e,r.processChunk(t),r.flush();let o=r.getResult();return!o&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",t?.length||0,"chars"),o}};import{zodToJsonSchema as yt}from"zod-to-json-schema";var q=class{static generateFileOutputInstructions(t,e){let r;typeof t?.parse=="function"?r=yt(t,{target:"openApi3"}):r=t;let o=this._buildExample(r);return`
1
+ import{AgentStrategy as De,DEFAULT_OUTPUT_BASE as Fe,SESSION_INFO_FILE as Ge,STOP_REQUEST_FILE as Be,getAllSkills as Je,getSkill as pe}from"@zibby/agent-workflow";import{spawn as Ke,execSync as G}from"node:child_process";import{writeFileSync as fe,readFileSync as me,mkdirSync as ge,existsSync as Y,accessSync as he,constants as ye,unlinkSync as Ve}from"node:fs";import{join as w,resolve as ze}from"node:path";import{homedir as H}from"node:os";import V from"chalk";var P={debug:0,info:1,warn:2,error:3,silent:4},re=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return P.debug;if(process.env.ZIBBY_VERBOSE==="true")return P.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in P?P[e]:P.info}_shouldLog(e){return P[e]>=this._level}_formatMessage(e,t,r={}){let s=new Date().toISOString(),n=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(n+=V.dim(` ${JSON.stringify(r)}`)),n}_getPrefix(e){return{debug:V.gray("[DEBUG]"),info:V.cyan("[INFO]"),warn:V.yellow("[WARN]"),error:V.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 P&&(this._level=P[e])}getLevel(){return Object.keys(P).find(e=>P[e]===this._level)}},i=new re;var Oe=[{alias:"auto",canonicalId:"claude-sonnet-4-6",vendor:"claude",label:"Claude \xB7 Sonnet 4.6",family:"claude-sonnet-4",pickerVisible:!0,isDefault:!0},{alias:"opus-4.8",canonicalId:"claude-opus-4-8",vendor:"claude",label:"Claude \xB7 Opus 4.8",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-8",canonicalId:"claude-opus-4-8",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.8"},{alias:"sonnet-4.8",canonicalId:"claude-sonnet-4-8",vendor:"claude",label:"Claude \xB7 Sonnet 4.8",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-8",canonicalId:"claude-sonnet-4-8",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.8"},{alias:"opus-4.7",canonicalId:"claude-opus-4-7",vendor:"claude",label:"Claude \xB7 Opus 4.7",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-7",canonicalId:"claude-opus-4-7",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.7"},{alias:"sonnet-4.7",canonicalId:"claude-sonnet-4-7",vendor:"claude",label:"Claude \xB7 Sonnet 4.7",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-7",canonicalId:"claude-sonnet-4-7",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.7"},{alias:"sonnet-4.6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"auto"},{alias:"sonnet-4-6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"auto"},{alias:"opus-4.6",canonicalId:"claude-opus-4-6",vendor:"claude",label:"Claude \xB7 Opus 4.6",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-6",canonicalId:"claude-opus-4-6",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.6"},{alias:"sonnet-4.5",canonicalId:"claude-sonnet-4-5-20250929",vendor:"claude",label:"Claude \xB7 Sonnet 4.5",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-5",canonicalId:"claude-sonnet-4-5-20250929",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.5"},{alias:"opus-4.5",canonicalId:"claude-opus-4-5-20251101",vendor:"claude",label:"Claude \xB7 Opus 4.5",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-5",canonicalId:"claude-opus-4-5-20251101",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.5"},{alias:"haiku-4.5",canonicalId:"claude-haiku-4-5-20251001",vendor:"claude",label:"Claude \xB7 Haiku 4.5",family:"claude-haiku-4"},{alias:"haiku-4-5",canonicalId:"claude-haiku-4-5-20251001",vendor:"claude",family:"claude-haiku-4",aliasOf:"haiku-4.5"},{alias:"claude-opus-4-8",canonicalId:"claude-opus-4-8",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.8"},{alias:"claude-sonnet-4-8",canonicalId:"claude-sonnet-4-8",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.8"},{alias:"claude-opus-4-7",canonicalId:"claude-opus-4-7",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.7"},{alias:"claude-sonnet-4-7",canonicalId:"claude-sonnet-4-7",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.7"},{alias:"claude-sonnet-4-6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"auto"},{alias:"claude-opus-4-6",canonicalId:"claude-opus-4-6",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.6"},{alias:"claude-sonnet-4-5-20250929",canonicalId:"claude-sonnet-4-5-20250929",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.5"},{alias:"claude-opus-4-5-20251101",canonicalId:"claude-opus-4-5-20251101",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.5"},{alias:"claude-haiku-4-5-20251001",canonicalId:"claude-haiku-4-5-20251001",vendor:"claude",family:"claude-haiku-4",aliasOf:"haiku-4.5"},{alias:"claude-opus-4-20250514",canonicalId:"claude-opus-4-20250514",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.5"},{alias:"auto",canonicalId:"o4-mini",vendor:"codex",label:"Codex \xB7 o4-mini",family:"o4-mini",isDefault:!0},{alias:"o4-mini",canonicalId:"o4-mini",vendor:"codex",label:"Codex \xB7 o4-mini",family:"o4-mini",pickerVisible:!0},{alias:"o3",canonicalId:"o3",vendor:"codex",family:"o3"},{alias:"o3-mini",canonicalId:"o3-mini",vendor:"codex",family:"o3-mini"},{alias:"codex-mini",canonicalId:"codex-mini-latest",vendor:"codex",family:"codex-mini"},{alias:"gpt-4o",canonicalId:"gpt-4o",vendor:"codex",label:"Codex \xB7 GPT-4o",family:"gpt-4o",pickerVisible:!0},{alias:"gpt-4o-mini",canonicalId:"gpt-4o-mini",vendor:"codex",label:"Codex \xB7 GPT-4o mini",family:"gpt-4o-mini",pickerVisible:!0},{alias:"gpt-5.2-codex",canonicalId:"gpt-5.2-codex",vendor:"codex",label:"Codex \xB7 GPT-5.2",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.2",canonicalId:"gpt-5.2",vendor:"codex",label:"Codex \xB7 GPT-5.2 base",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.3",canonicalId:"gpt-5.3",vendor:"codex",label:"Codex \xB7 GPT-5.3",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.3-codex",canonicalId:"gpt-5.3-codex",vendor:"codex",family:"gpt-5"},{alias:"gpt-5.4",canonicalId:"gpt-5.4",vendor:"codex",label:"Codex \xB7 GPT-5.4",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.5",canonicalId:"gpt-5.5",vendor:"codex",label:"Codex \xB7 GPT-5.5",family:"gpt-5",pickerVisible:!0},{alias:"auto",canonicalId:"gemini-3-pro",vendor:"gemini",label:"Gemini \xB7 3 Pro",family:"gemini-3",isDefault:!0},{alias:"gemini-3-pro",canonicalId:"gemini-3-pro",vendor:"gemini",label:"Gemini \xB7 3 Pro",family:"gemini-3",pickerVisible:!0},{alias:"gemini-3-flash",canonicalId:"gemini-3-flash",vendor:"gemini",label:"Gemini \xB7 3 Flash",family:"gemini-3",pickerVisible:!0},{alias:"gemini-2.5-pro",canonicalId:"gemini-2.5-pro",vendor:"gemini",label:"Gemini \xB7 2.5 Pro",family:"gemini-2.5",pickerVisible:!0},{alias:"gemini-2.5-flash",canonicalId:"gemini-2.5-flash",vendor:"gemini",label:"Gemini \xB7 2.5 Flash",family:"gemini-2.5",pickerVisible:!0}];function W(o){let e={};for(let t of Oe)t.vendor===o&&(e[t.alias]=t.canonicalId);return e}var z={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-3-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"};var Ze=W("claude"),Xe=W("codex"),qe=W("gemini"),Z={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var X=class o{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(e){if(!e)return null;this.buffer+=e;let t=this.buffer.split(`
2
+ `);this.buffer=t.pop()||"";let r="";for(let s of t)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 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(l)&&(this.rawText+=`${s}
3
+ `,r+=`${s}
4
+ `,this.extractedResult=l)}catch{if(s.includes('"text"')||s.includes('"content"')){let n=s.match(/"text"\s*:\s*"([^"]*)/),u=s.match(/"content"\s*:\s*"([^"]*)/),c=n?n[1]:u?u[1]:null;c&&!this.rawText.includes(c)&&(r+=c,this.rawText+=c)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(n,u)=>{if(!n)return;let c=`${n}:${JSON.stringify(u??{})}`;this._lastToolEmit!==c&&(this._lastToolEmit=c,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(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,r(e.input??e.arguments));return}let n=e.tool_call;if(n&&typeof n=="object"&&!Array.isArray(n)){let u=Object.keys(n);if(u.length===1){let c=u[0],y=n[c],d=y&&typeof y=="object"?y.args??y.input??y:void 0;t(c,r(d))}return}return}if(Array.isArray(e.tool_calls)){for(let n of e.tool_calls)t(n.name,r(n.input??n.arguments));return}let s=e.message??e;if(Array.isArray(s?.tool_calls)){for(let n of s.tool_calls)t(n.name,r(n.input??n.arguments));return}let l=s?.content??e.content;if(Array.isArray(l))for(let n of l)(n.type==="tool_use"||n.type==="tool_call")&&n.name&&t(n.name,r(n.input??n.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return e.type==="thinking"&&e.text||e.text?e.text:e.content&&typeof e.content=="string"?e.content:e.delta?e.delta:null}tryExtractResult(e){if(!e||typeof e!="string")return;let t=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,s;for(;(s=r.exec(e))!==null;){let m=s[1].trim();try{JSON.parse(m),t.push({text:m,source:"markdown"})}catch{}}let l=0,n=0;for(;l<e.length&&(l=e.indexOf("{",l),l!==-1);){let m=0,p=l;for(let b=l;b<e.length;b++)if(e[b]==="{")m++;else if(e[b]==="}"&&(m--,m===0)){p=b,t.push({text:e.substring(l,p+1),source:"brace"}),n++;break}l=p+1}let u=this.extractedResult,c=u?JSON.stringify(u).length:0,y=0,d=-1;for(let m=0;m<t.length;m++){let p=t[m];try{let b=p.text.replace(/,(\s*[}\]])/g,"$1"),x=JSON.parse(b);this.isValidResult(x)&&(y++,c=JSON.stringify(x).length,u=x,d=m)}catch{}}u&&(this.extractedResult=u)}isValidResult(e){if(!e||typeof e!="object"||Array.isArray(e)||e.session_id||e.timestamp_ms||e.type||e.call_id||e.tool_call||e.result&&typeof e.result=="object"&&(e.result.success&&typeof e.result.success=="object"||e.result.error&&typeof e.result.error=="object")||e.args&&typeof e.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(e),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(e,t=null){let r=new o;r.zodSchema=t,r.processChunk(e),r.flush();let s=r.getResult();return!s&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),s}};import{z as se}from"zod";import{zodToJsonSchema as Ie}from"zod-to-json-schema";function ve(o){if(!o)return null;if(typeof se?.toJSONSchema=="function")try{return se.toJSONSchema(o)}catch{}try{return Ie(o,{target:"openApi3"})}catch{return null}}var q=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=ve(e):r=e;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
8
8
  You MUST write your final result as pure JSON to this EXACT file path:
9
9
 
10
- ${e}
10
+ ${t}
11
11
 
12
12
  Use your file writing tool (WriteFile or ApplyPatch) to create this file.
13
13
  DO NOT just output JSON to stdout. The file MUST exist when you finish.
14
14
  DO NOT skip this step. The workflow WILL FAIL if the file is missing.
15
15
 
16
16
  Required JSON structure:
17
- ${JSON.stringify(o,null,2)}
17
+ ${JSON.stringify(s,null,2)}
18
18
 
19
19
  JSON types (strict \u2014 validators reject wrong types):
20
20
  - Use bare JSON numbers for numeric fields (e.g. 3000). Do NOT quote them as strings (wrong: "3000").
21
21
  - Use true/false without quotes for booleans.
22
22
  - Use unquoted null where a field may be null.
23
23
 
24
- Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(t){if(!t)return{};let e=t.type;if(e==="object"&&t.properties){let r={};for(let[o,a]of Object.entries(t.properties))r[o]=this._buildExample(a);return r}if(e==="array"&&t.items)return[this._buildExample(t.items)];if(t.enum&&Array.isArray(t.enum)&&t.enum.length>0)return`<${t.enum.join("|")}>`;if(e==="string")return"<string>";if(e==="number"||e==="integer")return 0;if(e==="boolean")return!1;if(t.description)return`<${t.description}>`;if(t.nullable||t.oneOf||t.anyOf){let r=t.oneOf?.find(o=>o.type!=="null")||t.anyOf?.find(o=>o.type!=="null");return r?this._buildExample(r):null}return"<value>"}};var 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+=`
24
+ Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(e){if(!e)return{};let t=e.type;if(t==="object"&&e.properties){let r={};for(let[s,l]of Object.entries(e.properties))r[s]=this._buildExample(l);return r}if(t==="array"&&e.items)return[this._buildExample(e.items)];if(e.enum&&Array.isArray(e.enum)&&e.enum.length>0)return`<${e.enum.join("|")}>`;if(t==="string")return"<string>";if(t==="number"||t==="integer")return 0;if(t==="boolean")return!1;if(e.description)return`<${e.description}>`;if(e.nullable||e.oneOf||e.anyOf){let r=e.oneOf?.find(s=>s.type!=="null")||e.anyOf?.find(s=>s.type!=="null");return r?this._buildExample(r):null}return"<value>"}};var Q=class o{constructor(e=""){this.userPrompt=e,this.systemInstructions=[],this.metadata={}}setUserPrompt(e){return this.userPrompt=e,this}appendUserPrompt(e){return this.userPrompt?this.userPrompt+=`
25
25
 
26
- ${t}`:this.userPrompt=t,this}addSkillHints(t){return t&&this.systemInstructions.push({type:"skill_hints",content:t,position:"prepend"}),this}addStructuredOutput(t,e){if(t&&e){let r=q.generateFileOutputInstructions(t,e);this.systemInstructions.push({type:"structured_output",content:r,position:"append"}),this.metadata.structuredOutputPath=e}return this}addExtraInstructions(t){if(t?.trim()){let e=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
26
+ ${e}`:this.userPrompt=e,this}addSkillHints(e){return e&&this.systemInstructions.push({type:"skill_hints",content:e,position:"prepend"}),this}addStructuredOutput(e,t){if(e&&t){let r=q.generateFileOutputInstructions(e,t);this.systemInstructions.push({type:"structured_output",content:r,position:"append"}),this.metadata.structuredOutputPath=t}return this}addExtraInstructions(e){if(e?.trim()){let t=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
27
27
  \u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
28
28
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
29
29
 
30
- ${t.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:e,position:"append"})}return this}addSkillFragments(t){return t&&t.length>0&&this.systemInstructions.push({type:"skill_fragments",content:t.join(`
30
+ ${e.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:t,position:"append"})}return this}addSkillFragments(e){return e&&e.length>0&&this.systemInstructions.push({type:"skill_fragments",content:e.join(`
31
31
 
32
- `),position:"append"}),this}addSystemInstruction(t,e="custom",r="append"){return t&&this.systemInstructions.push({type:e,content:t,position:r}),this}getUserPrompt(){return this.userPrompt}getSystemInstructions(){return this.systemInstructions}getMetadata(){return this.metadata}build(){let t=this.systemInstructions.filter(o=>o.position==="prepend").map(o=>o.content),e=this.systemInstructions.filter(o=>o.position==="append").map(o=>o.content);return[...t,this.userPrompt,...e].filter(Boolean).join(`
32
+ `),position:"append"}),this}addSystemInstruction(e,t="custom",r="append"){return e&&this.systemInstructions.push({type:t,content:e,position:r}),this}getUserPrompt(){return this.userPrompt}getSystemInstructions(){return this.systemInstructions}getMetadata(){return this.metadata}build(){let e=this.systemInstructions.filter(s=>s.position==="prepend").map(s=>s.content),t=this.systemInstructions.filter(s=>s.position==="append").map(s=>s.content);return[...e,this.userPrompt,...t].filter(Boolean).join(`
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 i(this.userPrompt);return t.systemInstructions=[...this.systemInstructions],t.metadata={...this.metadata},t}};import Ot from"axios";import{homedir as Et}from"node:os";import{join as St}from"node:path";import{existsSync as _t,readFileSync as bt}from"node:fs";import{toJSONSchema as At}from"zod";function It(){if(process.env.OPENAI_PROXY_TOKEN)return s.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return s.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let i=St(Et(),".zibby","config.json");if(_t(i)){let t=JSON.parse(bt(i,"utf-8"));if(t.sessionToken)return s.debug("[Auth] Using session token from zibby login"),t.sessionToken}}catch(i){s.debug(`[Auth] Could not read zibby login session: ${i.message}`)}return null}function xt(){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){s.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let e=It();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=xt();s.info(`\u{1F517} Using OpenAI proxy: ${r}`);let o=At(t),a=o;if(o.$ref&&o.definitions){let p=o.$ref.split("/").pop();a=o.definitions[p]||o,s.debug(`Extracted schema from $ref: ${p}`)}delete a.$schema,J(a);let n=4e5,u=i;i.length>n&&(s.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${i.length} chars) exceeds limit, keeping last ${n} chars`),u=`... [truncated early content] ...
35
- ${i.slice(-n)}`);let c=`Extract and format the following information into structured JSON matching the schema.
34
+ `)}getStats(){let e=this.userPrompt.length,t=this.build().length;return{userPromptLength:e,fullPromptLength:t,systemInstructionsLength:t-e,instructionCount:this.systemInstructions.length,instructionTypes:this.systemInstructions.map(r=>r.type)}}clone(){let e=new o(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};import Se from"axios";import{homedir as Ee}from"node:os";import{join as xe}from"node:path";import{existsSync as _e,readFileSync as Te}from"node:fs";import{toJSONSchema as Ae}from"zod";function we(){if(process.env.OPENAI_PROXY_TOKEN)return i.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return i.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let o=xe(Ee(),".zibby","config.json");if(_e(o)){let e=JSON.parse(Te(o,"utf-8"));if(e.sessionToken)return i.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(o){i.debug(`[Auth] Could not read zibby login session: ${o.message}`)}return null}function $e(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function B(o){if(!(typeof o!="object"||o===null)){if(Object.keys(o).length===0){o.type="object",o.additionalProperties=!0;return}if(o.type||(o.properties?o.type="object":o.items&&(o.type="array")),o.type==="object")if(o.properties){for(let[e,t]of Object.entries(o.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(o.properties[e]={type:["object","null"]});o.additionalProperties=!1,o.required=Object.keys(o.properties),Object.values(o.properties).forEach(B)}else"additionalProperties"in o||(o.additionalProperties=!0);o.type==="array"&&o.items&&B(o.items),o.anyOf&&o.anyOf.forEach(B),o.oneOf&&o.oneOf.forEach(B),o.allOf&&o.allOf.forEach(B)}}async function ie(o,e){i.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=we();if(!t)throw new Error("Authentication required for structured output processing.\n Local development: Run `zibby login`\n CI/CD: Set ZIBBY_USER_TOKEN environment variable (Personal Access Token from UI settings)");let r=$e();i.info(`\u{1F517} Using OpenAI proxy: ${r}`);let s=Ae(e),l=s;if(s.$ref&&s.definitions){let d=s.$ref.split("/").pop();l=s.definitions[d]||s,i.debug(`Extracted schema from $ref: ${d}`)}delete l.$schema,B(l);let n=4e5,u=o;o.length>n&&(i.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${o.length} chars) exceeds limit, keeping last ${n} chars`),u=`... [truncated early content] ...
35
+ ${o.slice(-n)}`);let c=`Extract and format the following information into structured JSON matching the schema.
36
36
 
37
37
  RAW CONTENT:
38
38
  ${u}
39
39
 
40
- Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,y={model:Y.OPENAI_POSTPROCESSING,messages:[{role:"user",content:c}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:a,strict:!0}}};s.info(`\u{1F4E4} Sending to OpenAI proxy: model=${Y.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(a.properties||{}).join(", ")}`),s.debug(` Schema size: ${JSON.stringify(a).length} chars`),s.debug(` Prompt size: ${c.length} chars`);try{let p={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(p["x-proxy-token"]=e,p["x-execution-id"]=process.env.EXECUTION_ID||""):(p.Authorization=`Bearer ${e}`,p["x-api-key"]=process.env.ZIBBY_API_KEY||"",p["x-execution-id"]=process.env.EXECUTION_ID||"");let f=(await Ot.post(r,y,{headers:p,timeout:Z.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!f)throw new Error("OpenAI proxy returned empty response");let O=JSON.parse(f);return s.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:O,raw:i}}catch(p){if(p.response){let g=p.response.status,f=p.response.data;throw s.error(`\u274C OpenAI proxy request failed: ${g}`),s.error(` Status: ${g}`),s.error(` Response: ${JSON.stringify(f,null,2)}`),g===401||g===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.`,y={model:z.OPENAI_POSTPROCESSING,messages:[{role:"user",content:c}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:l,strict:!0}}};i.info(`\u{1F4E4} Sending to OpenAI proxy: model=${z.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(l.properties||{}).join(", ")}`),i.debug(` Schema size: ${JSON.stringify(l).length} chars`),i.debug(` Prompt size: ${c.length} chars`);try{let d={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(d["x-proxy-token"]=t,d["x-execution-id"]=process.env.EXECUTION_ID||""):(d.Authorization=`Bearer ${t}`,d["x-api-key"]=process.env.ZIBBY_API_KEY||"",d["x-execution-id"]=process.env.EXECUTION_ID||"");let p=(await Se.post(r,y,{headers:d,timeout:Z.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!p)throw new Error("OpenAI proxy returned empty response");let b=JSON.parse(p);return i.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:b,raw:o}}catch(d){if(d.response){let m=d.response.status,p=d.response.data;throw i.error(`\u274C OpenAI proxy request failed: ${m}`),i.error(` Status: ${m}`),i.error(` Response: ${JSON.stringify(p,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(f)}`,{cause:p}):new Error(`Failed to format Cursor output: ${f?.error?.message||"Unknown error"}`,{cause:p})}throw s.error(`\u274C OpenAI proxy request failed: ${p.message}`),new Error(`Failed to format output: ${p.message}`,{cause:p})}}function st(i){let t=`${i}_POOL`,e=process.env[t];if(!e||typeof e!="string")return{picked:null,count:0,dispose:()=>{}};let r=e.split(/[,\n]+/).map(n=>n.trim()).filter(Boolean);if(r.length===0)return{picked:null,count:0,dispose:()=>{}};let o=r[Math.floor(Math.random()*r.length)],a=process.env[i];return process.env[i]=o,s.debug(`[auth-pool] ${i}: picked 1 of ${r.length} from pool (***${o.slice(-4)})`),{picked:o,count:r.length,dispose(){a===void 0?delete process.env[i]:process.env[i]=a}}}import{timeline as rt,Timeline as ae,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as ue}from"@zibby/agent-workflow";import{copyFileSync as Tt,existsSync as nt,lstatSync as wt,mkdirSync as it,rmSync as $t,symlinkSync as vt,unlinkSync as Rt}from"node:fs";import{join as M}from"node:path";import{homedir as Pt}from"node:os";import{randomBytes as Ct}from"node:crypto";var Nt=["cli-config.json","config.json","auth.json","argv.json"];function lt(i){return!(!i||typeof i!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function at(i){let t=M(i||process.cwd(),".zibby","tmp");it(t,{recursive:!0});let e=`${process.pid}-${Date.now()}-${Ct(4).toString("hex")}`,r=M(t,`cursor-agent-home-${e}`),o=M(r,".cursor");it(o,{recursive:!0});let a=Pt(),n=M(a,".cursor");if(nt(n))for(let u of Nt){let c=M(n,u);if(nt(c))try{Tt(c,M(o,u))}catch{}}if(process.platform==="darwin"){let u=M(a,"Library");if(nt(u))try{vt(u,M(r,"Library"))}catch{}}return r}function ut(i){if(!(!i||typeof i!="string"))try{let t=M(i,"Library");try{wt(t).isSymbolicLink()&&Rt(t)}catch{}$t(i,{recursive:!0,force:!0})}catch{}}var ht=class extends kt{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(t){let e=[$(j(),".local","bin","cursor-agent"),$(j(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"];for(let r of e)try{if(r.startsWith("/")){gt(r,mt.X_OK);let o=F(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(o&&o.length>0)return s.debug(`[Cursor] Found agent at: ${r} (version: ${o.trim().slice(0,50)})`),!0}else{let o=F(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!o)continue;let a=F(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(a&&a.length>0)return s.debug(`[Cursor] Found '${r}' in PATH at ${o} (version: ${a.trim().slice(0,50)})`),!0}}catch{continue}return s.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(t,e={}){let{workspace:r=process.cwd(),print:o=!1,schema:a=null,skills:n=null,sessionPath:u=null,nodeName:c=null,timeout:y=Z.CURSOR_AGENT_DEFAULT,config:p={},signal:g=null}=e,f=p?.agent?.strictMode||!1,O=e.model??p?.agent?.cursor?.model??Y.CURSOR,I=st("CURSOR_API_KEY");try{s.debug(`[Cursor] Invoking (model: ${O}, timeout: ${y/1e3}s, skills: ${JSON.stringify(n)})`);let m=(this._setupMcpConfig(u,r,p,n,c)||{}).isolatedMcpHome??null,T=[$(j(),".local","bin","cursor-agent"),$(j(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"],U=null;for(let h of T)try{if(h.startsWith("/"))gt(h,mt.X_OK),F(`"${h}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!F(`which ${h}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");F(`${h} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}U=h,s.debug(`[Agent] Using binary: ${h}`);break}catch(l){s.debug(`[Agent] Binary '${h}' check failed: ${l.message}`);continue}if(!U)throw new Error(`Cursor Agent CLI not found or not working.
42
+ Response: ${JSON.stringify(p)}`,{cause:d}):new Error(`Failed to format Cursor output: ${p?.error?.message||"Unknown error"}`,{cause:d})}throw i.error(`\u274C OpenAI proxy request failed: ${d.message}`),new Error(`Failed to format output: ${d.message}`,{cause:d})}}function ae(o){let e=`${o}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let r=t.split(/[,\n]+/).map(n=>n.trim()).filter(Boolean);if(r.length===0)return{picked:null,count:0,dispose:()=>{}};let s=r[Math.floor(Math.random()*r.length)],l=process.env[o];return process.env[o]=s,i.debug(`[auth-pool] ${o}: picked 1 of ${r.length} from pool (***${s.slice(-4)})`),{picked:s,count:r.length,dispose(){l===void 0?delete process.env[o]:process.env[o]=l}}}import{timeline as ne,Timeline as bt,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as Ot}from"@zibby/agent-workflow";import{copyFileSync as Ce,existsSync as oe,lstatSync as Pe,mkdirSync as le,rmSync as ke,symlinkSync as Re,unlinkSync as Ne}from"node:fs";import{join as M}from"node:path";import{homedir as Le}from"node:os";import{randomBytes as Me}from"node:crypto";var Ue=["cli-config.json","config.json","auth.json","argv.json"];function ue(o){return!(!o||typeof o!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function ce(o){let e=M(o||process.cwd(),".zibby","tmp");le(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${Me(4).toString("hex")}`,r=M(e,`cursor-agent-home-${t}`),s=M(r,".cursor");le(s,{recursive:!0});let l=Le(),n=M(l,".cursor");if(oe(n))for(let u of Ue){let c=M(n,u);if(oe(c))try{Ce(c,M(s,u))}catch{}}if(process.platform==="darwin"){let u=M(l,"Library");if(oe(u))try{Re(u,M(r,"Library"))}catch{}}return r}function de(o){if(!(!o||typeof o!="string"))try{let e=M(o,"Library");try{Pe(e).isSymbolicLink()&&Ne(e)}catch{}ke(o,{recursive:!0,force:!0})}catch{}}var be=class extends De{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[w(H(),".local","bin","cursor-agent"),w(H(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"];for(let r of t)try{if(r.startsWith("/")){he(r,ye.X_OK);let s=G(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return i.debug(`[Cursor] Found agent at: ${r} (version: ${s.trim().slice(0,50)})`),!0}else{let s=G(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!s)continue;let l=G(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(l&&l.length>0)return i.debug(`[Cursor] Found '${r}' in PATH at ${s} (version: ${l.trim().slice(0,50)})`),!0}}catch{continue}return i.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:r=process.cwd(),print:s=!1,schema:l=null,skills:n=null,sessionPath:u=null,nodeName:c=null,timeout:y=Z.CURSOR_AGENT_DEFAULT,config:d={},signal:m=null}=t,p=d?.agent?.strictMode||!1,b=t.model??d?.agent?.cursor?.model??z.CURSOR,x=ae("CURSOR_API_KEY");try{i.debug(`[Cursor] Invoking (model: ${b}, timeout: ${y/1e3}s, skills: ${JSON.stringify(n)})`);let g=(this._setupMcpConfig(u,r,d,n,c)||{}).isolatedMcpHome??null,T=[w(H(),".local","bin","cursor-agent"),w(H(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"],U=null;for(let h of T)try{if(h.startsWith("/"))he(h,ye.X_OK),G(`"${h}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!G(`which ${h}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");G(`${h} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}U=h,i.debug(`[Agent] Using binary: ${h}`);break}catch(a){i.debug(`[Agent] Binary '${h}' check failed: ${a.message}`);continue}if(!U)throw new Error(`Cursor Agent CLI not found or not working.
43
43
 
44
44
  Checked paths:
45
45
  ${T.map(h=>` - ${h}`).join(`
@@ -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 w=new V(t),A=null;if(a){let h=`zibby-result-${Date.now()}.json`;A=$(r,".zibby","tmp",h);let l=$(r,".zibby","tmp");H(l)||dt(l,{recursive:!0}),w.addStructuredOutput(a,A)}let K=process.env.CURSOR_API_KEY,W=K?` | key: ***${K.slice(-4)}`:" | key: not set";console.log(`
55
- \u25C6 Model: ${O||"auto"}${W}
56
- `);let D=(await import("chalk")).default,E=w.getUserPrompt();console.log(`
57
- ${D.bold("Prompt sent to LLM:")}`),console.log(D.dim("\u2500".repeat(60))),console.log(D.dim(E)),console.log(D.dim("\u2500".repeat(60)));let B=w.build(),N=w.getStats(),k=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",O||"auto"];if(process.env.CURSOR_API_KEY&&k.push("--api-key",process.env.CURSOR_API_KEY),k.push(B),s.debug(`[Agent] User prompt: ${N.userPromptLength} chars, System instructions: ${N.systemInstructionsLength} chars (${N.instructionCount} blocks), Full: ${N.fullPromptLength} chars, model: ${O||"auto"}`),s.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${O||"auto"} (from .zibby.config.js agent.cursor.model)
58
- `)}catch{}let v,L=null;try{let h=u||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);v=await this._spawnWithStreaming(U,k,r,y,null,h,m,g)}catch(h){L=h}let R=v?.stdout||"";if(a){let h=typeof a.parse=="function",l=null,_=!!(A&&H(A));if(A&&s.info(`[Agent] Result file: ${_?"present":"missing"} at ${A}`),_)try{let d=ft(A,"utf-8").trim();l=JSON.parse(d),s.info(`[Agent] Parsed JSON from result file OK (${d.length} chars) \u2192 object ready for validation`),L&&s.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(d){s.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${d.message}`)}else if(L)s.warn(`[Agent] Result file missing at ${A} (agent process error \u2014 may still recover if strictMode repairs)`);else throw s.error(`\u274C [Agent] Result file was never created at ${A}`),new Error(`Agent did not write required result file at ${A}`);if(l&&h)try{let d=a.parse(l);return s.info("\u2705 [Agent] Zod validation passed for structured result file"),f&&s.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:R,structured:d}}catch(d){let x=d.issues?d.issues.map(b=>` - ${b.path.join(".")}: ${b.message}`).join(`
59
- `):d.message?.slice(0,400);if(s.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
60
- ${x}`),s.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
61
- ${JSON.stringify(l,null,2).slice(0,500)}`),!f)throw new Error(`Agent output failed schema validation:
62
- ${x}
54
+ Test with: agent --version`);let A=new Q(e),E=null;if(l){let h=`zibby-result-${Date.now()}.json`;E=w(r,".zibby","tmp",h);let a=w(r,".zibby","tmp");Y(a)||ge(a,{recursive:!0}),A.addStructuredOutput(l,E)}let J=process.env.CURSOR_API_KEY,j=J?` | key: ***${J.slice(-4)}`:" | key: not set";console.log(`
55
+ \u25C6 Model: ${b||"auto"}${j}
56
+ `);let D=(await import("chalk")).default,O=A.getUserPrompt();console.log(`
57
+ ${D.bold("Prompt sent to LLM:")}`),console.log(D.dim("\u2500".repeat(60))),console.log(D.dim(O)),console.log(D.dim("\u2500".repeat(60)));let F=A.build(),R=A.getStats(),N=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",b||"auto"];if(process.env.CURSOR_API_KEY&&N.push("--api-key",process.env.CURSOR_API_KEY),N.push(F),i.debug(`[Agent] User prompt: ${R.userPromptLength} chars, System instructions: ${R.systemInstructionsLength} chars (${R.instructionCount} blocks), Full: ${R.fullPromptLength} chars, model: ${b||"auto"}`),i.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${b||"auto"} (from .zibby.config.js agent.cursor.model)
58
+ `)}catch{}let $,L=null;try{let h=u||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);$=await this._spawnWithStreaming(U,N,r,y,null,h,g,m)}catch(h){L=h}let C=$?.stdout||"";if(l){let h=typeof l.parse=="function",a=null,v=!!(E&&Y(E));if(E&&i.info(`[Agent] Result file: ${v?"present":"missing"} at ${E}`),v)try{let f=me(E,"utf-8").trim();a=JSON.parse(f),i.info(`[Agent] Parsed JSON from result file OK (${f.length} chars) \u2192 object ready for validation`),L&&i.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(f){i.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${f.message}`)}else if(L)i.warn(`[Agent] Result file missing at ${E} (agent process error \u2014 may still recover if strictMode repairs)`);else throw i.error(`\u274C [Agent] Result file was never created at ${E}`),new Error(`Agent did not write required result file at ${E}`);if(a&&h)try{let f=l.parse(a);return i.info("\u2705 [Agent] Zod validation passed for structured result file"),p&&i.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:C,structured:f}}catch(f){let _=f.issues?f.issues.map(S=>` - ${S.path.join(".")}: ${S.message}`).join(`
59
+ `):f.message?.slice(0,400);if(i.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
60
+ ${_}`),i.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
61
+ ${JSON.stringify(a,null,2).slice(0,500)}`),!p)throw new Error(`Agent output failed schema validation:
62
+ ${_}
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:d})}else{if(l)return s.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),f&&s.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:R,structured:l};_&&s.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(f&&!L){let d=v.parsedText,x=l?JSON.stringify(l):d;s.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${x.length} chars in)`);try{let b=await ot(x,a);if(h){let G=a.parse(b.structured);return s.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:R,structured:G}}return{raw:R,...b}}catch(b){if(s.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${b.message}`),l)return s.warn("[Agent] Using agent's original result file as fallback"),{raw:R,structured:l}}}if(L)throw L;let S=_?l==null?"file existed but JSON.parse failed \u2014 see WARN log above":h?"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 s.error(`\u274C [Agent] No validated structured output: ${S}`),s.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 ${A}. Enable strictMode for proxy fallback.`)}if(L)throw L;return this._extractFinalResult(R)||v?.parsedText||R}finally{I.dispose()}}_extractFinalResult(t){if(!t)return null;let e=t.split(`
66
- `),r=null;for(let o of e){let a=o.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 c=u.filter(y=>y.type==="text"&&y.text).map(y=>y.text).join("");c&&(r=c)}else typeof u=="string"&&u&&(r=u)}}catch{}}return r?.trim()||null}_setupMcpConfig(t,e,r,o=null,a=null){let n=r?.headless,u=$(j(),".cursor"),c=$(u,"mcp.json"),y={};if(H(c))try{y=JSON.parse(ft(c,"utf-8"))}catch{}let p=y.mcpServers||{},g=r?.paths?.output||Lt,f=$(e||process.cwd(),g,Mt),O=Array.isArray(o)?o.map(m=>ct(m)).filter(Boolean):[...Dt()].map(([,m])=>m),I=new Set;for(let m of O)typeof m.resolve=="function"&&(I.has(m.serverName)||(I.add(m.serverName),this._ensureSkillConfigured(p,m,t,f,a,n)));if(t){let m=ct("browser");m&&typeof m.resolve=="function"&&!I.has(m.serverName)&&this._ensureSkillConfigured(p,m,t,f,"execute_live",n)}if(Object.keys(p).length===0)return s.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let C=`${JSON.stringify({mcpServers:p},null,2)}
67
- `;if(lt(t)){let m=at(e||process.cwd()),T=$(m,".cursor","mcp.json");return pt(T,C,"utf8"),s.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${m} | servers: ${Object.keys(p).join(", ")}`),{isolatedMcpHome:m}}return H(u)||dt(u,{recursive:!0}),pt(c,C,"utf8"),s.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(p).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(t,e,r,o,a=null,n){let u=e.cursorKey||e.serverName,c=t[u]?u:t[e.serverName]?e.serverName:null;if(c&&r){let p=typeof e.resolve=="function"?e.resolve({sessionPath:r,nodeName:a,headless:n}):null;p?.args?t[c].args=p.args:t[c].args=(t[c].args||[]).map(O=>O.startsWith("--output-dir=")?`--output-dir=${r}`:O);let g=p?.env||{},f=e.sessionEnvKey?{[e.sessionEnvKey]:o}:{};t[c].env={...t[c].env||{},...g,...f},s.debug(`[MCP] Updated ${c} session \u2192 ${r}`);return}if(c)return;let y=e.resolve({sessionPath:r,nodeName:a,headless:n});y&&(t[u]={...y,...e.sessionEnvKey&&{env:{...y.env||{},[e.sessionEnvKey]:o}}},s.debug(`[MCP] Configured ${u}`))}_spawnWithStreaming(t,e,r,o,a=null,n=null,u=null,c=null){return new Promise((y,p)=>{let g=Date.now(),f="",O="",I=Date.now(),C=0,m=!1,T=null,U=!1,w=!1,A=null;if(n)try{A=$(Jt(String(n)),Ut)}catch{A=null}let K=!1,W=()=>{K||(K=!0,ut(u))},D={...process.env};u&&(D.HOME=u,process.platform==="win32"&&(D.USERPROFILE=u),s.debug(`[Agent] cursor-agent HOME=${u} (isolated MCP config)`));let E=Bt(t,e,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:D,...c&&{signal:c}});s.debug(`[Agent] PID: ${E.pid}`);let B=null,N=()=>{m||w||(m=!0,T="aborted",s.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),B=setTimeout(()=>{if(!w){s.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{E.kill("SIGKILL")}catch{}}},5e3))};c&&(c.aborted?N():c.addEventListener("abort",N,{once:!0})),E.stdin.on("error",l=>{l.code!=="EPIPE"&&s.warn(`[Agent] stdin error: ${l.message}`)}),E.stdout.on("error",l=>{l.code!=="EPIPE"&&s.warn(`[Agent] stdout error: ${l.message}`)}),E.stderr.on("error",l=>{l.code!=="EPIPE"&&s.warn(`[Agent] stderr error: ${l.message}`)}),a?(E.stdin.write(a,l=>{l&&l.code!=="EPIPE"&&s.warn(`[Agent] Failed to write to stdin: ${l.message}`),E.stdin.end()}),s.debug(`[Agent] Prompt also piped to stdin (${a.length} chars)`)):E.stdin.end();let k=null;A&&(k=setInterval(()=>{if(!(m||w))try{if(H(A)){m=!0,T="aborted";try{Ft(A)}catch{}s.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),E.kill("SIGTERM"),setTimeout(()=>{E.killed||E.kill("SIGKILL")},2e3)}}catch{}},600));let v=new Set,L=new Date(g).toISOString().replace(/\.\d+Z$/,""),R=setInterval(()=>{let l=Math.round((Date.now()-g)/1e3),_=Math.round((Date.now()-I)/1e3),S=[];try{let x=Math.ceil(l/60)+1,b=F(`find "${r}" -type f -mmin -${x} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(b)for(let G of b.split(`
68
- `)){let tt=G.replace(`${r}/`,"");v.has(tt)||(v.add(tt),S.push(tt))}}catch{}let d="";S.length>0&&(d=` | \u{1F4C1} new: ${S.map(b=>b.split("/").pop()).join(", ")}`),v.size>0&&(d+=` | \u{1F4E6} total: ${v.size} files`),s.debug(`\u{1F493} [Agent] Running for ${l}s | ${C} lines output${d}`),C===0&&l>=30&&v.size===0&&(l<35&&s.warn(`\u26A0\uFE0F [Agent] No output after ${l}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),l>=60&&(m=!0,T=T||"stall",s.error(`\u274C [Agent] No response after ${l}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),E.kill("SIGTERM"),setTimeout(()=>{E.killed||E.kill("SIGKILL")},3e3)))},3e4),Q=setTimeout(()=>{m=!0,T=T||"timeout";let l=Math.round((Date.now()-g)/1e3);s.error(`\u23F1\uFE0F [Agent] Timeout after ${l}s \u2014 killing process (PID: ${E.pid})`),f.trim()&&s.warn(`\u{1F4E4} [Agent] Partial output (${f.length} chars) before timeout:
69
- ${f.slice(-2e3)}`),E.kill("SIGTERM"),setTimeout(()=>{E.killed||E.kill("SIGKILL")},5e3)},o),h=new X;h.onToolCall=(l,_)=>{let S=l,d=_;if(l==="mcpToolCall"&&_?.name)S=_.name.replace(/^mcp_+[^_]+_+/,""),S.includes("-")&&S.split("-")[0]===S.split("-")[1]&&(S=S.split("-")[0]),d=_.args??_.input??_;else{if(l==="readToolCall"||l==="editToolCall"||l==="writeToolCall")return;(l.startsWith("mcp__")||l.includes("ToolCall"))&&(S=l.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(S.includes("memory")?rt.stepMemory(`Tool: ${S}`):rt.stepTool(`Tool: ${S}`),d!=null&&typeof d=="object"&&Object.keys(d).length>0&&!w){let b=JSON.stringify(d),G=b.length>100?`${b.substring(0,100)}...`:b;console.log(` Input: ${G}`)}},E.stdout.on("data",l=>{let _=l.toString();f+=_,I=Date.now(),U||(U=!0);let S=h.processChunk(_);S&&!w&&process.stdout.write(S);let d=_.split(`
70
- `).filter(x=>x.trim());C+=d.length}),E.stderr.on("data",l=>{let _=l.toString();O+=_,I=Date.now(),U||(U=!0);let S=_.split(`
71
- `).filter(d=>d.trim());for(let d of S)s.warn(`\u26A0\uFE0F [Agent stderr] ${d}`)}),E.on("close",(l,_)=>{if(w=!0,W(),clearTimeout(Q),clearInterval(R),k&&clearInterval(k),B&&clearTimeout(B),c&&!c.aborted)try{c.removeEventListener("abort",N)}catch{}h.flush();let S=Math.round((Date.now()-g)/1e3);if(s.debug(`[Agent] Exited: code=${l}, signal=${_}, elapsed=${S}s, output=${f.length} chars`),m){if(T==="aborted"){let b=new Error("Aborted via signal");b.name="AbortError",p(b);return}p(new Error(`Cursor Agent timed out after ${S}s (limit: ${o/1e3}s). ${C} lines produced. Last output ${Math.round((Date.now()-I)/1e3)}s ago. ${f.trim()?`
65
+ Enable strictMode in .zibby.config.js for automatic repair.`,{cause:f})}else{if(a)return i.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),p&&i.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:C,structured:a};v&&i.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(p&&!L){let f=$.parsedText,_=a?JSON.stringify(a):f;i.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${_.length} chars in)`);try{let S=await ie(_,l);if(h){let K=l.parse(S.structured);return i.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:C,structured:K}}return{raw:C,...S}}catch(S){if(i.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${S.message}`),a)return i.warn("[Agent] Using agent's original result file as fallback"),{raw:C,structured:a}}}if(L)throw L;let I=v?a==null?"file existed but JSON.parse failed \u2014 see WARN log above":h?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw i.error(`\u274C [Agent] No validated structured output: ${I}`),i.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error(`Agent did not produce a valid result file at ${E}. Enable strictMode for proxy fallback.`)}if(L)throw L;return this._extractFinalResult(C)||$?.parsedText||C}finally{x.dispose()}}_extractFinalResult(e){if(!e)return null;let t=e.split(`
66
+ `),r=null;for(let s of t){let l=s.trim();if(l)try{let n=JSON.parse(l);if(n.type==="assistant"&&n.message?.content){let u=n.message.content;if(Array.isArray(u)){let c=u.filter(y=>y.type==="text"&&y.text).map(y=>y.text).join("");c&&(r=c)}else typeof u=="string"&&u&&(r=u)}}catch{}}return r?.trim()||null}_setupMcpConfig(e,t,r,s=null,l=null){let n=r?.headless,u=w(H(),".cursor"),c=w(u,"mcp.json"),y={};if(Y(c))try{y=JSON.parse(me(c,"utf-8"))}catch{}let d=y.mcpServers||{},m=r?.paths?.output||Fe,p=w(t||process.cwd(),m,Ge),b=Array.isArray(s)?s.map(g=>pe(g)).filter(Boolean):[...Je()].map(([,g])=>g),x=new Set;for(let g of b)typeof g.resolve=="function"&&(x.has(g.serverName)||(x.add(g.serverName),this._ensureSkillConfigured(d,g,e,p,l,n)));if(e){let g=pe("browser");g&&typeof g.resolve=="function"&&!x.has(g.serverName)&&this._ensureSkillConfigured(d,g,e,p,"execute_live",n)}if(Object.keys(d).length===0)return i.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let k=`${JSON.stringify({mcpServers:d},null,2)}
67
+ `;if(ue(e)){let g=ce(t||process.cwd()),T=w(g,".cursor","mcp.json");return fe(T,k,"utf8"),i.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${g} | servers: ${Object.keys(d).join(", ")}`),{isolatedMcpHome:g}}return Y(u)||ge(u,{recursive:!0}),fe(c,k,"utf8"),i.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(d).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,s,l=null,n){let u=t.cursorKey||t.serverName,c=e[u]?u:e[t.serverName]?t.serverName:null;if(c&&r){let d=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:l,headless:n}):null;d?.args?e[c].args=d.args:e[c].args=(e[c].args||[]).map(b=>b.startsWith("--output-dir=")?`--output-dir=${r}`:b);let m=d?.env||{},p=t.sessionEnvKey?{[t.sessionEnvKey]:s}:{};e[c].env={...e[c].env||{},...m,...p},i.debug(`[MCP] Updated ${c} session \u2192 ${r}`);return}if(c)return;let y=t.resolve({sessionPath:r,nodeName:l,headless:n});y&&(e[u]={...y,...t.sessionEnvKey&&{env:{...y.env||{},[t.sessionEnvKey]:s}}},i.debug(`[MCP] Configured ${u}`))}_spawnWithStreaming(e,t,r,s,l=null,n=null,u=null,c=null){return new Promise((y,d)=>{let m=Date.now(),p="",b="",x=Date.now(),k=0,g=!1,T=null,U=!1,A=!1,E=null;if(n)try{E=w(ze(String(n)),Be)}catch{E=null}let J=!1,j=()=>{J||(J=!0,de(u))},D={...process.env};u&&(D.HOME=u,process.platform==="win32"&&(D.USERPROFILE=u),i.debug(`[Agent] cursor-agent HOME=${u} (isolated MCP config)`));let O=Ke(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:D,...c&&{signal:c}});i.debug(`[Agent] PID: ${O.pid}`);let F=null,R=()=>{g||A||(g=!0,T="aborted",i.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),F=setTimeout(()=>{if(!A){i.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{O.kill("SIGKILL")}catch{}}},5e3))};c&&(c.aborted?R():c.addEventListener("abort",R,{once:!0})),O.stdin.on("error",a=>{a.code!=="EPIPE"&&i.warn(`[Agent] stdin error: ${a.message}`)}),O.stdout.on("error",a=>{a.code!=="EPIPE"&&i.warn(`[Agent] stdout error: ${a.message}`)}),O.stderr.on("error",a=>{a.code!=="EPIPE"&&i.warn(`[Agent] stderr error: ${a.message}`)}),l?(O.stdin.write(l,a=>{a&&a.code!=="EPIPE"&&i.warn(`[Agent] Failed to write to stdin: ${a.message}`),O.stdin.end()}),i.debug(`[Agent] Prompt also piped to stdin (${l.length} chars)`)):O.stdin.end();let N=null;E&&(N=setInterval(()=>{if(!(g||A))try{if(Y(E)){g=!0,T="aborted";try{Ve(E)}catch{}i.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},2e3)}}catch{}},600));let $=new Set,L=new Date(m).toISOString().replace(/\.\d+Z$/,""),C=setInterval(()=>{let a=Math.round((Date.now()-m)/1e3),v=Math.round((Date.now()-x)/1e3),I=[];try{let _=Math.ceil(a/60)+1,S=G(`find "${r}" -type f -mmin -${_} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(S)for(let K of S.split(`
68
+ `)){let te=K.replace(`${r}/`,"");$.has(te)||($.add(te),I.push(te))}}catch{}let f="";I.length>0&&(f=` | \u{1F4C1} new: ${I.map(S=>S.split("/").pop()).join(", ")}`),$.size>0&&(f+=` | \u{1F4E6} total: ${$.size} files`),i.debug(`\u{1F493} [Agent] Running for ${a}s | ${k} lines output${f}`),k===0&&a>=30&&$.size===0&&(a<35&&i.warn(`\u26A0\uFE0F [Agent] No output after ${a}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),a>=60&&(g=!0,T=T||"stall",i.error(`\u274C [Agent] No response after ${a}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),ee=setTimeout(()=>{g=!0,T=T||"timeout";let a=Math.round((Date.now()-m)/1e3);i.error(`\u23F1\uFE0F [Agent] Timeout after ${a}s \u2014 killing process (PID: ${O.pid})`),p.trim()&&i.warn(`\u{1F4E4} [Agent] Partial output (${p.length} chars) before timeout:
69
+ ${p.slice(-2e3)}`),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},5e3)},s),h=new X;h.onToolCall=(a,v)=>{let I=a,f=v;if(a==="mcpToolCall"&&v?.name)I=v.name.replace(/^mcp_+[^_]+_+/,""),I.includes("-")&&I.split("-")[0]===I.split("-")[1]&&(I=I.split("-")[0]),f=v.args??v.input??v;else{if(a==="readToolCall"||a==="editToolCall"||a==="writeToolCall")return;(a.startsWith("mcp__")||a.includes("ToolCall"))&&(I=a.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(I.includes("memory")?ne.stepMemory(`Tool: ${I}`):ne.stepTool(`Tool: ${I}`),f!=null&&typeof f=="object"&&Object.keys(f).length>0&&!A){let S=JSON.stringify(f),K=S.length>100?`${S.substring(0,100)}...`:S;console.log(` Input: ${K}`)}},O.stdout.on("data",a=>{let v=a.toString();p+=v,x=Date.now(),U||(U=!0);let I=h.processChunk(v);I&&!A&&process.stdout.write(I);let f=v.split(`
70
+ `).filter(_=>_.trim());k+=f.length}),O.stderr.on("data",a=>{let v=a.toString();b+=v,x=Date.now(),U||(U=!0);let I=v.split(`
71
+ `).filter(f=>f.trim());for(let f of I)i.warn(`\u26A0\uFE0F [Agent stderr] ${f}`)}),O.on("close",(a,v)=>{if(A=!0,j(),clearTimeout(ee),clearInterval(C),N&&clearInterval(N),F&&clearTimeout(F),c&&!c.aborted)try{c.removeEventListener("abort",R)}catch{}h.flush();let I=Math.round((Date.now()-m)/1e3);if(i.debug(`[Agent] Exited: code=${a}, signal=${v}, elapsed=${I}s, output=${p.length} chars`),g){if(T==="aborted"){let S=new Error("Aborted via signal");S.name="AbortError",d(S);return}d(new Error(`Cursor Agent timed out after ${I}s (limit: ${s/1e3}s). ${k} lines produced. Last output ${Math.round((Date.now()-x)/1e3)}s ago. ${p.trim()?`
72
72
  Partial output (last 500 chars):
73
- ${f.slice(-500)}`:"No output captured."}`));return}if(l!==0){p(new Error(`Cursor Agent failed: exit code ${l}, signal ${c}. ${O.trim()?`
74
- Stderr: ${O.slice(-1e3)}`:""}${f.trim()?`
75
- Stdout (last 500 chars): ${f.slice(-500)}`:""}`));return}let d=h.getResult(),x=d?JSON.stringify(d,null,2):h.getRawText()||f||"";y({stdout:f||O||"",parsedText:x})}),E.on("error",l=>{if(W(),clearTimeout(Q),clearInterval(R),k&&clearInterval(k),B&&clearTimeout(B),c&&!c.aborted)try{c.removeEventListener("abort",N)}catch{}p(new Error(`Cursor Agent spawn error: ${l.message}
76
- Binary: ${t}
73
+ ${p.slice(-500)}`:"No output captured."}`));return}if(a!==0){d(new Error(`Cursor Agent failed: exit code ${a}, signal ${c}. ${b.trim()?`
74
+ Stderr: ${b.slice(-1e3)}`:""}${p.trim()?`
75
+ Stdout (last 500 chars): ${p.slice(-500)}`:""}`));return}let f=h.getResult(),_=f?JSON.stringify(f,null,2):h.getRawText()||p||"";y({stdout:p||b||"",parsedText:_})}),O.on("error",a=>{if(j(),clearTimeout(ee),clearInterval(C),N&&clearInterval(N),F&&clearTimeout(F),c&&!c.aborted)try{c.removeEventListener("abort",R)}catch{}d(new Error(`Cursor Agent spawn error: ${a.message}
76
+ Binary: ${e}
77
77
  This usually means the binary is not in PATH. Try:
78
- echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};export{ht as CursorAgentStrategy};
78
+ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};export{be as CursorAgentStrategy};
@@ -1,43 +1,43 @@
1
- import{AgentStrategy as ft,getSkill as dt}from"@zibby/agent-workflow";import{execSync as mt,spawn as ht}from"node:child_process";import{zodToJsonSchema as gt}from"zod-to-json-schema";import{existsSync as et,mkdirSync as rt,readFileSync as st,rmSync as yt,writeFileSync as nt}from"node:fs";import{join as w}from"node:path";import P from"chalk";var g={debug:0,info:1,warn:2,error:3,silent:4},W=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 W;var Q={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-3-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"};var tt={auto:"gemini-3-pro","gemini-3-pro":"gemini-3-pro","gemini-3-flash":"gemini-3-flash","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},It={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};import{zodToJsonSchema as pt}from"zod-to-json-schema";var $=class{static generateFileOutputInstructions(t,e){let s;typeof t?.parse=="function"?s=pt(t,{target:"openApi3"}):s=t;let n=this._buildExample(s);return`
1
+ import{AgentStrategy as Oe,getSkill as ve}from"@zibby/agent-workflow";import{execSync as be,spawn as xe}from"node:child_process";import{z as ee}from"zod";import{zodToJsonSchema as he}from"zod-to-json-schema";function te(a,e={target:"openApi3"}){if(!a)return null;if(typeof ee?.toJSONSchema=="function")try{return ee.toJSONSchema(a)}catch{}try{return he(a,e)}catch{return null}}import{existsSync as se,mkdirSync as oe,readFileSync as ae,rmSync as Se,writeFileSync as le}from"node:fs";import{join as E}from"node:path";import N from"chalk";var g={debug:0,info:1,warn:2,error:3,silent:4},W=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 e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in g?g[e]:g.info}_shouldLog(e){return g[e]>=this._level}_formatMessage(e,t,i={}){let r=new Date().toISOString(),n=`${this._getPrefix(e)} ${t}`;return Object.keys(i).length>0&&(n+=N.dim(` ${JSON.stringify(i)}`)),n}_getPrefix(e){return{debug:N.gray("[DEBUG]"),info:N.cyan("[INFO]"),warn:N.yellow("[WARN]"),error:N.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 g&&(this._level=g[e])}getLevel(){return Object.keys(g).find(e=>g[e]===this._level)}},c=new W;var ge=[{alias:"auto",canonicalId:"claude-sonnet-4-6",vendor:"claude",label:"Claude \xB7 Sonnet 4.6",family:"claude-sonnet-4",pickerVisible:!0,isDefault:!0},{alias:"opus-4.8",canonicalId:"claude-opus-4-8",vendor:"claude",label:"Claude \xB7 Opus 4.8",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-8",canonicalId:"claude-opus-4-8",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.8"},{alias:"sonnet-4.8",canonicalId:"claude-sonnet-4-8",vendor:"claude",label:"Claude \xB7 Sonnet 4.8",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-8",canonicalId:"claude-sonnet-4-8",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.8"},{alias:"opus-4.7",canonicalId:"claude-opus-4-7",vendor:"claude",label:"Claude \xB7 Opus 4.7",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-7",canonicalId:"claude-opus-4-7",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.7"},{alias:"sonnet-4.7",canonicalId:"claude-sonnet-4-7",vendor:"claude",label:"Claude \xB7 Sonnet 4.7",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-7",canonicalId:"claude-sonnet-4-7",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.7"},{alias:"sonnet-4.6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"auto"},{alias:"sonnet-4-6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"auto"},{alias:"opus-4.6",canonicalId:"claude-opus-4-6",vendor:"claude",label:"Claude \xB7 Opus 4.6",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-6",canonicalId:"claude-opus-4-6",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.6"},{alias:"sonnet-4.5",canonicalId:"claude-sonnet-4-5-20250929",vendor:"claude",label:"Claude \xB7 Sonnet 4.5",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-5",canonicalId:"claude-sonnet-4-5-20250929",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.5"},{alias:"opus-4.5",canonicalId:"claude-opus-4-5-20251101",vendor:"claude",label:"Claude \xB7 Opus 4.5",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-5",canonicalId:"claude-opus-4-5-20251101",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.5"},{alias:"haiku-4.5",canonicalId:"claude-haiku-4-5-20251001",vendor:"claude",label:"Claude \xB7 Haiku 4.5",family:"claude-haiku-4"},{alias:"haiku-4-5",canonicalId:"claude-haiku-4-5-20251001",vendor:"claude",family:"claude-haiku-4",aliasOf:"haiku-4.5"},{alias:"claude-opus-4-8",canonicalId:"claude-opus-4-8",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.8"},{alias:"claude-sonnet-4-8",canonicalId:"claude-sonnet-4-8",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.8"},{alias:"claude-opus-4-7",canonicalId:"claude-opus-4-7",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.7"},{alias:"claude-sonnet-4-7",canonicalId:"claude-sonnet-4-7",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.7"},{alias:"claude-sonnet-4-6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"auto"},{alias:"claude-opus-4-6",canonicalId:"claude-opus-4-6",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.6"},{alias:"claude-sonnet-4-5-20250929",canonicalId:"claude-sonnet-4-5-20250929",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.5"},{alias:"claude-opus-4-5-20251101",canonicalId:"claude-opus-4-5-20251101",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.5"},{alias:"claude-haiku-4-5-20251001",canonicalId:"claude-haiku-4-5-20251001",vendor:"claude",family:"claude-haiku-4",aliasOf:"haiku-4.5"},{alias:"claude-opus-4-20250514",canonicalId:"claude-opus-4-20250514",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.5"},{alias:"auto",canonicalId:"o4-mini",vendor:"codex",label:"Codex \xB7 o4-mini",family:"o4-mini",isDefault:!0},{alias:"o4-mini",canonicalId:"o4-mini",vendor:"codex",label:"Codex \xB7 o4-mini",family:"o4-mini",pickerVisible:!0},{alias:"o3",canonicalId:"o3",vendor:"codex",family:"o3"},{alias:"o3-mini",canonicalId:"o3-mini",vendor:"codex",family:"o3-mini"},{alias:"codex-mini",canonicalId:"codex-mini-latest",vendor:"codex",family:"codex-mini"},{alias:"gpt-4o",canonicalId:"gpt-4o",vendor:"codex",label:"Codex \xB7 GPT-4o",family:"gpt-4o",pickerVisible:!0},{alias:"gpt-4o-mini",canonicalId:"gpt-4o-mini",vendor:"codex",label:"Codex \xB7 GPT-4o mini",family:"gpt-4o-mini",pickerVisible:!0},{alias:"gpt-5.2-codex",canonicalId:"gpt-5.2-codex",vendor:"codex",label:"Codex \xB7 GPT-5.2",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.2",canonicalId:"gpt-5.2",vendor:"codex",label:"Codex \xB7 GPT-5.2 base",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.3",canonicalId:"gpt-5.3",vendor:"codex",label:"Codex \xB7 GPT-5.3",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.3-codex",canonicalId:"gpt-5.3-codex",vendor:"codex",family:"gpt-5"},{alias:"gpt-5.4",canonicalId:"gpt-5.4",vendor:"codex",label:"Codex \xB7 GPT-5.4",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.5",canonicalId:"gpt-5.5",vendor:"codex",label:"Codex \xB7 GPT-5.5",family:"gpt-5",pickerVisible:!0},{alias:"auto",canonicalId:"gemini-3-pro",vendor:"gemini",label:"Gemini \xB7 3 Pro",family:"gemini-3",isDefault:!0},{alias:"gemini-3-pro",canonicalId:"gemini-3-pro",vendor:"gemini",label:"Gemini \xB7 3 Pro",family:"gemini-3",pickerVisible:!0},{alias:"gemini-3-flash",canonicalId:"gemini-3-flash",vendor:"gemini",label:"Gemini \xB7 3 Flash",family:"gemini-3",pickerVisible:!0},{alias:"gemini-2.5-pro",canonicalId:"gemini-2.5-pro",vendor:"gemini",label:"Gemini \xB7 2.5 Pro",family:"gemini-2.5",pickerVisible:!0},{alias:"gemini-2.5-flash",canonicalId:"gemini-2.5-flash",vendor:"gemini",label:"Gemini \xB7 2.5 Flash",family:"gemini-2.5",pickerVisible:!0}];function R(a){let e={};for(let t of ge)t.vendor===a&&(e[t.alias]=t.canonicalId);return e}var ne={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-3-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"};var Me=R("claude"),Le=R("codex"),ie=R("gemini"),Re={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};import{z as re}from"zod";import{zodToJsonSchema as ye}from"zod-to-json-schema";function Ie(a){if(!a)return null;if(typeof re?.toJSONSchema=="function")try{return re.toJSONSchema(a)}catch{}try{return ye(a,{target:"openApi3"})}catch{return null}}var $=class{static generateFileOutputInstructions(e,t){let i;typeof e?.parse=="function"?i=Ie(e):i=e;let r=this._buildExample(i);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
5
5
  You MUST write your final result as pure JSON to this EXACT file path:
6
6
 
7
- ${e}
7
+ ${t}
8
8
 
9
9
  Use your file writing tool (WriteFile or ApplyPatch) to create this file.
10
10
  DO NOT just output JSON to stdout. The file MUST exist when you finish.
11
11
  DO NOT skip this step. The workflow WILL FAIL if the file is missing.
12
12
 
13
13
  Required JSON structure:
14
- ${JSON.stringify(n,null,2)}
14
+ ${JSON.stringify(r,null,2)}
15
15
 
16
16
  JSON types (strict \u2014 validators reject wrong types):
17
17
  - Use bare JSON numbers for numeric fields (e.g. 3000). Do NOT quote them as strings (wrong: "3000").
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 C=class c{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(e){if(!e)return{};let t=e.type;if(t==="object"&&e.properties){let i={};for(let[r,s]of Object.entries(e.properties))i[r]=this._buildExample(s);return i}if(t==="array"&&e.items)return[this._buildExample(e.items)];if(e.enum&&Array.isArray(e.enum)&&e.enum.length>0)return`<${e.enum.join("|")}>`;if(t==="string")return"<string>";if(t==="number"||t==="integer")return 0;if(t==="boolean")return!1;if(e.description)return`<${e.description}>`;if(e.nullable||e.oneOf||e.anyOf){let i=e.oneOf?.find(r=>r.type!=="null")||e.anyOf?.find(r=>r.type!=="null");return i?this._buildExample(i):null}return"<value>"}};var J=class a{constructor(e=""){this.userPrompt=e,this.systemInstructions=[],this.metadata={}}setUserPrompt(e){return this.userPrompt=e,this}appendUserPrompt(e){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=$.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
+ ${e}`:this.userPrompt=e,this}addSkillHints(e){return e&&this.systemInstructions.push({type:"skill_hints",content:e,position:"prepend"}),this}addStructuredOutput(e,t){if(e&&t){let i=$.generateFileOutputInstructions(e,t);this.systemInstructions.push({type:"structured_output",content:i,position:"append"}),this.metadata.structuredOutputPath=t}return this}addExtraInstructions(e){if(e?.trim()){let t=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
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
 
27
- ${t.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:e,position:"append"})}return this}addSkillFragments(t){return t&&t.length>0&&this.systemInstructions.push({type:"skill_fragments",content:t.join(`
28
-
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
-
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 c(this.userPrompt);return t.systemInstructions=[...this.systemInstructions],t.metadata={...this.metadata},t}};var J=class c{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
- `);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
- `,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],a=r[l],p=a&&typeof a=="object"?a.args??a.input??a:void 0;e(l,s(p))}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 m=n[1].trim();try{JSON.parse(m),e.push({text:m,source:"markdown"})}catch{}}let i=0,r=0;for(;i<t.length&&(i=t.indexOf("{",i),i!==-1);){let m=0,d=i;for(let h=i;h<t.length;h++)if(t[h]==="{")m++;else if(t[h]==="}"&&(m--,m===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,p=-1;for(let m=0;m<e.length;m++){let d=e[m];try{let h=d.text.replace(/,(\s*[}\]])/g,"$1"),T=JSON.parse(h);this.isValidResult(T)&&(a++,l=JSON.stringify(T).length,o=T,p=m)}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 c;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 H(c){let t=`${c}_POOL`,e=process.env[t];if(!e||typeof e!="string")return{picked:null,count:0,dispose:()=>{}};let s=e.split(/[,\n]+/).map(r=>r.trim()).filter(Boolean);if(s.length===0)return{picked:null,count:0,dispose:()=>{}};let n=s[Math.floor(Math.random()*s.length)],i=process.env[c];return process.env[c]=n,u.debug(`[auth-pool] ${c}: picked 1 of ${s.length} from pool (***${n.slice(-4)})`),{picked:n,count:s.length,dispose(){i===void 0?delete process.env[c]:process.env[c]=i}}}function Et(c){if(!c)return null;let t=String(c),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 p=t.slice(o,l+1);try{return JSON.parse(p)}catch{o=-1}}}}return null}function _t(c){let t=String(c||"").trim();if(!t)return null;try{return JSON.parse(t)}catch{return Et(t)}}function Ot(c){try{let t=JSON.parse(c);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 c}var it=class extends ft{constructor(){super("gemini","Gemini (Google)",70)}canHandle(t){if(!!!(process.env.GEMINI_API_KEY||process.env.GEMINI_API_KEY_POOL||process.env.GOOGLE_API_KEY||process.env.GOOGLE_API_KEY_POOL))return u.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return mt("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:p=null}=e,m=[H("GEMINI_API_KEY"),H("GOOGLE_API_KEY")];try{let d=s;(!d||d==="auto")&&(d=Q.GEMINI);let h=tt[d]||d,T=String(process.env.GEMINI_API_KEY||"").trim(),D=String(process.env.GOOGLE_API_KEY||"").trim(),R=this._resolveSkillsToMcp(r,{sessionPath:o,workspace:n,nodeName:l}),ot=Object.keys(R).length>0,v=new C(t),U=i&&typeof i.parse=="function",b=null;if(i){let f;try{let E=U?gt(i,{target:"openAi"}):i;f=JSON.stringify(E,null,2)}catch{f="{}"}if(ot){v.addSystemInstruction(`Write valid JSON that matches this schema:
35
- ${f}`,"schema_instruction","append");let E=`zibby-result-${Date.now()}.json`,_=w(n,".zibby","tmp");b=w(_,E),rt(_,{recursive:!0}),v.addStructuredOutput(i,b)}else v.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
36
- ${f}`,"json_instruction","append")}let lt=v.build(),ut=v.getUserPrompt(),M=v.getStats(),q=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),ct=q?` | key: ***${q.slice(-4)}`:" | key: not set";console.log(`
37
- \u25C6 Model: ${h||"auto"}${ct}
38
- `);let k=(await import("chalk")).default;console.log(`
39
- ${k.bold("Prompt sent to LLM:")}`),console.log(k.dim("\u2500".repeat(60))),console.log(k.dim(ut)),console.log(k.dim("\u2500".repeat(60)));let K=this._createGeminiConfigDir(n,R),x=["--output-format","json"];h&&h!=="auto"&&x.push("--model",h);let Y=Object.keys(R);if(Y.length>0){x.push("--approval-mode","yolo");for(let f of Y)x.push("--allowed-mcp-server-names",f);u.info(`[Gemini] Enabling MCP servers: ${Y.join(", ")}`)}else r&&r.length>0&&u.warn(`[Gemini] Skills requested but no MCP servers configured: ${r.join(", ")}`);x.push("-p",lt);let A={...process.env,GEMINI_CLI_HOME:K};T?(A.GEMINI_API_KEY=T,delete A.GOOGLE_API_KEY):D&&(A.GOOGLE_API_KEY=D,delete A.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: ${K}`),u.debug(`[Gemini] GEMINI_CLI_HOME env: ${A.GEMINI_CLI_HOME}`);let F="",N=null;try{F=await new Promise((E,_)=>{let O=ht("gemini",x,{cwd:n,env:A,stdio:["ignore","pipe","pipe"],...p&&{signal:p}}),z="",X="",B=!1,G=null,V=!1,Z=setTimeout(()=>{try{O.kill("SIGTERM")}catch{}},a),L=()=>{V||B||(V=!0,G=setTimeout(()=>{if(!B)try{O.kill("SIGKILL")}catch{}},5e3))};p&&(p.aborted?L():p.addEventListener("abort",L,{once:!0})),O.stdout.on("data",S=>{z+=S.toString()}),O.stderr.on("data",S=>{X+=S.toString()}),O.on("error",S=>{if(clearTimeout(Z),G&&clearTimeout(G),p&&!p.aborted)try{p.removeEventListener("abort",L)}catch{}_(S)}),O.on("close",S=>{if(B=!0,clearTimeout(Z),G&&clearTimeout(G),p&&!p.aborted)try{p.removeEventListener("abort",L)}catch{}if(V){let j=new Error("Aborted via signal");return j.name="AbortError",_(j)}if(S===0)return E(z.trim());_(new Error(`gemini failed with code ${S}: ${(X||z).trim()}`))})})}catch(f){N=f}finally{try{yt(K,{recursive:!0,force:!0})}catch{}}let y=Ot(F).trim();if(!i){if(N)throw N;return y}if(b){let f=et(b);if(u.info(`[Gemini] Result file: ${f?"present":"missing"} at ${b}`),f)try{let E=st(b,"utf-8").trim(),_=JSON.parse(E),O=U?i.parse(_):_;return u.info("[Gemini] Structured output recovered from result file"),{raw:y,structured:O}}catch(E){u.warn(`[Gemini] Result file parse/validation failed: ${E.message}`)}else N||u.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let I=null;if(i){let f=new J;f.zodSchema=i,f.processChunk(y),f.flush(),I=f.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
- ${y}`):u.info(`[Gemini] Raw text preview (first 1000 chars):
41
- ${y.slice(0,1e3)}`),I=_t(y)),!I)throw N||(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 at=U?i.parse(I):I;return{raw:y,structured:at}}finally{for(let d of m)d.dispose()}}_resolveSkillsToMcp(t,e={}){if(!Array.isArray(t)||t.length===0)return{};let s={};for(let n of t){let i=dt(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=w(t||process.cwd(),".zibby","tmp",`gemini-home-${s}`),i=w(n,".gemini");rt(i,{recursive:!0});let r=w(i,"settings.json"),o={},l=w(process.env.HOME||"",".gemini","settings.json");if(et(l))try{o=JSON.parse(st(l,"utf-8"))}catch{o={}}let a={...o,mcpServers:{...o.mcpServers&&typeof o.mcpServers=="object"?o.mcpServers:{},...e||{}}};nt(r,`${JSON.stringify(a,null,2)}
42
- `,"utf-8");let p=w(t||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{nt(p,`${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{it as GeminiAgentStrategy};
27
+ ${e.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:t,position:"append"})}return this}addSkillFragments(e){return e&&e.length>0&&this.systemInstructions.push({type:"skill_fragments",content:e.join(`
28
+
29
+ `),position:"append"}),this}addSystemInstruction(e,t="custom",i="append"){return e&&this.systemInstructions.push({type:t,content:e,position:i}),this}getUserPrompt(){return this.userPrompt}getSystemInstructions(){return this.systemInstructions}getMetadata(){return this.metadata}build(){let e=this.systemInstructions.filter(r=>r.position==="prepend").map(r=>r.content),t=this.systemInstructions.filter(r=>r.position==="append").map(r=>r.content);return[...e,this.userPrompt,...t].filter(Boolean).join(`
30
+
31
+ `)}getStats(){let e=this.userPrompt.length,t=this.build().length;return{userPromptLength:e,fullPromptLength:t,systemInstructionsLength:t-e,instructionCount:this.systemInstructions.length,instructionTypes:this.systemInstructions.map(i=>i.type)}}clone(){let e=new a(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};var D=class a{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(e){if(!e)return null;this.buffer+=e;let t=this.buffer.split(`
32
+ `);this.buffer=t.pop()||"";let i="";for(let r of t)if(r.trim())try{let s=JSON.parse(r);this._emitToolCalls(s);let n=this.extractText(s);if(n){if(this.rawText&&n.startsWith(this.rawText)){let o=n.substring(this.rawText.length);this.rawText=n,i+=o}else(!this.rawText.includes(n)||n.length<20)&&(this.rawText+=n,i+=n);this.tryExtractResult(this.rawText)}else this.isValidResult(s)&&(this.rawText+=`${r}
33
+ `,i+=`${r}
34
+ `,this.extractedResult=s)}catch{if(r.includes('"text"')||r.includes('"content"')){let n=r.match(/"text"\s*:\s*"([^"]*)/),o=r.match(/"content"\s*:\s*"([^"]*)/),l=n?n[1]:o?o[1]:null;l&&!this.rawText.includes(l)&&(i+=l,this.rawText+=l)}}return i||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let i=this.extractText(t);i&&(this.rawText+=i,e+=i,this.tryExtractResult(i))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(n,o)=>{if(!n)return;let l=`${n}:${JSON.stringify(o??{})}`;this._lastToolEmit!==l&&(this._lastToolEmit=l,this.onToolCall(n,o??void 0))},i=n=>{if(n!=null){if(typeof n=="object"&&!Array.isArray(n))return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,i(e.input??e.arguments));return}let n=e.tool_call;if(n&&typeof n=="object"&&!Array.isArray(n)){let o=Object.keys(n);if(o.length===1){let l=o[0],u=n[l],d=u&&typeof u=="object"?u.args??u.input??u:void 0;t(l,i(d))}return}return}if(Array.isArray(e.tool_calls)){for(let n of e.tool_calls)t(n.name,i(n.input??n.arguments));return}let r=e.message??e;if(Array.isArray(r?.tool_calls)){for(let n of r.tool_calls)t(n.name,i(n.input??n.arguments));return}let s=r?.content??e.content;if(Array.isArray(s))for(let n of s)(n.type==="tool_use"||n.type==="tool_call")&&n.name&&t(n.name,i(n.input??n.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join("")}return e.type==="thinking"&&e.text||e.text?e.text:e.content&&typeof e.content=="string"?e.content:e.delta?e.delta:null}tryExtractResult(e){if(!e||typeof e!="string")return;let t=[],i=/```json\s*\n?([\s\S]*?)\n?```/g,r;for(;(r=i.exec(e))!==null;){let m=r[1].trim();try{JSON.parse(m),t.push({text:m,source:"markdown"})}catch{}}let s=0,n=0;for(;s<e.length&&(s=e.indexOf("{",s),s!==-1);){let m=0,p=s;for(let h=s;h<e.length;h++)if(e[h]==="{")m++;else if(e[h]==="}"&&(m--,m===0)){p=h,t.push({text:e.substring(s,p+1),source:"brace"}),n++;break}s=p+1}let o=this.extractedResult,l=o?JSON.stringify(o).length:0,u=0,d=-1;for(let m=0;m<t.length;m++){let p=t[m];try{let h=p.text.replace(/,(\s*[}\]])/g,"$1"),_=JSON.parse(h);this.isValidResult(_)&&(u++,l=JSON.stringify(_).length,o=_,d=m)}catch{}}o&&(this.extractedResult=o)}isValidResult(e){if(!e||typeof e!="object"||Array.isArray(e)||e.session_id||e.timestamp_ms||e.type||e.call_id||e.tool_call||e.result&&typeof e.result=="object"&&(e.result.success&&typeof e.result.success=="object"||e.result.error&&typeof e.result.error=="object")||e.args&&typeof e.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(e),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(e,t=null){let i=new a;i.zodSchema=t,i.processChunk(e),i.flush();let r=i.getResult();return!r&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),r}};function q(a){let e=`${a}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let i=t.split(/[,\n]+/).map(n=>n.trim()).filter(Boolean);if(i.length===0)return{picked:null,count:0,dispose:()=>{}};let r=i[Math.floor(Math.random()*i.length)],s=process.env[a];return process.env[a]=r,c.debug(`[auth-pool] ${a}: picked 1 of ${i.length} from pool (***${r.slice(-4)})`),{picked:r,count:i.length,dispose(){s===void 0?delete process.env[a]:process.env[a]=s}}}function Ee(a){if(!a)return null;let e=String(a),t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t?.[1])try{return JSON.parse(t[1].trim())}catch{}let i=e.indexOf("{");if(i<0)return null;let r=0,s=!1,n=!1,o=-1;for(let l=i;l<e.length;l++){let u=e[l];if(s){n?n=!1:u==="\\"?n=!0:u==='"'&&(s=!1);continue}if(u==='"'){s=!0;continue}if(u==="{"){r===0&&(o=l),r+=1;continue}if(u==="}"){if(r===0)continue;if(r-=1,r===0&&o>=0){let d=e.slice(o,l+1);try{return JSON.parse(d)}catch{o=-1}}}}return null}function _e(a){let e=String(a||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return Ee(e)}}function Te(a){try{let e=JSON.parse(a);if(typeof e=="string")return e;if(typeof e?.response=="string")return e.response;if(typeof e?.text=="string")return e.text;if(typeof e?.output=="string")return e.output;if(Array.isArray(e?.candidates)&&e.candidates.length>0){let t=e.candidates[0];if(typeof t?.content=="string")return t.content;if(Array.isArray(t?.content?.parts)){let i=t.content.parts.map(r=>typeof r?.text=="string"?r.text:"").join("");if(i.trim())return i}}}catch{}return a}var ce=class extends Oe{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GEMINI_API_KEY_POOL||process.env.GOOGLE_API_KEY||process.env.GOOGLE_API_KEY_POOL))return c.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return be("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return c.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:i,workspace:r=process.cwd(),schema:s=null,skills:n=null,sessionPath:o=null,nodeName:l=null,timeout:u=600*1e3,signal:d=null}=t,m=[q("GEMINI_API_KEY"),q("GOOGLE_API_KEY")];try{let p=i;(!p||p==="auto")&&(p=ne.GEMINI);let h=ie[p]||p,_=String(process.env.GEMINI_API_KEY||"").trim(),V=String(process.env.GOOGLE_API_KEY||"").trim(),A=this._resolveSkillsToMcp(n,{sessionPath:o,workspace:r,nodeName:l}),ue=Object.keys(A).length>0,T=new J(e),U=s&&typeof s.parse=="function",w=null;if(s){let f;try{let I=U?te(s,{target:"openAi"}):s;f=JSON.stringify(I,null,2)}catch{f="{}"}if(ue){T.addSystemInstruction(`Write valid JSON that matches this schema:
35
+ ${f}`,"schema_instruction","append");let I=`zibby-result-${Date.now()}.json`,O=E(r,".zibby","tmp");w=E(O,I),oe(O,{recursive:!0}),T.addStructuredOutput(s,w)}else T.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
36
+ ${f}`,"json_instruction","append")}let de=T.build(),fe=T.getUserPrompt(),C=T.getStats(),X=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),pe=X?` | key: ***${X.slice(-4)}`:" | key: not set";console.log(`
37
+ \u25C6 Model: ${h||"auto"}${pe}
38
+ `);let M=(await import("chalk")).default;console.log(`
39
+ ${M.bold("Prompt sent to LLM:")}`),console.log(M.dim("\u2500".repeat(60))),console.log(M.dim(fe)),console.log(M.dim("\u2500".repeat(60)));let F=this._createGeminiConfigDir(r,A),x=["--output-format","json"];h&&h!=="auto"&&x.push("--model",h);let K=Object.keys(A);if(K.length>0){x.push("--approval-mode","yolo");for(let f of K)x.push("--allowed-mcp-server-names",f);c.info(`[Gemini] Enabling MCP servers: ${K.join(", ")}`)}else n&&n.length>0&&c.warn(`[Gemini] Skills requested but no MCP servers configured: ${n.join(", ")}`);x.push("-p",de);let k={...process.env,GEMINI_CLI_HOME:F};_?(k.GEMINI_API_KEY=_,delete k.GOOGLE_API_KEY):V&&(k.GOOGLE_API_KEY=V,delete k.GEMINI_API_KEY),c.debug(`[Gemini] Command: gemini ${x.slice(0,8).join(" ")}... (${x.length} total args)`),c.debug(`[Gemini] User prompt: ${C.userPromptLength} chars, System instructions: ${C.systemInstructionsLength} chars (${C.instructionCount} blocks), Full: ${C.fullPromptLength} chars`),c.debug(`[Gemini] Config home: ${F}`),c.debug(`[Gemini] GEMINI_CLI_HOME env: ${k.GEMINI_CLI_HOME}`);let Y="",G=null;try{Y=await new Promise((I,O)=>{let v=xe("gemini",x,{cwd:r,env:k,stdio:["ignore","pipe","pipe"],...d&&{signal:d}}),z="",Z="",B=!1,P=null,H=!1,j=setTimeout(()=>{try{v.kill("SIGTERM")}catch{}},u),L=()=>{H||B||(H=!0,P=setTimeout(()=>{if(!B)try{v.kill("SIGKILL")}catch{}},5e3))};d&&(d.aborted?L():d.addEventListener("abort",L,{once:!0})),v.stdout.on("data",b=>{z+=b.toString()}),v.stderr.on("data",b=>{Z+=b.toString()}),v.on("error",b=>{if(clearTimeout(j),P&&clearTimeout(P),d&&!d.aborted)try{d.removeEventListener("abort",L)}catch{}O(b)}),v.on("close",b=>{if(B=!0,clearTimeout(j),P&&clearTimeout(P),d&&!d.aborted)try{d.removeEventListener("abort",L)}catch{}if(H){let Q=new Error("Aborted via signal");return Q.name="AbortError",O(Q)}if(b===0)return I(z.trim());O(new Error(`gemini failed with code ${b}: ${(Z||z).trim()}`))})})}catch(f){G=f}finally{try{Se(F,{recursive:!0,force:!0})}catch{}}let y=Te(Y).trim();if(!s){if(G)throw G;return y}if(w){let f=se(w);if(c.info(`[Gemini] Result file: ${f?"present":"missing"} at ${w}`),f)try{let I=ae(w,"utf-8").trim(),O=JSON.parse(I),v=U?s.parse(O):O;return c.info("[Gemini] Structured output recovered from result file"),{raw:y,structured:v}}catch(I){c.warn(`[Gemini] Result file parse/validation failed: ${I.message}`)}else G||c.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let S=null;if(s){let f=new D;f.zodSchema=s,f.processChunk(y),f.flush(),S=f.getResult()}if(c.info(`[Gemini] Raw stdout length: ${Y.length} chars`),c.info(`[Gemini] Extracted text length: ${y.length} chars`),c.info(`[Gemini] StreamParser result: ${S?"extracted":"null"}`),S||(y.length<2e3?c.info(`[Gemini] Raw text preview:
40
+ ${y}`):c.info(`[Gemini] Raw text preview (first 1000 chars):
41
+ ${y.slice(0,1e3)}`),S=_e(y)),!S)throw G||(c.error("[Gemini] Failed to extract valid JSON from output"),c.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error("Gemini did not return valid JSON for structured output. Enable strictMode for proxy fallback."));let me=U?s.parse(S):S;return{raw:y,structured:me}}finally{for(let p of m)p.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let i={};for(let r of e){let s=ve(r);if(!s||typeof s.resolve!="function")continue;let n=s.resolve(t);if(!n)continue;let o=s.cursorKey||s.serverName||r,l={command:n.command};n.args?.length&&(l.args=n.args),n.env&&Object.keys(n.env).length>0&&(l.env=n.env),n.cwd&&(l.cwd=n.cwd),i[o]=l}return i}_createGeminiConfigDir(e,t){let i=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,r=E(e||process.cwd(),".zibby","tmp",`gemini-home-${i}`),s=E(r,".gemini");oe(s,{recursive:!0});let n=E(s,"settings.json"),o={},l=E(process.env.HOME||"",".gemini","settings.json");if(se(l))try{o=JSON.parse(ae(l,"utf-8"))}catch{o={}}let u={...o,mcpServers:{...o.mcpServers&&typeof o.mcpServers=="object"?o.mcpServers:{},...t||{}}};le(n,`${JSON.stringify(u,null,2)}
42
+ `,"utf-8");let d=E(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{le(d,`${JSON.stringify(u,null,2)}
43
+ `,"utf-8")}catch{}return c.debug(`[Gemini] Created isolated config with ${Object.keys(u.mcpServers||{}).length} MCP servers`),c.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(u.mcpServers||{}),null,2)}`),r}};export{ce as GeminiAgentStrategy};