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