@zibby/core 2.0.4 → 2.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/backend-client.js +1 -1
- package/dist/index.js +79 -79
- package/dist/package.json +4 -4
- package/dist/register-built-in-strategies.js +36 -36
- package/dist/strategies/claude-strategy.js +6 -6
- package/dist/strategies/index.js +61 -61
- package/dist/utils/repo-clone.js +1 -1
- package/dist/utils/repos.js +2 -2
- package/dist/utils/secure-git.js +1 -1
- package/package.json +4 -4
package/dist/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zibby/core",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.6",
|
|
4
4
|
"description": "Core test automation engine with multi-agent and multi-MCP support",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -69,9 +69,9 @@
|
|
|
69
69
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
70
70
|
"@openai/codex-sdk": "^0.143.0",
|
|
71
71
|
"@playwright/mcp": "^0.0.70",
|
|
72
|
-
"@zibby/agent-workflow": "2.0.
|
|
73
|
-
"@zibby/mcp-browser": "2.0.
|
|
74
|
-
"@zibby/skill-ids": "2.0.
|
|
72
|
+
"@zibby/agent-workflow": "2.0.6",
|
|
73
|
+
"@zibby/mcp-browser": "2.0.6",
|
|
74
|
+
"@zibby/skill-ids": "2.0.6",
|
|
75
75
|
"acorn": "^8.15.0",
|
|
76
76
|
"acorn-walk": "^8.3.5",
|
|
77
77
|
"axios": "^1.15.0",
|
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
var kt=Object.defineProperty;var wt=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var vt=(n,e)=>{for(var t in e)kt(n,t,{get:e[t],enumerable:!0})};var rt={};vt(rt,{zodToJson:()=>re});import{z as ot}from"zod";import{zodToJsonSchema as Pt}from"zod-to-json-schema";function Lt(n){if(!n||typeof n!="object")return n;if(Array.isArray(n.type))return n.type.includes("null")||(n.type=[...n.type,"null"]),n;if(typeof n.type=="string")return n.type=[n.type,"null"],n;for(let e of["anyOf","oneOf"])if(Array.isArray(n[e]))return n[e].some(t=>t&&t.type==="null")||(n[e]=[...n[e],{type:"null"}]),n;return{anyOf:[n,{type:"null"}]}}function le(n){if(!n||typeof n!="object")return n;for(let e of["$defs","definitions"])if(n[e]&&typeof n[e]=="object")for(let t of Object.keys(n[e]))n[e][t]=le(n[e][t]);for(let e of["anyOf","oneOf","allOf"])Array.isArray(n[e])&&(n[e]=n[e].map(le));if(n.properties&&typeof n.properties=="object"){n.additionalProperties=!1;let e=Object.keys(n.properties),t=new Set(Array.isArray(n.required)?n.required:[]);for(let r of e){let o=le(n.properties[r]);t.has(r)||(o=Lt(o)),n.properties[r]=o}n.required=e}return n.items&&(Array.isArray(n.items)?n.items=n.items.map(le):n.items=le(n.items)),n}function re(n,e={target:"openApi3"}){if(!n)return null;let t=e?.target==="openAi",r=null;if(typeof ot?.toJSONSchema=="function")try{r=ot.toJSONSchema(n)}catch{}if(!r)try{r=Pt(n,e)}catch{return null}if(t&&r)try{return le(r)}catch{return r}return r}var ye=wt(()=>{});import{registerStrategy as Ue}from"@zibby/agent-workflow";import{AgentStrategy as Rt,getSkill as at,NO_INTEGRATION_TOGGLEABLE_SKILL_IDS as Dt}from"@zibby/agent-workflow";import{query as Bt}from"@anthropic-ai/claude-agent-sdk";import It from"node:process";var et=Object.freeze(["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_INSTANCES","ATLASSIAN_ACCESS_TOKEN","JIRA_API_TOKEN","JIRA_EMAIL","SENTRY_AUTH_TOKEN","SLACK_BOT_TOKEN","DISCORD_BOT_TOKEN","ZIBBY_CHAT_SLACK_TOKEN","ZIBBY_CHAT_LARK_APP_SECRET","ZIBBY_CHAT_DISCORD_INTERACTION_TOKEN","LINEAR_API_KEY","LINEAR_OAUTH_TOKEN","PLANE_API_KEY","PLANE_OAUTH_TOKEN","ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_MEMORY_AWS_ACCESS_KEY_ID","ZIBBY_MEMORY_AWS_SECRET_ACCESS_KEY","ZIBBY_MEMORY_AWS_SESSION_TOKEN"]);function ae(n=It.env){let e={},t=new Set(et);for(let[r,o]of Object.entries(n))t.has(r)||o!==void 0&&(e[r]=o);return e}function tt(n){return!!n&&(n.transport==="http"||typeof n.url=="string"&&!n.command)}var Ct=new Set(["claude"]);function $t(){let n=String(process.env.MCP_ALWAYS_LOAD??"").trim().toLowerCase();return!(n==="0"||n==="false"||n==="off")}function Nt(n,e){return Ct.has(n)?$t()?typeof e.alwaysLoad=="boolean"?{alwaysLoad:e.alwaysLoad}:{}:{}:{}}function ne(n,e,{processEnv:t}={}){if(!e)return null;let r=Nt(n,e);if(tt(e)){let s=String(e.url||"").trim();if(!s)return null;let i=e.headers&&typeof e.headers=="object"?e.headers:void 0;switch(n){case"claude":return{type:"http",url:s,...i&&{headers:i},...r};case"codex":return{url:s,...i&&{http_headers:i}};case"gemini":return{url:s,type:"http",...i&&{headers:i}};case"cursor":return{url:s,...i&&{headers:i}};default:return{type:"http",url:s,...i&&{headers:i},...r}}}let o={command:e.command};return e.args?.length&&(o.args=e.args),e.cwd&&(o.cwd=e.cwd),t?o.env={...t,...e.env||{}}:e.env&&Object.keys(e.env).length&&(o.env=e.env),{...o,...r}}function nt(n){return tt(n)?`http \u2192 ${String(n.url||"").replace(/\?.*$/,"")}`:`${n?.command||"?"} ${(n?.args||[]).join(" ")}`.trim()}ye();import{writeFileSync as ze,mkdirSync as Fe,existsSync as fe,readFileSync as ct}from"fs";import{homedir as ut}from"os";import{join as q}from"path";import he from"chalk";var te={debug:0,info:1,warn:2,error:3,silent:4},Ge=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return te.debug;if(process.env.ZIBBY_VERBOSE==="true")return te.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in te?te[e]:te.info}_shouldLog(e){return te[e]>=this._level}_formatMessage(e,t,r={}){let o=new Date().toISOString(),i=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(i+=he.dim(` ${JSON.stringify(r)}`)),i}_getPrefix(e){return{debug:he.gray("[DEBUG]"),info:he.cyan("[INFO]"),warn:he.yellow("[WARN]"),error:he.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 te&&(this._level=te[e])}getLevel(){return Object.keys(te).find(e=>te[e]===this._level)}},c=new Ge;import{timeline as ce,Timeline as Jn,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as Un}from"@zibby/agent-workflow";var Mt=[{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:"opus-5",canonicalId:"claude-opus-5",vendor:"claude",label:"Claude \xB7 Opus 5",family:"claude-opus-5",pickerVisible:!0},{alias:"claude-opus-5",canonicalId:"claude-opus-5",vendor:"claude",family:"claude-opus-5",aliasOf:"opus-5"},{alias:"sonnet-5",canonicalId:"claude-sonnet-5",vendor:"claude",label:"Claude \xB7 Sonnet 5",family:"claude-sonnet-5",pickerVisible:!0},{alias:"claude-sonnet-5",canonicalId:"claude-sonnet-5",vendor:"claude",family:"claude-sonnet-5",aliasOf:"sonnet-5"},{alias:"fable-5",canonicalId:"claude-fable-5",vendor:"claude",label:"Claude \xB7 Fable 5",family:"claude-fable-5",pickerVisible:!0},{alias:"claude-fable-5",canonicalId:"claude-fable-5",vendor:"claude",family:"claude-fable-5",aliasOf:"fable-5"},{alias:"sonnet-4.8",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4"},{alias:"sonnet-4-8",canonicalId:"claude-sonnet-4-6",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-6",vendor:"claude",family:"claude-sonnet-4"},{alias:"sonnet-4-7",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.7"},{alias:"sonnet-4.6",canonicalId:"claude-sonnet-4-6",vendor:"claude",label:"Claude \xB7 Sonnet 4.6",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.6"},{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-6",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-6",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:"sonnet-4.6"},{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:"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"},{alias:"gpt-5.5",canonicalId:"gpt-5.5",vendor:"codex",label:"Codex \xB7 GPT-5.5",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.6-luna",canonicalId:"gpt-5.6-luna",vendor:"codex",label:"Codex \xB7 GPT-5.6 Luna",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.6-terra",canonicalId:"gpt-5.6-terra",vendor:"codex",label:"Codex \xB7 GPT-5.6 Terra",family:"gpt-5",pickerVisible:!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 Ae(n){let e={};for(let t of Mt)t.vendor===n&&(e[t.alias]=t.canonicalId);return e}function ue(n,e){let t=typeof e=="string"?e.trim():"";if(t)return t;throw new Error(`[${n}] No model reached this LLM call: the node passed none, no config sets one, and the run carries none (MODEL env unset). Refusing to silently substitute a vendor default \u2014 pick a model on the agent (deploy modal / MODEL cell) or pass options.model explicitly.`)}var st={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-3-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"};var je=Ae("claude"),Ye=Ae("codex"),it=Ae("gemini"),Yn={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};function X(n){let e=`${n}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let r=t.split(/[,\n]+/).map(i=>i.trim()).filter(Boolean);if(r.length===0)return{picked:null,count:0,dispose:()=>{}};let o=r[Math.floor(Math.random()*r.length)],s=process.env[n];return process.env[n]=o,c.debug(`[auth-pool] ${n}: picked 1 of ${r.length} from pool (***${o.slice(-4)})`),{picked:o,count:r.length,dispose(){s===void 0?delete process.env[n]:process.env[n]=s}}}function be(n){if(!n||typeof n!="object")return null;let e=(...o)=>{for(let s of o){if(s==null||s==="")continue;let i=Number(s);if(Number.isFinite(i))return i}return null},t=e(n.input_tokens,n.inputTokens,n.prompt_tokens,n.promptTokens),r=e(n.output_tokens,n.outputTokens,n.completion_tokens,n.completionTokens);return t==null&&r==null?null:{input:t||0,output:r||0}}import{createRequire as Kt}from"module";import R from"process";var lt=Kt(import.meta.url);function Jt(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")}function ft(n){if(!n||typeof n!="object")return null;let e=n.message?.content??n.content;return Array.isArray(e)&&e.length||typeof e=="string"&&e.length?e:typeof n.text=="string"&&n.text.length?n.text:null}function Ut(n){let e=ft(n);if(e===null)return null;let t;try{t=JSON.stringify(e)}catch{return null}return typeof t!="string"||!t?null:`${`${n.type||n.constructor?.name||"?"}`}:${t.length}:${Jt(t)}`}function Gt(n){if(!n||typeof n!="object")return"a message with no type";let e=n.type||n.constructor?.name||"unknown-type",t=n.subtype?`/${n.subtype}`:"",r=ft(n);if(typeof r=="string")return`${e}${t} text "${r.slice(0,80)}"`;if(!Array.isArray(r))return`${e}${t} (no readable content)`;let o=r.slice(0,4).map(s=>!s||typeof s!="object"?String(s).slice(0,30):s.type==="tool_use"?`tool_use ${s.name||"(unnamed)"}`:s.type==="tool_result"?`tool_result${s.is_error?" (error)":""}`:s.type==="text"&&typeof s.text=="string"?`text "${s.text.slice(0,60)}"`:s.type==="thinking"?"thinking":String(s.type||"block").slice(0,30));return r.length>o.length&&o.push(`+${r.length-o.length} more`),`${e}${t} [${o.join(", ")}]`}var dt=(n,e)=>{let t=String(n??"");return t.length>e?`${t.slice(0,e)}\u2026`:t},jt=/secret|token|password|passwd|credential|authorization|bearer|api[-_]?key|private[-_]?key|access[-_]?key/i,pt=(n,e=0)=>{if(n==null||e>6||typeof n!="object")return n;let t=Array.isArray(n)?[]:{};for(let[r,o]of Object.entries(n)){let s=jt.test(r)||r==="value"&&typeof n.key=="string";t[r]=s&&typeof o=="string"&&o?"[redacted]":pt(o,e+1)}return t},mt=n=>{try{if(n==null)return"";let e=pt(n),t=typeof e=="string"?e:JSON.stringify(e);return dt(String(t).slice(0,4e3).replace(/(bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,"$1[redacted]").replace(/(https?:\/\/[^/\s:@"']+):[^@/\s"']+@/gi,"$1:[redacted]@").replace(/([?&](?:token|api[-_]?key|apikey|secret|access[-_]?token|auth|key)=)[^&"'\s]+/gi,"$1[redacted]").replace(/sk-[A-Za-z0-9_-]{8,}/g,"sk-[redacted]").replace(/xox[bpoas]-[A-Za-z0-9-]{6,}/g,"xoxb-[redacted]").replace(/zby_[A-Za-z0-9_-]{12,}/g,"zby_[redacted]").replace(/gh[pousr]_[A-Za-z0-9]{20,}/g,"gh_[redacted]").replace(/glpat-[A-Za-z0-9_-]{16,}/g,"glpat-[redacted]").replace(/\bmcp_(?!_)[A-Za-z0-9-]{12,}/g,"mcp_[redacted]").replace(/ntn_[A-Za-z0-9]{10,}/g,"ntn_[redacted]").replace(/figd_[A-Za-z0-9_-]{10,}/g,"figd_[redacted]").replace(/sntrys_[A-Za-z0-9+/=._-]{10,}/g,"sntrys_[redacted]").replace(/ya29\.[A-Za-z0-9_-]{10,}/g,"ya29.[redacted]").replace(/AKIA[0-9A-Z]{16}/g,"AKIA[redacted]").replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*/g,"[redacted-private-key]").replace(/eyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,"eyJ[redacted-jwt]"),300)}catch{return""}},Yt=500;function zt(n){let e=n&&typeof n=="object"?n.content:void 0,t=new Set,r=0;if(typeof e=="string")r=e.length,e&&t.add("text");else if(Array.isArray(e))for(let l of e){if(typeof l=="string"){t.add("text"),r+=l.length;continue}!l||typeof l!="object"||(t.add(typeof l.type=="string"&&l.type?l.type:"unknown"),typeof l.text=="string"&&(r+=l.text.length))}else if(e!=null){t.add("json");try{r=JSON.stringify(e).length}catch{r=0}}let o=!(n&&n.is_error===!0),s={ok:o,chars:r};if(t.size&&(s.kind=[...t].join("+")),o)return s;let i=e;Array.isArray(e)&&(i=e.map(l=>typeof l=="string"?l:l&&typeof l.text=="string"?l.text:"").filter(Boolean).join(`
|
|
2
|
-
`));let a=
|
|
3
|
-
`);
|
|
1
|
+
var wt=Object.defineProperty;var It=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(o){throw t=[o],o}};var Ct=(n,e)=>{for(var t in e)wt(n,t,{get:e[t],enumerable:!0})};var st={};Ct(st,{zodToJson:()=>re});import{z as rt}from"zod";import{zodToJsonSchema as Mt}from"zod-to-json-schema";function Rt(n){if(!n||typeof n!="object")return n;if(Array.isArray(n.type))return n.type.includes("null")||(n.type=[...n.type,"null"]),n;if(typeof n.type=="string")return n.type=[n.type,"null"],n;for(let e of["anyOf","oneOf"])if(Array.isArray(n[e]))return n[e].some(t=>t&&t.type==="null")||(n[e]=[...n[e],{type:"null"}]),n;return{anyOf:[n,{type:"null"}]}}function le(n){if(!n||typeof n!="object")return n;for(let e of["$defs","definitions"])if(n[e]&&typeof n[e]=="object")for(let t of Object.keys(n[e]))n[e][t]=le(n[e][t]);for(let e of["anyOf","oneOf","allOf"])Array.isArray(n[e])&&(n[e]=n[e].map(le));if(n.properties&&typeof n.properties=="object"){n.additionalProperties=!1;let e=Object.keys(n.properties),t=new Set(Array.isArray(n.required)?n.required:[]);for(let o of e){let r=le(n.properties[o]);t.has(o)||(r=Rt(r)),n.properties[o]=r}n.required=e}return n.items&&(Array.isArray(n.items)?n.items=n.items.map(le):n.items=le(n.items)),n}function re(n,e={target:"openApi3"}){if(!n)return null;let t=e?.target==="openAi",o=null;if(typeof rt?.toJSONSchema=="function")try{o=rt.toJSONSchema(n)}catch{}if(!o)try{o=Mt(n,e)}catch{return null}if(t&&o)try{return le(o)}catch{return o}return o}var ye=It(()=>{});import{registerStrategy as Ge}from"@zibby/agent-workflow";import{AgentStrategy as Bt,getSkill as lt,NO_INTEGRATION_TOGGLEABLE_SKILL_IDS as Kt,formatProviderError as Jt}from"@zibby/agent-workflow";import{query as Ut}from"@anthropic-ai/claude-agent-sdk";import $t from"node:process";var tt=Object.freeze(["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_INSTANCES","ATLASSIAN_ACCESS_TOKEN","JIRA_API_TOKEN","JIRA_EMAIL","SENTRY_AUTH_TOKEN","SLACK_BOT_TOKEN","DISCORD_BOT_TOKEN","ZIBBY_CHAT_SLACK_TOKEN","ZIBBY_CHAT_LARK_APP_SECRET","ZIBBY_CHAT_DISCORD_INTERACTION_TOKEN","LINEAR_API_KEY","LINEAR_OAUTH_TOKEN","PLANE_API_KEY","PLANE_OAUTH_TOKEN","ZIBBY_INJECTED_GOOGLE_TOKEN","ZIBBY_INJECTED_LINKEDIN_TOKEN","ZIBBY_MEMORY_AWS_ACCESS_KEY_ID","ZIBBY_MEMORY_AWS_SECRET_ACCESS_KEY","ZIBBY_MEMORY_AWS_SESSION_TOKEN"]);function ae(n=$t.env){let e={},t=new Set(tt);for(let[o,r]of Object.entries(n))t.has(o)||r!==void 0&&(e[o]=r);return e}function nt(n){return!!n&&(n.transport==="http"||typeof n.url=="string"&&!n.command)}var Nt=new Set(["claude"]);function Pt(){let n=String(process.env.MCP_ALWAYS_LOAD??"").trim().toLowerCase();return!(n==="0"||n==="false"||n==="off")}function Lt(n,e){return Nt.has(n)?Pt()?typeof e.alwaysLoad=="boolean"?{alwaysLoad:e.alwaysLoad}:{}:{}:{}}function ne(n,e,{processEnv:t}={}){if(!e)return null;let o=Lt(n,e);if(nt(e)){let s=String(e.url||"").trim();if(!s)return null;let i=e.headers&&typeof e.headers=="object"?e.headers:void 0;switch(n){case"claude":return{type:"http",url:s,...i&&{headers:i},...o};case"codex":return{url:s,...i&&{http_headers:i}};case"gemini":return{url:s,type:"http",...i&&{headers:i}};case"cursor":return{url:s,...i&&{headers:i}};default:return{type:"http",url:s,...i&&{headers:i},...o}}}let r={command:e.command};return e.args?.length&&(r.args=e.args),e.cwd&&(r.cwd=e.cwd),t?r.env={...t,...e.env||{}}:e.env&&Object.keys(e.env).length&&(r.env=e.env),{...r,...o}}function ot(n){return nt(n)?`http \u2192 ${String(n.url||"").replace(/\?.*$/,"")}`:`${n?.command||"?"} ${(n?.args||[]).join(" ")}`.trim()}ye();import{writeFileSync as Fe,mkdirSync as He,existsSync as fe,readFileSync as ut}from"fs";import{homedir as ft}from"os";import{join as q}from"path";import he from"chalk";var te={debug:0,info:1,warn:2,error:3,silent:4},je=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return te.debug;if(process.env.ZIBBY_VERBOSE==="true")return te.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in te?te[e]:te.info}_shouldLog(e){return te[e]>=this._level}_formatMessage(e,t,o={}){let r=new Date().toISOString(),i=`${this._getPrefix(e)} ${t}`;return Object.keys(o).length>0&&(i+=he.dim(` ${JSON.stringify(o)}`)),i}_getPrefix(e){return{debug:he.gray("[DEBUG]"),info:he.cyan("[INFO]"),warn:he.yellow("[WARN]"),error:he.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 te&&(this._level=te[e])}getLevel(){return Object.keys(te).find(e=>te[e]===this._level)}},c=new je;import{timeline as ce,Timeline as jn,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as Yn}from"@zibby/agent-workflow";var Dt=[{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:"opus-5",canonicalId:"claude-opus-5",vendor:"claude",label:"Claude \xB7 Opus 5",family:"claude-opus-5",pickerVisible:!0},{alias:"claude-opus-5",canonicalId:"claude-opus-5",vendor:"claude",family:"claude-opus-5",aliasOf:"opus-5"},{alias:"sonnet-5",canonicalId:"claude-sonnet-5",vendor:"claude",label:"Claude \xB7 Sonnet 5",family:"claude-sonnet-5",pickerVisible:!0},{alias:"claude-sonnet-5",canonicalId:"claude-sonnet-5",vendor:"claude",family:"claude-sonnet-5",aliasOf:"sonnet-5"},{alias:"fable-5",canonicalId:"claude-fable-5",vendor:"claude",label:"Claude \xB7 Fable 5",family:"claude-fable-5",pickerVisible:!0},{alias:"claude-fable-5",canonicalId:"claude-fable-5",vendor:"claude",family:"claude-fable-5",aliasOf:"fable-5"},{alias:"sonnet-4.8",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4"},{alias:"sonnet-4-8",canonicalId:"claude-sonnet-4-6",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-6",vendor:"claude",family:"claude-sonnet-4"},{alias:"sonnet-4-7",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.7"},{alias:"sonnet-4.6",canonicalId:"claude-sonnet-4-6",vendor:"claude",label:"Claude \xB7 Sonnet 4.6",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.6"},{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-6",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-6",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:"sonnet-4.6"},{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:"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"},{alias:"gpt-5.5",canonicalId:"gpt-5.5",vendor:"codex",label:"Codex \xB7 GPT-5.5",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.6-luna",canonicalId:"gpt-5.6-luna",vendor:"codex",label:"Codex \xB7 GPT-5.6 Luna",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.6-terra",canonicalId:"gpt-5.6-terra",vendor:"codex",label:"Codex \xB7 GPT-5.6 Terra",family:"gpt-5",pickerVisible:!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 be(n){let e={};for(let t of Dt)t.vendor===n&&(e[t.alias]=t.canonicalId);return e}function ue(n,e){let t=typeof e=="string"?e.trim():"";if(t)return t;throw new Error(`[${n}] No model reached this LLM call: the node passed none, no config sets one, and the run carries none (MODEL env unset). Refusing to silently substitute a vendor default \u2014 pick a model on the agent (deploy modal / MODEL cell) or pass options.model explicitly.`)}var it={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 Ye=be("claude"),ze=be("codex"),at=be("gemini"),Hn={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};function X(n){let e=`${n}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let o=t.split(/[,\n]+/).map(i=>i.trim()).filter(Boolean);if(o.length===0)return{picked:null,count:0,dispose:()=>{}};let r=o[Math.floor(Math.random()*o.length)],s=process.env[n];return process.env[n]=r,c.debug(`[auth-pool] ${n}: picked 1 of ${o.length} from pool (***${r.slice(-4)})`),{picked:r,count:o.length,dispose(){s===void 0?delete process.env[n]:process.env[n]=s}}}function Te(n){if(!n||typeof n!="object")return null;let e=(...r)=>{for(let s of r){if(s==null||s==="")continue;let i=Number(s);if(Number.isFinite(i))return i}return null},t=e(n.input_tokens,n.inputTokens,n.prompt_tokens,n.promptTokens),o=e(n.output_tokens,n.outputTokens,n.completion_tokens,n.completionTokens);return t==null&&o==null?null:{input:t||0,output:o||0}}import{createRequire as Gt}from"module";import R from"process";var ct=Gt(import.meta.url);function jt(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")}function dt(n){if(!n||typeof n!="object")return null;let e=n.message?.content??n.content;return Array.isArray(e)&&e.length||typeof e=="string"&&e.length?e:typeof n.text=="string"&&n.text.length?n.text:null}function Yt(n){let e=dt(n);if(e===null)return null;let t;try{t=JSON.stringify(e)}catch{return null}return typeof t!="string"||!t?null:`${`${n.type||n.constructor?.name||"?"}`}:${t.length}:${jt(t)}`}function pt(n){if(!n||typeof n!="object")return"a message with no type";let e=n.type||n.constructor?.name||"unknown-type",t=n.subtype?`/${n.subtype}`:"",o=dt(n);if(typeof o=="string")return`${e}${t} text "${o.slice(0,80)}"`;if(!Array.isArray(o))return`${e}${t} (no readable content)`;let r=o.slice(0,4).map(s=>!s||typeof s!="object"?String(s).slice(0,30):s.type==="tool_use"?`tool_use ${s.name||"(unnamed)"}`:s.type==="tool_result"?`tool_result${s.is_error?" (error)":""}`:s.type==="text"&&typeof s.text=="string"?`text "${s.text.slice(0,60)}"`:s.type==="thinking"?"thinking":String(s.type||"block").slice(0,30));return o.length>r.length&&r.push(`+${o.length-r.length} more`),`${e}${t} [${r.join(", ")}]`}function zt(n){if(!n||typeof n!="object")return"";let e=n.message?.content??n.content;if(Array.isArray(e)){let t=e.filter(o=>o&&o.type==="text"&&typeof o.text=="string"&&o.text.trim()).map(o=>o.text.trim());if(t.length)return _e(t.join(" "))}else if(typeof e=="string"&&e.trim())return _e(e);return n.error&&typeof n.error=="object"&&typeof n.error.message=="string"?_e(n.error.message):typeof n.message=="string"&&n.message.trim()?_e(n.message):typeof n.result=="string"&&n.result.trim()?_e(n.result):pt(n)}function _e(n){let e=String(n).replace(/\s+/g," ").trim();return e.length>400?`${e.slice(0,400)}\u2026`:e}var mt=(n,e)=>{let t=String(n??"");return t.length>e?`${t.slice(0,e)}\u2026`:t},Ft=/secret|token|password|passwd|credential|authorization|bearer|api[-_]?key|private[-_]?key|access[-_]?key/i,gt=(n,e=0)=>{if(n==null||e>6||typeof n!="object")return n;let t=Array.isArray(n)?[]:{};for(let[o,r]of Object.entries(n)){let s=Ft.test(o)||o==="value"&&typeof n.key=="string";t[o]=s&&typeof r=="string"&&r?"[redacted]":gt(r,e+1)}return t},yt=n=>{try{if(n==null)return"";let e=gt(n),t=typeof e=="string"?e:JSON.stringify(e);return mt(String(t).slice(0,4e3).replace(/(bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,"$1[redacted]").replace(/(https?:\/\/[^/\s:@"']+):[^@/\s"']+@/gi,"$1:[redacted]@").replace(/([?&](?:token|api[-_]?key|apikey|secret|access[-_]?token|auth|key)=)[^&"'\s]+/gi,"$1[redacted]").replace(/sk-[A-Za-z0-9_-]{8,}/g,"sk-[redacted]").replace(/xox[bpoas]-[A-Za-z0-9-]{6,}/g,"xoxb-[redacted]").replace(/zby_[A-Za-z0-9_-]{12,}/g,"zby_[redacted]").replace(/gh[pousr]_[A-Za-z0-9]{20,}/g,"gh_[redacted]").replace(/glpat-[A-Za-z0-9_-]{16,}/g,"glpat-[redacted]").replace(/\bmcp_(?!_)[A-Za-z0-9-]{12,}/g,"mcp_[redacted]").replace(/ntn_[A-Za-z0-9]{10,}/g,"ntn_[redacted]").replace(/figd_[A-Za-z0-9_-]{10,}/g,"figd_[redacted]").replace(/sntrys_[A-Za-z0-9+/=._-]{10,}/g,"sntrys_[redacted]").replace(/ya29\.[A-Za-z0-9_-]{10,}/g,"ya29.[redacted]").replace(/AKIA[0-9A-Z]{16}/g,"AKIA[redacted]").replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*/g,"[redacted-private-key]").replace(/eyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,"eyJ[redacted-jwt]"),300)}catch{return""}},Ht=500;function Vt(n){let e=n&&typeof n=="object"?n.content:void 0,t=new Set,o=0;if(typeof e=="string")o=e.length,e&&t.add("text");else if(Array.isArray(e))for(let l of e){if(typeof l=="string"){t.add("text"),o+=l.length;continue}!l||typeof l!="object"||(t.add(typeof l.type=="string"&&l.type?l.type:"unknown"),typeof l.text=="string"&&(o+=l.text.length))}else if(e!=null){t.add("json");try{o=JSON.stringify(e).length}catch{o=0}}let r=!(n&&n.is_error===!0),s={ok:r,chars:o};if(t.size&&(s.kind=[...t].join("+")),r)return s;let i=e;Array.isArray(e)&&(i=e.map(l=>typeof l=="string"?l:l&&typeof l.text=="string"?l.text:"").filter(Boolean).join(`
|
|
2
|
+
`));let a=yt(i);return a&&(s.error=a),s}function Zt(){try{if(R.env.CLAUDE_CODE_EXECUTABLE&&fe(R.env.CLAUDE_CODE_EXECUTABLE))return R.env.CLAUDE_CODE_EXECUTABLE;let n=R.platform,e=R.arch,t=`@anthropic-ai/claude-agent-sdk-${n}-${e}`,o=n==="win32"?"claude.exe":"claude";try{let r=ct.resolve(`${t}/package.json`),s=q(r,"..",o);if(fe(s))return s}catch{}try{let r=ct.resolve("@anthropic-ai/claude-agent-sdk/package.json"),s=q(r,"..");for(let a of[o,q("vendor",o),q("bin",o)]){let l=q(s,a);if(fe(l))return l}let i=q(s,"..",`claude-agent-sdk-${n}-${e}`,o);if(fe(i))return i}catch{}}catch{}return null}var xe=Zt();xe&&c.debug(`Claude native CLI resolved to baked binary: ${xe}`);var ke=class extends Bt{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!R.env.ANTHROPIC_API_KEY||!!R.env.ANTHROPIC_API_KEY_POOL,o=!!R.env.CLAUDE_CODE_OAUTH_TOKEN||!!R.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,r=!!R.env.ANTHROPIC_AUTH_TOKEN||!!R.env.ANTHROPIC_AUTH_TOKEN_POOL,s=t||o||r;return s||c.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)."),s}async invoke(e,t={}){let{model:o,workspace:r=R.cwd(),schema:s=null,images:i=[],skills:a=null,sessionPath:l=null,nodeName:f=null,timeout:d,config:p={},activityLog:E=!1,signal:O=null,sessionId:P,resume:D,forkSession:L,sessionStore:T}=t,C=ue("claude",o),w=Ye[C]||C;Ye[C]&&C!==w&&c.debug(`Mapped model: ${C} \u2192 ${w}`);let _=[X("ANTHROPIC_API_KEY"),X("CLAUDE_CODE_OAUTH_TOKEN"),X("ANTHROPIC_AUTH_TOKEN")];try{c.debug(`Invoking Claude Agent SDK with model: ${w}, skills: ${JSON.stringify(a)}`);let A=mt,k=(y,x)=>{try{console.log(JSON.stringify({mode:y,...x}))}catch{}},I=R.env.CLAUDE_CODE_OAUTH_TOKEN,G=R.env.ANTHROPIC_API_KEY,$=R.env.ANTHROPIC_AUTH_TOKEN;R.env.CLAUDE_CODE_CREDENTIALS_JSON?qt(R.env.CLAUDE_CODE_CREDENTIALS_JSON):I&&Xt(I,R.env.__ZIBBY_CLAUDE_PLAN);let H=R.env.__ZIBBY_CLAUDE_PLAN,B=H?H.charAt(0).toUpperCase()+H.slice(1):null,j;if(I?j=B?`Claude ${B} plan \xB7 ***${I.slice(-4)}`:`Subscription \xB7 ***${I.slice(-4)}`:G?j=`API key \xB7 ***${G.slice(-4)}`:$?j=`Bearer \xB7 ***${$.slice(-4)}`:j="NONE \u2014 request will fail",!E){let y=(await import("chalk")).default;console.log(""),console.log(` ${y.cyan("\u25C6")} ${y.bold(w)}`),console.log(` ${y.dim("Auth: ")}${j}`),console.log(` ${y.dim("Workdir: ")}${r}`),console.log(""),console.log(y.bold("Prompt sent to LLM:")),console.log(y.dim("\u2500".repeat(60))),console.log(y.dim(e)),console.log(y.dim("\u2500".repeat(60)))}let{allowedTools:V,mcpServers:g}=this._resolveSkills(a,{sessionPath:l,workspace:r,nodeName:f});for(let y of t.extraMcpServers||[])if(y&&y.serverName&&y.def){if(Object.prototype.hasOwnProperty.call(g,y.serverName)){console.warn(`[custom-mcp] skip "${y.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let x=ne("claude",y.def);x&&(g[y.serverName]=x,V.push(`mcp__${y.serverName}__*`))}try{let y={cwd:r,allowedTools:V,...Array.isArray(t.disallowedTools)&&t.disallowedTools.length?{disallowedTools:t.disallowedTools}:{},settings:{permissions:{allow:["Bash(*)","Read(*)","Write(*)","Edit(*)","MultiEdit(*)","NotebookEdit(*)","Grep(*)","Glob(*)","WebFetch(*)","WebSearch(*)","Task(*)","TodoWrite(*)","Skill(*)"]}},model:w,env:ae(R.env),...xe&&{pathToClaudeCodeExecutable:xe},...Object.keys(g).length>0&&{mcpServers:g},...P&&{sessionId:P},...D&&{resume:D},...L&&{forkSession:!0},...T&&{sessionStore:T}};if(s){let z=typeof s.parse=="function"?re(s):s;y.outputFormat={type:"json_schema",schema:z},c.debug("Structured output enforced via SDK outputFormat")}c.debug(`Agent SDK options: ${JSON.stringify({cwd:y.cwd,toolCount:V.length,permissionMode:y.permissionMode,model:y.model,hasOutputFormat:!!y.outputFormat})}`);let x="",Q=0,N=new Map,K=[];c.debug("Starting Claude Agent SDK query stream");let v=e,W=Array.isArray(i)?i.filter(u=>u&&typeof u.path=="string"&&u.path.startsWith("/")):[];if(W.length){let u=W.map((z,b)=>` ${b+1}. ${z.path}${z.name?` (${z.name})`:""}`).join(`
|
|
3
|
+
`);v=`${e}
|
|
4
4
|
|
|
5
5
|
# Attached image files \u2014 VIEW THESE
|
|
6
6
|
The user attached ${W.length} image(s), saved locally. Use the Read tool on each path to SEE the image, then use what it shows to answer:
|
|
7
|
-
${
|
|
7
|
+
${u}`}let h;try{h=Ut({prompt:v,options:y})}catch(u){throw c.error(`Failed to initialize Claude Agent SDK: ${u.message}`),u}let M=null,Y=0,ee=3;if(O?.aborted){let u=new Error("Aborted via signal");throw u.name="AbortError",u}try{for await(let u of h){if(O?.aborted){let b=new Error("Aborted via signal");throw b.name="AbortError",b}if(K.push(u),u.type==="system"&&u.subtype==="init"){let b=u.mcp_servers||[];if(b.length>0){let m=b.map(S=>`${S.name}=${S.status}${S.error?` (${String(S.error).slice(0,120)})`:""}`).join(", ");c.info(`[mcp] SDK init \u2014 ${b.length} server(s): ${m}`);for(let S of b)S.status!=="connected"&&c.warn(`[mcp] server '${S.name}' did not connect: status=${S.status}`,{name:S.name,status:S.status,error:S.error})}else Object.keys(g||{}).length>0&&c.warn(`[mcp] SDK init returned no mcp_servers despite passing ${Object.keys(g).length} server(s) \u2014 SDK version may not expose this field, or config was dropped`);if(Array.isArray(u.tools)){let m=u.tools.filter(S=>S.startsWith("mcp__"));if(m.length>0){let S=F=>F.split("__")[1]||"",J=new Set(Object.entries(g||{}).filter(([,F])=>F&&F.alwaysLoad===!0).map(([F])=>F)),U=m.filter(F=>J.has(S(F))),Z=m.length-U.length,ie={};for(let F of m){let oe=S(F);J.has(oe)||(ie[oe]=(ie[oe]||0)+1)}let et=Object.entries(ie).sort((F,oe)=>oe[1]-F[1]).map(([F,oe])=>`${F}:${oe}`).join(" ");c.info(`[mcp] ${m.length} tool(s) reachable \u2014 ${U.length} IN PROMPT${U.length?` (${U.join(", ")})`:""}; ${Z} DEFERRED behind ToolSearch${et?` [${et}]`:""}`)}else Object.keys(g||{}).length>0&&c.warn("[mcp] no mcp__* tools in model's tool list \u2014 MCP servers configured but tools didn't reach the prompt")}}if(u.type==="system"&&u.subtype==="api_retry"){let b=Number(u.attempt)||0,m=Number(u.max_retries)||0,S=u.error_status!=null?String(u.error_status):"?",J=typeof u.error=="string"?u.error:"error",U=Number.isFinite(u.retry_delay_ms)?Math.round(u.retry_delay_ms):null,Z=`upstream ${S} (${J}) \u2014 SDK retry ${b}/${m}`+(U!=null?` in ${U}ms`:"");E&&k("turn:retry",{status:S,kind:J,attempt:b,maxRetries:m,delayMs:U,detail:Z}),c.warn(`[claude] transient ${Z}`);continue}if(u.type==="error"||u.error){let b=typeof u.error=="string"?u.error:u.error?.type||u.error?.name||null,m=u.error_status??u.error?.status??null,S=zt(u);try{c.error("SDK error event raw payload",{fullMessage:JSON.stringify(u,null,2)})}catch{}let J=new Error(Jt({kind:b,status:m,text:S}));J.providerErrorKind=b||null;let U=m==null?NaN:Number(m);throw J.providerErrorStatus=Number.isInteger(U)&&U>=100&&U<=599?U:null,J.providerErrorText=S,J}let z=Yt(u);if(z!==null)if(z===M){if(Y++,Y>=ee)throw new Error(`API stuck in loop (${Y}x identical): ${pt(u)}`)}else M=z,Y=1;if(u.type==="assistant"||u.constructor?.name==="AssistantMessage"){let b=u.message?.content||u.content||[];for(let m of b)if(m.type==="thinking"&&m.thinking)E?k("turn:thinking",{text:A(m.thinking,600)}):console.log(`${m.thinking.substring(0,200)}${m.thinking.length>200?"...":""}`);else if(m.type==="text"&&m.text)x+=m.text,E||(m.text.length<500?console.log(`${m.text}`):console.log(`${m.text.substring(0,200)}... (${m.text.length} chars)`));else if(m.type==="tool_use")if(Q++,m.name.includes("memory")?ce.stepMemory(`Tool: ${m.name}`):ce.stepTool(`Tool: ${m.name}`),E){let J=yt(m.input);k("turn:tool",{name:m.name,...J?{input:J}:{}}),m.id&&(N.set(m.id,m.name),N.size>Ht&&N.delete(N.keys().next().value))}else{let J=JSON.stringify(m.input).substring(0,100);console.log(` Input: ${J}${JSON.stringify(m.input).length>100?"...":""}`)}}else if(u.type==="user"){if(E){let b=u.message?.content||u.content;if(Array.isArray(b))for(let m of b){if(!m||m.type!=="tool_result")continue;let S=N.get(m.tool_use_id);k("turn:tool-result",{...S?{name:S}:{},...Vt(m)})}}}else if(u.type==="result"||u.constructor?.name==="ResultMessage"){let b=u.result||u.text||u.content||x;try{Wt({message:u,sessionPath:l,nodeName:f,model:C,toolCallCount:Q})}catch(S){c.debug(`usage.json write failed: ${S.message}`)}let m=Te(u?.usage||u?.message?.usage);if(s){if(u.structured_output){c.debug("Using SDK native structured_output");let J=typeof s.parse=="function"?s.parse(u.structured_output):u.structured_output;return{raw:b,structured:J,...m?{usage:m}:{},toolUseCount:Q}}if(b){let S=this._extractJson(b,s);if(S)return{raw:b,structured:S,...m?{usage:m}:{},toolUseCount:Q}}c.warn(`Could not extract structured output \u2014 returning raw text (${(b||"").length} chars)`)}return b||""}}if(c.warn(`Agent SDK ended without result. Collected ${K.length} messages`),x.length>0)return c.debug("Returning accumulated text from messages"),x;throw new Error("Claude Agent SDK query ended without result")}catch(u){let z={message:u?.message,name:u?.name,code:u?.code,cause:u?.cause?.message||u?.cause,stack:u?.stack?.split(`
|
|
8
8
|
`).slice(0,5).join(`
|
|
9
|
-
`),stringified:(()=>{try{return JSON.stringify(
|
|
10
|
-
\u25C6 Model: ${T}${
|
|
11
|
-
`),Array.isArray(l)&&l.length>0){let
|
|
12
|
-
${_.bold("Prompt sent to LLM:")}`),console.log(_.dim("\u2500".repeat(60))),console.log(_.dim(e)),console.log(_.dim("\u2500".repeat(60)));let
|
|
9
|
+
`),stringified:(()=>{try{return JSON.stringify(u,Object.getOwnPropertyNames(Object(u)))}catch{return String(u)}})()};throw c.error(`Error during query stream: ${u?.message||u}`,z),u}}catch(y){throw c.error("Claude Agent SDK call failed",{message:y?.message,name:y?.name,code:y?.code,cause:y?.cause?.message||y?.cause}),y}}finally{for(let A of _)A.dispose()}}_resolveSkills(e,t){let o=["Read","Write","Edit","Bash","Grep","Glob"];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:[...o],mcpServers:{}};let r=[...o],s={},i=R.env.WORKFLOW_ENABLED_INTEGRATIONS,a=typeof i=="string"&&i.trim()!==""?new Set(i.split(",").map(d=>d.trim()).filter(Boolean)):null,l=d=>{let p=lt(d);return p?.meta?.toggleable===!0?!0:p?.meta?.toggleable===void 0&&Kt.includes(d)},f=d=>a!==null&&a.size>0&&l(d)&&!a.has(d);for(let d of e){if(f(d)){c.debug(`Skill "${d}" disabled by enabledIntegrations allowlist \u2014 skipping`);continue}let p=lt(d);if(!p){c.warn(`Unknown skill "${d}" \u2014 skipping`);continue}if(p.allowedTools&&r.push(...p.allowedTools),typeof p.resolve=="function"){let E=p.resolve(t),O=ne("claude",E);O&&(s[p.serverName]=O,c.debug(`MCP: ${p.serverName} \u2192 ${ot(E)}`))}}return{allowedTools:r,mcpServers:s}}_extractJson(e,t){let o=[()=>{if(e.includes("===JSON_START===")){let r=e.indexOf("===JSON_START===")+16,s=e.indexOf("===JSON_END===");return e.substring(r,s).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 r=e.indexOf("{"),s=e.lastIndexOf("}");if(r!==-1&&s>r)return e.substring(r,s+1)}];for(let r of o)try{let s=r();if(!s)continue;let i=JSON.parse(s);if(typeof i!="object"||i===null)continue;return typeof t.parse=="function"?t.parse(i):i}catch{}return null}};function Wt({message:n,sessionPath:e,nodeName:t,model:o,toolCallCount:r}){if(!e||!t)return;let s=n?.usage||n?.message?.usage||{},i=Se(s.input_tokens,s.inputTokens),a=Se(s.output_tokens,s.outputTokens),l=Se(s.cache_read_input_tokens,s.cacheReadInputTokens),f=Se(s.cache_creation_input_tokens,s.cacheCreationInputTokens),d=Se(n?.duration_ms,n?.durationMs),p={model:o||null,input_tokens:i,output_tokens:a,cache_read_tokens:l,cache_creation_tokens:f,tool_call_count:typeof r=="number"?r:null,duration_ms:d,captured_at:new Date().toISOString()},E=q(e,t);try{He(E,{recursive:!0})}catch{}Fe(q(E,"usage.json"),JSON.stringify(p,null,2),"utf-8")}function Se(...n){for(let e of n){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e)))return Number(e)}return null}function Xt(n,e){let t=q(ft(),".claude"),o=q(t,".credentials.json"),r={claudeAiOauth:{accessToken:n,refreshToken:"",expiresAt:Date.now()+365*24*60*60*1e3,scopes:["user:inference","user:profile"],...e?{subscriptionType:String(e).toLowerCase()}:{}}};try{if(fe(o)&&JSON.parse(ut(o,"utf-8"))?.claudeAiOauth?.accessToken===n)return;He(t,{recursive:!0}),Fe(o,JSON.stringify(r,null,2),"utf-8"),c.debug(`Wrote Claude Code OAuth credentials to ${o}`)}catch(s){c.warn(`Could not write ${o}: ${s.message} \u2014 Claude SDK may fail to authenticate.`)}}function qt(n){let e=q(ft(),".claude"),t=q(e,".credentials.json"),o;try{o=JSON.parse(n)}catch(r){c.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${r.message}`);return}if(!o?.claudeAiOauth?.accessToken){c.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if(fe(t)){let r=JSON.parse(ut(t,"utf-8"));if(r?.claudeAiOauth?.accessToken===o.claudeAiOauth.accessToken&&r?.claudeAiOauth?.expiresAt===o.claudeAiOauth.expiresAt)return}He(e,{recursive:!0}),Fe(t,JSON.stringify(o,null,2),"utf-8"),c.debug(`Wrote full Claude Code credentials blob to ${t}`)}catch(r){c.warn(`Could not write ${t}: ${r.message} \u2014 Claude SDK may fail to authenticate.`)}}import{AgentStrategy as en,getSkill as tn}from"@zibby/agent-workflow";import{execSync as we}from"node:child_process";import{execSync as Qt}from"node:child_process";function ve(n){if(!/^[A-Za-z0-9._-]+$/.test(n))return!1;try{return Qt(`command -v ${n}`,{encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim().length>0}catch{return!1}}ye();import{readFileSync as nn,mkdirSync as Ve,cpSync as on,existsSync as rn}from"node:fs";import{join as Ee}from"node:path";import{homedir as sn}from"node:os";function Ze(n){if(Array.isArray(n))return n.map(Ze);if(n&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))o!==null&&(e[t]=Ze(o));return e}return n}var Ie=class extends en{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){return!(process.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY_POOL||process.env.CODEX_API_KEY||process.env.CODEX_API_KEY_POOL)?(c.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1):ve("codex")?!0:(c.warn("[Codex] codex CLI not on PATH. Install: npm install -g @openai/codex"),!1)}async invoke(e,t={}){let{model:o,workspace:r=process.cwd(),schema:s=null,images:i=[],skills:a=null,plugins:l=null,sessionPath:f=null,nodeName:d=null,timeout:p,config:E={},signal:O=null}=t,P=[X("OPENAI_API_KEY"),X("CODEX_API_KEY")];try{let{Codex:D}=await import("@openai/codex-sdk"),L=ue("codex",o),T=ze[L]||L;ze[L]&&L!==T&&c.debug(`Mapped model: ${L} \u2192 ${T}`),c.debug(`Invoking Codex SDK with model: ${T}, skills: ${JSON.stringify(a)}`);let C=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;C&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=C);let w=C?` | key: ***${C.slice(-4)}`:" | key: not set";if(console.log(`
|
|
10
|
+
\u25C6 Model: ${T}${w}
|
|
11
|
+
`),Array.isArray(l)&&l.length>0){let g=this._resolveCodexHome(f);process.env.CODEX_HOME=g;try{Ve(g,{recursive:!0})}catch{}this._ensurePlugins(l,g)}let _=(await import("chalk")).default;console.log(`
|
|
12
|
+
${_.bold("Prompt sent to LLM:")}`),console.log(_.dim("\u2500".repeat(60))),console.log(_.dim(e)),console.log(_.dim("\u2500".repeat(60)));let A=this._resolveSkillsToMcp(a,{sessionPath:f,workspace:r,nodeName:d});for(let g of t.extraMcpServers||[])if(g&&g.serverName&&g.def){if(Object.prototype.hasOwnProperty.call(A,g.serverName)){console.warn(`[custom-mcp] skip "${g.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let y=ne("codex",g.def);y&&(A[g.serverName]=y)}let k={};Object.keys(A).length>0&&(k.mcp_servers=A,Object.values(A).some(g=>g&&typeof g.url=="string")&&(k.experimental_use_rmcp_client=!0),c.debug(`[Codex] MCP servers: ${Object.keys(A).join(", ")}`));let I=this._resolveCodexBin(),G=new D({...I?{codexPathOverride:I}:{},...Object.keys(k).length>0&&{config:k},env:ae(process.env)}),$=r;try{$&&Ve($,{recursive:!0})}catch{}(!$||!rn($))&&($=process.cwd());let H=G.startThread({workingDirectory:$,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),B=s&&typeof s.parse=="function",j={};if(s)try{let g=B?re(s,{target:"openAi"}):s;j.outputSchema=g,c.debug("Structured output via SDK outputSchema")}catch(g){c.warn(`[Codex] Schema conversion failed, will extract from text: ${g.message}`)}let V=Array.isArray(i)?i.filter(g=>g&&typeof g.path=="string"&&g.path.startsWith("/")):[];if(V.length&&(e=`${e}
|
|
13
13
|
|
|
14
14
|
# Attached image files \u2014 VIEW THESE
|
|
15
|
-
The user attached ${
|
|
16
|
-
${
|
|
17
|
-
`)}`),O?.aborted){let
|
|
18
|
-
`).some(
|
|
15
|
+
The user attached ${V.length} image(s), saved locally. Read each path to SEE the image, then use what it shows to answer:
|
|
16
|
+
${V.map((g,y)=>` ${y+1}. ${g.path}${g.name?` (${g.name})`:""}`).join(`
|
|
17
|
+
`)}`),O?.aborted){let g=new Error("Aborted via signal");throw g.name="AbortError",g}try{let{events:g}=await H.runStreamed(e,j),y=0,x="",Q=null;for await(let N of g){if(O?.aborted){let v=new Error("Aborted via signal");throw v.name="AbortError",v}let K=N.type;if(K==="item.completed"){let v=N.item,W=v?.type;if(W==="mcp_tool_call"){y++;let h=`${v.server}/${v.tool}`;if(ce.stepTool(`Tool: ${h}`),v.arguments){let M=JSON.stringify(v.arguments),Y=M.length>100?`${M.substring(0,100)}...`:M;console.log(` Input: ${Y}`)}}else if(W==="tool_call"||W==="function_call"||W==="command_execution"){y++;let h=v.name||v.tool||v.command||"unknown";ce.stepTool(`Tool: ${h}`)}else W==="agent_message"&&(x=v.text||"",x.length<500?console.log(x):console.log(`${x.substring(0,200)}... (${x.length} chars)`))}else K==="turn.completed"?(c.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(N.usage||{})}`),N.usage&&(Q=N.usage)):c.debug(`[Codex] Event: ${K} ${JSON.stringify(N).slice(0,300)}`)}if(c.debug(`[Codex] Last agent message (${x.length} chars): ${x.slice(0,500)}`),s){if(!x)throw new Error("Codex agent returned no response");let N=JSON.parse(x),K=N;if(B)try{K=s.parse(N)}catch{K=s.parse(Ze(N))}c.debug("\u2705 [Codex] Structured output validated");let v=Te(Q);return{raw:x,structured:K,...v?{usage:v}:{}}}return x||""}catch(g){let y=g.message||String(g);throw c.error(`\u274C [Codex] SDK call failed: ${y}`),y.includes("exited with code")&&(j.outputSchema&&c.error("\u{1F4A1} [Codex] An outputSchema was sent \u2014 an OpenAI strict-mode-invalid schema (a property missing from `required`) makes codex exit 1 here."),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")),g}}finally{for(let D of P)D.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let o={};for(let r of e){let s=tn(r);if(!s){c.warn(`[Codex] Unknown skill "${r}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let a=s.serverName||r,l=ne("codex",i,{processEnv:process.env});l&&(o[a]=l,c.debug(`[Codex] MCP: ${a} \u2192 ${i.command} ${(i.args||[]).join(" ")}`))}return o}_resolveCodexHome(e){return process.env.CODEX_HOME?process.env.CODEX_HOME:e&&!this._isTempPath(e)?Ee(e,".codex-home"):Ee(sn(),".codex")}_isTempPath(e){let t=String(process.env.TMPDIR||"/tmp").replace(/\/+$/,""),o=String(e||"");return o==="/tmp"||o.startsWith("/tmp/")||o===t||o.startsWith(t+"/")}_resolveCodexBin(){if(process.env.CODEX_BIN)return process.env.CODEX_BIN;try{return we("command -v codex",{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}_ensurePlugins(e,t){let o={...process.env,CODEX_HOME:t};for(let r of e){let s=typeof r=="string"?r:r?.name,i=r&&typeof r=="object"?r.marketplacePath:null;if(!s||!i){c.warn(`[Codex][plugins] skipping malformed plugin declaration: ${JSON.stringify(r)} (need { name, marketplacePath })`);continue}let a=this._readMarketplaceName(i),l=`${s}@${a}`;if(this._isPluginInstalled(l,o)){c.info(`[Codex][plugins] ${l} already installed \u2014 skipping (idempotent)`),console.log(`\u25C6 [Codex] plugin ${l} already installed \u2014 skip`);continue}let f=this._safeMarketplacePath(i,t);c.info(`[Codex][plugins] installing ${l} from local marketplace ${f}`),console.log(`\u25C6 [Codex] installing plugin ${l} (local, no network)`);try{we(`codex plugin marketplace add ${JSON.stringify(f)}`,{env:o,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),we(`codex plugin add ${JSON.stringify(l)}`,{env:o,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),console.log(`\u25C6 [Codex] plugin ${l} installed`)}catch(d){let p=d.stderr&&d.stderr.toString()||d.message||String(d);throw c.error(`[Codex][plugins] failed to install ${l}: ${p}`),new Error(`Codex plugin install failed for ${l}: ${p}`,{cause:d})}}}_safeMarketplacePath(e,t){if(!String(e).includes("@"))return e;let o=Ee(t,".zibby-mkt",String(e).replace(/[^a-zA-Z0-9]+/g,"_"));try{return Ve(Ee(t,".zibby-mkt"),{recursive:!0}),on(e,o,{recursive:!0}),o}catch(r){return c.warn(`[Codex][plugins] could not copy @-containing marketplace to a safe path: ${r.message}`),e}}_readMarketplaceName(e){let t=Ee(e,".agents","plugins","marketplace.json"),o;try{o=JSON.parse(nn(t,"utf-8"))}catch(r){throw new Error(`Codex plugin marketplace manifest missing/unreadable at ${t}: ${r.message}`,{cause:r})}if(!o?.name||typeof o.name!="string")throw new Error(`Codex plugin marketplace manifest at ${t} has no string "name"`);return o.name}_isPluginInstalled(e,t){try{return we("codex plugin list",{env:t,stdio:"pipe",timeout:15e3,encoding:"utf-8"}).split(`
|
|
18
|
+
`).some(r=>r.includes(e)&&/installed/.test(r))}catch{return!1}}};import{AgentStrategy as cn,getSkill as un}from"@zibby/agent-workflow";import{spawn as fn}from"node:child_process";ye();import{existsSync as _t,mkdirSync as St,readFileSync as Et,rmSync as dn,writeFileSync as Ot}from"node:fs";import{join as se}from"node:path";import{z as ht}from"zod";import{zodToJsonSchema as an}from"zod-to-json-schema";function ln(n){if(!n)return null;if(typeof ht?.toJSONSchema=="function")try{return ht.toJSONSchema(n)}catch{}try{return an(n,{target:"openApi3"})}catch{return null}}var Ce=class{static generateFileOutputInstructions(e,t){let o;typeof e?.parse=="function"?o=ln(e):o=e;let r=this._buildExample(o);return`
|
|
19
19
|
\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
|
|
20
20
|
\u{1F6A8} MANDATORY: WRITE RESULT TO FILE \u{1F6A8}
|
|
21
21
|
\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
|
|
@@ -28,48 +28,48 @@ DO NOT just output JSON to stdout. The file MUST exist when you finish.
|
|
|
28
28
|
DO NOT skip this step. The workflow WILL FAIL if the file is missing.
|
|
29
29
|
|
|
30
30
|
Required JSON structure:
|
|
31
|
-
${JSON.stringify(
|
|
31
|
+
${JSON.stringify(r,null,2)}
|
|
32
32
|
|
|
33
33
|
JSON types (strict \u2014 validators reject wrong types):
|
|
34
34
|
- Use bare JSON numbers for numeric fields (e.g. 3000). Do NOT quote them as strings (wrong: "3000").
|
|
35
35
|
- Use true/false without quotes for booleans.
|
|
36
36
|
- Use unquoted null where a field may be null.
|
|
37
37
|
|
|
38
|
-
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
|
|
38
|
+
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 o={};for(let[r,s]of Object.entries(e.properties))o[r]=this._buildExample(s);return o}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 o=e.oneOf?.find(r=>r.type!=="null")||e.anyOf?.find(r=>r.type!=="null");return o?this._buildExample(o):null}return"<value>"}};var $e=class n{constructor(e=""){this.userPrompt=e,this.systemInstructions=[],this.metadata={}}setUserPrompt(e){return this.userPrompt=e,this}appendUserPrompt(e){return this.userPrompt?this.userPrompt+=`
|
|
39
39
|
|
|
40
|
-
${e}`:this.userPrompt=e,this}addSkillHints(e){return e&&this.systemInstructions.push({type:"skill_hints",content:e,position:"prepend"}),this}addStructuredOutput(e,t){if(e&&t){let
|
|
40
|
+
${e}`:this.userPrompt=e,this}addSkillHints(e){return e&&this.systemInstructions.push({type:"skill_hints",content:e,position:"prepend"}),this}addStructuredOutput(e,t){if(e&&t){let o=Ce.generateFileOutputInstructions(e,t);this.systemInstructions.push({type:"structured_output",content:o,position:"append"}),this.metadata.structuredOutputPath=t}return this}addExtraInstructions(e){if(e?.trim()){let t=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
41
41
|
\u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
42
42
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
43
43
|
|
|
44
44
|
${e.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:t,position:"append"})}return this}addSkillFragments(e){return e&&e.length>0&&this.systemInstructions.push({type:"skill_fragments",content:e.join(`
|
|
45
45
|
|
|
46
|
-
`),position:"append"}),this}addSystemInstruction(e,t="custom",
|
|
46
|
+
`),position:"append"}),this}addSystemInstruction(e,t="custom",o="append"){return e&&this.systemInstructions.push({type:t,content:e,position:o}),this}getUserPrompt(){return this.userPrompt}getSystemInstructions(){return this.systemInstructions}getMetadata(){return this.metadata}build(){let e=this.systemInstructions.filter(r=>r.position==="prepend").map(r=>r.content),t=this.systemInstructions.filter(r=>r.position==="append").map(r=>r.content);return[...e,this.userPrompt,...t].filter(Boolean).join(`
|
|
47
47
|
|
|
48
|
-
`)}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(
|
|
49
|
-
`);this.buffer=t.pop()||"";let
|
|
50
|
-
`,
|
|
51
|
-
`,this.extractedResult=s)}catch{if(
|
|
52
|
-
${h}`,"schema_instruction","append");let M=`zibby-result-${Date.now()}.json`,
|
|
53
|
-
${h}`,"json_instruction","append")}let k=
|
|
48
|
+
`)}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(o=>o.type)}}clone(){let e=new n(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};var Ne=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(`
|
|
49
|
+
`);this.buffer=t.pop()||"";let o="";for(let r of t)if(r.trim())try{let s=JSON.parse(r);this._emitToolCalls(s);let i=this.extractText(s);if(i){if(this.rawText&&i.startsWith(this.rawText)){let a=i.substring(this.rawText.length);this.rawText=i,o+=a}else(!this.rawText.includes(i)||i.length<20)&&(this.rawText+=i,o+=i);this.tryExtractResult(this.rawText)}else this.isValidResult(s)&&(this.rawText+=`${r}
|
|
50
|
+
`,o+=`${r}
|
|
51
|
+
`,this.extractedResult=s)}catch{if(r.includes('"text"')||r.includes('"content"')){let i=r.match(/"text"\s*:\s*"([^"]*)/),a=r.match(/"content"\s*:\s*"([^"]*)/),l=i?i[1]:a?a[1]:null;l&&!this.rawText.includes(l)&&(o+=l,this.rawText+=l)}}return o||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let o=this.extractText(t);o&&(this.rawText+=o,e+=o,this.tryExtractResult(o))}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 l=`${i}:${JSON.stringify(a??{})}`;this._lastToolEmit!==l&&(this._lastToolEmit=l,this.onToolCall(i,a??void 0))},o=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,o(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 l=a[0],f=i[l],d=f&&typeof f=="object"?f.args??f.input??f:void 0;t(l,o(d))}return}return}if(Array.isArray(e.tool_calls)){for(let i of e.tool_calls)t(i.name,o(i.input??i.arguments));return}let r=e.message??e;if(Array.isArray(r?.tool_calls)){for(let i of r.tool_calls)t(i.name,o(i.input??i.arguments));return}let s=r?.content??e.content;if(Array.isArray(s))for(let i of s)(i.type==="tool_use"||i.type==="tool_call")&&i.name&&t(i.name,o(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(o=>o.type==="text"&&o.text).map(o=>o.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=[],o=/```json\s*\n?([\s\S]*?)\n?```/g,r;for(;(r=o.exec(e))!==null;){let p=r[1].trim();try{JSON.parse(p),t.push({text:p,source:"markdown"})}catch{}}let s=0,i=0;for(;s<e.length&&(s=e.indexOf("{",s),s!==-1);){let p=0,E=s;for(let O=s;O<e.length;O++)if(e[O]==="{")p++;else if(e[O]==="}"&&(p--,p===0)){E=O,t.push({text:e.substring(s,E+1),source:"brace"}),i++;break}s=E+1}let a=this.extractedResult,l=a?JSON.stringify(a).length:0,f=0,d=-1;for(let p=0;p<t.length;p++){let E=t[p];try{let O=E.text.replace(/,(\s*[}\]])/g,"$1"),P=JSON.parse(O);this.isValidResult(P)&&(f++,l=JSON.stringify(P).length,a=P,d=p)}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 o=new n;o.zodSchema=t,o.processChunk(e),o.flush();let r=o.getResult();return!r&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),r}};function pn(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 o=e.indexOf("{");if(o<0)return null;let r=0,s=!1,i=!1,a=-1;for(let l=o;l<e.length;l++){let f=e[l];if(s){i?i=!1:f==="\\"?i=!0:f==='"'&&(s=!1);continue}if(f==='"'){s=!0;continue}if(f==="{"){r===0&&(a=l),r+=1;continue}if(f==="}"){if(r===0)continue;if(r-=1,r===0&&a>=0){let d=e.slice(a,l+1);try{return JSON.parse(d)}catch{a=-1}}}}return null}function mn(n){let e=String(n||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return pn(e)}}function gn(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 o=t.content.parts.map(r=>typeof r?.text=="string"?r.text:"").join("");if(o.trim())return o}}}catch{}return n}var Pe=class extends cn{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){return!(process.env.GEMINI_API_KEY||process.env.GEMINI_API_KEY_POOL||process.env.GOOGLE_API_KEY||process.env.GOOGLE_API_KEY_POOL)?(c.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1):ve("gemini")?!0:(c.warn("[Gemini] gemini CLI not on PATH. Install: npm install -g @google/gemini-cli"),!1)}async invoke(e,t={}){let{model:o,workspace:r=process.cwd(),schema:s=null,images:i=[],skills:a=null,sessionPath:l=null,nodeName:f=null,timeout:d=600*1e3,signal:p=null}=t,E=[X("GEMINI_API_KEY"),X("GOOGLE_API_KEY")];try{let O=ue("gemini",o),P=at[O]||O,D=String(process.env.GEMINI_API_KEY||"").trim(),L=String(process.env.GOOGLE_API_KEY||"").trim(),T=this._resolveSkillsToMcp(a,{sessionPath:l,workspace:r,nodeName:f});for(let h of t.extraMcpServers||[])if(h&&h.serverName&&h.def){if(Object.prototype.hasOwnProperty.call(T,h.serverName)){console.warn(`[custom-mcp] skip "${h.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let M=ne("gemini",h.def);M&&(T[h.serverName]=M)}let C=Object.keys(T).length>0,w=new $e(e),_=s&&typeof s.parse=="function",A=null;if(s){let h;try{let M=_?re(s,{target:"openAi"}):s;h=JSON.stringify(M,null,2)}catch{h="{}"}if(C){w.addSystemInstruction(`Write valid JSON that matches this schema:
|
|
52
|
+
${h}`,"schema_instruction","append");let M=`zibby-result-${Date.now()}.json`,Y=se(r,".zibby","tmp");A=se(Y,M),St(Y,{recursive:!0}),w.addStructuredOutput(s,A)}else w.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
|
|
53
|
+
${h}`,"json_instruction","append")}let k=w.build(),I=Array.isArray(i)?i.filter(h=>h&&typeof h.path=="string"&&h.path.startsWith("/")):[];I.length&&(k+=`
|
|
54
54
|
|
|
55
55
|
# Attached image files \u2014 VIEW THESE
|
|
56
56
|
The user attached ${I.length} image(s), saved locally. Read each path to SEE the image, then use what it shows to answer:
|
|
57
57
|
${I.map((h,M)=>` ${M+1}. ${h.path}${h.name?` (${h.name})`:""}`).join(`
|
|
58
|
-
`)}`);let
|
|
58
|
+
`)}`);let G=w.getUserPrompt(),$=w.getStats(),H=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),B=H?` | key: ***${H.slice(-4)}`:" | key: not set";console.log(`
|
|
59
59
|
\u25C6 Model: ${P}${B}
|
|
60
|
-
`);let
|
|
61
|
-
${
|
|
60
|
+
`);let j=(await import("chalk")).default;console.log(`
|
|
61
|
+
${j.bold("Prompt sent to LLM:")}`),console.log(j.dim("\u2500".repeat(60))),console.log(j.dim(G)),console.log(j.dim("\u2500".repeat(60)));let V=this._createGeminiConfigDir(r,T),g=["--output-format","json"];g.push("--model",P);let y=Object.keys(T);if(y.length>0){g.push("--approval-mode","yolo");for(let h of y)g.push("--allowed-mcp-server-names",h);c.info(`[Gemini] Enabling MCP servers: ${y.join(", ")}`)}else a&&a.length>0&&c.warn(`[Gemini] Skills requested but no MCP servers configured: ${a.join(", ")}`);g.push("-p",k);let x={...ae(process.env),GEMINI_CLI_HOME:V,GEMINI_CLI_TRUST_WORKSPACE:"true"};D?(x.GEMINI_API_KEY=D,delete x.GOOGLE_API_KEY):L&&(x.GOOGLE_API_KEY=L,delete x.GEMINI_API_KEY),c.debug(`[Gemini] Command: gemini ${g.slice(0,8).join(" ")}... (${g.length} total args)`),c.debug(`[Gemini] User prompt: ${$.userPromptLength} chars, System instructions: ${$.systemInstructionsLength} chars (${$.instructionCount} blocks), Full: ${$.fullPromptLength} chars`),c.debug(`[Gemini] Config home: ${V}`),c.debug(`[Gemini] GEMINI_CLI_HOME env: ${x.GEMINI_CLI_HOME}`);let Q="",N=null;try{Q=await new Promise((M,Y)=>{let ee=fn("gemini",g,{cwd:r,env:x,stdio:["ignore","pipe","pipe"],...p&&{signal:p}}),u="",z="",b=!1,m=null,S=!1,J=setTimeout(()=>{try{ee.kill("SIGTERM")}catch{}},d),U=()=>{S||b||(S=!0,m=setTimeout(()=>{if(!b)try{ee.kill("SIGKILL")}catch{}},5e3))};p&&(p.aborted?U():p.addEventListener("abort",U,{once:!0})),ee.stdout.on("data",Z=>{u+=Z.toString()}),ee.stderr.on("data",Z=>{z+=Z.toString()}),ee.on("error",Z=>{if(clearTimeout(J),m&&clearTimeout(m),p&&!p.aborted)try{p.removeEventListener("abort",U)}catch{}Y(Z)}),ee.on("close",Z=>{if(b=!0,clearTimeout(J),m&&clearTimeout(m),p&&!p.aborted)try{p.removeEventListener("abort",U)}catch{}if(S){let ie=new Error("Aborted via signal");return ie.name="AbortError",Y(ie)}if(Z===0)return M(u.trim());Y(new Error(`gemini failed with code ${Z}: ${(z||u).trim()}`))})})}catch(h){N=h}finally{try{dn(V,{recursive:!0,force:!0})}catch{}}let K=gn(Q).trim();if(!s){if(N)throw N;return K}if(A){let h=_t(A);if(c.info(`[Gemini] Result file: ${h?"present":"missing"} at ${A}`),h)try{let M=Et(A,"utf-8").trim(),Y=JSON.parse(M),ee=_?s.parse(Y):Y;return c.info("[Gemini] Structured output recovered from result file"),{raw:K,structured:ee}}catch(M){c.warn(`[Gemini] Result file parse/validation failed: ${M.message}`)}else N||c.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let v=null;if(s){let h=new Ne;h.zodSchema=s,h.processChunk(K),h.flush(),v=h.getResult()}if(c.info(`[Gemini] Raw stdout length: ${Q.length} chars`),c.info(`[Gemini] Extracted text length: ${K.length} chars`),c.info(`[Gemini] StreamParser result: ${v?"extracted":"null"}`),v||(K.length<2e3?c.info(`[Gemini] Raw text preview:
|
|
62
62
|
${K}`):c.info(`[Gemini] Raw text preview (first 1000 chars):
|
|
63
|
-
${K.slice(0,1e3)}`),
|
|
64
|
-
`,"utf-8");let d=se(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{
|
|
65
|
-
`,"utf-8")}catch{}return c.debug(`[Gemini] Created isolated config with ${Object.keys(
|
|
63
|
+
${K.slice(0,1e3)}`),v=mn(K)),!v)throw N||(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 W=_?s.parse(v):v;return{raw:K,structured:W}}finally{for(let O of E)O.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let o={};for(let r of e){let s=un(r);if(!s||typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let a=s.cursorKey||s.serverName||r,l=ne("gemini",i);l&&(o[a]=l)}return o}_createGeminiConfigDir(e,t){let o=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,r=se(e||process.cwd(),".zibby","tmp",`gemini-home-${o}`),s=se(r,".gemini");St(s,{recursive:!0});let i=se(s,"settings.json"),a={},l=se(process.env.HOME||"",".gemini","settings.json");if(_t(l))try{a=JSON.parse(Et(l,"utf-8"))}catch{a={}}let f={...a,mcpServers:{...a.mcpServers&&typeof a.mcpServers=="object"?a.mcpServers:{},...t||{}}};Ot(i,`${JSON.stringify(f,null,2)}
|
|
64
|
+
`,"utf-8");let d=se(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{Ot(d,`${JSON.stringify(f,null,2)}
|
|
65
|
+
`,"utf-8")}catch{}return c.debug(`[Gemini] Created isolated config with ${Object.keys(f.mcpServers||{}).length} MCP servers`),c.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(f.mcpServers||{}),null,2)}`),r}};import{AgentStrategy as wn,getSkill as Ke}from"@zibby/agent-workflow";var Oe=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 de=class extends Oe{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(o=>({id:o.id,name:o.function.name,args:JSON.parse(o.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 Ae=class{async fetchCompletion(e,t,o={}){throw new Error("fetchCompletion() must be implemented")}async fetchStreamingCompletion(e,t,o={}){throw new Error("fetchStreamingCompletion() must be implemented")}};function Le(n){return Buffer.byteLength(JSON.stringify(n),"utf8")}function Me(n,e){let t=String(n||"");if(t.length<=e)return t;let o=Math.max(0,e-28);return`${t.slice(0,o)}
|
|
66
66
|
|
|
67
|
-
[truncated for size budget]`}function
|
|
68
|
-
`);O=C.pop();for(let
|
|
69
|
-
`)||"",isError:s.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(
|
|
67
|
+
[truncated for size budget]`}function We(n,e=0){if(!n||typeof n!="object"||e>8)return n;if(Array.isArray(n))return n.map(o=>We(o,e+1));let t={};for(let[o,r]of Object.entries(n))o==="description"||o==="title"||o==="examples"||o==="default"||(t[o]=We(r,e+1));return t}function yn(n=[]){return n.map(e=>({...e,function:{...e.function,description:Me(e.function?.description||"",180),parameters:We(e.function?.parameters||{type:"object",properties:{}})}}))}function At(n){let e=new Set;for(let r of n)if(r.role==="assistant"&&Array.isArray(r.tool_calls))for(let s of r.tool_calls)e.add(s.id);let t=n.filter(r=>r.role==="tool"?e.has(r.tool_call_id):!0),o=new Set;for(let r of t)r.role==="tool"&&o.add(r.tool_call_id);return t.map(r=>{if(r.role!=="assistant"||!Array.isArray(r.tool_calls)||r.tool_calls.every(l=>o.has(l.id)))return r;let{tool_calls:i,...a}=r;return{...a,content:a.content||""}})}function Xe(n,e={}){let t=e.maxBytes||49e3,o=e.systemMaxChars||12e3,r={...n,messages:Array.isArray(n.messages)?[...n.messages]:[],tools:Array.isArray(n.tools)?yn(n.tools):n.tools};r.messages.length>0&&r.messages[0]?.role==="system"&&(r.messages[0]={...r.messages[0],content:Me(r.messages[0].content,o)});let s=!1;for(;Le(r)>t&&r.messages.length>2;)r.messages.splice(1,1),s=!0;if(s&&(r.messages=At(r.messages)),Le(r)>t&&r.messages.length>0&&(r.messages[0]={...r.messages[0],content:Me(r.messages[0].content,6e3)},s=!0),Le(r)>t){let i=r.messages.find(l=>l.role==="system")||r.messages[0],a=r.messages.slice(-2);r.messages=At([i,...a].filter(Boolean).map((l,f)=>({...l,content:Me(l.content,f===0?4e3:8e3)}))),s=!0}return{body:r,meta:{bytes:Le(r),trimmed:s,maxBytes:t,messageCount:r.messages.length}}}var bt=n=>Buffer.byteLength(JSON.stringify(n),"utf8"),pe=class extends Ae{async fetchCompletion(e,t,o={}){let r=bt(e),{body:s,meta:i}=Xe(e,o.payloadCompaction);o.onBudget?.({streaming:!1,beforeBytes:r,meta:i});let a=this.#e(o),l=`${t.baseUrl}${o.chatCompletionsPath||"/v1/chat/completions"}`,f=await fetch(l,{method:"POST",headers:t.headers,body:JSON.stringify(s),signal:a});if(!f.ok){let d=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}: ${d}`)}return f.json()}async fetchStreamingCompletion(e,t,o={}){let r={...e,stream:!0},s=bt(r),{body:i,meta:a}=Xe(r,o.payloadCompaction);o.onBudget?.({streaming:!0,beforeBytes:s,meta:a});let l=this.#e(o),f=`${t.baseUrl}${o.chatCompletionsPath||"/v1/chat/completions"}`,d=await fetch(f,{method:"POST",headers:t.headers,body:JSON.stringify(i),signal:l});if(!d.ok){let L=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}: ${L}`)}let p=d.body.getReader(),E=new TextDecoder,O="",P="",D=new Map;for(;;){let{done:L,value:T}=await p.read();if(L)break;O+=E.decode(T,{stream:!0});let C=O.split(`
|
|
68
|
+
`);O=C.pop();for(let w of C){if(!w.startsWith("data: "))continue;let _=w.slice(6).trim();if(_==="[DONE]")continue;let A;try{A=JSON.parse(_)}catch{continue}let k=A.choices?.[0]?.delta;if(k&&(k.content&&(P+=k.content,o.onToken&&o.onToken(k.content)),k.tool_calls))for(let I of k.tool_calls){let G=I.index??0;D.has(G)||D.set(G,{id:"",name:"",args:""});let $=D.get(G);I.id&&($.id=I.id),I.function?.name&&($.name=I.function.name),I.function?.arguments!=null&&($.args+=I.function.arguments)}}}if(D.size>0){let L=[...D.entries()].sort(([T],[C])=>T-C).map(([,T])=>({id:T.id,type:"function",function:{name:T.name,arguments:T.args}}));return{choices:[{message:{role:"assistant",content:P||null,tool_calls:L}}]}}return{choices:[{message:{role:"assistant",content:P}}]}}#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 hn}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as _n}from"@modelcontextprotocol/sdk/client/stdio.js";var Re=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:o,args:r=[],env:s={}}=t;c.debug(`[MCP] Starting ${e}: ${o} ${r.join(" ")}`);let i=new _n({command:o,args:r,env:{...process.env,...s}}),a=new hn({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await a.connect(i);let l={client:a,transport:i,serverConfig:t};return this.#e.set(e,l),l}async callTool(e,t,o={}){let r=this.#e.get(e);if(!r)throw new Error(`MCP server "${e}" not running`);c.debug(`[MCP] ${e}.${t}(${JSON.stringify(o).slice(0,200)})`);let s=await r.client.callTool({name:t,arguments:o});return{text:s.content?.filter(a=>a.type==="text").map(a=>a.text).join(`
|
|
69
|
+
`)||"",isError:s.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(o){c.debug(`[MCP] Error closing ${e}: ${o.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}};import{existsSync as Sn,readFileSync as En}from"node:fs";import{join as On}from"node:path";import{homedir as An}from"node:os";function bn(){try{let n=On(An(),".zibby","config.json");return Sn(n)?JSON.parse(En(n,"utf-8")):{}}catch{return{}}}function De(n){return String(n||"").replace(/\/v1\/?$/,"")}function Tn(n,e){let t=process.env.OPENAI_PROXY_URL;if(t)return De(t);if(n==="session")return e.proxyUrl?De(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(n==="byok"){let o=process.env.OPENAI_BASE_URL;return De(o||"https://api.openai.com")}return De(t||"")}function qe(){let n=bn(),e=process.env.ZIBBY_USER_TOKEN||n.sessionToken||null,t=process.env.OPENAI_API_KEY||null,o=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),r=process.env.OPENAI_PROXY_NO_AUTH==="true",s=process.env.OPENAI_PROXY_URL,i="session";o==="byok"||o==="local"||o==="session"?i=o:e?i="session":t?i="byok":s&&r&&(i="local");let a=Tn(i,n),l={"Content-Type":"application/json"};if(i==="session"){if(!e)return{ok:!1,mode:i,reason:"missing_session_token"};l.Authorization=`Bearer ${e}`}else if(i==="byok"){if(!t)return{ok:!1,mode:i,reason:"missing_openai_api_key"};l.Authorization=`Bearer ${t}`}else if(i==="local"){if(!a)return{ok:!1,mode:i,reason:"missing_openai_proxy_url"};!r&&t&&(l.Authorization=`Bearer ${t}`)}return a?{ok:!0,mode:i,baseUrl:a,headers:l,tokenPreview:l.Authorization?`***${l.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:i,reason:"missing_base_url"}}function Be(n,e){let t=String(n??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
|
|
70
70
|
|
|
71
|
-
[tool result truncated for size]`}function
|
|
72
|
-
\u{1F4D6} get_skill_context("${
|
|
73
|
-
`)),O}let a=s?.get(e.name)||null;if(!a)return`Unknown tool: ${e.name}`;let l=
|
|
74
|
-
\u25C6 Model: ${t} | proxy: ${
|
|
75
|
-
`);let s=(await import("chalk")).default;console.log(s.bold("Prompt sent to LLM:")),console.log(s.dim("\u2500".repeat(60)));let i=!1;for(let a of e)if(a.role==="system")console.log(s.dim(`[System] ${a.content||""}`));else{i||(console.log(s.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),i=!0);let l=a.role==="user"?"Human":"AI",
|
|
71
|
+
[tool result truncated for size]`}function xn(n,e){if(typeof n=="string")return Be(n,e);try{return Be(JSON.stringify(n),e)}catch{return Be(String(n),e)}}function Tt(n){let e=new Set;for(let r of n)if(r.role==="assistant"&&Array.isArray(r.tool_calls))for(let s of r.tool_calls)e.add(s.id);let t=n.filter(r=>r.role==="tool"?e.has(r.tool_call_id):!0),o=new Set;for(let r of t)r.role==="tool"&&o.add(r.tool_call_id);return t.map(r=>{if(r.role!=="assistant"||!Array.isArray(r.tool_calls)||r.tool_calls.every(l=>o.has(l.id)))return r;let{tool_calls:i,...a}=r;return{...a,content:a.content||""}})}function kn(n){let e=Array.isArray(n?.messages)?n.messages:[],t=e.find(s=>s.role==="system"),o=e.slice(-4).map(s=>({...s,content:Be(s.content,s.role==="tool"?1200:2500)}));o=Tt(o);let r={...n,messages:[t,...o].filter(Boolean)};return delete r.tools,r}async function vn({body:n,streaming:e,auth:t,options:o,fetchCompletion:r,fetchStreamingCompletion:s,onFallbackLog:i}){try{return e?await s(n,t,o):await r(n,t,o)}catch(a){let l=String(a?.message||a||"");if(!/proxy error 413|payload too large/i.test(l))throw a;let f=kn(n);return typeof i=="function"&&i(n,f),{data:e?await s(f,t,o):await r(f,t,o),fallback:f}}}async function xt({body:n,auth:e,options:t,streaming:o,toolContext:r,activeSkills:s,round:i,verbose:a,dependencies:l,config:f={}}){let d=f.maxToolResultChars||3e3,{fetchCompletion:p,fetchStreamingCompletion:E,onFallbackLog:O,hasToolCalls:P,getTextContent:D,parseToolCalls:L,buildAssistantMessage:T,buildToolResultMessage:C,executeTool:w,onToolCallLog:_,injectTools:A}=l;Array.isArray(n?.messages)&&(n.messages=Tt(n.messages));let k=await vn({body:n,streaming:o,auth:e,options:t,fetchCompletion:p,fetchStreamingCompletion:E,onFallbackLog:O}),I=k?.data||k;if(!P(I))return{done:!0,text:D(I),body:k?.fallback||n};let G=L(I),$=k?.fallback||n;$.messages.push(T(I)),a&&typeof _=="function"&&_(G);let H=await Promise.all(G.map((B,j)=>(typeof t.onToolCall=="function"&&t.onToolCall(B.name,B.args,{round:i,index:j,total:G.length}),w(B,r))));for(let B=0;B<G.length;B++){let V=G[B].name==="get_skill_context"?typeof H[B]=="string"?H[B]:JSON.stringify(H[B]):xn(H[B],d);$.messages.push(C(G[B].id,V))}return typeof t.onToolCall=="function"&&t.onToolCall(null),A($,s),{done:!1,body:$}}var In=it.ASSISTANT,Cn=15,Qe="get_skill_context";function ge(n){!n||typeof n!="object"||(n.type==="object"&&n.properties&&(n.required=Object.keys(n.properties),n.additionalProperties=!1,Object.values(n.properties).forEach(ge)),n.type==="array"&&n.items&&ge(n.items),n.anyOf&&n.anyOf.forEach(ge),n.oneOf&&n.oneOf.forEach(ge),n.allOf&&n.allOf.forEach(ge))}var kt={maxBytes:49e3,systemMaxChars:12e3},me=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",$n=n=>Buffer.byteLength(JSON.stringify(n),"utf8");function Je(n){return Array.isArray(n)?new Set(n.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function Nn(n){return Array.isArray(n)?n.map(e=>String(e||"").trim()).filter(Boolean):[]}var Ue=class extends wn{#e;#t;#n=new Re;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new de,this.#t=e.completionProvider||new pe):(this.#e=e||new de,this.#t=new pe)}canHandle(e){return qe().ok}async invoke(e,t={}){let o=X("OPENAI_API_KEY");try{let r=t.model||In,s=qe();if(!s.ok)throw s.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):s.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):s.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${s.reason}).`);let i=t.messages||[{role:"user",content:e}],a=s.baseUrl,l=me();if(l?await this.#m(i,r,a,s.tokenPreview||"none"):c.debug(`[Assistant] ${a} | model: ${r} | messages: ${i.length}`),t.schema)return this.#c(r,i,s,t);let f=t.activeSkills||[],d=this.#f(t),p=this.#d(f,d),E=this.#p(p),O=this.#u(t),P={...t,payloadCompaction:O},D={activeSkills:p,options:P,executionRegistry:E,capabilityPolicy:d},L=!!t.stream,T={model:r,messages:[...i],stream:!1};this.#r(T,p,d);for(let C=0;C<Cn;C++){if(t.signal?.aborted){let _=new Error("Aborted via signal");throw _.name="AbortError",_}let w=await xt({body:T,auth:s,options:P,streaming:L,toolContext:D,activeSkills:p,round:C,verbose:l,dependencies:{fetchCompletion:this.#s.bind(this),fetchStreamingCompletion:this.#l.bind(this),onFallbackLog:(_,A)=>{me()&&console.log(`413 fallback: messages ${_.messages.length} -> ${A.messages.length}, bytes=${$n(A)}`)},hasToolCalls:_=>this.#e.hasToolCalls(_),getTextContent:_=>this.#e.getTextContent(_),parseToolCalls:_=>this.#e.parseToolCalls(_),buildAssistantMessage:_=>this.#e.buildAssistantMessage(_),buildToolResultMessage:(_,A)=>this.#e.buildToolResultMessage(_,A),executeTool:(_,A)=>this.#a(_,A),onToolCallLog:async _=>{let A=(await import("chalk")).default;console.log(A.dim(` ${_.map(k=>`${k.name}(${JSON.stringify(k.args).slice(0,80)})`).join(", ")}`))},injectTools:(_,A)=>this.#r(_,A,d)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(w.done)return w.text;T.messages=w.body.messages,w.body.tools?T.tools=w.body.tools:delete T.tools}return"I hit my tool-calling limit for this turn. Please try again."}finally{o.dispose()}}async cleanup(){await this.#n.stopAll()}#r(e,t,o=null){let r=this.#i(t,o),s=this.#e.formatTools(r);this.#e.injectToolsIntoBody(e,s)}#i(e,t=null){let o=[],r=new Set;for(let s of e){let i=Ke(s);if(i?.tools?.length)for(let a of i.tools)this.#o(a.name,t)&&(r.has(a.name)||(r.add(a.name),o.push({name:a.name,description:a.description,parameters:a.parameters||a.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#o(Qe,t)&&o.push({name:Qe,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"]}}),o}async#a(e,t){let{activeSkills:o,options:r,executionRegistry:s,capabilityPolicy:i}=t;if(!this.#o(e.name,i))return`Tool "${e.name}" blocked by policy`;if(e.name===Qe){let f=String(e.args?.skillId||"").trim();if(!f)return JSON.stringify({error:"skillId is required"});if(!o.includes(f))return JSON.stringify({error:`Skill "${f}" is not active`,activeSkills:o});let d=Ke(f);if(!d)return JSON.stringify({error:`Skill "${f}" not found`});let p=typeof d.promptFragment=="function"?d.promptFragment():d.promptFragment||"",E=(d.tools||[]).map(P=>P.name),O=JSON.stringify({skillId:f,description:d.description||"",toolNames:E,promptFragment:p||""});return me()&&(console.log(`
|
|
72
|
+
\u{1F4D6} get_skill_context("${f}") \u2192 ${O.length} chars (fragment: ${p.length} chars)`),console.log(` tools: [${E.join(", ")}]`),console.log(` fragment preview: ${p.slice(0,200).replace(/\n/g,"\\n")}\u2026
|
|
73
|
+
`)),O}let a=s?.get(e.name)||null;if(!a)return`Unknown tool: ${e.name}`;let l=Ke(a.skillId);if(!l)return`Skill "${a.skillId}" not found for tool "${e.name}"`;if(a.mode==="handler")try{return l.handleToolCall(e.name,e.args,t)}catch(f){return`Error in ${e.name}: ${f.message}`}if(a.mode==="mcp")try{if(!this.#n.isRunning(l.serverName)){let d=l.resolve(r);if(!d)return`Skill "${a.skillId}" is not available (cannot start server)`;await this.#n.ensureServer(l.serverName,d)}let f=await this.#n.callTool(l.serverName,e.name,e.args);return f.text||(f.isError?"Tool call failed":"Done")}catch(f){return`MCP error (${l.serverName}): ${f.message}`}return`Skill "${a.skillId}" owns tool "${e.name}" but has no execution mode`}async#l(e,t,o){return this.#t.fetchStreamingCompletion(e,t,{...o,onBudget:({beforeBytes:r,meta:s})=>{me()&&console.log(`payload bytes (stream) before=${r} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#s(e,t,o){return this.#t.fetchCompletion(e,t,{...o,onBudget:({beforeBytes:r,meta:s})=>{me()&&console.log(`payload bytes before=${r} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#c(e,t,o,r){let{zodToJson:s}=await Promise.resolve().then(()=>(ye(),st)),i=typeof r.schema?.parse=="function",a=i?s(r.schema,{}):r.schema;delete a.$schema,ge(a);let l={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:a,strict:!0}}},f=await this.#s(l,o,r),d=this.#e.getTextContent(f),p=JSON.parse(d),E=i?r.schema.parse(p):p;return{raw:d,structured:E}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||kt.maxBytes),systemMaxChars:Number(t.systemMaxChars||kt.systemMaxChars)}}#f(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:Je(t.allowTools||e.allowTools),denyTools:Je(t.denyTools||e.denyTools),denyPrefixes:Nn(t.denyPrefixes||e.denyToolPrefixes),includeSkills:Je(t.includeSkills||e.includeSkills),excludeSkills:Je(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#d(e,t){let o=t?.includeSkills||new Set,r=t?.excludeSkills||new Set;return o.size===0&&r.size===0?e:e.filter(s=>!(o.size>0&&!o.has(s)||r.has(s)))}#o(e,t){let o=String(e||"").trim();if(!o)return!1;let r=t?.allowTools;if(r&&r.size>0&&!r.has(o))return!1;let s=t?.denyTools;return!(s&&s.has(o)||(t?.denyPrefixes||[]).some(a=>o.startsWith(a)))}#p(e){let t=new Map,o=[];for(let r of e){let s=Ke(r);if(!s?.tools?.length)continue;let i=typeof s.handleToolCall=="function"?"handler":s.serverName&&typeof s.resolve=="function"?"mcp":null;if(i)for(let a of s.tools){let l=String(a?.name||"").trim();if(l){if(t.has(l)){o.push({tool:l,winner:t.get(l).skillId,skipped:r});continue}t.set(l,{skillId:r,mode:i})}}}if(o.length>0&&me()){let r=o.slice(0,5).map(s=>`${s.tool}:${s.winner}>${s.skipped}`).join(", ");console.log(`tool registry collisions: ${r}${o.length>5?" ...":""}`)}return t}async#m(e,t,o,r){console.log(`
|
|
74
|
+
\u25C6 Model: ${t} | proxy: ${o} | token: ${r||"none"}
|
|
75
|
+
`);let s=(await import("chalk")).default;console.log(s.bold("Prompt sent to LLM:")),console.log(s.dim("\u2500".repeat(60)));let i=!1;for(let a of e)if(a.role==="system")console.log(s.dim(`[System] ${a.content||""}`));else{i||(console.log(s.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),i=!0);let l=a.role==="user"?"Human":"AI",f=a.content?.length>200?`${a.content.slice(0,200)}...`:a.content||"";console.log(s.dim(`[${l}] ${f}`))}console.log(s.dim("\u2500".repeat(60)))}};var vt=!1;function Ur(){vt||(Ge(new Ue),Ge(new ke),Ge(new Ie),Ge(new Pe),vt=!0)}export{Ur as registerBuiltInStrategies};
|