@zibby/core 2.0.13 → 2.0.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +115 -115
- package/dist/mcp/tool-broker-server.js +6 -3
- package/dist/package.json +5 -4
- package/dist/register-built-in-strategies.js +39 -39
- package/dist/strategies/codex-strategy.js +9 -9
- package/dist/strategies/gemini-strategy.js +10 -10
- package/dist/strategies/index.js +75 -75
- package/dist/strategies/tool-broker.js +1 -1
- package/package.json +5 -4
package/dist/strategies/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
var Sn=Object.defineProperty;var At=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var Ot=(t,e)=>{for(var n in e)Sn(t,n,{get:e[n],enumerable:!0})};var Jt={};Ot(Jt,{zodToJson:()=>ue});import{z as Gt}from"zod";import{zodToJsonSchema as Qn}from"zod-to-json-schema";function er(t){if(!t||typeof t!="object")return t;if(Array.isArray(t.type))return t.type.includes("null")||(t.type=[...t.type,"null"]),t;if(typeof t.type=="string")return t.type=[t.type,"null"],t;for(let e of["anyOf","oneOf"])if(Array.isArray(t[e]))return t[e].some(n=>n&&n.type==="null")||(t[e]=[...t[e],{type:"null"}]),t;return{anyOf:[t,{type:"null"}]}}function Ee(t){if(!t||typeof t!="object")return t;for(let e of["$defs","definitions"])if(t[e]&&typeof t[e]=="object")for(let n of Object.keys(t[e]))t[e][n]=Ee(t[e][n]);for(let e of["anyOf","oneOf","allOf"])Array.isArray(t[e])&&(t[e]=t[e].map(Ee));if(t.properties&&typeof t.properties=="object"){t.additionalProperties=!1;let e=Object.keys(t.properties),n=new Set(Array.isArray(t.required)?t.required:[]);for(let r of e){let o=Ee(t.properties[r]);n.has(r)||(o=er(o)),t.properties[r]=o}t.required=e}return t.items&&(Array.isArray(t.items)?t.items=t.items.map(Ee):t.items=Ee(t.items)),t}function ue(t,e={target:"openApi3"}){if(!t)return null;let n=e?.target==="openAi",r=null;if(typeof Gt?.toJSONSchema=="function")try{r=Gt.toJSONSchema(t)}catch{}if(!r)try{r=Qn(t,e)}catch{return null}if(n&&r)try{return Ee(r)}catch{return r}return r}var $e=At(()=>{});var _n={};Ot(_n,{INTEGRATION_API_TIMEOUT_MS:()=>gn,clearConnectedCache:()=>co,clearTokenCache:()=>ao,getConnectedIntegrations:()=>lo,resolveIntegrationToken:()=>io});import{existsSync as to,readFileSync as no}from"node:fs";import{homedir as ro}from"node:os";import{join as oo}from"node:path";function dn(){let t=process.env.ZIBBY_SELF_HOST;return t!=null&&t!==""&&t!=="0"&&t.toLowerCase()!=="false"}function pn(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let t=oo(ro(),".zibby","config.json");return to(t)&&JSON.parse(no(t,"utf-8")).sessionToken||null}catch{return null}}function mn(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app"}function so(t=process.env){let e=Number(t.INTEGRATION_API_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.min(12e4,Math.max(1e3,Math.floor(e))):gn}function yn(){let t=so();return{signal:AbortSignal.timeout(t),label:`after ${t}ms (INTEGRATION_API_TIMEOUT_MS)`}}function hn(t){return t?.name==="TimeoutError"||t?.name==="AbortError"}function cn(t,e,n){if(!hn(t))return t;let r=new Error(`${n} TIMED OUT ${e.label}`);return r.timedOut=!0,r.cause=t,r}async function io(t){if(dn()){let f=fn[t];if(f&&process.env[f])return{token:process.env[f]}}let e=Date.now(),n=ot.get(t);if(n&&n.expiresAt>e)return n.data;let r=pn();if(!r)throw new Error("Missing session credential: neither PROJECT_API_TOKEN nor ZIBBY_USER_TOKEN is set in this process env (and no ~/.zibby/config.json session). If this is an MCP skill child, the spawning skill must forward them \u2014 check the skill's envKeys / resolve() env (see @zibby/skills backend-session-env-contract). Interactive CLI: run `zibby login`.");let o=`${mn()}/integrations/token/${t}`,s=yn(),i;try{i=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${r}`},signal:s.signal})}catch(f){throw cn(f,s,`${t} token lookup`)}if(!i.ok){let f=await i.text().catch(()=>"");if(i.status===404){let d="";try{d=String(JSON.parse(f)?.error||"").trim()}catch{}throw new Error(d||`${t} is not connected. Connect it at https://studio.zibby.dev/integrations`)}throw i.status===401||i.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Failed to resolve ${t} token (${i.status}): ${f}`)}let a;try{a=await i.json()}catch(f){throw cn(f,s,`${t} token body read`)}if(!a||typeof a!="object")throw new Error(`Invalid response from ${t} token endpoint: expected object, got ${typeof a}`);if(t==="jira"){if(!a.token||typeof a.token!="string")throw new Error(`Invalid jira token response: token is ${typeof a.token}, expected string`);if(!a.cloudId&&!a.instanceUrl&&!a.baseUrl)throw new Error("Invalid jira token response: carries neither cloudId (OAuth connection) nor instanceUrl (API-token connection) \u2014 reconnect Jira.")}else if(t==="github"&&(!a.token||typeof a.token!="string"))throw new Error(`Invalid github token response: token is ${typeof a.token}, expected string`);let l=((a.expiresInSec||3e3)-120)*1e3;return ot.set(t,{data:a,expiresAt:e+l}),a}function ao(t){t?ot.delete(t):ot.clear()}function un(t){let e=process.env.WORKFLOW_ENABLED_INTEGRATIONS;if(typeof e!="string"||e.trim()==="")return t;let n=new Set(e.split(",").map(o=>o.trim()).filter(Boolean));if(n.size===0)return t;let r={};for(let[o,s]of Object.entries(t))n.has(o)&&(r[o]=s);return r}async function lo(){let t=Date.now();if(ve&&ve.expiresAt>t)return ve.data;if(dn()){let r={};for(let[s,i]of Object.entries(fn))r[s]=!!process.env[i];let o=un(r);return ve={data:o,expiresAt:t+6e4},o}let e=pn();if(!e)return{};let n=yn();try{let r=await fetch(`${mn()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:n.signal});if(!r.ok)return{};let o=await r.json(),s={};if(o&&typeof o=="object")for(let[a,l]of Object.entries(o))l&&typeof l=="object"&&"connected"in l&&(s[a]=!!l.connected);let i=un(s);return ve={data:i,expiresAt:t+6e4},i}catch(r){return hn(r)&&console.warn(`[backend-client] /integrations/status TIMED OUT ${n.label} \u2014 proceeding with no connection map`),{}}}function co(){ve=null}var ot,fn,gn,ve,En=At(()=>{ot=new Map,fn={github:"GITHUB_TOKEN",gitlab:"GITLAB_TOKEN",sentry:"SENTRY_AUTH_TOKEN",slack:"SLACK_BOT_TOKEN"};gn=2e4;ve=null});import{resolveInvocationModel as uo,resolveInvocationExtras as fo,resolveInvocationEffort as po}from"@zibby/agent-workflow";import{AgentStrategy as zn,DEFAULT_OUTPUT_BASE as Fn,SESSION_INFO_FILE as Yn,STOP_REQUEST_FILE as Hn,getAllSkills as Zn,getSkill as Lt}from"@zibby/agent-workflow";import{spawn as Wn,execSync as ce}from"node:child_process";import{writeFileSync as Mt,readFileSync as Dt,mkdirSync as Ut,existsSync as xe,accessSync as Bt,constants as jt,unlinkSync as Vn}from"node:fs";import{join as re,resolve as qn}from"node:path";import{homedir as we}from"node:os";import Ie from"chalk";var oe={debug:0,info:1,warn:2,error:3,silent:4},st=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return oe.debug;if(process.env.ZIBBY_VERBOSE==="true")return oe.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in oe?oe[e]:oe.info}_shouldLog(e){return oe[e]>=this._level}_formatMessage(e,n,r={}){let o=new Date().toISOString(),i=`${this._getPrefix(e)} ${n}`;return Object.keys(r).length>0&&(i+=Ie.dim(` ${JSON.stringify(r)}`)),i}_getPrefix(e){return{debug:Ie.gray("[DEBUG]"),info:Ie.cyan("[INFO]"),warn:Ie.yellow("[WARN]"),error:Ie.red("\u274C [ERROR]")}[e]||""}debug(e,n){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,n))}info(e,n){this._shouldLog("info")&&console.log(this._formatMessage("info",e,n))}warn(e,n){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,n))}error(e,n){this._shouldLog("error")&&console.error(this._formatMessage("error",e,n))}setLevel(e){e in oe&&(this._level=oe[e])}getLevel(){return Object.keys(oe).find(e=>oe[e]===this._level)}},c=new st;var Tt=[{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 Me(t){let e={};for(let n of Tt)n.vendor===t&&(e[n.alias]=n.canonicalId);return e}function An(){let t={};for(let e of Tt)!e.retiredCanonicalId||e.retiredCanonicalId===e.canonicalId||(t[e.alias]={alias:e.alias,vendor:e.vendor,requested:e.retiredCanonicalId,actual:e.canonicalId,evidence:e.unavailable||"retired by the vendor"});return t}function vt(t,e){let n=An()[e];return!n||n.vendor!==t?null:`MODEL REPOINTED: this run pinned "${n.alias}" (${n.requested}), but that model is RETIRED at the vendor (${n.evidence}) \u2014 running on "${n.actual}" instead. Output did NOT come from ${n.requested}. Redeploy the agent with a current model to make the pin match reality.`}function me(t,e){let n=typeof e=="string"?e.trim():"";if(n)return n;throw new Error(`[${t}] 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 le={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 it=Me("claude"),at=Me("codex"),It=Me("gemini"),De={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var ge=class t{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 n=this.buffer.split(`
|
|
2
|
-
`);this.buffer=
|
|
3
|
-
`,
|
|
4
|
-
`,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)&&(
|
|
1
|
+
var br=Object.defineProperty;var St=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var Ot=(t,e)=>{for(var r in e)br(t,r,{get:e[r],enumerable:!0})};var Jt={};Ot(Jt,{zodToJson:()=>fe});import{z as Gt}from"zod";import{zodToJsonSchema as Xr}from"zod-to-json-schema";function Qr(t){if(!t||typeof t!="object")return t;if(Array.isArray(t.type))return t.type.includes("null")||(t.type=[...t.type,"null"]),t;if(typeof t.type=="string")return t.type=[t.type,"null"],t;for(let e of["anyOf","oneOf"])if(Array.isArray(t[e]))return t[e].some(r=>r&&r.type==="null")||(t[e]=[...t[e],{type:"null"}]),t;return{anyOf:[t,{type:"null"}]}}function Ee(t){if(!t||typeof t!="object")return t;for(let e of["$defs","definitions"])if(t[e]&&typeof t[e]=="object")for(let r of Object.keys(t[e]))t[e][r]=Ee(t[e][r]);for(let e of["anyOf","oneOf","allOf"])Array.isArray(t[e])&&(t[e]=t[e].map(Ee));if(t.properties&&typeof t.properties=="object"){t.additionalProperties=!1;let e=Object.keys(t.properties),r=new Set(Array.isArray(t.required)?t.required:[]);for(let n of e){let o=Ee(t.properties[n]);r.has(n)||(o=Qr(o)),t.properties[n]=o}t.required=e}return t.items&&(Array.isArray(t.items)?t.items=t.items.map(Ee):t.items=Ee(t.items)),t}function fe(t,e={target:"openApi3"}){if(!t)return null;let r=e?.target==="openAi",n=null;if(typeof Gt?.toJSONSchema=="function")try{n=Gt.toJSONSchema(t)}catch{}if(!n)try{n=Xr(t,e)}catch{return null}if(r&&n)try{return Ee(n)}catch{return n}return n}var $e=St(()=>{});var hr={};Ot(hr,{INTEGRATION_API_TIMEOUT_MS:()=>mr,clearConnectedCache:()=>co,clearTokenCache:()=>ao,getConnectedIntegrations:()=>lo,resolveIntegrationToken:()=>io});import{existsSync as to,readFileSync as ro}from"node:fs";import{homedir as no}from"node:os";import{join as oo}from"node:path";function fr(){let t=process.env.ZIBBY_SELF_HOST;return t!=null&&t!==""&&t!=="0"&&t.toLowerCase()!=="false"}function dr(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let t=oo(no(),".zibby","config.json");return to(t)&&JSON.parse(ro(t,"utf-8")).sessionToken||null}catch{return null}}function pr(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app"}function so(t=process.env){let e=Number(t.INTEGRATION_API_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.min(12e4,Math.max(1e3,Math.floor(e))):mr}function gr(){let t=so();return{signal:AbortSignal.timeout(t),label:`after ${t}ms (INTEGRATION_API_TIMEOUT_MS)`}}function yr(t){return t?.name==="TimeoutError"||t?.name==="AbortError"}function lr(t,e,r){if(!yr(t))return t;let n=new Error(`${r} TIMED OUT ${e.label}`);return n.timedOut=!0,n.cause=t,n}async function io(t){if(fr()){let u=ur[t];if(u&&process.env[u])return{token:process.env[u]}}let e=Date.now(),r=ot.get(t);if(r&&r.expiresAt>e)return r.data;let n=dr();if(!n)throw new Error("Missing session credential: neither PROJECT_API_TOKEN nor ZIBBY_USER_TOKEN is set in this process env (and no ~/.zibby/config.json session). If this is an MCP skill child, the spawning skill must forward them \u2014 check the skill's envKeys / resolve() env (see @zibby/skills backend-session-env-contract). Interactive CLI: run `zibby login`.");let o=`${pr()}/integrations/token/${t}`,s=gr(),i;try{i=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${n}`},signal:s.signal})}catch(u){throw lr(u,s,`${t} token lookup`)}if(!i.ok){let u=await i.text().catch(()=>"");if(i.status===404){let f="";try{f=String(JSON.parse(u)?.error||"").trim()}catch{}throw new Error(f||`${t} is not connected. Connect it at https://studio.zibby.dev/integrations`)}throw i.status===401||i.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Failed to resolve ${t} token (${i.status}): ${u}`)}let a;try{a=await i.json()}catch(u){throw lr(u,s,`${t} token body read`)}if(!a||typeof a!="object")throw new Error(`Invalid response from ${t} token endpoint: expected object, got ${typeof a}`);if(t==="jira"){if(!a.token||typeof a.token!="string")throw new Error(`Invalid jira token response: token is ${typeof a.token}, expected string`);if(!a.cloudId&&!a.instanceUrl&&!a.baseUrl)throw new Error("Invalid jira token response: carries neither cloudId (OAuth connection) nor instanceUrl (API-token connection) \u2014 reconnect Jira.")}else if(t==="github"&&(!a.token||typeof a.token!="string"))throw new Error(`Invalid github token response: token is ${typeof a.token}, expected string`);let l=((a.expiresInSec||3e3)-120)*1e3;return ot.set(t,{data:a,expiresAt:e+l}),a}function ao(t){t?ot.delete(t):ot.clear()}function cr(t){let e=process.env.WORKFLOW_ENABLED_INTEGRATIONS;if(typeof e!="string"||e.trim()==="")return t;let r=new Set(e.split(",").map(o=>o.trim()).filter(Boolean));if(r.size===0)return t;let n={};for(let[o,s]of Object.entries(t))r.has(o)&&(n[o]=s);return n}async function lo(){let t=Date.now();if(ve&&ve.expiresAt>t)return ve.data;if(fr()){let n={};for(let[s,i]of Object.entries(ur))n[s]=!!process.env[i];let o=cr(n);return ve={data:o,expiresAt:t+6e4},o}let e=dr();if(!e)return{};let r=gr();try{let n=await fetch(`${pr()}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:r.signal});if(!n.ok)return{};let o=await n.json(),s={};if(o&&typeof o=="object")for(let[a,l]of Object.entries(o))l&&typeof l=="object"&&"connected"in l&&(s[a]=!!l.connected);let i=cr(s);return ve={data:i,expiresAt:t+6e4},i}catch(n){return yr(n)&&console.warn(`[backend-client] /integrations/status TIMED OUT ${r.label} \u2014 proceeding with no connection map`),{}}}function co(){ve=null}var ot,ur,mr,ve,_r=St(()=>{ot=new Map,ur={github:"GITHUB_TOKEN",gitlab:"GITLAB_TOKEN",sentry:"SENTRY_AUTH_TOKEN",slack:"SLACK_BOT_TOKEN"};mr=2e4;ve=null});import{resolveInvocationModel as uo,resolveInvocationExtras as fo,resolveInvocationEffort as po}from"@zibby/agent-workflow";import{AgentStrategy as Jr,DEFAULT_OUTPUT_BASE as zr,SESSION_INFO_FILE as Fr,STOP_REQUEST_FILE as Yr,getAllSkills as Hr,getSkill as Lt}from"@zibby/agent-workflow";import{spawn as Zr,execSync as ue}from"node:child_process";import{writeFileSync as Mt,readFileSync as Dt,mkdirSync as Ut,existsSync as xe,accessSync as Bt,constants as jt,unlinkSync as Wr}from"node:fs";import{join as ne,resolve as Vr}from"node:path";import{homedir as we}from"node:os";import Ie from"chalk";var oe={debug:0,info:1,warn:2,error:3,silent:4},st=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return oe.debug;if(process.env.ZIBBY_VERBOSE==="true")return oe.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in oe?oe[e]:oe.info}_shouldLog(e){return oe[e]>=this._level}_formatMessage(e,r,n={}){let o=new Date().toISOString(),i=`${this._getPrefix(e)} ${r}`;return Object.keys(n).length>0&&(i+=Ie.dim(` ${JSON.stringify(n)}`)),i}_getPrefix(e){return{debug:Ie.gray("[DEBUG]"),info:Ie.cyan("[INFO]"),warn:Ie.yellow("[WARN]"),error:Ie.red("\u274C [ERROR]")}[e]||""}debug(e,r){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,r))}info(e,r){this._shouldLog("info")&&console.log(this._formatMessage("info",e,r))}warn(e,r){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,r))}error(e,r){this._shouldLog("error")&&console.error(this._formatMessage("error",e,r))}setLevel(e){e in oe&&(this._level=oe[e])}getLevel(){return Object.keys(oe).find(e=>oe[e]===this._level)}},c=new st;var Tt=[{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 Me(t){let e={};for(let r of Tt)r.vendor===t&&(e[r.alias]=r.canonicalId);return e}function Ar(){let t={};for(let e of Tt)!e.retiredCanonicalId||e.retiredCanonicalId===e.canonicalId||(t[e.alias]={alias:e.alias,vendor:e.vendor,requested:e.retiredCanonicalId,actual:e.canonicalId,evidence:e.unavailable||"retired by the vendor"});return t}function vt(t,e){let r=Ar()[e];return!r||r.vendor!==t?null:`MODEL REPOINTED: this run pinned "${r.alias}" (${r.requested}), but that model is RETIRED at the vendor (${r.evidence}) \u2014 running on "${r.actual}" instead. Output did NOT come from ${r.requested}. Redeploy the agent with a current model to make the pin match reality.`}function me(t,e){let r=typeof e=="string"?e.trim():"";if(r)return r;throw new Error(`[${t}] 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 ce={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 it=Me("claude"),at=Me("codex"),It=Me("gemini"),De={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var ge=class t{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 r=this.buffer.split(`
|
|
2
|
+
`);this.buffer=r.pop()||"";let n="";for(let o of r)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,n+=a}else(!this.rawText.includes(i)||i.length<20)&&(this.rawText+=i,n+=i);this.tryExtractResult(this.rawText)}else this.isValidResult(s)&&(this.rawText+=`${o}
|
|
3
|
+
`,n+=`${o}
|
|
4
|
+
`,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)&&(n+=l,this.rawText+=l)}}return n||null}flush(){if(!this.buffer.trim())return null;let e="";try{let r=JSON.parse(this.buffer);this._emitToolCalls(r);let n=this.extractText(r);n&&(this.rawText+=n,e+=n,this.tryExtractResult(n))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let r=(i,a)=>{if(!i)return;let l=`${i}:${JSON.stringify(a??{})}`;this._lastToolEmit!==l&&(this._lastToolEmit=l,this.onToolCall(i,a??void 0))},n=i=>{if(i!=null){if(typeof i=="object"&&!Array.isArray(i))return i;if(typeof i=="string")try{return JSON.parse(i)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){r(e.name,n(e.input??e.arguments));return}let i=e.tool_call;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=Object.keys(i);if(a.length===1){let l=a[0],u=i[l],f=u&&typeof u=="object"?u.args??u.input??u:void 0;r(l,n(f))}return}return}if(Array.isArray(e.tool_calls)){for(let i of e.tool_calls)r(i.name,n(i.input??i.arguments));return}let o=e.message??e;if(Array.isArray(o?.tool_calls)){for(let i of o.tool_calls)r(i.name,n(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&&r(i.name,n(i.input??i.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let r=e.message.content;if(Array.isArray(r))return r.filter(n=>n.type==="text"&&n.text).map(n=>n.text).join("")}return e.type==="thinking"&&e.text||e.text?e.text:e.content&&typeof e.content=="string"?e.content:e.delta?e.delta:null}tryExtractResult(e){if(!e||typeof e!="string")return;let r=[],n=/```json\s*\n?([\s\S]*?)\n?```/g,o;for(;(o=n.exec(e))!==null;){let m=o[1].trim();try{JSON.parse(m),r.push({text:m,source:"markdown"})}catch{}}let s=0,i=0;for(;s<e.length&&(s=e.indexOf("{",s),s!==-1);){let m=0,E=s;for(let A=s;A<e.length;A++)if(e[A]==="{")m++;else if(e[A]==="}"&&(m--,m===0)){E=A,r.push({text:e.substring(s,E+1),source:"brace"}),i++;break}s=E+1}let a=this.extractedResult,l=a?JSON.stringify(a).length:0,u=0,f=-1;for(let m=0;m<r.length;m++){let E=r[m];try{let A=E.text.replace(/,(\s*[}\]])/g,"$1"),R=JSON.parse(A);this.isValidResult(R)&&(u++,l=JSON.stringify(R).length,a=R,f=m)}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,r=null){let n=new t;n.zodSchema=r,n.processChunk(e),n.flush();let o=n.getResult();return!o&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),o}};import{z as xt}from"zod";import{zodToJsonSchema as Sr}from"zod-to-json-schema";function Or(t){if(!t)return null;if(typeof xt?.toJSONSchema=="function")try{return xt.toJSONSchema(t)}catch{}try{return Sr(t,{target:"openApi3"})}catch{return null}}var Ue=class{static generateFileOutputInstructions(e,r){let n;typeof e?.parse=="function"?n=Or(e):n=e;let o=this._buildExample(n);return`
|
|
5
5
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
6
6
|
\u{1F6A8} MANDATORY: WRITE RESULT TO FILE \u{1F6A8}
|
|
7
7
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
8
8
|
You MUST write your final result as pure JSON to this EXACT file path:
|
|
9
9
|
|
|
10
|
-
${
|
|
10
|
+
${r}
|
|
11
11
|
|
|
12
12
|
Use your file writing tool (WriteFile or ApplyPatch) to create this file.
|
|
13
13
|
DO NOT just output JSON to stdout. The file MUST exist when you finish.
|
|
@@ -21,28 +21,28 @@ JSON types (strict \u2014 validators reject wrong types):
|
|
|
21
21
|
- Use true/false without quotes for booleans.
|
|
22
22
|
- Use unquoted null where a field may be null.
|
|
23
23
|
|
|
24
|
-
Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(e){if(!e)return{};let
|
|
24
|
+
Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(e){if(!e)return{};let r=e.type;if(r==="object"&&e.properties){let n={};for(let[o,s]of Object.entries(e.properties))n[o]=this._buildExample(s);return n}if(r==="array"&&e.items)return[this._buildExample(e.items)];if(e.enum&&Array.isArray(e.enum)&&e.enum.length>0)return`<${e.enum.join("|")}>`;if(r==="string")return"<string>";if(r==="number"||r==="integer")return 0;if(r==="boolean")return!1;if(e.description)return`<${e.description}>`;if(e.nullable||e.oneOf||e.anyOf){let n=e.oneOf?.find(o=>o.type!=="null")||e.anyOf?.find(o=>o.type!=="null");return n?this._buildExample(n):null}return"<value>"}};var ye=class t{constructor(e=""){this.userPrompt=e,this.systemInstructions=[],this.metadata={}}setUserPrompt(e){return this.userPrompt=e,this}appendUserPrompt(e){return this.userPrompt?this.userPrompt+=`
|
|
25
25
|
|
|
26
|
-
${e}`:this.userPrompt=e,this}addSkillHints(e){return e&&this.systemInstructions.push({type:"skill_hints",content:e,position:"prepend"}),this}addStructuredOutput(e,
|
|
26
|
+
${e}`:this.userPrompt=e,this}addSkillHints(e){return e&&this.systemInstructions.push({type:"skill_hints",content:e,position:"prepend"}),this}addStructuredOutput(e,r){if(e&&r){let n=Ue.generateFileOutputInstructions(e,r);this.systemInstructions.push({type:"structured_output",content:n,position:"append"}),this.metadata.structuredOutputPath=r}return this}addExtraInstructions(e){if(e?.trim()){let r=`\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
|
|
27
27
|
\u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
28
28
|
\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
|
|
29
29
|
|
|
30
|
-
${e.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:
|
|
30
|
+
${e.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:r,position:"append"})}return this}addSkillFragments(e){return e&&e.length>0&&this.systemInstructions.push({type:"skill_fragments",content:e.join(`
|
|
31
31
|
|
|
32
|
-
`),position:"append"}),this}addSystemInstruction(e,
|
|
32
|
+
`),position:"append"}),this}addSystemInstruction(e,r="custom",n="append"){return e&&this.systemInstructions.push({type:r,content:e,position:n}),this}getUserPrompt(){return this.userPrompt}getSystemInstructions(){return this.systemInstructions}getMetadata(){return this.metadata}build(){let e=this.systemInstructions.filter(o=>o.position==="prepend").map(o=>o.content),r=this.systemInstructions.filter(o=>o.position==="append").map(o=>o.content);return[...e,this.userPrompt,...r].filter(Boolean).join(`
|
|
33
33
|
|
|
34
|
-
`)}getStats(){let e=this.userPrompt.length,
|
|
34
|
+
`)}getStats(){let e=this.userPrompt.length,r=this.build().length;return{userPromptLength:e,fullPromptLength:r,systemInstructionsLength:r-e,instructionCount:this.systemInstructions.length,instructionTypes:this.systemInstructions.map(n=>n.type)}}clone(){let e=new t(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};function Be(t){return!!t&&(t.transport==="http"||typeof t.url=="string"&&!t.command)}var wt=Object.freeze({claude:"native",codex:"broker",gemini:"broker",cursor:"eager"});function $t(t){return wt[t]||"eager"}var Tr=new Set(Object.entries(wt).filter(([,t])=>t==="native").map(([t])=>t)),lt=Symbol("zibby.mcp.alwaysLoad");function vr(){let t=String(process.env.MCP_ALWAYS_LOAD??"").trim().toLowerCase();return!(t==="0"||t==="false"||t==="off")}function Ir(t,e){return Tr.has(t)?vr()?typeof e.alwaysLoad=="boolean"?{alwaysLoad:e.alwaysLoad}:{}:{}:{}}function re(t,e,{processEnv:r}={}){if(!e)return null;let n=Ir(t,e),o=i=>(e.alwaysLoad===!0&&Object.defineProperty(i,lt,{value:!0,enumerable:!1}),i);if(Be(e)){let i=String(e.url||"").trim();if(!i)return null;let a=e.headers&&typeof e.headers=="object"?e.headers:void 0;switch(t){case"claude":return o({type:"http",url:i,...a&&{headers:a},...n});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},...n})}}let s={command:e.command};return e.args?.length&&(s.args=e.args),e.cwd&&(s.cwd=e.cwd),r?s.env={...r,...e.env||{}}:e.env&&Object.keys(e.env).length&&(s.env=e.env),o({...s,...n})}function je(t){return Be(t)?`http \u2192 ${String(t.url||"").replace(/\?.*$/,"")}`:`${t?.command||"?"} ${(t?.args||[]).join(" ")}`.trim()}import xr from"axios";import{homedir as wr}from"node:os";import{join as $r}from"node:path";import{existsSync as kr,readFileSync as Cr}from"node:fs";import{toJSONSchema as Nr}from"zod";function Pr(){if(process.env.OPENAI_PROXY_TOKEN)return c.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return c.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let t=$r(wr(),".zibby","config.json");if(kr(t)){let e=JSON.parse(Cr(t,"utf-8"));if(e.sessionToken)return c.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(t){c.debug(`[Auth] Could not read zibby login session: ${t.message}`)}return null}function Rr(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function he(t){if(!(typeof t!="object"||t===null)){if(Object.keys(t).length===0){t.type="object",t.additionalProperties=!0;return}if(t.type||(t.properties?t.type="object":t.items&&(t.type="array")),t.type==="object")if(t.properties){for(let[e,r]of Object.entries(t.properties))r.type==="object"&&r.additionalProperties&&r.additionalProperties!==!1&&(!r.properties||Object.keys(r.properties).length===0)&&(t.properties[e]={type:["object","null"]});t.additionalProperties=!1,t.required=Object.keys(t.properties),Object.values(t.properties).forEach(he)}else"additionalProperties"in t||(t.additionalProperties=!0);t.type==="array"&&t.items&&he(t.items),t.anyOf&&t.anyOf.forEach(he),t.oneOf&&t.oneOf.forEach(he),t.allOf&&t.allOf.forEach(he)}}async function kt(t,e){c.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let r=Pr();if(!r)throw new Error("Authentication required for structured output processing.\n Local development: Run `zibby login`\n CI/CD: Set ZIBBY_USER_TOKEN environment variable (Personal Access Token from UI settings)");let n=Rr();c.info(`\u{1F517} Using OpenAI proxy: ${n}`);let o=Nr(e),s=o;if(o.$ref&&o.definitions){let f=o.$ref.split("/").pop();s=o.definitions[f]||o,c.debug(`Extracted schema from $ref: ${f}`)}delete s.$schema,he(s);let i=4e5,a=t;t.length>i&&(c.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${t.length} chars) exceeds limit, keeping last ${i} chars`),a=`... [truncated early content] ...
|
|
35
35
|
${t.slice(-i)}`);let l=`Extract and format the following information into structured JSON matching the schema.
|
|
36
36
|
|
|
37
37
|
RAW CONTENT:
|
|
38
38
|
${a}
|
|
39
39
|
|
|
40
|
-
Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,
|
|
40
|
+
Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,u={model:ce.OPENAI_POSTPROCESSING,messages:[{role:"user",content:l}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:s,strict:!0}}};c.info(`\u{1F4E4} Sending to OpenAI proxy: model=${ce.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(s.properties||{}).join(", ")}`),c.debug(` Schema size: ${JSON.stringify(s).length} chars`),c.debug(` Prompt size: ${l.length} chars`);try{let f={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(f["x-proxy-token"]=r,f["x-execution-id"]=process.env.EXECUTION_ID||""):(f.Authorization=`Bearer ${r}`,f["x-api-key"]=process.env.ZIBBY_API_KEY||"",f["x-execution-id"]=process.env.EXECUTION_ID||"");let E=(await xr.post(n,u,{headers:f,timeout:De.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!E)throw new Error("OpenAI proxy returned empty response");let A=JSON.parse(E);return c.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:A,raw:t}}catch(f){if(f.response){let m=f.response.status,E=f.response.data;throw c.error(`\u274C OpenAI proxy request failed: ${m}`),c.error(` Status: ${m}`),c.error(` Response: ${JSON.stringify(E,null,2)}`),m===401||m===403?new Error(`Authentication failed for OpenAI proxy.
|
|
41
41
|
Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
|
|
42
|
-
Response: ${JSON.stringify(
|
|
42
|
+
Response: ${JSON.stringify(E)}`,{cause:f}):new Error(`Failed to format Cursor output: ${E?.error?.message||"Unknown error"}`,{cause:f})}throw c.error(`\u274C OpenAI proxy request failed: ${f.message}`),new Error(`Failed to format output: ${f.message}`,{cause:f})}}function Q(t){let e=`${t}_POOL`,r=process.env[e];if(!r||typeof r!="string")return{picked:null,count:0,dispose:()=>{}};let n=r.split(/[,\n]+/).map(i=>i.trim()).filter(Boolean);if(n.length===0)return{picked:null,count:0,dispose:()=>{}};let o=n[Math.floor(Math.random()*n.length)],s=process.env[t];return process.env[t]=o,c.debug(`[auth-pool] ${t}: picked 1 of ${n.length} from pool (***${o.slice(-4)})`),{picked:o,count:n.length,dispose(){s===void 0?delete process.env[t]:process.env[t]=s}}}import{timeline as se,Timeline as jo,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as Ko}from"@zibby/agent-workflow";import{copyFileSync as Lr,existsSync as ct,lstatSync as Mr,mkdirSync as Ct,rmSync as Dr,symlinkSync as Ur,unlinkSync as Br}from"node:fs";import{join as ie}from"node:path";import{homedir as jr}from"node:os";import{randomBytes as Kr}from"node:crypto";var Gr=["cli-config.json","config.json","auth.json","argv.json"];function Nt(t){return!(!t||typeof t!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function Pt(t){let e=ie(t||process.cwd(),".zibby","tmp");Ct(e,{recursive:!0});let r=`${process.pid}-${Date.now()}-${Kr(4).toString("hex")}`,n=ie(e,`cursor-agent-home-${r}`),o=ie(n,".cursor");Ct(o,{recursive:!0});let s=jr(),i=ie(s,".cursor");if(ct(i))for(let a of Gr){let l=ie(i,a);if(ct(l))try{Lr(l,ie(o,a))}catch{}}if(process.platform==="darwin"){let a=ie(s,"Library");if(ct(a))try{Ur(a,ie(n,"Library"))}catch{}}return n}function Rt(t){if(!(!t||typeof t!="string"))try{let e=ie(t,"Library");try{Mr(e).isSymbolicLink()&&Br(e)}catch{}Dr(t,{recursive:!0,force:!0})}catch{}}var ut=class extends Jr{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let r=[ne(we(),".local","bin","cursor-agent"),ne(we(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"];for(let n of r)try{if(n.startsWith("/")){Bt(n,jt.X_OK);let o=ue(`"${n}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(o&&o.length>0)return c.debug(`[Cursor] Found agent at: ${n} (version: ${o.trim().slice(0,50)})`),!0}else{let o=ue(`which ${n}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!o)continue;let s=ue(`${n} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return c.debug(`[Cursor] Found '${n}' in PATH at ${o} (version: ${s.trim().slice(0,50)})`),!0}}catch{continue}return c.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,r={}){let{workspace:n=process.cwd(),print:o=!1,schema:s=null,skills:i=null,sessionPath:a=null,nodeName:l=null,timeout:u=De.CURSOR_AGENT_DEFAULT,config:f={},signal:m=null}=r,E=f?.agent?.strictMode||!1,A=r.model??f?.agent?.cursor?.model??ce.CURSOR,R=Q("CURSOR_API_KEY");try{c.debug(`[Cursor] Invoking (model: ${A}, timeout: ${u/1e3}s, skills: ${JSON.stringify(i)})`);let O=(this._setupMcpConfig(a,n,f,i,l)||{}).isolatedMcpHome??null,x=[ne(we(),".local","bin","cursor-agent"),ne(we(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"],L=null;for(let w of x)try{if(w.startsWith("/"))Bt(w,jt.X_OK),ue(`"${w}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!ue(`which ${w}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");ue(`${w} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}L=w,c.debug(`[Agent] Using binary: ${w}`);break}catch(y){c.debug(`[Agent] Binary '${w}' check failed: ${y.message}`);continue}if(!L)throw new Error(`Cursor Agent CLI not found or not working.
|
|
43
43
|
|
|
44
44
|
Checked paths:
|
|
45
|
-
${
|
|
45
|
+
${x.map(w=>` - ${w}`).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
Install cursor-agent:
|
|
@@ -51,86 +51,86 @@ Install cursor-agent:
|
|
|
51
51
|
Then add to PATH:
|
|
52
52
|
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
|
|
53
53
|
|
|
54
|
-
Test with: agent --version`);let P=new ye(e),
|
|
55
|
-
\u25C6 Model: ${
|
|
56
|
-
`);let
|
|
57
|
-
${
|
|
58
|
-
`)}catch{}let
|
|
59
|
-
`):
|
|
60
|
-
${
|
|
61
|
-
${JSON.stringify(
|
|
62
|
-
${
|
|
54
|
+
Test with: agent --version`);let P=new ye(e),_=null;if(s){let w=`zibby-result-${Date.now()}.json`;_=ne(n,".zibby","tmp",w);let y=ne(n,".zibby","tmp");xe(y)||Ut(y,{recursive:!0}),P.addStructuredOutput(s,_)}let N=process.env.CURSOR_API_KEY,$=N?` | key: ***${N.slice(-4)}`:" | key: not set";console.log(`
|
|
55
|
+
\u25C6 Model: ${A||"auto"}${$}
|
|
56
|
+
`);let k=(await import("chalk")).default,S=P.getUserPrompt();console.log(`
|
|
57
|
+
${k.bold("Prompt sent to LLM:")}`),console.log(k.dim("\u2500".repeat(60))),console.log(k.dim(S)),console.log(k.dim("\u2500".repeat(60)));let U=P.build(),D=P.getStats(),B=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",A||"auto"];if(process.env.CURSOR_API_KEY&&B.push("--api-key",process.env.CURSOR_API_KEY),B.push(U),c.debug(`[Agent] User prompt: ${D.userPromptLength} chars, System instructions: ${D.systemInstructionsLength} chars (${D.instructionCount} blocks), Full: ${D.fullPromptLength} chars, model: ${A||"auto"}`),c.debug(`[Agent] Workspace: ${n}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${A||"auto"} (from .zibby.config.js agent.cursor.model)
|
|
58
|
+
`)}catch{}let H,J=null;try{let w=a||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);H=await this._spawnWithStreaming(L,B,n,u,null,w,O,m)}catch(w){J=w}let F=H?.stdout||"";if(s){let w=typeof s.parse=="function",y=null,h=!!(_&&xe(_));if(_&&c.info(`[Agent] Result file: ${h?"present":"missing"} at ${_}`),h)try{let b=Dt(_,"utf-8").trim();y=JSON.parse(b),c.info(`[Agent] Parsed JSON from result file OK (${b.length} chars) \u2192 object ready for validation`),J&&c.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(b){c.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${b.message}`)}else if(J)c.warn(`[Agent] Result file missing at ${_} (agent process error \u2014 may still recover if strictMode repairs)`);else throw c.error(`\u274C [Agent] Result file was never created at ${_}`),new Error(`Agent did not write required result file at ${_}`);if(y&&w)try{let b=s.parse(y);return c.info("\u2705 [Agent] Zod validation passed for structured result file"),E&&c.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:F,structured:b}}catch(b){let G=b.issues?b.issues.map(j=>` - ${j.path.join(".")}: ${j.message}`).join(`
|
|
59
|
+
`):b.message?.slice(0,400);if(c.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
|
|
60
|
+
${G}`),c.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
|
|
61
|
+
${JSON.stringify(y,null,2).slice(0,500)}`),!E)throw new Error(`Agent output failed schema validation:
|
|
62
|
+
${G}
|
|
63
63
|
|
|
64
64
|
The agent wrote invalid data that doesn't match the required outputSchema.
|
|
65
|
-
Enable strictMode in .zibby.config.js for automatic repair.`,{cause:
|
|
66
|
-
`),
|
|
67
|
-
`;if(Nt(e)){let
|
|
68
|
-
`)){let
|
|
69
|
-
${
|
|
70
|
-
`).filter(
|
|
71
|
-
`).filter(
|
|
65
|
+
Enable strictMode in .zibby.config.js for automatic repair.`,{cause:b})}else{if(y)return c.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),E&&c.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:F,structured:y};h&&c.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(E&&!J){let b=H.parsedText,G=y?JSON.stringify(y):b;c.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${G.length} chars in)`);try{let j=await kt(G,s);if(w){let C=s.parse(j.structured);return c.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:F,structured:C}}return{raw:F,...j}}catch(j){if(c.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${j.message}`),y)return c.warn("[Agent] Using agent's original result file as fallback"),{raw:F,structured:y}}}if(J)throw J;let I=h?y==null?"file existed but JSON.parse failed \u2014 see WARN log above":w?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw c.error(`\u274C [Agent] No validated structured output: ${I}`),c.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error(`Agent did not produce a valid result file at ${_}. Enable strictMode for proxy fallback.`)}if(J)throw J;return this._extractFinalResult(F)||H?.parsedText||F}finally{R.dispose()}}_extractFinalResult(e){if(!e)return null;let r=e.split(`
|
|
66
|
+
`),n=null;for(let o of r){let s=o.trim();if(s)try{let i=JSON.parse(s);if(i.type==="assistant"&&i.message?.content){let a=i.message.content;if(Array.isArray(a)){let l=a.filter(u=>u.type==="text"&&u.text).map(u=>u.text).join("");l&&(n=l)}else typeof a=="string"&&a&&(n=a)}}catch{}}return n?.trim()||null}_setupMcpConfig(e,r,n,o=null,s=null){let i=n?.headless,a=ne(we(),".cursor"),l=ne(a,"mcp.json"),u={};if(xe(l))try{u=JSON.parse(Dt(l,"utf-8"))}catch{}let f=u.mcpServers||{},m=n?.paths?.output||zr,E=ne(r||process.cwd(),m,Fr),A=Array.isArray(o)?o.map(O=>Lt(O)).filter(Boolean):[...Hr()].map(([,O])=>O),R=new Set;for(let O of A)typeof O.resolve=="function"&&(R.has(O.serverName)||(R.add(O.serverName),this._ensureSkillConfigured(f,O,e,E,s,i)));if(e){let O=Lt("browser");O&&typeof O.resolve=="function"&&!R.has(O.serverName)&&this._ensureSkillConfigured(f,O,e,E,"execute_live",i)}if(Object.keys(f).length===0)return c.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let M=`${JSON.stringify({mcpServers:f},null,2)}
|
|
67
|
+
`;if(Nt(e)){let O=Pt(r||process.cwd()),x=ne(O,".cursor","mcp.json");return Mt(x,M,"utf8"),c.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${O} | servers: ${Object.keys(f).join(", ")}`),{isolatedMcpHome:O}}return xe(a)||Ut(a,{recursive:!0}),Mt(l,M,"utf8"),c.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(f).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,r,n,o,s=null,i){let a=r.cursorKey||r.serverName,l=e[a]?a:e[r.serverName]?r.serverName:null;if(l&&n){let f=typeof r.resolve=="function"?r.resolve({sessionPath:n,nodeName:s,headless:i}):null;f?.args?e[l].args=f.args:e[l].args=(e[l].args||[]).map(A=>A.startsWith("--output-dir=")?`--output-dir=${n}`:A);let m=f?.env||{},E=r.sessionEnvKey?{[r.sessionEnvKey]:o}:{};e[l].env={...e[l].env||{},...m,...E},c.debug(`[MCP] Updated ${l} session \u2192 ${n}`);return}if(l)return;let u=r.resolve({sessionPath:n,nodeName:s,headless:i});if(u){if(Be(u)){e[a]=re("cursor",u),c.debug(`[MCP] ${a} \u2192 ${je(u)}`);return}e[a]={...u,...r.sessionEnvKey&&{env:{...u.env||{},[r.sessionEnvKey]:o}}},c.debug(`[MCP] Configured ${a}`)}}_spawnWithStreaming(e,r,n,o,s=null,i=null,a=null,l=null){return new Promise((u,f)=>{let m=Date.now(),E="",A="",R=Date.now(),M=0,O=!1,x=null,L=!1,P=!1,_=null;if(i)try{_=ne(Vr(String(i)),Yr)}catch{_=null}let N=!1,$=()=>{N||(N=!0,Rt(a))},k={...process.env};a&&(k.HOME=a,process.platform==="win32"&&(k.USERPROFILE=a),c.debug(`[Agent] cursor-agent HOME=${a} (isolated MCP config)`));let S=Zr(e,r,{cwd:n,shell:!1,stdio:["pipe","pipe","pipe"],env:k,...l&&{signal:l}});c.debug(`[Agent] PID: ${S.pid}`);let U=null,D=()=>{O||P||(O=!0,x="aborted",c.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),U=setTimeout(()=>{if(!P){c.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{S.kill("SIGKILL")}catch{}}},5e3))};l&&(l.aborted?D():l.addEventListener("abort",D,{once:!0})),S.stdin.on("error",y=>{y.code!=="EPIPE"&&c.warn(`[Agent] stdin error: ${y.message}`)}),S.stdout.on("error",y=>{y.code!=="EPIPE"&&c.warn(`[Agent] stdout error: ${y.message}`)}),S.stderr.on("error",y=>{y.code!=="EPIPE"&&c.warn(`[Agent] stderr error: ${y.message}`)}),s?(S.stdin.write(s,y=>{y&&y.code!=="EPIPE"&&c.warn(`[Agent] Failed to write to stdin: ${y.message}`),S.stdin.end()}),c.debug(`[Agent] Prompt also piped to stdin (${s.length} chars)`)):S.stdin.end();let B=null;_&&(B=setInterval(()=>{if(!(O||P))try{if(xe(_)){O=!0,x="aborted";try{Wr(_)}catch{}c.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),S.kill("SIGTERM"),setTimeout(()=>{S.killed||S.kill("SIGKILL")},2e3)}}catch{}},600));let H=new Set,J=new Date(m).toISOString().replace(/\.\d+Z$/,""),F=setInterval(()=>{let y=Math.round((Date.now()-m)/1e3),h=Math.round((Date.now()-R)/1e3),I=[];try{let G=Math.ceil(y/60)+1,j=ue(`find "${n}" -type f -mmin -${G} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(j)for(let C of j.split(`
|
|
68
|
+
`)){let z=C.replace(`${n}/`,"");H.has(z)||(H.add(z),I.push(z))}}catch{}let b="";I.length>0&&(b=` | \u{1F4C1} new: ${I.map(j=>j.split("/").pop()).join(", ")}`),H.size>0&&(b+=` | \u{1F4E6} total: ${H.size} files`),c.debug(`\u{1F493} [Agent] Running for ${y}s | ${M} lines output${b}`),M===0&&y>=30&&H.size===0&&(y<35&&c.warn(`\u26A0\uFE0F [Agent] No output after ${y}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),y>=60&&(O=!0,x=x||"stall",c.error(`\u274C [Agent] No response after ${y}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),S.kill("SIGTERM"),setTimeout(()=>{S.killed||S.kill("SIGKILL")},3e3)))},3e4),v=setTimeout(()=>{O=!0,x=x||"timeout";let y=Math.round((Date.now()-m)/1e3);c.error(`\u23F1\uFE0F [Agent] Timeout after ${y}s \u2014 killing process (PID: ${S.pid})`),E.trim()&&c.warn(`\u{1F4E4} [Agent] Partial output (${E.length} chars) before timeout:
|
|
69
|
+
${E.slice(-2e3)}`),S.kill("SIGTERM"),setTimeout(()=>{S.killed||S.kill("SIGKILL")},5e3)},o),w=new ge;w.onToolCall=(y,h)=>{let I=y,b=h;if(y==="mcpToolCall"&&h?.name)I=h.name.replace(/^mcp_+[^_]+_+/,""),I.includes("-")&&I.split("-")[0]===I.split("-")[1]&&(I=I.split("-")[0]),b=h.args??h.input??h;else{if(y==="readToolCall"||y==="editToolCall"||y==="writeToolCall")return;(y.startsWith("mcp__")||y.includes("ToolCall"))&&(I=y.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(I.includes("memory")?se.stepMemory(`Tool: ${I}`):se.stepTool(`Tool: ${I}`),b!=null&&typeof b=="object"&&Object.keys(b).length>0&&!P){let j=JSON.stringify(b),C=j.length>100?`${j.substring(0,100)}...`:j;console.log(` Input: ${C}`)}},S.stdout.on("data",y=>{let h=y.toString();E+=h,R=Date.now(),L||(L=!0);let I=w.processChunk(h);I&&!P&&process.stdout.write(I);let b=h.split(`
|
|
70
|
+
`).filter(G=>G.trim());M+=b.length}),S.stderr.on("data",y=>{let h=y.toString();A+=h,R=Date.now(),L||(L=!0);let I=h.split(`
|
|
71
|
+
`).filter(b=>b.trim());for(let b of I)c.warn(`\u26A0\uFE0F [Agent stderr] ${b}`)}),S.on("close",(y,h)=>{if(P=!0,$(),clearTimeout(v),clearInterval(F),B&&clearInterval(B),U&&clearTimeout(U),l&&!l.aborted)try{l.removeEventListener("abort",D)}catch{}w.flush();let I=Math.round((Date.now()-m)/1e3);if(c.debug(`[Agent] Exited: code=${y}, signal=${h}, elapsed=${I}s, output=${E.length} chars`),O){if(x==="aborted"){let j=new Error("Aborted via signal");j.name="AbortError",f(j);return}f(new Error(`Cursor Agent timed out after ${I}s (limit: ${o/1e3}s). ${M} lines produced. Last output ${Math.round((Date.now()-R)/1e3)}s ago. ${E.trim()?`
|
|
72
72
|
Partial output (last 500 chars):
|
|
73
|
-
${
|
|
74
|
-
Stderr: ${
|
|
75
|
-
Stdout (last 500 chars): ${
|
|
73
|
+
${E.slice(-500)}`:"No output captured."}`));return}if(y!==0){f(new Error(`Cursor Agent failed: exit code ${y}, signal ${l}. ${A.trim()?`
|
|
74
|
+
Stderr: ${A.slice(-1e3)}`:""}${E.trim()?`
|
|
75
|
+
Stdout (last 500 chars): ${E.slice(-500)}`:""}`));return}let b=w.getResult(),G=b?JSON.stringify(b,null,2):w.getRawText()||E||"";u({stdout:E||A||"",parsedText:G})}),S.on("error",y=>{if($(),clearTimeout(v),clearInterval(F),B&&clearInterval(B),U&&clearTimeout(U),l&&!l.aborted)try{l.removeEventListener("abort",D)}catch{}f(new Error(`Cursor Agent spawn error: ${y.message}
|
|
76
76
|
Binary: ${e}
|
|
77
77
|
This usually means the binary is not in PATH. Try:
|
|
78
|
-
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};import{AgentStrategy as
|
|
79
|
-
`));let a=
|
|
80
|
-
`);
|
|
78
|
+
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};import{AgentStrategy as en,getSkill as zt,NO_INTEGRATION_TOGGLEABLE_SKILL_IDS as tn,formatProviderError as rn}from"@zibby/agent-workflow";import{query as nn}from"@anthropic-ai/claude-agent-sdk";import qr from"node:process";var Kt=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 _e(t=qr.env){let e={},r=new Set(Kt);for(let[n,o]of Object.entries(t))r.has(n)||o!==void 0&&(e[n]=o);return e}$e();import{writeFileSync as ft,mkdirSync as dt,existsSync as be,readFileSync as Yt}from"fs";import{homedir as Ht}from"os";import{join as te}from"path";function Ke(t){if(!t||typeof t!="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},r=e(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens),n=e(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens);return r==null&&n==null?null:{input:r||0,output:n||0}}import{createRequire as on}from"module";import Z from"process";var Ft=on(import.meta.url);function sn(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")}function Zt(t){if(!t||typeof t!="object")return null;let e=t.message?.content??t.content;return Array.isArray(e)&&e.length||typeof e=="string"&&e.length?e:typeof t.text=="string"&&t.text.length?t.text:null}function an(t){let e=Zt(t);if(e===null)return null;let r;try{r=JSON.stringify(e)}catch{return null}return typeof r!="string"||!r?null:`${`${t.type||t.constructor?.name||"?"}`}:${r.length}:${sn(r)}`}function Wt(t){if(!t||typeof t!="object")return"a message with no type";let e=t.type||t.constructor?.name||"unknown-type",r=t.subtype?`/${t.subtype}`:"",n=Zt(t);if(typeof n=="string")return`${e}${r} text "${n.slice(0,80)}"`;if(!Array.isArray(n))return`${e}${r} (no readable content)`;let o=n.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 n.length>o.length&&o.push(`+${n.length-o.length} more`),`${e}${r} [${o.join(", ")}]`}function ln(t){if(!t||typeof t!="object")return"";let e=t.message?.content??t.content;if(Array.isArray(e)){let r=e.filter(n=>n&&n.type==="text"&&typeof n.text=="string"&&n.text.trim()).map(n=>n.text.trim());if(r.length)return ke(r.join(" "))}else if(typeof e=="string"&&e.trim())return ke(e);return t.error&&typeof t.error=="object"&&typeof t.error.message=="string"?ke(t.error.message):typeof t.message=="string"&&t.message.trim()?ke(t.message):typeof t.result=="string"&&t.result.trim()?ke(t.result):Wt(t)}function ke(t){let e=String(t).replace(/\s+/g," ").trim();return e.length>400?`${e.slice(0,400)}\u2026`:e}function pt(t){let e=String(t??"").trim().slice(0,400);return!e||e.startsWith("```")||e.startsWith("{")||e.startsWith("[")?!0:/"reply"\s*:/.test(e)}var ze=(t,e)=>{let r=String(t??"");return r.length>e?`${r.slice(0,e)}\u2026`:r},cn=/secret|token|password|passwd|credential|authorization|bearer|api[-_]?key|private[-_]?key|access[-_]?key/i,Vt=(t,e=0)=>{if(t==null||e>6||typeof t!="object")return t;let r=Array.isArray(t)?[]:{};for(let[n,o]of Object.entries(t)){let s=cn.test(n)||n==="value"&&typeof t.key=="string";r[n]=s&&typeof o=="string"&&o?"[redacted]":Vt(o,e+1)}return r},de=t=>{try{if(t==null)return"";let e=Vt(t),r=typeof e=="string"?e:JSON.stringify(e);return ze(String(r).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""}},un=500;function mt(t){let e=t&&typeof t=="object"?t.content:void 0,r=new Set,n=0;if(typeof e=="string")n=e.length,e&&r.add("text");else if(Array.isArray(e))for(let l of e){if(typeof l=="string"){r.add("text"),n+=l.length;continue}!l||typeof l!="object"||(r.add(typeof l.type=="string"&&l.type?l.type:"unknown"),typeof l.text=="string"&&(n+=l.text.length))}else if(e!=null){r.add("json");try{n=JSON.stringify(e).length}catch{n=0}}let o=!(t&&t.is_error===!0),s={ok:o,chars:n};if(r.size&&(s.kind=[...r].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(`
|
|
79
|
+
`));let a=de(i);return a&&(s.error=a),s}function fn(){try{if(Z.env.CLAUDE_CODE_EXECUTABLE&&be(Z.env.CLAUDE_CODE_EXECUTABLE))return Z.env.CLAUDE_CODE_EXECUTABLE;let t=Z.platform,e=Z.arch,r=`@anthropic-ai/claude-agent-sdk-${t}-${e}`,n=t==="win32"?"claude.exe":"claude";try{let o=Ft.resolve(`${r}/package.json`),s=te(o,"..",n);if(be(s))return s}catch{}try{let o=Ft.resolve("@anthropic-ai/claude-agent-sdk/package.json"),s=te(o,"..");for(let a of[n,te("vendor",n),te("bin",n)]){let l=te(s,a);if(be(l))return l}let i=te(s,"..",`claude-agent-sdk-${t}-${e}`,n);if(be(i))return i}catch{}}catch{}return null}var Ge=fn();Ge&&c.debug(`Claude native CLI resolved to baked binary: ${Ge}`);var Je=class extends en{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let r=!!Z.env.ANTHROPIC_API_KEY||!!Z.env.ANTHROPIC_API_KEY_POOL,n=!!Z.env.CLAUDE_CODE_OAUTH_TOKEN||!!Z.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,o=!!Z.env.ANTHROPIC_AUTH_TOKEN||!!Z.env.ANTHROPIC_AUTH_TOKEN_POOL,s=r||n||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,r={}){let{model:n,workspace:o=Z.cwd(),schema:s=null,images:i=[],skills:a=null,sessionPath:l=null,nodeName:u=null,timeout:f,config:m={},activityLog:E=!1,signal:A=null,sessionId:R,resume:M,forkSession:O,sessionStore:x}=r,L=me("claude",n),P=it[L]||L;it[L]&&L!==P&&c.debug(`Mapped model: ${L} \u2192 ${P}`);let _=[Q("ANTHROPIC_API_KEY"),Q("CLAUDE_CODE_OAUTH_TOKEN"),Q("ANTHROPIC_AUTH_TOKEN")];try{c.debug(`Invoking Claude Agent SDK with model: ${P}, skills: ${JSON.stringify(a)}`);let N=ze,$=(v,w)=>{try{console.log(JSON.stringify({mode:v,...w}))}catch{}},k=Z.env.CLAUDE_CODE_OAUTH_TOKEN,S=Z.env.ANTHROPIC_API_KEY,U=Z.env.ANTHROPIC_AUTH_TOKEN;Z.env.CLAUDE_CODE_CREDENTIALS_JSON?mn(Z.env.CLAUDE_CODE_CREDENTIALS_JSON):k&&pn(k,Z.env.__ZIBBY_CLAUDE_PLAN);let D=Z.env.__ZIBBY_CLAUDE_PLAN,B=D?D.charAt(0).toUpperCase()+D.slice(1):null,H;if(k?H=B?`Claude ${B} plan \xB7 ***${k.slice(-4)}`:`Subscription \xB7 ***${k.slice(-4)}`:S?H=`API key \xB7 ***${S.slice(-4)}`:U?H=`Bearer \xB7 ***${U.slice(-4)}`:H="NONE \u2014 request will fail",!E){let v=(await import("chalk")).default;console.log(""),console.log(` ${v.cyan("\u25C6")} ${v.bold(P)}`),console.log(` ${v.dim("Auth: ")}${H}`),console.log(` ${v.dim("Workdir: ")}${o}`),console.log(""),console.log(v.bold("Prompt sent to LLM:")),console.log(v.dim("\u2500".repeat(60))),console.log(v.dim(e)),console.log(v.dim("\u2500".repeat(60)))}let{allowedTools:J,mcpServers:F}=this._resolveSkills(a,{sessionPath:l,workspace:o,nodeName:u});for(let v of r.extraMcpServers||[])if(v&&v.serverName&&v.def){if(Object.prototype.hasOwnProperty.call(F,v.serverName)){console.warn(`[custom-mcp] skip "${v.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let w=re("claude",v.def);w&&(F[v.serverName]=w,J.push(`mcp__${v.serverName}__*`))}try{let v={cwd:o,allowedTools:J,...r.effort?{effort:r.effort}:{},...Array.isArray(r.disallowedTools)&&r.disallowedTools.length?{disallowedTools:r.disallowedTools}:{},settings:{permissions:{allow:["Bash(*)","Read(*)","Write(*)","Edit(*)","MultiEdit(*)","NotebookEdit(*)","Grep(*)","Glob(*)","WebFetch(*)","WebSearch(*)","Task(*)","TodoWrite(*)","Skill(*)"]}},model:P,env:_e(Z.env),...Ge&&{pathToClaudeCodeExecutable:Ge},...Object.keys(F).length>0&&{mcpServers:F},...R&&{sessionId:R},...M&&{resume:M},...O&&{forkSession:!0},...x&&{sessionStore:x}};if(s){let W=typeof s.parse=="function"?fe(s):s;v.outputFormat={type:"json_schema",schema:W},c.debug("Structured output enforced via SDK outputFormat")}c.debug(`Agent SDK options: ${JSON.stringify({cwd:v.cwd,toolCount:J.length,permissionMode:v.permissionMode,model:v.model,hasOutputFormat:!!v.outputFormat})}`);let w="",y=0,h=new Map,I=[];c.debug("Starting Claude Agent SDK query stream");let b=e,G=Array.isArray(i)?i.filter(g=>g&&typeof g.path=="string"&&g.path.startsWith("/")):[];if(G.length){let g=G.map((W,p)=>` ${p+1}. ${W.path}${W.name?` (${W.name})`:""}`).join(`
|
|
80
|
+
`);b=`${e}
|
|
81
81
|
|
|
82
82
|
# Attached image files \u2014 VIEW THESE
|
|
83
|
-
The user attached ${
|
|
84
|
-
${
|
|
83
|
+
The user attached ${G.length} image(s), saved locally. Use the Read tool on each path to SEE the image, then use what it shows to answer:
|
|
84
|
+
${g}`}let j;try{j=nn({prompt:b,options:v})}catch(g){throw c.error(`Failed to initialize Claude Agent SDK: ${g.message}`),g}let C=null,z=0,q=!1,ee=3;if(A?.aborted){let g=new Error("Aborted via signal");throw g.name="AbortError",g}try{for await(let g of j){if(A?.aborted){let p=new Error("Aborted via signal");throw p.name="AbortError",p}if(I.push(g),g.type==="system"&&g.subtype==="init"){let p=g.mcp_servers||[];if(p.length>0){let T=p.map(d=>`${d.name}=${d.status}${d.error?` (${String(d.error).slice(0,120)})`:""}`).join(", ");c.info(`[mcp] SDK init \u2014 ${p.length} server(s): ${T}`);for(let d of p)(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(g.tools)){let T=g.tools.filter(d=>d.startsWith("mcp__"));if(T.length>0){let d=X=>X.split("__")[1]||"",Y=new Set(Object.entries(F||{}).filter(([,X])=>X&&X.alwaysLoad===!0).map(([X])=>X)),K=T.filter(X=>Y.has(d(X))),V=T.length-K.length,ae={};for(let X of T){let le=d(X);Y.has(le)||(ae[le]=(ae[le]||0)+1)}let At=Object.entries(ae).sort((X,le)=>le[1]-X[1]).map(([X,le])=>`${X}:${le}`).join(" ");c.info(`[mcp] ${T.length} tool(s) reachable \u2014 ${K.length} IN PROMPT${K.length?` (${K.join(", ")})`:""}; ${V} DEFERRED behind ToolSearch${At?` [${At}]`:""}`)}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(g.type==="system"&&g.subtype==="api_retry"){let p=Number(g.attempt)||0,T=Number(g.max_retries)||0,d=g.error_status!=null?String(g.error_status):"?",Y=typeof g.error=="string"?g.error:"error",K=Number.isFinite(g.retry_delay_ms)?Math.round(g.retry_delay_ms):null,V=`upstream ${d} (${Y}) \u2014 SDK retry ${p}/${T}`+(K!=null?` in ${K}ms`:"");E&&$("turn:retry",{status:d,kind:Y,attempt:p,maxRetries:T,delayMs:K,detail:V}),c.warn(`[claude] transient ${V}`);continue}if(g.type==="error"||g.error){let p=typeof g.error=="string"?g.error:g.error?.type||g.error?.name||null,T=g.error_status??g.error?.status??null,d=ln(g);try{c.error("SDK error event raw payload",{fullMessage:JSON.stringify(g,null,2)})}catch{}let Y=new Error(rn({kind:p,status:T,text:d}));Y.providerErrorKind=p||null;let K=T==null?NaN:Number(T);throw Y.providerErrorStatus=Number.isInteger(K)&&K>=100&&K<=599?K:null,Y.providerErrorText=d,Y}let W=an(g);if(W!==null)if(W===C){if(z++,z>=ee)throw new Error(`API stuck in loop (${z}x identical): ${Wt(g)}`)}else C=W,z=1;if(g.type==="assistant"||g.constructor?.name==="AssistantMessage"){let p=g.message?.content||g.content||[],T=Array.isArray(p)&&p.some(d=>d&&d.type==="tool_use");for(let d of p)if(d.type==="thinking"&&d.thinking)E?$("turn:thinking",{text:N(d.thinking,600)}):console.log(`${d.thinking.substring(0,200)}${d.thinking.length>200?"...":""}`);else if(d.type==="text"&&d.text){if(w+=d.text,E&&(T||!q))if(!T&&pt(d.text))q=!0;else{let Y=N(d.text.trim(),200);Y&&$("turn:narration",{text:Y,withTool:T})}E||(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(y++,d.name.includes("memory")?se.stepMemory(`Tool: ${d.name}`):se.stepTool(`Tool: ${d.name}`),E){let K=de(d.input);$("turn:tool",{name:d.name,...K?{input:K}:{}}),d.id&&(h.set(d.id,d.name),h.size>un&&h.delete(h.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(g.type==="user"){if(E){let p=g.message?.content||g.content;if(Array.isArray(p))for(let T of p){if(!T||T.type!=="tool_result")continue;let d=h.get(T.tool_use_id);$("turn:tool-result",{...d?{name:d}:{},...mt(T)})}}}else if(g.type==="result"||g.constructor?.name==="ResultMessage"){let p=g.result||g.text||g.content||w;try{dn({message:g,sessionPath:l,nodeName:u,model:L,toolCallCount:y})}catch(d){c.debug(`usage.json write failed: ${d.message}`)}let T=Ke(g?.usage||g?.message?.usage);if(s){if(g.structured_output){c.debug("Using SDK native structured_output");let Y=typeof s.parse=="function"?s.parse(g.structured_output):g.structured_output;return{raw:p,structured:Y,...T?{usage:T}:{},toolUseCount:y}}if(p){let d=this._extractJson(p,s);if(d)return{raw:p,structured:d,...T?{usage:T}:{},toolUseCount:y}}c.warn(`Could not extract structured output \u2014 returning raw text (${(p||"").length} chars)`)}return p||""}}if(c.warn(`Agent SDK ended without result. Collected ${I.length} messages`),w.length>0)return c.debug("Returning accumulated text from messages"),w;throw new Error("Claude Agent SDK query ended without result")}catch(g){let W={message:g?.message,name:g?.name,code:g?.code,cause:g?.cause?.message||g?.cause,stack:g?.stack?.split(`
|
|
85
85
|
`).slice(0,5).join(`
|
|
86
|
-
`),stringified:(()=>{try{return JSON.stringify(
|
|
87
|
-
\u25C6 Model: ${L}${
|
|
88
|
-
`),Array.isArray(l)&&l.length>0){let
|
|
89
|
-
${
|
|
86
|
+
`),stringified:(()=>{try{return JSON.stringify(g,Object.getOwnPropertyNames(Object(g)))}catch{return String(g)}})()};throw c.error(`Error during query stream: ${g?.message||g}`,W),g}}catch(v){throw c.error("Claude Agent SDK call failed",{message:v?.message,name:v?.name,code:v?.code,cause:v?.cause?.message||v?.cause}),v}}finally{for(let N of _)N.dispose()}}_resolveSkills(e,r){let n=["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:[...n],mcpServers:{}};let o=[...n],s={},i=Z.env.WORKFLOW_ENABLED_INTEGRATIONS,a=typeof i=="string"&&i.trim()!==""?new Set(i.split(",").map(f=>f.trim()).filter(Boolean)):null,l=f=>{let m=zt(f);return m?.meta?.toggleable===!0?!0:m?.meta?.toggleable===void 0&&tn.includes(f)},u=f=>a!==null&&a.size>0&&l(f)&&!a.has(f);for(let f of e){if(u(f)){c.debug(`Skill "${f}" disabled by enabledIntegrations allowlist \u2014 skipping`);continue}let m=zt(f);if(!m){c.warn(`Unknown skill "${f}" \u2014 skipping`);continue}if(m.allowedTools&&o.push(...m.allowedTools),typeof m.resolve=="function"){let E=m.resolve(r),A=re("claude",E);A&&(s[m.serverName]=A,c.debug(`MCP: ${m.serverName} \u2192 ${je(E)}`))}}return{allowedTools:o,mcpServers:s}}_extractJson(e,r){let n=[()=>{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 n)try{let s=o();if(!s)continue;let i=JSON.parse(s);if(typeof i!="object"||i===null)continue;return typeof r.parse=="function"?r.parse(i):i}catch{}return null}};function dn({message:t,sessionPath:e,nodeName:r,model:n,toolCallCount:o}){if(!e||!r)return;let s=t?.usage||t?.message?.usage||{},i=Ce(s.input_tokens,s.inputTokens),a=Ce(s.output_tokens,s.outputTokens),l=Ce(s.cache_read_input_tokens,s.cacheReadInputTokens),u=Ce(s.cache_creation_input_tokens,s.cacheCreationInputTokens),f=Ce(t?.duration_ms,t?.durationMs),m={model:n||null,input_tokens:i,output_tokens:a,cache_read_tokens:l,cache_creation_tokens:u,tool_call_count:typeof o=="number"?o:null,duration_ms:f,captured_at:new Date().toISOString()},E=te(e,r);try{dt(E,{recursive:!0})}catch{}ft(te(E,"usage.json"),JSON.stringify(m,null,2),"utf-8")}function Ce(...t){for(let e of t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e)))return Number(e)}return null}function pn(t,e){let r=te(Ht(),".claude"),n=te(r,".credentials.json"),o={claudeAiOauth:{accessToken:t,refreshToken:"",expiresAt:Date.now()+365*24*60*60*1e3,scopes:["user:inference","user:profile"],...e?{subscriptionType:String(e).toLowerCase()}:{}}};try{if(be(n)&&JSON.parse(Yt(n,"utf-8"))?.claudeAiOauth?.accessToken===t)return;dt(r,{recursive:!0}),ft(n,JSON.stringify(o,null,2),"utf-8"),c.debug(`Wrote Claude Code OAuth credentials to ${n}`)}catch(s){c.warn(`Could not write ${n}: ${s.message} \u2014 Claude SDK may fail to authenticate.`)}}function mn(t){let e=te(Ht(),".claude"),r=te(e,".credentials.json"),n;try{n=JSON.parse(t)}catch(o){c.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${o.message}`);return}if(!n?.claudeAiOauth?.accessToken){c.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if(be(r)){let o=JSON.parse(Yt(r,"utf-8"));if(o?.claudeAiOauth?.accessToken===n.claudeAiOauth.accessToken&&o?.claudeAiOauth?.expiresAt===n.claudeAiOauth.expiresAt)return}dt(e,{recursive:!0}),ft(r,JSON.stringify(n,null,2),"utf-8"),c.debug(`Wrote full Claude Code credentials blob to ${r}`)}catch(o){c.warn(`Could not write ${r}: ${o.message} \u2014 Claude SDK may fail to authenticate.`)}}import{AgentStrategy as vn,getSkill as In}from"@zibby/agent-workflow";import{mkdtempSync as gn,writeFileSync as yn,mkdirSync as hn,existsSync as _n}from"fs";import{join as Ne,dirname as qt}from"path";import{tmpdir as En}from"os";import{fileURLToPath as bn}from"url";var Xt="toolbox";function An(){let t=qt(bn(import.meta.url));for(let e=t,r=0;r<4;r++,e=qt(e)){let n=Ne(e,"mcp","tool-broker-server.js");if(_n(n))return n}throw new Error(`[tool-broker] cannot find mcp/tool-broker-server.js from ${t} \u2014 the package layout changed, or the build did not emit it.`)}function Sn(){let t=String(process.env.MCP_TOOL_BROKER??"").trim().toLowerCase();return!(t==="0"||t==="false"||t==="off")}function On(t){if(t){let e=Ne(t,".mcp-broker");return hn(e,{recursive:!0}),Ne(e,"spec.json")}return Ne(gn(Ne(En(),"mcp-broker-")),"spec.json")}function Fe(t,e,{sessionPath:r,toolWorkingSet:n}={}){let o=e&&typeof e=="object"?e:{},s=Object.keys(o);if(!s.length||$t(t)!=="broker"||!Sn()||s.length===1)return o;let i=s.filter(m=>o[m]&&o[m][lt]===!0),a=On(r),l=Array.isArray(n?.warmTools)?n.warmTools.filter(m=>m&&typeof m.server=="string"&&typeof m.tool=="string").map(m=>({server:m.server,tool:m.tool,...Number.isFinite(Number(m.lastUsedAt))?{lastUsedAt:Number(m.lastUsedAt)}:{}})):[],u=typeof n?.usagePath=="string"&&n.usagePath.trim()?n.usagePath.trim():null;yn(a,JSON.stringify({servers:o,pinned:i,...l.length?{warmTools:l}:{},...u?{usagePath:u}:{}},null,2),{mode:384}),console.error(`[tool-broker] ${t}: ${s.length} server(s) behind "${Xt}"${i.length?` (pinned: ${i.join(", ")})`:""} \u2014 spec ${a}`);let f={command:process.execPath,args:[An(),"--spec",a]};return{[Xt]:f}}import{execSync as He}from"node:child_process";import{execSync as Tn}from"node:child_process";function Ye(t){if(!/^[A-Za-z0-9._-]+$/.test(t))return!1;try{return Tn(`command -v ${t}`,{encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim().length>0}catch{return!1}}$e();import{readFileSync as xn,mkdirSync as gt,cpSync as wn,existsSync as $n}from"node:fs";import{join as Pe}from"node:path";import{homedir as kn}from"node:os";function yt(t){if(Array.isArray(t))return t.map(yt);if(t&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t))n!==null&&(e[r]=yt(n));return e}return t}var Ze=class extends vn{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):Ye("codex")?!0:(c.warn("[Codex] codex CLI not on PATH. Install: npm install -g @openai/codex"),!1)}async invoke(e,r={}){let{model:n,workspace:o=process.cwd(),schema:s=null,images:i=[],skills:a=null,plugins:l=null,sessionPath:u=null,nodeName:f=null,timeout:m,config:E={},activityLog:A=!1,signal:R=null}=r,M=[Q("OPENAI_API_KEY"),Q("CODEX_API_KEY")];try{let{Codex:O}=await import("@openai/codex-sdk"),x=me("codex",n),L=at[x]||x;at[x]&&x!==L&&c.debug(`Mapped model: ${x} \u2192 ${L}`);let P=vt("codex",x);P&&c.warn(P),c.debug(`Invoking Codex SDK with model: ${L}, skills: ${JSON.stringify(a)}`);let _=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;_&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=_);let N=typeof r.serviceTier=="string"?r.serviceTier.trim().toLowerCase():"",$=_?` | key: ***${_.slice(-4)}`:" | key: not set";if(console.log(`
|
|
87
|
+
\u25C6 Model: ${L}${N==="fast"?" | speed: fast":""}${$}
|
|
88
|
+
`),Array.isArray(l)&&l.length>0){let h=this._resolveCodexHome(u);process.env.CODEX_HOME=h;try{gt(h,{recursive:!0})}catch{}this._ensurePlugins(l,h)}let k=(h,I)=>{try{console.log(JSON.stringify({mode:h,...I}))}catch{}},S=this._resolveSkillsToMcp(a,{sessionPath:u,workspace:o,nodeName:f});for(let h of r.extraMcpServers||[])if(h&&h.serverName&&h.def){if(Object.prototype.hasOwnProperty.call(S,h.serverName)){console.warn(`[custom-mcp] skip "${h.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let I=re("codex",h.def);I&&(S[h.serverName]=I)}let U=Fe("codex",S,{sessionPath:u,toolWorkingSet:r.toolWorkingSet});if(U!==S&&(e+="\n\n# Toolbox access\nIntegration tools named in this prompt are behind the `toolbox` MCP. Call `toolbox/list_tools`, then `toolbox/call_tool`; use `toolbox/describe_tool` only for unclear or nested arguments. `list_mcp_resources` and `list_mcp_resource_templates` do not discover tools."),!A){let h=(await import("chalk")).default;console.log(`
|
|
89
|
+
${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 D={};r.effort&&(D.model_reasoning_effort=r.effort),N==="fast"?(D.service_tier="fast",D.features={fast_mode:!0}):N&&c.warn(`[Codex] ignoring unknown serviceTier "${N}" \u2014 expected "fast" or unset`),Object.keys(U).length>0&&(D.mcp_servers=U,Object.values(U).some(h=>h&&typeof h.url=="string")&&(D.experimental_use_rmcp_client=!0),c.debug(`[Codex] MCP servers: ${Object.keys(U).join(", ")}`+(U===S?"":` (broker over ${Object.keys(S).join(", ")})`)));let B=this._resolveCodexBin(),H=new O({...B?{codexPathOverride:B}:{},...Object.keys(D).length>0&&{config:D},env:_e(process.env)}),J=o;try{J&>(J,{recursive:!0})}catch{}(!J||!$n(J))&&(J=process.cwd());let F=H.startThread({workingDirectory:J,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),v=s&&typeof s.parse=="function",w=R?{signal:R}:{};if(s)try{let h=v?fe(s,{target:"openAi"}):s;w.outputSchema=h,c.debug("Structured output via SDK outputSchema")}catch(h){c.warn(`[Codex] Schema conversion failed, will extract from text: ${h.message}`)}let y=Array.isArray(i)?i.filter(h=>h&&typeof h.path=="string"&&h.path.startsWith("/")):[];if(y.length&&(e=`${e}
|
|
90
90
|
|
|
91
91
|
# Attached image files \u2014 VIEW THESE
|
|
92
|
-
The user attached ${
|
|
93
|
-
${
|
|
94
|
-
`)}`),R?.aborted){let
|
|
95
|
-
`).some(o=>o.includes(e)&&/installed/.test(o))}catch{return!1}}};import{AgentStrategy as
|
|
96
|
-
${C}`,"schema_instruction","append");let
|
|
97
|
-
${C}`,"json_instruction","append")}let
|
|
92
|
+
The user attached ${y.length} image(s), saved locally. Read each path to SEE the image, then use what it shows to answer:
|
|
93
|
+
${y.map((h,I)=>` ${I+1}. ${h.path}${h.name?` (${h.name})`:""}`).join(`
|
|
94
|
+
`)}`),R?.aborted){let h=new Error("Aborted via signal");throw h.name="AbortError",h}try{let{events:h}=await F.runStreamed(e,w),I=0,b="",G=null,j=new Set,C=500,z=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",q=p=>p.type==="mcp_tool_call"?de(p.arguments):p.type==="command_execution"?de({command:p.command}):p.type==="web_search"?de({query:p.query}):de(p.arguments||p.input),ee=p=>p==="mcp_tool_call"||p==="command_execution"||p==="web_search"||p==="tool_call"||p==="function_call",g=p=>{let T=p.id||`${p.type}:${j.size}`;if(j.has(T))return;j.add(T),j.size>C&&j.delete(j.values().next().value);let d=q(p);k("turn:tool",{name:z(p),...d?{input:d}:{}})},W=p=>{let T=p.status==="failed"||!!(p.error&&p.error.message),d;p.type==="mcp_tool_call"?d=T?p.error&&p.error.message||p.result&&p.result.content||"":p.result&&p.result.content||"":p.type==="command_execution"&&(d=p.aggregated_output||""),k("turn:tool-result",{name:z(p),...mt({content:d,is_error:T})})};for await(let p of h){if(R?.aborted){let d=new Error("Aborted via signal");throw d.name="AbortError",d}let T=p.type;if(A&&T==="item.started"&&p.item&&ee(p.item.type))g(p.item);else if(T==="item.completed"){let d=p.item,Y=d?.type;if(Y==="mcp_tool_call"){I++;let K=`${d.server}/${d.tool}`;if(se.stepTool(`Tool: ${K}`),A)g(d),W(d);else if(d.arguments){let V=JSON.stringify(d.arguments),ae=V.length>100?`${V.substring(0,100)}...`:V;console.log(` Input: ${ae}`)}}else if(ee(Y)){I++;let K=d.name||d.tool||d.command||d.query||"unknown";se.stepTool(`Tool: ${K}`),A&&(g(d),Y==="command_execution"&&W(d))}else if(Y==="agent_message")if(b=d.text||"",A){if(!pt(b)){let K=ze(b.trim(),200);K&&k("turn:narration",{text:K,withTool:!1})}}else b.length<500?console.log(b):console.log(`${b.substring(0,200)}... (${b.length} chars)`)}else if(T==="turn.completed"){c.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(p.usage||{})}`),p.usage&&(G=p.usage);break}else{if(T==="turn.failed")throw new Error(p.error?.message||"Codex turn failed");c.debug(`[Codex] Event: ${T} ${JSON.stringify(p).slice(0,300)}`)}}if(c.debug(`[Codex] Last agent message (${b.length} chars): ${b.slice(0,500)}`),s){if(!b)throw new Error("Codex agent returned no response");let p=JSON.parse(b),T=p;if(v)try{T=s.parse(p)}catch{T=s.parse(yt(p))}c.debug("\u2705 [Codex] Structured output validated");let d=Ke(G);return{raw:b,structured:T,...d?{usage:d}:{}}}return b||""}catch(h){let I=h.message||String(h);throw c.error(`\u274C [Codex] SDK call failed: ${I}`),I.includes("exited with code")&&(w.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 O of M)O.dispose()}}_resolveSkillsToMcp(e,r={}){if(!Array.isArray(e)||e.length===0)return{};let n={};for(let o of e){let s=In(o);if(!s){c.warn(`[Codex] Unknown skill "${o}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let i=s.resolve(r);if(!i)continue;let a=s.serverName||o,l=re("codex",i,{processEnv:process.env});l&&(n[a]=l,c.debug(`[Codex] MCP: ${a} \u2192 ${i.command} ${(i.args||[]).join(" ")}`))}return n}_resolveCodexHome(e){return process.env.CODEX_HOME?process.env.CODEX_HOME:e&&!this._isTempPath(e)?Pe(e,".codex-home"):Pe(kn(),".codex")}_isTempPath(e){let r=String(process.env.TMPDIR||"/tmp").replace(/\/+$/,""),n=String(e||"");return n==="/tmp"||n.startsWith("/tmp/")||n===r||n.startsWith(r+"/")}_resolveCodexBin(){if(process.env.CODEX_BIN)return process.env.CODEX_BIN;try{return He("command -v codex",{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}_ensurePlugins(e,r){let n={...process.env,CODEX_HOME:r};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,n)){c.info(`[Codex][plugins] ${l} already installed \u2014 skipping (idempotent)`),console.log(`\u25C6 [Codex] plugin ${l} already installed \u2014 skip`);continue}let u=this._safeMarketplacePath(i,r);c.info(`[Codex][plugins] installing ${l} from local marketplace ${u}`),console.log(`\u25C6 [Codex] installing plugin ${l} (local, no network)`);try{He(`codex plugin marketplace add ${JSON.stringify(u)}`,{env:n,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),He(`codex plugin add ${JSON.stringify(l)}`,{env:n,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),console.log(`\u25C6 [Codex] plugin ${l} installed`)}catch(f){let m=f.stderr&&f.stderr.toString()||f.message||String(f);throw c.error(`[Codex][plugins] failed to install ${l}: ${m}`),new Error(`Codex plugin install failed for ${l}: ${m}`,{cause:f})}}}_safeMarketplacePath(e,r){if(!String(e).includes("@"))return e;let n=Pe(r,".zibby-mkt",String(e).replace(/[^a-zA-Z0-9]+/g,"_"));try{return gt(Pe(r,".zibby-mkt"),{recursive:!0}),wn(e,n,{recursive:!0}),n}catch(o){return c.warn(`[Codex][plugins] could not copy @-containing marketplace to a safe path: ${o.message}`),e}}_readMarketplaceName(e){let r=Pe(e,".agents","plugins","marketplace.json"),n;try{n=JSON.parse(xn(r,"utf-8"))}catch(o){throw new Error(`Codex plugin marketplace manifest missing/unreadable at ${r}: ${o.message}`,{cause:o})}if(!n?.name||typeof n.name!="string")throw new Error(`Codex plugin marketplace manifest at ${r} has no string "name"`);return n.name}_isPluginInstalled(e,r){try{return He("codex plugin list",{env:r,stdio:"pipe",timeout:15e3,encoding:"utf-8"}).split(`
|
|
95
|
+
`).some(o=>o.includes(e)&&/installed/.test(o))}catch{return!1}}};import{AgentStrategy as Cn,getSkill as Nn}from"@zibby/agent-workflow";import{spawn as Pn}from"node:child_process";$e();import{existsSync as Qt,mkdirSync as er,readFileSync as tr,rmSync as Rn,writeFileSync as rr}from"node:fs";import{join as pe}from"node:path";function Ln(t){if(!t)return null;let e=String(t),r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(r?.[1])try{return JSON.parse(r[1].trim())}catch{}let n=e.indexOf("{");if(n<0)return null;let o=0,s=!1,i=!1,a=-1;for(let l=n;l<e.length;l++){let u=e[l];if(s){i?i=!1:u==="\\"?i=!0:u==='"'&&(s=!1);continue}if(u==='"'){s=!0;continue}if(u==="{"){o===0&&(a=l),o+=1;continue}if(u==="}"){if(o===0)continue;if(o-=1,o===0&&a>=0){let f=e.slice(a,l+1);try{return JSON.parse(f)}catch{a=-1}}}}return null}function Mn(t){let e=String(t||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return Ln(e)}}function Dn(t){try{let e=JSON.parse(t);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 r=e.candidates[0];if(typeof r?.content=="string")return r.content;if(Array.isArray(r?.content?.parts)){let n=r.content.parts.map(o=>typeof o?.text=="string"?o.text:"").join("");if(n.trim())return n}}}catch{}return t}var We=class t extends Cn{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){return!(process.env.GEMINI_API_KEY||process.env.GEMINI_API_KEY_POOL||process.env.GOOGLE_API_KEY||process.env.GOOGLE_API_KEY_POOL)?(c.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1):Ye("gemini")?!0:(c.warn("[Gemini] gemini CLI not on PATH. Install: npm install -g @google/gemini-cli"),!1)}async invoke(e,r={}){r.effort&&!t._effortWarned&&(t._effortWarned=!0,c.warn(`[Gemini] effort "${r.effort}" ignored \u2014 the Gemini CLI exposes no reasoning-effort control.`));let{model:n,workspace:o=process.cwd(),schema:s=null,images:i=[],skills:a=null,sessionPath:l=null,nodeName:u=null,timeout:f=600*1e3,signal:m=null}=r,E=[Q("GEMINI_API_KEY"),Q("GOOGLE_API_KEY")];try{let A=me("gemini",n),R=It[A]||A,M=String(process.env.GEMINI_API_KEY||"").trim(),O=String(process.env.GOOGLE_API_KEY||"").trim(),x=this._resolveSkillsToMcp(a,{sessionPath:l,workspace:o,nodeName:u});for(let C of r.extraMcpServers||[])if(C&&C.serverName&&C.def){if(Object.prototype.hasOwnProperty.call(x,C.serverName)){console.warn(`[custom-mcp] skip "${C.serverName}" \u2014 a built-in skill already owns that MCP name (no shadowing)`);continue}let z=re("gemini",C.def);z&&(x[C.serverName]=z)}let L=Fe("gemini",x,{sessionPath:l,toolWorkingSet:r.toolWorkingSet}),P=Object.keys(L).length>0,_=new ye(e),N=s&&typeof s.parse=="function",$=null;if(s){let C;try{let z=N?fe(s,{target:"openAi"}):s;C=JSON.stringify(z,null,2)}catch{C="{}"}if(P){_.addSystemInstruction(`Write valid JSON that matches this schema:
|
|
96
|
+
${C}`,"schema_instruction","append");let z=`zibby-result-${Date.now()}.json`,q=pe(o,".zibby","tmp");$=pe(q,z),er(q,{recursive:!0}),_.addStructuredOutput(s,$)}else _.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
|
|
97
|
+
${C}`,"json_instruction","append")}let k=_.build(),S=Array.isArray(i)?i.filter(C=>C&&typeof C.path=="string"&&C.path.startsWith("/")):[];S.length&&(k+=`
|
|
98
98
|
|
|
99
99
|
# Attached image files \u2014 VIEW THESE
|
|
100
100
|
The user attached ${S.length} image(s), saved locally. Read each path to SEE the image, then use what it shows to answer:
|
|
101
|
-
${S.map((C,
|
|
102
|
-
`)}`);let U=
|
|
103
|
-
\u25C6 Model: ${R}${
|
|
104
|
-
`);let
|
|
105
|
-
${
|
|
106
|
-
${
|
|
107
|
-
${
|
|
108
|
-
`,"utf-8");let
|
|
109
|
-
`,"utf-8")}catch{}return c.debug(`[Gemini] Created isolated config with ${Object.keys(
|
|
110
|
-
|
|
111
|
-
[truncated for size budget]`}function ht(t,e=0){if(!t||typeof t!="object"||e>8)return t;if(Array.isArray(t))return t.map(
|
|
112
|
-
`);
|
|
113
|
-
`)||"",isError:s.isError||!1}}isRunning(e){return this.#e.has(e)}async stopServer(e){let
|
|
114
|
-
|
|
115
|
-
[tool result truncated for size]`}function
|
|
116
|
-
\u{1F4D6} get_skill_context("${
|
|
117
|
-
`)),
|
|
118
|
-
\u25C6 Model: ${
|
|
119
|
-
`);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",
|
|
120
|
-
|
|
121
|
-
${
|
|
122
|
-
|
|
123
|
-
`)}`)}let
|
|
124
|
-
fields: ${
|
|
101
|
+
${S.map((C,z)=>` ${z+1}. ${C.path}${C.name?` (${C.name})`:""}`).join(`
|
|
102
|
+
`)}`);let U=_.getUserPrompt(),D=_.getStats(),B=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),H=B?` | key: ***${B.slice(-4)}`:" | key: not set";console.log(`
|
|
103
|
+
\u25C6 Model: ${R}${H}
|
|
104
|
+
`);let J=(await import("chalk")).default;console.log(`
|
|
105
|
+
${J.bold("Prompt sent to LLM:")}`),console.log(J.dim("\u2500".repeat(60))),console.log(J.dim(U)),console.log(J.dim("\u2500".repeat(60)));let F=this._createGeminiConfigDir(o,L),v=["--output-format","json"];v.push("--model",R);let w=Object.keys(L);if(w.length>0){v.push("--approval-mode","yolo");for(let C of w)v.push("--allowed-mcp-server-names",C);c.info(`[Gemini] Enabling MCP servers: ${w.join(", ")}`)}else a&&a.length>0&&c.warn(`[Gemini] Skills requested but no MCP servers configured: ${a.join(", ")}`);v.push("-p",k);let y={..._e(process.env),GEMINI_CLI_HOME:F,GEMINI_CLI_TRUST_WORKSPACE:"true"};M?(y.GEMINI_API_KEY=M,delete y.GOOGLE_API_KEY):O&&(y.GOOGLE_API_KEY=O,delete y.GEMINI_API_KEY),c.debug(`[Gemini] Command: gemini ${v.slice(0,8).join(" ")}... (${v.length} total args)`),c.debug(`[Gemini] User prompt: ${D.userPromptLength} chars, System instructions: ${D.systemInstructionsLength} chars (${D.instructionCount} blocks), Full: ${D.fullPromptLength} chars`),c.debug(`[Gemini] Config home: ${F}`),c.debug(`[Gemini] GEMINI_CLI_HOME env: ${y.GEMINI_CLI_HOME}`);let h="",I=null;try{h=await new Promise((z,q)=>{let ee=Pn("gemini",v,{cwd:o,env:y,stdio:["ignore","pipe","pipe"],...m&&{signal:m}}),g="",W="",p=!1,T=null,d=!1,Y=setTimeout(()=>{try{ee.kill("SIGTERM")}catch{}},f),K=()=>{d||p||(d=!0,T=setTimeout(()=>{if(!p)try{ee.kill("SIGKILL")}catch{}},5e3))};m&&(m.aborted?K():m.addEventListener("abort",K,{once:!0})),ee.stdout.on("data",V=>{g+=V.toString()}),ee.stderr.on("data",V=>{W+=V.toString()}),ee.on("error",V=>{if(clearTimeout(Y),T&&clearTimeout(T),m&&!m.aborted)try{m.removeEventListener("abort",K)}catch{}q(V)}),ee.on("close",V=>{if(p=!0,clearTimeout(Y),T&&clearTimeout(T),m&&!m.aborted)try{m.removeEventListener("abort",K)}catch{}if(d){let ae=new Error("Aborted via signal");return ae.name="AbortError",q(ae)}if(V===0)return z(g.trim());q(new Error(`gemini failed with code ${V}: ${(W||g).trim()}`))})})}catch(C){I=C}finally{try{Rn(F,{recursive:!0,force:!0})}catch{}}let b=Dn(h).trim();if(!s){if(I)throw I;return b}if($){let C=Qt($);if(c.info(`[Gemini] Result file: ${C?"present":"missing"} at ${$}`),C)try{let z=tr($,"utf-8").trim(),q=JSON.parse(z),ee=N?s.parse(q):q;return c.info("[Gemini] Structured output recovered from result file"),{raw:b,structured:ee}}catch(z){c.warn(`[Gemini] Result file parse/validation failed: ${z.message}`)}else I||c.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let G=null;if(s){let C=new ge;C.zodSchema=s,C.processChunk(b),C.flush(),G=C.getResult()}if(c.info(`[Gemini] Raw stdout length: ${h.length} chars`),c.info(`[Gemini] Extracted text length: ${b.length} chars`),c.info(`[Gemini] StreamParser result: ${G?"extracted":"null"}`),G||(b.length<2e3?c.info(`[Gemini] Raw text preview:
|
|
106
|
+
${b}`):c.info(`[Gemini] Raw text preview (first 1000 chars):
|
|
107
|
+
${b.slice(0,1e3)}`),G=Mn(b)),!G)throw I||(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 j=N?s.parse(G):G;return{raw:b,structured:j}}finally{for(let A of E)A.dispose()}}_resolveSkillsToMcp(e,r={}){if(!Array.isArray(e)||e.length===0)return{};let n={};for(let o of e){let s=Nn(o);if(!s||typeof s.resolve!="function")continue;let i=s.resolve(r);if(!i)continue;let a=s.cursorKey||s.serverName||o,l=re("gemini",i);l&&(n[a]=l)}return n}_createGeminiConfigDir(e,r){let n=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,o=pe(e||process.cwd(),".zibby","tmp",`gemini-home-${n}`),s=pe(o,".gemini");er(s,{recursive:!0});let i=pe(s,"settings.json"),a={},l=pe(process.env.HOME||"",".gemini","settings.json");if(Qt(l))try{a=JSON.parse(tr(l,"utf-8"))}catch{a={}}let u={...a,mcpServers:{...a.mcpServers&&typeof a.mcpServers=="object"?a.mcpServers:{},...r||{}}};rr(i,`${JSON.stringify(u,null,2)}
|
|
108
|
+
`,"utf-8");let f=pe(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{rr(f,`${JSON.stringify(u,null,2)}
|
|
109
|
+
`,"utf-8")}catch{}return c.debug(`[Gemini] Created isolated config with ${Object.keys(u.mcpServers||{}).length} MCP servers`),c.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(u.mcpServers||{}),null,2)}`),o}};import{AgentStrategy as Vn,getSkill as tt}from"@zibby/agent-workflow";var Re=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,r){throw new Error("buildToolResultMessage() must be implemented")}injectToolsIntoBody(e,r){throw new Error("injectToolsIntoBody() must be implemented")}};var Ae=class extends Re{formatTools(e){return e.map(r=>({type:"function",function:{name:r.name,description:r.description,parameters:r.parameters||r.input_schema||{type:"object",properties:{}}}}))}hasToolCalls(e){let r=e.choices?.[0]?.message;return!!(r?.tool_calls&&r.tool_calls.length>0)}parseToolCalls(e){return(e.choices?.[0]?.message?.tool_calls||[]).map(n=>({id:n.id,name:n.function.name,args:JSON.parse(n.function.arguments||"{}")}))}getTextContent(e){return e.choices?.[0]?.message?.content||""}buildAssistantMessage(e){return e.choices?.[0]?.message}buildToolResultMessage(e,r){return{role:"tool",tool_call_id:e,content:typeof r=="string"?r:JSON.stringify(r)}}injectToolsIntoBody(e,r){return r.length>0&&(e.tools=r),e}};var Le=class{async fetchCompletion(e,r,n={}){throw new Error("fetchCompletion() must be implemented")}async fetchStreamingCompletion(e,r,n={}){throw new Error("fetchStreamingCompletion() must be implemented")}};function Ve(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function qe(t,e){let r=String(t||"");if(r.length<=e)return r;let n=Math.max(0,e-28);return`${r.slice(0,n)}
|
|
110
|
+
|
|
111
|
+
[truncated for size budget]`}function ht(t,e=0){if(!t||typeof t!="object"||e>8)return t;if(Array.isArray(t))return t.map(n=>ht(n,e+1));let r={};for(let[n,o]of Object.entries(t))n==="description"||n==="title"||n==="examples"||n==="default"||(r[n]=ht(o,e+1));return r}function Un(t=[]){return t.map(e=>({...e,function:{...e.function,description:qe(e.function?.description||"",180),parameters:ht(e.function?.parameters||{type:"object",properties:{}})}}))}function nr(t){let e=new Set;for(let o of t)if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let s of o.tool_calls)e.add(s.id);let r=t.filter(o=>o.role==="tool"?e.has(o.tool_call_id):!0),n=new Set;for(let o of r)o.role==="tool"&&n.add(o.tool_call_id);return r.map(o=>{if(o.role!=="assistant"||!Array.isArray(o.tool_calls)||o.tool_calls.every(l=>n.has(l.id)))return o;let{tool_calls:i,...a}=o;return{...a,content:a.content||""}})}function _t(t,e={}){let r=e.maxBytes||49e3,n=e.systemMaxChars||12e3,o={...t,messages:Array.isArray(t.messages)?[...t.messages]:[],tools:Array.isArray(t.tools)?Un(t.tools):t.tools};o.messages.length>0&&o.messages[0]?.role==="system"&&(o.messages[0]={...o.messages[0],content:qe(o.messages[0].content,n)});let s=!1;for(;Ve(o)>r&&o.messages.length>2;)o.messages.splice(1,1),s=!0;if(s&&(o.messages=nr(o.messages)),Ve(o)>r&&o.messages.length>0&&(o.messages[0]={...o.messages[0],content:qe(o.messages[0].content,6e3)},s=!0),Ve(o)>r){let i=o.messages.find(l=>l.role==="system")||o.messages[0],a=o.messages.slice(-2);o.messages=nr([i,...a].filter(Boolean).map((l,u)=>({...l,content:qe(l.content,u===0?4e3:8e3)}))),s=!0}return{body:o,meta:{bytes:Ve(o),trimmed:s,maxBytes:r,messageCount:o.messages.length}}}var or=t=>Buffer.byteLength(JSON.stringify(t),"utf8"),Se=class extends Le{async fetchCompletion(e,r,n={}){let o=or(e),{body:s,meta:i}=_t(e,n.payloadCompaction);n.onBudget?.({streaming:!1,beforeBytes:o,meta:i});let a=this.#e(n),l=`${r.baseUrl}${n.chatCompletionsPath||"/v1/chat/completions"}`,u=await fetch(l,{method:"POST",headers:r.headers,body:JSON.stringify(s),signal:a});if(!u.ok){let f=await u.text();throw u.status===401||u.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${u.status}: ${f}`)}return u.json()}async fetchStreamingCompletion(e,r,n={}){let o={...e,stream:!0},s=or(o),{body:i,meta:a}=_t(o,n.payloadCompaction);n.onBudget?.({streaming:!0,beforeBytes:s,meta:a});let l=this.#e(n),u=`${r.baseUrl}${n.chatCompletionsPath||"/v1/chat/completions"}`,f=await fetch(u,{method:"POST",headers:r.headers,body:JSON.stringify(i),signal:l});if(!f.ok){let O=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}: ${O}`)}let m=f.body.getReader(),E=new TextDecoder,A="",R="",M=new Map;for(;;){let{done:O,value:x}=await m.read();if(O)break;A+=E.decode(x,{stream:!0});let L=A.split(`
|
|
112
|
+
`);A=L.pop();for(let P of L){if(!P.startsWith("data: "))continue;let _=P.slice(6).trim();if(_==="[DONE]")continue;let N;try{N=JSON.parse(_)}catch{continue}let $=N.choices?.[0]?.delta;if($&&($.content&&(R+=$.content,n.onToken&&n.onToken($.content)),$.tool_calls))for(let k of $.tool_calls){let S=k.index??0;M.has(S)||M.set(S,{id:"",name:"",args:""});let U=M.get(S);k.id&&(U.id=k.id),k.function?.name&&(U.name=k.function.name),k.function?.arguments!=null&&(U.args+=k.function.arguments)}}}if(M.size>0){let O=[...M.entries()].sort(([x],[L])=>x-L).map(([,x])=>({id:x.id,type:"function",function:{name:x.name,arguments:x.args}}));return{choices:[{message:{role:"assistant",content:R||null,tool_calls:O}}]}}return{choices:[{message:{role:"assistant",content:R}}]}}#e(e={}){let r=[e.signal,e.timeout?AbortSignal.timeout(e.timeout):null].filter(Boolean);return r.length>1?AbortSignal.any(r):r[0]||void 0}};import{Client as Bn}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as jn}from"@modelcontextprotocol/sdk/client/stdio.js";var Xe=class{#e=new Map;async ensureServer(e,r){if(this.#e.has(e))return this.#e.get(e);let{command:n,args:o=[],env:s={}}=r;c.debug(`[MCP] Starting ${e}: ${n} ${o.join(" ")}`);let i=new jn({command:n,args:o,env:{...process.env,...s}}),a=new Bn({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await a.connect(i);let l={client:a,transport:i,serverConfig:r};return this.#e.set(e,l),l}async callTool(e,r,n={}){let o=this.#e.get(e);if(!o)throw new Error(`MCP server "${e}" not running`);c.debug(`[MCP] ${e}.${r}(${JSON.stringify(n).slice(0,200)})`);let s=await o.client.callTool({name:r,arguments:n});return{text:s.content?.filter(a=>a.type==="text").map(a=>a.text).join(`
|
|
113
|
+
`)||"",isError:s.isError||!1}}isRunning(e){return this.#e.has(e)}async stopServer(e){let r=this.#e.get(e);if(r){try{await r.client.close()}catch(n){c.debug(`[MCP] Error closing ${e}: ${n.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(r=>this.stopServer(r)))}};import{existsSync as Kn,readFileSync as Gn}from"node:fs";import{join as Jn}from"node:path";import{homedir as zn}from"node:os";function Fn(){try{let t=Jn(zn(),".zibby","config.json");return Kn(t)?JSON.parse(Gn(t,"utf-8")):{}}catch{return{}}}function Qe(t){return String(t||"").replace(/\/v1\/?$/,"")}function Yn(t,e){let r=process.env.OPENAI_PROXY_URL;if(r)return Qe(r);if(t==="session")return e.proxyUrl?Qe(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(t==="byok"){let n=process.env.OPENAI_BASE_URL;return Qe(n||"https://api.openai.com")}return Qe(r||"")}function Et(){let t=Fn(),e=process.env.ZIBBY_USER_TOKEN||t.sessionToken||null,r=process.env.OPENAI_API_KEY||null,n=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),o=process.env.OPENAI_PROXY_NO_AUTH==="true",s=process.env.OPENAI_PROXY_URL,i="session";n==="byok"||n==="local"||n==="session"?i=n:e?i="session":r?i="byok":s&&o&&(i="local");let a=Yn(i,t),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(!r)return{ok:!1,mode:i,reason:"missing_openai_api_key"};l.Authorization=`Bearer ${r}`}else if(i==="local"){if(!a)return{ok:!1,mode:i,reason:"missing_openai_proxy_url"};!o&&r&&(l.Authorization=`Bearer ${r}`)}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 et(t,e){let r=String(t??"");return r.length<=e?r:`${r.slice(0,Math.max(0,e-30))}
|
|
114
|
+
|
|
115
|
+
[tool result truncated for size]`}function Hn(t,e){if(typeof t=="string")return et(t,e);try{return et(JSON.stringify(t),e)}catch{return et(String(t),e)}}function sr(t){let e=new Set;for(let o of t)if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let s of o.tool_calls)e.add(s.id);let r=t.filter(o=>o.role==="tool"?e.has(o.tool_call_id):!0),n=new Set;for(let o of r)o.role==="tool"&&n.add(o.tool_call_id);return r.map(o=>{if(o.role!=="assistant"||!Array.isArray(o.tool_calls)||o.tool_calls.every(l=>n.has(l.id)))return o;let{tool_calls:i,...a}=o;return{...a,content:a.content||""}})}function Zn(t){let e=Array.isArray(t?.messages)?t.messages:[],r=e.find(s=>s.role==="system"),n=e.slice(-4).map(s=>({...s,content:et(s.content,s.role==="tool"?1200:2500)}));n=sr(n);let o={...t,messages:[r,...n].filter(Boolean)};return delete o.tools,o}async function Wn({body:t,streaming:e,auth:r,options:n,fetchCompletion:o,fetchStreamingCompletion:s,onFallbackLog:i}){try{return e?await s(t,r,n):await o(t,r,n)}catch(a){let l=String(a?.message||a||"");if(!/proxy error 413|payload too large/i.test(l))throw a;let u=Zn(t);return typeof i=="function"&&i(t,u),{data:e?await s(u,r,n):await o(u,r,n),fallback:u}}}async function ir({body:t,auth:e,options:r,streaming:n,toolContext:o,activeSkills:s,round:i,verbose:a,dependencies:l,config:u={}}){let f=u.maxToolResultChars||3e3,{fetchCompletion:m,fetchStreamingCompletion:E,onFallbackLog:A,hasToolCalls:R,getTextContent:M,parseToolCalls:O,buildAssistantMessage:x,buildToolResultMessage:L,executeTool:P,onToolCallLog:_,injectTools:N}=l;Array.isArray(t?.messages)&&(t.messages=sr(t.messages));let $=await Wn({body:t,streaming:n,auth:e,options:r,fetchCompletion:m,fetchStreamingCompletion:E,onFallbackLog:A}),k=$?.data||$;if(!R(k))return{done:!0,text:M(k),body:$?.fallback||t};let S=O(k),U=$?.fallback||t;U.messages.push(x(k)),a&&typeof _=="function"&&_(S);let D=await Promise.all(S.map((B,H)=>(typeof r.onToolCall=="function"&&r.onToolCall(B.name,B.args,{round:i,index:H,total:S.length}),P(B,o))));for(let B=0;B<S.length;B++){let J=S[B].name==="get_skill_context"?typeof D[B]=="string"?D[B]:JSON.stringify(D[B]):Hn(D[B],f);U.messages.push(L(S[B].id,J))}return typeof r.onToolCall=="function"&&r.onToolCall(null),N(U,s),{done:!1,body:U}}var qn=ce.ASSISTANT,Xn=15,bt="get_skill_context";function Te(t){!t||typeof t!="object"||(t.type==="object"&&t.properties&&(t.required=Object.keys(t.properties),t.additionalProperties=!1,Object.values(t.properties).forEach(Te)),t.type==="array"&&t.items&&Te(t.items),t.anyOf&&t.anyOf.forEach(Te),t.oneOf&&t.oneOf.forEach(Te),t.allOf&&t.allOf.forEach(Te))}var ar={maxBytes:49e3,systemMaxChars:12e3},Oe=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Qn=t=>Buffer.byteLength(JSON.stringify(t),"utf8");function rt(t){return Array.isArray(t)?new Set(t.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function eo(t){return Array.isArray(t)?t.map(e=>String(e||"").trim()).filter(Boolean):[]}var nt=class extends Vn{#e;#t;#r=new Xe;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new Ae,this.#t=e.completionProvider||new Se):(this.#e=e||new Ae,this.#t=new Se)}canHandle(e){return Et().ok}async invoke(e,r={}){let n=Q("OPENAI_API_KEY");try{let o=r.model||qn,s=Et();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=r.messages||[{role:"user",content:e}],a=s.baseUrl,l=Oe();if(l?await this.#m(i,o,a,s.tokenPreview||"none"):c.debug(`[Assistant] ${a} | model: ${o} | messages: ${i.length}`),r.schema)return this.#c(o,i,s,r);let u=r.activeSkills||[],f=this.#f(r),m=this.#d(u,f),E=this.#p(m),A=this.#u(r),R={...r,payloadCompaction:A},M={activeSkills:m,options:R,executionRegistry:E,capabilityPolicy:f},O=!!r.stream,x={model:o,messages:[...i],stream:!1};this.#o(x,m,f);for(let L=0;L<Xn;L++){if(r.signal?.aborted){let _=new Error("Aborted via signal");throw _.name="AbortError",_}let P=await ir({body:x,auth:s,options:R,streaming:O,toolContext:M,activeSkills:m,round:L,verbose:l,dependencies:{fetchCompletion:this.#s.bind(this),fetchStreamingCompletion:this.#l.bind(this),onFallbackLog:(_,N)=>{Oe()&&console.log(`413 fallback: messages ${_.messages.length} -> ${N.messages.length}, bytes=${Qn(N)}`)},hasToolCalls:_=>this.#e.hasToolCalls(_),getTextContent:_=>this.#e.getTextContent(_),parseToolCalls:_=>this.#e.parseToolCalls(_),buildAssistantMessage:_=>this.#e.buildAssistantMessage(_),buildToolResultMessage:(_,N)=>this.#e.buildToolResultMessage(_,N),executeTool:(_,N)=>this.#a(_,N),onToolCallLog:async _=>{let N=(await import("chalk")).default;console.log(N.dim(` ${_.map($=>`${$.name}(${JSON.stringify($.args).slice(0,80)})`).join(", ")}`))},injectTools:(_,N)=>this.#o(_,N,f)},config:{maxToolResultChars:r.maxToolResultChars||3e3}});if(P.done)return P.text;x.messages=P.body.messages,P.body.tools?x.tools=P.body.tools:delete x.tools}return"I hit my tool-calling limit for this turn. Please try again."}finally{n.dispose()}}async cleanup(){await this.#r.stopAll()}#o(e,r,n=null){let o=this.#i(r,n),s=this.#e.formatTools(o);this.#e.injectToolsIntoBody(e,s)}#i(e,r=null){let n=[],o=new Set;for(let s of e){let i=tt(s);if(i?.tools?.length)for(let a of i.tools)this.#n(a.name,r)&&(o.has(a.name)||(o.add(a.name),n.push({name:a.name,description:a.description,parameters:a.parameters||a.input_schema||{type:"object",properties:{}}})))}return!r?.disableSkillContextTool&&this.#n(bt,r)&&n.push({name:bt,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),n}async#a(e,r){let{activeSkills:n,options:o,executionRegistry:s,capabilityPolicy:i}=r;if(!this.#n(e.name,i))return`Tool "${e.name}" blocked by policy`;if(e.name===bt){let u=String(e.args?.skillId||"").trim();if(!u)return JSON.stringify({error:"skillId is required"});if(!n.includes(u))return JSON.stringify({error:`Skill "${u}" is not active`,activeSkills:n});let f=tt(u);if(!f)return JSON.stringify({error:`Skill "${u}" not found`});let m=typeof f.promptFragment=="function"?f.promptFragment():f.promptFragment||"",E=(f.tools||[]).map(R=>R.name),A=JSON.stringify({skillId:u,description:f.description||"",toolNames:E,promptFragment:m||""});return Oe()&&(console.log(`
|
|
116
|
+
\u{1F4D6} get_skill_context("${u}") \u2192 ${A.length} chars (fragment: ${m.length} chars)`),console.log(` tools: [${E.join(", ")}]`),console.log(` fragment preview: ${m.slice(0,200).replace(/\n/g,"\\n")}\u2026
|
|
117
|
+
`)),A}let a=s?.get(e.name)||null;if(!a)return`Unknown tool: ${e.name}`;let l=tt(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,r)}catch(u){return`Error in ${e.name}: ${u.message}`}if(a.mode==="mcp")try{if(!this.#r.isRunning(l.serverName)){let f=l.resolve(o);if(!f)return`Skill "${a.skillId}" is not available (cannot start server)`;await this.#r.ensureServer(l.serverName,f)}let u=await this.#r.callTool(l.serverName,e.name,e.args);return u.text||(u.isError?"Tool call failed":"Done")}catch(u){return`MCP error (${l.serverName}): ${u.message}`}return`Skill "${a.skillId}" owns tool "${e.name}" but has no execution mode`}async#l(e,r,n){return this.#t.fetchStreamingCompletion(e,r,{...n,onBudget:({beforeBytes:o,meta:s})=>{Oe()&&console.log(`payload bytes (stream) before=${o} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#s(e,r,n){return this.#t.fetchCompletion(e,r,{...n,onBudget:({beforeBytes:o,meta:s})=>{Oe()&&console.log(`payload bytes before=${o} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#c(e,r,n,o){let{zodToJson:s}=await Promise.resolve().then(()=>($e(),Jt)),i=typeof o.schema?.parse=="function",a=i?s(o.schema,{}):o.schema;delete a.$schema,Te(a);let l={model:e,messages:r,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:a,strict:!0}}},u=await this.#s(l,n,o),f=this.#e.getTextContent(u),m=JSON.parse(f),E=i?o.schema.parse(m):m;return{raw:f,structured:E}}#u(e={}){let r=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(r.maxBytes||e.maxPayloadBytes||ar.maxBytes),systemMaxChars:Number(r.systemMaxChars||ar.systemMaxChars)}}#f(e={}){let r=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:rt(r.allowTools||e.allowTools),denyTools:rt(r.denyTools||e.denyTools),denyPrefixes:eo(r.denyPrefixes||e.denyToolPrefixes),includeSkills:rt(r.includeSkills||e.includeSkills),excludeSkills:rt(r.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(r.disableSkillContextTool||e.disableSkillContextTool)}}#d(e,r){let n=r?.includeSkills||new Set,o=r?.excludeSkills||new Set;return n.size===0&&o.size===0?e:e.filter(s=>!(n.size>0&&!n.has(s)||o.has(s)))}#n(e,r){let n=String(e||"").trim();if(!n)return!1;let o=r?.allowTools;if(o&&o.size>0&&!o.has(n))return!1;let s=r?.denyTools;return!(s&&s.has(n)||(r?.denyPrefixes||[]).some(a=>n.startsWith(a)))}#p(e){let r=new Map,n=[];for(let o of e){let s=tt(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(r.has(l)){n.push({tool:l,winner:r.get(l).skillId,skipped:o});continue}r.set(l,{skillId:o,mode:i})}}}if(n.length>0&&Oe()){let o=n.slice(0,5).map(s=>`${s.tool}:${s.winner}>${s.skipped}`).join(", ");console.log(`tool registry collisions: ${o}${n.length>5?" ...":""}`)}return r}async#m(e,r,n,o){console.log(`
|
|
118
|
+
\u25C6 Model: ${r} | proxy: ${n} | token: ${o||"none"}
|
|
119
|
+
`);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",u=a.content?.length>200?`${a.content.slice(0,200)}...`:a.content||"";console.log(s.dim(`[${l}] ${u}`))}console.log(s.dim("\u2500".repeat(60)))}};import{AgentStrategy as da}from"@zibby/agent-workflow";var Er=[new nt,new Je,new Ze,new We];function mo(t={}){let{state:e={},preferredAgent:r=null}=t,n=r||e.agentType||process.env.AGENT_TYPE;if(!n)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");c.debug(`Agent selection: requested=${n}`);let o=Er.find(s=>s.getName()===n);if(!o)throw new Error(`Unknown agent '${n}'. Available: ${Er.map(s=>s.getName()).join(", ")}`);if(c.debug(`Checking if ${n} can handle this environment...`),!o.canHandle(t)){let i={assistant:"Run `zibby login` to authenticate",claude:"Set ANTHROPIC_API_KEY in .env",cursor:"Install cursor-agent CLI or set CURSOR_API_KEY",codex:"Install codex CLI (npm i -g @openai/codex) and set OPENAI_API_KEY in .env",gemini:"Install gemini CLI (npm i -g @google/gemini-cli) and set GEMINI_API_KEY in .env"}[n]||"Check your environment configuration";throw new Error(`Agent '${n}' is not available. ${i}`)}return c.debug(`Using agent: ${o.getName()}`),o}async function ca(t,e={},r={}){try{await import("@zibby/skills")}catch{}try{await import("@zibby/skills-internal")}catch{}let n=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},o={...e,state:n},s=mo(o),i=n.config||r.config||{},a=n._currentNodeConfig||{},l=typeof a.agent=="string"?a.agent.trim():"",u=!l||l===s.name?a.model:null,f=uo({config:i,options:r,strategyName:s.name,envModel:process.env.MODEL,nodeConfigModel:u}),m=!l||l===s.name?a.effort:null,E=po({options:r,envEffort:process.env.EFFORT,nodeConfigEffort:m}),A={...r,model:f,...E?{effort:E}:{},...fo({options:r,stateView:n,context:e}),config:i},R=A.skills||[],M=t;if(R.length>0&&!r.skipPromptFragments){let{getSkill:L}=await import("@zibby/agent-workflow"),P=null;try{let{getConnectedIntegrations:$}=await Promise.resolve().then(()=>(_r(),hr));P=await $()}catch{P=null}let _=$=>{let k=$&&$.requiresIntegration;return!k||!P?!0:(Array.isArray(k)?k:[k]).some(U=>P[U]===!0)},N=R.map($=>{let k=L($);if(!_(k))return null;let S=k?.promptFragment;return typeof S=="function"?S():S}).filter(Boolean);N.length>0&&(M+=`
|
|
120
|
+
|
|
121
|
+
${N.join(`
|
|
122
|
+
|
|
123
|
+
`)}`)}let O=n._currentNodeConfig?.stores;if(Array.isArray(O)&&O.length>0&&typeof O[0]=="object"){let L=O.length<=8,P=O.map(_=>{let N=_?.id??_?.storeId??"",$=_?.name??N,k=_?.type?` \xB7 ${_.type}`:"",S=(_?.description||"").toString().replace(/\s+/g," ").trim(),U=`- ${$} \xB7 ${S||"(no description)"}${k}${N?` (id: ${N})`:""}`;if(L&&_?.schema&&typeof _.schema=="object"){let D=_.schema.properties&&typeof _.schema.properties=="object"?Object.keys(_.schema.properties):Object.keys(_.schema);D.length&&(U+=`
|
|
124
|
+
fields: ${D.join(", ")}`)}return U});M+=`
|
|
125
125
|
|
|
126
126
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
127
127
|
${P.join(`
|
|
128
|
-
`)}`}let
|
|
128
|
+
`)}`}let x=n._currentNodeConfig?.extraPromptInstructions?.trim();return x&&(M+=`
|
|
129
129
|
|
|
130
130
|
\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
|
|
131
131
|
\u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
132
132
|
\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
|
|
133
133
|
|
|
134
|
-
${
|
|
135
|
-
`),c.debug(`Prompt length: ${
|
|
136
|
-
${
|
|
134
|
+
${x}
|
|
135
|
+
`),c.debug(`Prompt length: ${M.length} chars`),process.env.STAGE!=="prod"&&c.debug(`Full prompt:
|
|
136
|
+
${M}`),s.invoke(M,A)}export{da as AgentStrategy,nt as AssistantStrategy,Je as ClaudeAgentStrategy,Ze as CodexAgentStrategy,ut as CursorAgentStrategy,We as GeminiAgentStrategy,mo as getAgentStrategy,ca as invokeAgent};
|