@zibby/core 0.5.25 → 0.5.26
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 +34 -34
- package/dist/package.json +2 -2
- package/dist/register-built-in-strategies.js +26 -26
- package/dist/strategies/claude-strategy.js +2 -2
- package/dist/strategies/index.js +28 -28
- package/package.json +2 -2
package/dist/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zibby/core",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.26",
|
|
4
4
|
"description": "Core test automation engine with multi-agent and multi-MCP support",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -70,7 +70,7 @@
|
|
|
70
70
|
"@playwright/mcp": "^0.0.70",
|
|
71
71
|
"@zibby/agent-workflow": "^0.4.13",
|
|
72
72
|
"@zibby/mcp-browser": "^0.1.8",
|
|
73
|
-
"@zibby/skill-ids": "^0.
|
|
73
|
+
"@zibby/skill-ids": "^0.2.0",
|
|
74
74
|
"acorn": "^8.15.0",
|
|
75
75
|
"acorn-walk": "^8.3.5",
|
|
76
76
|
"axios": "^1.15.0",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
1
|
+
var $t=Object.defineProperty;var Ct=(n,e)=>()=>(n&&(e=n(n=0)),e);var kt=(n,e)=>{for(var t in e)$t(n,t,{get:e[t],enumerable:!0})};var mt={};kt(mt,{zodToJson:()=>Q});import{z as pt}from"zod";import{zodToJsonSchema as so}from"zod-to-json-schema";function io(n){if(!n||typeof n!="object")return n;if(Array.isArray(n.type))return n.type.includes("null")||(n.type=[...n.type,"null"]),n;if(typeof n.type=="string")return n.type=[n.type,"null"],n;for(let e of["anyOf","oneOf"])if(Array.isArray(n[e]))return n[e].some(t=>t&&t.type==="null")||(n[e]=[...n[e],{type:"null"}]),n;return{anyOf:[n,{type:"null"}]}}function ne(n){if(!n||typeof n!="object")return n;for(let e of["$defs","definitions"])if(n[e]&&typeof n[e]=="object")for(let t of Object.keys(n[e]))n[e][t]=ne(n[e][t]);for(let e of["anyOf","oneOf","allOf"])Array.isArray(n[e])&&(n[e]=n[e].map(ne));if(n.properties&&typeof n.properties=="object"){n.additionalProperties=!1;let e=Object.keys(n.properties),t=new Set(Array.isArray(n.required)?n.required:[]);for(let r of e){let o=ne(n.properties[r]);t.has(r)||(o=io(o)),n.properties[r]=o}n.required=e}return n.items&&(Array.isArray(n.items)?n.items=n.items.map(ne):n.items=ne(n.items)),n}function Q(n,e={target:"openApi3"}){if(!n)return null;let t=e?.target==="openAi",r=null;if(typeof pt?.toJSONSchema=="function")try{r=pt.toJSONSchema(n)}catch{}if(!r)try{r=so(n,e)}catch{return null}if(t&&r)try{return ne(r)}catch{return r}return r}var ge=Ct(()=>{});import{registerStrategy as be}from"@zibby/agent-workflow";import{AgentStrategy as Zt,DEFAULT_OUTPUT_BASE as qt,SESSION_INFO_FILE as Qt,STOP_REQUEST_FILE as eo,getAllSkills as to,getSkill as lt}from"@zibby/agent-workflow";import{spawn as oo,execSync as q}from"node:child_process";import{writeFileSync as at,readFileSync as ct,mkdirSync as ut,existsSync as pe,accessSync as ft,constants as dt,unlinkSync as ro}from"node:fs";import{join as H,resolve as no}from"node:path";import{homedir as me}from"node:os";import de from"chalk";var X={debug:0,info:1,warn:2,error:3,silent:4},Je=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return X.debug;if(process.env.ZIBBY_VERBOSE==="true")return X.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in X?X[e]:X.info}_shouldLog(e){return X[e]>=this._level}_formatMessage(e,t,r={}){let o=new Date().toISOString(),i=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(i+=de.dim(` ${JSON.stringify(r)}`)),i}_getPrefix(e){return{debug:de.gray("[DEBUG]"),info:de.cyan("[INFO]"),warn:de.yellow("[WARN]"),error:de.red("\u274C [ERROR]")}[e]||""}debug(e,t){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,t))}info(e,t){this._shouldLog("info")&&console.log(this._formatMessage("info",e,t))}warn(e,t){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,t))}error(e,t){this._shouldLog("error")&&console.error(this._formatMessage("error",e,t))}setLevel(e){e in X&&(this._level=X[e])}getLevel(){return Object.keys(X).find(e=>X[e]===this._level)}},l=new Je;var Pt=[{alias:"auto",canonicalId:"claude-sonnet-4-6",vendor:"claude",label:"Claude \xB7 Sonnet 4.6",family:"claude-sonnet-4",pickerVisible:!0,isDefault:!0},{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:"sonnet-4.8",canonicalId:"claude-sonnet-4-8",vendor:"claude",label:"Claude \xB7 Sonnet 4.8",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-8",canonicalId:"claude-sonnet-4-8",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-7",vendor:"claude",label:"Claude \xB7 Sonnet 4.7",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-7",canonicalId:"claude-sonnet-4-7",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.7"},{alias:"sonnet-4.6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"auto"},{alias:"sonnet-4-6",canonicalId:"claude-sonnet-4-6",vendor:"claude",family:"claude-sonnet-4",aliasOf:"auto"},{alias:"opus-4.6",canonicalId:"claude-opus-4-6",vendor:"claude",label:"Claude \xB7 Opus 4.6",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-6",canonicalId:"claude-opus-4-6",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.6"},{alias:"sonnet-4.5",canonicalId:"claude-sonnet-4-5-20250929",vendor:"claude",label:"Claude \xB7 Sonnet 4.5",family:"claude-sonnet-4",pickerVisible:!0},{alias:"sonnet-4-5",canonicalId:"claude-sonnet-4-5-20250929",vendor:"claude",family:"claude-sonnet-4",aliasOf:"sonnet-4.5"},{alias:"opus-4.5",canonicalId:"claude-opus-4-5-20251101",vendor:"claude",label:"Claude \xB7 Opus 4.5",family:"claude-opus-4",pickerVisible:!0},{alias:"opus-4-5",canonicalId:"claude-opus-4-5-20251101",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.5"},{alias:"haiku-4.5",canonicalId:"claude-haiku-4-5-20251001",vendor:"claude",label:"Claude \xB7 Haiku 4.5",family:"claude-haiku-4"},{alias:"haiku-4-5",canonicalId:"claude-haiku-4-5-20251001",vendor:"claude",family:"claude-haiku-4",aliasOf:"haiku-4.5"},{alias:"claude-opus-4-8",canonicalId:"claude-opus-4-8",vendor:"claude",family:"claude-opus-4",aliasOf:"opus-4.8"},{alias:"claude-sonnet-4-8",canonicalId:"claude-sonnet-4-8",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-7",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:"auto"},{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:"auto",canonicalId:"o4-mini",vendor:"codex",label:"Codex \xB7 o4-mini",family:"o4-mini",isDefault:!0},{alias:"o4-mini",canonicalId:"o4-mini",vendor:"codex",label:"Codex \xB7 o4-mini",family:"o4-mini",pickerVisible:!0},{alias:"o3",canonicalId:"o3",vendor:"codex",family:"o3"},{alias:"o3-mini",canonicalId:"o3-mini",vendor:"codex",family:"o3-mini"},{alias:"codex-mini",canonicalId:"codex-mini-latest",vendor:"codex",family:"codex-mini"},{alias:"gpt-4o",canonicalId:"gpt-4o",vendor:"codex",label:"Codex \xB7 GPT-4o",family:"gpt-4o",pickerVisible:!0},{alias:"gpt-4o-mini",canonicalId:"gpt-4o-mini",vendor:"codex",label:"Codex \xB7 GPT-4o mini",family:"gpt-4o-mini",pickerVisible:!0},{alias:"gpt-5.2-codex",canonicalId:"gpt-5.2-codex",vendor:"codex",label:"Codex \xB7 GPT-5.2",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.2",canonicalId:"gpt-5.2",vendor:"codex",label:"Codex \xB7 GPT-5.2 base",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.3",canonicalId:"gpt-5.3",vendor:"codex",label:"Codex \xB7 GPT-5.3",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.3-codex",canonicalId:"gpt-5.3-codex",vendor:"codex",family:"gpt-5"},{alias:"gpt-5.4",canonicalId:"gpt-5.4",vendor:"codex",label:"Codex \xB7 GPT-5.4",family:"gpt-5",pickerVisible:!0},{alias:"gpt-5.5",canonicalId:"gpt-5.5",vendor:"codex",label:"Codex \xB7 GPT-5.5",family:"gpt-5",pickerVisible:!0},{alias:"auto",canonicalId:"gemini-3-pro",vendor:"gemini",label:"Gemini \xB7 3 Pro",family:"gemini-3",isDefault:!0},{alias:"gemini-3-pro",canonicalId:"gemini-3-pro",vendor:"gemini",label:"Gemini \xB7 3 Pro",family:"gemini-3",pickerVisible:!0},{alias:"gemini-3-flash",canonicalId:"gemini-3-flash",vendor:"gemini",label:"Gemini \xB7 3 Flash",family:"gemini-3",pickerVisible:!0},{alias:"gemini-2.5-pro",canonicalId:"gemini-2.5-pro",vendor:"gemini",label:"Gemini \xB7 2.5 Pro",family:"gemini-2.5",pickerVisible:!0},{alias:"gemini-2.5-flash",canonicalId:"gemini-2.5-flash",vendor:"gemini",label:"Gemini \xB7 2.5 Flash",family:"gemini-2.5",pickerVisible:!0}];function Ae(n){let e={};for(let t of Pt)t.vendor===n&&(e[t.alias]=t.canonicalId);return e}var F={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 Ke=Ae("claude"),Ge=Ae("codex"),et=Ae("gemini"),ve={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var te=class n{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(e){if(!e)return null;this.buffer+=e;let t=this.buffer.split(`
|
|
2
2
|
`);this.buffer=t.pop()||"";let r="";for(let o of t)if(o.trim())try{let 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*"([^"]*)/),c=i?i[1]:a?a[1]:null;c&&!this.rawText.includes(c)&&(r+=c,this.rawText+=c)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(i,a)=>{if(!i)return;let c=`${i}:${JSON.stringify(a??{})}`;this._lastToolEmit!==c&&(this._lastToolEmit=c,this.onToolCall(i,a??void 0))},r=i=>{if(i!=null){if(typeof i=="object"&&!Array.isArray(i))return i;if(typeof i=="string")try{return JSON.parse(i)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,r(e.input??e.arguments));return}let i=e.tool_call;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=Object.keys(i);if(a.length===1){let c=a[0],f=i[c],u=f&&typeof f=="object"?f.args??f.input??f:void 0;t(c,r(u))}return}return}if(Array.isArray(e.tool_calls)){for(let i of e.tool_calls)t(i.name,r(i.input??i.arguments));return}let o=e.message??e;if(Array.isArray(o?.tool_calls)){for(let i of o.tool_calls)t(i.name,r(i.input??i.arguments));return}let s=o?.content??e.content;if(Array.isArray(s))for(let i of s)(i.type==="tool_use"||i.type==="tool_call")&&i.name&&t(i.name,r(i.input??i.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return e.type==="thinking"&&e.text||e.text?e.text:e.content&&typeof e.content=="string"?e.content:e.delta?e.delta:null}tryExtractResult(e){if(!e||typeof e!="string")return;let t=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,o;for(;(o=r.exec(e))!==null;){let
|
|
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*"([^"]*)/),c=i?i[1]:a?a[1]:null;c&&!this.rawText.includes(c)&&(r+=c,this.rawText+=c)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(i,a)=>{if(!i)return;let c=`${i}:${JSON.stringify(a??{})}`;this._lastToolEmit!==c&&(this._lastToolEmit=c,this.onToolCall(i,a??void 0))},r=i=>{if(i!=null){if(typeof i=="object"&&!Array.isArray(i))return i;if(typeof i=="string")try{return JSON.parse(i)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,r(e.input??e.arguments));return}let i=e.tool_call;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=Object.keys(i);if(a.length===1){let c=a[0],f=i[c],u=f&&typeof f=="object"?f.args??f.input??f:void 0;t(c,r(u))}return}return}if(Array.isArray(e.tool_calls)){for(let i of e.tool_calls)t(i.name,r(i.input??i.arguments));return}let o=e.message??e;if(Array.isArray(o?.tool_calls)){for(let i of o.tool_calls)t(i.name,r(i.input??i.arguments));return}let s=o?.content??e.content;if(Array.isArray(s))for(let i of s)(i.type==="tool_use"||i.type==="tool_call")&&i.name&&t(i.name,r(i.input??i.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return e.type==="thinking"&&e.text||e.text?e.text:e.content&&typeof e.content=="string"?e.content:e.delta?e.delta:null}tryExtractResult(e){if(!e||typeof e!="string")return;let t=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,o;for(;(o=r.exec(e))!==null;){let g=o[1].trim();try{JSON.parse(g),t.push({text:g,source:"markdown"})}catch{}}let s=0,i=0;for(;s<e.length&&(s=e.indexOf("{",s),s!==-1);){let g=0,m=s;for(let O=s;O<e.length;O++)if(e[O]==="{")g++;else if(e[O]==="}"&&(g--,g===0)){m=O,t.push({text:e.substring(s,m+1),source:"brace"}),i++;break}s=m+1}let a=this.extractedResult,c=a?JSON.stringify(a).length:0,f=0,u=-1;for(let g=0;g<t.length;g++){let m=t[g];try{let O=m.text.replace(/,(\s*[}\]])/g,"$1"),I=JSON.parse(O);this.isValidResult(I)&&(f++,c=JSON.stringify(I).length,a=I,u=g)}catch{}}a&&(this.extractedResult=a)}isValidResult(e){if(!e||typeof e!="object"||Array.isArray(e)||e.session_id||e.timestamp_ms||e.type||e.call_id||e.tool_call||e.result&&typeof e.result=="object"&&(e.result.success&&typeof e.result.success=="object"||e.result.error&&typeof e.result.error=="object")||e.args&&typeof e.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(e),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(e,t=null){let r=new n;r.zodSchema=t,r.processChunk(e),r.flush();let o=r.getResult();return!o&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),o}};import{z as tt}from"zod";import{zodToJsonSchema as Nt}from"zod-to-json-schema";function Mt(n){if(!n)return null;if(typeof tt?.toJSONSchema=="function")try{return tt.toJSONSchema(n)}catch{}try{return Nt(n,{target:"openApi3"})}catch{return null}}var we=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=Mt(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
|
|
@@ -31,15 +31,15 @@ ${e.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:t,p
|
|
|
31
31
|
|
|
32
32
|
`),position:"append"}),this}addSystemInstruction(e,t="custom",r="append"){return e&&this.systemInstructions.push({type:t,content:e,position:r}),this}getUserPrompt(){return this.userPrompt}getSystemInstructions(){return this.systemInstructions}getMetadata(){return this.metadata}build(){let e=this.systemInstructions.filter(o=>o.position==="prepend").map(o=>o.content),t=this.systemInstructions.filter(o=>o.position==="append").map(o=>o.content);return[...e,this.userPrompt,...t].filter(Boolean).join(`
|
|
33
33
|
|
|
34
|
-
`)}getStats(){let e=this.userPrompt.length,t=this.build().length;return{userPromptLength:e,fullPromptLength:t,systemInstructionsLength:t-e,instructionCount:this.systemInstructions.length,instructionTypes:this.systemInstructions.map(r=>r.type)}}clone(){let e=new n(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};import
|
|
34
|
+
`)}getStats(){let e=this.userPrompt.length,t=this.build().length;return{userPromptLength:e,fullPromptLength:t,systemInstructionsLength:t-e,instructionCount:this.systemInstructions.length,instructionTypes:this.systemInstructions.map(r=>r.type)}}clone(){let e=new n(this.userPrompt);return e.systemInstructions=[...this.systemInstructions],e.metadata={...this.metadata},e}};import Rt from"axios";import{homedir as Lt}from"node:os";import{join as Dt}from"node:path";import{existsSync as Ut,readFileSync as Bt}from"node:fs";import{toJSONSchema as Jt}from"zod";function Kt(){if(process.env.OPENAI_PROXY_TOKEN)return l.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return l.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let n=Dt(Lt(),".zibby","config.json");if(Ut(n)){let e=JSON.parse(Bt(n,"utf-8"));if(e.sessionToken)return l.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(n){l.debug(`[Auth] Could not read zibby login session: ${n.message}`)}return null}function Gt(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function re(n){if(!(typeof n!="object"||n===null)){if(Object.keys(n).length===0){n.type="object",n.additionalProperties=!0;return}if(n.type||(n.properties?n.type="object":n.items&&(n.type="array")),n.type==="object")if(n.properties){for(let[e,t]of Object.entries(n.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(n.properties[e]={type:["object","null"]});n.additionalProperties=!1,n.required=Object.keys(n.properties),Object.values(n.properties).forEach(re)}else"additionalProperties"in n||(n.additionalProperties=!0);n.type==="array"&&n.items&&re(n.items),n.anyOf&&n.anyOf.forEach(re),n.oneOf&&n.oneOf.forEach(re),n.allOf&&n.allOf.forEach(re)}}async function ot(n,e){l.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=Kt();if(!t)throw new Error("Authentication required for structured output processing.\n Local development: Run `zibby login`\n CI/CD: Set ZIBBY_USER_TOKEN environment variable (Personal Access Token from UI settings)");let r=Gt();l.info(`\u{1F517} Using OpenAI proxy: ${r}`);let o=Jt(e),s=o;if(o.$ref&&o.definitions){let u=o.$ref.split("/").pop();s=o.definitions[u]||o,l.debug(`Extracted schema from $ref: ${u}`)}delete s.$schema,re(s);let i=4e5,a=n;n.length>i&&(l.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${n.length} chars) exceeds limit, keeping last ${i} chars`),a=`... [truncated early content] ...
|
|
35
35
|
${n.slice(-i)}`);let c=`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.`,f={model:F.OPENAI_POSTPROCESSING,messages:[{role:"user",content:c}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:s,strict:!0}}};l.info(`\u{1F4E4} Sending to OpenAI proxy: model=${F.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(s.properties||{}).join(", ")}`),l.debug(` Schema size: ${JSON.stringify(s).length} chars`),l.debug(` Prompt size: ${c.length} chars`);try{let u={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(u["x-proxy-token"]=t,u["x-execution-id"]=process.env.EXECUTION_ID||""):(u.Authorization=`Bearer ${t}`,u["x-api-key"]=process.env.ZIBBY_API_KEY||"",u["x-execution-id"]=process.env.EXECUTION_ID||"");let m=(await
|
|
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.`,f={model:F.OPENAI_POSTPROCESSING,messages:[{role:"user",content:c}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:s,strict:!0}}};l.info(`\u{1F4E4} Sending to OpenAI proxy: model=${F.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(s.properties||{}).join(", ")}`),l.debug(` Schema size: ${JSON.stringify(s).length} chars`),l.debug(` Prompt size: ${c.length} chars`);try{let u={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(u["x-proxy-token"]=t,u["x-execution-id"]=process.env.EXECUTION_ID||""):(u.Authorization=`Bearer ${t}`,u["x-api-key"]=process.env.ZIBBY_API_KEY||"",u["x-execution-id"]=process.env.EXECUTION_ID||"");let m=(await Rt.post(r,f,{headers:u,timeout:ve.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!m)throw new Error("OpenAI proxy returned empty response");let O=JSON.parse(m);return l.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:O,raw:n}}catch(u){if(u.response){let g=u.response.status,m=u.response.data;throw l.error(`\u274C OpenAI proxy request failed: ${g}`),l.error(` Status: ${g}`),l.error(` Response: ${JSON.stringify(m,null,2)}`),g===401||g===403?new Error(`Authentication failed for OpenAI proxy.
|
|
41
41
|
Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
|
|
42
|
-
Response: ${JSON.stringify(m)}`,{cause:u}):new Error(`Failed to format Cursor output: ${m?.error?.message||"Unknown error"}`,{cause:u})}throw l.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}function Y(n){let e=`${n}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let r=t.split(/[,\n]+/).map(i=>i.trim()).filter(Boolean);if(r.length===0)return{picked:null,count:0,dispose:()=>{}};let o=r[Math.floor(Math.random()*r.length)],s=process.env[n];return process.env[n]=o,l.debug(`[auth-pool] ${n}: picked 1 of ${r.length} from pool (***${o.slice(-4)})`),{picked:o,count:r.length,dispose(){s===void 0?delete process.env[n]:process.env[n]=s}}}import{timeline as V,Timeline as yr,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as _r}from"@zibby/agent-workflow";import{copyFileSync as
|
|
42
|
+
Response: ${JSON.stringify(m)}`,{cause:u}):new Error(`Failed to format Cursor output: ${m?.error?.message||"Unknown error"}`,{cause:u})}throw l.error(`\u274C OpenAI proxy request failed: ${u.message}`),new Error(`Failed to format output: ${u.message}`,{cause:u})}}function Y(n){let e=`${n}_POOL`,t=process.env[e];if(!t||typeof t!="string")return{picked:null,count:0,dispose:()=>{}};let r=t.split(/[,\n]+/).map(i=>i.trim()).filter(Boolean);if(r.length===0)return{picked:null,count:0,dispose:()=>{}};let o=r[Math.floor(Math.random()*r.length)],s=process.env[n];return process.env[n]=o,l.debug(`[auth-pool] ${n}: picked 1 of ${r.length} from pool (***${o.slice(-4)})`),{picked:o,count:r.length,dispose(){s===void 0?delete process.env[n]:process.env[n]=s}}}import{timeline as V,Timeline as yr,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as _r}from"@zibby/agent-workflow";import{copyFileSync as jt,existsSync as je,lstatSync as Ft,mkdirSync as rt,rmSync as Yt,symlinkSync as zt,unlinkSync as Ht}from"node:fs";import{join as W}from"node:path";import{homedir as Xt}from"node:os";import{randomBytes as Vt}from"node:crypto";var Wt=["cli-config.json","config.json","auth.json","argv.json"];function nt(n){return!(!n||typeof n!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function st(n){let e=W(n||process.cwd(),".zibby","tmp");rt(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${Vt(4).toString("hex")}`,r=W(e,`cursor-agent-home-${t}`),o=W(r,".cursor");rt(o,{recursive:!0});let s=Xt(),i=W(s,".cursor");if(je(i))for(let a of Wt){let c=W(i,a);if(je(c))try{jt(c,W(o,a))}catch{}}if(process.platform==="darwin"){let a=W(s,"Library");if(je(a))try{zt(a,W(r,"Library"))}catch{}}return r}function it(n){if(!(!n||typeof n!="string"))try{let e=W(n,"Library");try{Ft(e).isSymbolicLink()&&Ht(e)}catch{}Yt(n,{recursive:!0,force:!0})}catch{}}var xe=class extends Zt{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[H(me(),".local","bin","cursor-agent"),H(me(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"];for(let r of t)try{if(r.startsWith("/")){ft(r,dt.X_OK);let o=q(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(o&&o.length>0)return l.debug(`[Cursor] Found agent at: ${r} (version: ${o.trim().slice(0,50)})`),!0}else{let o=q(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!o)continue;let s=q(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return l.debug(`[Cursor] Found '${r}' in PATH at ${o} (version: ${s.trim().slice(0,50)})`),!0}}catch{continue}return l.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:r=process.cwd(),print:o=!1,schema:s=null,skills:i=null,sessionPath:a=null,nodeName:c=null,timeout:f=ve.CURSOR_AGENT_DEFAULT,config:u={},signal:g=null}=t,m=u?.agent?.strictMode||!1,O=t.model??u?.agent?.cursor?.model??F.CURSOR,I=Y("CURSOR_API_KEY");try{l.debug(`[Cursor] Invoking (model: ${O}, timeout: ${f/1e3}s, skills: ${JSON.stringify(i)})`);let _=(this._setupMcpConfig(a,r,u,i,c)||{}).isolatedMcpHome??null,b=[H(me(),".local","bin","cursor-agent"),H(me(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","agent","cursor-agent"],P=null;for(let E of b)try{if(E.startsWith("/"))ft(E,dt.X_OK),q(`"${E}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!q(`which ${E}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");q(`${E} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}P=E,l.debug(`[Agent] Using binary: ${E}`);break}catch(d){l.debug(`[Agent] Binary '${E}' check failed: ${d.message}`);continue}if(!P)throw new Error(`Cursor Agent CLI not found or not working.
|
|
43
43
|
|
|
44
44
|
Checked paths:
|
|
45
45
|
${b.map(E=>` - ${E}`).join(`
|
|
@@ -51,53 +51,53 @@ 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 M=new oe(e),
|
|
54
|
+
Test with: agent --version`);let M=new oe(e),h=null;if(s){let E=`zibby-result-${Date.now()}.json`;h=H(r,".zibby","tmp",E);let d=H(r,".zibby","tmp");pe(d)||ut(d,{recursive:!0}),M.addStructuredOutput(s,h)}let U=process.env.CURSOR_API_KEY,B=U?` | key: ***${U.slice(-4)}`:" | key: not set";console.log(`
|
|
55
55
|
\u25C6 Model: ${O||"auto"}${B}
|
|
56
56
|
`);let L=(await import("chalk")).default,S=M.getUserPrompt();console.log(`
|
|
57
57
|
${L.bold("Prompt sent to LLM:")}`),console.log(L.dim("\u2500".repeat(60))),console.log(L.dim(S)),console.log(L.dim("\u2500".repeat(60)));let J=M.build(),D=M.getStats(),R=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",O||"auto"];if(process.env.CURSOR_API_KEY&&R.push("--api-key",process.env.CURSOR_API_KEY),R.push(J),l.debug(`[Agent] User prompt: ${D.userPromptLength} chars, System instructions: ${D.systemInstructionsLength} chars (${D.instructionCount} blocks), Full: ${D.fullPromptLength} chars, model: ${O||"auto"}`),l.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 A,$=null;try{let E=a||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);A=await this._spawnWithStreaming(P,R,r,f,null,E,_,
|
|
58
|
+
`)}catch{}let A,$=null;try{let E=a||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);A=await this._spawnWithStreaming(P,R,r,f,null,E,_,g)}catch(E){$=E}let N=A?.stdout||"";if(s){let E=typeof s.parse=="function",d=null,v=!!(h&&pe(h));if(h&&l.info(`[Agent] Result file: ${v?"present":"missing"} at ${h}`),v)try{let y=ct(h,"utf-8").trim();d=JSON.parse(y),l.info(`[Agent] Parsed JSON from result file OK (${y.length} chars) \u2192 object ready for validation`),$&&l.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(y){l.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${y.message}`)}else if($)l.warn(`[Agent] Result file missing at ${h} (agent process error \u2014 may still recover if strictMode repairs)`);else throw l.error(`\u274C [Agent] Result file was never created at ${h}`),new Error(`Agent did not write required result file at ${h}`);if(d&&E)try{let y=s.parse(d);return l.info("\u2705 [Agent] Zod validation passed for structured result file"),m&&l.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:N,structured:y}}catch(y){let p=y.issues?y.issues.map(T=>` - ${T.path.join(".")}: ${T.message}`).join(`
|
|
59
59
|
`):y.message?.slice(0,400);if(l.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
|
|
60
60
|
${p}`),l.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
|
|
61
61
|
${JSON.stringify(d,null,2).slice(0,500)}`),!m)throw new Error(`Agent output failed schema validation:
|
|
62
62
|
${p}
|
|
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:y})}else{if(d)return l.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),m&&l.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:N,structured:d};v&&l.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(m&&!$){let y=A.parsedText,p=d?JSON.stringify(d):y;l.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${p.length} chars in)`);try{let T=await ot(p,s);if(E){let w=s.parse(T.structured);return l.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:N,structured:w}}return{raw:N,...T}}catch(T){if(l.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${T.message}`),d)return l.warn("[Agent] Using agent's original result file as fallback"),{raw:N,structured:d}}}if($)throw $;let C=v?d==null?"file existed but JSON.parse failed \u2014 see WARN log above":E?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw l.error(`\u274C [Agent] No validated structured output: ${C}`),l.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 ${
|
|
66
|
-
`),r=null;for(let o of t){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 c=a.filter(f=>f.type==="text"&&f.text).map(f=>f.text).join("");c&&(r=c)}else typeof a=="string"&&a&&(r=a)}}catch{}}return r?.trim()||null}_setupMcpConfig(e,t,r,o=null,s=null){let i=r?.headless,a=H(me(),".cursor"),c=H(a,"mcp.json"),f={};if(pe(c))try{f=JSON.parse(ct(c,"utf-8"))}catch{}let u=f.mcpServers||{},
|
|
67
|
-
`;if(nt(e)){let _=st(t||process.cwd()),b=H(_,".cursor","mcp.json");return at(b,k,"utf8"),l.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${_} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:_}}return pe(a)||ut(a,{recursive:!0}),at(c,k,"utf8"),l.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,o,s=null,i){let a=t.cursorKey||t.serverName,c=e[a]?a:e[t.serverName]?t.serverName:null;if(c&&r){let u=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:s,headless:i}):null;u?.args?e[c].args=u.args:e[c].args=(e[c].args||[]).map(O=>O.startsWith("--output-dir=")?`--output-dir=${r}`:O);let
|
|
68
|
-
`)){let x=w.replace(`${r}/`,"");A.has(x)||(A.add(x),C.push(x))}}catch{}let y="";C.length>0&&(y=` | \u{1F4C1} new: ${C.map(T=>T.split("/").pop()).join(", ")}`),A.size>0&&(y+=` | \u{1F4E6} total: ${A.size} files`),l.debug(`\u{1F493} [Agent] Running for ${d}s | ${k} lines output${y}`),k===0&&d>=30&&A.size===0&&(d<35&&l.warn(`\u26A0\uFE0F [Agent] No output after ${d}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),d>=60&&(_=!0,b=b||"stall",l.error(`\u274C [Agent] No response after ${d}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),S.kill("SIGTERM"),setTimeout(()=>{S.killed||S.kill("SIGKILL")},3e3)))},3e4),G=setTimeout(()=>{_=!0,b=b||"timeout";let d=Math.round((Date.now()-
|
|
65
|
+
Enable strictMode in .zibby.config.js for automatic repair.`,{cause:y})}else{if(d)return l.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),m&&l.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:N,structured:d};v&&l.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(m&&!$){let y=A.parsedText,p=d?JSON.stringify(d):y;l.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${p.length} chars in)`);try{let T=await ot(p,s);if(E){let w=s.parse(T.structured);return l.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:N,structured:w}}return{raw:N,...T}}catch(T){if(l.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${T.message}`),d)return l.warn("[Agent] Using agent's original result file as fallback"),{raw:N,structured:d}}}if($)throw $;let C=v?d==null?"file existed but JSON.parse failed \u2014 see WARN log above":E?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw l.error(`\u274C [Agent] No validated structured output: ${C}`),l.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($)throw $;return this._extractFinalResult(N)||A?.parsedText||N}finally{I.dispose()}}_extractFinalResult(e){if(!e)return null;let t=e.split(`
|
|
66
|
+
`),r=null;for(let o of t){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 c=a.filter(f=>f.type==="text"&&f.text).map(f=>f.text).join("");c&&(r=c)}else typeof a=="string"&&a&&(r=a)}}catch{}}return r?.trim()||null}_setupMcpConfig(e,t,r,o=null,s=null){let i=r?.headless,a=H(me(),".cursor"),c=H(a,"mcp.json"),f={};if(pe(c))try{f=JSON.parse(ct(c,"utf-8"))}catch{}let u=f.mcpServers||{},g=r?.paths?.output||qt,m=H(t||process.cwd(),g,Qt),O=Array.isArray(o)?o.map(_=>lt(_)).filter(Boolean):[...to()].map(([,_])=>_),I=new Set;for(let _ of O)typeof _.resolve=="function"&&(I.has(_.serverName)||(I.add(_.serverName),this._ensureSkillConfigured(u,_,e,m,s,i)));if(e){let _=lt("browser");_&&typeof _.resolve=="function"&&!I.has(_.serverName)&&this._ensureSkillConfigured(u,_,e,m,"execute_live",i)}if(Object.keys(u).length===0)return l.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let k=`${JSON.stringify({mcpServers:u},null,2)}
|
|
67
|
+
`;if(nt(e)){let _=st(t||process.cwd()),b=H(_,".cursor","mcp.json");return at(b,k,"utf8"),l.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${_} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:_}}return pe(a)||ut(a,{recursive:!0}),at(c,k,"utf8"),l.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,o,s=null,i){let a=t.cursorKey||t.serverName,c=e[a]?a:e[t.serverName]?t.serverName:null;if(c&&r){let u=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:s,headless:i}):null;u?.args?e[c].args=u.args:e[c].args=(e[c].args||[]).map(O=>O.startsWith("--output-dir=")?`--output-dir=${r}`:O);let g=u?.env||{},m=t.sessionEnvKey?{[t.sessionEnvKey]:o}:{};e[c].env={...e[c].env||{},...g,...m},l.debug(`[MCP] Updated ${c} session \u2192 ${r}`);return}if(c)return;let f=t.resolve({sessionPath:r,nodeName:s,headless:i});f&&(e[a]={...f,...t.sessionEnvKey&&{env:{...f.env||{},[t.sessionEnvKey]:o}}},l.debug(`[MCP] Configured ${a}`))}_spawnWithStreaming(e,t,r,o,s=null,i=null,a=null,c=null){return new Promise((f,u)=>{let g=Date.now(),m="",O="",I=Date.now(),k=0,_=!1,b=null,P=!1,M=!1,h=null;if(i)try{h=H(no(String(i)),eo)}catch{h=null}let U=!1,B=()=>{U||(U=!0,it(a))},L={...process.env};a&&(L.HOME=a,process.platform==="win32"&&(L.USERPROFILE=a),l.debug(`[Agent] cursor-agent HOME=${a} (isolated MCP config)`));let S=oo(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:L,...c&&{signal:c}});l.debug(`[Agent] PID: ${S.pid}`);let J=null,D=()=>{_||M||(_=!0,b="aborted",l.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),J=setTimeout(()=>{if(!M){l.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{S.kill("SIGKILL")}catch{}}},5e3))};c&&(c.aborted?D():c.addEventListener("abort",D,{once:!0})),S.stdin.on("error",d=>{d.code!=="EPIPE"&&l.warn(`[Agent] stdin error: ${d.message}`)}),S.stdout.on("error",d=>{d.code!=="EPIPE"&&l.warn(`[Agent] stdout error: ${d.message}`)}),S.stderr.on("error",d=>{d.code!=="EPIPE"&&l.warn(`[Agent] stderr error: ${d.message}`)}),s?(S.stdin.write(s,d=>{d&&d.code!=="EPIPE"&&l.warn(`[Agent] Failed to write to stdin: ${d.message}`),S.stdin.end()}),l.debug(`[Agent] Prompt also piped to stdin (${s.length} chars)`)):S.stdin.end();let R=null;h&&(R=setInterval(()=>{if(!(_||M))try{if(pe(h)){_=!0,b="aborted";try{ro(h)}catch{}l.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),S.kill("SIGTERM"),setTimeout(()=>{S.killed||S.kill("SIGKILL")},2e3)}}catch{}},600));let A=new Set,$=new Date(g).toISOString().replace(/\.\d+Z$/,""),N=setInterval(()=>{let d=Math.round((Date.now()-g)/1e3),v=Math.round((Date.now()-I)/1e3),C=[];try{let p=Math.ceil(d/60)+1,T=q(`find "${r}" -type f -mmin -${p} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(T)for(let w of T.split(`
|
|
68
|
+
`)){let x=w.replace(`${r}/`,"");A.has(x)||(A.add(x),C.push(x))}}catch{}let y="";C.length>0&&(y=` | \u{1F4C1} new: ${C.map(T=>T.split("/").pop()).join(", ")}`),A.size>0&&(y+=` | \u{1F4E6} total: ${A.size} files`),l.debug(`\u{1F493} [Agent] Running for ${d}s | ${k} lines output${y}`),k===0&&d>=30&&A.size===0&&(d<35&&l.warn(`\u26A0\uFE0F [Agent] No output after ${d}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),d>=60&&(_=!0,b=b||"stall",l.error(`\u274C [Agent] No response after ${d}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),S.kill("SIGTERM"),setTimeout(()=>{S.killed||S.kill("SIGKILL")},3e3)))},3e4),G=setTimeout(()=>{_=!0,b=b||"timeout";let d=Math.round((Date.now()-g)/1e3);l.error(`\u23F1\uFE0F [Agent] Timeout after ${d}s \u2014 killing process (PID: ${S.pid})`),m.trim()&&l.warn(`\u{1F4E4} [Agent] Partial output (${m.length} chars) before timeout:
|
|
69
69
|
${m.slice(-2e3)}`),S.kill("SIGTERM"),setTimeout(()=>{S.killed||S.kill("SIGKILL")},5e3)},o),E=new te;E.onToolCall=(d,v)=>{let C=d,y=v;if(d==="mcpToolCall"&&v?.name)C=v.name.replace(/^mcp_+[^_]+_+/,""),C.includes("-")&&C.split("-")[0]===C.split("-")[1]&&(C=C.split("-")[0]),y=v.args??v.input??v;else{if(d==="readToolCall"||d==="editToolCall"||d==="writeToolCall")return;(d.startsWith("mcp__")||d.includes("ToolCall"))&&(C=d.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(C.includes("memory")?V.stepMemory(`Tool: ${C}`):V.stepTool(`Tool: ${C}`),y!=null&&typeof y=="object"&&Object.keys(y).length>0&&!M){let T=JSON.stringify(y),w=T.length>100?`${T.substring(0,100)}...`:T;console.log(` Input: ${w}`)}},S.stdout.on("data",d=>{let v=d.toString();m+=v,I=Date.now(),P||(P=!0);let C=E.processChunk(v);C&&!M&&process.stdout.write(C);let y=v.split(`
|
|
70
70
|
`).filter(p=>p.trim());k+=y.length}),S.stderr.on("data",d=>{let v=d.toString();O+=v,I=Date.now(),P||(P=!0);let C=v.split(`
|
|
71
|
-
`).filter(y=>y.trim());for(let y of C)l.warn(`\u26A0\uFE0F [Agent stderr] ${y}`)}),S.on("close",(d,v)=>{if(M=!0,B(),clearTimeout(G),clearInterval(N),R&&clearInterval(R),J&&clearTimeout(J),c&&!c.aborted)try{c.removeEventListener("abort",D)}catch{}E.flush();let C=Math.round((Date.now()-
|
|
71
|
+
`).filter(y=>y.trim());for(let y of C)l.warn(`\u26A0\uFE0F [Agent stderr] ${y}`)}),S.on("close",(d,v)=>{if(M=!0,B(),clearTimeout(G),clearInterval(N),R&&clearInterval(R),J&&clearTimeout(J),c&&!c.aborted)try{c.removeEventListener("abort",D)}catch{}E.flush();let C=Math.round((Date.now()-g)/1e3);if(l.debug(`[Agent] Exited: code=${d}, signal=${v}, elapsed=${C}s, output=${m.length} chars`),_){if(b==="aborted"){let T=new Error("Aborted via signal");T.name="AbortError",u(T);return}u(new Error(`Cursor Agent timed out after ${C}s (limit: ${o/1e3}s). ${k} lines produced. Last output ${Math.round((Date.now()-I)/1e3)}s ago. ${m.trim()?`
|
|
72
72
|
Partial output (last 500 chars):
|
|
73
73
|
${m.slice(-500)}`:"No output captured."}`));return}if(d!==0){u(new Error(`Cursor Agent failed: exit code ${d}, signal ${c}. ${O.trim()?`
|
|
74
74
|
Stderr: ${O.slice(-1e3)}`:""}${m.trim()?`
|
|
75
75
|
Stdout (last 500 chars): ${m.slice(-500)}`:""}`));return}let y=E.getResult(),p=y?JSON.stringify(y,null,2):E.getRawText()||m||"";f({stdout:m||O||"",parsedText:p})}),S.on("error",d=>{if(B(),clearTimeout(G),clearInterval(N),R&&clearInterval(R),J&&clearTimeout(J),c&&!c.aborted)try{c.removeEventListener("abort",D)}catch{}u(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`))})})}};ge();import{AgentStrategy as
|
|
78
|
+
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};ge();import{AgentStrategy as lo,getSkill as gt,NO_INTEGRATION_TOGGLEABLE_SKILL_IDS as ao}from"@zibby/agent-workflow";import{query as co}from"@anthropic-ai/claude-agent-sdk";import{writeFileSync as Fe,mkdirSync as Ye,existsSync as se,readFileSync as yt}from"fs";import{homedir as _t}from"os";import{join as z}from"path";import{createRequire as uo}from"module";import K from"process";var ht=uo(import.meta.url);function fo(){try{if(K.env.CLAUDE_CODE_EXECUTABLE&&se(K.env.CLAUDE_CODE_EXECUTABLE))return K.env.CLAUDE_CODE_EXECUTABLE;let n=K.platform,e=K.arch,t=`@anthropic-ai/claude-agent-sdk-${n}-${e}`,r=n==="win32"?"claude.exe":"claude";try{let o=ht.resolve(`${t}/package.json`),s=z(o,"..",r);if(se(s))return s}catch{}try{let o=ht.resolve("@anthropic-ai/claude-agent-sdk/package.json"),s=z(o,"..");for(let a of[r,z("vendor",r),z("bin",r)]){let c=z(s,a);if(se(c))return c}let i=z(s,"..",`claude-agent-sdk-${n}-${e}`,r);if(se(i))return i}catch{}}catch{}return null}var Te=fo();Te&&l.debug(`Claude native CLI resolved to baked binary: ${Te}`);var Ie=class extends lo{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!K.env.ANTHROPIC_API_KEY||!!K.env.ANTHROPIC_API_KEY_POOL,r=!!K.env.CLAUDE_CODE_OAUTH_TOKEN||!!K.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,o=!!K.env.ANTHROPIC_AUTH_TOKEN||!!K.env.ANTHROPIC_AUTH_TOKEN_POOL,s=t||r||o;return s||l.debug("ClaudeAgentStrategy: no credentials. Set one of ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_AUTH_TOKEN (or a *_POOL variant for multi-token rotation)."),s}async invoke(e,t={}){let{model:r,workspace:o=K.cwd(),schema:s=null,images:i=[],skills:a=null,sessionPath:c=null,nodeName:f=null,timeout:u,config:g={},signal:m=null,sessionId:O,resume:I,forkSession:k,sessionStore:_}=t,b=r;(!b||b==="auto")&&(l.debug(`Model is '${b||"undefined"}', using default: ${F.CLAUDE}`),b=F.CLAUDE);let P=Ke[b]||b;Ke[b]&&b!==P&&l.debug(`Mapped model: ${b} \u2192 ${P}`);let M=[Y("ANTHROPIC_API_KEY"),Y("CLAUDE_CODE_OAUTH_TOKEN"),Y("ANTHROPIC_AUTH_TOKEN")];try{l.debug(`Invoking Claude Agent SDK with model: ${P}, skills: ${JSON.stringify(a)}`);let h=K.env.CLAUDE_CODE_OAUTH_TOKEN,U=K.env.ANTHROPIC_API_KEY,B=K.env.ANTHROPIC_AUTH_TOKEN;K.env.CLAUDE_CODE_CREDENTIALS_JSON?go(K.env.CLAUDE_CODE_CREDENTIALS_JSON):h&&mo(h,K.env.__ZIBBY_CLAUDE_PLAN);let L=K.env.__ZIBBY_CLAUDE_PLAN,S=L?L.charAt(0).toUpperCase()+L.slice(1):null,J;h?J=S?`Claude ${S} plan \xB7 ***${h.slice(-4)}`:`Subscription \xB7 ***${h.slice(-4)}`:U?J=`API key \xB7 ***${U.slice(-4)}`:B?J=`Bearer \xB7 ***${B.slice(-4)}`:J="NONE \u2014 request will fail";let D=(await import("chalk")).default;console.log(""),console.log(` ${D.cyan("\u25C6")} ${D.bold(P)}`),console.log(` ${D.dim("Auth: ")}${J}`),console.log(` ${D.dim("Workdir: ")}${o}`),console.log(""),console.log(D.bold("Prompt sent to LLM:")),console.log(D.dim("\u2500".repeat(60))),console.log(D.dim(e)),console.log(D.dim("\u2500".repeat(60)));let{allowedTools:R,mcpServers:A}=this._resolveSkills(a,{sessionPath:c,workspace:o,nodeName:f});try{let $={cwd:o,allowedTools:R,settings:{permissions:{allow:["Bash(*)","Read(*)","Write(*)","Edit(*)","MultiEdit(*)","NotebookEdit(*)","Grep(*)","Glob(*)","WebFetch(*)","WebSearch(*)","Task(*)","TodoWrite(*)","Skill(*)"]}},model:P,...Te&&{pathToClaudeCodeExecutable:Te},...Object.keys(A).length>0&&{mcpServers:A},...O&&{sessionId:O},...I&&{resume:I},...k&&{forkSession:!0},..._&&{sessionStore:_}};if(s){let T=typeof s.parse=="function"?Q(s):s;$.outputFormat={type:"json_schema",schema:T},l.debug("Structured output enforced via SDK outputFormat")}l.debug(`Agent SDK options: ${JSON.stringify({cwd:$.cwd,toolCount:R.length,permissionMode:$.permissionMode,model:$.model,hasOutputFormat:!!$.outputFormat})}`);let N="",G=0,E=[];l.debug("Starting Claude Agent SDK query stream");let d;try{d=co({prompt:e,options:$})}catch(p){throw l.error(`Failed to initialize Claude Agent SDK: ${p.message}`),p}let v=null,C=0,y=3;if(m?.aborted){let p=new Error("Aborted via signal");throw p.name="AbortError",p}try{for await(let p of d){if(m?.aborted){let w=new Error("Aborted via signal");throw w.name="AbortError",w}if(E.push(p),p.type==="system"&&p.subtype==="init"){let w=p.mcp_servers||[];if(w.length>0){let x=w.map(j=>`${j.name}=${j.status}${j.error?` (${String(j.error).slice(0,120)})`:""}`).join(", ");l.info(`[mcp] SDK init \u2014 ${w.length} server(s): ${x}`);for(let j of w)j.status!=="connected"&&l.warn(`[mcp] server '${j.name}' did not connect: status=${j.status}`,{name:j.name,status:j.status,error:j.error})}else Object.keys(A||{}).length>0&&l.warn(`[mcp] SDK init returned no mcp_servers despite passing ${Object.keys(A).length} server(s) \u2014 SDK version may not expose this field, or config was dropped`);if(Array.isArray(p.tools)){let x=p.tools.filter(j=>j.startsWith("mcp__"));x.length>0?l.info(`[mcp] tools visible to model: ${x.join(", ")}`):Object.keys(A||{}).length>0&&l.warn("[mcp] no mcp__* tools in model's tool list \u2014 MCP servers configured but tools didn't reach the prompt")}}if(p.type==="error"||p.error){let w=p.error?.message||p.error||p.message||"Unknown API error";try{l.error("SDK error event raw payload",{fullMessage:JSON.stringify(p,null,2)})}catch{}throw new Error(typeof w=="string"?w:JSON.stringify(w))}let T=JSON.stringify(p.message?.content||p.text||"").slice(0,200);if(T===v){if(C++,C>=y){let w=(p.message?.content?.[0]?.text||p.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${C}x repeated): ${w}`)}}else v=T,C=1;if(p.type==="assistant"||p.constructor?.name==="AssistantMessage"){let w=p.message?.content||p.content||[];for(let x of w)if(x.type==="thinking"&&x.thinking)console.log(`${x.thinking.substring(0,200)}${x.thinking.length>200?"...":""}`);else if(x.type==="text"&&x.text)N+=x.text,x.text.length<500?console.log(`${x.text}`):console.log(`${x.text.substring(0,200)}... (${x.text.length} chars)`);else if(x.type==="tool_use"){G++,x.name.includes("memory")?V.stepMemory(`Tool: ${x.name}`):V.stepTool(`Tool: ${x.name}`);let ue=JSON.stringify(x.input).substring(0,100);console.log(` Input: ${ue}${JSON.stringify(x.input).length>100?"...":""}`)}}else if(!(p.type==="user"&&p.tool_use_result)){if(p.type==="result"||p.constructor?.name==="ResultMessage"){let w=p.result||p.text||p.content||N;try{po({message:p,sessionPath:c,nodeName:f,model:b,toolCallCount:G})}catch(x){l.debug(`usage.json write failed: ${x.message}`)}if(s){if(p.structured_output){l.debug("Using SDK native structured_output");let j=typeof s.parse=="function"?s.parse(p.structured_output):p.structured_output;return{raw:w,structured:j}}if(w){let x=this._extractJson(w,s);if(x)return{raw:w,structured:x}}l.warn(`Could not extract structured output \u2014 returning raw text (${(w||"").length} chars)`)}return w||""}}}if(l.warn(`Agent SDK ended without result. Collected ${E.length} messages`),N.length>0)return l.debug("Returning accumulated text from messages"),N;throw new Error("Claude Agent SDK query ended without result")}catch(p){let T={message:p?.message,name:p?.name,code:p?.code,cause:p?.cause?.message||p?.cause,stack:p?.stack?.split(`
|
|
79
79
|
`).slice(0,5).join(`
|
|
80
|
-
`),stringified:(()=>{try{return JSON.stringify(p,Object.getOwnPropertyNames(Object(p)))}catch{return String(p)}})()};throw l.error(`Error during query stream: ${p?.message||p}`,T),p}}catch($){throw l.error("Claude Agent SDK call failed",{message:$?.message,name:$?.name,code:$?.code,cause:$?.cause?.message||$?.cause}),$}}finally{for(let
|
|
80
|
+
`),stringified:(()=>{try{return JSON.stringify(p,Object.getOwnPropertyNames(Object(p)))}catch{return String(p)}})()};throw l.error(`Error during query stream: ${p?.message||p}`,T),p}}catch($){throw l.error("Claude Agent SDK call failed",{message:$?.message,name:$?.name,code:$?.code,cause:$?.cause?.message||$?.cause}),$}}finally{for(let h of M)h.dispose()}}_resolveSkills(e,t){let r=["Read","Write","Edit","Bash","Grep","Glob"];if(e===null)return l.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return l.debug("Default IDE skills for code generation"),{allowedTools:[...r],mcpServers:{}};let o=[...r],s={},i=K.env.WORKFLOW_ENABLED_INTEGRATIONS,a=typeof i=="string"&&i.trim()!==""?new Set(i.split(",").map(u=>u.trim()).filter(Boolean)):null,c=u=>{let g=gt(u);return g?.meta?.toggleable===!0?!0:g?.meta?.toggleable===void 0&&ao.includes(u)},f=u=>a!==null&&a.size>0&&c(u)&&!a.has(u);for(let u of e){if(f(u)){l.debug(`Skill "${u}" disabled by enabledIntegrations allowlist \u2014 skipping`);continue}let g=gt(u);if(!g){l.warn(`Unknown skill "${u}" \u2014 skipping`);continue}if(g.allowedTools&&o.push(...g.allowedTools),typeof g.resolve=="function"){let m=g.resolve(t);m&&(s[g.serverName]=m,l.debug(`MCP: ${g.serverName} \u2192 ${m.command} ${m.args[0]}`))}}return{allowedTools:o,mcpServers:s}}_extractJson(e,t){let r=[()=>{if(e.includes("===JSON_START===")){let o=e.indexOf("===JSON_START===")+16,s=e.indexOf("===JSON_END===");return e.substring(o,s).trim()}},()=>e.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!e.startsWith("{"))return e.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>e.trim(),()=>{let o=e.indexOf("{"),s=e.lastIndexOf("}");if(o!==-1&&s>o)return e.substring(o,s+1)}];for(let o of r)try{let s=o();if(!s)continue;let i=JSON.parse(s);if(typeof i!="object"||i===null)continue;return typeof t.parse=="function"?t.parse(i):i}catch{}return null}};function po({message:n,sessionPath:e,nodeName:t,model:r,toolCallCount:o}){if(!e||!t)return;let s=n?.usage||n?.message?.usage||{},i=he(s.input_tokens,s.inputTokens),a=he(s.output_tokens,s.outputTokens),c=he(s.cache_read_input_tokens,s.cacheReadInputTokens),f=he(s.cache_creation_input_tokens,s.cacheCreationInputTokens),u=he(n?.duration_ms,n?.durationMs),g={model:r||null,input_tokens:i,output_tokens:a,cache_read_tokens:c,cache_creation_tokens:f,tool_call_count:typeof o=="number"?o:null,duration_ms:u,captured_at:new Date().toISOString()},m=z(e,t);try{Ye(m,{recursive:!0})}catch{}Fe(z(m,"usage.json"),JSON.stringify(g,null,2),"utf-8")}function he(...n){for(let e of n){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e)))return Number(e)}return null}function mo(n,e){let t=z(_t(),".claude"),r=z(t,".credentials.json"),o={claudeAiOauth:{accessToken:n,refreshToken:"",expiresAt:Date.now()+365*24*60*60*1e3,scopes:["user:inference","user:profile"],...e?{subscriptionType:String(e).toLowerCase()}:{}}};try{if(se(r)&&JSON.parse(yt(r,"utf-8"))?.claudeAiOauth?.accessToken===n)return;Ye(t,{recursive:!0}),Fe(r,JSON.stringify(o,null,2),"utf-8"),l.debug(`Wrote Claude Code OAuth credentials to ${r}`)}catch(s){l.warn(`Could not write ${r}: ${s.message} \u2014 Claude SDK may fail to authenticate.`)}}function go(n){let e=z(_t(),".claude"),t=z(e,".credentials.json"),r;try{r=JSON.parse(n)}catch(o){l.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${o.message}`);return}if(!r?.claudeAiOauth?.accessToken){l.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if(se(t)){let o=JSON.parse(yt(t,"utf-8"));if(o?.claudeAiOauth?.accessToken===r.claudeAiOauth.accessToken&&o?.claudeAiOauth?.expiresAt===r.claudeAiOauth.expiresAt)return}Ye(e,{recursive:!0}),Fe(t,JSON.stringify(r,null,2),"utf-8"),l.debug(`Wrote full Claude Code credentials blob to ${t}`)}catch(o){l.warn(`Could not write ${t}: ${o.message} \u2014 Claude SDK may fail to authenticate.`)}}ge();import{AgentStrategy as ho,getSkill as yo}from"@zibby/agent-workflow";import{execSync as ye}from"node:child_process";import{readFileSync as _o,mkdirSync as ze,cpSync as So,existsSync as Oo}from"node:fs";import{join as _e}from"node:path";import{homedir as bo}from"node:os";function He(n){if(Array.isArray(n))return n.map(He);if(n&&typeof n=="object"){let e={};for(let[t,r]of Object.entries(n))r!==null&&(e[t]=He(r));return e}return n}var $e=class extends ho{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY_POOL||process.env.CODEX_API_KEY||process.env.CODEX_API_KEY_POOL))return l.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return ye("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return l.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:r,workspace:o=process.cwd(),schema:s=null,skills:i=null,plugins:a=null,sessionPath:c=null,nodeName:f=null,timeout:u,config:g={},signal:m=null}=t,O=[Y("OPENAI_API_KEY"),Y("CODEX_API_KEY")];try{let{Codex:I}=await import("@openai/codex-sdk"),k=r;(!k||k==="auto")&&(l.debug(`Model is '${k||"undefined"}', using default: ${F.CODEX}`),k=F.CODEX);let _=Ge[k]||k;Ge[k]&&k!==_&&l.debug(`Mapped model: ${k} \u2192 ${_}`),l.debug(`Invoking Codex SDK with model: ${_}, skills: ${JSON.stringify(i)}`);let b=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;b&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=b);let P=b?` | key: ***${b.slice(-4)}`:" | key: not set";if(console.log(`
|
|
81
81
|
\u25C6 Model: ${_}${P}
|
|
82
82
|
`),Array.isArray(a)&&a.length>0){let A=this._resolveCodexHome(c);process.env.CODEX_HOME=A;try{ze(A,{recursive:!0})}catch{}this._ensurePlugins(a,A)}let M=(await import("chalk")).default;console.log(`
|
|
83
|
-
${M.bold("Prompt sent to LLM:")}`),console.log(M.dim("\u2500".repeat(60))),console.log(M.dim(e)),console.log(M.dim("\u2500".repeat(60)));let
|
|
84
|
-
`).some(o=>o.includes(e)&&/installed/.test(o))}catch{return!1}}};ge();import{AgentStrategy as Eo,getSkill as Ao}from"@zibby/agent-workflow";import{execSync as vo,spawn as wo}from"node:child_process";import{existsSync as
|
|
85
|
-
${y}`,"schema_instruction","append");let p=`zibby-result-${Date.now()}.json`,T=ee(o,".zibby","tmp");
|
|
83
|
+
${M.bold("Prompt sent to LLM:")}`),console.log(M.dim("\u2500".repeat(60))),console.log(M.dim(e)),console.log(M.dim("\u2500".repeat(60)));let h=this._resolveSkillsToMcp(i,{sessionPath:c,workspace:o,nodeName:f}),U={};Object.keys(h).length>0&&(U.mcp_servers=h,l.debug(`[Codex] MCP servers: ${Object.keys(h).join(", ")}`));let B=this._resolveCodexBin(),L=new I({...B?{codexPathOverride:B}:{},...Object.keys(U).length>0&&{config:U}}),S=o;try{S&&ze(S,{recursive:!0})}catch{}(!S||!Oo(S))&&(S=process.cwd());let J=L.startThread({workingDirectory:S,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),D=s&&typeof s.parse=="function",R={};if(s)try{let A=D?Q(s,{target:"openAi"}):s;R.outputSchema=A,l.debug("Structured output via SDK outputSchema")}catch(A){l.warn(`[Codex] Schema conversion failed, will extract from text: ${A.message}`)}if(m?.aborted){let A=new Error("Aborted via signal");throw A.name="AbortError",A}try{let{events:A}=await J.runStreamed(e,R),$=0,N="";for await(let G of A){if(m?.aborted){let d=new Error("Aborted via signal");throw d.name="AbortError",d}let E=G.type;if(E==="item.completed"){let d=G.item,v=d?.type;if(v==="mcp_tool_call"){$++;let C=`${d.server}/${d.tool}`;if(V.stepTool(`Tool: ${C}`),d.arguments){let y=JSON.stringify(d.arguments),p=y.length>100?`${y.substring(0,100)}...`:y;console.log(` Input: ${p}`)}}else if(v==="tool_call"||v==="function_call"||v==="command_execution"){$++;let C=d.name||d.tool||d.command||"unknown";V.stepTool(`Tool: ${C}`)}else v==="agent_message"&&(N=d.text||"",N.length<500?console.log(N):console.log(`${N.substring(0,200)}... (${N.length} chars)`))}else E==="turn.completed"?l.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(G.usage||{})}`):l.debug(`[Codex] Event: ${E} ${JSON.stringify(G).slice(0,300)}`)}if(l.debug(`[Codex] Last agent message (${N.length} chars): ${N.slice(0,500)}`),s){if(!N)throw new Error("Codex agent returned no response");let G=JSON.parse(N),E=G;if(D)try{E=s.parse(G)}catch{E=s.parse(He(G))}return l.debug("\u2705 [Codex] Structured output validated"),{raw:N,structured:E}}return N||""}catch(A){let $=A.message||String(A);throw l.error(`\u274C [Codex] SDK call failed: ${$}`),$.includes("exited with code")&&(R.outputSchema&&l.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."),l.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),l.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),A}}finally{for(let I of O)I.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let o of e){let s=yo(o);if(!s){l.warn(`[Codex] Unknown skill "${o}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let a=s.serverName||o,c={command:i.command};i.args?.length&&(c.args=i.args),c.env={...process.env,...i.env||{}},r[a]=c,l.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)?_e(e,".codex-home"):_e(bo(),".codex")}_isTempPath(e){let t=String(process.env.TMPDIR||"/tmp").replace(/\/+$/,""),r=String(e||"");return r==="/tmp"||r.startsWith("/tmp/")||r===t||r.startsWith(t+"/")}_resolveCodexBin(){if(process.env.CODEX_BIN)return process.env.CODEX_BIN;try{return ye("command -v codex",{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}_ensurePlugins(e,t){let r={...process.env,CODEX_HOME:t};for(let o of e){let s=typeof o=="string"?o:o?.name,i=o&&typeof o=="object"?o.marketplacePath:null;if(!s||!i){l.warn(`[Codex][plugins] skipping malformed plugin declaration: ${JSON.stringify(o)} (need { name, marketplacePath })`);continue}let a=this._readMarketplaceName(i),c=`${s}@${a}`;if(this._isPluginInstalled(c,r)){l.info(`[Codex][plugins] ${c} already installed \u2014 skipping (idempotent)`),console.log(`\u25C6 [Codex] plugin ${c} already installed \u2014 skip`);continue}let f=this._safeMarketplacePath(i,t);l.info(`[Codex][plugins] installing ${c} from local marketplace ${f}`),console.log(`\u25C6 [Codex] installing plugin ${c} (local, no network)`);try{ye(`codex plugin marketplace add ${JSON.stringify(f)}`,{env:r,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),ye(`codex plugin add ${JSON.stringify(c)}`,{env:r,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),console.log(`\u25C6 [Codex] plugin ${c} installed`)}catch(u){let g=u.stderr&&u.stderr.toString()||u.message||String(u);throw l.error(`[Codex][plugins] failed to install ${c}: ${g}`),new Error(`Codex plugin install failed for ${c}: ${g}`)}}}_safeMarketplacePath(e,t){if(!String(e).includes("@"))return e;let r=_e(t,".zibby-mkt",String(e).replace(/[^a-zA-Z0-9]+/g,"_"));try{return ze(_e(t,".zibby-mkt"),{recursive:!0}),So(e,r,{recursive:!0}),r}catch(o){return l.warn(`[Codex][plugins] could not copy @-containing marketplace to a safe path: ${o.message}`),e}}_readMarketplaceName(e){let t=_e(e,".agents","plugins","marketplace.json"),r;try{r=JSON.parse(_o(t,"utf-8"))}catch(o){throw new Error(`Codex plugin marketplace manifest missing/unreadable at ${t}: ${o.message}`)}if(!r?.name||typeof r.name!="string")throw new Error(`Codex plugin marketplace manifest at ${t} has no string "name"`);return r.name}_isPluginInstalled(e,t){try{return ye("codex plugin list",{env:t,stdio:"pipe",timeout:15e3,encoding:"utf-8"}).split(`
|
|
84
|
+
`).some(o=>o.includes(e)&&/installed/.test(o))}catch{return!1}}};ge();import{AgentStrategy as Eo,getSkill as Ao}from"@zibby/agent-workflow";import{execSync as vo,spawn as wo}from"node:child_process";import{existsSync as St,mkdirSync as Ot,readFileSync as bt,rmSync as xo,writeFileSync as Et}from"node:fs";import{join as ee}from"node:path";function To(n){if(!n)return null;let e=String(n),t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t?.[1])try{return JSON.parse(t[1].trim())}catch{}let r=e.indexOf("{");if(r<0)return null;let o=0,s=!1,i=!1,a=-1;for(let c=r;c<e.length;c++){let f=e[c];if(s){i?i=!1:f==="\\"?i=!0:f==='"'&&(s=!1);continue}if(f==='"'){s=!0;continue}if(f==="{"){o===0&&(a=c),o+=1;continue}if(f==="}"){if(o===0)continue;if(o-=1,o===0&&a>=0){let u=e.slice(a,c+1);try{return JSON.parse(u)}catch{a=-1}}}}return null}function Io(n){let e=String(n||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return To(e)}}function $o(n){try{let e=JSON.parse(n);if(typeof e=="string")return e;if(typeof e?.response=="string")return e.response;if(typeof e?.text=="string")return e.text;if(typeof e?.output=="string")return e.output;if(Array.isArray(e?.candidates)&&e.candidates.length>0){let t=e.candidates[0];if(typeof t?.content=="string")return t.content;if(Array.isArray(t?.content?.parts)){let r=t.content.parts.map(o=>typeof o?.text=="string"?o.text:"").join("");if(r.trim())return r}}}catch{}return n}var Ce=class extends Eo{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GEMINI_API_KEY_POOL||process.env.GOOGLE_API_KEY||process.env.GOOGLE_API_KEY_POOL))return l.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return vo("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return l.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:r,workspace:o=process.cwd(),schema:s=null,skills:i=null,sessionPath:a=null,nodeName:c=null,timeout:f=600*1e3,signal:u=null}=t,g=[Y("GEMINI_API_KEY"),Y("GOOGLE_API_KEY")];try{let m=r;(!m||m==="auto")&&(m=F.GEMINI);let O=et[m]||m,I=String(process.env.GEMINI_API_KEY||"").trim(),k=String(process.env.GOOGLE_API_KEY||"").trim(),_=this._resolveSkillsToMcp(i,{sessionPath:a,workspace:o,nodeName:c}),b=Object.keys(_).length>0,P=new oe(e),M=s&&typeof s.parse=="function",h=null;if(s){let y;try{let p=M?Q(s,{target:"openAi"}):s;y=JSON.stringify(p,null,2)}catch{y="{}"}if(b){P.addSystemInstruction(`Write valid JSON that matches this schema:
|
|
85
|
+
${y}`,"schema_instruction","append");let p=`zibby-result-${Date.now()}.json`,T=ee(o,".zibby","tmp");h=ee(T,p),Ot(T,{recursive:!0}),P.addStructuredOutput(s,h)}else P.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
|
|
86
86
|
${y}`,"json_instruction","append")}let U=P.build(),B=P.getUserPrompt(),L=P.getStats(),S=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),J=S?` | key: ***${S.slice(-4)}`:" | key: not set";console.log(`
|
|
87
87
|
\u25C6 Model: ${O||"auto"}${J}
|
|
88
88
|
`);let D=(await import("chalk")).default;console.log(`
|
|
89
|
-
${D.bold("Prompt sent to LLM:")}`),console.log(D.dim("\u2500".repeat(60))),console.log(D.dim(B)),console.log(D.dim("\u2500".repeat(60)));let R=this._createGeminiConfigDir(o,_),A=["--output-format","json"];O&&O!=="auto"&&A.push("--model",O);let $=Object.keys(_);if($.length>0){A.push("--approval-mode","yolo");for(let y of $)A.push("--allowed-mcp-server-names",y);l.info(`[Gemini] Enabling MCP servers: ${$.join(", ")}`)}else i&&i.length>0&&l.warn(`[Gemini] Skills requested but no MCP servers configured: ${i.join(", ")}`);A.push("-p",U);let N={...process.env,GEMINI_CLI_HOME:R};I?(N.GEMINI_API_KEY=I,delete N.GOOGLE_API_KEY):k&&(N.GOOGLE_API_KEY=k,delete N.GEMINI_API_KEY),l.debug(`[Gemini] Command: gemini ${A.slice(0,8).join(" ")}... (${A.length} total args)`),l.debug(`[Gemini] User prompt: ${L.userPromptLength} chars, System instructions: ${L.systemInstructionsLength} chars (${L.instructionCount} blocks), Full: ${L.fullPromptLength} chars`),l.debug(`[Gemini] Config home: ${R}`),l.debug(`[Gemini] GEMINI_CLI_HOME env: ${N.GEMINI_CLI_HOME}`);let G="",E=null;try{G=await new Promise((p,T)=>{let w=wo("gemini",A,{cwd:o,env:N,stdio:["ignore","pipe","pipe"],...u&&{signal:u}}),x="",j="",ue=!1,fe=null,Be=!1,qe=setTimeout(()=>{try{w.kill("SIGTERM")}catch{}},f),Ee=()=>{Be||ue||(Be=!0,fe=setTimeout(()=>{if(!ue)try{w.kill("SIGKILL")}catch{}},5e3))};u&&(u.aborted?Ee():u.addEventListener("abort",Ee,{once:!0})),w.stdout.on("data",Z=>{x+=Z.toString()}),w.stderr.on("data",Z=>{j+=Z.toString()}),w.on("error",Z=>{if(clearTimeout(qe),fe&&clearTimeout(fe),u&&!u.aborted)try{u.removeEventListener("abort",Ee)}catch{}T(Z)}),w.on("close",Z=>{if(ue=!0,clearTimeout(qe),fe&&clearTimeout(fe),u&&!u.aborted)try{u.removeEventListener("abort",Ee)}catch{}if(Be){let Qe=new Error("Aborted via signal");return Qe.name="AbortError",T(Qe)}if(Z===0)return p(x.trim());T(new Error(`gemini failed with code ${Z}: ${(j||x).trim()}`))})})}catch(y){E=y}finally{try{xo(R,{recursive:!0,force:!0})}catch{}}let d=$o(G).trim();if(!s){if(E)throw E;return d}if(
|
|
89
|
+
${D.bold("Prompt sent to LLM:")}`),console.log(D.dim("\u2500".repeat(60))),console.log(D.dim(B)),console.log(D.dim("\u2500".repeat(60)));let R=this._createGeminiConfigDir(o,_),A=["--output-format","json"];O&&O!=="auto"&&A.push("--model",O);let $=Object.keys(_);if($.length>0){A.push("--approval-mode","yolo");for(let y of $)A.push("--allowed-mcp-server-names",y);l.info(`[Gemini] Enabling MCP servers: ${$.join(", ")}`)}else i&&i.length>0&&l.warn(`[Gemini] Skills requested but no MCP servers configured: ${i.join(", ")}`);A.push("-p",U);let N={...process.env,GEMINI_CLI_HOME:R};I?(N.GEMINI_API_KEY=I,delete N.GOOGLE_API_KEY):k&&(N.GOOGLE_API_KEY=k,delete N.GEMINI_API_KEY),l.debug(`[Gemini] Command: gemini ${A.slice(0,8).join(" ")}... (${A.length} total args)`),l.debug(`[Gemini] User prompt: ${L.userPromptLength} chars, System instructions: ${L.systemInstructionsLength} chars (${L.instructionCount} blocks), Full: ${L.fullPromptLength} chars`),l.debug(`[Gemini] Config home: ${R}`),l.debug(`[Gemini] GEMINI_CLI_HOME env: ${N.GEMINI_CLI_HOME}`);let G="",E=null;try{G=await new Promise((p,T)=>{let w=wo("gemini",A,{cwd:o,env:N,stdio:["ignore","pipe","pipe"],...u&&{signal:u}}),x="",j="",ue=!1,fe=null,Be=!1,qe=setTimeout(()=>{try{w.kill("SIGTERM")}catch{}},f),Ee=()=>{Be||ue||(Be=!0,fe=setTimeout(()=>{if(!ue)try{w.kill("SIGKILL")}catch{}},5e3))};u&&(u.aborted?Ee():u.addEventListener("abort",Ee,{once:!0})),w.stdout.on("data",Z=>{x+=Z.toString()}),w.stderr.on("data",Z=>{j+=Z.toString()}),w.on("error",Z=>{if(clearTimeout(qe),fe&&clearTimeout(fe),u&&!u.aborted)try{u.removeEventListener("abort",Ee)}catch{}T(Z)}),w.on("close",Z=>{if(ue=!0,clearTimeout(qe),fe&&clearTimeout(fe),u&&!u.aborted)try{u.removeEventListener("abort",Ee)}catch{}if(Be){let Qe=new Error("Aborted via signal");return Qe.name="AbortError",T(Qe)}if(Z===0)return p(x.trim());T(new Error(`gemini failed with code ${Z}: ${(j||x).trim()}`))})})}catch(y){E=y}finally{try{xo(R,{recursive:!0,force:!0})}catch{}}let d=$o(G).trim();if(!s){if(E)throw E;return d}if(h){let y=St(h);if(l.info(`[Gemini] Result file: ${y?"present":"missing"} at ${h}`),y)try{let p=bt(h,"utf-8").trim(),T=JSON.parse(p),w=M?s.parse(T):T;return l.info("[Gemini] Structured output recovered from result file"),{raw:d,structured:w}}catch(p){l.warn(`[Gemini] Result file parse/validation failed: ${p.message}`)}else E||l.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let v=null;if(s){let y=new te;y.zodSchema=s,y.processChunk(d),y.flush(),v=y.getResult()}if(l.info(`[Gemini] Raw stdout length: ${G.length} chars`),l.info(`[Gemini] Extracted text length: ${d.length} chars`),l.info(`[Gemini] StreamParser result: ${v?"extracted":"null"}`),v||(d.length<2e3?l.info(`[Gemini] Raw text preview:
|
|
90
90
|
${d}`):l.info(`[Gemini] Raw text preview (first 1000 chars):
|
|
91
|
-
${d.slice(0,1e3)}`),v=Io(d)),!v)throw E||(l.error("[Gemini] Failed to extract valid JSON from output"),l.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 C=M?s.parse(v):v;return{raw:d,structured:C}}finally{for(let m of
|
|
92
|
-
`,"utf-8");let u=ee(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{
|
|
91
|
+
${d.slice(0,1e3)}`),v=Io(d)),!v)throw E||(l.error("[Gemini] Failed to extract valid JSON from output"),l.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 C=M?s.parse(v):v;return{raw:d,structured:C}}finally{for(let m of g)m.dispose()}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let r={};for(let o of e){let s=Ao(o);if(!s||typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let a=s.cursorKey||s.serverName||o,c={command:i.command};i.args?.length&&(c.args=i.args),i.env&&Object.keys(i.env).length>0&&(c.env=i.env),i.cwd&&(c.cwd=i.cwd),r[a]=c}return r}_createGeminiConfigDir(e,t){let r=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,o=ee(e||process.cwd(),".zibby","tmp",`gemini-home-${r}`),s=ee(o,".gemini");Ot(s,{recursive:!0});let i=ee(s,"settings.json"),a={},c=ee(process.env.HOME||"",".gemini","settings.json");if(St(c))try{a=JSON.parse(bt(c,"utf-8"))}catch{a={}}let f={...a,mcpServers:{...a.mcpServers&&typeof a.mcpServers=="object"?a.mcpServers:{},...t||{}}};Et(i,`${JSON.stringify(f,null,2)}
|
|
92
|
+
`,"utf-8");let u=ee(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{Et(u,`${JSON.stringify(f,null,2)}
|
|
93
93
|
`,"utf-8")}catch{}return l.debug(`[Gemini] Created isolated config with ${Object.keys(f.mcpServers||{}).length} MCP servers`),l.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(f.mcpServers||{}),null,2)}`),o}};import{AgentStrategy as Go,getSkill as Le}from"@zibby/agent-workflow";var Se=class{formatTools(e){throw new Error("formatTools() must be implemented")}hasToolCalls(e){throw new Error("hasToolCalls() must be implemented")}parseToolCalls(e){throw new Error("parseToolCalls() must be implemented")}getTextContent(e){throw new Error("getTextContent() must be implemented")}buildAssistantMessage(e){throw new Error("buildAssistantMessage() must be implemented")}buildToolResultMessage(e,t){throw new Error("buildToolResultMessage() must be implemented")}injectToolsIntoBody(e,t){throw new Error("injectToolsIntoBody() must be implemented")}};var ie=class extends Se{formatTools(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters||t.input_schema||{type:"object",properties:{}}}}))}hasToolCalls(e){let t=e.choices?.[0]?.message;return!!(t?.tool_calls&&t.tool_calls.length>0)}parseToolCalls(e){return(e.choices?.[0]?.message?.tool_calls||[]).map(r=>({id:r.id,name:r.function.name,args:JSON.parse(r.function.arguments||"{}")}))}getTextContent(e){return e.choices?.[0]?.message?.content||""}buildAssistantMessage(e){return e.choices?.[0]?.message}buildToolResultMessage(e,t){return{role:"tool",tool_call_id:e,content:typeof t=="string"?t:JSON.stringify(t)}}injectToolsIntoBody(e,t){return t.length>0&&(e.tools=t),e}};var Oe=class{async fetchCompletion(e,t,r={}){throw new Error("fetchCompletion() must be implemented")}async fetchStreamingCompletion(e,t,r={}){throw new Error("fetchStreamingCompletion() must be implemented")}};function ke(n){return Buffer.byteLength(JSON.stringify(n),"utf8")}function Pe(n,e){let t=String(n||"");if(t.length<=e)return t;let r=Math.max(0,e-28);return`${t.slice(0,r)}
|
|
94
94
|
|
|
95
|
-
[truncated for size budget]`}function Xe(n,e=0){if(!n||typeof n!="object"||e>8)return n;if(Array.isArray(n))return n.map(r=>Xe(r,e+1));let t={};for(let[r,o]of Object.entries(n))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=Xe(o,e+1));return t}function Co(n=[]){return n.map(e=>({...e,function:{...e.function,description:Pe(e.function?.description||"",180),parameters:Xe(e.function?.parameters||{type:"object",properties:{}})}}))}function
|
|
96
|
-
`);O=P.pop();for(let M of P){if(!M.startsWith("data: "))continue;let
|
|
95
|
+
[truncated for size budget]`}function Xe(n,e=0){if(!n||typeof n!="object"||e>8)return n;if(Array.isArray(n))return n.map(r=>Xe(r,e+1));let t={};for(let[r,o]of Object.entries(n))r==="description"||r==="title"||r==="examples"||r==="default"||(t[r]=Xe(o,e+1));return t}function Co(n=[]){return n.map(e=>({...e,function:{...e.function,description:Pe(e.function?.description||"",180),parameters:Xe(e.function?.parameters||{type:"object",properties:{}})}}))}function At(n){let e=new Set;for(let o of n)if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let s of o.tool_calls)e.add(s.id);let t=n.filter(o=>o.role==="tool"?e.has(o.tool_call_id):!0),r=new Set;for(let o of t)o.role==="tool"&&r.add(o.tool_call_id);return t.map(o=>{if(o.role!=="assistant"||!Array.isArray(o.tool_calls)||o.tool_calls.every(c=>r.has(c.id)))return o;let{tool_calls:i,...a}=o;return{...a,content:a.content||""}})}function Ve(n,e={}){let t=e.maxBytes||49e3,r=e.systemMaxChars||12e3,o={...n,messages:Array.isArray(n.messages)?[...n.messages]:[],tools:Array.isArray(n.tools)?Co(n.tools):n.tools};o.messages.length>0&&o.messages[0]?.role==="system"&&(o.messages[0]={...o.messages[0],content:Pe(o.messages[0].content,r)});let s=!1;for(;ke(o)>t&&o.messages.length>2;)o.messages.splice(1,1),s=!0;if(s&&(o.messages=At(o.messages)),ke(o)>t&&o.messages.length>0&&(o.messages[0]={...o.messages[0],content:Pe(o.messages[0].content,6e3)},s=!0),ke(o)>t){let i=o.messages.find(c=>c.role==="system")||o.messages[0],a=o.messages.slice(-2);o.messages=At([i,...a].filter(Boolean).map((c,f)=>({...c,content:Pe(c.content,f===0?4e3:8e3)}))),s=!0}return{body:o,meta:{bytes:ke(o),trimmed:s,maxBytes:t,messageCount:o.messages.length}}}var vt=n=>Buffer.byteLength(JSON.stringify(n),"utf8"),le=class extends Oe{async fetchCompletion(e,t,r={}){let o=vt(e),{body:s,meta:i}=Ve(e,r.payloadCompaction);r.onBudget?.({streaming:!1,beforeBytes:o,meta:i});let a=this.#e(r),c=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,f=await fetch(c,{method:"POST",headers:t.headers,body:JSON.stringify(s),signal:a});if(!f.ok){let u=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}: ${u}`)}return f.json()}async fetchStreamingCompletion(e,t,r={}){let o={...e,stream:!0},s=vt(o),{body:i,meta:a}=Ve(o,r.payloadCompaction);r.onBudget?.({streaming:!0,beforeBytes:s,meta:a});let c=this.#e(r),f=`${t.baseUrl}${r.chatCompletionsPath||"/v1/chat/completions"}`,u=await fetch(f,{method:"POST",headers:t.headers,body:JSON.stringify(i),signal:c});if(!u.ok){let _=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}: ${_}`)}let g=u.body.getReader(),m=new TextDecoder,O="",I="",k=new Map;for(;;){let{done:_,value:b}=await g.read();if(_)break;O+=m.decode(b,{stream:!0});let P=O.split(`
|
|
96
|
+
`);O=P.pop();for(let M of P){if(!M.startsWith("data: "))continue;let h=M.slice(6).trim();if(h==="[DONE]")continue;let U;try{U=JSON.parse(h)}catch{continue}let B=U.choices?.[0]?.delta;if(B&&(B.content&&(I+=B.content,r.onToken&&r.onToken(B.content)),B.tool_calls))for(let L of B.tool_calls){let S=L.index??0;k.has(S)||k.set(S,{id:"",name:"",args:""});let J=k.get(S);L.id&&(J.id=L.id),L.function?.name&&(J.name=L.function.name),L.function?.arguments!=null&&(J.args+=L.function.arguments)}}}if(k.size>0){let _=[...k.entries()].sort(([b],[P])=>b-P).map(([,b])=>({id:b.id,type:"function",function:{name:b.name,arguments:b.args}}));return{choices:[{message:{role:"assistant",content:I||null,tool_calls:_}}]}}return{choices:[{message:{role:"assistant",content:I}}]}}#e(e={}){let t=[e.signal,e.timeout?AbortSignal.timeout(e.timeout):null].filter(Boolean);return t.length>1?AbortSignal.any(t):t[0]||void 0}};import{Client as ko}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Po}from"@modelcontextprotocol/sdk/client/stdio.js";var Ne=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:r,args:o=[],env:s={}}=t;l.debug(`[MCP] Starting ${e}: ${r} ${o.join(" ")}`);let i=new Po({command:r,args:o,env:{...process.env,...s}}),a=new ko({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await a.connect(i);let c={client:a,transport:i,serverConfig:t};return this.#e.set(e,c),c}async callTool(e,t,r={}){let o=this.#e.get(e);if(!o)throw new Error(`MCP server "${e}" not running`);l.debug(`[MCP] ${e}.${t}(${JSON.stringify(r).slice(0,200)})`);let s=await o.client.callTool({name:t,arguments:r});return{text:s.content?.filter(a=>a.type==="text").map(a=>a.text).join(`
|
|
97
97
|
`)||"",isError:s.isError||!1}}isRunning(e){return this.#e.has(e)}async stopServer(e){let t=this.#e.get(e);if(t){try{await t.client.close()}catch(r){l.debug(`[MCP] Error closing ${e}: ${r.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}};import{existsSync as No,readFileSync as Mo}from"node:fs";import{join as Ro}from"node:path";import{homedir as Lo}from"node:os";function Do(){try{let n=Ro(Lo(),".zibby","config.json");return No(n)?JSON.parse(Mo(n,"utf-8")):{}}catch{return{}}}function Me(n){return String(n||"").replace(/\/v1\/?$/,"")}function Uo(n,e){let t=process.env.OPENAI_PROXY_URL;if(t)return Me(t);if(n==="session")return e.proxyUrl?Me(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(n==="byok"){let r=process.env.OPENAI_BASE_URL;return Me(r||"https://api.openai.com")}return Me(t||"")}function We(){let n=Do(),e=process.env.ZIBBY_USER_TOKEN||n.sessionToken||null,t=process.env.OPENAI_API_KEY||null,r=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),o=process.env.OPENAI_PROXY_NO_AUTH==="true",s=process.env.OPENAI_PROXY_URL,i="session";r==="byok"||r==="local"||r==="session"?i=r:e?i="session":t?i="byok":s&&o&&(i="local");let a=Uo(i,n),c={"Content-Type":"application/json"};if(i==="session"){if(!e)return{ok:!1,mode:i,reason:"missing_session_token"};c.Authorization=`Bearer ${e}`}else if(i==="byok"){if(!t)return{ok:!1,mode:i,reason:"missing_openai_api_key"};c.Authorization=`Bearer ${t}`}else if(i==="local"){if(!a)return{ok:!1,mode:i,reason:"missing_openai_proxy_url"};!o&&t&&(c.Authorization=`Bearer ${t}`)}return a?{ok:!0,mode:i,baseUrl:a,headers:c,tokenPreview:c.Authorization?`***${c.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:i,reason:"missing_base_url"}}function Re(n,e){let t=String(n??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
|
|
98
98
|
|
|
99
|
-
[tool result truncated for size]`}function Bo(n,e){if(typeof n=="string")return Re(n,e);try{return Re(JSON.stringify(n),e)}catch{return Re(String(n),e)}}function
|
|
100
|
-
\u{1F4D6} get_skill_context("${f}") \u2192 ${O.length} chars (fragment: ${
|
|
101
|
-
`)),O}let a=s?.get(e.name)||null;if(!a)return`Unknown tool: ${e.name}`;let c=Le(a.skillId);if(!c)return`Skill "${a.skillId}" not found for tool "${e.name}"`;if(a.mode==="handler")try{return c.handleToolCall(e.name,e.args,t)}catch(f){return`Error in ${e.name}: ${f.message}`}if(a.mode==="mcp")try{if(!this.#o.isRunning(c.serverName)){let u=c.resolve(o);if(!u)return`Skill "${a.skillId}" is not available (cannot start server)`;await this.#o.ensureServer(c.serverName,u)}let f=await this.#o.callTool(c.serverName,e.name,e.args);return f.text||(f.isError?"Tool call failed":"Done")}catch(f){return`MCP error (${c.serverName}): ${f.message}`}return`Skill "${a.skillId}" owns tool "${e.name}" but has no execution mode`}async#a(e,t,r){return this.#t.fetchStreamingCompletion(e,t,{...r,onBudget:({beforeBytes:o,meta:s})=>{ae()&&console.log(`payload bytes (stream) before=${o} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#s(e,t,r){return this.#t.fetchCompletion(e,t,{...r,onBudget:({beforeBytes:o,meta:s})=>{ae()&&console.log(`payload bytes before=${o} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#c(e,t,r,o){let{zodToJson:s}=await Promise.resolve().then(()=>(ge(),mt)),i=typeof o.schema?.parse=="function",a=i?s(o.schema,{}):o.schema;delete a.$schema,ce(a);let c={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:a,strict:!0}}},f=await this.#s(c,r,o),u=this.#e.getTextContent(f),
|
|
99
|
+
[tool result truncated for size]`}function Bo(n,e){if(typeof n=="string")return Re(n,e);try{return Re(JSON.stringify(n),e)}catch{return Re(String(n),e)}}function wt(n){let e=new Set;for(let o of n)if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let s of o.tool_calls)e.add(s.id);let t=n.filter(o=>o.role==="tool"?e.has(o.tool_call_id):!0),r=new Set;for(let o of t)o.role==="tool"&&r.add(o.tool_call_id);return t.map(o=>{if(o.role!=="assistant"||!Array.isArray(o.tool_calls)||o.tool_calls.every(c=>r.has(c.id)))return o;let{tool_calls:i,...a}=o;return{...a,content:a.content||""}})}function Jo(n){let e=Array.isArray(n?.messages)?n.messages:[],t=e.find(s=>s.role==="system"),r=e.slice(-4).map(s=>({...s,content:Re(s.content,s.role==="tool"?1200:2500)}));r=wt(r);let o={...n,messages:[t,...r].filter(Boolean)};return delete o.tools,o}async function Ko({body:n,streaming:e,auth:t,options:r,fetchCompletion:o,fetchStreamingCompletion:s,onFallbackLog:i}){try{return e?await s(n,t,r):await o(n,t,r)}catch(a){let c=String(a?.message||a||"");if(!/proxy error 413|payload too large/i.test(c))throw a;let f=Jo(n);return typeof i=="function"&&i(n,f),{data:e?await s(f,t,r):await o(f,t,r),fallback:f}}}async function xt({body:n,auth:e,options:t,streaming:r,toolContext:o,activeSkills:s,round:i,verbose:a,dependencies:c,config:f={}}){let u=f.maxToolResultChars||3e3,{fetchCompletion:g,fetchStreamingCompletion:m,onFallbackLog:O,hasToolCalls:I,getTextContent:k,parseToolCalls:_,buildAssistantMessage:b,buildToolResultMessage:P,executeTool:M,onToolCallLog:h,injectTools:U}=c;Array.isArray(n?.messages)&&(n.messages=wt(n.messages));let B=await Ko({body:n,streaming:r,auth:e,options:t,fetchCompletion:g,fetchStreamingCompletion:m,onFallbackLog:O}),L=B?.data||B;if(!I(L))return{done:!0,text:k(L),body:B?.fallback||n};let S=_(L),J=B?.fallback||n;J.messages.push(b(L)),a&&typeof h=="function"&&h(S);let D=await Promise.all(S.map((R,A)=>(typeof t.onToolCall=="function"&&t.onToolCall(R.name,R.args,{round:i,index:A,total:S.length}),M(R,o))));for(let R=0;R<S.length;R++){let $=S[R].name==="get_skill_context"?typeof D[R]=="string"?D[R]:JSON.stringify(D[R]):Bo(D[R],u);J.messages.push(P(S[R].id,$))}return typeof t.onToolCall=="function"&&t.onToolCall(null),U(J,s),{done:!1,body:J}}var jo=F.ASSISTANT,Fo=15,Ze="get_skill_context";function ce(n){!n||typeof n!="object"||(n.type==="object"&&n.properties&&(n.required=Object.keys(n.properties),n.additionalProperties=!1,Object.values(n.properties).forEach(ce)),n.type==="array"&&n.items&&ce(n.items),n.anyOf&&n.anyOf.forEach(ce),n.oneOf&&n.oneOf.forEach(ce),n.allOf&&n.allOf.forEach(ce))}var Tt={maxBytes:49e3,systemMaxChars:12e3},ae=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Yo=n=>Buffer.byteLength(JSON.stringify(n),"utf8");function De(n){return Array.isArray(n)?new Set(n.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function zo(n){return Array.isArray(n)?n.map(e=>String(e||"").trim()).filter(Boolean):[]}var Ue=class extends Go{#e;#t;#o=new Ne;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new ie,this.#t=e.completionProvider||new le):(this.#e=e||new ie,this.#t=new le)}canHandle(e){return We().ok}async invoke(e,t={}){let r=Y("OPENAI_API_KEY");try{let o=t.model&&t.model!=="auto"?t.model:jo,s=We();if(!s.ok)throw s.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):s.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):s.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${s.reason}).`);let i=t.messages||[{role:"user",content:e}],a=s.baseUrl,c=ae();if(c?await this.#m(i,o,a,s.tokenPreview||"none"):l.debug(`[Assistant] ${a} | model: ${o} | messages: ${i.length}`),t.schema)return this.#c(o,i,s,t);let f=t.activeSkills||[],u=this.#f(t),g=this.#d(f,u),m=this.#p(g),O=this.#u(t),I={...t,payloadCompaction:O},k={activeSkills:g,options:I,executionRegistry:m,capabilityPolicy:u},_=!!t.stream,b={model:o,messages:[...i],stream:!1};this.#n(b,g,u);for(let P=0;P<Fo;P++){if(t.signal?.aborted){let h=new Error("Aborted via signal");throw h.name="AbortError",h}let M=await xt({body:b,auth:s,options:I,streaming:_,toolContext:k,activeSkills:g,round:P,verbose:c,dependencies:{fetchCompletion:this.#s.bind(this),fetchStreamingCompletion:this.#a.bind(this),onFallbackLog:(h,U)=>{ae()&&console.log(`413 fallback: messages ${h.messages.length} -> ${U.messages.length}, bytes=${Yo(U)}`)},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,U)=>this.#e.buildToolResultMessage(h,U),executeTool:(h,U)=>this.#l(h,U),onToolCallLog:async h=>{let U=(await import("chalk")).default;console.log(U.dim(` ${h.map(B=>`${B.name}(${JSON.stringify(B.args).slice(0,80)})`).join(", ")}`))},injectTools:(h,U)=>this.#n(h,U,u)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(M.done)return M.text;b.messages=M.body.messages,M.body.tools?b.tools=M.body.tools:delete b.tools}return"I hit my tool-calling limit for this turn. Please try again."}finally{r.dispose()}}async cleanup(){await this.#o.stopAll()}#n(e,t,r=null){let o=this.#i(t,r),s=this.#e.formatTools(o);this.#e.injectToolsIntoBody(e,s)}#i(e,t=null){let r=[],o=new Set;for(let s of e){let i=Le(s);if(i?.tools?.length)for(let a of i.tools)this.#r(a.name,t)&&(o.has(a.name)||(o.add(a.name),r.push({name:a.name,description:a.description,parameters:a.parameters||a.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#r(Ze,t)&&r.push({name:Ze,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),r}async#l(e,t){let{activeSkills:r,options:o,executionRegistry:s,capabilityPolicy:i}=t;if(!this.#r(e.name,i))return`Tool "${e.name}" blocked by policy`;if(e.name===Ze){let f=String(e.args?.skillId||"").trim();if(!f)return JSON.stringify({error:"skillId is required"});if(!r.includes(f))return JSON.stringify({error:`Skill "${f}" is not active`,activeSkills:r});let u=Le(f);if(!u)return JSON.stringify({error:`Skill "${f}" not found`});let g=typeof u.promptFragment=="function"?u.promptFragment():u.promptFragment||"",m=(u.tools||[]).map(I=>I.name),O=JSON.stringify({skillId:f,description:u.description||"",toolNames:m,promptFragment:g||""});return ae()&&(console.log(`
|
|
100
|
+
\u{1F4D6} get_skill_context("${f}") \u2192 ${O.length} chars (fragment: ${g.length} chars)`),console.log(` tools: [${m.join(", ")}]`),console.log(` fragment preview: ${g.slice(0,200).replace(/\n/g,"\\n")}\u2026
|
|
101
|
+
`)),O}let a=s?.get(e.name)||null;if(!a)return`Unknown tool: ${e.name}`;let c=Le(a.skillId);if(!c)return`Skill "${a.skillId}" not found for tool "${e.name}"`;if(a.mode==="handler")try{return c.handleToolCall(e.name,e.args,t)}catch(f){return`Error in ${e.name}: ${f.message}`}if(a.mode==="mcp")try{if(!this.#o.isRunning(c.serverName)){let u=c.resolve(o);if(!u)return`Skill "${a.skillId}" is not available (cannot start server)`;await this.#o.ensureServer(c.serverName,u)}let f=await this.#o.callTool(c.serverName,e.name,e.args);return f.text||(f.isError?"Tool call failed":"Done")}catch(f){return`MCP error (${c.serverName}): ${f.message}`}return`Skill "${a.skillId}" owns tool "${e.name}" but has no execution mode`}async#a(e,t,r){return this.#t.fetchStreamingCompletion(e,t,{...r,onBudget:({beforeBytes:o,meta:s})=>{ae()&&console.log(`payload bytes (stream) before=${o} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#s(e,t,r){return this.#t.fetchCompletion(e,t,{...r,onBudget:({beforeBytes:o,meta:s})=>{ae()&&console.log(`payload bytes before=${o} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#c(e,t,r,o){let{zodToJson:s}=await Promise.resolve().then(()=>(ge(),mt)),i=typeof o.schema?.parse=="function",a=i?s(o.schema,{}):o.schema;delete a.$schema,ce(a);let c={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:a,strict:!0}}},f=await this.#s(c,r,o),u=this.#e.getTextContent(f),g=JSON.parse(u),m=i?o.schema.parse(g):g;return{raw:u,structured:m}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||Tt.maxBytes),systemMaxChars:Number(t.systemMaxChars||Tt.systemMaxChars)}}#f(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:De(t.allowTools||e.allowTools),denyTools:De(t.denyTools||e.denyTools),denyPrefixes:zo(t.denyPrefixes||e.denyToolPrefixes),includeSkills:De(t.includeSkills||e.includeSkills),excludeSkills:De(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#d(e,t){let r=t?.includeSkills||new Set,o=t?.excludeSkills||new Set;return r.size===0&&o.size===0?e:e.filter(s=>!(r.size>0&&!r.has(s)||o.has(s)))}#r(e,t){let r=String(e||"").trim();if(!r)return!1;let o=t?.allowTools;if(o&&o.size>0&&!o.has(r))return!1;let s=t?.denyTools;return!(s&&s.has(r)||(t?.denyPrefixes||[]).some(a=>r.startsWith(a)))}#p(e){let t=new Map,r=[];for(let o of e){let s=Le(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 c=String(a?.name||"").trim();if(c){if(t.has(c)){r.push({tool:c,winner:t.get(c).skillId,skipped:o});continue}t.set(c,{skillId:o,mode:i})}}}if(r.length>0&&ae()){let o=r.slice(0,5).map(s=>`${s.tool}:${s.winner}>${s.skipped}`).join(", ");console.log(`tool registry collisions: ${o}${r.length>5?" ...":""}`)}return t}async#m(e,t,r,o){console.log(`
|
|
102
102
|
\u25C6 Model: ${t} | proxy: ${r} | token: ${o||"none"}
|
|
103
|
-
`);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 c=a.role==="user"?"Human":"AI",f=a.content?.length>200?`${a.content.slice(0,200)}...`:a.content||"";console.log(s.dim(`[${c}] ${f}`))}console.log(s.dim("\u2500".repeat(60)))}};var
|
|
103
|
+
`);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 c=a.role==="user"?"Human":"AI",f=a.content?.length>200?`${a.content.slice(0,200)}...`:a.content||"";console.log(s.dim(`[${c}] ${f}`))}console.log(s.dim("\u2500".repeat(60)))}};var It=!1;function ss(){It||(be(new Ue),be(new xe),be(new Ie),be(new $e),be(new Ce),It=!0)}export{ss as registerBuiltInStrategies};
|