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