@zibby/core 0.5.13 → 0.5.14
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 +125 -125
- package/dist/package.json +1 -1
- package/dist/register-built-in-strategies.js +39 -39
- package/dist/strategies/claude-strategy.js +2 -2
- package/dist/strategies/index.js +35 -35
- package/package.json +1 -1
package/dist/strategies/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var St=Object.defineProperty;var
|
|
1
|
+
var St=Object.defineProperty;var Ot=(s,e)=>()=>(s&&(e=s(s=0)),e);var bt=(s,e)=>{for(var t in e)St(s,t,{get:e[t],enumerable:!0})};var st={};bt(st,{zodToJson:()=>Z});import{z as rt}from"zod";import{zodToJsonSchema as Wt}from"zod-to-json-schema";function Z(s,e={target:"openApi3"}){if(!s)return null;if(typeof rt?.toJSONSchema=="function")try{return rt.toJSONSchema(s)}catch{}try{return Wt(s,e)}catch{return null}}var fe=Ot(()=>{});import{AgentStrategy as Gt,DEFAULT_OUTPUT_BASE as Jt,SESSION_INFO_FILE as jt,STOP_REQUEST_FILE as Ft,getAllSkills as Yt,getSkill as qe}from"@zibby/agent-workflow";import{spawn as zt,execSync as X}from"node:child_process";import{writeFileSync as Qe,readFileSync as et,mkdirSync as tt,existsSync as ue,accessSync as ot,constants as nt,unlinkSync as Ht}from"node:fs";import{join as Y,resolve as Vt}from"node:path";import{homedir as de}from"node:os";import ce from"chalk";var z={debug:0,info:1,warn:2,error:3,silent:4},Ne=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return z.debug;if(process.env.ZIBBY_VERBOSE==="true")return z.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in z?z[e]:z.info}_shouldLog(e){return z[e]>=this._level}_formatMessage(e,t,n={}){let o=new Date().toISOString(),i=`${this._getPrefix(e)} ${t}`;return Object.keys(n).length>0&&(i+=ce.dim(` ${JSON.stringify(n)}`)),i}_getPrefix(e){return{debug:ce.gray("[DEBUG]"),info:ce.cyan("[INFO]"),warn:ce.yellow("[WARN]"),error:ce.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 z&&(this._level=z[e])}getLevel(){return Object.keys(z).find(e=>z[e]===this._level)}},l=new Ne;var Et=[{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 ye(s){let e={};for(let t of Et)t.vendor===s&&(e[t.alias]=t.canonicalId);return e}var j={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 Re=ye("claude"),Me=ye("codex"),Ye=ye("gemini"),_e={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var Q=class s{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
2
|
`);this.buffer=t.pop()||"";let n="";for(let o of t)if(o.trim())try{let r=JSON.parse(o);this._emitToolCalls(r);let i=this.extractText(r);if(i){if(this.rawText&&i.startsWith(this.rawText)){let a=i.substring(this.rawText.length);this.rawText=i,n+=a}else(!this.rawText.includes(i)||i.length<20)&&(this.rawText+=i,n+=i);this.tryExtractResult(this.rawText)}else this.isValidResult(r)&&(this.rawText+=`${o}
|
|
3
3
|
`,n+=`${o}
|
|
4
|
-
`,this.extractedResult=r)}catch{if(o.includes('"text"')||o.includes('"content"')){let i=o.match(/"text"\s*:\s*"([^"]*)/),a=o.match(/"content"\s*:\s*"([^"]*)/),c=i?i[1]:a?a[1]:null;c&&!this.rawText.includes(c)&&(n+=c,this.rawText+=c)}}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=(i,a)=>{if(!i)return;let c=`${i}:${JSON.stringify(a??{})}`;this._lastToolEmit!==c&&(this._lastToolEmit=c,this.onToolCall(i,a??void 0))},n=i=>{if(i!=null){if(typeof i=="object"&&!Array.isArray(i))return i;if(typeof i=="string")try{return JSON.parse(i)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,n(e.input??e.arguments));return}let i=e.tool_call;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=Object.keys(i);if(a.length===1){let c=a[0],d=i[c],u=d&&typeof d=="object"?d.args??d.input??d:void 0;t(c,n(u))}return}return}if(Array.isArray(e.tool_calls)){for(let i of e.tool_calls)t(i.name,n(i.input??i.arguments));return}let o=e.message??e;if(Array.isArray(o?.tool_calls)){for(let i of o.tool_calls)t(i.name,n(i.input??i.arguments));return}let r=o?.content??e.content;if(Array.isArray(r))for(let i of r)(i.type==="tool_use"||i.type==="tool_call")&&i.name&&t(i.name,n(i.input??i.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,o;for(;(o=n.exec(e))!==null;){let h=o[1].trim();try{JSON.parse(h),t.push({text:h,source:"markdown"})}catch{}}let r=0,i=0;for(;r<e.length&&(r=e.indexOf("{",r),r!==-1);){let h=0,m=r;for(let y=r;y<e.length;y++)if(e[y]==="{")h++;else if(e[y]==="}"&&(h--,h===0)){m=y,t.push({text:e.substring(r,m+1),source:"brace"}),i++;break}r=m+1}let a=this.extractedResult,c=a?JSON.stringify(a).length:0,d=0,u=-1;for(let h=0;h<t.length;h++){let m=t[h];try{let y=m.text.replace(/,(\s*[}\]])/g,"$1"),
|
|
4
|
+
`,this.extractedResult=r)}catch{if(o.includes('"text"')||o.includes('"content"')){let i=o.match(/"text"\s*:\s*"([^"]*)/),a=o.match(/"content"\s*:\s*"([^"]*)/),c=i?i[1]:a?a[1]:null;c&&!this.rawText.includes(c)&&(n+=c,this.rawText+=c)}}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=(i,a)=>{if(!i)return;let c=`${i}:${JSON.stringify(a??{})}`;this._lastToolEmit!==c&&(this._lastToolEmit=c,this.onToolCall(i,a??void 0))},n=i=>{if(i!=null){if(typeof i=="object"&&!Array.isArray(i))return i;if(typeof i=="string")try{return JSON.parse(i)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,n(e.input??e.arguments));return}let i=e.tool_call;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=Object.keys(i);if(a.length===1){let c=a[0],d=i[c],u=d&&typeof d=="object"?d.args??d.input??d:void 0;t(c,n(u))}return}return}if(Array.isArray(e.tool_calls)){for(let i of e.tool_calls)t(i.name,n(i.input??i.arguments));return}let o=e.message??e;if(Array.isArray(o?.tool_calls)){for(let i of o.tool_calls)t(i.name,n(i.input??i.arguments));return}let r=o?.content??e.content;if(Array.isArray(r))for(let i of r)(i.type==="tool_use"||i.type==="tool_call")&&i.name&&t(i.name,n(i.input??i.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,o;for(;(o=n.exec(e))!==null;){let h=o[1].trim();try{JSON.parse(h),t.push({text:h,source:"markdown"})}catch{}}let r=0,i=0;for(;r<e.length&&(r=e.indexOf("{",r),r!==-1);){let h=0,m=r;for(let y=r;y<e.length;y++)if(e[y]==="{")h++;else if(e[y]==="}"&&(h--,h===0)){m=y,t.push({text:e.substring(r,m+1),source:"brace"}),i++;break}r=m+1}let a=this.extractedResult,c=a?JSON.stringify(a).length:0,d=0,u=-1;for(let h=0;h<t.length;h++){let m=t[h];try{let y=m.text.replace(/,(\s*[}\]])/g,"$1"),b=JSON.parse(y);this.isValidResult(b)&&(d++,c=JSON.stringify(b).length,a=b,u=h)}catch{}}a&&(this.extractedResult=a)}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 s;n.zodSchema=t,n.processChunk(e),n.flush();let o=n.getResult();return!o&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),o}};import{z as ze}from"zod";import{zodToJsonSchema as At}from"zod-to-json-schema";function Tt(s){if(!s)return null;if(typeof ze?.toJSONSchema=="function")try{return ze.toJSONSchema(s)}catch{}try{return At(s,{target:"openApi3"})}catch{return null}}var Se=class{static generateFileOutputInstructions(e,t){let n;typeof e?.parse=="function"?n=Tt(e):n=e;let o=this._buildExample(n);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
|
|
@@ -31,18 +31,18 @@ ${e.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:t,p
|
|
|
31
31
|
|
|
32
32
|
`),position:"append"}),this}addSystemInstruction(e,t="custom",n="append"){return e&&this.systemInstructions.push({type:t,content:e,position:n}),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 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 s(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};import
|
|
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(n=>n.type)}}clone(){let e=new s(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};import vt from"axios";import{homedir as wt}from"node:os";import{join as It}from"node:path";import{existsSync as xt,readFileSync as $t}from"node:fs";import{toJSONSchema as Ct}from"zod";function kt(){if(process.env.OPENAI_PROXY_TOKEN)return l.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return l.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let s=It(wt(),".zibby","config.json");if(xt(s)){let e=JSON.parse($t(s,"utf-8"));if(e.sessionToken)return l.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(s){l.debug(`[Auth] Could not read zibby login session: ${s.message}`)}return null}function Pt(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function te(s){if(!(typeof s!="object"||s===null)){if(Object.keys(s).length===0){s.type="object",s.additionalProperties=!0;return}if(s.type||(s.properties?s.type="object":s.items&&(s.type="array")),s.type==="object")if(s.properties){for(let[e,t]of Object.entries(s.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(s.properties[e]={type:["object","null"]});s.additionalProperties=!1,s.required=Object.keys(s.properties),Object.values(s.properties).forEach(te)}else"additionalProperties"in s||(s.additionalProperties=!0);s.type==="array"&&s.items&&te(s.items),s.anyOf&&s.anyOf.forEach(te),s.oneOf&&s.oneOf.forEach(te),s.allOf&&s.allOf.forEach(te)}}async function He(s,e){l.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=kt();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 n=Pt();l.info(`\u{1F517} Using OpenAI proxy: ${n}`);let o=Ct(e),r=o;if(o.$ref&&o.definitions){let u=o.$ref.split("/").pop();r=o.definitions[u]||o,l.debug(`Extracted schema from $ref: ${u}`)}delete r.$schema,te(r);let i=4e5,a=s;s.length>i&&(l.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${s.length} chars) exceeds limit, keeping last ${i} chars`),a=`... [truncated early content] ...
|
|
35
35
|
${s.slice(-i)}`);let c=`Extract and format the following information into structured JSON matching the schema.
|
|
36
36
|
|
|
37
37
|
RAW CONTENT:
|
|
38
38
|
${a}
|
|
39
39
|
|
|
40
|
-
Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,d={model:j.OPENAI_POSTPROCESSING,messages:[{role:"user",content:c}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:r,strict:!0}}};l.info(`\u{1F4E4} Sending to OpenAI proxy: model=${j.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(r.properties||{}).join(", ")}`),l.debug(` Schema size: ${JSON.stringify(r).length} chars`),l.debug(` Prompt size: ${c.length} chars`);try{let u={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(u["x-proxy-token"]=t,u["x-execution-id"]=process.env.EXECUTION_ID||""):(u.Authorization=`Bearer ${t}`,u["x-api-key"]=process.env.ZIBBY_API_KEY||"",u["x-execution-id"]=process.env.EXECUTION_ID||"");let m=(await
|
|
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.`,d={model:j.OPENAI_POSTPROCESSING,messages:[{role:"user",content:c}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:r,strict:!0}}};l.info(`\u{1F4E4} Sending to OpenAI proxy: model=${j.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(r.properties||{}).join(", ")}`),l.debug(` Schema size: ${JSON.stringify(r).length} chars`),l.debug(` Prompt size: ${c.length} chars`);try{let u={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(u["x-proxy-token"]=t,u["x-execution-id"]=process.env.EXECUTION_ID||""):(u.Authorization=`Bearer ${t}`,u["x-api-key"]=process.env.ZIBBY_API_KEY||"",u["x-execution-id"]=process.env.EXECUTION_ID||"");let m=(await vt.post(n,d,{headers:u,timeout:_e.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!m)throw new Error("OpenAI proxy returned empty response");let y=JSON.parse(m);return l.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:y,raw:s}}catch(u){if(u.response){let h=u.response.status,m=u.response.data;throw l.error(`\u274C OpenAI proxy request failed: ${h}`),l.error(` Status: ${h}`),l.error(` Response: ${JSON.stringify(m,null,2)}`),h===401||h===403?new Error(`Authentication failed for OpenAI proxy.
|
|
41
41
|
Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
|
|
42
|
-
Response: ${JSON.stringify(m)}`,{cause:u}):new Error(`Failed to format Cursor output: ${m?.error?.message||"Unknown error"}`,{cause:u})}throw l.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}function F(s){let e=`${s}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let n=t.split(/[,\n]+/).map(i=>i.trim()).filter(Boolean);if(n.length===0)return{picked:null,count:0,dispose:()=>{}};let o=n[Math.floor(Math.random()*n.length)],r=process.env[s];return process.env[s]=o,l.debug(`[auth-pool] ${s}: picked 1 of ${n.length} from pool (***${o.slice(-4)})`),{picked:o,count:n.length,dispose(){r===void 0?delete process.env[s]:process.env[s]=r}}}import{timeline as H,Timeline as
|
|
42
|
+
Response: ${JSON.stringify(m)}`,{cause:u}):new Error(`Failed to format Cursor output: ${m?.error?.message||"Unknown error"}`,{cause:u})}throw l.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}function F(s){let e=`${s}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let n=t.split(/[,\n]+/).map(i=>i.trim()).filter(Boolean);if(n.length===0)return{picked:null,count:0,dispose:()=>{}};let o=n[Math.floor(Math.random()*n.length)],r=process.env[s];return process.env[s]=o,l.debug(`[auth-pool] ${s}: picked 1 of ${n.length} from pool (***${o.slice(-4)})`),{picked:o,count:n.length,dispose(){r===void 0?delete process.env[s]:process.env[s]=r}}}import{timeline as H,Timeline as nn,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as rn}from"@zibby/agent-workflow";import{copyFileSync as Nt,existsSync as Le,lstatSync as Rt,mkdirSync as Ve,rmSync as Mt,symlinkSync as Lt,unlinkSync as Dt}from"node:fs";import{join as V}from"node:path";import{homedir as Ut}from"node:os";import{randomBytes as Kt}from"node:crypto";var Bt=["cli-config.json","config.json","auth.json","argv.json"];function We(s){return!(!s||typeof s!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function Xe(s){let e=V(s||process.cwd(),".zibby","tmp");Ve(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${Kt(4).toString("hex")}`,n=V(e,`cursor-agent-home-${t}`),o=V(n,".cursor");Ve(o,{recursive:!0});let r=Ut(),i=V(r,".cursor");if(Le(i))for(let a of Bt){let c=V(i,a);if(Le(c))try{Nt(c,V(o,a))}catch{}}if(process.platform==="darwin"){let a=V(r,"Library");if(Le(a))try{Lt(a,V(n,"Library"))}catch{}}return n}function Ze(s){if(!(!s||typeof s!="string"))try{let e=V(s,"Library");try{Rt(e).isSymbolicLink()&&Dt(e)}catch{}Mt(s,{recursive:!0,force:!0})}catch{}}var Oe=class extends Gt{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[Y(de(),".local","bin","cursor-agent"),Y(de(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"];for(let n of t)try{if(n.startsWith("/")){ot(n,nt.X_OK);let o=X(`"${n}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(o&&o.length>0)return l.debug(`[Cursor] Found agent at: ${n} (version: ${o.trim().slice(0,50)})`),!0}else{let o=X(`which ${n}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!o)continue;let r=X(`${n} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(r&&r.length>0)return l.debug(`[Cursor] Found '${n}' in PATH at ${o} (version: ${r.trim().slice(0,50)})`),!0}}catch{continue}return l.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:n=process.cwd(),print:o=!1,schema:r=null,skills:i=null,sessionPath:a=null,nodeName:c=null,timeout:d=_e.CURSOR_AGENT_DEFAULT,config:u={},signal:h=null}=t,m=u?.agent?.strictMode||!1,y=t.model??u?.agent?.cursor?.model??j.CURSOR,b=F("CURSOR_API_KEY");try{l.debug(`[Cursor] Invoking (model: ${y}, timeout: ${d/1e3}s, skills: ${JSON.stringify(i)})`);let _=(this._setupMcpConfig(a,n,u,i,c)||{}).isolatedMcpHome??null,O=[Y(de(),".local","bin","cursor-agent"),Y(de(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"],A=null;for(let v of O)try{if(v.startsWith("/"))ot(v,nt.X_OK),X(`"${v}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!X(`which ${v}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");X(`${v} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}A=v,l.debug(`[Agent] Using binary: ${v}`);break}catch(f){l.debug(`[Agent] Binary '${v}' check failed: ${f.message}`);continue}if(!A)throw new Error(`Cursor Agent CLI not found or not working.
|
|
43
43
|
|
|
44
44
|
Checked paths:
|
|
45
|
-
${
|
|
45
|
+
${O.map(v=>` - ${v}`).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
Install cursor-agent:
|
|
@@ -51,64 +51,64 @@ 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 L=new ee(e),g=null;if(r){let
|
|
55
|
-
\u25C6 Model: ${y||"auto"}${
|
|
54
|
+
Test with: agent --version`);let L=new ee(e),g=null;if(r){let v=`zibby-result-${Date.now()}.json`;g=Y(n,".zibby","tmp",v);let f=Y(n,".zibby","tmp");ue(f)||tt(f,{recursive:!0}),L.addStructuredOutput(r,g)}let K=process.env.CURSOR_API_KEY,B=K?` | key: ***${K.slice(-4)}`:" | key: not set";console.log(`
|
|
55
|
+
\u25C6 Model: ${y||"auto"}${B}
|
|
56
56
|
`);let M=(await import("chalk")).default,E=L.getUserPrompt();console.log(`
|
|
57
|
-
${M.bold("Prompt sent to LLM:")}`),console.log(M.dim("\u2500".repeat(60))),console.log(M.dim(E)),console.log(M.dim("\u2500".repeat(60)));let w=L.build(),N=L.getStats(),
|
|
58
|
-
`)}catch{}let C,k=null;try{let
|
|
57
|
+
${M.bold("Prompt sent to LLM:")}`),console.log(M.dim("\u2500".repeat(60))),console.log(M.dim(E)),console.log(M.dim("\u2500".repeat(60)));let w=L.build(),N=L.getStats(),T=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",y||"auto"];if(process.env.CURSOR_API_KEY&&T.push("--api-key",process.env.CURSOR_API_KEY),T.push(w),l.debug(`[Agent] User prompt: ${N.userPromptLength} chars, System instructions: ${N.systemInstructionsLength} chars (${N.instructionCount} blocks), Full: ${N.fullPromptLength} chars, model: ${y||"auto"}`),l.debug(`[Agent] Workspace: ${n}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${y||"auto"} (from .zibby.config.js agent.cursor.model)
|
|
58
|
+
`)}catch{}let C,k=null;try{let v=a||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);C=await this._spawnWithStreaming(A,T,n,d,null,v,_,h)}catch(v){k=v}let P=C?.stdout||"";if(r){let v=typeof r.parse=="function",f=null,R=!!(g&&ue(g));if(g&&l.info(`[Agent] Result file: ${R?"present":"missing"} at ${g}`),R)try{let S=et(g,"utf-8").trim();f=JSON.parse(S),l.info(`[Agent] Parsed JSON from result file OK (${S.length} chars) \u2192 object ready for validation`),k&&l.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(S){l.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${S.message}`)}else if(k)l.warn(`[Agent] Result file missing at ${g} (agent process error \u2014 may still recover if strictMode repairs)`);else throw l.error(`\u274C [Agent] Result file was never created at ${g}`),new Error(`Agent did not write required result file at ${g}`);if(f&&v)try{let S=r.parse(f);return l.info("\u2705 [Agent] Zod validation passed for structured result file"),m&&l.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:P,structured:S}}catch(S){let p=S.issues?S.issues.map($=>` - ${$.path.join(".")}: ${$.message}`).join(`
|
|
59
59
|
`):S.message?.slice(0,400);if(l.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
|
|
60
60
|
${p}`),l.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
|
|
61
61
|
${JSON.stringify(f,null,2).slice(0,500)}`),!m)throw new Error(`Agent output failed schema validation:
|
|
62
62
|
${p}
|
|
63
63
|
|
|
64
64
|
The agent wrote invalid data that doesn't match the required outputSchema.
|
|
65
|
-
Enable strictMode in .zibby.config.js for automatic repair.`,{cause:S})}else{if(f)return l.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),m&&l.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:P,structured:f};R&&l.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(m&&!k){let S=C.parsedText,p=f?JSON.stringify(f):S;l.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${p.length} chars in)`);try{let $=await He(p,r);if(
|
|
66
|
-
`),n=null;for(let o of t){let r=o.trim();if(r)try{let i=JSON.parse(r);if(i.type==="assistant"&&i.message?.content){let a=i.message.content;if(Array.isArray(a)){let c=a.filter(d=>d.type==="text"&&d.text).map(d=>d.text).join("");c&&(n=c)}else typeof a=="string"&&a&&(n=a)}}catch{}}return n?.trim()||null}_setupMcpConfig(e,t,n,o=null,r=null){let i=n?.headless,a=Y(de(),".cursor"),c=Y(a,"mcp.json"),d={};if(ue(c))try{d=JSON.parse(et(c,"utf-8"))}catch{}let u=d.mcpServers||{},h=n?.paths?.output||
|
|
67
|
-
`;if(
|
|
68
|
-
`)){let x=I.replace(`${n}/`,"");C.has(x)||(C.add(x),U.push(x))}}catch{}let S="";U.length>0&&(S=` | \u{1F4C1} new: ${U.map($=>$.split("/").pop()).join(", ")}`),C.size>0&&(S+=` | \u{1F4E6} total: ${C.size} files`),l.debug(`\u{1F493} [Agent] Running for ${f}s | ${D} lines output${S}`),D===0&&f>=30&&C.size===0&&(f<35&&l.warn(`\u26A0\uFE0F [Agent] No output after ${f}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),f>=60&&(_=!0,
|
|
69
|
-
${m.slice(-2e3)}`),E.kill("SIGTERM"),setTimeout(()=>{E.killed||E.kill("SIGKILL")},5e3)},o),
|
|
70
|
-
`).filter(p=>p.trim());D+=S.length}),E.stderr.on("data",f=>{let R=f.toString();y+=R,
|
|
71
|
-
`).filter(S=>S.trim());for(let S of U)l.warn(`\u26A0\uFE0F [Agent stderr] ${S}`)}),E.on("close",(f,R)=>{if(L=!0,
|
|
65
|
+
Enable strictMode in .zibby.config.js for automatic repair.`,{cause:S})}else{if(f)return l.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),m&&l.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:P,structured:f};R&&l.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(m&&!k){let S=C.parsedText,p=f?JSON.stringify(f):S;l.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${p.length} chars in)`);try{let $=await He(p,r);if(v){let I=r.parse($.structured);return l.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:P,structured:I}}return{raw:P,...$}}catch($){if(l.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${$.message}`),f)return l.warn("[Agent] Using agent's original result file as fallback"),{raw:P,structured:f}}}if(k)throw k;let U=R?f==null?"file existed but JSON.parse failed \u2014 see WARN log above":v?"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 l.error(`\u274C [Agent] No validated structured output: ${U}`),l.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 ${g}. Enable strictMode for proxy fallback.`)}if(k)throw k;return this._extractFinalResult(P)||C?.parsedText||P}finally{b.dispose()}}_extractFinalResult(e){if(!e)return null;let t=e.split(`
|
|
66
|
+
`),n=null;for(let o of t){let r=o.trim();if(r)try{let i=JSON.parse(r);if(i.type==="assistant"&&i.message?.content){let a=i.message.content;if(Array.isArray(a)){let c=a.filter(d=>d.type==="text"&&d.text).map(d=>d.text).join("");c&&(n=c)}else typeof a=="string"&&a&&(n=a)}}catch{}}return n?.trim()||null}_setupMcpConfig(e,t,n,o=null,r=null){let i=n?.headless,a=Y(de(),".cursor"),c=Y(a,"mcp.json"),d={};if(ue(c))try{d=JSON.parse(et(c,"utf-8"))}catch{}let u=d.mcpServers||{},h=n?.paths?.output||Jt,m=Y(t||process.cwd(),h,jt),y=Array.isArray(o)?o.map(_=>qe(_)).filter(Boolean):[...Yt()].map(([,_])=>_),b=new Set;for(let _ of y)typeof _.resolve=="function"&&(b.has(_.serverName)||(b.add(_.serverName),this._ensureSkillConfigured(u,_,e,m,r,i)));if(e){let _=qe("browser");_&&typeof _.resolve=="function"&&!b.has(_.serverName)&&this._ensureSkillConfigured(u,_,e,m,"execute_live",i)}if(Object.keys(u).length===0)return l.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let D=`${JSON.stringify({mcpServers:u},null,2)}
|
|
67
|
+
`;if(We(e)){let _=Xe(t||process.cwd()),O=Y(_,".cursor","mcp.json");return Qe(O,D,"utf8"),l.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${_} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:_}}return ue(a)||tt(a,{recursive:!0}),Qe(c,D,"utf8"),l.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,n,o,r=null,i){let a=t.cursorKey||t.serverName,c=e[a]?a:e[t.serverName]?t.serverName:null;if(c&&n){let u=typeof t.resolve=="function"?t.resolve({sessionPath:n,nodeName:r,headless:i}):null;u?.args?e[c].args=u.args:e[c].args=(e[c].args||[]).map(y=>y.startsWith("--output-dir=")?`--output-dir=${n}`:y);let h=u?.env||{},m=t.sessionEnvKey?{[t.sessionEnvKey]:o}:{};e[c].env={...e[c].env||{},...h,...m},l.debug(`[MCP] Updated ${c} session \u2192 ${n}`);return}if(c)return;let d=t.resolve({sessionPath:n,nodeName:r,headless:i});d&&(e[a]={...d,...t.sessionEnvKey&&{env:{...d.env||{},[t.sessionEnvKey]:o}}},l.debug(`[MCP] Configured ${a}`))}_spawnWithStreaming(e,t,n,o,r=null,i=null,a=null,c=null){return new Promise((d,u)=>{let h=Date.now(),m="",y="",b=Date.now(),D=0,_=!1,O=null,A=!1,L=!1,g=null;if(i)try{g=Y(Vt(String(i)),Ft)}catch{g=null}let K=!1,B=()=>{K||(K=!0,Ze(a))},M={...process.env};a&&(M.HOME=a,process.platform==="win32"&&(M.USERPROFILE=a),l.debug(`[Agent] cursor-agent HOME=${a} (isolated MCP config)`));let E=zt(e,t,{cwd:n,shell:!1,stdio:["pipe","pipe","pipe"],env:M,...c&&{signal:c}});l.debug(`[Agent] PID: ${E.pid}`);let w=null,N=()=>{_||L||(_=!0,O="aborted",l.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),w=setTimeout(()=>{if(!L){l.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",f=>{f.code!=="EPIPE"&&l.warn(`[Agent] stdin error: ${f.message}`)}),E.stdout.on("error",f=>{f.code!=="EPIPE"&&l.warn(`[Agent] stdout error: ${f.message}`)}),E.stderr.on("error",f=>{f.code!=="EPIPE"&&l.warn(`[Agent] stderr error: ${f.message}`)}),r?(E.stdin.write(r,f=>{f&&f.code!=="EPIPE"&&l.warn(`[Agent] Failed to write to stdin: ${f.message}`),E.stdin.end()}),l.debug(`[Agent] Prompt also piped to stdin (${r.length} chars)`)):E.stdin.end();let T=null;g&&(T=setInterval(()=>{if(!(_||L))try{if(ue(g)){_=!0,O="aborted";try{Ht(g)}catch{}l.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 C=new Set,k=new Date(h).toISOString().replace(/\.\d+Z$/,""),P=setInterval(()=>{let f=Math.round((Date.now()-h)/1e3),R=Math.round((Date.now()-b)/1e3),U=[];try{let p=Math.ceil(f/60)+1,$=X(`find "${n}" -type f -mmin -${p} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if($)for(let I of $.split(`
|
|
68
|
+
`)){let x=I.replace(`${n}/`,"");C.has(x)||(C.add(x),U.push(x))}}catch{}let S="";U.length>0&&(S=` | \u{1F4C1} new: ${U.map($=>$.split("/").pop()).join(", ")}`),C.size>0&&(S+=` | \u{1F4E6} total: ${C.size} files`),l.debug(`\u{1F493} [Agent] Running for ${f}s | ${D} lines output${S}`),D===0&&f>=30&&C.size===0&&(f<35&&l.warn(`\u26A0\uFE0F [Agent] No output after ${f}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),f>=60&&(_=!0,O=O||"stall",l.error(`\u274C [Agent] No response after ${f}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),J=setTimeout(()=>{_=!0,O=O||"timeout";let f=Math.round((Date.now()-h)/1e3);l.error(`\u23F1\uFE0F [Agent] Timeout after ${f}s \u2014 killing process (PID: ${E.pid})`),m.trim()&&l.warn(`\u{1F4E4} [Agent] Partial output (${m.length} chars) before timeout:
|
|
69
|
+
${m.slice(-2e3)}`),E.kill("SIGTERM"),setTimeout(()=>{E.killed||E.kill("SIGKILL")},5e3)},o),v=new Q;v.onToolCall=(f,R)=>{let U=f,S=R;if(f==="mcpToolCall"&&R?.name)U=R.name.replace(/^mcp_+[^_]+_+/,""),U.includes("-")&&U.split("-")[0]===U.split("-")[1]&&(U=U.split("-")[0]),S=R.args??R.input??R;else{if(f==="readToolCall"||f==="editToolCall"||f==="writeToolCall")return;(f.startsWith("mcp__")||f.includes("ToolCall"))&&(U=f.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(U.includes("memory")?H.stepMemory(`Tool: ${U}`):H.stepTool(`Tool: ${U}`),S!=null&&typeof S=="object"&&Object.keys(S).length>0&&!L){let $=JSON.stringify(S),I=$.length>100?`${$.substring(0,100)}...`:$;console.log(` Input: ${I}`)}},E.stdout.on("data",f=>{let R=f.toString();m+=R,b=Date.now(),A||(A=!0);let U=v.processChunk(R);U&&!L&&process.stdout.write(U);let S=R.split(`
|
|
70
|
+
`).filter(p=>p.trim());D+=S.length}),E.stderr.on("data",f=>{let R=f.toString();y+=R,b=Date.now(),A||(A=!0);let U=R.split(`
|
|
71
|
+
`).filter(S=>S.trim());for(let S of U)l.warn(`\u26A0\uFE0F [Agent stderr] ${S}`)}),E.on("close",(f,R)=>{if(L=!0,B(),clearTimeout(J),clearInterval(P),T&&clearInterval(T),w&&clearTimeout(w),c&&!c.aborted)try{c.removeEventListener("abort",N)}catch{}v.flush();let U=Math.round((Date.now()-h)/1e3);if(l.debug(`[Agent] Exited: code=${f}, signal=${R}, elapsed=${U}s, output=${m.length} chars`),_){if(O==="aborted"){let $=new Error("Aborted via signal");$.name="AbortError",u($);return}u(new Error(`Cursor Agent timed out after ${U}s (limit: ${o/1e3}s). ${D} lines produced. Last output ${Math.round((Date.now()-b)/1e3)}s ago. ${m.trim()?`
|
|
72
72
|
Partial output (last 500 chars):
|
|
73
73
|
${m.slice(-500)}`:"No output captured."}`));return}if(f!==0){u(new Error(`Cursor Agent failed: exit code ${f}, signal ${c}. ${y.trim()?`
|
|
74
74
|
Stderr: ${y.slice(-1e3)}`:""}${m.trim()?`
|
|
75
|
-
Stdout (last 500 chars): ${m.slice(-500)}`:""}`));return}let S=
|
|
75
|
+
Stdout (last 500 chars): ${m.slice(-500)}`:""}`));return}let S=v.getResult(),p=S?JSON.stringify(S,null,2):v.getRawText()||m||"";d({stdout:m||y||"",parsedText:p})}),E.on("error",f=>{if(B(),clearTimeout(J),clearInterval(P),T&&clearInterval(T),w&&clearTimeout(w),c&&!c.aborted)try{c.removeEventListener("abort",N)}catch{}u(new Error(`Cursor Agent spawn error: ${f.message}
|
|
76
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`))})})}};fe();import{AgentStrategy as
|
|
78
|
+
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};fe();import{AgentStrategy as Xt,getSkill as Zt,NO_INTEGRATION_TOGGLEABLE_SKILL_IDS as qt}from"@zibby/agent-workflow";import{query as Qt}from"@anthropic-ai/claude-agent-sdk";import{writeFileSync as De,mkdirSync as Ue,existsSync as it,readFileSync as lt}from"fs";import{homedir as at}from"os";import{join as oe}from"path";var be=class extends Xt{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!process.env.ANTHROPIC_API_KEY||!!process.env.ANTHROPIC_API_KEY_POOL,n=!!process.env.CLAUDE_CODE_OAUTH_TOKEN||!!process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,o=!!process.env.ANTHROPIC_AUTH_TOKEN||!!process.env.ANTHROPIC_AUTH_TOKEN_POOL,r=t||n||o;return r||l.debug("ClaudeAgentStrategy: no credentials. Set one of ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_AUTH_TOKEN (or a *_POOL variant for multi-token rotation)."),r}async invoke(e,t={}){let{model:n,workspace:o=process.cwd(),schema:r=null,images:i=[],skills:a=null,sessionPath:c=null,nodeName:d=null,timeout:u,config:h={},signal:m=null,sessionId:y,resume:b,forkSession:D,sessionStore:_}=t,O=n;(!O||O==="auto")&&(l.debug(`Model is '${O||"undefined"}', using default: ${j.CLAUDE}`),O=j.CLAUDE);let A=Re[O]||O;Re[O]&&O!==A&&l.debug(`Mapped model: ${O} \u2192 ${A}`);let L=[F("ANTHROPIC_API_KEY"),F("CLAUDE_CODE_OAUTH_TOKEN"),F("ANTHROPIC_AUTH_TOKEN")];try{l.debug(`Invoking Claude Agent SDK with model: ${A}, skills: ${JSON.stringify(a)}`);let g=process.env.CLAUDE_CODE_OAUTH_TOKEN,K=process.env.ANTHROPIC_API_KEY,B=process.env.ANTHROPIC_AUTH_TOKEN;process.env.CLAUDE_CODE_CREDENTIALS_JSON?oo(process.env.CLAUDE_CODE_CREDENTIALS_JSON):g&&to(g,process.env.__ZIBBY_CLAUDE_PLAN);let M=process.env.__ZIBBY_CLAUDE_PLAN,E=M?M.charAt(0).toUpperCase()+M.slice(1):null,w;g?w=E?`Claude ${E} plan \xB7 ***${g.slice(-4)}`:`Subscription \xB7 ***${g.slice(-4)}`:K?w=`API key \xB7 ***${K.slice(-4)}`:B?w=`Bearer \xB7 ***${B.slice(-4)}`:w="NONE \u2014 request will fail";let N=(await import("chalk")).default;console.log(""),console.log(` ${N.cyan("\u25C6")} ${N.bold(A)}`),console.log(` ${N.dim("Auth: ")}${w}`),console.log(` ${N.dim("Workdir: ")}${o}`),console.log(""),console.log(N.bold("Prompt sent to LLM:")),console.log(N.dim("\u2500".repeat(60))),console.log(N.dim(e)),console.log(N.dim("\u2500".repeat(60)));let{allowedTools:T,mcpServers:C}=this._resolveSkills(a,{sessionPath:c,workspace:o,nodeName:d});try{let k={cwd:o,allowedTools:T,settings:{permissions:{allow:["Bash(*)","Read(*)","Write(*)","Edit(*)","MultiEdit(*)","NotebookEdit(*)","Grep(*)","Glob(*)","WebFetch(*)","WebSearch(*)","Task(*)","TodoWrite(*)","Skill(*)"]}},model:A,...Object.keys(C).length>0&&{mcpServers:C},...y&&{sessionId:y},...b&&{resume:b},...D&&{forkSession:!0},..._&&{sessionStore:_}};if(r){let $=typeof r.parse=="function"?Z(r):r;k.outputFormat={type:"json_schema",schema:$},l.debug("Structured output enforced via SDK outputFormat")}l.debug(`Agent SDK options: ${JSON.stringify({cwd:k.cwd,toolCount:T.length,permissionMode:k.permissionMode,model:k.model,hasOutputFormat:!!k.outputFormat})}`);let P="",J=0,v=[];l.debug("Starting Claude Agent SDK query stream");let f;try{f=Qt({prompt:e,options:k})}catch(p){throw l.error(`Failed to initialize Claude Agent SDK: ${p.message}`),p}let R=null,U=0,S=3;if(m?.aborted){let p=new Error("Aborted via signal");throw p.name="AbortError",p}try{for await(let p of f){if(m?.aborted){let I=new Error("Aborted via signal");throw I.name="AbortError",I}if(v.push(p),p.type==="system"&&p.subtype==="init"){let I=p.mcp_servers||[];if(I.length>0){let x=I.map(G=>`${G.name}=${G.status}${G.error?` (${String(G.error).slice(0,120)})`:""}`).join(", ");l.info(`[mcp] SDK init \u2014 ${I.length} server(s): ${x}`);for(let G of I)G.status!=="connected"&&l.warn(`[mcp] server '${G.name}' did not connect: status=${G.status}`,{name:G.name,status:G.status,error:G.error})}else Object.keys(C||{}).length>0&&l.warn(`[mcp] SDK init returned no mcp_servers despite passing ${Object.keys(C).length} server(s) \u2014 SDK version may not expose this field, or config was dropped`);if(Array.isArray(p.tools)){let x=p.tools.filter(G=>G.startsWith("mcp__"));x.length>0?l.info(`[mcp] tools visible to model: ${x.join(", ")}`):Object.keys(C||{}).length>0&&l.warn("[mcp] no mcp__* tools in model's tool list \u2014 MCP servers configured but tools didn't reach the prompt")}}if(p.type==="error"||p.error){let I=p.error?.message||p.error||p.message||"Unknown API error";try{l.error("SDK error event raw payload",{fullMessage:JSON.stringify(p,null,2)})}catch{}throw new Error(typeof I=="string"?I:JSON.stringify(I))}let $=JSON.stringify(p.message?.content||p.text||"").slice(0,200);if($===R){if(U++,U>=S){let I=(p.message?.content?.[0]?.text||p.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${U}x repeated): ${I}`)}}else R=$,U=1;if(p.type==="assistant"||p.constructor?.name==="AssistantMessage"){let I=p.message?.content||p.content||[];for(let x of I)if(x.type==="thinking"&&x.thinking)console.log(`${x.thinking.substring(0,200)}${x.thinking.length>200?"...":""}`);else if(x.type==="text"&&x.text)P+=x.text,x.text.length<500?console.log(`${x.text}`):console.log(`${x.text.substring(0,200)}... (${x.text.length} chars)`);else if(x.type==="tool_use"){J++,x.name.includes("memory")?H.stepMemory(`Tool: ${x.name}`):H.stepTool(`Tool: ${x.name}`);let le=JSON.stringify(x.input).substring(0,100);console.log(` Input: ${le}${JSON.stringify(x.input).length>100?"...":""}`)}}else if(!(p.type==="user"&&p.tool_use_result)){if(p.type==="result"||p.constructor?.name==="ResultMessage"){let I=p.result||p.text||p.content||P;try{eo({message:p,sessionPath:c,nodeName:d,model:O,toolCallCount:J})}catch(x){l.debug(`usage.json write failed: ${x.message}`)}if(r){if(p.structured_output){l.debug("Using SDK native structured_output");let G=typeof r.parse=="function"?r.parse(p.structured_output):p.structured_output;return{raw:I,structured:G}}if(I){let x=this._extractJson(I,r);if(x)return{raw:I,structured:x}}l.warn(`Could not extract structured output \u2014 returning raw text (${(I||"").length} chars)`)}return I||""}}}if(l.warn(`Agent SDK ended without result. Collected ${v.length} messages`),P.length>0)return l.debug("Returning accumulated text from messages"),P;throw new Error("Claude Agent SDK query ended without result")}catch(p){let $={message:p?.message,name:p?.name,code:p?.code,cause:p?.cause?.message||p?.cause,stack:p?.stack?.split(`
|
|
79
79
|
`).slice(0,5).join(`
|
|
80
|
-
`),stringified:(()=>{try{return JSON.stringify(p,Object.getOwnPropertyNames(Object(p)))}catch{return String(p)}})()};throw l.error(`Error during query stream: ${p?.message||p}`,$),p}}catch(k){throw l.error("Claude Agent SDK call failed",{message:k?.message,name:k?.name,code:k?.code,cause:k?.cause?.message||k?.cause}),k}}finally{for(let g of L)g.dispose()}}_resolveSkills(e,t){let n=["Read","Write","Edit","Bash","Grep","Glob"];if(e===null)return l.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return l.debug("Default IDE skills for code generation"),{allowedTools:[...n],mcpServers:{}};let o=[...n],r={};for(let
|
|
81
|
-
\u25C6 Model: ${D}${
|
|
80
|
+
`),stringified:(()=>{try{return JSON.stringify(p,Object.getOwnPropertyNames(Object(p)))}catch{return String(p)}})()};throw l.error(`Error during query stream: ${p?.message||p}`,$),p}}catch(k){throw l.error("Claude Agent SDK call failed",{message:k?.message,name:k?.name,code:k?.code,cause:k?.cause?.message||k?.cause}),k}}finally{for(let g of L)g.dispose()}}_resolveSkills(e,t){let n=["Read","Write","Edit","Bash","Grep","Glob"];if(e===null)return l.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return l.debug("Default IDE skills for code generation"),{allowedTools:[...n],mcpServers:{}};let o=[...n],r={},i=process.env.WORKFLOW_ENABLED_INTEGRATIONS,a=typeof i=="string"&&i.trim()!==""?new Set(i.split(",").map(d=>d.trim()).filter(Boolean)):null,c=d=>a!==null&&a.size>0&&qt.includes(d)&&!a.has(d);for(let d of e){if(c(d)){l.debug(`Skill "${d}" disabled by enabledIntegrations allowlist \u2014 skipping`);continue}let u=Zt(d);if(!u){l.warn(`Unknown skill "${d}" \u2014 skipping`);continue}if(u.allowedTools&&o.push(...u.allowedTools),typeof u.resolve=="function"){let h=u.resolve(t);h&&(r[u.serverName]=h,l.debug(`MCP: ${u.serverName} \u2192 ${h.command} ${h.args[0]}`))}}return{allowedTools:o,mcpServers:r}}_extractJson(e,t){let n=[()=>{if(e.includes("===JSON_START===")){let o=e.indexOf("===JSON_START===")+16,r=e.indexOf("===JSON_END===");return e.substring(o,r).trim()}},()=>e.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!e.startsWith("{"))return e.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>e.trim(),()=>{let o=e.indexOf("{"),r=e.lastIndexOf("}");if(o!==-1&&r>o)return e.substring(o,r+1)}];for(let o of n)try{let r=o();if(!r)continue;let i=JSON.parse(r);if(typeof i!="object"||i===null)continue;return typeof t.parse=="function"?t.parse(i):i}catch{}return null}};function eo({message:s,sessionPath:e,nodeName:t,model:n,toolCallCount:o}){if(!e||!t)return;let r=s?.usage||s?.message?.usage||{},i=pe(r.input_tokens,r.inputTokens),a=pe(r.output_tokens,r.outputTokens),c=pe(r.cache_read_input_tokens,r.cacheReadInputTokens),d=pe(r.cache_creation_input_tokens,r.cacheCreationInputTokens),u=pe(s?.duration_ms,s?.durationMs),h={model:n||null,input_tokens:i,output_tokens:a,cache_read_tokens:c,cache_creation_tokens:d,tool_call_count:typeof o=="number"?o:null,duration_ms:u,captured_at:new Date().toISOString()},m=oe(e,t);try{Ue(m,{recursive:!0})}catch{}De(oe(m,"usage.json"),JSON.stringify(h,null,2),"utf-8")}function pe(...s){for(let e of s){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e)))return Number(e)}return null}function to(s,e){let t=oe(at(),".claude"),n=oe(t,".credentials.json"),o={claudeAiOauth:{accessToken:s,...e?{subscriptionType:String(e).toLowerCase()}:{}}};try{if(it(n)&&JSON.parse(lt(n,"utf-8"))?.claudeAiOauth?.accessToken===s)return;Ue(t,{recursive:!0}),De(n,JSON.stringify(o,null,2),"utf-8"),l.debug(`Wrote Claude Code OAuth credentials to ${n}`)}catch(r){l.warn(`Could not write ${n}: ${r.message} \u2014 Claude SDK may fail to authenticate.`)}}function oo(s){let e=oe(at(),".claude"),t=oe(e,".credentials.json"),n;try{n=JSON.parse(s)}catch(o){l.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${o.message}`);return}if(!n?.claudeAiOauth?.accessToken){l.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if(it(t)){let o=JSON.parse(lt(t,"utf-8"));if(o?.claudeAiOauth?.accessToken===n.claudeAiOauth.accessToken&&o?.claudeAiOauth?.expiresAt===n.claudeAiOauth.expiresAt)return}Ue(e,{recursive:!0}),De(t,JSON.stringify(n,null,2),"utf-8"),l.debug(`Wrote full Claude Code credentials blob to ${t}`)}catch(o){l.warn(`Could not write ${t}: ${o.message} \u2014 Claude SDK may fail to authenticate.`)}}fe();import{AgentStrategy as no,getSkill as ro}from"@zibby/agent-workflow";import{execSync as so}from"node:child_process";var Ee=class extends no{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY_POOL||process.env.CODEX_API_KEY||process.env.CODEX_API_KEY_POOL))return l.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return so("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return l.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:n,workspace:o=process.cwd(),schema:r=null,skills:i=null,sessionPath:a=null,nodeName:c=null,timeout:d,config:u={},signal:h=null}=t,m=[F("OPENAI_API_KEY"),F("CODEX_API_KEY")];try{let{Codex:y}=await import("@openai/codex-sdk"),b=n;(!b||b==="auto")&&(l.debug(`Model is '${b||"undefined"}', using default: ${j.CODEX}`),b=j.CODEX);let D=Me[b]||b;Me[b]&&b!==D&&l.debug(`Mapped model: ${b} \u2192 ${D}`),l.debug(`Invoking Codex SDK with model: ${D}, skills: ${JSON.stringify(i)}`);let _=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;_&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=_);let O=_?` | key: ***${_.slice(-4)}`:" | key: not set";console.log(`
|
|
81
|
+
\u25C6 Model: ${D}${O}
|
|
82
82
|
`);let A=(await import("chalk")).default;console.log(`
|
|
83
|
-
${A.bold("Prompt sent to LLM:")}`),console.log(A.dim("\u2500".repeat(60))),console.log(A.dim(e)),console.log(A.dim("\u2500".repeat(60)));let L=this._resolveSkillsToMcp(i,{sessionPath:a,workspace:o,nodeName:c}),g={};Object.keys(L).length>0&&(g.mcp_servers=L,l.debug(`[Codex] MCP servers: ${Object.keys(L).join(", ")}`));let
|
|
83
|
+
${A.bold("Prompt sent to LLM:")}`),console.log(A.dim("\u2500".repeat(60))),console.log(A.dim(e)),console.log(A.dim("\u2500".repeat(60)));let L=this._resolveSkillsToMcp(i,{sessionPath:a,workspace:o,nodeName:c}),g={};Object.keys(L).length>0&&(g.mcp_servers=L,l.debug(`[Codex] MCP servers: ${Object.keys(L).join(", ")}`));let B=new y({...Object.keys(g).length>0&&{config:g}}).startThread({workingDirectory:o,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),M=r&&typeof r.parse=="function",E={};if(r)try{let w=M?Z(r,{target:"openAi"}):r;E.outputSchema=w,l.debug("Structured output via SDK outputSchema")}catch(w){l.warn(`[Codex] Schema conversion failed, will extract from text: ${w.message}`)}if(h?.aborted){let w=new Error("Aborted via signal");throw w.name="AbortError",w}try{let{events:w}=await B.runStreamed(e,E),N=0,T="";for await(let C of w){if(h?.aborted){let P=new Error("Aborted via signal");throw P.name="AbortError",P}let k=C.type;if(k==="item.completed"){let P=C.item,J=P?.type;if(J==="mcp_tool_call"){N++;let v=`${P.server}/${P.tool}`;if(H.stepTool(`Tool: ${v}`),P.arguments){let f=JSON.stringify(P.arguments),R=f.length>100?`${f.substring(0,100)}...`:f;console.log(` Input: ${R}`)}}else if(J==="tool_call"||J==="function_call"||J==="command_execution"){N++;let v=P.name||P.tool||P.command||"unknown";H.stepTool(`Tool: ${v}`)}else J==="agent_message"&&(T=P.text||"",T.length<500?console.log(T):console.log(`${T.substring(0,200)}... (${T.length} chars)`))}else k==="turn.completed"?l.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(C.usage||{})}`):l.debug(`[Codex] Event: ${k} ${JSON.stringify(C).slice(0,300)}`)}if(l.debug(`[Codex] Last agent message (${T.length} chars): ${T.slice(0,500)}`),r){if(!T)throw new Error("Codex agent returned no response");let C=JSON.parse(T),k=M?r.parse(C):C;return l.debug("\u2705 [Codex] Structured output validated"),{raw:T,structured:k}}return T||""}catch(w){let N=w.message||String(w);throw l.error(`\u274C [Codex] SDK call failed: ${N}`),N.includes("exited with code")&&(l.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),l.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),w}}finally{for(let y of m)y.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let n={};for(let o of e){let r=ro(o);if(!r){l.warn(`[Codex] Unknown skill "${o}" \u2014 skipping`);continue}if(typeof r.resolve!="function")continue;let i=r.resolve(t);if(!i)continue;let a=r.serverName||o,c={command:i.command};i.args?.length&&(c.args=i.args),i.env&&Object.keys(i.env).length>0&&(c.env=i.env),n[a]=c,l.debug(`[Codex] MCP: ${a} \u2192 ${i.command} ${(i.args||[]).join(" ")}`)}return n}};fe();import{AgentStrategy as io,getSkill as lo}from"@zibby/agent-workflow";import{execSync as ao,spawn as co}from"node:child_process";import{existsSync as ct,mkdirSync as ut,readFileSync as dt,rmSync as uo,writeFileSync as ft}from"node:fs";import{join as q}from"node:path";function fo(s){if(!s)return null;let e=String(s),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 o=0,r=!1,i=!1,a=-1;for(let c=n;c<e.length;c++){let d=e[c];if(r){i?i=!1:d==="\\"?i=!0:d==='"'&&(r=!1);continue}if(d==='"'){r=!0;continue}if(d==="{"){o===0&&(a=c),o+=1;continue}if(d==="}"){if(o===0)continue;if(o-=1,o===0&&a>=0){let u=e.slice(a,c+1);try{return JSON.parse(u)}catch{a=-1}}}}return null}function po(s){let e=String(s||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return fo(e)}}function mo(s){try{let e=JSON.parse(s);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(o=>typeof o?.text=="string"?o.text:"").join("");if(n.trim())return n}}}catch{}return s}var Ae=class extends io{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 ao("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:n,workspace:o=process.cwd(),schema:r=null,skills:i=null,sessionPath:a=null,nodeName:c=null,timeout:d=600*1e3,signal:u=null}=t,h=[F("GEMINI_API_KEY"),F("GOOGLE_API_KEY")];try{let m=n;(!m||m==="auto")&&(m=j.GEMINI);let y=Ye[m]||m,b=String(process.env.GEMINI_API_KEY||"").trim(),D=String(process.env.GOOGLE_API_KEY||"").trim(),_=this._resolveSkillsToMcp(i,{sessionPath:a,workspace:o,nodeName:c}),O=Object.keys(_).length>0,A=new ee(e),L=r&&typeof r.parse=="function",g=null;if(r){let S;try{let p=L?Z(r,{target:"openAi"}):r;S=JSON.stringify(p,null,2)}catch{S="{}"}if(O){A.addSystemInstruction(`Write valid JSON that matches this schema:
|
|
84
84
|
${S}`,"schema_instruction","append");let p=`zibby-result-${Date.now()}.json`,$=q(o,".zibby","tmp");g=q($,p),ut($,{recursive:!0}),A.addStructuredOutput(r,g)}else A.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
|
|
85
|
-
${S}`,"json_instruction","append")}let K=A.build(),
|
|
85
|
+
${S}`,"json_instruction","append")}let K=A.build(),B=A.getUserPrompt(),M=A.getStats(),E=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),w=E?` | key: ***${E.slice(-4)}`:" | key: not set";console.log(`
|
|
86
86
|
\u25C6 Model: ${y||"auto"}${w}
|
|
87
87
|
`);let N=(await import("chalk")).default;console.log(`
|
|
88
|
-
${N.bold("Prompt sent to LLM:")}`),console.log(N.dim("\u2500".repeat(60))),console.log(N.dim(
|
|
88
|
+
${N.bold("Prompt sent to LLM:")}`),console.log(N.dim("\u2500".repeat(60))),console.log(N.dim(B)),console.log(N.dim("\u2500".repeat(60)));let T=this._createGeminiConfigDir(o,_),C=["--output-format","json"];y&&y!=="auto"&&C.push("--model",y);let k=Object.keys(_);if(k.length>0){C.push("--approval-mode","yolo");for(let S of k)C.push("--allowed-mcp-server-names",S);l.info(`[Gemini] Enabling MCP servers: ${k.join(", ")}`)}else i&&i.length>0&&l.warn(`[Gemini] Skills requested but no MCP servers configured: ${i.join(", ")}`);C.push("-p",K);let P={...process.env,GEMINI_CLI_HOME:T};b?(P.GEMINI_API_KEY=b,delete P.GOOGLE_API_KEY):D&&(P.GOOGLE_API_KEY=D,delete P.GEMINI_API_KEY),l.debug(`[Gemini] Command: gemini ${C.slice(0,8).join(" ")}... (${C.length} total args)`),l.debug(`[Gemini] User prompt: ${M.userPromptLength} chars, System instructions: ${M.systemInstructionsLength} chars (${M.instructionCount} blocks), Full: ${M.fullPromptLength} chars`),l.debug(`[Gemini] Config home: ${T}`),l.debug(`[Gemini] GEMINI_CLI_HOME env: ${P.GEMINI_CLI_HOME}`);let J="",v=null;try{J=await new Promise((p,$)=>{let I=co("gemini",C,{cwd:o,env:P,stdio:["ignore","pipe","pipe"],...u&&{signal:u}}),x="",G="",le=!1,ae=null,Pe=!1,je=setTimeout(()=>{try{I.kill("SIGTERM")}catch{}},d),he=()=>{Pe||le||(Pe=!0,ae=setTimeout(()=>{if(!le)try{I.kill("SIGKILL")}catch{}},5e3))};u&&(u.aborted?he():u.addEventListener("abort",he,{once:!0})),I.stdout.on("data",W=>{x+=W.toString()}),I.stderr.on("data",W=>{G+=W.toString()}),I.on("error",W=>{if(clearTimeout(je),ae&&clearTimeout(ae),u&&!u.aborted)try{u.removeEventListener("abort",he)}catch{}$(W)}),I.on("close",W=>{if(le=!0,clearTimeout(je),ae&&clearTimeout(ae),u&&!u.aborted)try{u.removeEventListener("abort",he)}catch{}if(Pe){let Fe=new Error("Aborted via signal");return Fe.name="AbortError",$(Fe)}if(W===0)return p(x.trim());$(new Error(`gemini failed with code ${W}: ${(G||x).trim()}`))})})}catch(S){v=S}finally{try{uo(T,{recursive:!0,force:!0})}catch{}}let f=mo(J).trim();if(!r){if(v)throw v;return f}if(g){let S=ct(g);if(l.info(`[Gemini] Result file: ${S?"present":"missing"} at ${g}`),S)try{let p=dt(g,"utf-8").trim(),$=JSON.parse(p),I=L?r.parse($):$;return l.info("[Gemini] Structured output recovered from result file"),{raw:f,structured:I}}catch(p){l.warn(`[Gemini] Result file parse/validation failed: ${p.message}`)}else v||l.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let R=null;if(r){let S=new Q;S.zodSchema=r,S.processChunk(f),S.flush(),R=S.getResult()}if(l.info(`[Gemini] Raw stdout length: ${J.length} chars`),l.info(`[Gemini] Extracted text length: ${f.length} chars`),l.info(`[Gemini] StreamParser result: ${R?"extracted":"null"}`),R||(f.length<2e3?l.info(`[Gemini] Raw text preview:
|
|
89
89
|
${f}`):l.info(`[Gemini] Raw text preview (first 1000 chars):
|
|
90
|
-
${f.slice(0,1e3)}`),R=
|
|
90
|
+
${f.slice(0,1e3)}`),R=po(f)),!R)throw v||(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 U=L?r.parse(R):R;return{raw:f,structured:U}}finally{for(let m of h)m.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let n={};for(let o of e){let r=lo(o);if(!r||typeof r.resolve!="function")continue;let i=r.resolve(t);if(!i)continue;let a=r.cursorKey||r.serverName||o,c={command:i.command};i.args?.length&&(c.args=i.args),i.env&&Object.keys(i.env).length>0&&(c.env=i.env),i.cwd&&(c.cwd=i.cwd),n[a]=c}return n}_createGeminiConfigDir(e,t){let n=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,o=q(e||process.cwd(),".zibby","tmp",`gemini-home-${n}`),r=q(o,".gemini");ut(r,{recursive:!0});let i=q(r,"settings.json"),a={},c=q(process.env.HOME||"",".gemini","settings.json");if(ct(c))try{a=JSON.parse(dt(c,"utf-8"))}catch{a={}}let d={...a,mcpServers:{...a.mcpServers&&typeof a.mcpServers=="object"?a.mcpServers:{},...t||{}}};ft(i,`${JSON.stringify(d,null,2)}
|
|
91
91
|
`,"utf-8");let u=q(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{ft(u,`${JSON.stringify(d,null,2)}
|
|
92
|
-
`,"utf-8")}catch{}return l.debug(`[Gemini] Created isolated config with ${Object.keys(d.mcpServers||{}).length} MCP servers`),l.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(d.mcpServers||{}),null,2)}`),o}};import{AgentStrategy as
|
|
92
|
+
`,"utf-8")}catch{}return l.debug(`[Gemini] Created isolated config with ${Object.keys(d.mcpServers||{}).length} MCP servers`),l.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(d.mcpServers||{}),null,2)}`),o}};import{AgentStrategy as Io,getSkill as $e}from"@zibby/agent-workflow";var me=class{formatTools(e){throw new Error("formatTools() must be implemented")}hasToolCalls(e){throw new Error("hasToolCalls() must be implemented")}parseToolCalls(e){throw new Error("parseToolCalls() must be implemented")}getTextContent(e){throw new Error("getTextContent() must be implemented")}buildAssistantMessage(e){throw new Error("buildAssistantMessage() must be implemented")}buildToolResultMessage(e,t){throw new Error("buildToolResultMessage() must be implemented")}injectToolsIntoBody(e,t){throw new Error("injectToolsIntoBody() must be implemented")}};var ne=class extends me{formatTools(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters||t.input_schema||{type:"object",properties:{}}}}))}hasToolCalls(e){let t=e.choices?.[0]?.message;return!!(t?.tool_calls&&t.tool_calls.length>0)}parseToolCalls(e){return(e.choices?.[0]?.message?.tool_calls||[]).map(n=>({id:n.id,name:n.function.name,args:JSON.parse(n.function.arguments||"{}")}))}getTextContent(e){return e.choices?.[0]?.message?.content||""}buildAssistantMessage(e){return e.choices?.[0]?.message}buildToolResultMessage(e,t){return{role:"tool",tool_call_id:e,content:typeof t=="string"?t:JSON.stringify(t)}}injectToolsIntoBody(e,t){return t.length>0&&(e.tools=t),e}};var ge=class{async fetchCompletion(e,t,n={}){throw new Error("fetchCompletion() must be implemented")}async fetchStreamingCompletion(e,t,n={}){throw new Error("fetchStreamingCompletion() must be implemented")}};function Te(s){return Buffer.byteLength(JSON.stringify(s),"utf8")}function ve(s,e){let t=String(s||"");if(t.length<=e)return t;let n=Math.max(0,e-28);return`${t.slice(0,n)}
|
|
93
93
|
|
|
94
|
-
[truncated for size budget]`}function Ke(s,e=0){if(!s||typeof s!="object"||e>8)return s;if(Array.isArray(s))return s.map(n=>Ke(n,e+1));let t={};for(let[n,o]of Object.entries(s))n==="description"||n==="title"||n==="examples"||n==="default"||(t[n]=Ke(o,e+1));return t}function
|
|
95
|
-
`);y=A.pop();for(let L of A){if(!L.startsWith("data: "))continue;let g=L.slice(6).trim();if(g==="[DONE]")continue;let K;try{K=JSON.parse(g)}catch{continue}let
|
|
96
|
-
`)||"",isError:r.isError||!1}}isRunning(e){return this.#e.has(e)}async stopServer(e){let t=this.#e.get(e);if(t){try{await t.client.close()}catch(n){l.debug(`[MCP] Error closing ${e}: ${n.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}};import{existsSync as
|
|
94
|
+
[truncated for size budget]`}function Ke(s,e=0){if(!s||typeof s!="object"||e>8)return s;if(Array.isArray(s))return s.map(n=>Ke(n,e+1));let t={};for(let[n,o]of Object.entries(s))n==="description"||n==="title"||n==="examples"||n==="default"||(t[n]=Ke(o,e+1));return t}function go(s=[]){return s.map(e=>({...e,function:{...e.function,description:ve(e.function?.description||"",180),parameters:Ke(e.function?.parameters||{type:"object",properties:{}})}}))}function pt(s){let e=new Set;for(let o of s)if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)e.add(r.id);let t=s.filter(o=>o.role==="tool"?e.has(o.tool_call_id):!0),n=new Set;for(let o of t)o.role==="tool"&&n.add(o.tool_call_id);return t.map(o=>{if(o.role!=="assistant"||!Array.isArray(o.tool_calls)||o.tool_calls.every(c=>n.has(c.id)))return o;let{tool_calls:i,...a}=o;return{...a,content:a.content||""}})}function Be(s,e={}){let t=e.maxBytes||49e3,n=e.systemMaxChars||12e3,o={...s,messages:Array.isArray(s.messages)?[...s.messages]:[],tools:Array.isArray(s.tools)?go(s.tools):s.tools};o.messages.length>0&&o.messages[0]?.role==="system"&&(o.messages[0]={...o.messages[0],content:ve(o.messages[0].content,n)});let r=!1;for(;Te(o)>t&&o.messages.length>2;)o.messages.splice(1,1),r=!0;if(r&&(o.messages=pt(o.messages)),Te(o)>t&&o.messages.length>0&&(o.messages[0]={...o.messages[0],content:ve(o.messages[0].content,6e3)},r=!0),Te(o)>t){let i=o.messages.find(c=>c.role==="system")||o.messages[0],a=o.messages.slice(-2);o.messages=pt([i,...a].filter(Boolean).map((c,d)=>({...c,content:ve(c.content,d===0?4e3:8e3)}))),r=!0}return{body:o,meta:{bytes:Te(o),trimmed:r,maxBytes:t,messageCount:o.messages.length}}}var mt=s=>Buffer.byteLength(JSON.stringify(s),"utf8"),re=class extends ge{async fetchCompletion(e,t,n={}){let o=mt(e),{body:r,meta:i}=Be(e,n.payloadCompaction);n.onBudget?.({streaming:!1,beforeBytes:o,meta:i});let a=this.#e(n),c=`${t.baseUrl}${n.chatCompletionsPath||"/v1/chat/completions"}`,d=await fetch(c,{method:"POST",headers:t.headers,body:JSON.stringify(r),signal:a});if(!d.ok){let u=await d.text();throw d.status===401||d.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${d.status}: ${u}`)}return d.json()}async fetchStreamingCompletion(e,t,n={}){let o={...e,stream:!0},r=mt(o),{body:i,meta:a}=Be(o,n.payloadCompaction);n.onBudget?.({streaming:!0,beforeBytes:r,meta:a});let c=this.#e(n),d=`${t.baseUrl}${n.chatCompletionsPath||"/v1/chat/completions"}`,u=await fetch(d,{method:"POST",headers:t.headers,body:JSON.stringify(i),signal:c});if(!u.ok){let _=await u.text();throw u.status===401||u.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${u.status}: ${_}`)}let h=u.body.getReader(),m=new TextDecoder,y="",b="",D=new Map;for(;;){let{done:_,value:O}=await h.read();if(_)break;y+=m.decode(O,{stream:!0});let A=y.split(`
|
|
95
|
+
`);y=A.pop();for(let L of A){if(!L.startsWith("data: "))continue;let g=L.slice(6).trim();if(g==="[DONE]")continue;let K;try{K=JSON.parse(g)}catch{continue}let B=K.choices?.[0]?.delta;if(B&&(B.content&&(b+=B.content,n.onToken&&n.onToken(B.content)),B.tool_calls))for(let M of B.tool_calls){let E=M.index??0;D.has(E)||D.set(E,{id:"",name:"",args:""});let w=D.get(E);M.id&&(w.id=M.id),M.function?.name&&(w.name=M.function.name),M.function?.arguments!=null&&(w.args+=M.function.arguments)}}}if(D.size>0){let _=[...D.entries()].sort(([O],[A])=>O-A).map(([,O])=>({id:O.id,type:"function",function:{name:O.name,arguments:O.args}}));return{choices:[{message:{role:"assistant",content:b||null,tool_calls:_}}]}}return{choices:[{message:{role:"assistant",content:b}}]}}#e(e={}){let t=[e.signal,e.timeout?AbortSignal.timeout(e.timeout):null].filter(Boolean);return t.length>1?AbortSignal.any(t):t[0]||void 0}};import{Client as ho}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as yo}from"@modelcontextprotocol/sdk/client/stdio.js";var we=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:n,args:o=[],env:r={}}=t;l.debug(`[MCP] Starting ${e}: ${n} ${o.join(" ")}`);let i=new yo({command:n,args:o,env:{...process.env,...r}}),a=new ho({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await a.connect(i);let c={client:a,transport:i,serverConfig:t};return this.#e.set(e,c),c}async callTool(e,t,n={}){let o=this.#e.get(e);if(!o)throw new Error(`MCP server "${e}" not running`);l.debug(`[MCP] ${e}.${t}(${JSON.stringify(n).slice(0,200)})`);let r=await o.client.callTool({name:t,arguments:n});return{text:r.content?.filter(a=>a.type==="text").map(a=>a.text).join(`
|
|
96
|
+
`)||"",isError:r.isError||!1}}isRunning(e){return this.#e.has(e)}async stopServer(e){let t=this.#e.get(e);if(t){try{await t.client.close()}catch(n){l.debug(`[MCP] Error closing ${e}: ${n.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}};import{existsSync as _o,readFileSync as So}from"node:fs";import{join as Oo}from"node:path";import{homedir as bo}from"node:os";function Eo(){try{let s=Oo(bo(),".zibby","config.json");return _o(s)?JSON.parse(So(s,"utf-8")):{}}catch{return{}}}function Ie(s){return String(s||"").replace(/\/v1\/?$/,"")}function Ao(s,e){let t=process.env.OPENAI_PROXY_URL;if(t)return Ie(t);if(s==="session")return e.proxyUrl?Ie(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(s==="byok"){let n=process.env.OPENAI_BASE_URL;return Ie(n||"https://api.openai.com")}return Ie(t||"")}function Ge(){let s=Eo(),e=process.env.ZIBBY_USER_TOKEN||s.sessionToken||null,t=process.env.OPENAI_API_KEY||null,n=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),o=process.env.OPENAI_PROXY_NO_AUTH==="true",r=process.env.OPENAI_PROXY_URL,i="session";n==="byok"||n==="local"||n==="session"?i=n:e?i="session":t?i="byok":r&&o&&(i="local");let a=Ao(i,s),c={"Content-Type":"application/json"};if(i==="session"){if(!e)return{ok:!1,mode:i,reason:"missing_session_token"};c.Authorization=`Bearer ${e}`}else if(i==="byok"){if(!t)return{ok:!1,mode:i,reason:"missing_openai_api_key"};c.Authorization=`Bearer ${t}`}else if(i==="local"){if(!a)return{ok:!1,mode:i,reason:"missing_openai_proxy_url"};!o&&t&&(c.Authorization=`Bearer ${t}`)}return a?{ok:!0,mode:i,baseUrl:a,headers:c,tokenPreview:c.Authorization?`***${c.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:i,reason:"missing_base_url"}}function xe(s,e){let t=String(s??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
|
|
97
97
|
|
|
98
|
-
[tool result truncated for size]`}function
|
|
98
|
+
[tool result truncated for size]`}function To(s,e){if(typeof s=="string")return xe(s,e);try{return xe(JSON.stringify(s),e)}catch{return xe(String(s),e)}}function gt(s){let e=new Set;for(let o of s)if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)e.add(r.id);let t=s.filter(o=>o.role==="tool"?e.has(o.tool_call_id):!0),n=new Set;for(let o of t)o.role==="tool"&&n.add(o.tool_call_id);return t.map(o=>{if(o.role!=="assistant"||!Array.isArray(o.tool_calls)||o.tool_calls.every(c=>n.has(c.id)))return o;let{tool_calls:i,...a}=o;return{...a,content:a.content||""}})}function vo(s){let e=Array.isArray(s?.messages)?s.messages:[],t=e.find(r=>r.role==="system"),n=e.slice(-4).map(r=>({...r,content:xe(r.content,r.role==="tool"?1200:2500)}));n=gt(n);let o={...s,messages:[t,...n].filter(Boolean)};return delete o.tools,o}async function wo({body:s,streaming:e,auth:t,options:n,fetchCompletion:o,fetchStreamingCompletion:r,onFallbackLog:i}){try{return e?await r(s,t,n):await o(s,t,n)}catch(a){let c=String(a?.message||a||"");if(!/proxy error 413|payload too large/i.test(c))throw a;let d=vo(s);return typeof i=="function"&&i(s,d),{data:e?await r(d,t,n):await o(d,t,n),fallback:d}}}async function ht({body:s,auth:e,options:t,streaming:n,toolContext:o,activeSkills:r,round:i,verbose:a,dependencies:c,config:d={}}){let u=d.maxToolResultChars||3e3,{fetchCompletion:h,fetchStreamingCompletion:m,onFallbackLog:y,hasToolCalls:b,getTextContent:D,parseToolCalls:_,buildAssistantMessage:O,buildToolResultMessage:A,executeTool:L,onToolCallLog:g,injectTools:K}=c;Array.isArray(s?.messages)&&(s.messages=gt(s.messages));let B=await wo({body:s,streaming:n,auth:e,options:t,fetchCompletion:h,fetchStreamingCompletion:m,onFallbackLog:y}),M=B?.data||B;if(!b(M))return{done:!0,text:D(M),body:B?.fallback||s};let E=_(M),w=B?.fallback||s;w.messages.push(O(M)),a&&typeof g=="function"&&g(E);let N=await Promise.all(E.map((T,C)=>(typeof t.onToolCall=="function"&&t.onToolCall(T.name,T.args,{round:i,index:C,total:E.length}),L(T,o))));for(let T=0;T<E.length;T++){let k=E[T].name==="get_skill_context"?typeof N[T]=="string"?N[T]:JSON.stringify(N[T]):To(N[T],u);w.messages.push(A(E[T].id,k))}return typeof t.onToolCall=="function"&&t.onToolCall(null),K(w,r),{done:!1,body:w}}var xo=j.ASSISTANT,$o=15,Je="get_skill_context";function ie(s){!s||typeof s!="object"||(s.type==="object"&&s.properties&&(s.required=Object.keys(s.properties),s.additionalProperties=!1,Object.values(s.properties).forEach(ie)),s.type==="array"&&s.items&&ie(s.items),s.anyOf&&s.anyOf.forEach(ie),s.oneOf&&s.oneOf.forEach(ie),s.allOf&&s.allOf.forEach(ie))}var yt={maxBytes:49e3,systemMaxChars:12e3},se=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Co=s=>Buffer.byteLength(JSON.stringify(s),"utf8");function Ce(s){return Array.isArray(s)?new Set(s.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function ko(s){return Array.isArray(s)?s.map(e=>String(e||"").trim()).filter(Boolean):[]}var ke=class extends Io{#e;#t;#o=new we;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new ne,this.#t=e.completionProvider||new re):(this.#e=e||new ne,this.#t=new re)}canHandle(e){return Ge().ok}async invoke(e,t={}){let n=F("OPENAI_API_KEY");try{let o=t.model&&t.model!=="auto"?t.model:xo,r=Ge();if(!r.ok)throw r.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):r.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):r.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${r.reason}).`);let i=t.messages||[{role:"user",content:e}],a=r.baseUrl,c=se();if(c?await this.#m(i,o,a,r.tokenPreview||"none"):l.debug(`[Assistant] ${a} | model: ${o} | messages: ${i.length}`),t.schema)return this.#c(o,i,r,t);let d=t.activeSkills||[],u=this.#d(t),h=this.#f(d,u),m=this.#p(h),y=this.#u(t),b={...t,payloadCompaction:y},D={activeSkills:h,options:b,executionRegistry:m,capabilityPolicy:u},_=!!t.stream,O={model:o,messages:[...i],stream:!1};this.#r(O,h,u);for(let A=0;A<$o;A++){if(t.signal?.aborted){let g=new Error("Aborted via signal");throw g.name="AbortError",g}let L=await ht({body:O,auth:r,options:b,streaming:_,toolContext:D,activeSkills:h,round:A,verbose:c,dependencies:{fetchCompletion:this.#s.bind(this),fetchStreamingCompletion:this.#a.bind(this),onFallbackLog:(g,K)=>{se()&&console.log(`413 fallback: messages ${g.messages.length} -> ${K.messages.length}, bytes=${Co(K)}`)},hasToolCalls:g=>this.#e.hasToolCalls(g),getTextContent:g=>this.#e.getTextContent(g),parseToolCalls:g=>this.#e.parseToolCalls(g),buildAssistantMessage:g=>this.#e.buildAssistantMessage(g),buildToolResultMessage:(g,K)=>this.#e.buildToolResultMessage(g,K),executeTool:(g,K)=>this.#l(g,K),onToolCallLog:async g=>{let K=(await import("chalk")).default;console.log(K.dim(` ${g.map(B=>`${B.name}(${JSON.stringify(B.args).slice(0,80)})`).join(", ")}`))},injectTools:(g,K)=>this.#r(g,K,u)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(L.done)return L.text;O.messages=L.body.messages,L.body.tools?O.tools=L.body.tools:delete O.tools}return"I hit my tool-calling limit for this turn. Please try again."}finally{n.dispose()}}async cleanup(){await this.#o.stopAll()}#r(e,t,n=null){let o=this.#i(t,n),r=this.#e.formatTools(o);this.#e.injectToolsIntoBody(e,r)}#i(e,t=null){let n=[],o=new Set;for(let r of e){let i=$e(r);if(i?.tools?.length)for(let a of i.tools)this.#n(a.name,t)&&(o.has(a.name)||(o.add(a.name),n.push({name:a.name,description:a.description,parameters:a.parameters||a.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#n(Je,t)&&n.push({name:Je,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),n}async#l(e,t){let{activeSkills:n,options:o,executionRegistry:r,capabilityPolicy:i}=t;if(!this.#n(e.name,i))return`Tool "${e.name}" blocked by policy`;if(e.name===Je){let d=String(e.args?.skillId||"").trim();if(!d)return JSON.stringify({error:"skillId is required"});if(!n.includes(d))return JSON.stringify({error:`Skill "${d}" is not active`,activeSkills:n});let u=$e(d);if(!u)return JSON.stringify({error:`Skill "${d}" not found`});let h=typeof u.promptFragment=="function"?u.promptFragment():u.promptFragment||"",m=(u.tools||[]).map(b=>b.name),y=JSON.stringify({skillId:d,description:u.description||"",toolNames:m,promptFragment:h||""});return se()&&(console.log(`
|
|
99
99
|
\u{1F4D6} get_skill_context("${d}") \u2192 ${y.length} chars (fragment: ${h.length} chars)`),console.log(` tools: [${m.join(", ")}]`),console.log(` fragment preview: ${h.slice(0,200).replace(/\n/g,"\\n")}\u2026
|
|
100
|
-
`)),y}let a=r?.get(e.name)||null;if(!a)return`Unknown tool: ${e.name}`;let c=$e(a.skillId);if(!c)return`Skill "${a.skillId}" not found for tool "${e.name}"`;if(a.mode==="handler")try{return c.handleToolCall(e.name,e.args,t)}catch(d){return`Error in ${e.name}: ${d.message}`}if(a.mode==="mcp")try{if(!this.#o.isRunning(c.serverName)){let u=c.resolve(o);if(!u)return`Skill "${a.skillId}" is not available (cannot start server)`;await this.#o.ensureServer(c.serverName,u)}let d=await this.#o.callTool(c.serverName,e.name,e.args);return d.text||(d.isError?"Tool call failed":"Done")}catch(d){return`MCP error (${c.serverName}): ${d.message}`}return`Skill "${a.skillId}" owns tool "${e.name}" but has no execution mode`}async#a(e,t,n){return this.#t.fetchStreamingCompletion(e,t,{...n,onBudget:({beforeBytes:o,meta:r})=>{se()&&console.log(`payload bytes (stream) before=${o} after=${r.bytes} trimmed=${r.trimmed} messages=${r.messageCount}`)}})}async#s(e,t,n){return this.#t.fetchCompletion(e,t,{...n,onBudget:({beforeBytes:o,meta:r})=>{se()&&console.log(`payload bytes before=${o} after=${r.bytes} trimmed=${r.trimmed} messages=${r.messageCount}`)}})}async#c(e,t,n,o){let{zodToJson:r}=await Promise.resolve().then(()=>(fe(),st)),i=typeof o.schema?.parse=="function",a=i?r(o.schema,{}):o.schema;delete a.$schema,ie(a);let c={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:a,strict:!0}}},d=await this.#s(c,n,o),u=this.#e.getTextContent(d),h=JSON.parse(u),m=i?o.schema.parse(h):h;return{raw:u,structured:m}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||yt.maxBytes),systemMaxChars:Number(t.systemMaxChars||yt.systemMaxChars)}}#d(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:Ce(t.allowTools||e.allowTools),denyTools:Ce(t.denyTools||e.denyTools),denyPrefixes:
|
|
100
|
+
`)),y}let a=r?.get(e.name)||null;if(!a)return`Unknown tool: ${e.name}`;let c=$e(a.skillId);if(!c)return`Skill "${a.skillId}" not found for tool "${e.name}"`;if(a.mode==="handler")try{return c.handleToolCall(e.name,e.args,t)}catch(d){return`Error in ${e.name}: ${d.message}`}if(a.mode==="mcp")try{if(!this.#o.isRunning(c.serverName)){let u=c.resolve(o);if(!u)return`Skill "${a.skillId}" is not available (cannot start server)`;await this.#o.ensureServer(c.serverName,u)}let d=await this.#o.callTool(c.serverName,e.name,e.args);return d.text||(d.isError?"Tool call failed":"Done")}catch(d){return`MCP error (${c.serverName}): ${d.message}`}return`Skill "${a.skillId}" owns tool "${e.name}" but has no execution mode`}async#a(e,t,n){return this.#t.fetchStreamingCompletion(e,t,{...n,onBudget:({beforeBytes:o,meta:r})=>{se()&&console.log(`payload bytes (stream) before=${o} after=${r.bytes} trimmed=${r.trimmed} messages=${r.messageCount}`)}})}async#s(e,t,n){return this.#t.fetchCompletion(e,t,{...n,onBudget:({beforeBytes:o,meta:r})=>{se()&&console.log(`payload bytes before=${o} after=${r.bytes} trimmed=${r.trimmed} messages=${r.messageCount}`)}})}async#c(e,t,n,o){let{zodToJson:r}=await Promise.resolve().then(()=>(fe(),st)),i=typeof o.schema?.parse=="function",a=i?r(o.schema,{}):o.schema;delete a.$schema,ie(a);let c={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:a,strict:!0}}},d=await this.#s(c,n,o),u=this.#e.getTextContent(d),h=JSON.parse(u),m=i?o.schema.parse(h):h;return{raw:u,structured:m}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||yt.maxBytes),systemMaxChars:Number(t.systemMaxChars||yt.systemMaxChars)}}#d(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:Ce(t.allowTools||e.allowTools),denyTools:Ce(t.denyTools||e.denyTools),denyPrefixes:ko(t.denyPrefixes||e.denyToolPrefixes),includeSkills:Ce(t.includeSkills||e.includeSkills),excludeSkills:Ce(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#f(e,t){let n=t?.includeSkills||new Set,o=t?.excludeSkills||new Set;return n.size===0&&o.size===0?e:e.filter(r=>!(n.size>0&&!n.has(r)||o.has(r)))}#n(e,t){let n=String(e||"").trim();if(!n)return!1;let o=t?.allowTools;if(o&&o.size>0&&!o.has(n))return!1;let r=t?.denyTools;return!(r&&r.has(n)||(t?.denyPrefixes||[]).some(a=>n.startsWith(a)))}#p(e){let t=new Map,n=[];for(let o of e){let r=$e(o);if(!r?.tools?.length)continue;let i=typeof r.handleToolCall=="function"?"handler":r.serverName&&typeof r.resolve=="function"?"mcp":null;if(i)for(let a of r.tools){let c=String(a?.name||"").trim();if(c){if(t.has(c)){n.push({tool:c,winner:t.get(c).skillId,skipped:o});continue}t.set(c,{skillId:o,mode:i})}}}if(n.length>0&&se()){let o=n.slice(0,5).map(r=>`${r.tool}:${r.winner}>${r.skipped}`).join(", ");console.log(`tool registry collisions: ${o}${n.length>5?" ...":""}`)}return t}async#m(e,t,n,o){console.log(`
|
|
101
101
|
\u25C6 Model: ${t} | proxy: ${n} | token: ${o||"none"}
|
|
102
|
-
`);let r=(await import("chalk")).default;console.log(r.bold("Prompt sent to LLM:")),console.log(r.dim("\u2500".repeat(60)));let i=!1;for(let a of e)if(a.role==="system")console.log(r.dim(`[System] ${a.content||""}`));else{i||(console.log(r.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),i=!0);let c=a.role==="user"?"Human":"AI",d=a.content?.length>200?`${a.content.slice(0,200)}...`:a.content||"";console.log(r.dim(`[${c}] ${d}`))}console.log(r.dim("\u2500".repeat(60)))}};import{AgentStrategy as
|
|
102
|
+
`);let r=(await import("chalk")).default;console.log(r.bold("Prompt sent to LLM:")),console.log(r.dim("\u2500".repeat(60)));let i=!1;for(let a of e)if(a.role==="system")console.log(r.dim(`[System] ${a.content||""}`));else{i||(console.log(r.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),i=!0);let c=a.role==="user"?"Human":"AI",d=a.content?.length>200?`${a.content.slice(0,200)}...`:a.content||"";console.log(r.dim(`[${c}] ${d}`))}console.log(r.dim("\u2500".repeat(60)))}};import{AgentStrategy as jr}from"@zibby/agent-workflow";var _t=[new ke,new Oe,new be,new Ee,new Ae];function Po(s={}){let{state:e={},preferredAgent:t=null}=s,n=t||e.agentType||process.env.AGENT_TYPE;if(!n)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");l.debug(`Agent selection: requested=${n}`);let o=_t.find(r=>r.getName()===n);if(!o)throw new Error(`Unknown agent '${n}'. Available: ${_t.map(r=>r.getName()).join(", ")}`);if(l.debug(`Checking if ${n} can handle this environment...`),!o.canHandle(s)){let i={assistant:"Run `zibby login` to authenticate",claude:"Set ANTHROPIC_API_KEY in .env",cursor:"Install cursor-agent CLI or set CURSOR_API_KEY",codex:"Install codex CLI (npm i -g @openai/codex) and set OPENAI_API_KEY in .env",gemini:"Install gemini CLI (npm i -g @google/gemini-cli) and set GEMINI_API_KEY in .env"}[n]||"Check your environment configuration";throw new Error(`Agent '${n}' is not available. ${i}`)}return l.debug(`Using agent: ${o.getName()}`),o}async function Br(s,e={},t={}){try{await import("@zibby/skills")}catch{}try{await import("@zibby/skills-internal")}catch{}let n=Po(e),o=e.state?.config||t.config||{},r=o.models||{},i=t.nodeName&&r[t.nodeName]||null,a=r.default||null,c=n.name,d=o.agent?.[c]?.model||null,u=i||a||d||t.model||null,h={...t,model:u,workspace:e.state?.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:o},m=h.skills||[],y=s;if(m.length>0&&!t.skipPromptFragments){let{getSkill:D}=await import("@zibby/agent-workflow"),_=m.map(O=>{let A=D(O)?.promptFragment;return typeof A=="function"?A():A}).filter(Boolean);_.length>0&&(y+=`
|
|
103
103
|
|
|
104
104
|
${_.join(`
|
|
105
105
|
|
|
106
|
-
`)}`)}let
|
|
106
|
+
`)}`)}let b=e.state?._currentNodeConfig?.extraPromptInstructions?.trim();return b&&(y+=`
|
|
107
107
|
|
|
108
108
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
109
109
|
\u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
110
110
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
111
111
|
|
|
112
|
-
${
|
|
112
|
+
${b}
|
|
113
113
|
`),l.debug(`Prompt length: ${y.length} chars`),process.env.STAGE!=="prod"&&l.debug(`Full prompt:
|
|
114
|
-
${y}`),n.invoke(y,h)}export{
|
|
114
|
+
${y}`),n.invoke(y,h)}export{jr as AgentStrategy,ke as AssistantStrategy,be as ClaudeAgentStrategy,Ee as CodexAgentStrategy,Oe as CursorAgentStrategy,Ae as GeminiAgentStrategy,Po as getAgentStrategy,Br as invokeAgent};
|