@zibby/core 0.1.38 → 0.1.40
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/agents/base.js +47 -40
- package/dist/framework/agents/cursor-strategy.js +29 -22
- package/dist/framework/agents/gemini-strategy.js +11 -11
- package/dist/framework/agents/index.js +45 -38
- package/dist/framework/agents/utils/cursor-output-formatter.js +2 -2
- package/dist/framework/agents/utils/structured-output-formatter.js +1 -1
- package/dist/framework/code-generator.js +33 -26
- package/dist/framework/graph-compiler.js +47 -40
- package/dist/framework/graph.js +50 -43
- package/dist/framework/index.js +23 -16
- package/dist/framework/node-registry.js +39 -32
- package/dist/framework/node.js +43 -36
- package/dist/index.js +47 -40
- package/dist/package.json +1 -1
- package/package.json +1 -1
package/dist/framework/node.js
CHANGED
|
@@ -14,7 +14,7 @@ ${et}`,e.col=tt))}return n(i,o,r)}}var Zt,ie,Xt,qe,ke,Ve,Qe,Ne,et,tt,Pe,j,le=R((
|
|
|
14
14
|
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Xt} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:o,details:r}=t;if(r)for(let i of r)this._rawWrite(`${ke} ${i}`);let s=o?D.dim(` ${rt(o)}`):"";this._rawWrite(`${qe} ${D.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,o={}){this._stopIntercepting();let{duration:r}=o,s=r?D.dim(` ${rt(r)}`):"";this._rawWrite(`${Ne} ${D.red(t)}`),this._rawWrite(`${qe} ${D.red("failed")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(D.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){this._rawWrite(D.green.bold("\u2713 Workflow completed"))}},j=new Pe});var st,ae,nt,Re=R(()=>{st=".zibby/output",ae=".session-info.json",nt=".zibby-studio-stop"});var J,z=R(()=>{J=class{constructor(e,t,o=0){this.name=e,this.description=t,this.priority=o}async invoke(e,t={}){throw new Error("AgentStrategy.invoke() must be implemented by subclass")}canHandle(e){throw new Error("AgentStrategy.canHandle() must be implemented by subclass")}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var U,Me,Le,it,we,H=R(()=>{U={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"},Me={auto:"claude-sonnet-4-6","sonnet-4.6":"claude-sonnet-4-6","sonnet-4-6":"claude-sonnet-4-6","opus-4.6":"claude-opus-4-6","opus-4-6":"claude-opus-4-6","sonnet-4.5":"claude-sonnet-4-5-20250929","sonnet-4-5":"claude-sonnet-4-5-20250929","opus-4.5":"claude-opus-4-20250514","opus-4-5":"claude-opus-4-20250514","claude-sonnet-4-6":"claude-sonnet-4-6","claude-opus-4-6":"claude-opus-4-6","claude-sonnet-4-5-20250929":"claude-sonnet-4-5-20250929","claude-opus-4-20250514":"claude-opus-4-20250514"},Le={auto:"o4-mini","o4-mini":"o4-mini",o3:"o3","o3-mini":"o3-mini","codex-mini":"codex-mini-latest","gpt-4o":"gpt-4o","gpt-4o-mini":"gpt-4o-mini","gpt-5.2-codex":"gpt-5.2-codex","gpt-5.2":"gpt-5.2","gpt-5.3":"gpt-5.3","gpt-5.4":"gpt-5.4"},it={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},we={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4}});var lt={};Xe(lt,{getAllSkills:()=>De,getSkill:()=>B,hasSkill:()=>Vt,listSkillIds:()=>Qt,registerSkill:()=>qt});function qt(n){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");ce.set(n.id,Object.freeze({...n}))}function B(n){return ce.get(n)||null}function Vt(n){return ce.has(n)}function De(){return new Map(ce)}function Qt(){return Array.from(ce.keys())}var ce,Z=R(()=>{ce=new Map});var V,Ue=R(()=>{V=class n{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(e){if(!e)return null;this.buffer+=e;let t=this.buffer.split(`
|
|
15
15
|
`);this.buffer=t.pop()||"";let o="";for(let r of t)if(r.trim())try{let s=JSON.parse(r);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+=`${r}
|
|
16
16
|
`,o+=`${r}
|
|
17
|
-
`,this.extractedResult=s)}catch{if(r.includes('"text"')||r.includes('"content"')){let i=r.match(/"text"\s*:\s*"([^"]*)/),l=r.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],u=i[c],
|
|
17
|
+
`,this.extractedResult=s)}catch{if(r.includes('"text"')||r.includes('"content"')){let i=r.match(/"text"\s*:\s*"([^"]*)/),l=r.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],u=i[c],d=u&&typeof u=="object"?u.args??u.input??u:void 0;t(c,o(d))}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 r=e.message??e;if(Array.isArray(r?.tool_calls)){for(let i of r.tool_calls)t(i.name,o(i.input??i.arguments));return}let s=r?.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,r;for(;(r=o.exec(e))!==null;){let p=r[1].trim();try{JSON.parse(p),t.push({text:p,source:"markdown"})}catch{}}let s=0,i=0;for(;s<e.length&&(s=e.indexOf("{",s),s!==-1);){let p=0,m=s;for(let S=s;S<e.length;S++)if(e[S]==="{")p++;else if(e[S]==="}"&&(p--,p===0)){m=S,t.push({text:e.substring(s,m+1),source:"brace"}),i++;break}s=m+1}let l=this.extractedResult,c=l?JSON.stringify(l).length:0,u=0,d=-1;for(let p=0;p<t.length;p++){let m=t[p];try{let S=m.text.replace(/,(\s*[}\]])/g,"$1"),A=JSON.parse(S);this.isValidResult(A)&&(u++,c=JSON.stringify(A).length,l=A,d=p)}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 n;o.zodSchema=t,o.processChunk(e),o.flush();let r=o.getResult();return!r&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),r}}});import{zodToJsonSchema as er}from"zod-to-json-schema";var Q,Be=R(()=>{Q=class{static generateFileOutputInstructions(e,t){let o;typeof e?.parse=="function"?o=er(e,{target:"openApi3"}):o=e;let r=this._buildExample(o);return`
|
|
18
18
|
\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
|
|
19
19
|
\u{1F6A8} MANDATORY: WRITE RESULT TO FILE \u{1F6A8}
|
|
20
20
|
\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
|
|
@@ -34,18 +34,18 @@ JSON types (strict \u2014 validators reject wrong types):
|
|
|
34
34
|
- Use true/false without quotes for booleans.
|
|
35
35
|
- Use unquoted null where a field may be null.
|
|
36
36
|
|
|
37
|
-
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[r,s]of Object.entries(e.properties))o[r]=this._buildExample(s);return o}if(t==="array"&&e.items)return[this._buildExample(e.items)];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(r=>r.type!=="null")||e.anyOf?.find(r=>r.type!=="null");return o?this._buildExample(o):null}return"<value>"}}});import tr from"axios";import{homedir as rr}from"node:os";import{join as or}from"node:path";import{existsSync as sr,readFileSync as nr}from"node:fs";import{toJSONSchema as ir}from"zod";function lr(){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 n=or(rr(),".zibby","config.json");if(sr(n)){let e=JSON.parse(nr(n,"utf-8"));if(e.sessionToken)return a.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(n){a.debug(`[Auth] Could not read zibby login session: ${n.message}`)}return null}function ar(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function ee(n){if(!(typeof n!="object"||n===null)){if(Object.keys(n).length===0){n.type="object",n.additionalProperties=!0;return}if(n.type||(n.properties?n.type="object":n.items&&(n.type="array")),n.type==="object")if(n.properties){for(let[e,t]of Object.entries(n.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(n.properties[e]={type:["object","null"]});n.additionalProperties=!1,n.required=Object.keys(n.properties),Object.values(n.properties).forEach(ee)}else"additionalProperties"in n||(n.additionalProperties=!0);n.type==="array"&&n.items&&ee(n.items),n.anyOf&&n.anyOf.forEach(ee),n.oneOf&&n.oneOf.forEach(ee),n.allOf&&n.allOf.forEach(ee)}}async function at(n,e){a.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=lr();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=ar();a.info(`\u{1F517} Using OpenAI proxy: ${o}`);let r=ir(e),s=r;if(r.$ref&&r.definitions){let
|
|
37
|
+
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[r,s]of Object.entries(e.properties))o[r]=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(r=>r.type!=="null")||e.anyOf?.find(r=>r.type!=="null");return o?this._buildExample(o):null}return"<value>"}}});import tr from"axios";import{homedir as rr}from"node:os";import{join as or}from"node:path";import{existsSync as sr,readFileSync as nr}from"node:fs";import{toJSONSchema as ir}from"zod";function lr(){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 n=or(rr(),".zibby","config.json");if(sr(n)){let e=JSON.parse(nr(n,"utf-8"));if(e.sessionToken)return a.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(n){a.debug(`[Auth] Could not read zibby login session: ${n.message}`)}return null}function ar(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function ee(n){if(!(typeof n!="object"||n===null)){if(Object.keys(n).length===0){n.type="object",n.additionalProperties=!0;return}if(n.type||(n.properties?n.type="object":n.items&&(n.type="array")),n.type==="object")if(n.properties){for(let[e,t]of Object.entries(n.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(n.properties[e]={type:["object","null"]});n.additionalProperties=!1,n.required=Object.keys(n.properties),Object.values(n.properties).forEach(ee)}else"additionalProperties"in n||(n.additionalProperties=!0);n.type==="array"&&n.items&&ee(n.items),n.anyOf&&n.anyOf.forEach(ee),n.oneOf&&n.oneOf.forEach(ee),n.allOf&&n.allOf.forEach(ee)}}async function at(n,e){a.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=lr();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=ar();a.info(`\u{1F517} Using OpenAI proxy: ${o}`);let r=ir(e),s=r;if(r.$ref&&r.definitions){let d=r.$ref.split("/").pop();s=r.definitions[d]||r,a.debug(`Extracted schema from $ref: ${d}`)}delete s.$schema,ee(s);let i=4e5,l=n;n.length>i&&(a.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${n.length} chars) exceeds limit, keeping last ${i} chars`),l=`... [truncated early content] ...
|
|
38
38
|
${n.slice(-i)}`);let c=`Extract and format the following information into structured JSON matching the schema.
|
|
39
39
|
|
|
40
40
|
RAW CONTENT:
|
|
41
41
|
${l}
|
|
42
42
|
|
|
43
|
-
Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,u={model:U.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=${U.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
|
|
43
|
+
Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,u={model:U.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=${U.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 d={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(d["x-proxy-token"]=t,d["x-execution-id"]=process.env.EXECUTION_ID||""):(d.Authorization=`Bearer ${t}`,d["x-api-key"]=process.env.ZIBBY_API_KEY||"",d["x-execution-id"]=process.env.EXECUTION_ID||"");let m=(await tr.post(o,u,{headers:d,timeout:we.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!m)throw new Error("OpenAI proxy returned empty response");let S=JSON.parse(m);return a.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:S,raw:n}}catch(d){if(d.response){let p=d.response.status,m=d.response.data;throw a.error(`\u274C OpenAI proxy request failed: ${p}`),a.error(` Status: ${p}`),a.error(` Response: ${JSON.stringify(m,null,2)}`),p===401||p===403?new Error(`Authentication failed for OpenAI proxy.
|
|
44
44
|
Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
|
|
45
|
-
Response: ${JSON.stringify(m)}`,{cause:
|
|
45
|
+
Response: ${JSON.stringify(m)}`,{cause:d}):new Error(`Failed to format Cursor output: ${m?.error?.message||"Unknown error"}`,{cause:d})}throw a.error(`\u274C OpenAI proxy request failed: ${d.message}`),new Error(`Failed to format output: ${d.message}`,{cause:d})}}var ct=R(()=>{W();H()});import{copyFileSync as cr,existsSync as Je,lstatSync as ur,mkdirSync as ut,rmSync as fr,symlinkSync as dr,unlinkSync as pr}from"node:fs";import{join as Y}from"node:path";import{homedir as mr}from"node:os";import{randomBytes as gr}from"node:crypto";function ft(n){return!(!n||typeof n!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function dt(n){let e=Y(n||process.cwd(),".zibby","tmp");ut(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${gr(4).toString("hex")}`,o=Y(e,`cursor-agent-home-${t}`),r=Y(o,".cursor");ut(r,{recursive:!0});let s=mr(),i=Y(s,".cursor");if(Je(i))for(let l of hr){let c=Y(i,l);if(Je(c))try{cr(c,Y(r,l))}catch{}}if(process.platform==="darwin"){let l=Y(s,"Library");if(Je(l))try{dr(l,Y(o,"Library"))}catch{}}return o}function pt(n){if(!(!n||typeof n!="string"))try{let e=Y(n,"Library");try{ur(e).isSymbolicLink()&&pr(e)}catch{}fr(n,{recursive:!0,force:!0})}catch{}}var hr,mt=R(()=>{hr=["cli-config.json","config.json","auth.json","argv.json"]});import{spawn as yr,execSync as X}from"node:child_process";import{writeFileSync as gt,readFileSync as ht,mkdirSync as yt,existsSync as ue,accessSync as St,constants as _t,unlinkSync as Sr}from"node:fs";import{join as F,resolve as _r}from"node:path";import{homedir as fe}from"node:os";var de,wt=R(()=>{z();W();H();Re();Z();Ue();Be();ct();le();mt();de=class extends J{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[F(fe(),".local","bin","cursor-agent"),F(fe(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"];for(let o of t)try{if(o.startsWith("/")){St(o,_t.X_OK);let r=X(`"${o}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(r&&r.length>0)return a.debug(`[Cursor] Found agent at: ${o} (version: ${r.trim().slice(0,50)})`),!0}else{let r=X(`which ${o}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!r)continue;let s=X(`${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 ${r} (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:r=!1,schema:s=null,skills:i=null,sessionPath:l=null,nodeName:c=null,timeout:u=we.CURSOR_AGENT_DEFAULT,config:d={}}=t,p=d?.agent?.strictMode||!1,m=t.model??d?.agent?.cursor?.model??U.CURSOR;a.debug(`[Cursor] Invoking (model: ${m}, timeout: ${u/1e3}s, skills: ${JSON.stringify(i)})`);let A=(this._setupMcpConfig(l,o,d,i,c)||{}).isolatedMcpHome??null,k=[F(fe(),".local","bin","cursor-agent"),F(fe(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],h=null;for(let O of k)try{if(O.startsWith("/"))St(O,_t.X_OK),X(`"${O}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!X(`which ${O}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");X(`${O} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}h=O,a.debug(`[Agent] Using binary: ${O}`);break}catch(g){a.debug(`[Agent] Binary '${O}' check failed: ${g.message}`);continue}if(!h)throw new Error(`Cursor Agent CLI not found or not working.
|
|
46
46
|
|
|
47
47
|
Checked paths:
|
|
48
|
-
${k.map(
|
|
48
|
+
${k.map(O=>` - ${O}`).join(`
|
|
49
49
|
`)}
|
|
50
50
|
|
|
51
51
|
Install cursor-agent:
|
|
@@ -54,52 +54,59 @@ Install cursor-agent:
|
|
|
54
54
|
Then add to PATH:
|
|
55
55
|
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
|
|
56
56
|
|
|
57
|
-
Test with: agent --version`);let _=null;if(s){let
|
|
57
|
+
Test with: agent --version`);let _=null;if(s){let O=`zibby-result-${Date.now()}.json`;_=F(o,".zibby","tmp",O);let g=F(o,".zibby","tmp");ue(g)||yt(g,{recursive:!0});let x=Q.generateFileOutputInstructions(s,_);e=`${e}
|
|
58
58
|
|
|
59
|
-
${x}`}let
|
|
59
|
+
${x}`}let b=process.env.CURSOR_API_KEY,E=b?` | key: ***${b.slice(-4)}`:" | key: not set";console.log(`
|
|
60
60
|
\u25C6 Model: ${m||"auto"}${E}
|
|
61
61
|
`);let w=(await import("chalk")).default;console.log(`
|
|
62
62
|
${w.bold("Prompt sent to LLM:")}`),console.log(w.dim("\u2500".repeat(60))),console.log(w.dim(e)),console.log(w.dim("\u2500".repeat(60)));let P=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",m||"auto"];if(process.env.CURSOR_API_KEY&&P.push("--api-key",process.env.CURSOR_API_KEY),P.push(e),a.debug(`[Agent] Prompt: ${e.length} chars, model: ${m||"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 ${m||"auto"} (from .zibby.config.js agent.cursor.model)
|
|
63
|
-
`)}catch{}let N,y=null;try{let
|
|
64
|
-
`)
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
${
|
|
68
|
-
|
|
69
|
-
|
|
63
|
+
`)}catch{}let N,y=null;try{let O=l||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);N=await this._spawnWithStreaming(h,P,o,u,null,O,A)}catch(O){y=O}let T=N?.stdout||"";if(s){let O=typeof s.parse=="function",g=null,x=!!(_&&ue(_));if(_&&a.info(`[Agent] Result file: ${x?"present":"missing"} at ${_}`),x)try{let f=ht(_,"utf-8").trim();g=JSON.parse(f),a.info(`[Agent] Parsed JSON from result file OK (${f.length} chars) \u2192 object ready for validation`),y&&a.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(f){a.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${f.message}`)}else if(y)a.warn(`[Agent] Result file missing at ${_} (agent process error \u2014 may still recover if strictMode repairs)`);else throw a.error(`\u274C [Agent] Result file was never created at ${_}`),new Error(`Agent did not write required result file at ${_}`);if(g&&O)try{let f=s.parse(g);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:T,structured:f}}catch(f){let v=f.issues?f.issues.map(C=>` - ${C.path.join(".")}: ${C.message}`).join(`
|
|
64
|
+
`):f.message?.slice(0,400);if(a.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
|
|
65
|
+
${v}`),a.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
|
|
66
|
+
${JSON.stringify(g,null,2).slice(0,500)}`),!p)throw new Error(`Agent output failed schema validation:
|
|
67
|
+
${v}
|
|
68
|
+
|
|
69
|
+
The agent wrote invalid data that doesn't match the required outputSchema.
|
|
70
|
+
Enable strictMode in .zibby.config.js for automatic repair.`,{cause:f})}else{if(g)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:T,structured:g};x&&a.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(p&&!y){let f=N.parsedText,v=g?JSON.stringify(g):f;a.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${v.length} chars in)`);try{let C=await at(v,s);if(O){let M=s.parse(C.structured);return a.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:T,structured:M}}return{raw:T,...C}}catch(C){if(a.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${C.message}`),g)return a.warn("[Agent] Using agent's original result file as fallback"),{raw:T,structured:g}}}if(y)throw y;let I=x?g==null?"file existed but JSON.parse failed \u2014 see WARN log above":O?"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: ${I}`),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 ${_}. Enable strictMode for proxy fallback.`)}if(y)throw y;return this._extractFinalResult(T)||N?.parsedText||T}_extractFinalResult(e){if(!e)return null;let t=e.split(`
|
|
71
|
+
`),o=null;for(let r of t){let s=r.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(u=>u.type==="text"&&u.text).map(u=>u.text).join("");c&&(o=c)}else typeof l=="string"&&l&&(o=l)}}catch{}}return o?.trim()||null}_setupMcpConfig(e,t,o,r=null,s=null){let i=o?.headless,l=F(fe(),".cursor"),c=F(l,"mcp.json"),u={};if(ue(c))try{u=JSON.parse(ht(c,"utf-8"))}catch{}let d=u.mcpServers||{},p=o?.paths?.output||st,m=F(t||process.cwd(),p,ae),S=Array.isArray(r)?r.map(h=>B(h)).filter(Boolean):[...De()].map(([,h])=>h),A=new Set;for(let h of S)typeof h.resolve=="function"&&(A.has(h.serverName)||(A.add(h.serverName),this._ensureSkillConfigured(d,h,e,m,s,i)));if(e){let h=B("browser");h&&typeof h.resolve=="function"&&!A.has(h.serverName)&&this._ensureSkillConfigured(d,h,e,m,"execute_live",i)}if(Object.keys(d).length===0)return a.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let k=`${JSON.stringify({mcpServers:d},null,2)}
|
|
72
|
+
`;if(ft(e)){let h=dt(t||process.cwd()),_=F(h,".cursor","mcp.json");return gt(_,k,"utf8"),a.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${h} | servers: ${Object.keys(d).join(", ")}`),{isolatedMcpHome:h}}return ue(l)||yt(l,{recursive:!0}),gt(c,k,"utf8"),a.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(d).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,o,r,s=null,i){let l=t.cursorKey||t.serverName,c=e[l]?l:e[t.serverName]?t.serverName:null;if(c&&o){let d=typeof t.resolve=="function"?t.resolve({sessionPath:o,nodeName:s,headless:i}):null;d?.args?e[c].args=d.args:e[c].args=(e[c].args||[]).map(S=>S.startsWith("--output-dir=")?`--output-dir=${o}`:S);let p=d?.env||{},m=t.sessionEnvKey?{[t.sessionEnvKey]:r}:{};e[c].env={...e[c].env||{},...p,...m},a.debug(`[MCP] Updated ${c} session \u2192 ${o}`);return}if(c)return;let u=t.resolve({sessionPath:o,nodeName:s,headless:i});u&&(e[l]={...u,...t.sessionEnvKey&&{env:{...u.env||{},[t.sessionEnvKey]:r}}},a.debug(`[MCP] Configured ${l}`))}_spawnWithStreaming(e,t,o,r,s=null,i=null,l=null){return new Promise((c,u)=>{let d=Date.now(),p="",m="",S=Date.now(),A=0,k=!1,h=null,_=!1,b=!1,E=null;if(i)try{E=F(_r(String(i)),nt)}catch{E=null}let w=!1,P=()=>{w||(w=!0,pt(l))},N={...process.env};l&&(N.HOME=l,process.platform==="win32"&&(N.USERPROFILE=l),a.debug(`[Agent] cursor-agent HOME=${l} (isolated MCP config)`));let y=yr(e,t,{cwd:o,shell:!1,stdio:["pipe","pipe","pipe"],env:N});a.debug(`[Agent] PID: ${y.pid}`),y.stdin.on("error",f=>{f.code!=="EPIPE"&&a.warn(`[Agent] stdin error: ${f.message}`)}),y.stdout.on("error",f=>{f.code!=="EPIPE"&&a.warn(`[Agent] stdout error: ${f.message}`)}),y.stderr.on("error",f=>{f.code!=="EPIPE"&&a.warn(`[Agent] stderr error: ${f.message}`)}),s?(y.stdin.write(s,f=>{f&&f.code!=="EPIPE"&&a.warn(`[Agent] Failed to write to stdin: ${f.message}`),y.stdin.end()}),a.debug(`[Agent] Prompt also piped to stdin (${s.length} chars)`)):y.stdin.end();let T=null;E&&(T=setInterval(()=>{if(!(k||b))try{if(ue(E)){k=!0,h="studio-stop";try{Sr(E)}catch{}a.warn("\u{1F6D1} Studio stop requested \u2014 terminating Cursor agent (and MCP browser session)"),y.kill("SIGTERM"),setTimeout(()=>{y.killed||y.kill("SIGKILL")},2e3)}}catch{}},600));let $=new Set,O=new Date(d).toISOString().replace(/\.\d+Z$/,""),g=setInterval(()=>{let f=Math.round((Date.now()-d)/1e3),v=Math.round((Date.now()-S)/1e3),C=[];try{let G=Math.ceil(f/60)+1,L=X(`find "${o}" -type f -mmin -${G} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(L)for(let Ie of L.split(`
|
|
73
|
+
`)){let ve=Ie.replace(`${o}/`,"");$.has(ve)||($.add(ve),C.push(ve))}}catch{}let M="";C.length>0&&(M=` | \u{1F4C1} new: ${C.map(L=>L.split("/").pop()).join(", ")}`),$.size>0&&(M+=` | \u{1F4E6} total: ${$.size} files`),a.debug(`\u{1F493} [Agent] Running for ${f}s | ${A} lines output${M}`),A===0&&f>=30&&$.size===0&&(f<35&&a.warn(`\u26A0\uFE0F [Agent] No output after ${f}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),f>=60&&(k=!0,h=h||"stall",a.error(`\u274C [Agent] No response after ${f}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),y.kill("SIGTERM"),setTimeout(()=>{y.killed||y.kill("SIGKILL")},3e3)))},3e4),x=setTimeout(()=>{k=!0,h=h||"timeout";let f=Math.round((Date.now()-d)/1e3);a.error(`\u23F1\uFE0F [Agent] Timeout after ${f}s \u2014 killing process (PID: ${y.pid})`),p.trim()&&a.warn(`\u{1F4E4} [Agent] Partial output (${p.length} chars) before timeout:
|
|
74
|
+
${p.slice(-2e3)}`),y.kill("SIGTERM"),setTimeout(()=>{y.killed||y.kill("SIGKILL")},5e3)},r),I=new V;I.onToolCall=(f,v)=>{let C=f,M=v;if(f==="mcpToolCall"&&v?.name)C=v.name.replace(/^mcp_+[^_]+_+/,""),C.includes("-")&&C.split("-")[0]===C.split("-")[1]&&(C=C.split("-")[0]),M=v.args??v.input??v;else{if(f==="readToolCall"||f==="editToolCall"||f==="writeToolCall")return;(f.startsWith("mcp__")||f.includes("ToolCall"))&&(C=f.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(C.includes("memory")?j.stepMemory(`Tool: ${C}`):j.stepTool(`Tool: ${C}`),M!=null&&typeof M=="object"&&Object.keys(M).length>0&&!b){let L=JSON.stringify(M),Ie=L.length>100?`${L.substring(0,100)}...`:L;console.log(` Input: ${Ie}`)}},y.stdout.on("data",f=>{let v=f.toString();p+=v,S=Date.now(),_||(_=!0);let C=I.processChunk(v);C&&!b&&process.stdout.write(C);let M=v.split(`
|
|
75
|
+
`).filter(G=>G.trim());A+=M.length}),y.stderr.on("data",f=>{let v=f.toString();m+=v,S=Date.now(),_||(_=!0);let C=v.split(`
|
|
76
|
+
`).filter(M=>M.trim());for(let M of C)a.warn(`\u26A0\uFE0F [Agent stderr] ${M}`)}),y.on("close",(f,v)=>{b=!0,P(),clearTimeout(x),clearInterval(g),T&&clearInterval(T),I.flush();let C=Math.round((Date.now()-d)/1e3);if(a.debug(`[Agent] Exited: code=${f}, signal=${v}, elapsed=${C}s, output=${p.length} chars`),k){if(h==="studio-stop"){u(new Error("Stopped from Zibby Studio"));return}u(new Error(`Cursor Agent timed out after ${C}s (limit: ${r/1e3}s). ${A} lines produced. Last output ${Math.round((Date.now()-S)/1e3)}s ago. ${p.trim()?`
|
|
70
77
|
Partial output (last 500 chars):
|
|
71
|
-
${
|
|
72
|
-
Stderr: ${m.slice(-1e3)}`:""}${
|
|
73
|
-
Stdout (last 500 chars): ${
|
|
78
|
+
${p.slice(-500)}`:"No output captured."}`));return}if(f!==0){u(new Error(`Cursor Agent failed: exit code ${f}, signal ${v}. ${m.trim()?`
|
|
79
|
+
Stderr: ${m.slice(-1e3)}`:""}${p.trim()?`
|
|
80
|
+
Stdout (last 500 chars): ${p.slice(-500)}`:""}`));return}let M=I.getResult(),G=M?JSON.stringify(M,null,2):I.getRawText()||p||"";c({stdout:p||m||"",parsedText:G})}),y.on("error",f=>{P(),clearTimeout(x),clearInterval(g),T&&clearInterval(T),u(new Error(`Cursor Agent spawn error: ${f.message}
|
|
74
81
|
Binary: ${e}
|
|
75
82
|
This usually means the binary is not in PATH. Try:
|
|
76
|
-
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}}});import{query as wr}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as Er}from"zod-to-json-schema";var pe,Et=R(()=>{z();W();le();H();Z();pe=class extends J{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!process.env.ANTHROPIC_API_KEY;return t||a.debug("ClaudeAgentStrategy: ANTHROPIC_API_KEY not set"),t}async invoke(e,t={}){let{model:o,workspace:r=process.cwd(),schema:s=null,images:i=[],skills:l=null,sessionPath:c=null,nodeName:u=null,timeout:
|
|
83
|
+
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}}});import{query as wr}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as Er}from"zod-to-json-schema";var pe,Et=R(()=>{z();W();le();H();Z();pe=class extends J{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!process.env.ANTHROPIC_API_KEY;return t||a.debug("ClaudeAgentStrategy: ANTHROPIC_API_KEY not set"),t}async invoke(e,t={}){let{model:o,workspace:r=process.cwd(),schema:s=null,images:i=[],skills:l=null,sessionPath:c=null,nodeName:u=null,timeout:d,config:p={}}=t,m=o;(!m||m==="auto")&&(a.debug(`Model is '${m||"undefined"}', using default: ${U.CLAUDE}`),m=U.CLAUDE);let S=Me[m]||m;Me[m]&&m!==S&&a.debug(`Mapped model: ${m} \u2192 ${S}`),a.debug(`Invoking Claude Agent SDK with model: ${S}, skills: ${JSON.stringify(l)}`);let A=process.env.ANTHROPIC_API_KEY,k=A?` | key: ***${A.slice(-4)}`:" | key: not set";console.log(`
|
|
77
84
|
\u25C6 Model: ${S}${k}
|
|
78
85
|
`);let h=(await import("chalk")).default;console.log(`
|
|
79
|
-
${h.bold("Prompt sent to LLM:")}`),console.log(h.dim("\u2500".repeat(60))),console.log(h.dim(e)),console.log(h.dim("\u2500".repeat(60)));let{allowedTools:_,mcpServers:
|
|
86
|
+
${h.bold("Prompt sent to LLM:")}`),console.log(h.dim("\u2500".repeat(60))),console.log(h.dim(e)),console.log(h.dim("\u2500".repeat(60)));let{allowedTools:_,mcpServers:b}=this._resolveSkills(l,{sessionPath:c,workspace:r,nodeName:u});try{let E={cwd:r,allowedTools:_,permissionMode:"bypassPermissions",model:S,...Object.keys(b).length>0&&{mcpServers:b}};if(s){let x=typeof s.parse=="function"?Er(s,{target:"openApi3"}):s;E.outputFormat={type:"json_schema",schema:x},a.debug("Structured output enforced via SDK outputFormat")}a.debug(`Agent SDK options: ${JSON.stringify({cwd:E.cwd,toolCount:_.length,permissionMode:E.permissionMode,model:E.model,hasOutputFormat:!!E.outputFormat})}`);let w="",P=0,N=[];a.debug("Starting Claude Agent SDK query stream");let y;try{y=wr({prompt:e,options:E})}catch(g){throw a.error(`Failed to initialize Claude Agent SDK: ${g.message}`),g}let T=null,$=0,O=3;try{for await(let g of y){if(N.push(g),g.type==="error"||g.error){let I=g.error?.message||g.error||g.message||"Unknown API error";throw new Error(typeof I=="string"?I:JSON.stringify(I))}let x=JSON.stringify(g.message?.content||g.text||"").slice(0,200);if(x===T){if($++,$>=O){let I=(g.message?.content?.[0]?.text||g.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${$}x repeated): ${I}`)}}else T=x,$=1;if(g.type==="assistant"||g.constructor?.name==="AssistantMessage"){let I=g.message?.content||g.content||[];for(let f of I)if(f.type==="thinking"&&f.thinking)console.log(`${f.thinking.substring(0,200)}${f.thinking.length>200?"...":""}`);else if(f.type==="text"&&f.text)w+=f.text,f.text.length<500?console.log(`${f.text}`):console.log(`${f.text.substring(0,200)}... (${f.text.length} chars)`);else if(f.type==="tool_use"){P++,f.name.includes("memory")?j.stepMemory(`Tool: ${f.name}`):j.stepTool(`Tool: ${f.name}`);let C=JSON.stringify(f.input).substring(0,100);console.log(` Input: ${C}${JSON.stringify(f.input).length>100?"...":""}`)}}else if(!(g.type==="user"&&g.tool_use_result)){if(g.type==="result"||g.constructor?.name==="ResultMessage"){let I=g.result||g.text||g.content||w;if(s){if(g.structured_output){a.debug("Using SDK native structured_output");let v=typeof s.parse=="function"?s.parse(g.structured_output):g.structured_output;return{raw:I,structured:v}}if(I){let f=this._extractJson(I,s);if(f)return{raw:I,structured:f}}a.warn(`Could not extract structured output \u2014 returning raw text (${(I||"").length} chars)`)}return I||""}}}if(a.warn(`Agent SDK ended without result. Collected ${N.length} messages`),w.length>0)return a.debug("Returning accumulated text from messages"),w;throw new Error("Claude Agent SDK query ended without result")}catch(g){throw a.error(`Error during query stream: ${g.message}`),g}}catch(E){throw a.error("Claude Agent SDK call failed",{error:E.message}),E}}_resolveSkills(e,t){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:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};let o=[],r={};for(let s of e){let i=B(s);if(!i){a.warn(`Unknown skill "${s}" \u2014 skipping`);continue}if(i.allowedTools&&o.push(...i.allowedTools),typeof i.resolve=="function"){let l=i.resolve(t);l&&(r[i.serverName]=l,a.debug(`MCP: ${i.serverName} \u2192 ${l.command} ${l.args[0]}`))}}return{allowedTools:o,mcpServers:r}}_extractJson(e,t){let o=[()=>{if(e.includes("===JSON_START===")){let r=e.indexOf("===JSON_START===")+16,s=e.indexOf("===JSON_END===");return e.substring(r,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 r=e.indexOf("{"),s=e.lastIndexOf("}");if(r!==-1&&s>r)return e.substring(r,s+1)}];for(let r of o)try{let s=r();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}}});import{execSync as br}from"node:child_process";import{zodToJsonSchema as Or}from"zod-to-json-schema";var me,bt=R(()=>{z();W();le();H();Z();me=class extends J{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.CODEX_API_KEY))return a.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return br("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:r=process.cwd(),schema:s=null,skills:i=null,sessionPath:l=null,nodeName:c=null,timeout:u,config:d={}}=t,{Codex:p}=await import("@openai/codex-sdk"),m=o;(!m||m==="auto")&&(a.debug(`Model is '${m||"undefined"}', using default: ${U.CODEX}`),m=U.CODEX);let S=Le[m]||m;Le[m]&&m!==S&&a.debug(`Mapped model: ${m} \u2192 ${S}`),a.debug(`Invoking Codex SDK with model: ${S}, skills: ${JSON.stringify(i)}`);let A=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;A&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=A);let k=A?` | key: ***${A.slice(-4)}`:" | key: not set";console.log(`
|
|
80
87
|
\u25C6 Model: ${S}${k}
|
|
81
88
|
`);let h=(await import("chalk")).default;console.log(`
|
|
82
|
-
${h.bold("Prompt sent to LLM:")}`),console.log(h.dim("\u2500".repeat(60))),console.log(h.dim(e)),console.log(h.dim("\u2500".repeat(60)));let _=this._resolveSkillsToMcp(i,{sessionPath:l,workspace:r,nodeName:c}),
|
|
89
|
+
${h.bold("Prompt sent to LLM:")}`),console.log(h.dim("\u2500".repeat(60))),console.log(h.dim(e)),console.log(h.dim("\u2500".repeat(60)));let _=this._resolveSkillsToMcp(i,{sessionPath:l,workspace:r,nodeName:c}),b={};Object.keys(_).length>0&&(b.mcp_servers=_,a.debug(`[Codex] MCP servers: ${Object.keys(_).join(", ")}`));let w=new p({...Object.keys(b).length>0&&{config:b}}).startThread({workingDirectory:r,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),P=s&&typeof s.parse=="function",N={};if(s)try{let y=P?Or(s,{target:"openAi"}):s;N.outputSchema=y,a.debug("Structured output via SDK outputSchema")}catch(y){a.warn(`[Codex] Schema conversion failed, will extract from text: ${y.message}`)}try{let{events:y}=await w.runStreamed(e,N),T=0,$="";for await(let O of y){let g=O.type;if(g==="item.completed"){let x=O.item,I=x?.type;if(I==="mcp_tool_call"){T++;let f=`${x.server}/${x.tool}`;if(j.stepTool(`Tool: ${f}`),x.arguments){let v=JSON.stringify(x.arguments),C=v.length>100?`${v.substring(0,100)}...`:v;console.log(` Input: ${C}`)}}else if(I==="tool_call"||I==="function_call"||I==="command_execution"){T++;let f=x.name||x.tool||x.command||"unknown";j.stepTool(`Tool: ${f}`)}else I==="agent_message"&&($=x.text||"",$.length<500?console.log($):console.log(`${$.substring(0,200)}... (${$.length} chars)`))}else g==="turn.completed"?a.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(O.usage||{})}`):a.debug(`[Codex] Event: ${g} ${JSON.stringify(O).slice(0,300)}`)}if(a.debug(`[Codex] Last agent message (${$.length} chars): ${$.slice(0,500)}`),s){if(!$)throw new Error("Codex agent returned no response");let O=JSON.parse($),g=P?s.parse(O):O;return a.debug("\u2705 [Codex] Structured output validated"),{raw:$,structured:g}}return $||""}catch(y){let T=y.message||String(y);throw a.error(`\u274C [Codex] SDK call failed: ${T}`),T.includes("exited with code")&&(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")),y}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let o={};for(let r of e){let s=B(r);if(!s){a.warn(`[Codex] Unknown skill "${r}" \u2014 skipping`);continue}if(typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let l=s.serverName||r,c={command:i.command};i.args?.length&&(c.args=i.args),i.env&&Object.keys(i.env).length>0&&(c.env=i.env),o[l]=c,a.debug(`[Codex] MCP: ${l} \u2192 ${i.command} ${(i.args||[]).join(" ")}`)}return o}}});import{execSync as xr,spawn as $r}from"node:child_process";import{zodToJsonSchema as Ar}from"zod-to-json-schema";import{existsSync as Ot,mkdirSync as xt,readFileSync as $t,rmSync as Tr,writeFileSync as At}from"node:fs";import{join as q}from"node:path";function Ir(n){if(!n)return null;let e=String(n),t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t?.[1])try{return JSON.parse(t[1].trim())}catch{}let o=e.indexOf("{");if(o<0)return null;let r=0,s=!1,i=!1,l=-1;for(let c=o;c<e.length;c++){let u=e[c];if(s){i?i=!1:u==="\\"?i=!0:u==='"'&&(s=!1);continue}if(u==='"'){s=!0;continue}if(u==="{"){r===0&&(l=c),r+=1;continue}if(u==="}"){if(r===0)continue;if(r-=1,r===0&&l>=0){let d=e.slice(l,c+1);try{return JSON.parse(d)}catch{l=-1}}}}return null}function vr(n){let e=String(n||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return Ir(e)}}function Cr(n){try{let e=JSON.parse(n);if(typeof e=="string")return e;if(typeof e?.response=="string")return e.response;if(typeof e?.text=="string")return e.text;if(typeof e?.output=="string")return e.output;if(Array.isArray(e?.candidates)&&e.candidates.length>0){let t=e.candidates[0];if(typeof t?.content=="string")return t.content;if(Array.isArray(t?.content?.parts)){let o=t.content.parts.map(r=>typeof r?.text=="string"?r.text:"").join("");if(o.trim())return o}}}catch{}return n}var ge,Tt=R(()=>{z();W();H();Z();Be();Ue();ge=class extends J{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY))return a.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return xr("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:r=process.cwd(),schema:s=null,skills:i=null,sessionPath:l=null,nodeName:c=null,timeout:u=600*1e3}=t,d=o;(!d||d==="auto")&&(d=U.GEMINI);let p=it[d]||d,m=String(process.env.GEMINI_API_KEY||"").trim(),S=String(process.env.GOOGLE_API_KEY||"").trim(),A=this._resolveSkillsToMcp(i,{sessionPath:l,workspace:r,nodeName:c}),k=Object.keys(A).length>0,h=e,_=s&&typeof s.parse=="function",b=null;if(s){let x;try{let I=_?Ar(s,{target:"openAi"}):s;x=JSON.stringify(I,null,2)}catch{x="{}"}if(k){h+=`
|
|
83
90
|
|
|
84
91
|
Write valid JSON that matches this schema:
|
|
85
|
-
${x}`;let I=`zibby-result-${Date.now()}.json`,
|
|
92
|
+
${x}`;let I=`zibby-result-${Date.now()}.json`,f=q(r,".zibby","tmp");b=q(f,I),xt(f,{recursive:!0}),h+=Q.generateFileOutputInstructions(s,b)}else h+=`
|
|
86
93
|
|
|
87
94
|
Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
|
|
88
|
-
${x}`}let E=this._createGeminiConfigDir(r,A),w=["--output-format","json"];
|
|
95
|
+
${x}`}let E=this._createGeminiConfigDir(r,A),w=["--output-format","json"];p&&p!=="auto"&&w.push("--model",p);let P=Object.keys(A);if(P.length>0){w.push("--approval-mode","yolo");for(let x of P)w.push("--allowed-mcp-server-names",x);a.info(`[Gemini] Enabling MCP servers: ${P.join(", ")}`)}else i&&i.length>0&&a.warn(`[Gemini] Skills requested but no MCP servers configured: ${i.join(", ")}`);w.push("-p",h);let N={...process.env,GEMINI_CLI_HOME:E};m?(N.GEMINI_API_KEY=m,delete N.GOOGLE_API_KEY):S&&(N.GOOGLE_API_KEY=S,delete N.GEMINI_API_KEY),a.debug(`[Gemini] Command: gemini ${w.slice(0,8).join(" ")}... (${w.length} total args)`),a.debug(`[Gemini] Config home: ${E}`),a.debug(`[Gemini] GEMINI_CLI_HOME env: ${N.GEMINI_CLI_HOME}`);let y="",T=null;try{y=await new Promise((I,f)=>{let v=$r("gemini",w,{cwd:r,env:N,stdio:["ignore","pipe","pipe"]}),C="",M="",G=setTimeout(()=>{try{v.kill("SIGTERM")}catch{}},u);v.stdout.on("data",L=>{C+=L.toString()}),v.stderr.on("data",L=>{M+=L.toString()}),v.on("error",L=>{clearTimeout(G),f(L)}),v.on("close",L=>{if(clearTimeout(G),L===0)return I(C.trim());f(new Error(`gemini failed with code ${L}: ${(M||C).trim()}`))})})}catch(x){T=x}finally{try{Tr(E,{recursive:!0,force:!0})}catch{}}let $=Cr(y).trim();if(!s){if(T)throw T;return $}if(b){let x=Ot(b);if(a.info(`[Gemini] Result file: ${x?"present":"missing"} at ${b}`),x)try{let I=$t(b,"utf-8").trim(),f=JSON.parse(I),v=_?s.parse(f):f;return a.info("[Gemini] Structured output recovered from result file"),{raw:$,structured:v}}catch(I){a.warn(`[Gemini] Result file parse/validation failed: ${I.message}`)}else T||a.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let O=null;if(s){let x=new V;x.zodSchema=s,x.processChunk($),x.flush(),O=x.getResult()}if(a.info(`[Gemini] Raw stdout length: ${y.length} chars`),a.info(`[Gemini] Extracted text length: ${$.length} chars`),a.info(`[Gemini] StreamParser result: ${O?"extracted":"null"}`),O||($.length<2e3?a.info(`[Gemini] Raw text preview:
|
|
89
96
|
${$}`):a.info(`[Gemini] Raw text preview (first 1000 chars):
|
|
90
|
-
${$.slice(0,1e3)}`),
|
|
91
|
-
`,"utf-8");let
|
|
92
|
-
`,"utf-8")}catch{}return a.debug(`[Gemini] Created isolated config with ${Object.keys(u.mcpServers||{}).length} MCP servers`),a.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(u.mcpServers||{}),null,2)}`),r}}});var he,je=R(()=>{he=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 te,It=R(()=>{je();te=class extends he{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 ye,Fe=R(()=>{ye=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 Ee(n){return Buffer.byteLength(JSON.stringify(n),"utf8")}function
|
|
97
|
+
${$.slice(0,1e3)}`),O=vr($)),!O)throw T||(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 g=_?s.parse(O):O;return{raw:$,structured:g}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let o={};for(let r of e){let s=B(r);if(!s||typeof s.resolve!="function")continue;let i=s.resolve(t);if(!i)continue;let l=s.cursorKey||s.serverName||r,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)}`,r=q(e||process.cwd(),".zibby","tmp",`gemini-home-${o}`),s=q(r,".gemini");xt(s,{recursive:!0});let i=q(s,"settings.json"),l={},c=q(process.env.HOME||"",".gemini","settings.json");if(Ot(c))try{l=JSON.parse($t(c,"utf-8"))}catch{l={}}let u={...l,mcpServers:{...l.mcpServers&&typeof l.mcpServers=="object"?l.mcpServers:{},...t||{}}};At(i,`${JSON.stringify(u,null,2)}
|
|
98
|
+
`,"utf-8");let d=q(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{At(d,`${JSON.stringify(u,null,2)}
|
|
99
|
+
`,"utf-8")}catch{}return a.debug(`[Gemini] Created isolated config with ${Object.keys(u.mcpServers||{}).length} MCP servers`),a.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(u.mcpServers||{}),null,2)}`),r}}});var he,je=R(()=>{he=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 te,It=R(()=>{je();te=class extends he{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 ye,Fe=R(()=>{ye=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 Ee(n){return Buffer.byteLength(JSON.stringify(n),"utf8")}function be(n,e){let t=String(n||"");if(t.length<=e)return t;let o=Math.max(0,e-28);return`${t.slice(0,o)}
|
|
93
100
|
|
|
94
|
-
[truncated for size budget]`}function Ge(n,e=0){if(!n||typeof n!="object"||e>8)return n;if(Array.isArray(n))return n.map(o=>Ge(o,e+1));let t={};for(let[o,r]of Object.entries(n))o==="description"||o==="title"||o==="examples"||o==="default"||(t[o]=Ge(r,e+1));return t}function kr(n=[]){return n.map(e=>({...e,function:{...e.function,description:
|
|
95
|
-
`);S=
|
|
101
|
+
[truncated for size budget]`}function Ge(n,e=0){if(!n||typeof n!="object"||e>8)return n;if(Array.isArray(n))return n.map(o=>Ge(o,e+1));let t={};for(let[o,r]of Object.entries(n))o==="description"||o==="title"||o==="examples"||o==="default"||(t[o]=Ge(r,e+1));return t}function kr(n=[]){return n.map(e=>({...e,function:{...e.function,description:be(e.function?.description||"",180),parameters:Ge(e.function?.parameters||{type:"object",properties:{}})}}))}function vt(n){let e=new Set;for(let r of n)if(r.role==="assistant"&&Array.isArray(r.tool_calls))for(let s of r.tool_calls)e.add(s.id);let t=n.filter(r=>r.role==="tool"?e.has(r.tool_call_id):!0),o=new Set;for(let r of t)r.role==="tool"&&o.add(r.tool_call_id);return t.map(r=>{if(r.role!=="assistant"||!Array.isArray(r.tool_calls)||r.tool_calls.every(c=>o.has(c.id)))return r;let{tool_calls:i,...l}=r;return{...l,content:l.content||""}})}function Ke(n,e={}){let t=e.maxBytes||49e3,o=e.systemMaxChars||12e3,r={...n,messages:Array.isArray(n.messages)?[...n.messages]:[],tools:Array.isArray(n.tools)?kr(n.tools):n.tools};r.messages.length>0&&r.messages[0]?.role==="system"&&(r.messages[0]={...r.messages[0],content:be(r.messages[0].content,o)});let s=!1;for(;Ee(r)>t&&r.messages.length>2;)r.messages.splice(1,1),s=!0;if(s&&(r.messages=vt(r.messages)),Ee(r)>t&&r.messages.length>0&&(r.messages[0]={...r.messages[0],content:be(r.messages[0].content,6e3)},s=!0),Ee(r)>t){let i=r.messages.find(c=>c.role==="system")||r.messages[0],l=r.messages.slice(-2);r.messages=vt([i,...l].filter(Boolean).map((c,u)=>({...c,content:be(c.content,u===0?4e3:8e3)}))),s=!0}return{body:r,meta:{bytes:Ee(r),trimmed:s,maxBytes:t,messageCount:r.messages.length}}}var Ct=R(()=>{});var kt,re,Nt=R(()=>{Fe();Ct();kt=n=>Buffer.byteLength(JSON.stringify(n),"utf8"),re=class extends ye{async fetchCompletion(e,t,o={}){let r=kt(e),{body:s,meta:i}=Ke(e,o.payloadCompaction);o.onBudget?.({streaming:!1,beforeBytes:r,meta:i});let l=this.#e(o),c=`${t.baseUrl}${o.chatCompletionsPath||"/v1/chat/completions"}`,u=await fetch(c,{method:"POST",headers:t.headers,body:JSON.stringify(s),signal:l});if(!u.ok){let d=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}: ${d}`)}return u.json()}async fetchStreamingCompletion(e,t,o={}){let r={...e,stream:!0},s=kt(r),{body:i,meta:l}=Ke(r,o.payloadCompaction);o.onBudget?.({streaming:!0,beforeBytes:s,meta:l});let c=this.#e(o),u=`${t.baseUrl}${o.chatCompletionsPath||"/v1/chat/completions"}`,d=await fetch(u,{method:"POST",headers:t.headers,body:JSON.stringify(i),signal:c});if(!d.ok){let h=await d.text();throw d.status===401||d.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${d.status}: ${h}`)}let p=d.body.getReader(),m=new TextDecoder,S="",A="",k=new Map;for(;;){let{done:h,value:_}=await p.read();if(h)break;S+=m.decode(_,{stream:!0});let b=S.split(`
|
|
102
|
+
`);S=b.pop();for(let E of b){if(!E.startsWith("data: "))continue;let w=E.slice(6).trim();if(w==="[DONE]")continue;let P;try{P=JSON.parse(w)}catch{continue}let N=P.choices?.[0]?.delta;if(N&&(N.content&&(A+=N.content,o.onToken&&o.onToken(N.content)),N.tool_calls))for(let y of N.tool_calls){let T=y.index??0;k.has(T)||k.set(T,{id:"",name:"",args:""});let $=k.get(T);y.id&&($.id=y.id),y.function?.name&&($.name=y.function.name),y.function?.arguments!=null&&($.args+=y.function.arguments)}}}if(k.size>0){let h=[...k.entries()].sort(([_],[b])=>_-b).map(([,_])=>({id:_.id,type:"function",function:{name:_.name,arguments:_.args}}));return{choices:[{message:{role:"assistant",content:A||null,tool_calls:h}}]}}return{choices:[{message:{role:"assistant",content:A}}]}}#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}}});var Pt=R(()=>{je();It();Fe();Nt()});import{Client as Nr}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Pr}from"@modelcontextprotocol/sdk/client/stdio.js";var Oe,Rt=R(()=>{W();Oe=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:o,args:r=[],env:s={}}=t;a.debug(`[MCP] Starting ${e}: ${o} ${r.join(" ")}`);let i=new Pr({command:o,args:r,env:{...process.env,...s}}),l=new Nr({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 r=this.#e.get(e);if(!r)throw new Error(`MCP server "${e}" not running`);a.debug(`[MCP] ${e}.${t}(${JSON.stringify(o).slice(0,200)})`);let s=await r.client.callTool({name:t,arguments:o});return{text:s.content?.filter(l=>l.type==="text").map(l=>l.text).join(`
|
|
96
103
|
`)||"",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 Rr,readFileSync as Mr}from"node:fs";import{join as Lr}from"node:path";import{homedir as Dr}from"node:os";function Ur(){try{let n=Lr(Dr(),".zibby","config.json");return Rr(n)?JSON.parse(Mr(n,"utf-8")):{}}catch{return{}}}function xe(n){return String(n||"").replace(/\/v1\/?$/,"")}function Br(n,e){let t=process.env.OPENAI_PROXY_URL;if(t)return xe(t);if(n==="session")return e.proxyUrl?xe(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(n==="byok"){let o=process.env.OPENAI_BASE_URL;return xe(o||"https://api.openai.com")}return xe(t||"")}function We(){let n=Ur(),e=process.env.ZIBBY_USER_TOKEN||n.sessionToken||null,t=process.env.OPENAI_API_KEY||null,o=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),r=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&&r&&(i="local");let l=Br(i,n),c={"Content-Type":"application/json"};if(i==="session"){if(!e)return{ok:!1,mode:i,reason:"missing_session_token"};c.Authorization=`Bearer ${e}`}else if(i==="byok"){if(!t)return{ok:!1,mode:i,reason:"missing_openai_api_key"};c.Authorization=`Bearer ${t}`}else if(i==="local"){if(!l)return{ok:!1,mode:i,reason:"missing_openai_proxy_url"};!r&&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"}}var Mt=R(()=>{});function $e(n,e){let t=String(n??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
|
|
97
104
|
|
|
98
|
-
[tool result truncated for size]`}function Jr(n,e){if(typeof n=="string")return $e(n,e);try{return $e(JSON.stringify(n),e)}catch{return $e(String(n),e)}}function Lt(n){let e=new Set;for(let r of n)if(r.role==="assistant"&&Array.isArray(r.tool_calls))for(let s of r.tool_calls)e.add(s.id);let t=n.filter(r=>r.role==="tool"?e.has(r.tool_call_id):!0),o=new Set;for(let r of t)r.role==="tool"&&o.add(r.tool_call_id);return t.map(r=>{if(r.role!=="assistant"||!Array.isArray(r.tool_calls)||r.tool_calls.every(c=>o.has(c.id)))return r;let{tool_calls:i,...l}=r;return{...l,content:l.content||""}})}function jr(n){let e=Array.isArray(n?.messages)?n.messages:[],t=e.find(s=>s.role==="system"),o=e.slice(-4).map(s=>({...s,content:$e(s.content,s.role==="tool"?1200:2500)}));o=Lt(o);let r={...n,messages:[t,...o].filter(Boolean)};return delete r.tools,r}async function Fr({body:n,streaming:e,auth:t,options:o,fetchCompletion:r,fetchStreamingCompletion:s,onFallbackLog:i}){try{return e?await s(n,t,o):await r(n,t,o)}catch(l){let c=String(l?.message||l||"");if(!/proxy error 413|payload too large/i.test(c))throw l;let u=jr(n);return typeof i=="function"&&i(n,u),{data:e?await s(u,t,o):await r(u,t,o),fallback:u}}}async function Dt({body:n,auth:e,options:t,streaming:o,toolContext:r,activeSkills:s,round:i,verbose:l,dependencies:c,config:u={}}){let
|
|
99
|
-
\u{1F4D6} get_skill_context("${u}") \u2192 ${S.length} chars (fragment: ${
|
|
100
|
-
`)),S}let l=s?.get(e.name)||null;if(!l)return`Unknown tool: ${e.name}`;let c=B(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(u){return`Error in ${e.name}: ${u.message}`}if(l.mode==="mcp")try{if(!this.#r.isRunning(c.serverName)){let
|
|
105
|
+
[tool result truncated for size]`}function Jr(n,e){if(typeof n=="string")return $e(n,e);try{return $e(JSON.stringify(n),e)}catch{return $e(String(n),e)}}function Lt(n){let e=new Set;for(let r of n)if(r.role==="assistant"&&Array.isArray(r.tool_calls))for(let s of r.tool_calls)e.add(s.id);let t=n.filter(r=>r.role==="tool"?e.has(r.tool_call_id):!0),o=new Set;for(let r of t)r.role==="tool"&&o.add(r.tool_call_id);return t.map(r=>{if(r.role!=="assistant"||!Array.isArray(r.tool_calls)||r.tool_calls.every(c=>o.has(c.id)))return r;let{tool_calls:i,...l}=r;return{...l,content:l.content||""}})}function jr(n){let e=Array.isArray(n?.messages)?n.messages:[],t=e.find(s=>s.role==="system"),o=e.slice(-4).map(s=>({...s,content:$e(s.content,s.role==="tool"?1200:2500)}));o=Lt(o);let r={...n,messages:[t,...o].filter(Boolean)};return delete r.tools,r}async function Fr({body:n,streaming:e,auth:t,options:o,fetchCompletion:r,fetchStreamingCompletion:s,onFallbackLog:i}){try{return e?await s(n,t,o):await r(n,t,o)}catch(l){let c=String(l?.message||l||"");if(!/proxy error 413|payload too large/i.test(c))throw l;let u=jr(n);return typeof i=="function"&&i(n,u),{data:e?await s(u,t,o):await r(u,t,o),fallback:u}}}async function Dt({body:n,auth:e,options:t,streaming:o,toolContext:r,activeSkills:s,round:i,verbose:l,dependencies:c,config:u={}}){let d=u.maxToolResultChars||3e3,{fetchCompletion:p,fetchStreamingCompletion:m,onFallbackLog:S,hasToolCalls:A,getTextContent:k,parseToolCalls:h,buildAssistantMessage:_,buildToolResultMessage:b,executeTool:E,onToolCallLog:w,injectTools:P}=c;Array.isArray(n?.messages)&&(n.messages=Lt(n.messages));let N=await Fr({body:n,streaming:o,auth:e,options:t,fetchCompletion:p,fetchStreamingCompletion:m,onFallbackLog:S}),y=N?.data||N;if(!A(y))return{done:!0,text:k(y),body:N?.fallback||n};let T=h(y),$=N?.fallback||n;$.messages.push(_(y)),l&&typeof w=="function"&&w(T);let O=await Promise.all(T.map((g,x)=>(typeof t.onToolCall=="function"&&t.onToolCall(g.name,g.args,{round:i,index:x,total:T.length}),E(g,r))));for(let g=0;g<T.length;g++){let I=T[g].name==="get_skill_context"?typeof O[g]=="string"?O[g]:JSON.stringify(O[g]):Jr(O[g],d);$.messages.push(b(T[g].id,I))}return typeof t.onToolCall=="function"&&t.onToolCall(null),P($,s),{done:!1,body:$}}var Ut=R(()=>{});function se(n){!n||typeof n!="object"||(n.type==="object"&&n.properties&&(n.required=Object.keys(n.properties),n.additionalProperties=!1,Object.values(n.properties).forEach(se)),n.type==="array"&&n.items&&se(n.items),n.anyOf&&n.anyOf.forEach(se),n.oneOf&&n.oneOf.forEach(se),n.allOf&&n.allOf.forEach(se))}function Ae(n){return Array.isArray(n)?new Set(n.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function Yr(n){return Array.isArray(n)?n.map(e=>String(e||"").trim()).filter(Boolean):[]}var Gr,Kr,Ye,Bt,oe,Wr,Se,Jt=R(()=>{z();W();H();Pt();Rt();Z();Mt();Ut();Gr=U.ASSISTANT,Kr=15,Ye="get_skill_context";Bt={maxBytes:49e3,systemMaxChars:12e3},oe=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Wr=n=>Buffer.byteLength(JSON.stringify(n),"utf8");Se=class extends J{#e;#t;#r=new Oe;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new te,this.#t=e.completionProvider||new re):(this.#e=e||new te,this.#t=new re)}canHandle(e){return We().ok}async invoke(e,t={}){let o=t.model&&t.model!=="auto"?t.model:Gr,r=We();if(!r.ok)throw r.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):r.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):r.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${r.reason}).`);let s=t.messages||[{role:"user",content:e}],i=r.baseUrl,l=oe();if(l?await this.#m(s,o,i,r.tokenPreview||"none"):a.debug(`[Assistant] ${i} | model: ${o} | messages: ${s.length}`),t.schema)return this.#c(o,s,r,t);let c=t.activeSkills||[],u=this.#f(t),d=this.#d(c,u),p=this.#p(d),m=this.#u(t),S={...t,payloadCompaction:m},A={activeSkills:d,options:S,executionRegistry:p,capabilityPolicy:u},k=!!t.stream,h={model:o,messages:[...s],stream:!1};this.#s(h,d,u);for(let _=0;_<Kr;_++){if(t.signal?.aborted)throw new Error("Aborted");let b=await Dt({body:h,auth:r,options:S,streaming:k,toolContext:A,activeSkills:d,round:_,verbose:l,dependencies:{fetchCompletion:this.#n.bind(this),fetchStreamingCompletion:this.#a.bind(this),onFallbackLog:(E,w)=>{oe()&&console.log(`413 fallback: messages ${E.messages.length} -> ${w.messages.length}, bytes=${Wr(w)}`)},hasToolCalls:E=>this.#e.hasToolCalls(E),getTextContent:E=>this.#e.getTextContent(E),parseToolCalls:E=>this.#e.parseToolCalls(E),buildAssistantMessage:E=>this.#e.buildAssistantMessage(E),buildToolResultMessage:(E,w)=>this.#e.buildToolResultMessage(E,w),executeTool:(E,w)=>this.#l(E,w),onToolCallLog:async E=>{let w=(await import("chalk")).default;console.log(w.dim(` ${E.map(P=>`${P.name}(${JSON.stringify(P.args).slice(0,80)})`).join(", ")}`))},injectTools:(E,w)=>this.#s(E,w,u)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(b.done)return b.text;h.messages=b.body.messages,b.body.tools?h.tools=b.body.tools:delete h.tools}return"I hit my tool-calling limit for this turn. Please try again."}async cleanup(){await this.#r.stopAll()}#s(e,t,o=null){let r=this.#i(t,o),s=this.#e.formatTools(r);this.#e.injectToolsIntoBody(e,s)}#i(e,t=null){let o=[],r=new Set;for(let s of e){let i=B(s);if(i?.tools?.length)for(let l of i.tools)this.#o(l.name,t)&&(r.has(l.name)||(r.add(l.name),o.push({name:l.name,description:l.description,parameters:l.parameters||l.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#o(Ye,t)&&o.push({name:Ye,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#l(e,t){let{activeSkills:o,options:r,executionRegistry:s,capabilityPolicy:i}=t;if(!this.#o(e.name,i))return`Tool "${e.name}" blocked by policy`;if(e.name===Ye){let u=String(e.args?.skillId||"").trim();if(!u)return JSON.stringify({error:"skillId is required"});if(!o.includes(u))return JSON.stringify({error:`Skill "${u}" is not active`,activeSkills:o});let d=B(u);if(!d)return JSON.stringify({error:`Skill "${u}" not found`});let p=typeof d.promptFragment=="function"?d.promptFragment():d.promptFragment||"",m=(d.tools||[]).map(A=>A.name),S=JSON.stringify({skillId:u,description:d.description||"",toolNames:m,promptFragment:p||""});return oe()&&(console.log(`
|
|
106
|
+
\u{1F4D6} get_skill_context("${u}") \u2192 ${S.length} chars (fragment: ${p.length} chars)`),console.log(` tools: [${m.join(", ")}]`),console.log(` fragment preview: ${p.slice(0,200).replace(/\n/g,"\\n")}\u2026
|
|
107
|
+
`)),S}let l=s?.get(e.name)||null;if(!l)return`Unknown tool: ${e.name}`;let c=B(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(u){return`Error in ${e.name}: ${u.message}`}if(l.mode==="mcp")try{if(!this.#r.isRunning(c.serverName)){let d=c.resolve(r);if(!d)return`Skill "${l.skillId}" is not available (cannot start server)`;await this.#r.ensureServer(c.serverName,d)}let u=await this.#r.callTool(c.serverName,e.name,e.args);return u.text||(u.isError?"Tool call failed":"Done")}catch(u){return`MCP error (${c.serverName}): ${u.message}`}return`Skill "${l.skillId}" owns tool "${e.name}" but has no execution mode`}async#a(e,t,o){return this.#t.fetchStreamingCompletion(e,t,{...o,onBudget:({beforeBytes:r,meta:s})=>{oe()&&console.log(`payload bytes (stream) before=${r} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#n(e,t,o){return this.#t.fetchCompletion(e,t,{...o,onBudget:({beforeBytes:r,meta:s})=>{oe()&&console.log(`payload bytes before=${r} after=${s.bytes} trimmed=${s.trimmed} messages=${s.messageCount}`)}})}async#c(e,t,o,r){let{zodToJsonSchema:s}=await import("zod-to-json-schema"),i=typeof r.schema?.parse=="function",l=i?s(r.schema):r.schema;delete l.$schema,se(l);let c={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:l,strict:!0}}},u=await this.#n(c,o,r),d=this.#e.getTextContent(u),p=JSON.parse(d),m=i?r.schema.parse(p):p;return{raw:d,structured:m}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||Bt.maxBytes),systemMaxChars:Number(t.systemMaxChars||Bt.systemMaxChars)}}#f(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:Ae(t.allowTools||e.allowTools),denyTools:Ae(t.denyTools||e.denyTools),denyPrefixes:Yr(t.denyPrefixes||e.denyToolPrefixes),includeSkills:Ae(t.includeSkills||e.includeSkills),excludeSkills:Ae(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#d(e,t){let o=t?.includeSkills||new Set,r=t?.excludeSkills||new Set;return o.size===0&&r.size===0?e:e.filter(s=>!(o.size>0&&!o.has(s)||r.has(s)))}#o(e,t){let o=String(e||"").trim();if(!o)return!1;let r=t?.allowTools;if(r&&r.size>0&&!r.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 r of e){let s=B(r);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:r});continue}t.set(c,{skillId:r,mode:i})}}}if(o.length>0&&oe()){let r=o.slice(0,5).map(s=>`${s.tool}:${s.winner}>${s.skipped}`).join(", ");console.log(`tool registry collisions: ${r}${o.length>5?" ...":""}`)}return t}async#m(e,t,o,r){console.log(`
|
|
101
108
|
\u25C6 Model: ${t} | proxy: ${o} | token: ${r||"none"}
|
|
102
|
-
`);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",u=l.content?.length>200?`${l.content.slice(0,200)}...`:l.content||"";console.log(s.dim(`[${c}] ${u}`))}console.log(s.dim("\u2500".repeat(60)))}}});var Gt={};Xe(Gt,{AgentStrategy:()=>J,AssistantStrategy:()=>Se,ClaudeAgentStrategy:()=>pe,CodexAgentStrategy:()=>me,CursorAgentStrategy:()=>de,GeminiAgentStrategy:()=>ge,getAgentStrategy:()=>Ft,invokeAgent:()=>zr});function Ft(n={}){let{state:e={},preferredAgent:t=null}=n,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 r=jt.find(s=>s.getName()===o);if(!r)throw new Error(`Unknown agent '${o}'. Available: ${jt.map(s=>s.getName()).join(", ")}`);if(a.debug(`Checking if ${o} can handle this environment...`),!r.canHandle(n)){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: ${r.getName()}`),r}async function zr(n,e={},t={}){try{await import("@zibby/skills")}catch{}let o=Ft(e),r=e.state?.config||t.config||{},s=r.models||{},i=t.nodeName&&s[t.nodeName]||null,l=s.default||null,c=o.name,u=r.agent?.[c]?.model||null,
|
|
109
|
+
`);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",u=l.content?.length>200?`${l.content.slice(0,200)}...`:l.content||"";console.log(s.dim(`[${c}] ${u}`))}console.log(s.dim("\u2500".repeat(60)))}}});var Gt={};Xe(Gt,{AgentStrategy:()=>J,AssistantStrategy:()=>Se,ClaudeAgentStrategy:()=>pe,CodexAgentStrategy:()=>me,CursorAgentStrategy:()=>de,GeminiAgentStrategy:()=>ge,getAgentStrategy:()=>Ft,invokeAgent:()=>zr});function Ft(n={}){let{state:e={},preferredAgent:t=null}=n,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 r=jt.find(s=>s.getName()===o);if(!r)throw new Error(`Unknown agent '${o}'. Available: ${jt.map(s=>s.getName()).join(", ")}`);if(a.debug(`Checking if ${o} can handle this environment...`),!r.canHandle(n)){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: ${r.getName()}`),r}async function zr(n,e={},t={}){try{await import("@zibby/skills")}catch{}let o=Ft(e),r=e.state?.config||t.config||{},s=r.models||{},i=t.nodeName&&s[t.nodeName]||null,l=s.default||null,c=o.name,u=r.agent?.[c]?.model||null,d=i||l||u||t.model||null,p={...t,model:d,workspace:e.state?.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:r},m=p.skills||[];if(m.length>0&&!t.skipPromptFragments){let{getSkill:A}=await Promise.resolve().then(()=>(Z(),lt)),k=m.map(h=>{let _=A(h)?.promptFragment;return typeof _=="function"?_():_}).filter(Boolean);k.length>0&&(n+=`
|
|
103
110
|
|
|
104
111
|
${k.join(`
|
|
105
112
|
|
|
@@ -111,10 +118,10 @@ ${k.join(`
|
|
|
111
118
|
|
|
112
119
|
${S}
|
|
113
120
|
`),a.debug(`Prompt length: ${n.length} chars`),process.env.STAGE!=="prod"&&a.debug(`Full prompt:
|
|
114
|
-
${n}`),o.invoke(n,
|
|
121
|
+
${n}`),o.invoke(n,p)}var jt,Kt=R(()=>{wt();Et();bt();Tt();Jt();W();z();jt=[new Se,new de,new pe,new me,new ge]});var _e=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let o=e.match(/\{[\s\S]*\}/);return o?this.validate(JSON.parse(o[0])):this.validate({result:e.trim()})}validate(e){let t=[];for(let[o,r]of Object.entries(this.schema)){if(r.required&&!(o in e)&&t.push(`Missing required field: ${o}`),o in e&&r.type){let s=typeof e[o];s!==r.type&&t.push(`Field '${o}' expected ${r.type}, got ${s}`)}if(r.validate&&o in e){let s=r.validate(e[o]);s&&t.push(`Field '${o}': ${s}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
115
122
|
${t.join(`
|
|
116
|
-
`)}`);return e}};W();le();Re();import{writeFileSync as ze,readFileSync as Wt,existsSync as Yt,mkdirSync as Hr}from"node:fs";import{join as He,dirname as Zr}from"node:path";import Te from"chalk";var Ze=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new _e(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){let o=()=>t&&typeof t.getAll=="function"?t.getAll():e,r=
|
|
123
|
+
`)}`);return e}};W();le();Re();import{writeFileSync as ze,readFileSync as Wt,existsSync as Yt,mkdirSync as Hr}from"node:fs";import{join as He,dirname as Zr}from"node:path";import Te from"chalk";var Ze=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new _e(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){let o=()=>t&&typeof t.getAll=="function"?t.getAll():e,r=p=>t&&typeof t.get=="function"?t.get(p):e?.[p];if(typeof this.customExecute=="function"){a.info("\u26A1 Using custom execute method (skipping LLM)");try{let p=await this.customExecute(e);return typeof p=="object"&&p!==null&&p.success===!1?{success:!1,error:p.error||"Node execution failed",raw:p.raw||null}:this.isZodSchema?(a.debug("Validating return value against outputSchema..."),{success:!0,output:this.outputSchema.parse(p),raw:null}):{success:!0,output:p,raw:null}}catch(p){return a.error(`\u274C Node '${this.name}' execution failed: ${p.message}`),p.name==="ZodError"&&a.error(`Schema validation errors: ${JSON.stringify(p.errors,null,2)}`),{success:!1,error:p.message,raw:null}}}let s=typeof this.prompt=="function"?this.prompt(o()):this.prompt,i=r("_skillHints");i&&(s=`${i}
|
|
117
124
|
|
|
118
|
-
${s}`);let l=o(),c=l.cwd||process.cwd(),u=l.sessionPath;try{if(u){let
|
|
119
|
-
\u{1F50D} ${Te.cyan("Validated output:")} ${Te.white(JSON.stringify(E,null,2))}`);let w=E;if(typeof this.onComplete=="function")try{w=await this.onComplete(o(),E)}catch(P){a.warn(`onComplete hook failed: ${P.message}`)}return{success:!0,output:w,raw:
|
|
120
|
-
\u{1F50D} ${Te.cyan("Parsed output:")} ${Te.white(JSON.stringify(w,null,2))}`),j.step("Output parsed"),{success:!0,output:w,raw:
|
|
125
|
+
${s}`);let l=o(),c=l.cwd||process.cwd(),u=l.sessionPath;try{if(u){let p=He(u,ae);if(Yt(p)){let S=JSON.parse(Wt(p,"utf-8"));S.currentNode=this.name,ze(p,JSON.stringify(S,null,2),"utf-8")}let m=He(u,"..",ae);if(Yt(m))try{let S=JSON.parse(Wt(m,"utf-8"));S.currentNode=this.name,ze(m,JSON.stringify(S,null,2),"utf-8")}catch{}}}catch(p){a.debug(`Could not update session info: ${p.message}`)}let d=null;for(let p=0;p<=this.retries;p++)try{a.debug(`Node.execute attempt ${p} for '${this.name}'`);let m=o(),S=m.config||{},A={state:m},k={workspace:c,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:u,config:S,nodeName:this.name,timeout:this.config?.timeout||3e5},h=e?._coreInvokeAgent;h||(h=(await Promise.resolve().then(()=>(Kt(),Gt))).invokeAgent);let _=await h(s,A,k),b,E;if(typeof _=="string"?(b=_,E=null):_.structured?(b=_.raw||JSON.stringify(_.structured,null,2),E=_.structured):(b=_.raw||JSON.stringify(_,null,2),E=_.extracted||null),u)try{let w=He(u,this.name,"raw_stream_output.txt");Hr(Zr(w),{recursive:!0}),ze(w,typeof b=="string"?b:JSON.stringify(b),"utf-8")}catch(w){a.debug(`Could not save raw output: ${w.message}`)}if(this.isZodSchema&&E){console.log(`
|
|
126
|
+
\u{1F50D} ${Te.cyan("Validated output:")} ${Te.white(JSON.stringify(E,null,2))}`);let w=E;if(typeof this.onComplete=="function")try{w=await this.onComplete(o(),E)}catch(P){a.warn(`onComplete hook failed: ${P.message}`)}return{success:!0,output:w,raw:b}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:b}),raw:b}}catch(w){throw new Error(`onComplete failed: ${w.message}`,{cause:w})}if(this.parser){let w=this.parser.parse(b);return console.log(`
|
|
127
|
+
\u{1F50D} ${Te.cyan("Parsed output:")} ${Te.white(JSON.stringify(w,null,2))}`),j.step("Output parsed"),{success:!0,output:w,raw:b}}return{success:!0,output:b,raw:b}}catch(m){d=m,p<this.retries&&a.info(`Node '${this.name}' failed, retrying (${p+1}/${this.retries})...`)}return{success:!1,error:d.message,raw:null}}},zt=class extends Ze{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,t){let o=t&&typeof t.getAll=="function"?t.getAll():e;return{success:!0,output:{nextNode:this.condition(o)},raw:null}}};export{zt as ConditionalNode,Ze as Node};
|