@zibby/core 2.0.8 → 2.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +161 -161
- package/dist/mcp/tool-broker-server.js +4 -0
- package/dist/package.json +4 -4
- package/dist/register-built-in-strategies.js +41 -41
- package/dist/strategies/claude-strategy.js +4 -4
- package/dist/strategies/codex-strategy.js +9 -8
- package/dist/strategies/cursor-strategy.js +21 -21
- package/dist/strategies/gemini-strategy.js +18 -18
- package/dist/strategies/index.js +69 -69
- package/dist/strategies/mcp-server-config.js +1 -1
- package/dist/strategies/tool-broker.js +1 -0
- package/package.json +4 -4
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
var Ct=Object.defineProperty;var $t=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(o){throw t=[o],o}};var Nt=(n,e)=>{for(var t in e)Ct(n,t,{get:e[t],enumerable:!0})};var st={};Nt(st,{zodToJson:()=>re});import{z as rt}from"zod";import{zodToJsonSchema as Dt}from"zod-to-json-schema";function Bt(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=Bt(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=Dt(n,e)}catch{return null}if(t&&o)try{return le(o)}catch{return o}return o}var ye=$t(()=>{});import{registerStrategy as Je}from"@zibby/agent-workflow";import{AgentStrategy as Ut,getSkill as ut,NO_INTEGRATION_TOGGLEABLE_SKILL_IDS as Gt,formatProviderError as Jt}from"@zibby/agent-workflow";import{query as jt}from"@anthropic-ai/claude-agent-sdk";import Pt 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=Pt.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 Lt=new Set(["claude"]);function Mt(){let n=String(process.env.MCP_ALWAYS_LOAD??"").trim().toLowerCase();return!(n==="0"||n==="false"||n==="off")}function Rt(n,e){return Lt.has(n)?Mt()?typeof e.alwaysLoad=="boolean"?{alwaysLoad:e.alwaysLoad}:{}:{}:{}}function ne(n,e,{processEnv:t}={}){if(!e)return null;let o=Rt(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 dt}from"fs";import{homedir as pt}from"os";import{join as ee}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 zn,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as Fn}from"@zibby/agent-workflow";var it=[{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",pickerVisible:!0},{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.6-luna",vendor:"codex",label:"Codex \xB7 GPT-5.2",family:"gpt-5",retiredCanonicalId:"gpt-5.2-codex",unavailable:"2026-08-26 API-key probe: 404 Model not found"},{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.5",vendor:"codex",label:"Codex \xB7 GPT-5.3",family:"gpt-5",retiredCanonicalId:"gpt-5.3",unavailable:"2026-08-26 API-key probe: model_not_found"},{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:"gpt-5.6-sol",canonicalId:"gpt-5.6-sol",vendor:"codex",label:"Codex \xB7 GPT-5.6 Sol",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 it)t.vendor===n&&(e[t.alias]=t.canonicalId);return e}function Kt(){let n={};for(let e of it)!e.retiredCanonicalId||e.retiredCanonicalId===e.canonicalId||(n[e.alias]={alias:e.alias,vendor:e.vendor,requested:e.retiredCanonicalId,actual:e.canonicalId,evidence:e.unavailable||"retired by the vendor"});return n}function at(n,e){let t=Kt()[e];return!t||t.vendor!==n?null:`MODEL REPOINTED: this run pinned "${t.alias}" (${t.requested}), but that model is RETIRED at the vendor (${t.evidence}) \u2014 running on "${t.actual}" instead. Output did NOT come from ${t.requested}. Redeploy the agent with a current model to make the pin match reality.`}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 lt={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"),ct=be("gemini"),Zn={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};function Q(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 xe(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 Yt}from"module";import L from"process";var ft=Yt(import.meta.url);function zt(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 mt(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 Ft(n){let e=mt(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}:${zt(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}`:"",o=mt(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 Ht(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):gt(n)}function _e(n){let e=String(n).replace(/\s+/g," ").trim();return e.length>400?`${e.slice(0,400)}\u2026`:e}var yt=(n,e)=>{let t=String(n??"");return t.length>e?`${t.slice(0,e)}\u2026`:t},Vt=/secret|token|password|passwd|credential|authorization|bearer|api[-_]?key|private[-_]?key|access[-_]?key/i,ht=(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=Vt.test(o)||o==="value"&&typeof n.key=="string";t[o]=s&&typeof r=="string"&&r?"[redacted]":ht(r,e+1)}return t},_t=n=>{try{if(n==null)return"";let e=ht(n),t=typeof e=="string"?e:JSON.stringify(e);return yt(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""}},Zt=500;function Wt(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=
|
|
3
|
-
`);
|
|
1
|
+
var jt=Object.defineProperty;var Ut=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var Jt=(n,e)=>{for(var t in e)jt(n,t,{get:e[t],enumerable:!0})};var gt={};Jt(gt,{zodToJson:()=>oe});import{z as mt}from"zod";import{zodToJsonSchema as Ht}from"zod-to-json-schema";function Vt(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 ue(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]=ue(n[e][t]);for(let e of["anyOf","oneOf","allOf"])Array.isArray(n[e])&&(n[e]=n[e].map(ue));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=ue(n.properties[r]);t.has(r)||(o=Vt(o)),n.properties[r]=o}n.required=e}return n.items&&(Array.isArray(n.items)?n.items=n.items.map(ue):n.items=ue(n.items)),n}function oe(n,e={target:"openApi3"}){if(!n)return null;let t=e?.target==="openAi",r=null;if(typeof mt?.toJSONSchema=="function")try{r=mt.toJSONSchema(n)}catch{}if(!r)try{r=Ht(n,e)}catch{return null}if(t&&r)try{return ue(r)}catch{return r}return r}var _e=Ut(()=>{});import{registerStrategy as He}from"@zibby/agent-workflow";import{AgentStrategy as Zt,getSkill as Et,NO_INTEGRATION_TOGGLEABLE_SKILL_IDS as qt,formatProviderError as Xt}from"@zibby/agent-workflow";import{query as Qt}from"@anthropic-ai/claude-agent-sdk";import Gt from"node:process";var ct=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 ce(n=Gt.env){let e={},t=new Set(ct);for(let[r,o]of Object.entries(n))t.has(r)||o!==void 0&&(e[r]=o);return e}function ut(n){return!!n&&(n.transport==="http"||typeof n.url=="string"&&!n.command)}var ft=Object.freeze({claude:"native",codex:"broker",gemini:"broker",cursor:"eager"});function dt(n){return ft[n]||"eager"}var zt=new Set(Object.entries(ft).filter(([,n])=>n==="native").map(([n])=>n)),Ve=Symbol("zibby.mcp.alwaysLoad");function Yt(){let n=String(process.env.MCP_ALWAYS_LOAD??"").trim().toLowerCase();return!(n==="0"||n==="false"||n==="off")}function Ft(n,e){return zt.has(n)?Yt()?typeof e.alwaysLoad=="boolean"?{alwaysLoad:e.alwaysLoad}:{}:{}:{}}function ne(n,e,{processEnv:t}={}){if(!e)return null;let r=Ft(n,e),o=i=>(e.alwaysLoad===!0&&Object.defineProperty(i,Ve,{value:!0,enumerable:!1}),i);if(ut(e)){let i=String(e.url||"").trim();if(!i)return null;let a=e.headers&&typeof e.headers=="object"?e.headers:void 0;switch(n){case"claude":return o({type:"http",url:i,...a&&{headers:a},...r});case"codex":return o({url:i,...a&&{http_headers:a}});case"gemini":return o({url:i,type:"http",...a&&{headers:a}});case"cursor":return o({url:i,...a&&{headers:a}});default:return o({type:"http",url:i,...a&&{headers:a},...r})}}let s={command:e.command};return e.args?.length&&(s.args=e.args),e.cwd&&(s.cwd=e.cwd),t?s.env={...t,...e.env||{}}:e.env&&Object.keys(e.env).length&&(s.env=e.env),o({...s,...r})}function pt(n){return ut(n)?`http \u2192 ${String(n.url||"").replace(/\?.*$/,"")}`:`${n?.command||"?"} ${(n?.args||[]).join(" ")}`.trim()}_e();import{writeFileSync as Xe,mkdirSync as Qe,existsSync as pe,readFileSync as At}from"fs";import{homedir as bt}from"os";import{join as ee}from"path";import Se from"chalk";var te={debug:0,info:1,warn:2,error:3,silent:4},We=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+=Se.dim(` ${JSON.stringify(r)}`)),i}_getPrefix(e){return{debug:Se.gray("[DEBUG]"),info:Se.cyan("[INFO]"),warn:Se.yellow("[WARN]"),error:Se.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 We;import{timeline as fe,Timeline as cr,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as ur}from"@zibby/agent-workflow";var yt=[{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",pickerVisible:!0},{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.6-luna",vendor:"codex",label:"Codex \xB7 GPT-5.2",family:"gpt-5",retiredCanonicalId:"gpt-5.2-codex",unavailable:"2026-08-26 API-key probe: 404 Model not found"},{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.5",vendor:"codex",label:"Codex \xB7 GPT-5.3",family:"gpt-5",retiredCanonicalId:"gpt-5.3",unavailable:"2026-08-26 API-key probe: model_not_found"},{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:"gpt-5.6-sol",canonicalId:"gpt-5.6-sol",vendor:"codex",label:"Codex \xB7 GPT-5.6 Sol",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 ve(n){let e={};for(let t of yt)t.vendor===n&&(e[t.alias]=t.canonicalId);return e}function Wt(){let n={};for(let e of yt)!e.retiredCanonicalId||e.retiredCanonicalId===e.canonicalId||(n[e.alias]={alias:e.alias,vendor:e.vendor,requested:e.retiredCanonicalId,actual:e.canonicalId,evidence:e.unavailable||"retired by the vendor"});return n}function ht(n,e){let t=Wt()[e];return!t||t.vendor!==n?null:`MODEL REPOINTED: this run pinned "${t.alias}" (${t.requested}), but that model is RETIRED at the vendor (${t.evidence}) \u2014 running on "${t.actual}" instead. Output did NOT come from ${t.requested}. Redeploy the agent with a current model to make the pin match reality.`}function de(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 _t={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 Ze=ve("claude"),qe=ve("codex"),St=ve("gemini"),pr={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};function Q(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 ke(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 en}from"module";import D from"process";var Ot=en(import.meta.url);function tn(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 xt(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 nn(n){let e=xt(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}:${tn(t)}`}function Tt(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=xt(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(", ")}]`}function rn(n){if(!n||typeof n!="object")return"";let e=n.message?.content??n.content;if(Array.isArray(e)){let t=e.filter(r=>r&&r.type==="text"&&typeof r.text=="string"&&r.text.trim()).map(r=>r.text.trim());if(t.length)return Ee(t.join(" "))}else if(typeof e=="string"&&e.trim())return Ee(e);return n.error&&typeof n.error=="object"&&typeof n.error.message=="string"?Ee(n.error.message):typeof n.message=="string"&&n.message.trim()?Ee(n.message):typeof n.result=="string"&&n.result.trim()?Ee(n.result):Tt(n)}function Ee(n){let e=String(n).replace(/\s+/g," ").trim();return e.length>400?`${e.slice(0,400)}\u2026`:e}function et(n){let e=String(n??"").trim().slice(0,400);return!e||e.startsWith("```")||e.startsWith("{")||e.startsWith("[")?!0:/"reply"\s*:/.test(e)}var Ce=(n,e)=>{let t=String(n??"");return t.length>e?`${t.slice(0,e)}\u2026`:t},on=/secret|token|password|passwd|credential|authorization|bearer|api[-_]?key|private[-_]?key|access[-_]?key/i,vt=(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=on.test(r)||r==="value"&&typeof n.key=="string";t[r]=s&&typeof o=="string"&&o?"[redacted]":vt(o,e+1)}return t},se=n=>{try{if(n==null)return"";let e=vt(n),t=typeof e=="string"?e:JSON.stringify(e);return Ce(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""}},sn=500;function tt(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=se(i);return a&&(s.error=a),s}function an(){try{if(D.env.CLAUDE_CODE_EXECUTABLE&&pe(D.env.CLAUDE_CODE_EXECUTABLE))return D.env.CLAUDE_CODE_EXECUTABLE;let n=D.platform,e=D.arch,t=`@anthropic-ai/claude-agent-sdk-${n}-${e}`,r=n==="win32"?"claude.exe":"claude";try{let o=Ot.resolve(`${t}/package.json`),s=ee(o,"..",r);if(pe(s))return s}catch{}try{let o=Ot.resolve("@anthropic-ai/claude-agent-sdk/package.json"),s=ee(o,"..");for(let a of[r,ee("vendor",r),ee("bin",r)]){let l=ee(s,a);if(pe(l))return l}let i=ee(s,"..",`claude-agent-sdk-${n}-${e}`,r);if(pe(i))return i}catch{}}catch{}return null}var we=an();we&&c.debug(`Claude native CLI resolved to baked binary: ${we}`);var Ie=class extends Zt{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!D.env.ANTHROPIC_API_KEY||!!D.env.ANTHROPIC_API_KEY_POOL,r=!!D.env.CLAUDE_CODE_OAUTH_TOKEN||!!D.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,o=!!D.env.ANTHROPIC_AUTH_TOKEN||!!D.env.ANTHROPIC_AUTH_TOKEN_POOL,s=t||r||o;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:r,workspace:o=D.cwd(),schema:s=null,images:i=[],skills:a=null,sessionPath:l=null,nodeName:f=null,timeout:m,config:y={},activityLog:b=!1,signal:A=null,sessionId:$,resume:U,forkSession:K,sessionStore:T}=t,w=de("claude",r),M=Ze[w]||w;Ze[w]&&w!==M&&c.debug(`Mapped model: ${w} \u2192 ${M}`);let E=[Q("ANTHROPIC_API_KEY"),Q("CLAUDE_CODE_OAUTH_TOKEN"),Q("ANTHROPIC_AUTH_TOKEN")];try{c.debug(`Invoking Claude Agent SDK with model: ${M}, skills: ${JSON.stringify(a)}`);let I=Ce,x=(S,z)=>{try{console.log(JSON.stringify({mode:S,...z}))}catch{}},v=D.env.CLAUDE_CODE_OAUTH_TOKEN,N=D.env.ANTHROPIC_API_KEY,j=D.env.ANTHROPIC_AUTH_TOKEN;D.env.CLAUDE_CODE_CREDENTIALS_JSON?un(D.env.CLAUDE_CODE_CREDENTIALS_JSON):v&&cn(v,D.env.__ZIBBY_CLAUDE_PLAN);let Y=D.env.__ZIBBY_CLAUDE_PLAN,B=Y?Y.charAt(0).toUpperCase()+Y.slice(1):null,G;if(v?G=B?`Claude ${B} plan \xB7 ***${v.slice(-4)}`:`Subscription \xB7 ***${v.slice(-4)}`:N?G=`API key \xB7 ***${N.slice(-4)}`:j?G=`Bearer \xB7 ***${j.slice(-4)}`:G="NONE \u2014 request will fail",!b){let S=(await import("chalk")).default;console.log(""),console.log(` ${S.cyan("\u25C6")} ${S.bold(M)}`),console.log(` ${S.dim("Auth: ")}${G}`),console.log(` ${S.dim("Workdir: ")}${o}`),console.log(""),console.log(S.bold("Prompt sent to LLM:")),console.log(S.dim("\u2500".repeat(60))),console.log(S.dim(e)),console.log(S.dim("\u2500".repeat(60)))}let{allowedTools:X,mcpServers:F}=this._resolveSkills(a,{sessionPath:l,workspace:o,nodeName:f});for(let S of t.extraMcpServers||[])if(S&&S.serverName&&S.def){if(Object.prototype.hasOwnProperty.call(F,S.serverName)){console.warn(`[custom-mcp] skip "${S.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let z=ne("claude",S.def);z&&(F[S.serverName]=z,X.push(`mcp__${S.serverName}__*`))}try{let S={cwd:o,allowedTools:X,...t.effort?{effort:t.effort}:{},...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:M,env:ce(D.env),...we&&{pathToClaudeCodeExecutable:we},...Object.keys(F).length>0&&{mcpServers:F},...$&&{sessionId:$},...U&&{resume:U},...K&&{forkSession:!0},...T&&{sessionStore:T}};if(s){let p=typeof s.parse=="function"?oe(s):s;S.outputFormat={type:"json_schema",schema:p},c.debug("Structured output enforced via SDK outputFormat")}c.debug(`Agent SDK options: ${JSON.stringify({cwd:S.cwd,toolCount:X.length,permissionMode:S.permissionMode,model:S.model,hasOutputFormat:!!S.outputFormat})}`);let z="",h=0,L=new Map,P=[];c.debug("Starting Claude Agent SDK query stream");let H=e,J=Array.isArray(i)?i.filter(u=>u&&typeof u.path=="string"&&u.path.startsWith("/")):[];if(J.length){let u=J.map((p,_)=>` ${_+1}. ${p.path}${p.name?` (${p.name})`:""}`).join(`
|
|
3
|
+
`);H=`${e}
|
|
4
4
|
|
|
5
5
|
# Attached image files \u2014 VIEW THESE
|
|
6
|
-
The user attached ${
|
|
7
|
-
${u}`}let
|
|
6
|
+
The user attached ${J.length} image(s), saved locally. Use the Read tool on each path to SEE the image, then use what it shows to answer:
|
|
7
|
+
${u}`}let ae;try{ae=Qt({prompt:H,options:S})}catch(u){throw c.error(`Failed to initialize Claude Agent SDK: ${u.message}`),u}let O=null,R=0,V=!1,Z=3;if(A?.aborted){let u=new Error("Aborted via signal");throw u.name="AbortError",u}try{for await(let u of ae){if(A?.aborted){let _=new Error("Aborted via signal");throw _.name="AbortError",_}if(P.push(u),u.type==="system"&&u.subtype==="init"){let _=u.mcp_servers||[];if(_.length>0){let g=_.map(d=>`${d.name}=${d.status}${d.error?` (${String(d.error).slice(0,120)})`:""}`).join(", ");c.info(`[mcp] SDK init \u2014 ${_.length} server(s): ${g}`);for(let d of _)(d.status==="failed"||d.status==="needs-auth")&&c.warn(`[mcp] server '${d.name}' did not connect: status=${d.status}`,{name:d.name,status:d.status,error:d.error})}else Object.keys(F||{}).length>0&&c.warn(`[mcp] SDK init returned no mcp_servers despite passing ${Object.keys(F).length} server(s) \u2014 SDK version may not expose this field, or config was dropped`);if(Array.isArray(u.tools)){let g=u.tools.filter(d=>d.startsWith("mcp__"));if(g.length>0){let d=q=>q.split("__")[1]||"",C=new Set(Object.entries(F||{}).filter(([,q])=>q&&q.alwaysLoad===!0).map(([q])=>q)),k=g.filter(q=>C.has(d(q))),W=g.length-k.length,le={};for(let q of g){let re=d(q);C.has(re)||(le[re]=(le[re]||0)+1)}let lt=Object.entries(le).sort((q,re)=>re[1]-q[1]).map(([q,re])=>`${q}:${re}`).join(" ");c.info(`[mcp] ${g.length} tool(s) reachable \u2014 ${k.length} IN PROMPT${k.length?` (${k.join(", ")})`:""}; ${W} DEFERRED behind ToolSearch${lt?` [${lt}]`:""}`)}else Object.keys(F||{}).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 _=Number(u.attempt)||0,g=Number(u.max_retries)||0,d=u.error_status!=null?String(u.error_status):"?",C=typeof u.error=="string"?u.error:"error",k=Number.isFinite(u.retry_delay_ms)?Math.round(u.retry_delay_ms):null,W=`upstream ${d} (${C}) \u2014 SDK retry ${_}/${g}`+(k!=null?` in ${k}ms`:"");b&&x("turn:retry",{status:d,kind:C,attempt:_,maxRetries:g,delayMs:k,detail:W}),c.warn(`[claude] transient ${W}`);continue}if(u.type==="error"||u.error){let _=typeof u.error=="string"?u.error:u.error?.type||u.error?.name||null,g=u.error_status??u.error?.status??null,d=rn(u);try{c.error("SDK error event raw payload",{fullMessage:JSON.stringify(u,null,2)})}catch{}let C=new Error(Xt({kind:_,status:g,text:d}));C.providerErrorKind=_||null;let k=g==null?NaN:Number(g);throw C.providerErrorStatus=Number.isInteger(k)&&k>=100&&k<=599?k:null,C.providerErrorText=d,C}let p=nn(u);if(p!==null)if(p===O){if(R++,R>=Z)throw new Error(`API stuck in loop (${R}x identical): ${Tt(u)}`)}else O=p,R=1;if(u.type==="assistant"||u.constructor?.name==="AssistantMessage"){let _=u.message?.content||u.content||[],g=Array.isArray(_)&&_.some(d=>d&&d.type==="tool_use");for(let d of _)if(d.type==="thinking"&&d.thinking)b?x("turn:thinking",{text:I(d.thinking,600)}):console.log(`${d.thinking.substring(0,200)}${d.thinking.length>200?"...":""}`);else if(d.type==="text"&&d.text){if(z+=d.text,b&&(g||!V))if(!g&&et(d.text))V=!0;else{let C=I(d.text.trim(),200);C&&x("turn:narration",{text:C,withTool:g})}b||(d.text.length<500?console.log(`${d.text}`):console.log(`${d.text.substring(0,200)}... (${d.text.length} chars)`))}else if(d.type==="tool_use")if(h++,d.name.includes("memory")?fe.stepMemory(`Tool: ${d.name}`):fe.stepTool(`Tool: ${d.name}`),b){let k=se(d.input);x("turn:tool",{name:d.name,...k?{input:k}:{}}),d.id&&(L.set(d.id,d.name),L.size>sn&&L.delete(L.keys().next().value))}else{let k=JSON.stringify(d.input).substring(0,100);console.log(` Input: ${k}${JSON.stringify(d.input).length>100?"...":""}`)}}else if(u.type==="user"){if(b){let _=u.message?.content||u.content;if(Array.isArray(_))for(let g of _){if(!g||g.type!=="tool_result")continue;let d=L.get(g.tool_use_id);x("turn:tool-result",{...d?{name:d}:{},...tt(g)})}}}else if(u.type==="result"||u.constructor?.name==="ResultMessage"){let _=u.result||u.text||u.content||z;try{ln({message:u,sessionPath:l,nodeName:f,model:w,toolCallCount:h})}catch(d){c.debug(`usage.json write failed: ${d.message}`)}let g=ke(u?.usage||u?.message?.usage);if(s){if(u.structured_output){c.debug("Using SDK native structured_output");let C=typeof s.parse=="function"?s.parse(u.structured_output):u.structured_output;return{raw:_,structured:C,...g?{usage:g}:{},toolUseCount:h}}if(_){let d=this._extractJson(_,s);if(d)return{raw:_,structured:d,...g?{usage:g}:{},toolUseCount:h}}c.warn(`Could not extract structured output \u2014 returning raw text (${(_||"").length} chars)`)}return _||""}}if(c.warn(`Agent SDK ended without result. Collected ${P.length} messages`),z.length>0)return c.debug("Returning accumulated text from messages"),z;throw new Error("Claude Agent SDK query ended without result")}catch(u){let p={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(u,Object.getOwnPropertyNames(Object(u)))}catch{return String(u)}})()};throw c.error(`Error during query stream: ${u?.message||u}`,
|
|
10
|
-
\u25C6 Model: ${
|
|
11
|
-
`),Array.isArray(l)&&l.length>0){let
|
|
12
|
-
${
|
|
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}`,p),u}}catch(S){throw c.error("Claude Agent SDK call failed",{message:S?.message,name:S?.name,code:S?.code,cause:S?.cause?.message||S?.cause}),S}}finally{for(let I of E)I.dispose()}}_resolveSkills(e,t){let r=["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:[...r],mcpServers:{}};let o=[...r],s={},i=D.env.WORKFLOW_ENABLED_INTEGRATIONS,a=typeof i=="string"&&i.trim()!==""?new Set(i.split(",").map(m=>m.trim()).filter(Boolean)):null,l=m=>{let y=Et(m);return y?.meta?.toggleable===!0?!0:y?.meta?.toggleable===void 0&&qt.includes(m)},f=m=>a!==null&&a.size>0&&l(m)&&!a.has(m);for(let m of e){if(f(m)){c.debug(`Skill "${m}" disabled by enabledIntegrations allowlist \u2014 skipping`);continue}let y=Et(m);if(!y){c.warn(`Unknown skill "${m}" \u2014 skipping`);continue}if(y.allowedTools&&o.push(...y.allowedTools),typeof y.resolve=="function"){let b=y.resolve(t),A=ne("claude",b);A&&(s[y.serverName]=A,c.debug(`MCP: ${y.serverName} \u2192 ${pt(b)}`))}}return{allowedTools:o,mcpServers:s}}_extractJson(e,t){let r=[()=>{if(e.includes("===JSON_START===")){let o=e.indexOf("===JSON_START===")+16,s=e.indexOf("===JSON_END===");return e.substring(o,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 o=e.indexOf("{"),s=e.lastIndexOf("}");if(o!==-1&&s>o)return e.substring(o,s+1)}];for(let o of r)try{let s=o();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 ln({message:n,sessionPath:e,nodeName:t,model:r,toolCallCount:o}){if(!e||!t)return;let s=n?.usage||n?.message?.usage||{},i=Oe(s.input_tokens,s.inputTokens),a=Oe(s.output_tokens,s.outputTokens),l=Oe(s.cache_read_input_tokens,s.cacheReadInputTokens),f=Oe(s.cache_creation_input_tokens,s.cacheCreationInputTokens),m=Oe(n?.duration_ms,n?.durationMs),y={model:r||null,input_tokens:i,output_tokens:a,cache_read_tokens:l,cache_creation_tokens:f,tool_call_count:typeof o=="number"?o:null,duration_ms:m,captured_at:new Date().toISOString()},b=ee(e,t);try{Qe(b,{recursive:!0})}catch{}Xe(ee(b,"usage.json"),JSON.stringify(y,null,2),"utf-8")}function Oe(...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 cn(n,e){let t=ee(bt(),".claude"),r=ee(t,".credentials.json"),o={claudeAiOauth:{accessToken:n,refreshToken:"",expiresAt:Date.now()+365*24*60*60*1e3,scopes:["user:inference","user:profile"],...e?{subscriptionType:String(e).toLowerCase()}:{}}};try{if(pe(r)&&JSON.parse(At(r,"utf-8"))?.claudeAiOauth?.accessToken===n)return;Qe(t,{recursive:!0}),Xe(r,JSON.stringify(o,null,2),"utf-8"),c.debug(`Wrote Claude Code OAuth credentials to ${r}`)}catch(s){c.warn(`Could not write ${r}: ${s.message} \u2014 Claude SDK may fail to authenticate.`)}}function un(n){let e=ee(bt(),".claude"),t=ee(e,".credentials.json"),r;try{r=JSON.parse(n)}catch(o){c.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${o.message}`);return}if(!r?.claudeAiOauth?.accessToken){c.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if(pe(t)){let o=JSON.parse(At(t,"utf-8"));if(o?.claudeAiOauth?.accessToken===r.claudeAiOauth.accessToken&&o?.claudeAiOauth?.expiresAt===r.claudeAiOauth.expiresAt)return}Qe(e,{recursive:!0}),Xe(t,JSON.stringify(r,null,2),"utf-8"),c.debug(`Wrote full Claude Code credentials blob to ${t}`)}catch(o){c.warn(`Could not write ${t}: ${o.message} \u2014 Claude SDK may fail to authenticate.`)}}import{AgentStrategy as On,getSkill as An}from"@zibby/agent-workflow";import{mkdtempSync as fn,writeFileSync as dn,mkdirSync as pn,existsSync as mn}from"fs";import{join as Ae,dirname as kt}from"path";import{tmpdir as gn}from"os";import{fileURLToPath as yn}from"url";var wt="toolbox";function hn(){let n=kt(yn(import.meta.url));for(let e=n,t=0;t<4;t++,e=kt(e)){let r=Ae(e,"mcp","tool-broker-server.js");if(mn(r))return r}throw new Error(`[tool-broker] cannot find mcp/tool-broker-server.js from ${n} \u2014 the package layout changed, or the build did not emit it.`)}function _n(){let n=String(process.env.MCP_TOOL_BROKER??"").trim().toLowerCase();return!(n==="0"||n==="false"||n==="off")}function Sn(n){if(n){let e=Ae(n,".mcp-broker");return pn(e,{recursive:!0}),Ae(e,"spec.json")}return Ae(fn(Ae(gn(),"mcp-broker-")),"spec.json")}function $e(n,e,{sessionPath:t}={}){let r=e&&typeof e=="object"?e:{},o=Object.keys(r);if(!o.length||dt(n)!=="broker"||!_n()||o.length===1)return r;let s=o.filter(l=>r[l]&&r[l][Ve]===!0),i=Sn(t);dn(i,JSON.stringify({servers:r,pinned:s},null,2),{mode:384}),console.error(`[tool-broker] ${n}: ${o.length} server(s) behind "${wt}"${s.length?` (pinned: ${s.join(", ")})`:""} \u2014 spec ${i}`);let a={command:process.execPath,args:[hn(),"--spec",i]};return{[wt]:a}}import{execSync as Pe}from"node:child_process";import{execSync as En}from"node:child_process";function Ne(n){if(!/^[A-Za-z0-9._-]+$/.test(n))return!1;try{return En(`command -v ${n}`,{encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim().length>0}catch{return!1}}_e();import{readFileSync as bn,mkdirSync as nt,cpSync as xn,existsSync as Tn}from"node:fs";import{join as be}from"node:path";import{homedir as vn}from"node:os";function rt(n){if(Array.isArray(n))return n.map(rt);if(n&&typeof n=="object"){let e={};for(let[t,r]of Object.entries(n))r!==null&&(e[t]=rt(r));return e}return n}var Le=class extends On{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):Ne("codex")?!0:(c.warn("[Codex] codex CLI not on PATH. Install: npm install -g @openai/codex"),!1)}async invoke(e,t={}){let{model:r,workspace:o=process.cwd(),schema:s=null,images:i=[],skills:a=null,plugins:l=null,sessionPath:f=null,nodeName:m=null,timeout:y,config:b={},activityLog:A=!1,signal:$=null}=t,U=[Q("OPENAI_API_KEY"),Q("CODEX_API_KEY")];try{let{Codex:K}=await import("@openai/codex-sdk"),T=de("codex",r),w=qe[T]||T;qe[T]&&T!==w&&c.debug(`Mapped model: ${T} \u2192 ${w}`);let M=ht("codex",T);M&&c.warn(M),c.debug(`Invoking Codex SDK with model: ${w}, skills: ${JSON.stringify(a)}`);let E=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;E&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=E);let I=E?` | key: ***${E.slice(-4)}`:" | key: not set";if(console.log(`
|
|
10
|
+
\u25C6 Model: ${w}${I}
|
|
11
|
+
`),Array.isArray(l)&&l.length>0){let h=this._resolveCodexHome(f);process.env.CODEX_HOME=h;try{nt(h,{recursive:!0})}catch{}this._ensurePlugins(l,h)}let x=(h,L)=>{try{console.log(JSON.stringify({mode:h,...L}))}catch{}};if(!A){let h=(await import("chalk")).default;console.log(`
|
|
12
|
+
${h.bold("Prompt sent to LLM:")}`),console.log(h.dim("\u2500".repeat(60))),console.log(h.dim(e)),console.log(h.dim("\u2500".repeat(60)))}let v=this._resolveSkillsToMcp(a,{sessionPath:f,workspace:o,nodeName:m});for(let h of t.extraMcpServers||[])if(h&&h.serverName&&h.def){if(Object.prototype.hasOwnProperty.call(v,h.serverName)){console.warn(`[custom-mcp] skip "${h.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let L=ne("codex",h.def);L&&(v[h.serverName]=L)}let N=$e("codex",v,{sessionPath:f}),j={};t.effort&&(j.model_reasoning_effort=t.effort),Object.keys(N).length>0&&(j.mcp_servers=N,Object.values(N).some(h=>h&&typeof h.url=="string")&&(j.experimental_use_rmcp_client=!0),c.debug(`[Codex] MCP servers: ${Object.keys(N).join(", ")}`+(N===v?"":` (broker over ${Object.keys(v).join(", ")})`)));let Y=this._resolveCodexBin(),B=new K({...Y?{codexPathOverride:Y}:{},...Object.keys(j).length>0&&{config:j},env:ce(process.env)}),G=o;try{G&&nt(G,{recursive:!0})}catch{}(!G||!Tn(G))&&(G=process.cwd());let X=B.startThread({workingDirectory:G,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),F=s&&typeof s.parse=="function",S=$?{signal:$}:{};if(s)try{let h=F?oe(s,{target:"openAi"}):s;S.outputSchema=h,c.debug("Structured output via SDK outputSchema")}catch(h){c.warn(`[Codex] Schema conversion failed, will extract from text: ${h.message}`)}let z=Array.isArray(i)?i.filter(h=>h&&typeof h.path=="string"&&h.path.startsWith("/")):[];if(z.length&&(e=`${e}
|
|
13
13
|
|
|
14
14
|
# Attached image files \u2014 VIEW THESE
|
|
15
|
-
The user attached ${
|
|
16
|
-
${
|
|
17
|
-
`)}`)
|
|
18
|
-
`).some(
|
|
15
|
+
The user attached ${z.length} image(s), saved locally. Read each path to SEE the image, then use what it shows to answer:
|
|
16
|
+
${z.map((h,L)=>` ${L+1}. ${h.path}${h.name?` (${h.name})`:""}`).join(`
|
|
17
|
+
`)}`),$?.aborted){let h=new Error("Aborted via signal");throw h.name="AbortError",h}try{let{events:h}=await X.runStreamed(e,S),L=0,P="",H=null,J=new Set,ae=500,O=p=>p.type==="mcp_tool_call"?`mcp__${p.server}__${p.tool}`:p.type==="command_execution"?"Bash":p.type==="web_search"?"WebSearch":p.name||p.tool||"unknown",R=p=>p.type==="mcp_tool_call"?se(p.arguments):p.type==="command_execution"?se({command:p.command}):p.type==="web_search"?se({query:p.query}):se(p.arguments||p.input),V=p=>p==="mcp_tool_call"||p==="command_execution"||p==="web_search"||p==="tool_call"||p==="function_call",Z=p=>{let _=p.id||`${p.type}:${J.size}`;if(J.has(_))return;J.add(_),J.size>ae&&J.delete(J.values().next().value);let g=R(p);x("turn:tool",{name:O(p),...g?{input:g}:{}})},u=p=>{let _=p.status==="failed"||!!(p.error&&p.error.message),g;p.type==="mcp_tool_call"?g=_?p.error&&p.error.message||p.result&&p.result.content||"":p.result&&p.result.content||"":p.type==="command_execution"&&(g=p.aggregated_output||""),x("turn:tool-result",{name:O(p),...tt({content:g,is_error:_})})};for await(let p of h){if($?.aborted){let g=new Error("Aborted via signal");throw g.name="AbortError",g}let _=p.type;if(A&&_==="item.started"&&p.item&&V(p.item.type))Z(p.item);else if(_==="item.completed"){let g=p.item,d=g?.type;if(d==="mcp_tool_call"){L++;let C=`${g.server}/${g.tool}`;if(fe.stepTool(`Tool: ${C}`),A)Z(g),u(g);else if(g.arguments){let k=JSON.stringify(g.arguments),W=k.length>100?`${k.substring(0,100)}...`:k;console.log(` Input: ${W}`)}}else if(V(d)){L++;let C=g.name||g.tool||g.command||g.query||"unknown";fe.stepTool(`Tool: ${C}`),A&&(Z(g),d==="command_execution"&&u(g))}else if(d==="agent_message")if(P=g.text||"",A){if(!et(P)){let C=Ce(P.trim(),200);C&&x("turn:narration",{text:C,withTool:!1})}}else P.length<500?console.log(P):console.log(`${P.substring(0,200)}... (${P.length} chars)`)}else _==="turn.completed"?(c.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(p.usage||{})}`),p.usage&&(H=p.usage)):c.debug(`[Codex] Event: ${_} ${JSON.stringify(p).slice(0,300)}`)}if(c.debug(`[Codex] Last agent message (${P.length} chars): ${P.slice(0,500)}`),s){if(!P)throw new Error("Codex agent returned no response");let p=JSON.parse(P),_=p;if(F)try{_=s.parse(p)}catch{_=s.parse(rt(p))}c.debug("\u2705 [Codex] Structured output validated");let g=ke(H);return{raw:P,structured:_,...g?{usage:g}:{}}}return P||""}catch(h){let L=h.message||String(h);throw c.error(`\u274C [Codex] SDK call failed: ${L}`),L.includes("exited with code")&&(S.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")),h}}finally{for(let K of U)K.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let o of e){let s=An(o);if(!s){c.warn(`[Codex] Unknown skill "${o}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let a=s.serverName||o,l=ne("codex",i,{processEnv:process.env});l&&(r[a]=l,c.debug(`[Codex] MCP: ${a} \u2192 ${i.command} ${(i.args||[]).join(" ")}`))}return r}_resolveCodexHome(e){return process.env.CODEX_HOME?process.env.CODEX_HOME:e&&!this._isTempPath(e)?be(e,".codex-home"):be(vn(),".codex")}_isTempPath(e){let t=String(process.env.TMPDIR||"/tmp").replace(/\/+$/,""),r=String(e||"");return r==="/tmp"||r.startsWith("/tmp/")||r===t||r.startsWith(t+"/")}_resolveCodexBin(){if(process.env.CODEX_BIN)return process.env.CODEX_BIN;try{return Pe("command -v codex",{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}_ensurePlugins(e,t){let r={...process.env,CODEX_HOME:t};for(let o of e){let s=typeof o=="string"?o:o?.name,i=o&&typeof o=="object"?o.marketplacePath:null;if(!s||!i){c.warn(`[Codex][plugins] skipping malformed plugin declaration: ${JSON.stringify(o)} (need { name, marketplacePath })`);continue}let a=this._readMarketplaceName(i),l=`${s}@${a}`;if(this._isPluginInstalled(l,r)){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{Pe(`codex plugin marketplace add ${JSON.stringify(f)}`,{env:r,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),Pe(`codex plugin add ${JSON.stringify(l)}`,{env:r,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),console.log(`\u25C6 [Codex] plugin ${l} installed`)}catch(m){let y=m.stderr&&m.stderr.toString()||m.message||String(m);throw c.error(`[Codex][plugins] failed to install ${l}: ${y}`),new Error(`Codex plugin install failed for ${l}: ${y}`,{cause:m})}}}_safeMarketplacePath(e,t){if(!String(e).includes("@"))return e;let r=be(t,".zibby-mkt",String(e).replace(/[^a-zA-Z0-9]+/g,"_"));try{return nt(be(t,".zibby-mkt"),{recursive:!0}),xn(e,r,{recursive:!0}),r}catch(o){return c.warn(`[Codex][plugins] could not copy @-containing marketplace to a safe path: ${o.message}`),e}}_readMarketplaceName(e){let t=be(e,".agents","plugins","marketplace.json"),r;try{r=JSON.parse(bn(t,"utf-8"))}catch(o){throw new Error(`Codex plugin marketplace manifest missing/unreadable at ${t}: ${o.message}`,{cause:o})}if(!r?.name||typeof r.name!="string")throw new Error(`Codex plugin marketplace manifest at ${t} has no string "name"`);return r.name}_isPluginInstalled(e,t){try{return Pe("codex plugin list",{env:t,stdio:"pipe",timeout:15e3,encoding:"utf-8"}).split(`
|
|
18
|
+
`).some(o=>o.includes(e)&&/installed/.test(o))}catch{return!1}}};import{AgentStrategy as In,getSkill as Cn}from"@zibby/agent-workflow";import{spawn as $n}from"node:child_process";_e();import{existsSync as Ct,mkdirSync as $t,readFileSync as Nt,rmSync as Nn,writeFileSync as Pt}from"node:fs";import{join as ie}from"node:path";import{z as It}from"zod";import{zodToJsonSchema as kn}from"zod-to-json-schema";function wn(n){if(!n)return null;if(typeof It?.toJSONSchema=="function")try{return It.toJSONSchema(n)}catch{}try{return kn(n,{target:"openApi3"})}catch{return null}}var Me=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=wn(e):r=e;let o=this._buildExample(r);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(o,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 r={};for(let[o,s]of Object.entries(e.properties))r[o]=this._buildExample(s);return r}if(t==="array"&&e.items)return[this._buildExample(e.items)];if(e.enum&&Array.isArray(e.enum)&&e.enum.length>0)return`<${e.enum.join("|")}>`;if(t==="string")return"<string>";if(t==="number"||t==="integer")return 0;if(t==="boolean")return!1;if(e.description)return`<${e.description}>`;if(e.nullable||e.oneOf||e.anyOf){let r=e.oneOf?.find(o=>o.type!=="null")||e.anyOf?.find(o=>o.type!=="null");return r?this._buildExample(r):null}return"<value>"}};var Re=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 r=Me.generateFileOutputInstructions(e,t);this.systemInstructions.push({type:"structured_output",content:r,position:"append"}),this.metadata.structuredOutputPath=t}return this}addExtraInstructions(e){if(e?.trim()){let t=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
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",r="append"){return e&&this.systemInstructions.push({type:t,content:e,position:r}),this}getUserPrompt(){return this.userPrompt}getSystemInstructions(){return this.systemInstructions}getMetadata(){return this.metadata}build(){let e=this.systemInstructions.filter(o=>o.position==="prepend").map(o=>o.content),t=this.systemInstructions.filter(o=>o.position==="append").map(o=>o.content);return[...e,this.userPrompt,...t].filter(Boolean).join(`
|
|
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
|
-
${
|
|
53
|
-
${
|
|
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(r=>r.type)}}clone(){let e=new n(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};var De=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 r="";for(let o of t)if(o.trim())try{let s=JSON.parse(o);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,r+=a}else(!this.rawText.includes(i)||i.length<20)&&(this.rawText+=i,r+=i);this.tryExtractResult(this.rawText)}else this.isValidResult(s)&&(this.rawText+=`${o}
|
|
50
|
+
`,r+=`${o}
|
|
51
|
+
`,this.extractedResult=s)}catch{if(o.includes('"text"')||o.includes('"content"')){let i=o.match(/"text"\s*:\s*"([^"]*)/),a=o.match(/"content"\s*:\s*"([^"]*)/),l=i?i[1]:a?a[1]:null;l&&!this.rawText.includes(l)&&(r+=l,this.rawText+=l)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(i,a)=>{if(!i)return;let l=`${i}:${JSON.stringify(a??{})}`;this._lastToolEmit!==l&&(this._lastToolEmit=l,this.onToolCall(i,a??void 0))},r=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,r(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],m=f&&typeof f=="object"?f.args??f.input??f:void 0;t(l,r(m))}return}return}if(Array.isArray(e.tool_calls)){for(let i of e.tool_calls)t(i.name,r(i.input??i.arguments));return}let o=e.message??e;if(Array.isArray(o?.tool_calls)){for(let i of o.tool_calls)t(i.name,r(i.input??i.arguments));return}let s=o?.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,r(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(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return e.type==="thinking"&&e.text||e.text?e.text:e.content&&typeof e.content=="string"?e.content:e.delta?e.delta:null}tryExtractResult(e){if(!e||typeof e!="string")return;let t=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,o;for(;(o=r.exec(e))!==null;){let y=o[1].trim();try{JSON.parse(y),t.push({text:y,source:"markdown"})}catch{}}let s=0,i=0;for(;s<e.length&&(s=e.indexOf("{",s),s!==-1);){let y=0,b=s;for(let A=s;A<e.length;A++)if(e[A]==="{")y++;else if(e[A]==="}"&&(y--,y===0)){b=A,t.push({text:e.substring(s,b+1),source:"brace"}),i++;break}s=b+1}let a=this.extractedResult,l=a?JSON.stringify(a).length:0,f=0,m=-1;for(let y=0;y<t.length;y++){let b=t[y];try{let A=b.text.replace(/,(\s*[}\]])/g,"$1"),$=JSON.parse(A);this.isValidResult($)&&(f++,l=JSON.stringify($).length,a=$,m=y)}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 r=new n;r.zodSchema=t,r.processChunk(e),r.flush();let o=r.getResult();return!o&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),o}};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 r=e.indexOf("{");if(r<0)return null;let o=0,s=!1,i=!1,a=-1;for(let l=r;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==="{"){o===0&&(a=l),o+=1;continue}if(f==="}"){if(o===0)continue;if(o-=1,o===0&&a>=0){let m=e.slice(a,l+1);try{return JSON.parse(m)}catch{a=-1}}}}return null}function Ln(n){let e=String(n||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return Pn(e)}}function Mn(n){try{let e=JSON.parse(n);if(typeof e=="string")return e;if(typeof e?.response=="string")return e.response;if(typeof e?.text=="string")return e.text;if(typeof e?.output=="string")return e.output;if(Array.isArray(e?.candidates)&&e.candidates.length>0){let t=e.candidates[0];if(typeof t?.content=="string")return t.content;if(Array.isArray(t?.content?.parts)){let r=t.content.parts.map(o=>typeof o?.text=="string"?o.text:"").join("");if(r.trim())return r}}}catch{}return n}var Be=class n extends In{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):Ne("gemini")?!0:(c.warn("[Gemini] gemini CLI not on PATH. Install: npm install -g @google/gemini-cli"),!1)}async invoke(e,t={}){t.effort&&!n._effortWarned&&(n._effortWarned=!0,c.warn(`[Gemini] effort "${t.effort}" ignored \u2014 the Gemini CLI exposes no reasoning-effort control.`));let{model:r,workspace:o=process.cwd(),schema:s=null,images:i=[],skills:a=null,sessionPath:l=null,nodeName:f=null,timeout:m=600*1e3,signal:y=null}=t,b=[Q("GEMINI_API_KEY"),Q("GOOGLE_API_KEY")];try{let A=de("gemini",r),$=St[A]||A,U=String(process.env.GEMINI_API_KEY||"").trim(),K=String(process.env.GOOGLE_API_KEY||"").trim(),T=this._resolveSkillsToMcp(a,{sessionPath:l,workspace:o,nodeName:f});for(let O of t.extraMcpServers||[])if(O&&O.serverName&&O.def){if(Object.prototype.hasOwnProperty.call(T,O.serverName)){console.warn(`[custom-mcp] skip "${O.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let R=ne("gemini",O.def);R&&(T[O.serverName]=R)}let w=$e("gemini",T,{sessionPath:l}),M=Object.keys(w).length>0,E=new Re(e),I=s&&typeof s.parse=="function",x=null;if(s){let O;try{let R=I?oe(s,{target:"openAi"}):s;O=JSON.stringify(R,null,2)}catch{O="{}"}if(M){E.addSystemInstruction(`Write valid JSON that matches this schema:
|
|
52
|
+
${O}`,"schema_instruction","append");let R=`zibby-result-${Date.now()}.json`,V=ie(o,".zibby","tmp");x=ie(V,R),$t(V,{recursive:!0}),E.addStructuredOutput(s,x)}else E.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
|
|
53
|
+
${O}`,"json_instruction","append")}let v=E.build(),N=Array.isArray(i)?i.filter(O=>O&&typeof O.path=="string"&&O.path.startsWith("/")):[];N.length&&(v+=`
|
|
54
54
|
|
|
55
55
|
# Attached image files \u2014 VIEW THESE
|
|
56
|
-
The user attached ${
|
|
57
|
-
${
|
|
58
|
-
`)}`);let
|
|
59
|
-
\u25C6 Model: ${
|
|
60
|
-
`);let
|
|
61
|
-
${
|
|
62
|
-
${
|
|
63
|
-
${
|
|
64
|
-
`,"utf-8");let
|
|
65
|
-
`,"utf-8")}catch{}return c.debug(`[Gemini] Created isolated config with ${Object.keys(
|
|
56
|
+
The user attached ${N.length} image(s), saved locally. Read each path to SEE the image, then use what it shows to answer:
|
|
57
|
+
${N.map((O,R)=>` ${R+1}. ${O.path}${O.name?` (${O.name})`:""}`).join(`
|
|
58
|
+
`)}`);let j=E.getUserPrompt(),Y=E.getStats(),B=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),G=B?` | key: ***${B.slice(-4)}`:" | key: not set";console.log(`
|
|
59
|
+
\u25C6 Model: ${$}${G}
|
|
60
|
+
`);let X=(await import("chalk")).default;console.log(`
|
|
61
|
+
${X.bold("Prompt sent to LLM:")}`),console.log(X.dim("\u2500".repeat(60))),console.log(X.dim(j)),console.log(X.dim("\u2500".repeat(60)));let F=this._createGeminiConfigDir(o,w),S=["--output-format","json"];S.push("--model",$);let z=Object.keys(w);if(z.length>0){S.push("--approval-mode","yolo");for(let O of z)S.push("--allowed-mcp-server-names",O);c.info(`[Gemini] Enabling MCP servers: ${z.join(", ")}`)}else a&&a.length>0&&c.warn(`[Gemini] Skills requested but no MCP servers configured: ${a.join(", ")}`);S.push("-p",v);let h={...ce(process.env),GEMINI_CLI_HOME:F,GEMINI_CLI_TRUST_WORKSPACE:"true"};U?(h.GEMINI_API_KEY=U,delete h.GOOGLE_API_KEY):K&&(h.GOOGLE_API_KEY=K,delete h.GEMINI_API_KEY),c.debug(`[Gemini] Command: gemini ${S.slice(0,8).join(" ")}... (${S.length} total args)`),c.debug(`[Gemini] User prompt: ${Y.userPromptLength} chars, System instructions: ${Y.systemInstructionsLength} chars (${Y.instructionCount} blocks), Full: ${Y.fullPromptLength} chars`),c.debug(`[Gemini] Config home: ${F}`),c.debug(`[Gemini] GEMINI_CLI_HOME env: ${h.GEMINI_CLI_HOME}`);let L="",P=null;try{L=await new Promise((R,V)=>{let Z=$n("gemini",S,{cwd:o,env:h,stdio:["ignore","pipe","pipe"],...y&&{signal:y}}),u="",p="",_=!1,g=null,d=!1,C=setTimeout(()=>{try{Z.kill("SIGTERM")}catch{}},m),k=()=>{d||_||(d=!0,g=setTimeout(()=>{if(!_)try{Z.kill("SIGKILL")}catch{}},5e3))};y&&(y.aborted?k():y.addEventListener("abort",k,{once:!0})),Z.stdout.on("data",W=>{u+=W.toString()}),Z.stderr.on("data",W=>{p+=W.toString()}),Z.on("error",W=>{if(clearTimeout(C),g&&clearTimeout(g),y&&!y.aborted)try{y.removeEventListener("abort",k)}catch{}V(W)}),Z.on("close",W=>{if(_=!0,clearTimeout(C),g&&clearTimeout(g),y&&!y.aborted)try{y.removeEventListener("abort",k)}catch{}if(d){let le=new Error("Aborted via signal");return le.name="AbortError",V(le)}if(W===0)return R(u.trim());V(new Error(`gemini failed with code ${W}: ${(p||u).trim()}`))})})}catch(O){P=O}finally{try{Nn(F,{recursive:!0,force:!0})}catch{}}let H=Mn(L).trim();if(!s){if(P)throw P;return H}if(x){let O=Ct(x);if(c.info(`[Gemini] Result file: ${O?"present":"missing"} at ${x}`),O)try{let R=Nt(x,"utf-8").trim(),V=JSON.parse(R),Z=I?s.parse(V):V;return c.info("[Gemini] Structured output recovered from result file"),{raw:H,structured:Z}}catch(R){c.warn(`[Gemini] Result file parse/validation failed: ${R.message}`)}else P||c.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let J=null;if(s){let O=new De;O.zodSchema=s,O.processChunk(H),O.flush(),J=O.getResult()}if(c.info(`[Gemini] Raw stdout length: ${L.length} chars`),c.info(`[Gemini] Extracted text length: ${H.length} chars`),c.info(`[Gemini] StreamParser result: ${J?"extracted":"null"}`),J||(H.length<2e3?c.info(`[Gemini] Raw text preview:
|
|
62
|
+
${H}`):c.info(`[Gemini] Raw text preview (first 1000 chars):
|
|
63
|
+
${H.slice(0,1e3)}`),J=Ln(H)),!J)throw P||(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 ae=I?s.parse(J):J;return{raw:H,structured:ae}}finally{for(let A of b)A.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let o of e){let s=Cn(o);if(!s||typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let a=s.cursorKey||s.serverName||o,l=ne("gemini",i);l&&(r[a]=l)}return r}_createGeminiConfigDir(e,t){let r=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,o=ie(e||process.cwd(),".zibby","tmp",`gemini-home-${r}`),s=ie(o,".gemini");$t(s,{recursive:!0});let i=ie(s,"settings.json"),a={},l=ie(process.env.HOME||"",".gemini","settings.json");if(Ct(l))try{a=JSON.parse(Nt(l,"utf-8"))}catch{a={}}let f={...a,mcpServers:{...a.mcpServers&&typeof a.mcpServers=="object"?a.mcpServers:{},...t||{}}};Pt(i,`${JSON.stringify(f,null,2)}
|
|
64
|
+
`,"utf-8");let m=ie(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{Pt(m,`${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)}`),o}};import{AgentStrategy as Vn,getSkill as ze}from"@zibby/agent-workflow";var xe=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 me=class extends xe{formatTools(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters||t.input_schema||{type:"object",properties:{}}}}))}hasToolCalls(e){let t=e.choices?.[0]?.message;return!!(t?.tool_calls&&t.tool_calls.length>0)}parseToolCalls(e){return(e.choices?.[0]?.message?.tool_calls||[]).map(r=>({id:r.id,name:r.function.name,args:JSON.parse(r.function.arguments||"{}")}))}getTextContent(e){return e.choices?.[0]?.message?.content||""}buildAssistantMessage(e){return e.choices?.[0]?.message}buildToolResultMessage(e,t){return{role:"tool",tool_call_id:e,content:typeof t=="string"?t:JSON.stringify(t)}}injectToolsIntoBody(e,t){return t.length>0&&(e.tools=t),e}};var Te=class{async fetchCompletion(e,t,r={}){throw new Error("fetchCompletion() must be implemented")}async fetchStreamingCompletion(e,t,r={}){throw new Error("fetchStreamingCompletion() must be implemented")}};function Ke(n){return Buffer.byteLength(JSON.stringify(n),"utf8")}function je(n,e){let t=String(n||"");if(t.length<=e)return t;let r=Math.max(0,e-28);return`${t.slice(0,r)}
|
|
66
66
|
|
|
67
|
-
[truncated for size budget]`}function
|
|
68
|
-
`);
|
|
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 ot(n,e=0){if(!n||typeof n!="object"||e>8)return n;if(Array.isArray(n))return n.map(r=>ot(r,e+1));let t={};for(let[r,o]of Object.entries(n))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=ot(o,e+1));return t}function Rn(n=[]){return n.map(e=>({...e,function:{...e.function,description:je(e.function?.description||"",180),parameters:ot(e.function?.parameters||{type:"object",properties:{}})}}))}function Lt(n){let e=new Set;for(let o of n)if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let s of o.tool_calls)e.add(s.id);let t=n.filter(o=>o.role==="tool"?e.has(o.tool_call_id):!0),r=new Set;for(let o of t)o.role==="tool"&&r.add(o.tool_call_id);return t.map(o=>{if(o.role!=="assistant"||!Array.isArray(o.tool_calls)||o.tool_calls.every(l=>r.has(l.id)))return o;let{tool_calls:i,...a}=o;return{...a,content:a.content||""}})}function st(n,e={}){let t=e.maxBytes||49e3,r=e.systemMaxChars||12e3,o={...n,messages:Array.isArray(n.messages)?[...n.messages]:[],tools:Array.isArray(n.tools)?Rn(n.tools):n.tools};o.messages.length>0&&o.messages[0]?.role==="system"&&(o.messages[0]={...o.messages[0],content:je(o.messages[0].content,r)});let s=!1;for(;Ke(o)>t&&o.messages.length>2;)o.messages.splice(1,1),s=!0;if(s&&(o.messages=Lt(o.messages)),Ke(o)>t&&o.messages.length>0&&(o.messages[0]={...o.messages[0],content:je(o.messages[0].content,6e3)},s=!0),Ke(o)>t){let i=o.messages.find(l=>l.role==="system")||o.messages[0],a=o.messages.slice(-2);o.messages=Lt([i,...a].filter(Boolean).map((l,f)=>({...l,content:je(l.content,f===0?4e3:8e3)}))),s=!0}return{body:o,meta:{bytes:Ke(o),trimmed:s,maxBytes:t,messageCount:o.messages.length}}}var Mt=n=>Buffer.byteLength(JSON.stringify(n),"utf8"),ge=class extends Te{async fetchCompletion(e,t,r={}){let o=Mt(e),{body:s,meta:i}=st(e,r.payloadCompaction);r.onBudget?.({streaming:!1,beforeBytes:o,meta:i});let a=this.#e(r),l=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,f=await fetch(l,{method:"POST",headers:t.headers,body:JSON.stringify(s),signal:a});if(!f.ok){let m=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}: ${m}`)}return f.json()}async fetchStreamingCompletion(e,t,r={}){let o={...e,stream:!0},s=Mt(o),{body:i,meta:a}=st(o,r.payloadCompaction);r.onBudget?.({streaming:!0,beforeBytes:s,meta:a});let l=this.#e(r),f=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,m=await fetch(f,{method:"POST",headers:t.headers,body:JSON.stringify(i),signal:l});if(!m.ok){let K=await m.text();throw m.status===401||m.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${m.status}: ${K}`)}let y=m.body.getReader(),b=new TextDecoder,A="",$="",U=new Map;for(;;){let{done:K,value:T}=await y.read();if(K)break;A+=b.decode(T,{stream:!0});let w=A.split(`
|
|
68
|
+
`);A=w.pop();for(let M of w){if(!M.startsWith("data: "))continue;let E=M.slice(6).trim();if(E==="[DONE]")continue;let I;try{I=JSON.parse(E)}catch{continue}let x=I.choices?.[0]?.delta;if(x&&(x.content&&($+=x.content,r.onToken&&r.onToken(x.content)),x.tool_calls))for(let v of x.tool_calls){let N=v.index??0;U.has(N)||U.set(N,{id:"",name:"",args:""});let j=U.get(N);v.id&&(j.id=v.id),v.function?.name&&(j.name=v.function.name),v.function?.arguments!=null&&(j.args+=v.function.arguments)}}}if(U.size>0){let K=[...U.entries()].sort(([T],[w])=>T-w).map(([,T])=>({id:T.id,type:"function",function:{name:T.name,arguments:T.args}}));return{choices:[{message:{role:"assistant",content:$||null,tool_calls:K}}]}}return{choices:[{message:{role:"assistant",content:$}}]}}#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 Dn}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Bn}from"@modelcontextprotocol/sdk/client/stdio.js";var Ue=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:r,args:o=[],env:s={}}=t;c.debug(`[MCP] Starting ${e}: ${r} ${o.join(" ")}`);let i=new Bn({command:r,args:o,env:{...process.env,...s}}),a=new Dn({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,r={}){let o=this.#e.get(e);if(!o)throw new Error(`MCP server "${e}" not running`);c.debug(`[MCP] ${e}.${t}(${JSON.stringify(r).slice(0,200)})`);let s=await o.client.callTool({name:t,arguments:r});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(r){c.debug(`[MCP] Error closing ${e}: ${r.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}};import{existsSync as Kn,readFileSync as jn}from"node:fs";import{join as Un}from"node:path";import{homedir as Jn}from"node:os";function Gn(){try{let n=Un(Jn(),".zibby","config.json");return Kn(n)?JSON.parse(jn(n,"utf-8")):{}}catch{return{}}}function Je(n){return String(n||"").replace(/\/v1\/?$/,"")}function zn(n,e){let t=process.env.OPENAI_PROXY_URL;if(t)return Je(t);if(n==="session")return e.proxyUrl?Je(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(n==="byok"){let r=process.env.OPENAI_BASE_URL;return Je(r||"https://api.openai.com")}return Je(t||"")}function it(){let n=Gn(),e=process.env.ZIBBY_USER_TOKEN||n.sessionToken||null,t=process.env.OPENAI_API_KEY||null,r=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),o=process.env.OPENAI_PROXY_NO_AUTH==="true",s=process.env.OPENAI_PROXY_URL,i="session";r==="byok"||r==="local"||r==="session"?i=r:e?i="session":t?i="byok":s&&o&&(i="local");let a=zn(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"};!o&&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 Ge(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
|
-
`)),
|
|
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 Yn(n,e){if(typeof n=="string")return Ge(n,e);try{return Ge(JSON.stringify(n),e)}catch{return Ge(String(n),e)}}function Rt(n){let e=new Set;for(let o of n)if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let s of o.tool_calls)e.add(s.id);let t=n.filter(o=>o.role==="tool"?e.has(o.tool_call_id):!0),r=new Set;for(let o of t)o.role==="tool"&&r.add(o.tool_call_id);return t.map(o=>{if(o.role!=="assistant"||!Array.isArray(o.tool_calls)||o.tool_calls.every(l=>r.has(l.id)))return o;let{tool_calls:i,...a}=o;return{...a,content:a.content||""}})}function Fn(n){let e=Array.isArray(n?.messages)?n.messages:[],t=e.find(s=>s.role==="system"),r=e.slice(-4).map(s=>({...s,content:Ge(s.content,s.role==="tool"?1200:2500)}));r=Rt(r);let o={...n,messages:[t,...r].filter(Boolean)};return delete o.tools,o}async function Hn({body:n,streaming:e,auth:t,options:r,fetchCompletion:o,fetchStreamingCompletion:s,onFallbackLog:i}){try{return e?await s(n,t,r):await o(n,t,r)}catch(a){let l=String(a?.message||a||"");if(!/proxy error 413|payload too large/i.test(l))throw a;let f=Fn(n);return typeof i=="function"&&i(n,f),{data:e?await s(f,t,r):await o(f,t,r),fallback:f}}}async function Dt({body:n,auth:e,options:t,streaming:r,toolContext:o,activeSkills:s,round:i,verbose:a,dependencies:l,config:f={}}){let m=f.maxToolResultChars||3e3,{fetchCompletion:y,fetchStreamingCompletion:b,onFallbackLog:A,hasToolCalls:$,getTextContent:U,parseToolCalls:K,buildAssistantMessage:T,buildToolResultMessage:w,executeTool:M,onToolCallLog:E,injectTools:I}=l;Array.isArray(n?.messages)&&(n.messages=Rt(n.messages));let x=await Hn({body:n,streaming:r,auth:e,options:t,fetchCompletion:y,fetchStreamingCompletion:b,onFallbackLog:A}),v=x?.data||x;if(!$(v))return{done:!0,text:U(v),body:x?.fallback||n};let N=K(v),j=x?.fallback||n;j.messages.push(T(v)),a&&typeof E=="function"&&E(N);let Y=await Promise.all(N.map((B,G)=>(typeof t.onToolCall=="function"&&t.onToolCall(B.name,B.args,{round:i,index:G,total:N.length}),M(B,o))));for(let B=0;B<N.length;B++){let X=N[B].name==="get_skill_context"?typeof Y[B]=="string"?Y[B]:JSON.stringify(Y[B]):Yn(Y[B],m);j.messages.push(w(N[B].id,X))}return typeof t.onToolCall=="function"&&t.onToolCall(null),I(j,s),{done:!1,body:j}}var Wn=_t.ASSISTANT,Zn=15,at="get_skill_context";function he(n){!n||typeof n!="object"||(n.type==="object"&&n.properties&&(n.required=Object.keys(n.properties),n.additionalProperties=!1,Object.values(n.properties).forEach(he)),n.type==="array"&&n.items&&he(n.items),n.anyOf&&n.anyOf.forEach(he),n.oneOf&&n.oneOf.forEach(he),n.allOf&&n.allOf.forEach(he))}var Bt={maxBytes:49e3,systemMaxChars:12e3},ye=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",qn=n=>Buffer.byteLength(JSON.stringify(n),"utf8");function Ye(n){return Array.isArray(n)?new Set(n.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function Xn(n){return Array.isArray(n)?n.map(e=>String(e||"").trim()).filter(Boolean):[]}var Fe=class extends Vn{#e;#t;#n=new Ue;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new me,this.#t=e.completionProvider||new ge):(this.#e=e||new me,this.#t=new ge)}canHandle(e){return it().ok}async invoke(e,t={}){let r=Q("OPENAI_API_KEY");try{let o=t.model||Wn,s=it();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=ye();if(l?await this.#m(i,o,a,s.tokenPreview||"none"):c.debug(`[Assistant] ${a} | model: ${o} | messages: ${i.length}`),t.schema)return this.#c(o,i,s,t);let f=t.activeSkills||[],m=this.#f(t),y=this.#d(f,m),b=this.#p(y),A=this.#u(t),$={...t,payloadCompaction:A},U={activeSkills:y,options:$,executionRegistry:b,capabilityPolicy:m},K=!!t.stream,T={model:o,messages:[...i],stream:!1};this.#o(T,y,m);for(let w=0;w<Zn;w++){if(t.signal?.aborted){let E=new Error("Aborted via signal");throw E.name="AbortError",E}let M=await Dt({body:T,auth:s,options:$,streaming:K,toolContext:U,activeSkills:y,round:w,verbose:l,dependencies:{fetchCompletion:this.#s.bind(this),fetchStreamingCompletion:this.#l.bind(this),onFallbackLog:(E,I)=>{ye()&&console.log(`413 fallback: messages ${E.messages.length} -> ${I.messages.length}, bytes=${qn(I)}`)},hasToolCalls:E=>this.#e.hasToolCalls(E),getTextContent:E=>this.#e.getTextContent(E),parseToolCalls:E=>this.#e.parseToolCalls(E),buildAssistantMessage:E=>this.#e.buildAssistantMessage(E),buildToolResultMessage:(E,I)=>this.#e.buildToolResultMessage(E,I),executeTool:(E,I)=>this.#a(E,I),onToolCallLog:async E=>{let I=(await import("chalk")).default;console.log(I.dim(` ${E.map(x=>`${x.name}(${JSON.stringify(x.args).slice(0,80)})`).join(", ")}`))},injectTools:(E,I)=>this.#o(E,I,m)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(M.done)return M.text;T.messages=M.body.messages,M.body.tools?T.tools=M.body.tools:delete T.tools}return"I hit my tool-calling limit for this turn. Please try again."}finally{r.dispose()}}async cleanup(){await this.#n.stopAll()}#o(e,t,r=null){let o=this.#i(t,r),s=this.#e.formatTools(o);this.#e.injectToolsIntoBody(e,s)}#i(e,t=null){let r=[],o=new Set;for(let s of e){let i=ze(s);if(i?.tools?.length)for(let a of i.tools)this.#r(a.name,t)&&(o.has(a.name)||(o.add(a.name),r.push({name:a.name,description:a.description,parameters:a.parameters||a.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#r(at,t)&&r.push({name:at,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),r}async#a(e,t){let{activeSkills:r,options:o,executionRegistry:s,capabilityPolicy:i}=t;if(!this.#r(e.name,i))return`Tool "${e.name}" blocked by policy`;if(e.name===at){let f=String(e.args?.skillId||"").trim();if(!f)return JSON.stringify({error:"skillId is required"});if(!r.includes(f))return JSON.stringify({error:`Skill "${f}" is not active`,activeSkills:r});let m=ze(f);if(!m)return JSON.stringify({error:`Skill "${f}" not found`});let y=typeof m.promptFragment=="function"?m.promptFragment():m.promptFragment||"",b=(m.tools||[]).map($=>$.name),A=JSON.stringify({skillId:f,description:m.description||"",toolNames:b,promptFragment:y||""});return ye()&&(console.log(`
|
|
72
|
+
\u{1F4D6} get_skill_context("${f}") \u2192 ${A.length} chars (fragment: ${y.length} chars)`),console.log(` tools: [${b.join(", ")}]`),console.log(` fragment preview: ${y.slice(0,200).replace(/\n/g,"\\n")}\u2026
|
|
73
|
+
`)),A}let a=s?.get(e.name)||null;if(!a)return`Unknown tool: ${e.name}`;let l=ze(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 m=l.resolve(o);if(!m)return`Skill "${a.skillId}" is not available (cannot start server)`;await this.#n.ensureServer(l.serverName,m)}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,r){return this.#t.fetchStreamingCompletion(e,t,{...r,onBudget:({beforeBytes:o,meta:s})=>{ye()&&console.log(`payload bytes (stream) before=${o} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#s(e,t,r){return this.#t.fetchCompletion(e,t,{...r,onBudget:({beforeBytes:o,meta:s})=>{ye()&&console.log(`payload bytes before=${o} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#c(e,t,r,o){let{zodToJson:s}=await Promise.resolve().then(()=>(_e(),gt)),i=typeof o.schema?.parse=="function",a=i?s(o.schema,{}):o.schema;delete a.$schema,he(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,r,o),m=this.#e.getTextContent(f),y=JSON.parse(m),b=i?o.schema.parse(y):y;return{raw:m,structured:b}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||Bt.maxBytes),systemMaxChars:Number(t.systemMaxChars||Bt.systemMaxChars)}}#f(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:Ye(t.allowTools||e.allowTools),denyTools:Ye(t.denyTools||e.denyTools),denyPrefixes:Xn(t.denyPrefixes||e.denyToolPrefixes),includeSkills:Ye(t.includeSkills||e.includeSkills),excludeSkills:Ye(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#d(e,t){let r=t?.includeSkills||new Set,o=t?.excludeSkills||new Set;return r.size===0&&o.size===0?e:e.filter(s=>!(r.size>0&&!r.has(s)||o.has(s)))}#r(e,t){let r=String(e||"").trim();if(!r)return!1;let o=t?.allowTools;if(o&&o.size>0&&!o.has(r))return!1;let s=t?.denyTools;return!(s&&s.has(r)||(t?.denyPrefixes||[]).some(a=>r.startsWith(a)))}#p(e){let t=new Map,r=[];for(let o of e){let s=ze(o);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)){r.push({tool:l,winner:t.get(l).skillId,skipped:o});continue}t.set(l,{skillId:o,mode:i})}}}if(r.length>0&&ye()){let o=r.slice(0,5).map(s=>`${s.tool}:${s.winner}>${s.skipped}`).join(", ");console.log(`tool registry collisions: ${o}${r.length>5?" ...":""}`)}return t}async#m(e,t,r,o){console.log(`
|
|
74
|
+
\u25C6 Model: ${t} | proxy: ${r} | token: ${o||"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 Kt=!1;function ys(){Kt||(He(new Fe),He(new Ie),He(new Le),He(new Be),Kt=!0)}export{ys as registerBuiltInStrategies};
|