@zibby/core 0.5.30 → 0.5.33
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.
- package/dist/index.js +90 -90
- package/dist/models.js +1 -1
- package/dist/package.json +1 -1
- package/dist/register-built-in-strategies.js +54 -54
- package/dist/strategies/assistant-strategy.js +5 -5
- package/dist/strategies/claude-strategy.js +2 -2
- package/dist/strategies/codex-strategy.js +5 -5
- package/dist/strategies/cursor-strategy.js +9 -9
- package/dist/strategies/gemini-strategy.js +9 -9
- package/dist/strategies/index.js +61 -61
- package/dist/strategies/utils/openai-proxy-formatter.js +3 -3
- package/dist/strategies/utils/usage.js +1 -0
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{AgentStrategy as ve,getSkill as xe}from"@zibby/agent-workflow";import
|
|
1
|
+
import{AgentStrategy as ve,getSkill as xe}from"@zibby/agent-workflow";import Oe from"node:process";var Ie=Object.freeze(["GITHUB_TOKEN","GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","ATLASSIAN_ACCESS_TOKEN","JIRA_API_TOKEN","JIRA_EMAIL","SENTRY_AUTH_TOKEN","SLACK_BOT_TOKEN","DISCORD_BOT_TOKEN","LINEAR_API_KEY","LINEAR_OAUTH_TOKEN","PLANE_API_KEY","PLANE_OAUTH_TOKEN","ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_MEMORY_AWS_ACCESS_KEY_ID","ZIBBY_MEMORY_AWS_SECRET_ACCESS_KEY","ZIBBY_MEMORY_AWS_SESSION_TOKEN"]);function te(i=Oe.env){let e={},t=new Set(Ie);for(let[n,s]of Object.entries(i))t.has(n)||s!==void 0&&(e[n]=s);return e}import{execSync as Te,spawn as Ae}from"node:child_process";import{z as ne}from"zod";import{zodToJsonSchema as Ee}from"zod-to-json-schema";function _e(i){if(!i||typeof i!="object")return i;if(Array.isArray(i.type))return i.type.includes("null")||(i.type=[...i.type,"null"]),i;if(typeof i.type=="string")return i.type=[i.type,"null"],i;for(let e of["anyOf","oneOf"])if(Array.isArray(i[e]))return i[e].some(t=>t&&t.type==="null")||(i[e]=[...i[e],{type:"null"}]),i;return{anyOf:[i,{type:"null"}]}}function w(i){if(!i||typeof i!="object")return i;for(let e of["$defs","definitions"])if(i[e]&&typeof i[e]=="object")for(let t of Object.keys(i[e]))i[e][t]=w(i[e][t]);for(let e of["anyOf","oneOf","allOf"])Array.isArray(i[e])&&(i[e]=i[e].map(w));if(i.properties&&typeof i.properties=="object"){i.additionalProperties=!1;let e=Object.keys(i.properties),t=new Set(Array.isArray(i.required)?i.required:[]);for(let n of e){let s=w(i.properties[n]);t.has(n)||(s=_e(s)),i.properties[n]=s}i.required=e}return i.items&&(Array.isArray(i.items)?i.items=i.items.map(w):i.items=w(i.items)),i}function ie(i,e={target:"openApi3"}){if(!i)return null;let t=e?.target==="openAi",n=null;if(typeof ne?.toJSONSchema=="function")try{n=ne.toJSONSchema(i)}catch{}if(!n)try{n=Ee(i,e)}catch{return null}if(t&&n)try{return w(n)}catch{return n}return n}import{existsSync as ae,mkdirSync as ce,readFileSync as ue,rmSync as Ne,writeFileSync as fe}from"node:fs";import{join as v}from"node:path";import P from"chalk";var y={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 y.debug;if(process.env.ZIBBY_VERBOSE==="true")return y.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in y?y[e]:y.info}_shouldLog(e){return y[e]>=this._level}_formatMessage(e,t,n={}){let s=new Date().toISOString(),r=`${this._getPrefix(e)} ${t}`;return Object.keys(n).length>0&&(r+=P.dim(` ${JSON.stringify(n)}`)),r}_getPrefix(e){return{debug:P.gray("[DEBUG]"),info:P.cyan("[INFO]"),warn:P.yellow("[WARN]"),error:P.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 y&&(this._level=y[e])}getLevel(){return Object.keys(y).find(e=>y[e]===this._level)}},c=new W;var re=[{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 $(i){let e={};for(let t of re)t.vendor===i&&(e[t.alias]=t.canonicalId);return e}function se(i,e){let t=typeof e=="string"?e.trim():"";if(t&&t!=="auto")return t;if(t==="auto"&&re.some(n=>n.vendor===i&&n.isDefault))return"auto";throw new Error(`[${i}] No model reached this LLM call: the node passed none, no config sets one, and the run carries none (MODEL env unset). Refusing to silently substitute a vendor default \u2014 pick a model on the agent (deploy modal / MODEL cell) or pass options.model explicitly.`)}var Ye=$("claude"),Ve=$("codex"),oe=$("gemini"),Ue={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};import{z as le}from"zod";import{zodToJsonSchema as Se}from"zod-to-json-schema";function be(i){if(!i)return null;if(typeof le?.toJSONSchema=="function")try{return le.toJSONSchema(i)}catch{}try{return Se(i,{target:"openApi3"})}catch{return null}}var D=class{static generateFileOutputInstructions(e,t){let n;typeof e?.parse=="function"?n=be(e):n=e;let s=this._buildExample(n);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
|
|
@@ -31,13 +31,13 @@ ${e.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:t,p
|
|
|
31
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(n=>n.type)}}clone(){let e=new i(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};var K=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(`
|
|
32
32
|
`);this.buffer=t.pop()||"";let n="";for(let s of t)if(s.trim())try{let o=JSON.parse(s);this._emitToolCalls(o);let r=this.extractText(o);if(r){if(this.rawText&&r.startsWith(this.rawText)){let l=r.substring(this.rawText.length);this.rawText=r,n+=l}else(!this.rawText.includes(r)||r.length<20)&&(this.rawText+=r,n+=r);this.tryExtractResult(this.rawText)}else this.isValidResult(o)&&(this.rawText+=`${s}
|
|
33
33
|
`,n+=`${s}
|
|
34
|
-
`,this.extractedResult=o)}catch{if(s.includes('"text"')||s.includes('"content"')){let r=s.match(/"text"\s*:\s*"([^"]*)/),l=s.match(/"content"\s*:\s*"([^"]*)/),a=r?r[1]:l?l[1]:null;a&&!this.rawText.includes(a)&&(n+=a,this.rawText+=a)}}return n||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let n=this.extractText(t);n&&(this.rawText+=n,e+=n,this.tryExtractResult(n))}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=(r,l)=>{if(!r)return;let a=`${r}:${JSON.stringify(l??{})}`;this._lastToolEmit!==a&&(this._lastToolEmit=a,this.onToolCall(r,l??void 0))},n=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(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,n(e.input??e.arguments));return}let r=e.tool_call;if(r&&typeof r=="object"&&!Array.isArray(r)){let l=Object.keys(r);if(l.length===1){let a=l[0],u=r[a],f=u&&typeof u=="object"?u.args??u.input??u:void 0;t(a,n(f))}return}return}if(Array.isArray(e.tool_calls)){for(let r of e.tool_calls)t(r.name,n(r.input??r.arguments));return}let s=e.message??e;if(Array.isArray(s?.tool_calls)){for(let r of s.tool_calls)t(r.name,n(r.input??r.arguments));return}let o=s?.content??e.content;if(Array.isArray(o))for(let r of o)(r.type==="tool_use"||r.type==="tool_call")&&r.name&&t(r.name,n(r.input??r.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(n=>n.type==="text"&&n.text).map(n=>n.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=[],n=/```json\s*\n?([\s\S]*?)\n?```/g,s;for(;(s=n.exec(e))!==null;){let
|
|
35
|
-
${d}`,"schema_instruction","append");let O=`zibby-result-${Date.now()}.json`,I=v(s,".zibby","tmp");A=v(I,O),
|
|
36
|
-
${d}`,"json_instruction","append")}let
|
|
37
|
-
\u25C6 Model: ${
|
|
34
|
+
`,this.extractedResult=o)}catch{if(s.includes('"text"')||s.includes('"content"')){let r=s.match(/"text"\s*:\s*"([^"]*)/),l=s.match(/"content"\s*:\s*"([^"]*)/),a=r?r[1]:l?l[1]:null;a&&!this.rawText.includes(a)&&(n+=a,this.rawText+=a)}}return n||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let n=this.extractText(t);n&&(this.rawText+=n,e+=n,this.tryExtractResult(n))}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=(r,l)=>{if(!r)return;let a=`${r}:${JSON.stringify(l??{})}`;this._lastToolEmit!==a&&(this._lastToolEmit=a,this.onToolCall(r,l??void 0))},n=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(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,n(e.input??e.arguments));return}let r=e.tool_call;if(r&&typeof r=="object"&&!Array.isArray(r)){let l=Object.keys(r);if(l.length===1){let a=l[0],u=r[a],f=u&&typeof u=="object"?u.args??u.input??u:void 0;t(a,n(f))}return}return}if(Array.isArray(e.tool_calls)){for(let r of e.tool_calls)t(r.name,n(r.input??r.arguments));return}let s=e.message??e;if(Array.isArray(s?.tool_calls)){for(let r of s.tool_calls)t(r.name,n(r.input??r.arguments));return}let o=s?.content??e.content;if(Array.isArray(o))for(let r of o)(r.type==="tool_use"||r.type==="tool_call")&&r.name&&t(r.name,n(r.input??r.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(n=>n.type==="text"&&n.text).map(n=>n.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=[],n=/```json\s*\n?([\s\S]*?)\n?```/g,s;for(;(s=n.exec(e))!==null;){let p=s[1].trim();try{JSON.parse(p),t.push({text:p,source:"markdown"})}catch{}}let o=0,r=0;for(;o<e.length&&(o=e.indexOf("{",o),o!==-1);){let p=0,g=o;for(let m=o;m<e.length;m++)if(e[m]==="{")p++;else if(e[m]==="}"&&(p--,p===0)){g=m,t.push({text:e.substring(o,g+1),source:"brace"}),r++;break}o=g+1}let l=this.extractedResult,a=l?JSON.stringify(l).length:0,u=0,f=-1;for(let p=0;p<t.length;p++){let g=t[p];try{let m=g.text.replace(/,(\s*[}\]])/g,"$1"),x=JSON.parse(m);this.isValidResult(x)&&(u++,a=JSON.stringify(x).length,l=x,f=p)}catch{}}l&&(this.extractedResult=l)}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 n=new i;n.zodSchema=t,n.processChunk(e),n.flush();let s=n.getResult();return!s&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),s}};function j(i){let e=`${i}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let n=t.split(/[,\n]+/).map(r=>r.trim()).filter(Boolean);if(n.length===0)return{picked:null,count:0,dispose:()=>{}};let s=n[Math.floor(Math.random()*n.length)],o=process.env[i];return process.env[i]=s,c.debug(`[auth-pool] ${i}: picked 1 of ${n.length} from pool (***${s.slice(-4)})`),{picked:s,count:n.length,dispose(){o===void 0?delete process.env[i]:process.env[i]=o}}}function ke(i){if(!i)return null;let e=String(i),t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t?.[1])try{return JSON.parse(t[1].trim())}catch{}let n=e.indexOf("{");if(n<0)return null;let s=0,o=!1,r=!1,l=-1;for(let a=n;a<e.length;a++){let u=e[a];if(o){r?r=!1:u==="\\"?r=!0:u==='"'&&(o=!1);continue}if(u==='"'){o=!0;continue}if(u==="{"){s===0&&(l=a),s+=1;continue}if(u==="}"){if(s===0)continue;if(s-=1,s===0&&l>=0){let f=e.slice(l,a+1);try{return JSON.parse(f)}catch{l=-1}}}}return null}function we(i){let e=String(i||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return ke(e)}}function Ge(i){try{let e=JSON.parse(i);if(typeof e=="string")return e;if(typeof e?.response=="string")return e.response;if(typeof e?.text=="string")return e.text;if(typeof e?.output=="string")return e.output;if(Array.isArray(e?.candidates)&&e.candidates.length>0){let t=e.candidates[0];if(typeof t?.content=="string")return t.content;if(Array.isArray(t?.content?.parts)){let n=t.content.parts.map(s=>typeof s?.text=="string"?s.text:"").join("");if(n.trim())return n}}}catch{}return i}var de=class extends ve{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GEMINI_API_KEY_POOL||process.env.GOOGLE_API_KEY||process.env.GOOGLE_API_KEY_POOL))return c.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return Te("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return c.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:n,workspace:s=process.cwd(),schema:o=null,skills:r=null,sessionPath:l=null,nodeName:a=null,timeout:u=600*1e3,signal:f=null}=t,p=[j("GEMINI_API_KEY"),j("GOOGLE_API_KEY")];try{let g=se("gemini",n),m=oe[g]||g,x=String(process.env.GEMINI_API_KEY||"").trim(),Y=String(process.env.GOOGLE_API_KEY||"").trim(),C=this._resolveSkillsToMcp(r,{sessionPath:l,workspace:s,nodeName:a}),pe=Object.keys(C).length>0,T=new J(e),V=o&&typeof o.parse=="function",A=null;if(o){let d;try{let O=V?ie(o,{target:"openAi"}):o;d=JSON.stringify(O,null,2)}catch{d="{}"}if(pe){T.addSystemInstruction(`Write valid JSON that matches this schema:
|
|
35
|
+
${d}`,"schema_instruction","append");let O=`zibby-result-${Date.now()}.json`,I=v(s,".zibby","tmp");A=v(I,O),ce(I,{recursive:!0}),T.addStructuredOutput(o,A)}else T.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
|
|
36
|
+
${d}`,"json_instruction","append")}let me=T.build(),ge=T.getUserPrompt(),L=T.getStats(),Z=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),ye=Z?` | key: ***${Z.slice(-4)}`:" | key: not set";console.log(`
|
|
37
|
+
\u25C6 Model: ${m||"auto"}${ye}
|
|
38
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(
|
|
39
|
+
${M.bold("Prompt sent to LLM:")}`),console.log(M.dim("\u2500".repeat(60))),console.log(M.dim(ge)),console.log(M.dim("\u2500".repeat(60)));let U=this._createGeminiConfigDir(s,C),S=["--output-format","json"];m&&m!=="auto"&&S.push("--model",m);let B=Object.keys(C);if(B.length>0){S.push("--approval-mode","yolo");for(let d of B)S.push("--allowed-mcp-server-names",d);c.info(`[Gemini] Enabling MCP servers: ${B.join(", ")}`)}else r&&r.length>0&&c.warn(`[Gemini] Skills requested but no MCP servers configured: ${r.join(", ")}`);S.push("-p",me);let N={...te(process.env),GEMINI_CLI_HOME:U};x?(N.GEMINI_API_KEY=x,delete N.GOOGLE_API_KEY):Y&&(N.GOOGLE_API_KEY=Y,delete N.GEMINI_API_KEY),c.debug(`[Gemini] Command: gemini ${S.slice(0,8).join(" ")}... (${S.length} total args)`),c.debug(`[Gemini] User prompt: ${L.userPromptLength} chars, System instructions: ${L.systemInstructionsLength} chars (${L.instructionCount} blocks), Full: ${L.fullPromptLength} chars`),c.debug(`[Gemini] Config home: ${U}`),c.debug(`[Gemini] GEMINI_CLI_HOME env: ${N.GEMINI_CLI_HOME}`);let F="",k=null;try{F=await new Promise((O,I)=>{let E=Ae("gemini",S,{cwd:s,env:N,stdio:["ignore","pipe","pipe"],...f&&{signal:f}}),z="",X="",H=!1,G=null,q=!1,Q=setTimeout(()=>{try{E.kill("SIGTERM")}catch{}},u),R=()=>{q||H||(q=!0,G=setTimeout(()=>{if(!H)try{E.kill("SIGKILL")}catch{}},5e3))};f&&(f.aborted?R():f.addEventListener("abort",R,{once:!0})),E.stdout.on("data",_=>{z+=_.toString()}),E.stderr.on("data",_=>{X+=_.toString()}),E.on("error",_=>{if(clearTimeout(Q),G&&clearTimeout(G),f&&!f.aborted)try{f.removeEventListener("abort",R)}catch{}I(_)}),E.on("close",_=>{if(H=!0,clearTimeout(Q),G&&clearTimeout(G),f&&!f.aborted)try{f.removeEventListener("abort",R)}catch{}if(q){let ee=new Error("Aborted via signal");return ee.name="AbortError",I(ee)}if(_===0)return O(z.trim());I(new Error(`gemini failed with code ${_}: ${(X||z).trim()}`))})})}catch(d){k=d}finally{try{Ne(U,{recursive:!0,force:!0})}catch{}}let h=Ge(F).trim();if(!o){if(k)throw k;return h}if(A){let d=ae(A);if(c.info(`[Gemini] Result file: ${d?"present":"missing"} at ${A}`),d)try{let O=ue(A,"utf-8").trim(),I=JSON.parse(O),E=V?o.parse(I):I;return c.info("[Gemini] Structured output recovered from result file"),{raw:h,structured:E}}catch(O){c.warn(`[Gemini] Result file parse/validation failed: ${O.message}`)}else k||c.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let b=null;if(o){let d=new K;d.zodSchema=o,d.processChunk(h),d.flush(),b=d.getResult()}if(c.info(`[Gemini] Raw stdout length: ${F.length} chars`),c.info(`[Gemini] Extracted text length: ${h.length} chars`),c.info(`[Gemini] StreamParser result: ${b?"extracted":"null"}`),b||(h.length<2e3?c.info(`[Gemini] Raw text preview:
|
|
40
40
|
${h}`):c.info(`[Gemini] Raw text preview (first 1000 chars):
|
|
41
|
-
${h.slice(0,1e3)}`),b=we(h)),!b)throw k||(c.error("[Gemini] Failed to extract valid JSON from output"),c.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error("Gemini did not return valid JSON for structured output. Enable strictMode for proxy fallback."));let
|
|
42
|
-
`,"utf-8");let f=v(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{
|
|
43
|
-
`,"utf-8")}catch{}return c.debug(`[Gemini] Created isolated config with ${Object.keys(u.mcpServers||{}).length} MCP servers`),c.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(u.mcpServers||{}),null,2)}`),s}};export{
|
|
41
|
+
${h.slice(0,1e3)}`),b=we(h)),!b)throw k||(c.error("[Gemini] Failed to extract valid JSON from output"),c.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error("Gemini did not return valid JSON for structured output. Enable strictMode for proxy fallback."));let he=V?o.parse(b):b;return{raw:h,structured:he}}finally{for(let g of p)g.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let n={};for(let s of e){let o=xe(s);if(!o||typeof o.resolve!="function")continue;let r=o.resolve(t);if(!r)continue;let l=o.cursorKey||o.serverName||s,a={command:r.command};r.args?.length&&(a.args=r.args),r.env&&Object.keys(r.env).length>0&&(a.env=r.env),r.cwd&&(a.cwd=r.cwd),n[l]=a}return n}_createGeminiConfigDir(e,t){let n=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,s=v(e||process.cwd(),".zibby","tmp",`gemini-home-${n}`),o=v(s,".gemini");ce(o,{recursive:!0});let r=v(o,"settings.json"),l={},a=v(process.env.HOME||"",".gemini","settings.json");if(ae(a))try{l=JSON.parse(ue(a,"utf-8"))}catch{l={}}let u={...l,mcpServers:{...l.mcpServers&&typeof l.mcpServers=="object"?l.mcpServers:{},...t||{}}};fe(r,`${JSON.stringify(u,null,2)}
|
|
42
|
+
`,"utf-8");let f=v(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{fe(f,`${JSON.stringify(u,null,2)}
|
|
43
|
+
`,"utf-8")}catch{}return c.debug(`[Gemini] Created isolated config with ${Object.keys(u.mcpServers||{}).length} MCP servers`),c.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(u.mcpServers||{}),null,2)}`),s}};export{de as GeminiAgentStrategy};
|