@zibby/core 0.5.5 → 0.5.6

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,13 +1,13 @@
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}
1
+ import{AgentStrategy as Me,DEFAULT_OUTPUT_BASE as Ue,SESSION_INFO_FILE as De,STOP_REQUEST_FILE as Fe,getAllSkills as Ge,getSkill as de}from"@zibby/agent-workflow";import{spawn as Be,execSync as G}from"node:child_process";import{writeFileSync as pe,readFileSync as fe,mkdirSync as me,existsSync as Y,accessSync as ge,constants as he,unlinkSync as Je}from"node:fs";import{join as w,resolve as Ke}from"node:path";import{homedir as H}from"node:os";import z from"chalk";var C={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 C.debug;if(process.env.ZIBBY_VERBOSE==="true")return C.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in C?C[e]:C.info}_shouldLog(e){return C[e]>=this._level}_formatMessage(e,t,r={}){let o=new Date().toISOString(),n=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(n+=z.dim(` ${JSON.stringify(r)}`)),n}_getPrefix(e){return{debug:z.gray("[DEBUG]"),info:z.cyan("[INFO]"),warn:z.yellow("[WARN]"),error:z.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 C&&(this._level=C[e])}getLevel(){return Object.keys(C).find(e=>C[e]===this._level)}},s=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(i){let e={};for(let t of Oe)t.vendor===i&&(e[t.alias]=t.canonicalId);return e}var V={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 je=W("claude"),We=W("codex"),Ze=W("gemini"),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(e){if(!e)return null;this.buffer+=e;let t=this.buffer.split(`
2
+ `);this.buffer=t.pop()||"";let r="";for(let o of t)if(o.trim())try{let l=JSON.parse(o);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+=`${o}
3
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`
4
+ `,this.extractedResult=l)}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 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 o=e.message??e;if(Array.isArray(o?.tool_calls)){for(let n of o.tool_calls)t(n.name,r(n.input??n.arguments));return}let l=o?.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,o;for(;(o=r.exec(e))!==null;){let m=o[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 O=l;O<e.length;O++)if(e[O]==="{")m++;else if(e[O]==="}"&&(m--,m===0)){p=O,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 O=p.text.replace(/,(\s*[}\]])/g,"$1"),x=JSON.parse(O);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 i;r.zodSchema=t,r.processChunk(e),r.flush();let o=r.getResult();return!o&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),o}};import{zodToJsonSchema as be}from"zod-to-json-schema";var q=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=be(e,{target:"openApi3"}):r=e;let o=this._buildExample(r);return`
5
5
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
6
6
  \u{1F6A8} MANDATORY: WRITE RESULT TO FILE \u{1F6A8}
7
7
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
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.
@@ -21,25 +21,25 @@ JSON types (strict \u2014 validators reject wrong types):
21
21
  - Use true/false without quotes for booleans.
22
22
  - Use unquoted null where a field may be null.
23
23
 
24
- Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(t){if(!t)return{};let e=t.type;if(e==="object"&&t.properties){let r={};for(let[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[o,l]of Object.entries(e.properties))r[o]=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(o=>o.type!=="null")||e.anyOf?.find(o=>o.type!=="null");return r?this._buildExample(r):null}return"<value>"}};var Q=class i{constructor(e=""){this.userPrompt=e,this.systemInstructions=[],this.metadata={}}setUserPrompt(e){return this.userPrompt=e,this}appendUserPrompt(e){return this.userPrompt?this.userPrompt+=`
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(o=>o.position==="prepend").map(o=>o.content),t=this.systemInstructions.filter(o=>o.position==="append").map(o=>o.content);return[...e,this.userPrompt,...t].filter(Boolean).join(`
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] ...
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 i(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};import Ie from"axios";import{homedir as Ee}from"node:os";import{join as ve}from"node:path";import{existsSync as Se,readFileSync as xe}from"node:fs";import{toJSONSchema as _e}from"zod";function Te(){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=ve(Ee(),".zibby","config.json");if(Se(i)){let e=JSON.parse(xe(i,"utf-8"));if(e.sessionToken)return s.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(i){s.debug(`[Auth] Could not read zibby login session: ${i.message}`)}return null}function Ae(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function B(i){if(!(typeof i!="object"||i===null)){if(Object.keys(i).length===0){i.type="object",i.additionalProperties=!0;return}if(i.type||(i.properties?i.type="object":i.items&&(i.type="array")),i.type==="object")if(i.properties){for(let[e,t]of Object.entries(i.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(i.properties[e]={type:["object","null"]});i.additionalProperties=!1,i.required=Object.keys(i.properties),Object.values(i.properties).forEach(B)}else"additionalProperties"in i||(i.additionalProperties=!0);i.type==="array"&&i.items&&B(i.items),i.anyOf&&i.anyOf.forEach(B),i.oneOf&&i.oneOf.forEach(B),i.allOf&&i.allOf.forEach(B)}}async function se(i,e){s.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=Te();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=Ae();s.info(`\u{1F517} Using OpenAI proxy: ${r}`);let o=_e(e),l=o;if(o.$ref&&o.definitions){let d=o.$ref.split("/").pop();l=o.definitions[d]||o,s.debug(`Extracted schema from $ref: ${d}`)}delete l.$schema,B(l);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
35
  ${i.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:V.OPENAI_POSTPROCESSING,messages:[{role:"user",content:c}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:l,strict:!0}}};s.info(`\u{1F4E4} Sending to OpenAI proxy: model=${V.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(l.properties||{}).join(", ")}`),s.debug(` Schema size: ${JSON.stringify(l).length} chars`),s.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 Ie.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 O=JSON.parse(p);return s.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:O,raw:i}}catch(d){if(d.response){let m=d.response.status,p=d.response.data;throw s.error(`\u274C OpenAI proxy request failed: ${m}`),s.error(` Status: ${m}`),s.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 s.error(`\u274C OpenAI proxy request failed: ${d.message}`),new Error(`Failed to format output: ${d.message}`,{cause:d})}}function ie(i){let e=`${i}_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 o=r[Math.floor(Math.random()*r.length)],l=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(){l===void 0?delete process.env[i]:process.env[i]=l}}}import{timeline as ne,Timeline as gt,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as ht}from"@zibby/agent-workflow";import{copyFileSync as we,existsSync as oe,lstatSync as $e,mkdirSync as ae,rmSync as Pe,symlinkSync as Ce,unlinkSync as ke}from"node:fs";import{join as M}from"node:path";import{homedir as Re}from"node:os";import{randomBytes as Ne}from"node:crypto";var Le=["cli-config.json","config.json","auth.json","argv.json"];function le(i){return!(!i||typeof i!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function ue(i){let e=M(i||process.cwd(),".zibby","tmp");ae(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${Ne(4).toString("hex")}`,r=M(e,`cursor-agent-home-${t}`),o=M(r,".cursor");ae(o,{recursive:!0});let l=Re(),n=M(l,".cursor");if(oe(n))for(let u of Le){let c=M(n,u);if(oe(c))try{we(c,M(o,u))}catch{}}if(process.platform==="darwin"){let u=M(l,"Library");if(oe(u))try{Ce(u,M(r,"Library"))}catch{}}return r}function ce(i){if(!(!i||typeof i!="string"))try{let e=M(i,"Library");try{$e(e).isSymbolicLink()&&ke(e)}catch{}Pe(i,{recursive:!0,force:!0})}catch{}}var ye=class extends Me{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("/")){ge(r,he.X_OK);let o=G(`"${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=G(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!o)continue;let l=G(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(l&&l.length>0)return s.debug(`[Cursor] Found '${r}' in PATH at ${o} (version: ${l.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(e,t={}){let{workspace:r=process.cwd(),print:o=!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,O=t.model??d?.agent?.cursor?.model??V.CURSOR,x=ie("CURSOR_API_KEY");try{s.debug(`[Cursor] Invoking (model: ${O}, 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("/"))ge(h,he.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,s.debug(`[Agent] Using binary: ${h}`);break}catch(a){s.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),S=null;if(l){let h=`zibby-result-${Date.now()}.json`;S=w(r,".zibby","tmp",h);let a=w(r,".zibby","tmp");Y(a)||me(a,{recursive:!0}),A.addStructuredOutput(l,S)}let J=process.env.CURSOR_API_KEY,j=J?` | key: ***${J.slice(-4)}`:" | key: not set";console.log(`
55
+ \u25C6 Model: ${O||"auto"}${j}
56
+ `);let D=(await import("chalk")).default,b=A.getUserPrompt();console.log(`
57
+ ${D.bold("Prompt sent to LLM:")}`),console.log(D.dim("\u2500".repeat(60))),console.log(D.dim(b)),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",O||"auto"];if(process.env.CURSOR_API_KEY&&N.push("--api-key",process.env.CURSOR_API_KEY),N.push(F),s.debug(`[Agent] User prompt: ${R.userPromptLength} chars, System instructions: ${R.systemInstructionsLength} chars (${R.instructionCount} blocks), Full: ${R.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 $,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 P=$?.stdout||"";if(l){let h=typeof l.parse=="function",a=null,E=!!(S&&Y(S));if(S&&s.info(`[Agent] Result file: ${E?"present":"missing"} at ${S}`),E)try{let f=fe(S,"utf-8").trim();a=JSON.parse(f),s.info(`[Agent] Parsed JSON from result file OK (${f.length} chars) \u2192 object ready for validation`),L&&s.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(f){s.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${f.message}`)}else if(L)s.warn(`[Agent] Result file missing at ${S} (agent process error \u2014 may still recover if strictMode repairs)`);else throw s.error(`\u274C [Agent] Result file was never created at ${S}`),new Error(`Agent did not write required result file at ${S}`);if(a&&h)try{let f=l.parse(a);return s.info("\u2705 [Agent] Zod validation passed for structured result file"),p&&s.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:P,structured:f}}catch(f){let _=f.issues?f.issues.map(v=>` - ${v.path.join(".")}: ${v.message}`).join(`
59
+ `):f.message?.slice(0,400);if(s.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
60
+ ${_}`),s.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 s.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),p&&s.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:P,structured:a};E&&s.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;s.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${_.length} chars in)`);try{let v=await se(_,l);if(h){let K=l.parse(v.structured);return s.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:P,structured:K}}return{raw:P,...v}}catch(v){if(s.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${v.message}`),a)return s.warn("[Agent] Using agent's original result file as fallback"),{raw:P,structured:a}}}if(L)throw L;let I=E?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 s.error(`\u274C [Agent] No validated structured output: ${I}`),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 ${S}. Enable strictMode for proxy fallback.`)}if(L)throw L;return this._extractFinalResult(P)||$?.parsedText||P}finally{x.dispose()}}_extractFinalResult(e){if(!e)return null;let t=e.split(`
66
+ `),r=null;for(let o of t){let l=o.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,o=null,l=null){let n=r?.headless,u=w(H(),".cursor"),c=w(u,"mcp.json"),y={};if(Y(c))try{y=JSON.parse(fe(c,"utf-8"))}catch{}let d=y.mcpServers||{},m=r?.paths?.output||Ue,p=w(t||process.cwd(),m,De),O=Array.isArray(o)?o.map(g=>de(g)).filter(Boolean):[...Ge()].map(([,g])=>g),x=new Set;for(let g of O)typeof g.resolve=="function"&&(x.has(g.serverName)||(x.add(g.serverName),this._ensureSkillConfigured(d,g,e,p,l,n)));if(e){let g=de("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 s.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let k=`${JSON.stringify({mcpServers:d},null,2)}
67
+ `;if(le(e)){let g=ue(t||process.cwd()),T=w(g,".cursor","mcp.json");return pe(T,k,"utf8"),s.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${g} | servers: ${Object.keys(d).join(", ")}`),{isolatedMcpHome:g}}return Y(u)||me(u,{recursive:!0}),pe(c,k,"utf8"),s.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(d).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,o,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(O=>O.startsWith("--output-dir=")?`--output-dir=${r}`:O);let m=d?.env||{},p=t.sessionEnvKey?{[t.sessionEnvKey]:o}:{};e[c].env={...e[c].env||{},...m,...p},s.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]:o}}},s.debug(`[MCP] Configured ${u}`))}_spawnWithStreaming(e,t,r,o,l=null,n=null,u=null,c=null){return new Promise((y,d)=>{let m=Date.now(),p="",O="",x=Date.now(),k=0,g=!1,T=null,U=!1,A=!1,S=null;if(n)try{S=w(Ke(String(n)),Fe)}catch{S=null}let J=!1,j=()=>{J||(J=!0,ce(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 b=Be(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:D,...c&&{signal:c}});s.debug(`[Agent] PID: ${b.pid}`);let F=null,R=()=>{g||A||(g=!0,T="aborted",s.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),F=setTimeout(()=>{if(!A){s.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{b.kill("SIGKILL")}catch{}}},5e3))};c&&(c.aborted?R():c.addEventListener("abort",R,{once:!0})),b.stdin.on("error",a=>{a.code!=="EPIPE"&&s.warn(`[Agent] stdin error: ${a.message}`)}),b.stdout.on("error",a=>{a.code!=="EPIPE"&&s.warn(`[Agent] stdout error: ${a.message}`)}),b.stderr.on("error",a=>{a.code!=="EPIPE"&&s.warn(`[Agent] stderr error: ${a.message}`)}),l?(b.stdin.write(l,a=>{a&&a.code!=="EPIPE"&&s.warn(`[Agent] Failed to write to stdin: ${a.message}`),b.stdin.end()}),s.debug(`[Agent] Prompt also piped to stdin (${l.length} chars)`)):b.stdin.end();let N=null;S&&(N=setInterval(()=>{if(!(g||A))try{if(Y(S)){g=!0,T="aborted";try{Je(S)}catch{}s.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),b.kill("SIGTERM"),setTimeout(()=>{b.killed||b.kill("SIGKILL")},2e3)}}catch{}},600));let $=new Set,L=new Date(m).toISOString().replace(/\.\d+Z$/,""),P=setInterval(()=>{let a=Math.round((Date.now()-m)/1e3),E=Math.round((Date.now()-x)/1e3),I=[];try{let _=Math.ceil(a/60)+1,v=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(v)for(let K of v.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(v=>v.split("/").pop()).join(", ")}`),$.size>0&&(f+=` | \u{1F4E6} total: ${$.size} files`),s.debug(`\u{1F493} [Agent] Running for ${a}s | ${k} lines output${f}`),k===0&&a>=30&&$.size===0&&(a<35&&s.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",s.error(`\u274C [Agent] No response after ${a}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),b.kill("SIGTERM"),setTimeout(()=>{b.killed||b.kill("SIGKILL")},3e3)))},3e4),ee=setTimeout(()=>{g=!0,T=T||"timeout";let a=Math.round((Date.now()-m)/1e3);s.error(`\u23F1\uFE0F [Agent] Timeout after ${a}s \u2014 killing process (PID: ${b.pid})`),p.trim()&&s.warn(`\u{1F4E4} [Agent] Partial output (${p.length} chars) before timeout:
69
+ ${p.slice(-2e3)}`),b.kill("SIGTERM"),setTimeout(()=>{b.killed||b.kill("SIGKILL")},5e3)},o),h=new X;h.onToolCall=(a,E)=>{let I=a,f=E;if(a==="mcpToolCall"&&E?.name)I=E.name.replace(/^mcp_+[^_]+_+/,""),I.includes("-")&&I.split("-")[0]===I.split("-")[1]&&(I=I.split("-")[0]),f=E.args??E.input??E;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 v=JSON.stringify(f),K=v.length>100?`${v.substring(0,100)}...`:v;console.log(` Input: ${K}`)}},b.stdout.on("data",a=>{let E=a.toString();p+=E,x=Date.now(),U||(U=!0);let I=h.processChunk(E);I&&!A&&process.stdout.write(I);let f=E.split(`
70
+ `).filter(_=>_.trim());k+=f.length}),b.stderr.on("data",a=>{let E=a.toString();O+=E,x=Date.now(),U||(U=!0);let I=E.split(`
71
+ `).filter(f=>f.trim());for(let f of I)s.warn(`\u26A0\uFE0F [Agent stderr] ${f}`)}),b.on("close",(a,E)=>{if(A=!0,j(),clearTimeout(ee),clearInterval(P),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(s.debug(`[Agent] Exited: code=${a}, signal=${E}, elapsed=${I}s, output=${p.length} chars`),g){if(T==="aborted"){let v=new Error("Aborted via signal");v.name="AbortError",d(v);return}d(new Error(`Cursor Agent timed out after ${I}s (limit: ${o/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}. ${O.trim()?`
74
+ Stderr: ${O.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||O||"",parsedText:_})}),b.on("error",a=>{if(j(),clearTimeout(ee),clearInterval(P),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{ye 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 me,getSkill as ge}from"@zibby/agent-workflow";import{execSync as he,spawn as ye}from"node:child_process";import{zodToJsonSchema as Ie}from"zod-to-json-schema";import{existsSync as ne,mkdirSync as ie,readFileSync as se,rmSync as Oe,writeFileSync as re}from"node:fs";import{join as S}from"node:path";import A from"chalk";var h={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 h.debug;if(process.env.ZIBBY_VERBOSE==="true")return h.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in h?h[e]:h.info}_shouldLog(e){return h[e]>=this._level}_formatMessage(e,t,i={}){let s=new Date().toISOString(),n=`${this._getPrefix(e)} ${t}`;return Object.keys(i).length>0&&(n+=A.dim(` ${JSON.stringify(i)}`)),n}_getPrefix(e){return{debug:A.gray("[DEBUG]"),info:A.cyan("[INFO]"),warn:A.yellow("[WARN]"),error:A.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 h&&(this._level=h[e])}getLevel(){return Object.keys(h).find(e=>h[e]===this._level)}},l=new W;var fe=[{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 L(c){let e={};for(let t of fe)t.vendor===c&&(e[t.alias]=t.canonicalId);return e}var ee={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 we=L("claude"),ke=L("codex"),te=L("gemini"),Ge={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};import{zodToJsonSchema as pe}from"zod-to-json-schema";var $=class{static generateFileOutputInstructions(e,t){let i;typeof e?.parse=="function"?i=pe(e,{target:"openApi3"}):i=e;let s=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(s,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[s,r]of Object.entries(e.properties))i[s]=this._buildExample(r);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(s=>s.type!=="null")||e.anyOf?.find(s=>s.type!=="null");return i?this._buildExample(i):null}return"<value>"}};var D=class c{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(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(`
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 c(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};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(e){if(!e)return null;this.buffer+=e;let t=this.buffer.split(`
32
+ `);this.buffer=t.pop()||"";let i="";for(let s of t)if(s.trim())try{let r=JSON.parse(s);this._emitToolCalls(r);let n=this.extractText(r);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(r)&&(this.rawText+=`${s}
33
+ `,i+=`${s}
34
+ `,this.extractedResult=r)}catch{if(s.includes('"text"')||s.includes('"content"')){let n=s.match(/"text"\s*:\s*"([^"]*)/),o=s.match(/"content"\s*:\s*"([^"]*)/),a=n?n[1]:o?o[1]:null;a&&!this.rawText.includes(a)&&(i+=a,this.rawText+=a)}}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 a=`${n}:${JSON.stringify(o??{})}`;this._lastToolEmit!==a&&(this._lastToolEmit=a,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 a=o[0],u=n[a],d=u&&typeof u=="object"?u.args??u.input??u:void 0;t(a,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 s=e.message??e;if(Array.isArray(s?.tool_calls)){for(let n of s.tool_calls)t(n.name,i(n.input??n.arguments));return}let r=s?.content??e.content;if(Array.isArray(r))for(let n of r)(n.type==="tool_use"||n.type==="tool_call")&&n.name&&t(n.name,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,s;for(;(s=i.exec(e))!==null;){let m=s[1].trim();try{JSON.parse(m),t.push({text:m,source:"markdown"})}catch{}}let r=0,n=0;for(;r<e.length&&(r=e.indexOf("{",r),r!==-1);){let m=0,p=r;for(let g=r;g<e.length;g++)if(e[g]==="{")m++;else if(e[g]==="}"&&(m--,m===0)){p=g,t.push({text:e.substring(r,p+1),source:"brace"}),n++;break}r=p+1}let o=this.extractedResult,a=o?JSON.stringify(o).length:0,u=0,d=-1;for(let m=0;m<t.length;m++){let p=t[m];try{let g=p.text.replace(/,(\s*[}\]])/g,"$1"),_=JSON.parse(g);this.isValidResult(_)&&(u++,a=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 c;i.zodSchema=t,i.processChunk(e),i.flush();let s=i.getResult();return!s&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),s}};function q(c){let e=`${c}_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 s=i[Math.floor(Math.random()*i.length)],r=process.env[c];return process.env[c]=s,l.debug(`[auth-pool] ${c}: picked 1 of ${i.length} from pool (***${s.slice(-4)})`),{picked:s,count:i.length,dispose(){r===void 0?delete process.env[c]:process.env[c]=r}}}function xe(c){if(!c)return null;let e=String(c),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 s=0,r=!1,n=!1,o=-1;for(let a=i;a<e.length;a++){let u=e[a];if(r){n?n=!1:u==="\\"?n=!0:u==='"'&&(r=!1);continue}if(u==='"'){r=!0;continue}if(u==="{"){s===0&&(o=a),s+=1;continue}if(u==="}"){if(s===0)continue;if(s-=1,s===0&&o>=0){let d=e.slice(o,a+1);try{return JSON.parse(d)}catch{o=-1}}}}return null}function ve(c){let e=String(c||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return xe(e)}}function Ee(c){try{let e=JSON.parse(c);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(s=>typeof s?.text=="string"?s.text:"").join("");if(i.trim())return i}}}catch{}return c}var oe=class extends me{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 l.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return he("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return l.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:i,workspace:s=process.cwd(),schema:r=null,skills:n=null,sessionPath:o=null,nodeName:a=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=ee.GEMINI);let g=te[p]||p,_=String(process.env.GEMINI_API_KEY||"").trim(),V=String(process.env.GOOGLE_API_KEY||"").trim(),N=this._resolveSkillsToMcp(n,{sessionPath:o,workspace:s,nodeName:a}),ae=Object.keys(N).length>0,T=new D(e),U=r&&typeof r.parse=="function",w=null;if(r){let f;try{let I=U?Ie(r,{target:"openAi"}):r;f=JSON.stringify(I,null,2)}catch{f="{}"}if(ae){T.addSystemInstruction(`Write valid JSON that matches this schema:
35
+ ${f}`,"schema_instruction","append");let I=`zibby-result-${Date.now()}.json`,O=S(s,".zibby","tmp");w=S(O,I),ie(O,{recursive:!0}),T.addStructuredOutput(r,w)}else T.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
36
+ ${f}`,"json_instruction","append")}let le=T.build(),ce=T.getUserPrompt(),C=T.getStats(),X=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),ue=X?` | key: ***${X.slice(-4)}`:" | key: not set";console.log(`
37
+ \u25C6 Model: ${g||"auto"}${ue}
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(ce)),console.log(M.dim("\u2500".repeat(60)));let K=this._createGeminiConfigDir(s,N),E=["--output-format","json"];g&&g!=="auto"&&E.push("--model",g);let F=Object.keys(N);if(F.length>0){E.push("--approval-mode","yolo");for(let f of F)E.push("--allowed-mcp-server-names",f);l.info(`[Gemini] Enabling MCP servers: ${F.join(", ")}`)}else n&&n.length>0&&l.warn(`[Gemini] Skills requested but no MCP servers configured: ${n.join(", ")}`);E.push("-p",le);let k={...process.env,GEMINI_CLI_HOME:K};_?(k.GEMINI_API_KEY=_,delete k.GOOGLE_API_KEY):V&&(k.GOOGLE_API_KEY=V,delete k.GEMINI_API_KEY),l.debug(`[Gemini] Command: gemini ${E.slice(0,8).join(" ")}... (${E.length} total args)`),l.debug(`[Gemini] User prompt: ${C.userPromptLength} chars, System instructions: ${C.systemInstructionsLength} chars (${C.instructionCount} blocks), Full: ${C.fullPromptLength} chars`),l.debug(`[Gemini] Config home: ${K}`),l.debug(`[Gemini] GEMINI_CLI_HOME env: ${k.GEMINI_CLI_HOME}`);let Y="",G=null;try{Y=await new Promise((I,O)=>{let x=ye("gemini",E,{cwd:s,env:k,stdio:["ignore","pipe","pipe"],...d&&{signal:d}}),z="",Z="",B=!1,P=null,H=!1,j=setTimeout(()=>{try{x.kill("SIGTERM")}catch{}},u),R=()=>{H||B||(H=!0,P=setTimeout(()=>{if(!B)try{x.kill("SIGKILL")}catch{}},5e3))};d&&(d.aborted?R():d.addEventListener("abort",R,{once:!0})),x.stdout.on("data",v=>{z+=v.toString()}),x.stderr.on("data",v=>{Z+=v.toString()}),x.on("error",v=>{if(clearTimeout(j),P&&clearTimeout(P),d&&!d.aborted)try{d.removeEventListener("abort",R)}catch{}O(v)}),x.on("close",v=>{if(B=!0,clearTimeout(j),P&&clearTimeout(P),d&&!d.aborted)try{d.removeEventListener("abort",R)}catch{}if(H){let Q=new Error("Aborted via signal");return Q.name="AbortError",O(Q)}if(v===0)return I(z.trim());O(new Error(`gemini failed with code ${v}: ${(Z||z).trim()}`))})})}catch(f){G=f}finally{try{Oe(K,{recursive:!0,force:!0})}catch{}}let y=Ee(Y).trim();if(!r){if(G)throw G;return y}if(w){let f=ne(w);if(l.info(`[Gemini] Result file: ${f?"present":"missing"} at ${w}`),f)try{let I=se(w,"utf-8").trim(),O=JSON.parse(I),x=U?r.parse(O):O;return l.info("[Gemini] Structured output recovered from result file"),{raw:y,structured:x}}catch(I){l.warn(`[Gemini] Result file parse/validation failed: ${I.message}`)}else G||l.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let b=null;if(r){let f=new J;f.zodSchema=r,f.processChunk(y),f.flush(),b=f.getResult()}if(l.info(`[Gemini] Raw stdout length: ${Y.length} chars`),l.info(`[Gemini] Extracted text length: ${y.length} chars`),l.info(`[Gemini] StreamParser result: ${b?"extracted":"null"}`),b||(y.length<2e3?l.info(`[Gemini] Raw text preview:
40
+ ${y}`):l.info(`[Gemini] Raw text preview (first 1000 chars):
41
+ ${y.slice(0,1e3)}`),b=ve(y)),!b)throw G||(l.error("[Gemini] Failed to extract valid JSON from output"),l.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 de=U?r.parse(b):b;return{raw:y,structured:de}}finally{for(let p of m)p.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let i={};for(let s of e){let r=ge(s);if(!r||typeof r.resolve!="function")continue;let n=r.resolve(t);if(!n)continue;let o=r.cursorKey||r.serverName||s,a={command:n.command};n.args?.length&&(a.args=n.args),n.env&&Object.keys(n.env).length>0&&(a.env=n.env),n.cwd&&(a.cwd=n.cwd),i[o]=a}return i}_createGeminiConfigDir(e,t){let i=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,s=S(e||process.cwd(),".zibby","tmp",`gemini-home-${i}`),r=S(s,".gemini");ie(r,{recursive:!0});let n=S(r,"settings.json"),o={},a=S(process.env.HOME||"",".gemini","settings.json");if(ne(a))try{o=JSON.parse(se(a,"utf-8"))}catch{o={}}let u={...o,mcpServers:{...o.mcpServers&&typeof o.mcpServers=="object"?o.mcpServers:{},...t||{}}};re(n,`${JSON.stringify(u,null,2)}
42
+ `,"utf-8");let d=S(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{re(d,`${JSON.stringify(u,null,2)}
43
+ `,"utf-8")}catch{}return l.debug(`[Gemini] Created isolated config with ${Object.keys(u.mcpServers||{}).length} MCP servers`),l.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(u.mcpServers||{}),null,2)}`),s}};export{oe as GeminiAgentStrategy};