@zibby/core 0.1.38 → 0.1.40
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/agents/base.js +47 -40
- package/dist/framework/agents/cursor-strategy.js +29 -22
- package/dist/framework/agents/gemini-strategy.js +11 -11
- package/dist/framework/agents/index.js +45 -38
- package/dist/framework/agents/utils/cursor-output-formatter.js +2 -2
- package/dist/framework/agents/utils/structured-output-formatter.js +1 -1
- package/dist/framework/code-generator.js +33 -26
- package/dist/framework/graph-compiler.js +47 -40
- package/dist/framework/graph.js +50 -43
- package/dist/framework/index.js +23 -16
- package/dist/framework/node-registry.js +39 -32
- package/dist/framework/node.js +43 -36
- package/dist/index.js +47 -40
- package/dist/package.json +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Kt=Object.defineProperty;var P=(n,e)=>()=>(n&&(e=n(n=0)),e);var Fe=(n,e)=>{for(var t in e)Kt(n,t,{get:e[t],enumerable:!0})};var Ke={};Fe(Ke,{getAllSkills:()=>Ae,getSkill:()=>U,hasSkill:()=>Wt,listSkillIds:()=>Yt,registerSkill:()=>zt});function zt(n){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");se.set(n.id,Object.freeze({...n}))}function U(n){return se.get(n)||null}function Wt(n){return se.has(n)}function Ae(){return new Map(se)}function Yt(){return Array.from(se.keys())}var se,Y=P(()=>{se=new Map});var j,H=P(()=>{j=class{constructor(e,t,r=0){this.name=e,this.description=t,this.priority=r}async invoke(e,t={}){throw new Error("AgentStrategy.invoke() must be implemented by subclass")}canHandle(e){throw new Error("AgentStrategy.canHandle() must be implemented by subclass")}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});import ie from"chalk";var F,
|
|
1
|
+
var Kt=Object.defineProperty;var P=(n,e)=>()=>(n&&(e=n(n=0)),e);var Fe=(n,e)=>{for(var t in e)Kt(n,t,{get:e[t],enumerable:!0})};var Ke={};Fe(Ke,{getAllSkills:()=>Ae,getSkill:()=>U,hasSkill:()=>Wt,listSkillIds:()=>Yt,registerSkill:()=>zt});function zt(n){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");se.set(n.id,Object.freeze({...n}))}function U(n){return se.get(n)||null}function Wt(n){return se.has(n)}function Ae(){return new Map(se)}function Yt(){return Array.from(se.keys())}var se,Y=P(()=>{se=new Map});var j,H=P(()=>{j=class{constructor(e,t,r=0){this.name=e,this.description=t,this.priority=r}async invoke(e,t={}){throw new Error("AgentStrategy.invoke() must be implemented by subclass")}canHandle(e){throw new Error("AgentStrategy.canHandle() must be implemented by subclass")}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});import ie from"chalk";var F,ve,c,K=P(()=>{F={debug:0,info:1,warn:2,error:3,silent:4},ve=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return F.debug;if(process.env.ZIBBY_VERBOSE==="true")return F.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in F?F[e]:F.info}_shouldLog(e){return F[e]>=this._level}_formatMessage(e,t,r={}){let o=new Date().toISOString(),s=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(s+=ie.dim(` ${JSON.stringify(r)}`)),s}_getPrefix(e){return{debug:ie.gray("[DEBUG]"),info:ie.cyan("[INFO]"),warn:ie.yellow("[WARN]"),error:ie.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 F&&(this._level=F[e])}getLevel(){return Object.keys(F).find(e=>F[e]===this._level)}},c=new ve});var B,Ie,ke,We,ye,Z=P(()=>{B={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"},Ie={auto:"claude-sonnet-4-6","sonnet-4.6":"claude-sonnet-4-6","sonnet-4-6":"claude-sonnet-4-6","opus-4.6":"claude-opus-4-6","opus-4-6":"claude-opus-4-6","sonnet-4.5":"claude-sonnet-4-5-20250929","sonnet-4-5":"claude-sonnet-4-5-20250929","opus-4.5":"claude-opus-4-20250514","opus-4-5":"claude-opus-4-20250514","claude-sonnet-4-6":"claude-sonnet-4-6","claude-opus-4-6":"claude-opus-4-6","claude-sonnet-4-5-20250929":"claude-sonnet-4-5-20250929","claude-opus-4-20250514":"claude-opus-4-20250514"},ke={auto:"o4-mini","o4-mini":"o4-mini",o3:"o3","o3-mini":"o3-mini","codex-mini":"codex-mini-latest","gpt-4o":"gpt-4o","gpt-4o-mini":"gpt-4o-mini","gpt-5.2-codex":"gpt-5.2-codex","gpt-5.2":"gpt-5.2","gpt-5.3":"gpt-5.3","gpt-5.4":"gpt-5.4"},We={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},ye={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4}});var Ye,He,Ze,Xe=P(()=>{Ye=".zibby/output",He=".session-info.json",Ze=".zibby-studio-stop"});var q,Ce=P(()=>{q=class n{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 r="";for(let o of t)if(o.trim())try{let i=JSON.parse(o);this._emitToolCalls(i);let s=this.extractText(i);if(s){if(this.rawText&&s.startsWith(this.rawText)){let l=s.substring(this.rawText.length);this.rawText=s,r+=l}else(!this.rawText.includes(s)||s.length<20)&&(this.rawText+=s,r+=s);this.tryExtractResult(this.rawText)}else this.isValidResult(i)&&(this.rawText+=`${o}
|
|
3
3
|
`,r+=`${o}
|
|
4
4
|
`,this.extractedResult=i)}catch{if(o.includes('"text"')||o.includes('"content"')){let s=o.match(/"text"\s*:\s*"([^"]*)/),l=o.match(/"content"\s*:\s*"([^"]*)/),a=s?s[1]:l?l[1]:null;a&&!this.rawText.includes(a)&&(r+=a,this.rawText+=a)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(s,l)=>{if(!s)return;let a=`${s}:${JSON.stringify(l??{})}`;this._lastToolEmit!==a&&(this._lastToolEmit=a,this.onToolCall(s,l??void 0))},r=s=>{if(s!=null){if(typeof s=="object"&&!Array.isArray(s))return s;if(typeof s=="string")try{return JSON.parse(s)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,r(e.input??e.arguments));return}let s=e.tool_call;if(s&&typeof s=="object"&&!Array.isArray(s)){let l=Object.keys(s);if(l.length===1){let a=l[0],u=s[a],f=u&&typeof u=="object"?u.args??u.input??u:void 0;t(a,r(f))}return}return}if(Array.isArray(e.tool_calls)){for(let s of e.tool_calls)t(s.name,r(s.input??s.arguments));return}let o=e.message??e;if(Array.isArray(o?.tool_calls)){for(let s of o.tool_calls)t(s.name,r(s.input??s.arguments));return}let i=o?.content??e.content;if(Array.isArray(i))for(let s of i)(s.type==="tool_use"||s.type==="tool_call")&&s.name&&t(s.name,r(s.input??s.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return e.type==="thinking"&&e.text||e.text?e.text:e.content&&typeof e.content=="string"?e.content:e.delta?e.delta:null}tryExtractResult(e){if(!e||typeof e!="string")return;let t=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,o;for(;(o=r.exec(e))!==null;){let h=o[1].trim();try{JSON.parse(h),t.push({text:h,source:"markdown"})}catch{}}let i=0,s=0;for(;i<e.length&&(i=e.indexOf("{",i),i!==-1);){let h=0,m=i;for(let S=i;S<e.length;S++)if(e[S]==="{")h++;else if(e[S]==="}"&&(h--,h===0)){m=S,t.push({text:e.substring(i,m+1),source:"brace"}),s++;break}i=m+1}let l=this.extractedResult,a=l?JSON.stringify(l).length:0,u=0,f=-1;for(let h=0;h<t.length;h++){let m=t[h];try{let S=m.text.replace(/,(\s*[}\]])/g,"$1"),w=JSON.parse(S);this.isValidResult(w)&&(u++,a=JSON.stringify(w).length,l=w,f=h)}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 r=new n;r.zodSchema=t,r.processChunk(e),r.flush();let o=r.getResult();return!o&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),o}}});import{zodToJsonSchema as Ht}from"zod-to-json-schema";var Q,Ne=P(()=>{Q=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=Ht(e,{target:"openApi3"}):r=e;let o=this._buildExample(r);return`
|
|
@@ -21,7 +21,7 @@ JSON types (strict \u2014 validators reject wrong types):
|
|
|
21
21
|
- Use true/false without quotes for booleans.
|
|
22
22
|
- Use unquoted null where a field may be null.
|
|
23
23
|
|
|
24
|
-
Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(e){if(!e)return{};let t=e.type;if(t==="object"&&e.properties){let r={};for(let[o,i]of Object.entries(e.properties))r[o]=this._buildExample(i);return r}if(t==="array"&&e.items)return[this._buildExample(e.items)];if(t==="string")return"<string>";if(t==="number"||t==="integer")return 0;if(t==="boolean")return!1;if(e.description)return`<${e.description}>`;if(e.nullable||e.oneOf||e.anyOf){let r=e.oneOf?.find(o=>o.type!=="null")||e.anyOf?.find(o=>o.type!=="null");return r?this._buildExample(r):null}return"<value>"}}});import Zt from"axios";import{homedir as Xt}from"node:os";import{join as Vt}from"node:path";import{existsSync as qt,readFileSync as Qt}from"node:fs";import{toJSONSchema as eo}from"zod";function to(){if(process.env.OPENAI_PROXY_TOKEN)return c.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return c.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let n=Vt(Xt(),".zibby","config.json");if(qt(n)){let e=JSON.parse(Qt(n,"utf-8"));if(e.sessionToken)return c.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(n){c.debug(`[Auth] Could not read zibby login session: ${n.message}`)}return null}function oo(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function ee(n){if(!(typeof n!="object"||n===null)){if(Object.keys(n).length===0){n.type="object",n.additionalProperties=!0;return}if(n.type||(n.properties?n.type="object":n.items&&(n.type="array")),n.type==="object")if(n.properties){for(let[e,t]of Object.entries(n.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(n.properties[e]={type:["object","null"]});n.additionalProperties=!1,n.required=Object.keys(n.properties),Object.values(n.properties).forEach(ee)}else"additionalProperties"in n||(n.additionalProperties=!0);n.type==="array"&&n.items&&ee(n.items),n.anyOf&&n.anyOf.forEach(ee),n.oneOf&&n.oneOf.forEach(ee),n.allOf&&n.allOf.forEach(ee)}}async function Ve(n,e){c.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=to();if(!t)throw new Error("Authentication required for structured output processing.\n Local development: Run `zibby login`\n CI/CD: Set ZIBBY_USER_TOKEN environment variable (Personal Access Token from UI settings)");let r=oo();c.info(`\u{1F517} Using OpenAI proxy: ${r}`);let o=eo(e),i=o;if(o.$ref&&o.definitions){let f=o.$ref.split("/").pop();i=o.definitions[f]||o,c.debug(`Extracted schema from $ref: ${f}`)}delete i.$schema,ee(i);let s=4e5,l=n;n.length>s&&(c.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${n.length} chars) exceeds limit, keeping last ${s} chars`),l=`... [truncated early content] ...
|
|
24
|
+
Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(e){if(!e)return{};let t=e.type;if(t==="object"&&e.properties){let r={};for(let[o,i]of Object.entries(e.properties))r[o]=this._buildExample(i);return r}if(t==="array"&&e.items)return[this._buildExample(e.items)];if(e.enum&&Array.isArray(e.enum)&&e.enum.length>0)return`<${e.enum.join("|")}>`;if(t==="string")return"<string>";if(t==="number"||t==="integer")return 0;if(t==="boolean")return!1;if(e.description)return`<${e.description}>`;if(e.nullable||e.oneOf||e.anyOf){let r=e.oneOf?.find(o=>o.type!=="null")||e.anyOf?.find(o=>o.type!=="null");return r?this._buildExample(r):null}return"<value>"}}});import Zt from"axios";import{homedir as Xt}from"node:os";import{join as Vt}from"node:path";import{existsSync as qt,readFileSync as Qt}from"node:fs";import{toJSONSchema as eo}from"zod";function to(){if(process.env.OPENAI_PROXY_TOKEN)return c.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return c.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let n=Vt(Xt(),".zibby","config.json");if(qt(n)){let e=JSON.parse(Qt(n,"utf-8"));if(e.sessionToken)return c.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(n){c.debug(`[Auth] Could not read zibby login session: ${n.message}`)}return null}function oo(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function ee(n){if(!(typeof n!="object"||n===null)){if(Object.keys(n).length===0){n.type="object",n.additionalProperties=!0;return}if(n.type||(n.properties?n.type="object":n.items&&(n.type="array")),n.type==="object")if(n.properties){for(let[e,t]of Object.entries(n.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(n.properties[e]={type:["object","null"]});n.additionalProperties=!1,n.required=Object.keys(n.properties),Object.values(n.properties).forEach(ee)}else"additionalProperties"in n||(n.additionalProperties=!0);n.type==="array"&&n.items&&ee(n.items),n.anyOf&&n.anyOf.forEach(ee),n.oneOf&&n.oneOf.forEach(ee),n.allOf&&n.allOf.forEach(ee)}}async function Ve(n,e){c.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=to();if(!t)throw new Error("Authentication required for structured output processing.\n Local development: Run `zibby login`\n CI/CD: Set ZIBBY_USER_TOKEN environment variable (Personal Access Token from UI settings)");let r=oo();c.info(`\u{1F517} Using OpenAI proxy: ${r}`);let o=eo(e),i=o;if(o.$ref&&o.definitions){let f=o.$ref.split("/").pop();i=o.definitions[f]||o,c.debug(`Extracted schema from $ref: ${f}`)}delete i.$schema,ee(i);let s=4e5,l=n;n.length>s&&(c.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${n.length} chars) exceeds limit, keeping last ${s} chars`),l=`... [truncated early content] ...
|
|
25
25
|
${n.slice(-s)}`);let a=`Extract and format the following information into structured JSON matching the schema.
|
|
26
26
|
|
|
27
27
|
RAW CONTENT:
|
|
@@ -42,10 +42,10 @@ ${ot}`,e.col=rt))}return n(s,r,o)}}var ro,le,no,Qe,Pe,et,tt,Re,ot,rt,Me,z,_e=P((
|
|
|
42
42
|
`)}stepTool(e){this._origStdoutWrite?this._writeDot(et,e):process.stdout.write.bind(process.stdout)(`${le} ${et} ${e}
|
|
43
43
|
`)}stepMemory(e){let t=D.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(tt,t):process.stdout.write.bind(process.stdout)(`${le} ${tt} ${t}
|
|
44
44
|
`)}stepFail(e){this._origStdoutWrite?this._writeDot(Re,D.red(e)):process.stdout.write.bind(process.stdout)(`${le} ${Re} ${D.red(e)}
|
|
45
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${no} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:o}=t;if(o)for(let s of o)this._rawWrite(`${Pe} ${s}`);let i=r?D.dim(` ${nt(r)}`):"";this._rawWrite(`${Qe} ${D.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:o}=r,i=o?D.dim(` ${nt(o)}`):"";this._rawWrite(`${Re} ${D.red(t)}`),this._rawWrite(`${Qe} ${D.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(D.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){this._rawWrite(D.green.bold("\u2713 Workflow completed"))}},z=new Me});import{copyFileSync as so,existsSync as Le,lstatSync as io,mkdirSync as it,rmSync as lo,symlinkSync as ao,unlinkSync as co}from"node:fs";import{join as W}from"node:path";import{homedir as uo}from"node:os";import{randomBytes as fo}from"node:crypto";function lt(n){return!(!n||typeof n!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function at(n){let e=W(n||process.cwd(),".zibby","tmp");it(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${fo(4).toString("hex")}`,r=W(e,`cursor-agent-home-${t}`),o=W(r,".cursor");it(o,{recursive:!0});let i=uo(),s=W(i,".cursor");if(Le(s))for(let l of po){let a=W(s,l);if(Le(a))try{so(a,W(o,l))}catch{}}if(process.platform==="darwin"){let l=W(i,"Library");if(Le(l))try{ao(l,W(r,"Library"))}catch{}}return r}function ct(n){if(!(!n||typeof n!="string"))try{let e=W(n,"Library");try{io(e).isSymbolicLink()&&co(e)}catch{}lo(n,{recursive:!0,force:!0})}catch{}}var po,ut=P(()=>{po=["cli-config.json","config.json","auth.json","argv.json"]});import{spawn as go,execSync as X}from"node:child_process";import{writeFileSync as ft,readFileSync as dt,mkdirSync as pt,existsSync as ae,accessSync as gt,constants as mt,unlinkSync as mo}from"node:fs";import{join as J,resolve as ho}from"node:path";import{homedir as ce}from"node:os";var ue,ht=P(()=>{H();K();Z();Xe();Y();Ce();Ne();qe();_e();ut();ue=class extends j{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[J(ce(),".local","bin","cursor-agent"),J(ce(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"];for(let r of t)try{if(r.startsWith("/")){gt(r,mt.X_OK);let o=X(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(o&&o.length>0)return c.debug(`[Cursor] Found agent at: ${r} (version: ${o.trim().slice(0,50)})`),!0}else{let o=X(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!o)continue;let i=X(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(i&&i.length>0)return c.debug(`[Cursor] Found '${r}' in PATH at ${o} (version: ${i.trim().slice(0,50)})`),!0}}catch{continue}return c.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:r=process.cwd(),print:o=!1,schema:i=null,skills:s=null,sessionPath:l=null,nodeName:a=null,timeout:u=ye.CURSOR_AGENT_DEFAULT,config:f={}}=t,h=f?.agent?.strictMode||!1,m=t.model??f?.agent?.cursor?.model??B.CURSOR;c.debug(`[Cursor] Invoking (model: ${m}, timeout: ${u/1e3}s, skills: ${JSON.stringify(s)})`);let w=(this._setupMcpConfig(l,r,f,s,a)||{}).isolatedMcpHome??null,
|
|
45
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${no} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:o}=t;if(o)for(let s of o)this._rawWrite(`${Pe} ${s}`);let i=r?D.dim(` ${nt(r)}`):"";this._rawWrite(`${Qe} ${D.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:o}=r,i=o?D.dim(` ${nt(o)}`):"";this._rawWrite(`${Re} ${D.red(t)}`),this._rawWrite(`${Qe} ${D.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(D.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){this._rawWrite(D.green.bold("\u2713 Workflow completed"))}},z=new Me});import{copyFileSync as so,existsSync as Le,lstatSync as io,mkdirSync as it,rmSync as lo,symlinkSync as ao,unlinkSync as co}from"node:fs";import{join as W}from"node:path";import{homedir as uo}from"node:os";import{randomBytes as fo}from"node:crypto";function lt(n){return!(!n||typeof n!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function at(n){let e=W(n||process.cwd(),".zibby","tmp");it(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${fo(4).toString("hex")}`,r=W(e,`cursor-agent-home-${t}`),o=W(r,".cursor");it(o,{recursive:!0});let i=uo(),s=W(i,".cursor");if(Le(s))for(let l of po){let a=W(s,l);if(Le(a))try{so(a,W(o,l))}catch{}}if(process.platform==="darwin"){let l=W(i,"Library");if(Le(l))try{ao(l,W(r,"Library"))}catch{}}return r}function ct(n){if(!(!n||typeof n!="string"))try{let e=W(n,"Library");try{io(e).isSymbolicLink()&&co(e)}catch{}lo(n,{recursive:!0,force:!0})}catch{}}var po,ut=P(()=>{po=["cli-config.json","config.json","auth.json","argv.json"]});import{spawn as go,execSync as X}from"node:child_process";import{writeFileSync as ft,readFileSync as dt,mkdirSync as pt,existsSync as ae,accessSync as gt,constants as mt,unlinkSync as mo}from"node:fs";import{join as J,resolve as ho}from"node:path";import{homedir as ce}from"node:os";var ue,ht=P(()=>{H();K();Z();Xe();Y();Ce();Ne();qe();_e();ut();ue=class extends j{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[J(ce(),".local","bin","cursor-agent"),J(ce(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"];for(let r of t)try{if(r.startsWith("/")){gt(r,mt.X_OK);let o=X(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(o&&o.length>0)return c.debug(`[Cursor] Found agent at: ${r} (version: ${o.trim().slice(0,50)})`),!0}else{let o=X(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!o)continue;let i=X(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(i&&i.length>0)return c.debug(`[Cursor] Found '${r}' in PATH at ${o} (version: ${i.trim().slice(0,50)})`),!0}}catch{continue}return c.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:r=process.cwd(),print:o=!1,schema:i=null,skills:s=null,sessionPath:l=null,nodeName:a=null,timeout:u=ye.CURSOR_AGENT_DEFAULT,config:f={}}=t,h=f?.agent?.strictMode||!1,m=t.model??f?.agent?.cursor?.model??B.CURSOR;c.debug(`[Cursor] Invoking (model: ${m}, timeout: ${u/1e3}s, skills: ${JSON.stringify(s)})`);let w=(this._setupMcpConfig(l,r,f,s,a)||{}).isolatedMcpHome??null,k=[J(ce(),".local","bin","cursor-agent"),J(ce(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],g=null;for(let E of k)try{if(E.startsWith("/"))gt(E,mt.X_OK),X(`"${E}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!X(`which ${E}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");X(`${E} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}g=E,c.debug(`[Agent] Using binary: ${E}`);break}catch(p){c.debug(`[Agent] Binary '${E}' check failed: ${p.message}`);continue}if(!g)throw new Error(`Cursor Agent CLI not found or not working.
|
|
46
46
|
|
|
47
47
|
Checked paths:
|
|
48
|
-
${
|
|
48
|
+
${k.map(E=>` - ${E}`).join(`
|
|
49
49
|
`)}
|
|
50
50
|
|
|
51
51
|
Install cursor-agent:
|
|
@@ -60,48 +60,55 @@ ${x}`}let C=process.env.CURSOR_API_KEY,b=C?` | key: ***${C.slice(-4)}`:" | key:
|
|
|
60
60
|
\u25C6 Model: ${m||"auto"}${b}
|
|
61
61
|
`);let A=(await import("chalk")).default;console.log(`
|
|
62
62
|
${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 R=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",m||"auto"];if(process.env.CURSOR_API_KEY&&R.push("--api-key",process.env.CURSOR_API_KEY),R.push(e),c.debug(`[Agent] Prompt: ${e.length} chars, model: ${m||"auto"}`),c.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${m||"auto"} (from .zibby.config.js agent.cursor.model)
|
|
63
|
-
`)}catch{}let N,y=null;try{let E=l||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);N=await this._spawnWithStreaming(g,R,r,u,null,E,w)}catch(E){y=E}let
|
|
64
|
-
`)
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
${
|
|
68
|
-
|
|
69
|
-
|
|
63
|
+
`)}catch{}let N,y=null;try{let E=l||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);N=await this._spawnWithStreaming(g,R,r,u,null,E,w)}catch(E){y=E}let $=N?.stdout||"";if(i){let E=typeof i.parse=="function",p=null,x=!!(_&&ae(_));if(_&&c.info(`[Agent] Result file: ${x?"present":"missing"} at ${_}`),x)try{let d=dt(_,"utf-8").trim();p=JSON.parse(d),c.info(`[Agent] Parsed JSON from result file OK (${d.length} chars) \u2192 object ready for validation`),y&&c.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(d){c.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${d.message}`)}else if(y)c.warn(`[Agent] Result file missing at ${_} (agent process error \u2014 may still recover if strictMode repairs)`);else throw c.error(`\u274C [Agent] Result file was never created at ${_}`),new Error(`Agent did not write required result file at ${_}`);if(p&&E)try{let d=i.parse(p);return c.info("\u2705 [Agent] Zod validation passed for structured result file"),h&&c.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:$,structured:d}}catch(d){let v=d.issues?d.issues.map(I=>` - ${I.path.join(".")}: ${I.message}`).join(`
|
|
64
|
+
`):d.message?.slice(0,400);if(c.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
|
|
65
|
+
${v}`),c.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
|
|
66
|
+
${JSON.stringify(p,null,2).slice(0,500)}`),!h)throw new Error(`Agent output failed schema validation:
|
|
67
|
+
${v}
|
|
68
|
+
|
|
69
|
+
The agent wrote invalid data that doesn't match the required outputSchema.
|
|
70
|
+
Enable strictMode in .zibby.config.js for automatic repair.`,{cause:d})}else{if(p)return c.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),h&&c.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:$,structured:p};x&&c.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(h&&!y){let d=N.parsedText,v=p?JSON.stringify(p):d;c.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${v.length} chars in)`);try{let I=await Ve(v,i);if(E){let M=i.parse(I.structured);return c.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:$,structured:M}}return{raw:$,...I}}catch(I){if(c.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${I.message}`),p)return c.warn("[Agent] Using agent's original result file as fallback"),{raw:$,structured:p}}}if(y)throw y;let O=x?p==null?"file existed but JSON.parse failed \u2014 see WARN log above":E?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw c.error(`\u274C [Agent] No validated structured output: ${O}`),c.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 ${_}. Enable strictMode for proxy fallback.`)}if(y)throw y;return this._extractFinalResult($)||N?.parsedText||$}_extractFinalResult(e){if(!e)return null;let t=e.split(`
|
|
71
|
+
`),r=null;for(let o of t){let i=o.trim();if(i)try{let s=JSON.parse(i);if(s.type==="assistant"&&s.message?.content){let l=s.message.content;if(Array.isArray(l)){let a=l.filter(u=>u.type==="text"&&u.text).map(u=>u.text).join("");a&&(r=a)}else typeof l=="string"&&l&&(r=l)}}catch{}}return r?.trim()||null}_setupMcpConfig(e,t,r,o=null,i=null){let s=r?.headless,l=J(ce(),".cursor"),a=J(l,"mcp.json"),u={};if(ae(a))try{u=JSON.parse(dt(a,"utf-8"))}catch{}let f=u.mcpServers||{},h=r?.paths?.output||Ye,m=J(t||process.cwd(),h,He),S=Array.isArray(o)?o.map(g=>U(g)).filter(Boolean):[...Ae()].map(([,g])=>g),w=new Set;for(let g of S)typeof g.resolve=="function"&&(w.has(g.serverName)||(w.add(g.serverName),this._ensureSkillConfigured(f,g,e,m,i,s)));if(e){let g=U("browser");g&&typeof g.resolve=="function"&&!w.has(g.serverName)&&this._ensureSkillConfigured(f,g,e,m,"execute_live",s)}if(Object.keys(f).length===0)return c.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let k=`${JSON.stringify({mcpServers:f},null,2)}
|
|
72
|
+
`;if(lt(e)){let g=at(t||process.cwd()),_=J(g,".cursor","mcp.json");return ft(_,k,"utf8"),c.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${g} | servers: ${Object.keys(f).join(", ")}`),{isolatedMcpHome:g}}return ae(l)||pt(l,{recursive:!0}),ft(a,k,"utf8"),c.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(f).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,o,i=null,s){let l=t.cursorKey||t.serverName,a=e[l]?l:e[t.serverName]?t.serverName:null;if(a&&r){let f=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:i,headless:s}):null;f?.args?e[a].args=f.args:e[a].args=(e[a].args||[]).map(S=>S.startsWith("--output-dir=")?`--output-dir=${r}`:S);let h=f?.env||{},m=t.sessionEnvKey?{[t.sessionEnvKey]:o}:{};e[a].env={...e[a].env||{},...h,...m},c.debug(`[MCP] Updated ${a} session \u2192 ${r}`);return}if(a)return;let u=t.resolve({sessionPath:r,nodeName:i,headless:s});u&&(e[l]={...u,...t.sessionEnvKey&&{env:{...u.env||{},[t.sessionEnvKey]:o}}},c.debug(`[MCP] Configured ${l}`))}_spawnWithStreaming(e,t,r,o,i=null,s=null,l=null){return new Promise((a,u)=>{let f=Date.now(),h="",m="",S=Date.now(),w=0,k=!1,g=null,_=!1,C=!1,b=null;if(s)try{b=J(ho(String(s)),Ze)}catch{b=null}let A=!1,R=()=>{A||(A=!0,ct(l))},N={...process.env};l&&(N.HOME=l,process.platform==="win32"&&(N.USERPROFILE=l),c.debug(`[Agent] cursor-agent HOME=${l} (isolated MCP config)`));let y=go(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:N});c.debug(`[Agent] PID: ${y.pid}`),y.stdin.on("error",d=>{d.code!=="EPIPE"&&c.warn(`[Agent] stdin error: ${d.message}`)}),y.stdout.on("error",d=>{d.code!=="EPIPE"&&c.warn(`[Agent] stdout error: ${d.message}`)}),y.stderr.on("error",d=>{d.code!=="EPIPE"&&c.warn(`[Agent] stderr error: ${d.message}`)}),i?(y.stdin.write(i,d=>{d&&d.code!=="EPIPE"&&c.warn(`[Agent] Failed to write to stdin: ${d.message}`),y.stdin.end()}),c.debug(`[Agent] Prompt also piped to stdin (${i.length} chars)`)):y.stdin.end();let $=null;b&&($=setInterval(()=>{if(!(k||C))try{if(ae(b)){k=!0,g="studio-stop";try{mo(b)}catch{}c.warn("\u{1F6D1} Studio stop requested \u2014 terminating Cursor agent (and MCP browser session)"),y.kill("SIGTERM"),setTimeout(()=>{y.killed||y.kill("SIGKILL")},2e3)}}catch{}},600));let T=new Set,E=new Date(f).toISOString().replace(/\.\d+Z$/,""),p=setInterval(()=>{let d=Math.round((Date.now()-f)/1e3),v=Math.round((Date.now()-S)/1e3),I=[];try{let G=Math.ceil(d/60)+1,L=X(`find "${r}" -type f -mmin -${G} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(L)for(let $e of L.split(`
|
|
73
|
+
`)){let Oe=$e.replace(`${r}/`,"");T.has(Oe)||(T.add(Oe),I.push(Oe))}}catch{}let M="";I.length>0&&(M=` | \u{1F4C1} new: ${I.map(L=>L.split("/").pop()).join(", ")}`),T.size>0&&(M+=` | \u{1F4E6} total: ${T.size} files`),c.debug(`\u{1F493} [Agent] Running for ${d}s | ${w} lines output${M}`),w===0&&d>=30&&T.size===0&&(d<35&&c.warn(`\u26A0\uFE0F [Agent] No output after ${d}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),d>=60&&(k=!0,g=g||"stall",c.error(`\u274C [Agent] No response after ${d}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),y.kill("SIGTERM"),setTimeout(()=>{y.killed||y.kill("SIGKILL")},3e3)))},3e4),x=setTimeout(()=>{k=!0,g=g||"timeout";let d=Math.round((Date.now()-f)/1e3);c.error(`\u23F1\uFE0F [Agent] Timeout after ${d}s \u2014 killing process (PID: ${y.pid})`),h.trim()&&c.warn(`\u{1F4E4} [Agent] Partial output (${h.length} chars) before timeout:
|
|
74
|
+
${h.slice(-2e3)}`),y.kill("SIGTERM"),setTimeout(()=>{y.killed||y.kill("SIGKILL")},5e3)},o),O=new q;O.onToolCall=(d,v)=>{let I=d,M=v;if(d==="mcpToolCall"&&v?.name)I=v.name.replace(/^mcp_+[^_]+_+/,""),I.includes("-")&&I.split("-")[0]===I.split("-")[1]&&(I=I.split("-")[0]),M=v.args??v.input??v;else{if(d==="readToolCall"||d==="editToolCall"||d==="writeToolCall")return;(d.startsWith("mcp__")||d.includes("ToolCall"))&&(I=d.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(I.includes("memory")?z.stepMemory(`Tool: ${I}`):z.stepTool(`Tool: ${I}`),M!=null&&typeof M=="object"&&Object.keys(M).length>0&&!C){let L=JSON.stringify(M),$e=L.length>100?`${L.substring(0,100)}...`:L;console.log(` Input: ${$e}`)}},y.stdout.on("data",d=>{let v=d.toString();h+=v,S=Date.now(),_||(_=!0);let I=O.processChunk(v);I&&!C&&process.stdout.write(I);let M=v.split(`
|
|
75
|
+
`).filter(G=>G.trim());w+=M.length}),y.stderr.on("data",d=>{let v=d.toString();m+=v,S=Date.now(),_||(_=!0);let I=v.split(`
|
|
76
|
+
`).filter(M=>M.trim());for(let M of I)c.warn(`\u26A0\uFE0F [Agent stderr] ${M}`)}),y.on("close",(d,v)=>{C=!0,R(),clearTimeout(x),clearInterval(p),$&&clearInterval($),O.flush();let I=Math.round((Date.now()-f)/1e3);if(c.debug(`[Agent] Exited: code=${d}, signal=${v}, elapsed=${I}s, output=${h.length} chars`),k){if(g==="studio-stop"){u(new Error("Stopped from Zibby Studio"));return}u(new Error(`Cursor Agent timed out after ${I}s (limit: ${o/1e3}s). ${w} lines produced. Last output ${Math.round((Date.now()-S)/1e3)}s ago. ${h.trim()?`
|
|
70
77
|
Partial output (last 500 chars):
|
|
71
78
|
${h.slice(-500)}`:"No output captured."}`));return}if(d!==0){u(new Error(`Cursor Agent failed: exit code ${d}, signal ${v}. ${m.trim()?`
|
|
72
79
|
Stderr: ${m.slice(-1e3)}`:""}${h.trim()?`
|
|
73
|
-
Stdout (last 500 chars): ${h.slice(-500)}`:""}`));return}let M
|
|
80
|
+
Stdout (last 500 chars): ${h.slice(-500)}`:""}`));return}let M=O.getResult(),G=M?JSON.stringify(M,null,2):O.getRawText()||h||"";a({stdout:h||m||"",parsedText:G})}),y.on("error",d=>{R(),clearTimeout(x),clearInterval(p),$&&clearInterval($),u(new Error(`Cursor Agent spawn error: ${d.message}
|
|
74
81
|
Binary: ${e}
|
|
75
82
|
This usually means the binary is not in PATH. Try:
|
|
76
|
-
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}}});import{query as yo}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as _o}from"zod-to-json-schema";var fe,yt=P(()=>{H();K();_e();Z();Y();fe=class extends j{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!process.env.ANTHROPIC_API_KEY;return t||c.debug("ClaudeAgentStrategy: ANTHROPIC_API_KEY not set"),t}async invoke(e,t={}){let{model:r,workspace:o=process.cwd(),schema:i=null,images:s=[],skills:l=null,sessionPath:a=null,nodeName:u=null,timeout:f,config:h={}}=t,m=r;(!m||m==="auto")&&(c.debug(`Model is '${m||"undefined"}', using default: ${B.CLAUDE}`),m=B.CLAUDE);let S=
|
|
77
|
-
\u25C6 Model: ${S}${
|
|
83
|
+
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}}});import{query as yo}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as _o}from"zod-to-json-schema";var fe,yt=P(()=>{H();K();_e();Z();Y();fe=class extends j{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!process.env.ANTHROPIC_API_KEY;return t||c.debug("ClaudeAgentStrategy: ANTHROPIC_API_KEY not set"),t}async invoke(e,t={}){let{model:r,workspace:o=process.cwd(),schema:i=null,images:s=[],skills:l=null,sessionPath:a=null,nodeName:u=null,timeout:f,config:h={}}=t,m=r;(!m||m==="auto")&&(c.debug(`Model is '${m||"undefined"}', using default: ${B.CLAUDE}`),m=B.CLAUDE);let S=Ie[m]||m;Ie[m]&&m!==S&&c.debug(`Mapped model: ${m} \u2192 ${S}`),c.debug(`Invoking Claude Agent SDK with model: ${S}, skills: ${JSON.stringify(l)}`);let w=process.env.ANTHROPIC_API_KEY,k=w?` | key: ***${w.slice(-4)}`:" | key: not set";console.log(`
|
|
84
|
+
\u25C6 Model: ${S}${k}
|
|
78
85
|
`);let g=(await import("chalk")).default;console.log(`
|
|
79
|
-
${g.bold("Prompt sent to LLM:")}`),console.log(g.dim("\u2500".repeat(60))),console.log(g.dim(e)),console.log(g.dim("\u2500".repeat(60)));let{allowedTools:_,mcpServers:C}=this._resolveSkills(l,{sessionPath:a,workspace:o,nodeName:u});try{let b={cwd:o,allowedTools:_,permissionMode:"bypassPermissions",model:S,...Object.keys(C).length>0&&{mcpServers:C}};if(i){let x=typeof i.parse=="function"?_o(i,{target:"openApi3"}):i;b.outputFormat={type:"json_schema",schema:x},c.debug("Structured output enforced via SDK outputFormat")}c.debug(`Agent SDK options: ${JSON.stringify({cwd:b.cwd,toolCount:_.length,permissionMode:b.permissionMode,model:b.model,hasOutputFormat:!!b.outputFormat})}`);let A="",R=0,N=[];c.debug("Starting Claude Agent SDK query stream");let y;try{y=yo({prompt:e,options:b})}catch(p){throw c.error(`Failed to initialize Claude Agent SDK: ${p.message}`),p}let
|
|
80
|
-
\u25C6 Model: ${S}${
|
|
86
|
+
${g.bold("Prompt sent to LLM:")}`),console.log(g.dim("\u2500".repeat(60))),console.log(g.dim(e)),console.log(g.dim("\u2500".repeat(60)));let{allowedTools:_,mcpServers:C}=this._resolveSkills(l,{sessionPath:a,workspace:o,nodeName:u});try{let b={cwd:o,allowedTools:_,permissionMode:"bypassPermissions",model:S,...Object.keys(C).length>0&&{mcpServers:C}};if(i){let x=typeof i.parse=="function"?_o(i,{target:"openApi3"}):i;b.outputFormat={type:"json_schema",schema:x},c.debug("Structured output enforced via SDK outputFormat")}c.debug(`Agent SDK options: ${JSON.stringify({cwd:b.cwd,toolCount:_.length,permissionMode:b.permissionMode,model:b.model,hasOutputFormat:!!b.outputFormat})}`);let A="",R=0,N=[];c.debug("Starting Claude Agent SDK query stream");let y;try{y=yo({prompt:e,options:b})}catch(p){throw c.error(`Failed to initialize Claude Agent SDK: ${p.message}`),p}let $=null,T=0,E=3;try{for await(let p of y){if(N.push(p),p.type==="error"||p.error){let O=p.error?.message||p.error||p.message||"Unknown API error";throw new Error(typeof O=="string"?O:JSON.stringify(O))}let x=JSON.stringify(p.message?.content||p.text||"").slice(0,200);if(x===$){if(T++,T>=E){let O=(p.message?.content?.[0]?.text||p.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${T}x repeated): ${O}`)}}else $=x,T=1;if(p.type==="assistant"||p.constructor?.name==="AssistantMessage"){let O=p.message?.content||p.content||[];for(let d of O)if(d.type==="thinking"&&d.thinking)console.log(`${d.thinking.substring(0,200)}${d.thinking.length>200?"...":""}`);else if(d.type==="text"&&d.text)A+=d.text,d.text.length<500?console.log(`${d.text}`):console.log(`${d.text.substring(0,200)}... (${d.text.length} chars)`);else if(d.type==="tool_use"){R++,d.name.includes("memory")?z.stepMemory(`Tool: ${d.name}`):z.stepTool(`Tool: ${d.name}`);let I=JSON.stringify(d.input).substring(0,100);console.log(` Input: ${I}${JSON.stringify(d.input).length>100?"...":""}`)}}else if(!(p.type==="user"&&p.tool_use_result)){if(p.type==="result"||p.constructor?.name==="ResultMessage"){let O=p.result||p.text||p.content||A;if(i){if(p.structured_output){c.debug("Using SDK native structured_output");let v=typeof i.parse=="function"?i.parse(p.structured_output):p.structured_output;return{raw:O,structured:v}}if(O){let d=this._extractJson(O,i);if(d)return{raw:O,structured:d}}c.warn(`Could not extract structured output \u2014 returning raw text (${(O||"").length} chars)`)}return O||""}}}if(c.warn(`Agent SDK ended without result. Collected ${N.length} messages`),A.length>0)return c.debug("Returning accumulated text from messages"),A;throw new Error("Claude Agent SDK query ended without result")}catch(p){throw c.error(`Error during query stream: ${p.message}`),p}}catch(b){throw c.error("Claude Agent SDK call failed",{error:b.message}),b}}_resolveSkills(e,t){if(e===null)return c.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return c.debug("Default IDE skills for code generation"),{allowedTools:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};let r=[],o={};for(let i of e){let s=U(i);if(!s){c.warn(`Unknown skill "${i}" \u2014 skipping`);continue}if(s.allowedTools&&r.push(...s.allowedTools),typeof s.resolve=="function"){let l=s.resolve(t);l&&(o[s.serverName]=l,c.debug(`MCP: ${s.serverName} \u2192 ${l.command} ${l.args[0]}`))}}return{allowedTools:r,mcpServers:o}}_extractJson(e,t){let r=[()=>{if(e.includes("===JSON_START===")){let o=e.indexOf("===JSON_START===")+16,i=e.indexOf("===JSON_END===");return e.substring(o,i).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("{"),i=e.lastIndexOf("}");if(o!==-1&&i>o)return e.substring(o,i+1)}];for(let o of r)try{let i=o();if(!i)continue;let s=JSON.parse(i);if(typeof s!="object"||s===null)continue;return typeof t.parse=="function"?t.parse(s):s}catch{}return null}}});import{execSync as So}from"node:child_process";import{zodToJsonSchema as wo}from"zod-to-json-schema";var de,_t=P(()=>{H();K();_e();Z();Y();de=class extends j{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.CODEX_API_KEY))return c.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 c.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:r,workspace:o=process.cwd(),schema:i=null,skills:s=null,sessionPath:l=null,nodeName:a=null,timeout:u,config:f={}}=t,{Codex:h}=await import("@openai/codex-sdk"),m=r;(!m||m==="auto")&&(c.debug(`Model is '${m||"undefined"}', using default: ${B.CODEX}`),m=B.CODEX);let S=ke[m]||m;ke[m]&&m!==S&&c.debug(`Mapped model: ${m} \u2192 ${S}`),c.debug(`Invoking Codex SDK with model: ${S}, skills: ${JSON.stringify(s)}`);let w=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;w&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=w);let k=w?` | key: ***${w.slice(-4)}`:" | key: not set";console.log(`
|
|
87
|
+
\u25C6 Model: ${S}${k}
|
|
81
88
|
`);let g=(await import("chalk")).default;console.log(`
|
|
82
|
-
${g.bold("Prompt sent to LLM:")}`),console.log(g.dim("\u2500".repeat(60))),console.log(g.dim(e)),console.log(g.dim("\u2500".repeat(60)));let _=this._resolveSkillsToMcp(s,{sessionPath:l,workspace:o,nodeName:a}),C={};Object.keys(_).length>0&&(C.mcp_servers=_,c.debug(`[Codex] MCP servers: ${Object.keys(_).join(", ")}`));let A=new h({...Object.keys(C).length>0&&{config:C}}).startThread({workingDirectory:o,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),R=i&&typeof i.parse=="function",N={};if(i)try{let y=R?wo(i,{target:"openAi"}):i;N.outputSchema=y,c.debug("Structured output via SDK outputSchema")}catch(y){c.warn(`[Codex] Schema conversion failed, will extract from text: ${y.message}`)}try{let{events:y}=await A.runStreamed(e,N)
|
|
89
|
+
${g.bold("Prompt sent to LLM:")}`),console.log(g.dim("\u2500".repeat(60))),console.log(g.dim(e)),console.log(g.dim("\u2500".repeat(60)));let _=this._resolveSkillsToMcp(s,{sessionPath:l,workspace:o,nodeName:a}),C={};Object.keys(_).length>0&&(C.mcp_servers=_,c.debug(`[Codex] MCP servers: ${Object.keys(_).join(", ")}`));let A=new h({...Object.keys(C).length>0&&{config:C}}).startThread({workingDirectory:o,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),R=i&&typeof i.parse=="function",N={};if(i)try{let y=R?wo(i,{target:"openAi"}):i;N.outputSchema=y,c.debug("Structured output via SDK outputSchema")}catch(y){c.warn(`[Codex] Schema conversion failed, will extract from text: ${y.message}`)}try{let{events:y}=await A.runStreamed(e,N),$=0,T="";for await(let E of y){let p=E.type;if(p==="item.completed"){let x=E.item,O=x?.type;if(O==="mcp_tool_call"){$++;let d=`${x.server}/${x.tool}`;if(z.stepTool(`Tool: ${d}`),x.arguments){let v=JSON.stringify(x.arguments),I=v.length>100?`${v.substring(0,100)}...`:v;console.log(` Input: ${I}`)}}else if(O==="tool_call"||O==="function_call"||O==="command_execution"){$++;let d=x.name||x.tool||x.command||"unknown";z.stepTool(`Tool: ${d}`)}else O==="agent_message"&&(T=x.text||"",T.length<500?console.log(T):console.log(`${T.substring(0,200)}... (${T.length} chars)`))}else p==="turn.completed"?c.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(E.usage||{})}`):c.debug(`[Codex] Event: ${p} ${JSON.stringify(E).slice(0,300)}`)}if(c.debug(`[Codex] Last agent message (${T.length} chars): ${T.slice(0,500)}`),i){if(!T)throw new Error("Codex agent returned no response");let E=JSON.parse(T),p=R?i.parse(E):E;return c.debug("\u2705 [Codex] Structured output validated"),{raw:T,structured:p}}return T||""}catch(y){let $=y.message||String(y);throw c.error(`\u274C [Codex] SDK call failed: ${$}`),$.includes("exited with code")&&(c.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),c.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),y}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let o of e){let i=U(o);if(!i){c.warn(`[Codex] Unknown skill "${o}" \u2014 skipping`);continue}if(typeof i.resolve!="function")continue;let s=i.resolve(t);if(!s)continue;let l=i.serverName||o,a={command:s.command};s.args?.length&&(a.args=s.args),s.env&&Object.keys(s.env).length>0&&(a.env=s.env),r[l]=a,c.debug(`[Codex] MCP: ${l} \u2192 ${s.command} ${(s.args||[]).join(" ")}`)}return r}}});import{execSync as bo,spawn as Eo}from"node:child_process";import{zodToJsonSchema as xo}from"zod-to-json-schema";import{existsSync as St,mkdirSync as wt,readFileSync as bt,rmSync as To,writeFileSync as Et}from"node:fs";import{join as V}from"node:path";function $o(n){if(!n)return null;let e=String(n),t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t?.[1])try{return JSON.parse(t[1].trim())}catch{}let r=e.indexOf("{");if(r<0)return null;let o=0,i=!1,s=!1,l=-1;for(let a=r;a<e.length;a++){let u=e[a];if(i){s?s=!1:u==="\\"?s=!0:u==='"'&&(i=!1);continue}if(u==='"'){i=!0;continue}if(u==="{"){o===0&&(l=a),o+=1;continue}if(u==="}"){if(o===0)continue;if(o-=1,o===0&&l>=0){let f=e.slice(l,a+1);try{return JSON.parse(f)}catch{l=-1}}}}return null}function Oo(n){let e=String(n||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return $o(e)}}function Ao(n){try{let e=JSON.parse(n);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 r=t.content.parts.map(o=>typeof o?.text=="string"?o.text:"").join("");if(r.trim())return r}}}catch{}return n}var pe,xt=P(()=>{H();K();Z();Y();Ne();Ce();pe=class extends j{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY))return c.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return bo("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:r,workspace:o=process.cwd(),schema:i=null,skills:s=null,sessionPath:l=null,nodeName:a=null,timeout:u=600*1e3}=t,f=r;(!f||f==="auto")&&(f=B.GEMINI);let h=We[f]||f,m=String(process.env.GEMINI_API_KEY||"").trim(),S=String(process.env.GOOGLE_API_KEY||"").trim(),w=this._resolveSkillsToMcp(s,{sessionPath:l,workspace:o,nodeName:a}),k=Object.keys(w).length>0,g=e,_=i&&typeof i.parse=="function",C=null;if(i){let x;try{let O=_?xo(i,{target:"openAi"}):i;x=JSON.stringify(O,null,2)}catch{x="{}"}if(k){g+=`
|
|
83
90
|
|
|
84
91
|
Write valid JSON that matches this schema:
|
|
85
|
-
${x}`;let
|
|
92
|
+
${x}`;let O=`zibby-result-${Date.now()}.json`,d=V(o,".zibby","tmp");C=V(d,O),wt(d,{recursive:!0}),g+=Q.generateFileOutputInstructions(i,C)}else g+=`
|
|
86
93
|
|
|
87
94
|
Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
|
|
88
|
-
${x}`}let b=this._createGeminiConfigDir(o,w),A=["--output-format","json"];h&&h!=="auto"&&A.push("--model",h);let R=Object.keys(w);if(R.length>0){A.push("--approval-mode","yolo");for(let x of R)A.push("--allowed-mcp-server-names",x);c.info(`[Gemini] Enabling MCP servers: ${R.join(", ")}`)}else s&&s.length>0&&c.warn(`[Gemini] Skills requested but no MCP servers configured: ${s.join(", ")}`);A.push("-p",g);let N={...process.env,GEMINI_CLI_HOME:b};m?(N.GEMINI_API_KEY=m,delete N.GOOGLE_API_KEY):S&&(N.GOOGLE_API_KEY=S,delete N.GEMINI_API_KEY),c.debug(`[Gemini] Command: gemini ${A.slice(0,8).join(" ")}... (${A.length} total args)`),c.debug(`[Gemini] Config home: ${b}`),c.debug(`[Gemini] GEMINI_CLI_HOME env: ${N.GEMINI_CLI_HOME}`);let y=""
|
|
95
|
+
${x}`}let b=this._createGeminiConfigDir(o,w),A=["--output-format","json"];h&&h!=="auto"&&A.push("--model",h);let R=Object.keys(w);if(R.length>0){A.push("--approval-mode","yolo");for(let x of R)A.push("--allowed-mcp-server-names",x);c.info(`[Gemini] Enabling MCP servers: ${R.join(", ")}`)}else s&&s.length>0&&c.warn(`[Gemini] Skills requested but no MCP servers configured: ${s.join(", ")}`);A.push("-p",g);let N={...process.env,GEMINI_CLI_HOME:b};m?(N.GEMINI_API_KEY=m,delete N.GOOGLE_API_KEY):S&&(N.GOOGLE_API_KEY=S,delete N.GEMINI_API_KEY),c.debug(`[Gemini] Command: gemini ${A.slice(0,8).join(" ")}... (${A.length} total args)`),c.debug(`[Gemini] Config home: ${b}`),c.debug(`[Gemini] GEMINI_CLI_HOME env: ${N.GEMINI_CLI_HOME}`);let y="",$=null;try{y=await new Promise((O,d)=>{let v=Eo("gemini",A,{cwd:o,env:N,stdio:["ignore","pipe","pipe"]}),I="",M="",G=setTimeout(()=>{try{v.kill("SIGTERM")}catch{}},u);v.stdout.on("data",L=>{I+=L.toString()}),v.stderr.on("data",L=>{M+=L.toString()}),v.on("error",L=>{clearTimeout(G),d(L)}),v.on("close",L=>{if(clearTimeout(G),L===0)return O(I.trim());d(new Error(`gemini failed with code ${L}: ${(M||I).trim()}`))})})}catch(x){$=x}finally{try{To(b,{recursive:!0,force:!0})}catch{}}let T=Ao(y).trim();if(!i){if($)throw $;return T}if(C){let x=St(C);if(c.info(`[Gemini] Result file: ${x?"present":"missing"} at ${C}`),x)try{let O=bt(C,"utf-8").trim(),d=JSON.parse(O),v=_?i.parse(d):d;return c.info("[Gemini] Structured output recovered from result file"),{raw:T,structured:v}}catch(O){c.warn(`[Gemini] Result file parse/validation failed: ${O.message}`)}else $||c.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let E=null;if(i){let x=new q;x.zodSchema=i,x.processChunk(T),x.flush(),E=x.getResult()}if(c.info(`[Gemini] Raw stdout length: ${y.length} chars`),c.info(`[Gemini] Extracted text length: ${T.length} chars`),c.info(`[Gemini] StreamParser result: ${E?"extracted":"null"}`),E||(T.length<2e3?c.info(`[Gemini] Raw text preview:
|
|
89
96
|
${T}`):c.info(`[Gemini] Raw text preview (first 1000 chars):
|
|
90
|
-
${T.slice(0,1e3)}`),E
|
|
97
|
+
${T.slice(0,1e3)}`),E=Oo(T)),!E)throw $||(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 p=_?i.parse(E):E;return{raw:T,structured:p}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let o of e){let i=U(o);if(!i||typeof i.resolve!="function")continue;let s=i.resolve(t);if(!s)continue;let l=i.cursorKey||i.serverName||o,a={command:s.command};s.args?.length&&(a.args=s.args),s.env&&Object.keys(s.env).length>0&&(a.env=s.env),s.cwd&&(a.cwd=s.cwd),r[l]=a}return r}_createGeminiConfigDir(e,t){let r=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,o=V(e||process.cwd(),".zibby","tmp",`gemini-home-${r}`),i=V(o,".gemini");wt(i,{recursive:!0});let s=V(i,"settings.json"),l={},a=V(process.env.HOME||"",".gemini","settings.json");if(St(a))try{l=JSON.parse(bt(a,"utf-8"))}catch{l={}}let u={...l,mcpServers:{...l.mcpServers&&typeof l.mcpServers=="object"?l.mcpServers:{},...t||{}}};Et(s,`${JSON.stringify(u,null,2)}
|
|
91
98
|
`,"utf-8");let f=V(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{Et(f,`${JSON.stringify(u,null,2)}
|
|
92
99
|
`,"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)}`),o}}});var ge,De=P(()=>{ge=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 te,Tt=P(()=>{De();te=class extends ge{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(r=>({id:r.id,name:r.function.name,args:JSON.parse(r.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 me,Ue=P(()=>{me=class{async fetchCompletion(e,t,r={}){throw new Error("fetchCompletion() must be implemented")}async fetchStreamingCompletion(e,t,r={}){throw new Error("fetchStreamingCompletion() must be implemented")}}});function Se(n){return Buffer.byteLength(JSON.stringify(n),"utf8")}function we(n,e){let t=String(n||"");if(t.length<=e)return t;let r=Math.max(0,e-28);return`${t.slice(0,r)}
|
|
93
100
|
|
|
94
|
-
[truncated for size budget]`}function Be(n,e=0){if(!n||typeof n!="object"||e>8)return n;if(Array.isArray(n))return n.map(r=>Be(r,e+1));let t={};for(let[r,o]of Object.entries(n))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=Be(o,e+1));return t}function
|
|
95
|
-
`);S=C.pop();for(let b of C){if(!b.startsWith("data: "))continue;let A=b.slice(6).trim();if(A==="[DONE]")continue;let R;try{R=JSON.parse(A)}catch{continue}let N=R.choices?.[0]?.delta;if(N&&(N.content&&(w+=N.content,r.onToken&&r.onToken(N.content)),N.tool_calls))for(let y of N.tool_calls){let
|
|
101
|
+
[truncated for size budget]`}function Be(n,e=0){if(!n||typeof n!="object"||e>8)return n;if(Array.isArray(n))return n.map(r=>Be(r,e+1));let t={};for(let[r,o]of Object.entries(n))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=Be(o,e+1));return t}function vo(n=[]){return n.map(e=>({...e,function:{...e.function,description:we(e.function?.description||"",180),parameters:Be(e.function?.parameters||{type:"object",properties:{}})}}))}function $t(n){let e=new Set;for(let o of n)if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let i of o.tool_calls)e.add(i.id);let t=n.filter(o=>o.role==="tool"?e.has(o.tool_call_id):!0),r=new Set;for(let o of t)o.role==="tool"&&r.add(o.tool_call_id);return t.map(o=>{if(o.role!=="assistant"||!Array.isArray(o.tool_calls)||o.tool_calls.every(a=>r.has(a.id)))return o;let{tool_calls:s,...l}=o;return{...l,content:l.content||""}})}function je(n,e={}){let t=e.maxBytes||49e3,r=e.systemMaxChars||12e3,o={...n,messages:Array.isArray(n.messages)?[...n.messages]:[],tools:Array.isArray(n.tools)?vo(n.tools):n.tools};o.messages.length>0&&o.messages[0]?.role==="system"&&(o.messages[0]={...o.messages[0],content:we(o.messages[0].content,r)});let i=!1;for(;Se(o)>t&&o.messages.length>2;)o.messages.splice(1,1),i=!0;if(i&&(o.messages=$t(o.messages)),Se(o)>t&&o.messages.length>0&&(o.messages[0]={...o.messages[0],content:we(o.messages[0].content,6e3)},i=!0),Se(o)>t){let s=o.messages.find(a=>a.role==="system")||o.messages[0],l=o.messages.slice(-2);o.messages=$t([s,...l].filter(Boolean).map((a,u)=>({...a,content:we(a.content,u===0?4e3:8e3)}))),i=!0}return{body:o,meta:{bytes:Se(o),trimmed:i,maxBytes:t,messageCount:o.messages.length}}}var Ot=P(()=>{});var At,oe,vt=P(()=>{Ue();Ot();At=n=>Buffer.byteLength(JSON.stringify(n),"utf8"),oe=class extends me{async fetchCompletion(e,t,r={}){let o=At(e),{body:i,meta:s}=je(e,r.payloadCompaction);r.onBudget?.({streaming:!1,beforeBytes:o,meta:s});let l=this.#e(r),a=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,u=await fetch(a,{method:"POST",headers:t.headers,body:JSON.stringify(i),signal:l});if(!u.ok){let f=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}: ${f}`)}return u.json()}async fetchStreamingCompletion(e,t,r={}){let o={...e,stream:!0},i=At(o),{body:s,meta:l}=je(o,r.payloadCompaction);r.onBudget?.({streaming:!0,beforeBytes:i,meta:l});let a=this.#e(r),u=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,f=await fetch(u,{method:"POST",headers:t.headers,body:JSON.stringify(s),signal:a});if(!f.ok){let g=await f.text();throw f.status===401||f.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${f.status}: ${g}`)}let h=f.body.getReader(),m=new TextDecoder,S="",w="",k=new Map;for(;;){let{done:g,value:_}=await h.read();if(g)break;S+=m.decode(_,{stream:!0});let C=S.split(`
|
|
102
|
+
`);S=C.pop();for(let b of C){if(!b.startsWith("data: "))continue;let A=b.slice(6).trim();if(A==="[DONE]")continue;let R;try{R=JSON.parse(A)}catch{continue}let N=R.choices?.[0]?.delta;if(N&&(N.content&&(w+=N.content,r.onToken&&r.onToken(N.content)),N.tool_calls))for(let y of N.tool_calls){let $=y.index??0;k.has($)||k.set($,{id:"",name:"",args:""});let T=k.get($);y.id&&(T.id=y.id),y.function?.name&&(T.name=y.function.name),y.function?.arguments!=null&&(T.args+=y.function.arguments)}}}if(k.size>0){let g=[...k.entries()].sort(([_],[C])=>_-C).map(([,_])=>({id:_.id,type:"function",function:{name:_.name,arguments:_.args}}));return{choices:[{message:{role:"assistant",content:w||null,tool_calls:g}}]}}return{choices:[{message:{role:"assistant",content:w}}]}}#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}}});var It=P(()=>{De();Tt();Ue();vt()});import{Client as Io}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as ko}from"@modelcontextprotocol/sdk/client/stdio.js";var be,kt=P(()=>{K();be=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:r,args:o=[],env:i={}}=t;c.debug(`[MCP] Starting ${e}: ${r} ${o.join(" ")}`);let s=new ko({command:r,args:o,env:{...process.env,...i}}),l=new Io({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await l.connect(s);let a={client:l,transport:s,serverConfig:t};return this.#e.set(e,a),a}async callTool(e,t,r={}){let o=this.#e.get(e);if(!o)throw new Error(`MCP server "${e}" not running`);c.debug(`[MCP] ${e}.${t}(${JSON.stringify(r).slice(0,200)})`);let i=await o.client.callTool({name:t,arguments:r});return{text:i.content?.filter(l=>l.type==="text").map(l=>l.text).join(`
|
|
96
103
|
`)||"",isError:i.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(r){c.debug(`[MCP] Error closing ${e}: ${r.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}}});import{existsSync as Co,readFileSync as No}from"node:fs";import{join as Po}from"node:path";import{homedir as Ro}from"node:os";function Mo(){try{let n=Po(Ro(),".zibby","config.json");return Co(n)?JSON.parse(No(n,"utf-8")):{}}catch{return{}}}function Ee(n){return String(n||"").replace(/\/v1\/?$/,"")}function Lo(n,e){let t=process.env.OPENAI_PROXY_URL;if(t)return Ee(t);if(n==="session")return e.proxyUrl?Ee(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(n==="byok"){let r=process.env.OPENAI_BASE_URL;return Ee(r||"https://api.openai.com")}return Ee(t||"")}function Je(){let n=Mo(),e=process.env.ZIBBY_USER_TOKEN||n.sessionToken||null,t=process.env.OPENAI_API_KEY||null,r=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),o=process.env.OPENAI_PROXY_NO_AUTH==="true",i=process.env.OPENAI_PROXY_URL,s="session";r==="byok"||r==="local"||r==="session"?s=r:e?s="session":t?s="byok":i&&o&&(s="local");let l=Lo(s,n),a={"Content-Type":"application/json"};if(s==="session"){if(!e)return{ok:!1,mode:s,reason:"missing_session_token"};a.Authorization=`Bearer ${e}`}else if(s==="byok"){if(!t)return{ok:!1,mode:s,reason:"missing_openai_api_key"};a.Authorization=`Bearer ${t}`}else if(s==="local"){if(!l)return{ok:!1,mode:s,reason:"missing_openai_proxy_url"};!o&&t&&(a.Authorization=`Bearer ${t}`)}return l?{ok:!0,mode:s,baseUrl:l,headers:a,tokenPreview:a.Authorization?`***${a.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:s,reason:"missing_base_url"}}var Ct=P(()=>{});function xe(n,e){let t=String(n??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
|
|
97
104
|
|
|
98
|
-
[tool result truncated for size]`}function Do(n,e){if(typeof n=="string")return xe(n,e);try{return xe(JSON.stringify(n),e)}catch{return xe(String(n),e)}}function Nt(n){let e=new Set;for(let o of n)if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let i of o.tool_calls)e.add(i.id);let t=n.filter(o=>o.role==="tool"?e.has(o.tool_call_id):!0),r=new Set;for(let o of t)o.role==="tool"&&r.add(o.tool_call_id);return t.map(o=>{if(o.role!=="assistant"||!Array.isArray(o.tool_calls)||o.tool_calls.every(a=>r.has(a.id)))return o;let{tool_calls:s,...l}=o;return{...l,content:l.content||""}})}function Uo(n){let e=Array.isArray(n?.messages)?n.messages:[],t=e.find(i=>i.role==="system"),r=e.slice(-4).map(i=>({...i,content:xe(i.content,i.role==="tool"?1200:2500)}));r=Nt(r);let o={...n,messages:[t,...r].filter(Boolean)};return delete o.tools,o}async function Bo({body:n,streaming:e,auth:t,options:r,fetchCompletion:o,fetchStreamingCompletion:i,onFallbackLog:s}){try{return e?await i(n,t,r):await o(n,t,r)}catch(l){let a=String(l?.message||l||"");if(!/proxy error 413|payload too large/i.test(a))throw l;let u=Uo(n);return typeof s=="function"&&s(n,u),{data:e?await i(u,t,r):await o(u,t,r),fallback:u}}}async function Pt({body:n,auth:e,options:t,streaming:r,toolContext:o,activeSkills:i,round:s,verbose:l,dependencies:a,config:u={}}){let f=u.maxToolResultChars||3e3,{fetchCompletion:h,fetchStreamingCompletion:m,onFallbackLog:S,hasToolCalls:w,getTextContent:
|
|
105
|
+
[tool result truncated for size]`}function Do(n,e){if(typeof n=="string")return xe(n,e);try{return xe(JSON.stringify(n),e)}catch{return xe(String(n),e)}}function Nt(n){let e=new Set;for(let o of n)if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let i of o.tool_calls)e.add(i.id);let t=n.filter(o=>o.role==="tool"?e.has(o.tool_call_id):!0),r=new Set;for(let o of t)o.role==="tool"&&r.add(o.tool_call_id);return t.map(o=>{if(o.role!=="assistant"||!Array.isArray(o.tool_calls)||o.tool_calls.every(a=>r.has(a.id)))return o;let{tool_calls:s,...l}=o;return{...l,content:l.content||""}})}function Uo(n){let e=Array.isArray(n?.messages)?n.messages:[],t=e.find(i=>i.role==="system"),r=e.slice(-4).map(i=>({...i,content:xe(i.content,i.role==="tool"?1200:2500)}));r=Nt(r);let o={...n,messages:[t,...r].filter(Boolean)};return delete o.tools,o}async function Bo({body:n,streaming:e,auth:t,options:r,fetchCompletion:o,fetchStreamingCompletion:i,onFallbackLog:s}){try{return e?await i(n,t,r):await o(n,t,r)}catch(l){let a=String(l?.message||l||"");if(!/proxy error 413|payload too large/i.test(a))throw l;let u=Uo(n);return typeof s=="function"&&s(n,u),{data:e?await i(u,t,r):await o(u,t,r),fallback:u}}}async function Pt({body:n,auth:e,options:t,streaming:r,toolContext:o,activeSkills:i,round:s,verbose:l,dependencies:a,config:u={}}){let f=u.maxToolResultChars||3e3,{fetchCompletion:h,fetchStreamingCompletion:m,onFallbackLog:S,hasToolCalls:w,getTextContent:k,parseToolCalls:g,buildAssistantMessage:_,buildToolResultMessage:C,executeTool:b,onToolCallLog:A,injectTools:R}=a;Array.isArray(n?.messages)&&(n.messages=Nt(n.messages));let N=await Bo({body:n,streaming:r,auth:e,options:t,fetchCompletion:h,fetchStreamingCompletion:m,onFallbackLog:S}),y=N?.data||N;if(!w(y))return{done:!0,text:k(y),body:N?.fallback||n};let $=g(y),T=N?.fallback||n;T.messages.push(_(y)),l&&typeof A=="function"&&A($);let E=await Promise.all($.map((p,x)=>(typeof t.onToolCall=="function"&&t.onToolCall(p.name,p.args,{round:s,index:x,total:$.length}),b(p,o))));for(let p=0;p<$.length;p++){let O=$[p].name==="get_skill_context"?typeof E[p]=="string"?E[p]:JSON.stringify(E[p]):Do(E[p],f);T.messages.push(C($[p].id,O))}return typeof t.onToolCall=="function"&&t.onToolCall(null),R(T,i),{done:!1,body:T}}var Rt=P(()=>{});function ne(n){!n||typeof n!="object"||(n.type==="object"&&n.properties&&(n.required=Object.keys(n.properties),n.additionalProperties=!1,Object.values(n.properties).forEach(ne)),n.type==="array"&&n.items&&ne(n.items),n.anyOf&&n.anyOf.forEach(ne),n.oneOf&&n.oneOf.forEach(ne),n.allOf&&n.allOf.forEach(ne))}function Te(n){return Array.isArray(n)?new Set(n.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function Fo(n){return Array.isArray(n)?n.map(e=>String(e||"").trim()).filter(Boolean):[]}var jo,Jo,Ge,Mt,re,Go,he,Lt=P(()=>{H();K();Z();It();kt();Y();Ct();Rt();jo=B.ASSISTANT,Jo=15,Ge="get_skill_context";Mt={maxBytes:49e3,systemMaxChars:12e3},re=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Go=n=>Buffer.byteLength(JSON.stringify(n),"utf8");he=class extends j{#e;#t;#o=new be;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new te,this.#t=e.completionProvider||new oe):(this.#e=e||new te,this.#t=new oe)}canHandle(e){return Je().ok}async invoke(e,t={}){let r=t.model&&t.model!=="auto"?t.model:jo,o=Je();if(!o.ok)throw o.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):o.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):o.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${o.reason}).`);let i=t.messages||[{role:"user",content:e}],s=o.baseUrl,l=re();if(l?await this.#g(i,r,s,o.tokenPreview||"none"):c.debug(`[Assistant] ${s} | model: ${r} | messages: ${i.length}`),t.schema)return this.#c(r,i,o,t);let a=t.activeSkills||[],u=this.#f(t),f=this.#d(a,u),h=this.#p(f),m=this.#u(t),S={...t,payloadCompaction:m},w={activeSkills:f,options:S,executionRegistry:h,capabilityPolicy:u},k=!!t.stream,g={model:r,messages:[...i],stream:!1};this.#n(g,f,u);for(let _=0;_<Jo;_++){if(t.signal?.aborted)throw new Error("Aborted");let C=await Pt({body:g,auth:o,options:S,streaming:k,toolContext:w,activeSkills:f,round:_,verbose:l,dependencies:{fetchCompletion:this.#s.bind(this),fetchStreamingCompletion:this.#a.bind(this),onFallbackLog:(b,A)=>{re()&&console.log(`413 fallback: messages ${b.messages.length} -> ${A.messages.length}, bytes=${Go(A)}`)},hasToolCalls:b=>this.#e.hasToolCalls(b),getTextContent:b=>this.#e.getTextContent(b),parseToolCalls:b=>this.#e.parseToolCalls(b),buildAssistantMessage:b=>this.#e.buildAssistantMessage(b),buildToolResultMessage:(b,A)=>this.#e.buildToolResultMessage(b,A),executeTool:(b,A)=>this.#l(b,A),onToolCallLog:async b=>{let A=(await import("chalk")).default;console.log(A.dim(` ${b.map(R=>`${R.name}(${JSON.stringify(R.args).slice(0,80)})`).join(", ")}`))},injectTools:(b,A)=>this.#n(b,A,u)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(C.done)return C.text;g.messages=C.body.messages,C.body.tools?g.tools=C.body.tools:delete g.tools}return"I hit my tool-calling limit for this turn. Please try again."}async cleanup(){await this.#o.stopAll()}#n(e,t,r=null){let o=this.#i(t,r),i=this.#e.formatTools(o);this.#e.injectToolsIntoBody(e,i)}#i(e,t=null){let r=[],o=new Set;for(let i of e){let s=U(i);if(s?.tools?.length)for(let l of s.tools)this.#r(l.name,t)&&(o.has(l.name)||(o.add(l.name),r.push({name:l.name,description:l.description,parameters:l.parameters||l.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#r(Ge,t)&&r.push({name:Ge,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"]}}),r}async#l(e,t){let{activeSkills:r,options:o,executionRegistry:i,capabilityPolicy:s}=t;if(!this.#r(e.name,s))return`Tool "${e.name}" blocked by policy`;if(e.name===Ge){let u=String(e.args?.skillId||"").trim();if(!u)return JSON.stringify({error:"skillId is required"});if(!r.includes(u))return JSON.stringify({error:`Skill "${u}" is not active`,activeSkills:r});let f=U(u);if(!f)return JSON.stringify({error:`Skill "${u}" not found`});let h=typeof f.promptFragment=="function"?f.promptFragment():f.promptFragment||"",m=(f.tools||[]).map(w=>w.name),S=JSON.stringify({skillId:u,description:f.description||"",toolNames:m,promptFragment:h||""});return re()&&(console.log(`
|
|
99
106
|
\u{1F4D6} get_skill_context("${u}") \u2192 ${S.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
107
|
`)),S}let l=i?.get(e.name)||null;if(!l)return`Unknown tool: ${e.name}`;let a=U(l.skillId);if(!a)return`Skill "${l.skillId}" not found for tool "${e.name}"`;if(l.mode==="handler")try{return a.handleToolCall(e.name,e.args,t)}catch(u){return`Error in ${e.name}: ${u.message}`}if(l.mode==="mcp")try{if(!this.#o.isRunning(a.serverName)){let f=a.resolve(o);if(!f)return`Skill "${l.skillId}" is not available (cannot start server)`;await this.#o.ensureServer(a.serverName,f)}let u=await this.#o.callTool(a.serverName,e.name,e.args);return u.text||(u.isError?"Tool call failed":"Done")}catch(u){return`MCP error (${a.serverName}): ${u.message}`}return`Skill "${l.skillId}" owns tool "${e.name}" but has no execution mode`}async#a(e,t,r){return this.#t.fetchStreamingCompletion(e,t,{...r,onBudget:({beforeBytes:o,meta:i})=>{re()&&console.log(`payload bytes (stream) before=${o} after=${i.bytes} trimmed=${i.trimmed} messages=${i.messageCount}`)}})}async#s(e,t,r){return this.#t.fetchCompletion(e,t,{...r,onBudget:({beforeBytes:o,meta:i})=>{re()&&console.log(`payload bytes before=${o} after=${i.bytes} trimmed=${i.trimmed} messages=${i.messageCount}`)}})}async#c(e,t,r,o){let{zodToJsonSchema:i}=await import("zod-to-json-schema"),s=typeof o.schema?.parse=="function",l=s?i(o.schema):o.schema;delete l.$schema,ne(l);let a={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:l,strict:!0}}},u=await this.#s(a,r,o),f=this.#e.getTextContent(u),h=JSON.parse(f),m=s?o.schema.parse(h):h;return{raw:f,structured:m}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||Mt.maxBytes),systemMaxChars:Number(t.systemMaxChars||Mt.systemMaxChars)}}#f(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:Te(t.allowTools||e.allowTools),denyTools:Te(t.denyTools||e.denyTools),denyPrefixes:Fo(t.denyPrefixes||e.denyToolPrefixes),includeSkills:Te(t.includeSkills||e.includeSkills),excludeSkills:Te(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#d(e,t){let r=t?.includeSkills||new Set,o=t?.excludeSkills||new Set;return r.size===0&&o.size===0?e:e.filter(i=>!(r.size>0&&!r.has(i)||o.has(i)))}#r(e,t){let r=String(e||"").trim();if(!r)return!1;let o=t?.allowTools;if(o&&o.size>0&&!o.has(r))return!1;let i=t?.denyTools;return!(i&&i.has(r)||(t?.denyPrefixes||[]).some(l=>r.startsWith(l)))}#p(e){let t=new Map,r=[];for(let o of e){let i=U(o);if(!i?.tools?.length)continue;let s=typeof i.handleToolCall=="function"?"handler":i.serverName&&typeof i.resolve=="function"?"mcp":null;if(s)for(let l of i.tools){let a=String(l?.name||"").trim();if(a){if(t.has(a)){r.push({tool:a,winner:t.get(a).skillId,skipped:o});continue}t.set(a,{skillId:o,mode:s})}}}if(r.length>0&&re()){let o=r.slice(0,5).map(i=>`${i.tool}:${i.winner}>${i.skipped}`).join(", ");console.log(`tool registry collisions: ${o}${r.length>5?" ...":""}`)}return t}async#g(e,t,r,o){console.log(`
|
|
101
108
|
\u25C6 Model: ${t} | proxy: ${r} | token: ${o||"none"}
|
|
102
|
-
`);let i=(await import("chalk")).default;console.log(i.bold("Prompt sent to LLM:")),console.log(i.dim("\u2500".repeat(60)));let s=!1;for(let l of e)if(l.role==="system")console.log(i.dim(`[System] ${l.content||""}`));else{s||(console.log(i.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),s=!0);let a=l.role==="user"?"Human":"AI",u=l.content?.length>200?`${l.content.slice(0,200)}...`:l.content||"";console.log(i.dim(`[${a}] ${u}`))}console.log(i.dim("\u2500".repeat(60)))}}});var Bt={};Fe(Bt,{AgentStrategy:()=>j,AssistantStrategy:()=>he,ClaudeAgentStrategy:()=>fe,CodexAgentStrategy:()=>de,CursorAgentStrategy:()=>ue,GeminiAgentStrategy:()=>pe,getAgentStrategy:()=>Ut,invokeAgent:()=>Ko});function Ut(n={}){let{state:e={},preferredAgent:t=null}=n,r=t||e.agentType||process.env.AGENT_TYPE;if(!r)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");c.debug(`Agent selection: requested=${r}`);let o=Dt.find(i=>i.getName()===r);if(!o)throw new Error(`Unknown agent '${r}'. Available: ${Dt.map(i=>i.getName()).join(", ")}`);if(c.debug(`Checking if ${r} can handle this environment...`),!o.canHandle(n)){let s={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"}[r]||"Check your environment configuration";throw new Error(`Agent '${r}' is not available. ${s}`)}return c.debug(`Using agent: ${o.getName()}`),o}async function Ko(n,e={},t={}){try{await import("@zibby/skills")}catch{}let r=Ut(e),o=e.state?.config||t.config||{},i=o.models||{},s=t.nodeName&&i[t.nodeName]||null,l=i.default||null,a=r.name,u=o.agent?.[a]?.model||null,f=s||l||u||t.model||null,h={...t,model:f,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||[];if(m.length>0&&!t.skipPromptFragments){let{getSkill:w}=await Promise.resolve().then(()=>(Y(),Ke)),
|
|
109
|
+
`);let i=(await import("chalk")).default;console.log(i.bold("Prompt sent to LLM:")),console.log(i.dim("\u2500".repeat(60)));let s=!1;for(let l of e)if(l.role==="system")console.log(i.dim(`[System] ${l.content||""}`));else{s||(console.log(i.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),s=!0);let a=l.role==="user"?"Human":"AI",u=l.content?.length>200?`${l.content.slice(0,200)}...`:l.content||"";console.log(i.dim(`[${a}] ${u}`))}console.log(i.dim("\u2500".repeat(60)))}}});var Bt={};Fe(Bt,{AgentStrategy:()=>j,AssistantStrategy:()=>he,ClaudeAgentStrategy:()=>fe,CodexAgentStrategy:()=>de,CursorAgentStrategy:()=>ue,GeminiAgentStrategy:()=>pe,getAgentStrategy:()=>Ut,invokeAgent:()=>Ko});function Ut(n={}){let{state:e={},preferredAgent:t=null}=n,r=t||e.agentType||process.env.AGENT_TYPE;if(!r)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");c.debug(`Agent selection: requested=${r}`);let o=Dt.find(i=>i.getName()===r);if(!o)throw new Error(`Unknown agent '${r}'. Available: ${Dt.map(i=>i.getName()).join(", ")}`);if(c.debug(`Checking if ${r} can handle this environment...`),!o.canHandle(n)){let s={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"}[r]||"Check your environment configuration";throw new Error(`Agent '${r}' is not available. ${s}`)}return c.debug(`Using agent: ${o.getName()}`),o}async function Ko(n,e={},t={}){try{await import("@zibby/skills")}catch{}let r=Ut(e),o=e.state?.config||t.config||{},i=o.models||{},s=t.nodeName&&i[t.nodeName]||null,l=i.default||null,a=r.name,u=o.agent?.[a]?.model||null,f=s||l||u||t.model||null,h={...t,model:f,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||[];if(m.length>0&&!t.skipPromptFragments){let{getSkill:w}=await Promise.resolve().then(()=>(Y(),Ke)),k=m.map(g=>{let _=w(g)?.promptFragment;return typeof _=="function"?_():_}).filter(Boolean);k.length>0&&(n+=`
|
|
103
110
|
|
|
104
|
-
${
|
|
111
|
+
${k.join(`
|
|
105
112
|
|
|
106
113
|
`)}`)}let S=e.state?._currentNodeConfig?.extraPromptInstructions?.trim();return S&&(n+=`
|
|
107
114
|
|
|
@@ -119,7 +126,7 @@ ${a}`),i.includes(".")||o.add(s)}}return r.length===0?n:`${n}
|
|
|
119
126
|
|
|
120
127
|
${r.join(`
|
|
121
128
|
|
|
122
|
-
`)}`}function ls(n,e={}){let{nodes:t,edges:r,nodeConfigs:o={}}=n,i=new Set,s=[],l=new Map;for(let g of t){let _=g.data?.nodeType||g.type;l.set(g.id,_),_==="decision"?i.add(g.id):s.push({id:g.id,nodeType:_,label:g.data?.label||g.id})}let a=s.some(g=>{let _=o[g.id]||{};return!_.customCode&&!_.executeCode}),{toolsPerNode:u,toolIdsByVar:f}=or(s,o),{simpleEdges:h,conditionalEdges:m}=rr(r,i),S=nr(s,r,i),w=[],
|
|
129
|
+
`)}`}function ls(n,e={}){let{nodes:t,edges:r,nodeConfigs:o={}}=n,i=new Set,s=[],l=new Map;for(let g of t){let _=g.data?.nodeType||g.type;l.set(g.id,_),_==="decision"?i.add(g.id):s.push({id:g.id,nodeType:_,label:g.data?.label||g.id})}let a=s.some(g=>{let _=o[g.id]||{};return!_.customCode&&!_.executeCode}),{toolsPerNode:u,toolIdsByVar:f}=or(s,o),{simpleEdges:h,conditionalEdges:m}=rr(r,i),S=nr(s,r,i),w=[],k=e.workflowType||"workflow";return w.push(Xo(e)),w.push(Vo(k,{usesRegisteredNodes:a})),w.push(qo(f)),w.push(Qo(k)),w.push(er(s,o)),w.push(tr(s,S,h,m,u,k)),w.filter(Boolean).join(`
|
|
123
130
|
`)}function as(n){let e={};for(let[t,r]of Object.entries(n)){let{tools:o,...i}=r;Object.keys(i).length>0&&(e[t]=i)}return e}function Xo(n){let e=n.workflowType||"workflow";return["// Generated by Zibby Visual Workflow Editor",`// ${n.projectId?`Project: ${n.projectId} | `:""}Type: ${e} | Version: ${n.version??0}`,`// Downloaded: ${new Date().toISOString()}`,"//",`// Upload back: zibby workflow upload --project <id> --type ${e}`,""].join(`
|
|
124
131
|
`)}function Vo(n,{usesRegisteredNodes:e=!0}={}){let t=["import '@zibby/skills';","import { WorkflowGraph } from '@zibby/core/framework/graph.js';","import { invokeAgent } from '@zibby/core';","import { getResolvedToolDefinitions } from '@zibby/core/framework/tool-resolver.js';"];return e&&t.push("import '@zibby/core/templates/register-nodes.js';"),t.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),t.join(`
|
|
125
132
|
`)}function qo(n){if(n.size===0)return"";let e=["// \u2500\u2500 Tool Bindings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Each call resolves skill IDs \u2192 full schemas + MCP server configs","// from the skill registry (populated by @zibby/skills import above)."];for(let[t,r]of n){let o=r.join(", ");e.push(`const ${t} = getResolvedToolDefinitions(${JSON.stringify(r)}); // ${o}`)}return e.push(""),e.join(`
|