@zibby/core 0.1.38 → 0.1.41
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 +86 -72
- package/dist/framework/agents/cursor-strategy.js +49 -34
- package/dist/framework/agents/gemini-strategy.js +24 -15
- package/dist/framework/agents/index.js +80 -66
- package/dist/framework/agents/utils/cursor-output-formatter.js +2 -2
- package/dist/framework/agents/utils/prompt-builder.js +31 -0
- package/dist/framework/agents/utils/structured-output-formatter.js +1 -1
- package/dist/framework/code-generator.js +83 -69
- package/dist/framework/graph-compiler.js +91 -77
- package/dist/framework/graph.js +81 -67
- package/dist/framework/index.js +96 -82
- package/dist/framework/node-registry.js +75 -61
- package/dist/framework/node.js +78 -64
- package/dist/index.js +119 -105
- package/dist/package.json +1 -1
- package/package.json +1 -1
package/dist/framework/index.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Bo=Object.defineProperty;var et=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var B=(r,e)=>()=>(r&&(e=r(r=0)),e);var It=(r,e)=>{for(var t in e)Bo(r,t,{get:e[t],enumerable:!0})};import Ee from"chalk";var V,ot,u,z=B(()=>{V={debug:0,info:1,warn:2,error:3,silent:4},ot=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return V.debug;if(process.env.ZIBBY_VERBOSE==="true")return V.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in V?V[e]:V.info}_shouldLog(e){return V[e]>=this._level}_formatMessage(e,t,o={}){let s=new Date().toISOString(),i=`${this._getPrefix(e)} ${t}`;return Object.keys(o).length>0&&(i+=Ee.dim(` ${JSON.stringify(o)}`)),i}_getPrefix(e){return{debug:Ee.gray("[DEBUG]"),info:Ee.cyan("[INFO]"),warn:Ee.yellow("[WARN]"),error:Ee.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 V&&(this._level=V[e])}getLevel(){return Object.keys(V).find(e=>V[e]===this._level)}},u=new ot});import G from"chalk";function Rt(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function Mt(r,e){return(t,o,s)=>{if(typeof t!="string")return r(t,o,s);let n=process.stdout.columns||120,i="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(i+=Nt,e.col=Pt,e.lineStart=!1),l===`
|
|
2
2
|
`?(i+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,i+=l):e.inEsc?(i+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,i+=l,e.col>=n&&(i+=`
|
|
3
|
-
${
|
|
3
|
+
${Nt}`,e.col=Pt))}return r(i,o,s)}}var Fo,$e,Go,vt,st,Ct,kt,rt,Nt,Pt,nt,U,le=B(()=>{Fo="__WORKFLOW_GRAPH_LOG__",$e=G.gray("\u2502"),Go=G.gray("\u250C"),vt=G.gray("\u2514"),st=G.green("\u25C6"),Ct=G.hex("#c084fc")("\u25C6"),kt=G.hex("#2dd4bf")("\u25C6"),rt=G.red("\u25C6"),Nt=`${$e} `,Pt=2;nt=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null;let e=String(process.env.ZIBBY_RUN_SOURCE||"").trim().toLowerCase(),t=String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1";this._emitWorkflowGraphMarkers=t||e==="studio"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=Mt(this._origStdoutWrite,e),process.stderr.write=Mt(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
4
4
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
5
5
|
`),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
|
|
6
|
-
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${
|
|
6
|
+
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Fo}${JSON.stringify(e)}
|
|
7
7
|
`;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
8
8
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
|
|
9
9
|
`)):process.stdout.write.bind(process.stdout)(`${e} ${t}
|
|
10
|
-
`)}step(e){this._origStdoutWrite?this._writeDot(
|
|
11
|
-
`)}stepTool(e){this._origStdoutWrite?this._writeDot(
|
|
12
|
-
`)}stepMemory(e){let t=
|
|
13
|
-
`)}stepFail(e){this._origStdoutWrite?this._writeDot(rt,
|
|
14
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${
|
|
15
|
-
`);this.buffer=t.pop()||"";let o="";for(let
|
|
16
|
-
`,o+=`${
|
|
17
|
-
`,this.extractedResult=n)}catch{if(
|
|
10
|
+
`)}step(e){this._origStdoutWrite?this._writeDot(st,e):process.stdout.write.bind(process.stdout)(`${$e} ${st} ${e}
|
|
11
|
+
`)}stepTool(e){this._origStdoutWrite?this._writeDot(Ct,e):process.stdout.write.bind(process.stdout)(`${$e} ${Ct} ${e}
|
|
12
|
+
`)}stepMemory(e){let t=G.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(kt,t):process.stdout.write.bind(process.stdout)(`${$e} ${kt} ${t}
|
|
13
|
+
`)}stepFail(e){this._origStdoutWrite?this._writeDot(rt,G.red(e)):process.stdout.write.bind(process.stdout)(`${$e} ${rt} ${G.red(e)}
|
|
14
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Go} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:o,details:s}=t;if(s)for(let i of s)this._rawWrite(`${st} ${i}`);let n=o?G.dim(` ${Rt(o)}`):"";this._rawWrite(`${vt} ${G.green("done")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,o={}){this._stopIntercepting();let{duration:s}=o,n=s?G.dim(` ${Rt(s)}`):"";this._rawWrite(`${rt} ${G.red(t)}`),this._rawWrite(`${vt} ${G.red("failed")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(G.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){this._rawWrite(G.green.bold("\u2713 Workflow completed"))}},U=new nt});var ce,Lt,ee,Be,Dt,Ue=B(()=>{ce=".zibby/output",Lt="sessions",ee=".session-info.json",Be=".zibby-studio-stop",Dt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"]});var J,te=B(()=>{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 K,it,at,Bt,je,oe=B(()=>{K={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"},it={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"},at={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"},Bt={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},je={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4}});var lt={};It(lt,{getAllSkills:()=>Fe,getSkill:()=>F,hasSkill:()=>jt,listSkillIds:()=>Ft,registerSkill:()=>Ut});function Ut(r){if(!r||typeof r.id!="string")throw new Error("Skill definition must include a string id");be.set(r.id,Object.freeze({...r}))}function F(r){return be.get(r)||null}function jt(r){return be.has(r)}function Fe(){return new Map(be)}function Ft(){return Array.from(be.keys())}var be,X=B(()=>{be=new Map});var ue,ct=B(()=>{ue=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(`
|
|
15
|
+
`);this.buffer=t.pop()||"";let o="";for(let s of t)if(s.trim())try{let n=JSON.parse(s);this._emitToolCalls(n);let i=this.extractText(n);if(i){if(this.rawText&&i.startsWith(this.rawText)){let a=i.substring(this.rawText.length);this.rawText=i,o+=a}else(!this.rawText.includes(i)||i.length<20)&&(this.rawText+=i,o+=i);this.tryExtractResult(this.rawText)}else this.isValidResult(n)&&(this.rawText+=`${s}
|
|
16
|
+
`,o+=`${s}
|
|
17
|
+
`,this.extractedResult=n)}catch{if(s.includes('"text"')||s.includes('"content"')){let i=s.match(/"text"\s*:\s*"([^"]*)/),a=s.match(/"content"\s*:\s*"([^"]*)/),l=i?i[1]:a?a[1]:null;l&&!this.rawText.includes(l)&&(o+=l,this.rawText+=l)}}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,a)=>{if(!i)return;let l=`${i}:${JSON.stringify(a??{})}`;this._lastToolEmit!==l&&(this._lastToolEmit=l,this.onToolCall(i,a??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 a=Object.keys(i);if(a.length===1){let l=a[0],c=i[l],d=c&&typeof c=="object"?c.args??c.input??c:void 0;t(l,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 s=e.message??e;if(Array.isArray(s?.tool_calls)){for(let i of s.tool_calls)t(i.name,o(i.input??i.arguments));return}let n=s?.content??e.content;if(Array.isArray(n))for(let i of n)(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,s;for(;(s=o.exec(e))!==null;){let p=s[1].trim();try{JSON.parse(p),t.push({text:p,source:"markdown"})}catch{}}let n=0,i=0;for(;n<e.length&&(n=e.indexOf("{",n),n!==-1);){let p=0,f=n;for(let S=n;S<e.length;S++)if(e[S]==="{")p++;else if(e[S]==="}"&&(p--,p===0)){f=S,t.push({text:e.substring(n,f+1),source:"brace"}),i++;break}n=f+1}let a=this.extractedResult,l=a?JSON.stringify(a).length:0,c=0,d=-1;for(let p=0;p<t.length;p++){let f=t[p];try{let S=f.text.replace(/,(\s*[}\]])/g,"$1"),h=JSON.parse(S);this.isValidResult(h)&&(c++,l=JSON.stringify(h).length,a=h,d=p)}catch{}}a&&(this.extractedResult=a)}isValidResult(e){if(!e||typeof e!="object"||Array.isArray(e)||e.session_id||e.timestamp_ms||e.type||e.call_id||e.tool_call||e.result&&typeof e.result=="object"&&(e.result.success&&typeof e.result.success=="object"||e.result.error&&typeof e.result.error=="object")||e.args&&typeof e.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(e),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(e,t=null){let o=new r;o.zodSchema=t,o.processChunk(e),o.flush();let s=o.getResult();return!s&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),s}}});import{zodToJsonSchema as Jo}from"zod-to-json-schema";var Ge,Gt=B(()=>{Ge=class{static generateFileOutputInstructions(e,t){let o;typeof e?.parse=="function"?o=Jo(e,{target:"openApi3"}):o=e;let s=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
|
|
@@ -27,25 +27,35 @@ DO NOT just output JSON to stdout. The file MUST exist when you finish.
|
|
|
27
27
|
DO NOT skip this step. The workflow WILL FAIL if the file is missing.
|
|
28
28
|
|
|
29
29
|
Required JSON structure:
|
|
30
|
-
${JSON.stringify(
|
|
30
|
+
${JSON.stringify(s,null,2)}
|
|
31
31
|
|
|
32
32
|
JSON types (strict \u2014 validators reject wrong types):
|
|
33
33
|
- Use bare JSON numbers for numeric fields (e.g. 3000). Do NOT quote them as strings (wrong: "3000").
|
|
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[
|
|
38
|
-
|
|
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[s,n]of Object.entries(e.properties))o[s]=this._buildExample(n);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(s=>s.type!=="null")||e.anyOf?.find(s=>s.type!=="null");return o?this._buildExample(o):null}return"<value>"}}});var de,ut=B(()=>{Gt();de=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+=`
|
|
38
|
+
|
|
39
|
+
${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=Ge.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
|
|
40
|
+
\u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
41
|
+
\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
|
|
42
|
+
|
|
43
|
+
${e.trim()}`;this.systemInstructions.push({type:"extra_instructions",content:t,position:"append"})}return this}addSkillFragments(e){return e&&e.length>0&&this.systemInstructions.push({type:"skill_fragments",content:e.join(`
|
|
44
|
+
|
|
45
|
+
`),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(s=>s.position==="prepend").map(s=>s.content),t=this.systemInstructions.filter(s=>s.position==="append").map(s=>s.content);return[...e,this.userPrompt,...t].filter(Boolean).join(`
|
|
46
|
+
|
|
47
|
+
`)}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 Ko from"axios";import{homedir as Yo}from"node:os";import{join as Wo}from"node:path";import{existsSync as zo,readFileSync as Zo}from"node:fs";import{toJSONSchema as Ho}from"zod";function Vo(){if(process.env.OPENAI_PROXY_TOKEN)return u.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return u.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let r=Wo(Yo(),".zibby","config.json");if(zo(r)){let e=JSON.parse(Zo(r,"utf-8"));if(e.sessionToken)return u.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(r){u.debug(`[Auth] Could not read zibby login session: ${r.message}`)}return null}function Xo(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function fe(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(fe)}else"additionalProperties"in r||(r.additionalProperties=!0);r.type==="array"&&r.items&&fe(r.items),r.anyOf&&r.anyOf.forEach(fe),r.oneOf&&r.oneOf.forEach(fe),r.allOf&&r.allOf.forEach(fe)}}async function Jt(r,e){u.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=Vo();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=Xo();u.info(`\u{1F517} Using OpenAI proxy: ${o}`);let s=Ho(e),n=s;if(s.$ref&&s.definitions){let d=s.$ref.split("/").pop();n=s.definitions[d]||s,u.debug(`Extracted schema from $ref: ${d}`)}delete n.$schema,fe(n);let i=4e5,a=r;r.length>i&&(u.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${r.length} chars) exceeds limit, keeping last ${i} chars`),a=`... [truncated early content] ...
|
|
48
|
+
${r.slice(-i)}`);let l=`Extract and format the following information into structured JSON matching the schema.
|
|
39
49
|
|
|
40
50
|
RAW CONTENT:
|
|
41
51
|
${a}
|
|
42
52
|
|
|
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.`,c={model:
|
|
53
|
+
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.`,c={model:K.OPENAI_POSTPROCESSING,messages:[{role:"user",content:l}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:n,strict:!0}}};u.info(`\u{1F4E4} Sending to OpenAI proxy: model=${K.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(n.properties||{}).join(", ")}`),u.debug(` Schema size: ${JSON.stringify(n).length} chars`),u.debug(` Prompt size: ${l.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 f=(await Ko.post(o,c,{headers:d,timeout:je.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!f)throw new Error("OpenAI proxy returned empty response");let S=JSON.parse(f);return u.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:S,raw:r}}catch(d){if(d.response){let p=d.response.status,f=d.response.data;throw u.error(`\u274C OpenAI proxy request failed: ${p}`),u.error(` Status: ${p}`),u.error(` Response: ${JSON.stringify(f,null,2)}`),p===401||p===403?new Error(`Authentication failed for OpenAI proxy.
|
|
44
54
|
Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
|
|
45
|
-
Response: ${JSON.stringify(f)}`,{cause:d}):new Error(`Failed to format Cursor output: ${f?.error?.message||"Unknown error"}`,{cause:d})}throw u.error(`\u274C OpenAI proxy request failed: ${d.message}`),new Error(`Failed to format output: ${d.message}`,{cause:d})}}var
|
|
55
|
+
Response: ${JSON.stringify(f)}`,{cause:d}):new Error(`Failed to format Cursor output: ${f?.error?.message||"Unknown error"}`,{cause:d})}throw u.error(`\u274C OpenAI proxy request failed: ${d.message}`),new Error(`Failed to format output: ${d.message}`,{cause:d})}}var Kt=B(()=>{z();oe()});import{copyFileSync as qo,existsSync as dt,lstatSync as Qo,mkdirSync as Yt,rmSync as es,symlinkSync as ts,unlinkSync as os}from"node:fs";import{join as Q}from"node:path";import{homedir as ss}from"node:os";import{randomBytes as rs}from"node:crypto";function Wt(r){return!(!r||typeof r!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function zt(r){let e=Q(r||process.cwd(),".zibby","tmp");Yt(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${rs(4).toString("hex")}`,o=Q(e,`cursor-agent-home-${t}`),s=Q(o,".cursor");Yt(s,{recursive:!0});let n=ss(),i=Q(n,".cursor");if(dt(i))for(let a of ns){let l=Q(i,a);if(dt(l))try{qo(l,Q(s,a))}catch{}}if(process.platform==="darwin"){let a=Q(n,"Library");if(dt(a))try{ts(a,Q(o,"Library"))}catch{}}return o}function Zt(r){if(!(!r||typeof r!="string"))try{let e=Q(r,"Library");try{Qo(e).isSymbolicLink()&&os(e)}catch{}es(r,{recursive:!0,force:!0})}catch{}}var ns,Ht=B(()=>{ns=["cli-config.json","config.json","auth.json","argv.json"]});import{spawn as is,execSync as se}from"node:child_process";import{writeFileSync as Vt,readFileSync as Xt,mkdirSync as qt,existsSync as xe,accessSync as Qt,constants as eo,unlinkSync as as}from"node:fs";import{join as Z,resolve as ls}from"node:path";import{homedir as Oe}from"node:os";var Te,to=B(()=>{te();z();oe();Ue();X();ct();ut();Kt();le();Ht();Te=class extends J{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[Z(Oe(),".local","bin","cursor-agent"),Z(Oe(),".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("/")){Qt(o,eo.X_OK);let s=se(`"${o}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return u.debug(`[Cursor] Found agent at: ${o} (version: ${s.trim().slice(0,50)})`),!0}else{let s=se(`which ${o}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!s)continue;let n=se(`${o} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(n&&n.length>0)return u.debug(`[Cursor] Found '${o}' in PATH at ${s} (version: ${n.trim().slice(0,50)})`),!0}}catch{continue}return u.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:s=!1,schema:n=null,skills:i=null,sessionPath:a=null,nodeName:l=null,timeout:c=je.CURSOR_AGENT_DEFAULT,config:d={}}=t,p=d?.agent?.strictMode||!1,f=t.model??d?.agent?.cursor?.model??K.CURSOR;u.debug(`[Cursor] Invoking (model: ${f}, timeout: ${c/1e3}s, skills: ${JSON.stringify(i)})`);let h=(this._setupMcpConfig(a,o,d,i,l)||{}).isolatedMcpHome??null,x=[Z(Oe(),".local","bin","cursor-agent"),Z(Oe(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],y=null;for(let m of x)try{if(m.startsWith("/"))Qt(m,eo.X_OK),se(`"${m}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!se(`which ${m}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");se(`${m} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}y=m,u.debug(`[Agent] Using binary: ${m}`);break}catch(b){u.debug(`[Agent] Binary '${m}' check failed: ${b.message}`);continue}if(!y)throw new Error(`Cursor Agent CLI not found or not working.
|
|
46
56
|
|
|
47
57
|
Checked paths:
|
|
48
|
-
${
|
|
58
|
+
${x.map(m=>` - ${m}`).join(`
|
|
49
59
|
`)}
|
|
50
60
|
|
|
51
61
|
Install cursor-agent:
|
|
@@ -54,92 +64,96 @@ Install cursor-agent:
|
|
|
54
64
|
Then add to PATH:
|
|
55
65
|
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
|
|
56
66
|
|
|
57
|
-
Test with: agent --version`);let w=null;if(n){let
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
\
|
|
61
|
-
`);let
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
`)
|
|
67
|
+
Test with: agent --version`);let w=new de(e),g=null;if(n){let m=`zibby-result-${Date.now()}.json`;g=Z(o,".zibby","tmp",m);let b=Z(o,".zibby","tmp");xe(b)||qt(b,{recursive:!0}),w.addStructuredOutput(n,g)}let $=process.env.CURSOR_API_KEY,O=$?` | key: ***${$.slice(-4)}`:" | key: not set";console.log(`
|
|
68
|
+
\u25C6 Model: ${f||"auto"}${O}
|
|
69
|
+
`);let T=(await import("chalk")).default,C=w.getUserPrompt();console.log(`
|
|
70
|
+
${T.bold("Prompt sent to LLM:")}`),console.log(T.dim("\u2500".repeat(60))),console.log(T.dim(C)),console.log(T.dim("\u2500".repeat(60)));let E=w.build(),k=w.getStats(),A=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",f||"auto"];if(process.env.CURSOR_API_KEY&&A.push("--api-key",process.env.CURSOR_API_KEY),A.push(E),u.debug(`[Agent] User prompt: ${k.userPromptLength} chars, System instructions: ${k.systemInstructionsLength} chars (${k.instructionCount} blocks), Full: ${k.fullPromptLength} chars, model: ${f||"auto"}`),u.debug(`[Agent] Workspace: ${o}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${f||"auto"} (from .zibby.config.js agent.cursor.model)
|
|
71
|
+
`)}catch{}let M,_=null;try{let m=a||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);M=await this._spawnWithStreaming(y,A,o,c,null,m,h)}catch(m){_=m}let N=M?.stdout||"";if(n){let m=typeof n.parse=="function",b=null,I=!!(g&&xe(g));if(g&&u.info(`[Agent] Result file: ${I?"present":"missing"} at ${g}`),I)try{let v=Xt(g,"utf-8").trim();b=JSON.parse(v),u.info(`[Agent] Parsed JSON from result file OK (${v.length} chars) \u2192 object ready for validation`),_&&u.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(v){u.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${v.message}`)}else if(_)u.warn(`[Agent] Result file missing at ${g} (agent process error \u2014 may still recover if strictMode repairs)`);else throw u.error(`\u274C [Agent] Result file was never created at ${g}`),new Error(`Agent did not write required result file at ${g}`);if(b&&m)try{let v=n.parse(b);return u.info("\u2705 [Agent] Zod validation passed for structured result file"),p&&u.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:N,structured:v}}catch(v){let R=v.issues?v.issues.map(L=>` - ${L.path.join(".")}: ${L.message}`).join(`
|
|
72
|
+
`):v.message?.slice(0,400);if(u.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
|
|
73
|
+
${R}`),u.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
|
|
74
|
+
${JSON.stringify(b,null,2).slice(0,500)}`),!p)throw new Error(`Agent output failed schema validation:
|
|
75
|
+
${R}
|
|
76
|
+
|
|
77
|
+
The agent wrote invalid data that doesn't match the required outputSchema.
|
|
78
|
+
Enable strictMode in .zibby.config.js for automatic repair.`,{cause:v})}else{if(b)return u.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),p&&u.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:N,structured:b};I&&u.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(p&&!_){let v=M.parsedText,R=b?JSON.stringify(b):v;u.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${R.length} chars in)`);try{let L=await Jt(R,n);if(m){let D=n.parse(L.structured);return u.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:N,structured:D}}return{raw:N,...L}}catch(L){if(u.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${L.message}`),b)return u.warn("[Agent] Using agent's original result file as fallback"),{raw:N,structured:b}}}if(_)throw _;let j=I?b==null?"file existed but JSON.parse failed \u2014 see WARN log above":m?"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 u.error(`\u274C [Agent] No validated structured output: ${j}`),u.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 ${g}. Enable strictMode for proxy fallback.`)}if(_)throw _;return this._extractFinalResult(N)||M?.parsedText||N}_extractFinalResult(e){if(!e)return null;let t=e.split(`
|
|
79
|
+
`),o=null;for(let s of t){let n=s.trim();if(n)try{let i=JSON.parse(n);if(i.type==="assistant"&&i.message?.content){let a=i.message.content;if(Array.isArray(a)){let l=a.filter(c=>c.type==="text"&&c.text).map(c=>c.text).join("");l&&(o=l)}else typeof a=="string"&&a&&(o=a)}}catch{}}return o?.trim()||null}_setupMcpConfig(e,t,o,s=null,n=null){let i=o?.headless,a=Z(Oe(),".cursor"),l=Z(a,"mcp.json"),c={};if(xe(l))try{c=JSON.parse(Xt(l,"utf-8"))}catch{}let d=c.mcpServers||{},p=o?.paths?.output||ce,f=Z(t||process.cwd(),p,ee),S=Array.isArray(s)?s.map(y=>F(y)).filter(Boolean):[...Fe()].map(([,y])=>y),h=new Set;for(let y of S)typeof y.resolve=="function"&&(h.has(y.serverName)||(h.add(y.serverName),this._ensureSkillConfigured(d,y,e,f,n,i)));if(e){let y=F("browser");y&&typeof y.resolve=="function"&&!h.has(y.serverName)&&this._ensureSkillConfigured(d,y,e,f,"execute_live",i)}if(Object.keys(d).length===0)return u.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let x=`${JSON.stringify({mcpServers:d},null,2)}
|
|
80
|
+
`;if(Wt(e)){let y=zt(t||process.cwd()),w=Z(y,".cursor","mcp.json");return Vt(w,x,"utf8"),u.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${y} | servers: ${Object.keys(d).join(", ")}`),{isolatedMcpHome:y}}return xe(a)||qt(a,{recursive:!0}),Vt(l,x,"utf8"),u.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(d).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,o,s,n=null,i){let a=t.cursorKey||t.serverName,l=e[a]?a:e[t.serverName]?t.serverName:null;if(l&&o){let d=typeof t.resolve=="function"?t.resolve({sessionPath:o,nodeName:n,headless:i}):null;d?.args?e[l].args=d.args:e[l].args=(e[l].args||[]).map(S=>S.startsWith("--output-dir=")?`--output-dir=${o}`:S);let p=d?.env||{},f=t.sessionEnvKey?{[t.sessionEnvKey]:s}:{};e[l].env={...e[l].env||{},...p,...f},u.debug(`[MCP] Updated ${l} session \u2192 ${o}`);return}if(l)return;let c=t.resolve({sessionPath:o,nodeName:n,headless:i});c&&(e[a]={...c,...t.sessionEnvKey&&{env:{...c.env||{},[t.sessionEnvKey]:s}}},u.debug(`[MCP] Configured ${a}`))}_spawnWithStreaming(e,t,o,s,n=null,i=null,a=null){return new Promise((l,c)=>{let d=Date.now(),p="",f="",S=Date.now(),h=0,x=!1,y=null,w=!1,g=!1,$=null;if(i)try{$=Z(ls(String(i)),Be)}catch{$=null}let O=!1,T=()=>{O||(O=!0,Zt(a))},C={...process.env};a&&(C.HOME=a,process.platform==="win32"&&(C.USERPROFILE=a),u.debug(`[Agent] cursor-agent HOME=${a} (isolated MCP config)`));let E=is(e,t,{cwd:o,shell:!1,stdio:["pipe","pipe","pipe"],env:C});u.debug(`[Agent] PID: ${E.pid}`),E.stdin.on("error",m=>{m.code!=="EPIPE"&&u.warn(`[Agent] stdin error: ${m.message}`)}),E.stdout.on("error",m=>{m.code!=="EPIPE"&&u.warn(`[Agent] stdout error: ${m.message}`)}),E.stderr.on("error",m=>{m.code!=="EPIPE"&&u.warn(`[Agent] stderr error: ${m.message}`)}),n?(E.stdin.write(n,m=>{m&&m.code!=="EPIPE"&&u.warn(`[Agent] Failed to write to stdin: ${m.message}`),E.stdin.end()}),u.debug(`[Agent] Prompt also piped to stdin (${n.length} chars)`)):E.stdin.end();let k=null;$&&(k=setInterval(()=>{if(!(x||g))try{if(xe($)){x=!0,y="studio-stop";try{as($)}catch{}u.warn("\u{1F6D1} Studio stop requested \u2014 terminating Cursor agent (and MCP browser session)"),E.kill("SIGTERM"),setTimeout(()=>{E.killed||E.kill("SIGKILL")},2e3)}}catch{}},600));let A=new Set,M=new Date(d).toISOString().replace(/\.\d+Z$/,""),_=setInterval(()=>{let m=Math.round((Date.now()-d)/1e3),b=Math.round((Date.now()-S)/1e3),I=[];try{let v=Math.ceil(m/60)+1,R=se(`find "${o}" -type f -mmin -${v} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(R)for(let L of R.split(`
|
|
81
|
+
`)){let D=L.replace(`${o}/`,"");A.has(D)||(A.add(D),I.push(D))}}catch{}let j="";I.length>0&&(j=` | \u{1F4C1} new: ${I.map(R=>R.split("/").pop()).join(", ")}`),A.size>0&&(j+=` | \u{1F4E6} total: ${A.size} files`),u.debug(`\u{1F493} [Agent] Running for ${m}s | ${h} lines output${j}`),h===0&&m>=30&&A.size===0&&(m<35&&u.warn(`\u26A0\uFE0F [Agent] No output after ${m}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),m>=60&&(x=!0,y=y||"stall",u.error(`\u274C [Agent] No response after ${m}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),E.kill("SIGTERM"),setTimeout(()=>{E.killed||E.kill("SIGKILL")},3e3)))},3e4),N=setTimeout(()=>{x=!0,y=y||"timeout";let m=Math.round((Date.now()-d)/1e3);u.error(`\u23F1\uFE0F [Agent] Timeout after ${m}s \u2014 killing process (PID: ${E.pid})`),p.trim()&&u.warn(`\u{1F4E4} [Agent] Partial output (${p.length} chars) before timeout:
|
|
82
|
+
${p.slice(-2e3)}`),E.kill("SIGTERM"),setTimeout(()=>{E.killed||E.kill("SIGKILL")},5e3)},s),P=new ue;P.onToolCall=(m,b)=>{let I=m,j=b;if(m==="mcpToolCall"&&b?.name)I=b.name.replace(/^mcp_+[^_]+_+/,""),I.includes("-")&&I.split("-")[0]===I.split("-")[1]&&(I=I.split("-")[0]),j=b.args??b.input??b;else{if(m==="readToolCall"||m==="editToolCall"||m==="writeToolCall")return;(m.startsWith("mcp__")||m.includes("ToolCall"))&&(I=m.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(I.includes("memory")?U.stepMemory(`Tool: ${I}`):U.stepTool(`Tool: ${I}`),j!=null&&typeof j=="object"&&Object.keys(j).length>0&&!g){let R=JSON.stringify(j),L=R.length>100?`${R.substring(0,100)}...`:R;console.log(` Input: ${L}`)}},E.stdout.on("data",m=>{let b=m.toString();p+=b,S=Date.now(),w||(w=!0);let I=P.processChunk(b);I&&!g&&process.stdout.write(I);let j=b.split(`
|
|
83
|
+
`).filter(v=>v.trim());h+=j.length}),E.stderr.on("data",m=>{let b=m.toString();f+=b,S=Date.now(),w||(w=!0);let I=b.split(`
|
|
84
|
+
`).filter(j=>j.trim());for(let j of I)u.warn(`\u26A0\uFE0F [Agent stderr] ${j}`)}),E.on("close",(m,b)=>{g=!0,T(),clearTimeout(N),clearInterval(_),k&&clearInterval(k),P.flush();let I=Math.round((Date.now()-d)/1e3);if(u.debug(`[Agent] Exited: code=${m}, signal=${b}, elapsed=${I}s, output=${p.length} chars`),x){if(y==="studio-stop"){c(new Error("Stopped from Zibby Studio"));return}c(new Error(`Cursor Agent timed out after ${I}s (limit: ${s/1e3}s). ${h} lines produced. Last output ${Math.round((Date.now()-S)/1e3)}s ago. ${p.trim()?`
|
|
70
85
|
Partial output (last 500 chars):
|
|
71
|
-
${p.slice(-500)}`:"No output captured."}`));return}if(m!==0){c(new Error(`Cursor Agent failed: exit code ${m}, signal ${
|
|
86
|
+
${p.slice(-500)}`:"No output captured."}`));return}if(m!==0){c(new Error(`Cursor Agent failed: exit code ${m}, signal ${b}. ${f.trim()?`
|
|
72
87
|
Stderr: ${f.slice(-1e3)}`:""}${p.trim()?`
|
|
73
|
-
Stdout (last 500 chars): ${p.slice(-500)}`:""}`));return}let
|
|
88
|
+
Stdout (last 500 chars): ${p.slice(-500)}`:""}`));return}let j=P.getResult(),v=j?JSON.stringify(j,null,2):P.getRawText()||p||"";l({stdout:p||f||"",parsedText:v})}),E.on("error",m=>{T(),clearTimeout(N),clearInterval(_),k&&clearInterval(k),c(new Error(`Cursor Agent spawn error: ${m.message}
|
|
74
89
|
Binary: ${e}
|
|
75
90
|
This usually means the binary is not in PATH. Try:
|
|
76
|
-
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}}});import{query as
|
|
77
|
-
\u25C6 Model: ${
|
|
91
|
+
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}}});import{query as cs}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as us}from"zod-to-json-schema";var Ae,oo=B(()=>{te();z();le();oe();X();Ae=class extends J{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!process.env.ANTHROPIC_API_KEY;return t||u.debug("ClaudeAgentStrategy: ANTHROPIC_API_KEY not set"),t}async invoke(e,t={}){let{model:o,workspace:s=process.cwd(),schema:n=null,images:i=[],skills:a=null,sessionPath:l=null,nodeName:c=null,timeout:d,config:p={}}=t,f=o;(!f||f==="auto")&&(u.debug(`Model is '${f||"undefined"}', using default: ${K.CLAUDE}`),f=K.CLAUDE);let S=it[f]||f;it[f]&&f!==S&&u.debug(`Mapped model: ${f} \u2192 ${S}`),u.debug(`Invoking Claude Agent SDK with model: ${S}, skills: ${JSON.stringify(a)}`);let h=process.env.ANTHROPIC_API_KEY,x=h?` | key: ***${h.slice(-4)}`:" | key: not set";console.log(`
|
|
92
|
+
\u25C6 Model: ${S}${x}
|
|
78
93
|
`);let y=(await import("chalk")).default;console.log(`
|
|
79
|
-
${y.bold("Prompt sent to LLM:")}`),console.log(y.dim("\u2500".repeat(60))),console.log(y.dim(e)),console.log(y.dim("\u2500".repeat(60)));let{allowedTools:w,mcpServers:
|
|
80
|
-
\u25C6 Model: ${
|
|
94
|
+
${y.bold("Prompt sent to LLM:")}`),console.log(y.dim("\u2500".repeat(60))),console.log(y.dim(e)),console.log(y.dim("\u2500".repeat(60)));let{allowedTools:w,mcpServers:g}=this._resolveSkills(a,{sessionPath:l,workspace:s,nodeName:c});try{let $={cwd:s,allowedTools:w,permissionMode:"bypassPermissions",model:S,...Object.keys(g).length>0&&{mcpServers:g}};if(n){let N=typeof n.parse=="function"?us(n,{target:"openApi3"}):n;$.outputFormat={type:"json_schema",schema:N},u.debug("Structured output enforced via SDK outputFormat")}u.debug(`Agent SDK options: ${JSON.stringify({cwd:$.cwd,toolCount:w.length,permissionMode:$.permissionMode,model:$.model,hasOutputFormat:!!$.outputFormat})}`);let O="",T=0,C=[];u.debug("Starting Claude Agent SDK query stream");let E;try{E=cs({prompt:e,options:$})}catch(_){throw u.error(`Failed to initialize Claude Agent SDK: ${_.message}`),_}let k=null,A=0,M=3;try{for await(let _ of E){if(C.push(_),_.type==="error"||_.error){let P=_.error?.message||_.error||_.message||"Unknown API error";throw new Error(typeof P=="string"?P:JSON.stringify(P))}let N=JSON.stringify(_.message?.content||_.text||"").slice(0,200);if(N===k){if(A++,A>=M){let P=(_.message?.content?.[0]?.text||_.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${A}x repeated): ${P}`)}}else k=N,A=1;if(_.type==="assistant"||_.constructor?.name==="AssistantMessage"){let P=_.message?.content||_.content||[];for(let m of P)if(m.type==="thinking"&&m.thinking)console.log(`${m.thinking.substring(0,200)}${m.thinking.length>200?"...":""}`);else if(m.type==="text"&&m.text)O+=m.text,m.text.length<500?console.log(`${m.text}`):console.log(`${m.text.substring(0,200)}... (${m.text.length} chars)`);else if(m.type==="tool_use"){T++,m.name.includes("memory")?U.stepMemory(`Tool: ${m.name}`):U.stepTool(`Tool: ${m.name}`);let I=JSON.stringify(m.input).substring(0,100);console.log(` Input: ${I}${JSON.stringify(m.input).length>100?"...":""}`)}}else if(!(_.type==="user"&&_.tool_use_result)){if(_.type==="result"||_.constructor?.name==="ResultMessage"){let P=_.result||_.text||_.content||O;if(n){if(_.structured_output){u.debug("Using SDK native structured_output");let b=typeof n.parse=="function"?n.parse(_.structured_output):_.structured_output;return{raw:P,structured:b}}if(P){let m=this._extractJson(P,n);if(m)return{raw:P,structured:m}}u.warn(`Could not extract structured output \u2014 returning raw text (${(P||"").length} chars)`)}return P||""}}}if(u.warn(`Agent SDK ended without result. Collected ${C.length} messages`),O.length>0)return u.debug("Returning accumulated text from messages"),O;throw new Error("Claude Agent SDK query ended without result")}catch(_){throw u.error(`Error during query stream: ${_.message}`),_}}catch($){throw u.error("Claude Agent SDK call failed",{error:$.message}),$}}_resolveSkills(e,t){if(e===null)return u.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return u.debug("Default IDE skills for code generation"),{allowedTools:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};let o=[],s={};for(let n of e){let i=F(n);if(!i){u.warn(`Unknown skill "${n}" \u2014 skipping`);continue}if(i.allowedTools&&o.push(...i.allowedTools),typeof i.resolve=="function"){let a=i.resolve(t);a&&(s[i.serverName]=a,u.debug(`MCP: ${i.serverName} \u2192 ${a.command} ${a.args[0]}`))}}return{allowedTools:o,mcpServers:s}}_extractJson(e,t){let o=[()=>{if(e.includes("===JSON_START===")){let s=e.indexOf("===JSON_START===")+16,n=e.indexOf("===JSON_END===");return e.substring(s,n).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 s=e.indexOf("{"),n=e.lastIndexOf("}");if(s!==-1&&n>s)return e.substring(s,n+1)}];for(let s of o)try{let n=s();if(!n)continue;let i=JSON.parse(n);if(typeof i!="object"||i===null)continue;return typeof t.parse=="function"?t.parse(i):i}catch{}return null}}});import{execSync as ds}from"node:child_process";import{zodToJsonSchema as fs}from"zod-to-json-schema";var Ie,so=B(()=>{te();z();le();oe();X();Ie=class extends J{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.CODEX_API_KEY))return u.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return ds("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return u.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:o,workspace:s=process.cwd(),schema:n=null,skills:i=null,sessionPath:a=null,nodeName:l=null,timeout:c,config:d={}}=t,{Codex:p}=await import("@openai/codex-sdk"),f=o;(!f||f==="auto")&&(u.debug(`Model is '${f||"undefined"}', using default: ${K.CODEX}`),f=K.CODEX);let S=at[f]||f;at[f]&&f!==S&&u.debug(`Mapped model: ${f} \u2192 ${S}`),u.debug(`Invoking Codex SDK with model: ${S}, skills: ${JSON.stringify(i)}`);let h=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;h&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=h);let x=h?` | key: ***${h.slice(-4)}`:" | key: not set";console.log(`
|
|
95
|
+
\u25C6 Model: ${S}${x}
|
|
81
96
|
`);let y=(await import("chalk")).default;console.log(`
|
|
82
|
-
${y.bold("Prompt sent to LLM:")}`),console.log(y.dim("\u2500".repeat(60))),console.log(y.dim(e)),console.log(y.dim("\u2500".repeat(60)));let w=this._resolveSkillsToMcp(i,{sessionPath:a,workspace:
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
${
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
${
|
|
89
|
-
${
|
|
90
|
-
|
|
91
|
-
`,"utf-8");let
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
`)
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
\
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
`)}`)}let _=e.state?._currentNodeConfig?.extraPromptInstructions?.trim();return _&&(s+=`
|
|
97
|
+
${y.bold("Prompt sent to LLM:")}`),console.log(y.dim("\u2500".repeat(60))),console.log(y.dim(e)),console.log(y.dim("\u2500".repeat(60)));let w=this._resolveSkillsToMcp(i,{sessionPath:a,workspace:s,nodeName:l}),g={};Object.keys(w).length>0&&(g.mcp_servers=w,u.debug(`[Codex] MCP servers: ${Object.keys(w).join(", ")}`));let O=new p({...Object.keys(g).length>0&&{config:g}}).startThread({workingDirectory:s,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),T=n&&typeof n.parse=="function",C={};if(n)try{let E=T?fs(n,{target:"openAi"}):n;C.outputSchema=E,u.debug("Structured output via SDK outputSchema")}catch(E){u.warn(`[Codex] Schema conversion failed, will extract from text: ${E.message}`)}try{let{events:E}=await O.runStreamed(e,C),k=0,A="";for await(let M of E){let _=M.type;if(_==="item.completed"){let N=M.item,P=N?.type;if(P==="mcp_tool_call"){k++;let m=`${N.server}/${N.tool}`;if(U.stepTool(`Tool: ${m}`),N.arguments){let b=JSON.stringify(N.arguments),I=b.length>100?`${b.substring(0,100)}...`:b;console.log(` Input: ${I}`)}}else if(P==="tool_call"||P==="function_call"||P==="command_execution"){k++;let m=N.name||N.tool||N.command||"unknown";U.stepTool(`Tool: ${m}`)}else P==="agent_message"&&(A=N.text||"",A.length<500?console.log(A):console.log(`${A.substring(0,200)}... (${A.length} chars)`))}else _==="turn.completed"?u.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(M.usage||{})}`):u.debug(`[Codex] Event: ${_} ${JSON.stringify(M).slice(0,300)}`)}if(u.debug(`[Codex] Last agent message (${A.length} chars): ${A.slice(0,500)}`),n){if(!A)throw new Error("Codex agent returned no response");let M=JSON.parse(A),_=T?n.parse(M):M;return u.debug("\u2705 [Codex] Structured output validated"),{raw:A,structured:_}}return A||""}catch(E){let k=E.message||String(E);throw u.error(`\u274C [Codex] SDK call failed: ${k}`),k.includes("exited with code")&&(u.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),u.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),E}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let o={};for(let s of e){let n=F(s);if(!n){u.warn(`[Codex] Unknown skill "${s}" \u2014 skipping`);continue}if(typeof n.resolve!="function")continue;let i=n.resolve(t);if(!i)continue;let a=n.serverName||s,l={command:i.command};i.args?.length&&(l.args=i.args),i.env&&Object.keys(i.env).length>0&&(l.env=i.env),o[a]=l,u.debug(`[Codex] MCP: ${a} \u2192 ${i.command} ${(i.args||[]).join(" ")}`)}return o}}});import{execSync as ps,spawn as ms}from"node:child_process";import{zodToJsonSchema as gs}from"zod-to-json-schema";import{existsSync as ro,mkdirSync as no,readFileSync as io,rmSync as hs,writeFileSync as ao}from"node:fs";import{join as re}from"node:path";function ys(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 s=0,n=!1,i=!1,a=-1;for(let l=o;l<e.length;l++){let c=e[l];if(n){i?i=!1:c==="\\"?i=!0:c==='"'&&(n=!1);continue}if(c==='"'){n=!0;continue}if(c==="{"){s===0&&(a=l),s+=1;continue}if(c==="}"){if(s===0)continue;if(s-=1,s===0&&a>=0){let d=e.slice(a,l+1);try{return JSON.parse(d)}catch{a=-1}}}}return null}function Ss(r){let e=String(r||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return ys(e)}}function _s(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(s=>typeof s?.text=="string"?s.text:"").join("");if(o.trim())return o}}}catch{}return r}var ve,lo=B(()=>{te();z();oe();X();ut();ct();ve=class extends J{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY))return u.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return ps("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return u.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:o,workspace:s=process.cwd(),schema:n=null,skills:i=null,sessionPath:a=null,nodeName:l=null,timeout:c=600*1e3}=t,d=o;(!d||d==="auto")&&(d=K.GEMINI);let p=Bt[d]||d,f=String(process.env.GEMINI_API_KEY||"").trim(),S=String(process.env.GOOGLE_API_KEY||"").trim(),h=this._resolveSkillsToMcp(i,{sessionPath:a,workspace:s,nodeName:l}),x=Object.keys(h).length>0,y=new de(e),w=n&&typeof n.parse=="function",g=null;if(n){let v;try{let R=w?gs(n,{target:"openAi"}):n;v=JSON.stringify(R,null,2)}catch{v="{}"}if(x){y.addSystemInstruction(`Write valid JSON that matches this schema:
|
|
98
|
+
${v}`,"schema_instruction","append");let R=`zibby-result-${Date.now()}.json`,L=re(s,".zibby","tmp");g=re(L,R),no(L,{recursive:!0}),y.addStructuredOutput(n,g)}else y.addSystemInstruction(`Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
|
|
99
|
+
${v}`,"json_instruction","append")}let $=y.build(),O=y.getUserPrompt(),T=y.getStats(),C=String(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||"").trim(),E=C?` | key: ***${C.slice(-4)}`:" | key: not set";console.log(`
|
|
100
|
+
\u25C6 Model: ${p||"auto"}${E}
|
|
101
|
+
`);let k=(await import("chalk")).default;console.log(`
|
|
102
|
+
${k.bold("Prompt sent to LLM:")}`),console.log(k.dim("\u2500".repeat(60))),console.log(k.dim(O)),console.log(k.dim("\u2500".repeat(60)));let A=this._createGeminiConfigDir(s,h),M=["--output-format","json"];p&&p!=="auto"&&M.push("--model",p);let _=Object.keys(h);if(_.length>0){M.push("--approval-mode","yolo");for(let v of _)M.push("--allowed-mcp-server-names",v);u.info(`[Gemini] Enabling MCP servers: ${_.join(", ")}`)}else i&&i.length>0&&u.warn(`[Gemini] Skills requested but no MCP servers configured: ${i.join(", ")}`);M.push("-p",$);let N={...process.env,GEMINI_CLI_HOME:A};f?(N.GEMINI_API_KEY=f,delete N.GOOGLE_API_KEY):S&&(N.GOOGLE_API_KEY=S,delete N.GEMINI_API_KEY),u.debug(`[Gemini] Command: gemini ${M.slice(0,8).join(" ")}... (${M.length} total args)`),u.debug(`[Gemini] User prompt: ${T.userPromptLength} chars, System instructions: ${T.systemInstructionsLength} chars (${T.instructionCount} blocks), Full: ${T.fullPromptLength} chars`),u.debug(`[Gemini] Config home: ${A}`),u.debug(`[Gemini] GEMINI_CLI_HOME env: ${N.GEMINI_CLI_HOME}`);let P="",m=null;try{P=await new Promise((R,L)=>{let D=ms("gemini",M,{cwd:s,env:N,stdio:["ignore","pipe","pipe"]}),q="",ae="",W=setTimeout(()=>{try{D.kill("SIGTERM")}catch{}},c);D.stdout.on("data",Y=>{q+=Y.toString()}),D.stderr.on("data",Y=>{ae+=Y.toString()}),D.on("error",Y=>{clearTimeout(W),L(Y)}),D.on("close",Y=>{if(clearTimeout(W),Y===0)return R(q.trim());L(new Error(`gemini failed with code ${Y}: ${(ae||q).trim()}`))})})}catch(v){m=v}finally{try{hs(A,{recursive:!0,force:!0})}catch{}}let b=_s(P).trim();if(!n){if(m)throw m;return b}if(g){let v=ro(g);if(u.info(`[Gemini] Result file: ${v?"present":"missing"} at ${g}`),v)try{let R=io(g,"utf-8").trim(),L=JSON.parse(R),D=w?n.parse(L):L;return u.info("[Gemini] Structured output recovered from result file"),{raw:b,structured:D}}catch(R){u.warn(`[Gemini] Result file parse/validation failed: ${R.message}`)}else m||u.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let I=null;if(n){let v=new ue;v.zodSchema=n,v.processChunk(b),v.flush(),I=v.getResult()}if(u.info(`[Gemini] Raw stdout length: ${P.length} chars`),u.info(`[Gemini] Extracted text length: ${b.length} chars`),u.info(`[Gemini] StreamParser result: ${I?"extracted":"null"}`),I||(b.length<2e3?u.info(`[Gemini] Raw text preview:
|
|
103
|
+
${b}`):u.info(`[Gemini] Raw text preview (first 1000 chars):
|
|
104
|
+
${b.slice(0,1e3)}`),I=Ss(b)),!I)throw m||(u.error("[Gemini] Failed to extract valid JSON from output"),u.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error("Gemini did not return valid JSON for structured output. Enable strictMode for proxy fallback."));let j=w?n.parse(I):I;return{raw:b,structured:j}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let o={};for(let s of e){let n=F(s);if(!n||typeof n.resolve!="function")continue;let i=n.resolve(t);if(!i)continue;let a=n.cursorKey||n.serverName||s,l={command:i.command};i.args?.length&&(l.args=i.args),i.env&&Object.keys(i.env).length>0&&(l.env=i.env),i.cwd&&(l.cwd=i.cwd),o[a]=l}return o}_createGeminiConfigDir(e,t){let o=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,s=re(e||process.cwd(),".zibby","tmp",`gemini-home-${o}`),n=re(s,".gemini");no(n,{recursive:!0});let i=re(n,"settings.json"),a={},l=re(process.env.HOME||"",".gemini","settings.json");if(ro(l))try{a=JSON.parse(io(l,"utf-8"))}catch{a={}}let c={...a,mcpServers:{...a.mcpServers&&typeof a.mcpServers=="object"?a.mcpServers:{},...t||{}}};ao(i,`${JSON.stringify(c,null,2)}
|
|
105
|
+
`,"utf-8");let d=re(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{ao(d,`${JSON.stringify(c,null,2)}
|
|
106
|
+
`,"utf-8")}catch{}return u.debug(`[Gemini] Created isolated config with ${Object.keys(c.mcpServers||{}).length} MCP servers`),u.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(c.mcpServers||{}),null,2)}`),s}}});var Ce,ft=B(()=>{Ce=class{formatTools(e){throw new Error("formatTools() must be implemented")}hasToolCalls(e){throw new Error("hasToolCalls() must be implemented")}parseToolCalls(e){throw new Error("parseToolCalls() must be implemented")}getTextContent(e){throw new Error("getTextContent() must be implemented")}buildAssistantMessage(e){throw new Error("buildAssistantMessage() must be implemented")}buildToolResultMessage(e,t){throw new Error("buildToolResultMessage() must be implemented")}injectToolsIntoBody(e,t){throw new Error("injectToolsIntoBody() must be implemented")}}});var pe,co=B(()=>{ft();pe=class extends Ce{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 ke,pt=B(()=>{ke=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 Je(r){return Buffer.byteLength(JSON.stringify(r),"utf8")}function Ke(r,e){let t=String(r||"");if(t.length<=e)return t;let o=Math.max(0,e-28);return`${t.slice(0,o)}
|
|
107
|
+
|
|
108
|
+
[truncated for size budget]`}function mt(r,e=0){if(!r||typeof r!="object"||e>8)return r;if(Array.isArray(r))return r.map(o=>mt(o,e+1));let t={};for(let[o,s]of Object.entries(r))o==="description"||o==="title"||o==="examples"||o==="default"||(t[o]=mt(s,e+1));return t}function ws(r=[]){return r.map(e=>({...e,function:{...e.function,description:Ke(e.function?.description||"",180),parameters:mt(e.function?.parameters||{type:"object",properties:{}})}}))}function uo(r){let e=new Set;for(let s of r)if(s.role==="assistant"&&Array.isArray(s.tool_calls))for(let n of s.tool_calls)e.add(n.id);let t=r.filter(s=>s.role==="tool"?e.has(s.tool_call_id):!0),o=new Set;for(let s of t)s.role==="tool"&&o.add(s.tool_call_id);return t.map(s=>{if(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.every(l=>o.has(l.id)))return s;let{tool_calls:i,...a}=s;return{...a,content:a.content||""}})}function gt(r,e={}){let t=e.maxBytes||49e3,o=e.systemMaxChars||12e3,s={...r,messages:Array.isArray(r.messages)?[...r.messages]:[],tools:Array.isArray(r.tools)?ws(r.tools):r.tools};s.messages.length>0&&s.messages[0]?.role==="system"&&(s.messages[0]={...s.messages[0],content:Ke(s.messages[0].content,o)});let n=!1;for(;Je(s)>t&&s.messages.length>2;)s.messages.splice(1,1),n=!0;if(n&&(s.messages=uo(s.messages)),Je(s)>t&&s.messages.length>0&&(s.messages[0]={...s.messages[0],content:Ke(s.messages[0].content,6e3)},n=!0),Je(s)>t){let i=s.messages.find(l=>l.role==="system")||s.messages[0],a=s.messages.slice(-2);s.messages=uo([i,...a].filter(Boolean).map((l,c)=>({...l,content:Ke(l.content,c===0?4e3:8e3)}))),n=!0}return{body:s,meta:{bytes:Je(s),trimmed:n,maxBytes:t,messageCount:s.messages.length}}}var fo=B(()=>{});var po,me,mo=B(()=>{pt();fo();po=r=>Buffer.byteLength(JSON.stringify(r),"utf8"),me=class extends ke{async fetchCompletion(e,t,o={}){let s=po(e),{body:n,meta:i}=gt(e,o.payloadCompaction);o.onBudget?.({streaming:!1,beforeBytes:s,meta:i});let a=this.#e(o),l=`${t.baseUrl}${o.chatCompletionsPath||"/v1/chat/completions"}`,c=await fetch(l,{method:"POST",headers:t.headers,body:JSON.stringify(n),signal:a});if(!c.ok){let d=await c.text();throw c.status===401||c.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${c.status}: ${d}`)}return c.json()}async fetchStreamingCompletion(e,t,o={}){let s={...e,stream:!0},n=po(s),{body:i,meta:a}=gt(s,o.payloadCompaction);o.onBudget?.({streaming:!0,beforeBytes:n,meta:a});let l=this.#e(o),c=`${t.baseUrl}${o.chatCompletionsPath||"/v1/chat/completions"}`,d=await fetch(c,{method:"POST",headers:t.headers,body:JSON.stringify(i),signal:l});if(!d.ok){let y=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}: ${y}`)}let p=d.body.getReader(),f=new TextDecoder,S="",h="",x=new Map;for(;;){let{done:y,value:w}=await p.read();if(y)break;S+=f.decode(w,{stream:!0});let g=S.split(`
|
|
109
|
+
`);S=g.pop();for(let $ of g){if(!$.startsWith("data: "))continue;let O=$.slice(6).trim();if(O==="[DONE]")continue;let T;try{T=JSON.parse(O)}catch{continue}let C=T.choices?.[0]?.delta;if(C&&(C.content&&(h+=C.content,o.onToken&&o.onToken(C.content)),C.tool_calls))for(let E of C.tool_calls){let k=E.index??0;x.has(k)||x.set(k,{id:"",name:"",args:""});let A=x.get(k);E.id&&(A.id=E.id),E.function?.name&&(A.name=E.function.name),E.function?.arguments!=null&&(A.args+=E.function.arguments)}}}if(x.size>0){let y=[...x.entries()].sort(([w],[g])=>w-g).map(([,w])=>({id:w.id,type:"function",function:{name:w.name,arguments:w.args}}));return{choices:[{message:{role:"assistant",content:h||null,tool_calls:y}}]}}return{choices:[{message:{role:"assistant",content:h}}]}}#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 go=B(()=>{ft();co();pt();mo()});import{Client as Es}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as $s}from"@modelcontextprotocol/sdk/client/stdio.js";var Ye,ho=B(()=>{z();Ye=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:o,args:s=[],env:n={}}=t;u.debug(`[MCP] Starting ${e}: ${o} ${s.join(" ")}`);let i=new $s({command:o,args:s,env:{...process.env,...n}}),a=new Es({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await a.connect(i);let l={client:a,transport:i,serverConfig:t};return this.#e.set(e,l),l}async callTool(e,t,o={}){let s=this.#e.get(e);if(!s)throw new Error(`MCP server "${e}" not running`);u.debug(`[MCP] ${e}.${t}(${JSON.stringify(o).slice(0,200)})`);let n=await s.client.callTool({name:t,arguments:o});return{text:n.content?.filter(a=>a.type==="text").map(a=>a.text).join(`
|
|
110
|
+
`)||"",isError:n.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){u.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 bs,readFileSync as xs}from"node:fs";import{join as Os}from"node:path";import{homedir as Ts}from"node:os";function As(){try{let r=Os(Ts(),".zibby","config.json");return bs(r)?JSON.parse(xs(r,"utf-8")):{}}catch{return{}}}function We(r){return String(r||"").replace(/\/v1\/?$/,"")}function Is(r,e){let t=process.env.OPENAI_PROXY_URL;if(t)return We(t);if(r==="session")return e.proxyUrl?We(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 We(o||"https://api.openai.com")}return We(t||"")}function ht(){let r=As(),e=process.env.ZIBBY_USER_TOKEN||r.sessionToken||null,t=process.env.OPENAI_API_KEY||null,o=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),s=process.env.OPENAI_PROXY_NO_AUTH==="true",n=process.env.OPENAI_PROXY_URL,i="session";o==="byok"||o==="local"||o==="session"?i=o:e?i="session":t?i="byok":n&&s&&(i="local");let a=Is(i,r),l={"Content-Type":"application/json"};if(i==="session"){if(!e)return{ok:!1,mode:i,reason:"missing_session_token"};l.Authorization=`Bearer ${e}`}else if(i==="byok"){if(!t)return{ok:!1,mode:i,reason:"missing_openai_api_key"};l.Authorization=`Bearer ${t}`}else if(i==="local"){if(!a)return{ok:!1,mode:i,reason:"missing_openai_proxy_url"};!s&&t&&(l.Authorization=`Bearer ${t}`)}return a?{ok:!0,mode:i,baseUrl:a,headers:l,tokenPreview:l.Authorization?`***${l.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:i,reason:"missing_base_url"}}var yo=B(()=>{});function ze(r,e){let t=String(r??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
|
|
111
|
+
|
|
112
|
+
[tool result truncated for size]`}function vs(r,e){if(typeof r=="string")return ze(r,e);try{return ze(JSON.stringify(r),e)}catch{return ze(String(r),e)}}function So(r){let e=new Set;for(let s of r)if(s.role==="assistant"&&Array.isArray(s.tool_calls))for(let n of s.tool_calls)e.add(n.id);let t=r.filter(s=>s.role==="tool"?e.has(s.tool_call_id):!0),o=new Set;for(let s of t)s.role==="tool"&&o.add(s.tool_call_id);return t.map(s=>{if(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.every(l=>o.has(l.id)))return s;let{tool_calls:i,...a}=s;return{...a,content:a.content||""}})}function Cs(r){let e=Array.isArray(r?.messages)?r.messages:[],t=e.find(n=>n.role==="system"),o=e.slice(-4).map(n=>({...n,content:ze(n.content,n.role==="tool"?1200:2500)}));o=So(o);let s={...r,messages:[t,...o].filter(Boolean)};return delete s.tools,s}async function ks({body:r,streaming:e,auth:t,options:o,fetchCompletion:s,fetchStreamingCompletion:n,onFallbackLog:i}){try{return e?await n(r,t,o):await s(r,t,o)}catch(a){let l=String(a?.message||a||"");if(!/proxy error 413|payload too large/i.test(l))throw a;let c=Cs(r);return typeof i=="function"&&i(r,c),{data:e?await n(c,t,o):await s(c,t,o),fallback:c}}}async function _o({body:r,auth:e,options:t,streaming:o,toolContext:s,activeSkills:n,round:i,verbose:a,dependencies:l,config:c={}}){let d=c.maxToolResultChars||3e3,{fetchCompletion:p,fetchStreamingCompletion:f,onFallbackLog:S,hasToolCalls:h,getTextContent:x,parseToolCalls:y,buildAssistantMessage:w,buildToolResultMessage:g,executeTool:$,onToolCallLog:O,injectTools:T}=l;Array.isArray(r?.messages)&&(r.messages=So(r.messages));let C=await ks({body:r,streaming:o,auth:e,options:t,fetchCompletion:p,fetchStreamingCompletion:f,onFallbackLog:S}),E=C?.data||C;if(!h(E))return{done:!0,text:x(E),body:C?.fallback||r};let k=y(E),A=C?.fallback||r;A.messages.push(w(E)),a&&typeof O=="function"&&O(k);let M=await Promise.all(k.map((_,N)=>(typeof t.onToolCall=="function"&&t.onToolCall(_.name,_.args,{round:i,index:N,total:k.length}),$(_,s))));for(let _=0;_<k.length;_++){let P=k[_].name==="get_skill_context"?typeof M[_]=="string"?M[_]:JSON.stringify(M[_]):vs(M[_],d);A.messages.push(g(k[_].id,P))}return typeof t.onToolCall=="function"&&t.onToolCall(null),T(A,n),{done:!1,body:A}}var wo=B(()=>{});function he(r){!r||typeof r!="object"||(r.type==="object"&&r.properties&&(r.required=Object.keys(r.properties),r.additionalProperties=!1,Object.values(r.properties).forEach(he)),r.type==="array"&&r.items&&he(r.items),r.anyOf&&r.anyOf.forEach(he),r.oneOf&&r.oneOf.forEach(he),r.allOf&&r.allOf.forEach(he))}function Ze(r){return Array.isArray(r)?new Set(r.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function Ms(r){return Array.isArray(r)?r.map(e=>String(e||"").trim()).filter(Boolean):[]}var Ns,Ps,yt,Eo,ge,Rs,Ne,$o=B(()=>{te();z();oe();go();ho();X();yo();wo();Ns=K.ASSISTANT,Ps=15,yt="get_skill_context";Eo={maxBytes:49e3,systemMaxChars:12e3},ge=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",Rs=r=>Buffer.byteLength(JSON.stringify(r),"utf8");Ne=class extends J{#e;#t;#o=new Ye;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new pe,this.#t=e.completionProvider||new me):(this.#e=e||new pe,this.#t=new me)}canHandle(e){return ht().ok}async invoke(e,t={}){let o=t.model&&t.model!=="auto"?t.model:Ns,s=ht();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 n=t.messages||[{role:"user",content:e}],i=s.baseUrl,a=ge();if(a?await this.#m(n,o,i,s.tokenPreview||"none"):u.debug(`[Assistant] ${i} | model: ${o} | messages: ${n.length}`),t.schema)return this.#c(o,n,s,t);let l=t.activeSkills||[],c=this.#d(t),d=this.#f(l,c),p=this.#p(d),f=this.#u(t),S={...t,payloadCompaction:f},h={activeSkills:d,options:S,executionRegistry:p,capabilityPolicy:c},x=!!t.stream,y={model:o,messages:[...n],stream:!1};this.#r(y,d,c);for(let w=0;w<Ps;w++){if(t.signal?.aborted)throw new Error("Aborted");let g=await _o({body:y,auth:s,options:S,streaming:x,toolContext:h,activeSkills:d,round:w,verbose:a,dependencies:{fetchCompletion:this.#n.bind(this),fetchStreamingCompletion:this.#l.bind(this),onFallbackLog:($,O)=>{ge()&&console.log(`413 fallback: messages ${$.messages.length} -> ${O.messages.length}, bytes=${Rs(O)}`)},hasToolCalls:$=>this.#e.hasToolCalls($),getTextContent:$=>this.#e.getTextContent($),parseToolCalls:$=>this.#e.parseToolCalls($),buildAssistantMessage:$=>this.#e.buildAssistantMessage($),buildToolResultMessage:($,O)=>this.#e.buildToolResultMessage($,O),executeTool:($,O)=>this.#a($,O),onToolCallLog:async $=>{let O=(await import("chalk")).default;console.log(O.dim(` ${$.map(T=>`${T.name}(${JSON.stringify(T.args).slice(0,80)})`).join(", ")}`))},injectTools:($,O)=>this.#r($,O,c)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(g.done)return g.text;y.messages=g.body.messages,g.body.tools?y.tools=g.body.tools:delete y.tools}return"I hit my tool-calling limit for this turn. Please try again."}async cleanup(){await this.#o.stopAll()}#r(e,t,o=null){let s=this.#i(t,o),n=this.#e.formatTools(s);this.#e.injectToolsIntoBody(e,n)}#i(e,t=null){let o=[],s=new Set;for(let n of e){let i=F(n);if(i?.tools?.length)for(let a of i.tools)this.#s(a.name,t)&&(s.has(a.name)||(s.add(a.name),o.push({name:a.name,description:a.description,parameters:a.parameters||a.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#s(yt,t)&&o.push({name:yt,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:s,executionRegistry:n,capabilityPolicy:i}=t;if(!this.#s(e.name,i))return`Tool "${e.name}" blocked by policy`;if(e.name===yt){let c=String(e.args?.skillId||"").trim();if(!c)return JSON.stringify({error:"skillId is required"});if(!o.includes(c))return JSON.stringify({error:`Skill "${c}" is not active`,activeSkills:o});let d=F(c);if(!d)return JSON.stringify({error:`Skill "${c}" not found`});let p=typeof d.promptFragment=="function"?d.promptFragment():d.promptFragment||"",f=(d.tools||[]).map(h=>h.name),S=JSON.stringify({skillId:c,description:d.description||"",toolNames:f,promptFragment:p||""});return ge()&&(console.log(`
|
|
113
|
+
\u{1F4D6} get_skill_context("${c}") \u2192 ${S.length} chars (fragment: ${p.length} chars)`),console.log(` tools: [${f.join(", ")}]`),console.log(` fragment preview: ${p.slice(0,200).replace(/\n/g,"\\n")}\u2026
|
|
114
|
+
`)),S}let a=n?.get(e.name)||null;if(!a)return`Unknown tool: ${e.name}`;let l=F(a.skillId);if(!l)return`Skill "${a.skillId}" not found for tool "${e.name}"`;if(a.mode==="handler")try{return l.handleToolCall(e.name,e.args,t)}catch(c){return`Error in ${e.name}: ${c.message}`}if(a.mode==="mcp")try{if(!this.#o.isRunning(l.serverName)){let d=l.resolve(s);if(!d)return`Skill "${a.skillId}" is not available (cannot start server)`;await this.#o.ensureServer(l.serverName,d)}let c=await this.#o.callTool(l.serverName,e.name,e.args);return c.text||(c.isError?"Tool call failed":"Done")}catch(c){return`MCP error (${l.serverName}): ${c.message}`}return`Skill "${a.skillId}" owns tool "${e.name}" but has no execution mode`}async#l(e,t,o){return this.#t.fetchStreamingCompletion(e,t,{...o,onBudget:({beforeBytes:s,meta:n})=>{ge()&&console.log(`payload bytes (stream) before=${s} after=${n.bytes} trimmed=${n.trimmed} messages=${n.messageCount}`)}})}async#n(e,t,o){return this.#t.fetchCompletion(e,t,{...o,onBudget:({beforeBytes:s,meta:n})=>{ge()&&console.log(`payload bytes before=${s} after=${n.bytes} trimmed=${n.trimmed} messages=${n.messageCount}`)}})}async#c(e,t,o,s){let{zodToJsonSchema:n}=await import("zod-to-json-schema"),i=typeof s.schema?.parse=="function",a=i?n(s.schema):s.schema;delete a.$schema,he(a);let l={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:a,strict:!0}}},c=await this.#n(l,o,s),d=this.#e.getTextContent(c),p=JSON.parse(d),f=i?s.schema.parse(p):p;return{raw:d,structured:f}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||Eo.maxBytes),systemMaxChars:Number(t.systemMaxChars||Eo.systemMaxChars)}}#d(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:Ze(t.allowTools||e.allowTools),denyTools:Ze(t.denyTools||e.denyTools),denyPrefixes:Ms(t.denyPrefixes||e.denyToolPrefixes),includeSkills:Ze(t.includeSkills||e.includeSkills),excludeSkills:Ze(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#f(e,t){let o=t?.includeSkills||new Set,s=t?.excludeSkills||new Set;return o.size===0&&s.size===0?e:e.filter(n=>!(o.size>0&&!o.has(n)||s.has(n)))}#s(e,t){let o=String(e||"").trim();if(!o)return!1;let s=t?.allowTools;if(s&&s.size>0&&!s.has(o))return!1;let n=t?.denyTools;return!(n&&n.has(o)||(t?.denyPrefixes||[]).some(a=>o.startsWith(a)))}#p(e){let t=new Map,o=[];for(let s of e){let n=F(s);if(!n?.tools?.length)continue;let i=typeof n.handleToolCall=="function"?"handler":n.serverName&&typeof n.resolve=="function"?"mcp":null;if(i)for(let a of n.tools){let l=String(a?.name||"").trim();if(l){if(t.has(l)){o.push({tool:l,winner:t.get(l).skillId,skipped:s});continue}t.set(l,{skillId:s,mode:i})}}}if(o.length>0&&ge()){let s=o.slice(0,5).map(n=>`${n.tool}:${n.winner}>${n.skipped}`).join(", ");console.log(`tool registry collisions: ${s}${o.length>5?" ...":""}`)}return t}async#m(e,t,o,s){console.log(`
|
|
115
|
+
\u25C6 Model: ${t} | proxy: ${o} | token: ${s||"none"}
|
|
116
|
+
`);let n=(await import("chalk")).default;console.log(n.bold("Prompt sent to LLM:")),console.log(n.dim("\u2500".repeat(60)));let i=!1;for(let a of e)if(a.role==="system")console.log(n.dim(`[System] ${a.content||""}`));else{i||(console.log(n.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),i=!0);let l=a.role==="user"?"Human":"AI",c=a.content?.length>200?`${a.content.slice(0,200)}...`:a.content||"";console.log(n.dim(`[${l}] ${c}`))}console.log(n.dim("\u2500".repeat(60)))}}});var Pe={};It(Pe,{AgentStrategy:()=>J,AssistantStrategy:()=>Ne,ClaudeAgentStrategy:()=>Ae,CodexAgentStrategy:()=>Ie,CursorAgentStrategy:()=>Te,GeminiAgentStrategy:()=>ve,getAgentStrategy:()=>St,invokeAgent:()=>xo});function St(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");u.debug(`Agent selection: requested=${o}`);let s=bo.find(n=>n.getName()===o);if(!s)throw new Error(`Unknown agent '${o}'. Available: ${bo.map(n=>n.getName()).join(", ")}`);if(u.debug(`Checking if ${o} can handle this environment...`),!s.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 u.debug(`Using agent: ${s.getName()}`),s}async function xo(r,e={},t={}){try{await import("@zibby/skills")}catch{}let o=St(e),s=e.state?.config||t.config||{},n=s.models||{},i=t.nodeName&&n[t.nodeName]||null,a=n.default||null,l=o.name,c=s.agent?.[l]?.model||null,d=i||a||c||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:s},f=p.skills||[],S=r;if(f.length>0&&!t.skipPromptFragments){let{getSkill:x}=await Promise.resolve().then(()=>(X(),lt)),y=f.map(w=>{let g=x(w)?.promptFragment;return typeof g=="function"?g():g}).filter(Boolean);y.length>0&&(S+=`
|
|
117
|
+
|
|
118
|
+
${y.join(`
|
|
119
|
+
|
|
120
|
+
`)}`)}let h=e.state?._currentNodeConfig?.extraPromptInstructions?.trim();return h&&(S+=`
|
|
107
121
|
|
|
108
122
|
\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
|
|
109
123
|
\u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
110
124
|
\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
|
|
111
125
|
|
|
112
|
-
${
|
|
113
|
-
`),u.debug(`Prompt length: ${
|
|
114
|
-
${
|
|
126
|
+
${h}
|
|
127
|
+
`),u.debug(`Prompt length: ${S.length} chars`),process.env.STAGE!=="prod"&&u.debug(`Full prompt:
|
|
128
|
+
${S}`),o.invoke(S,p)}var bo,ye=B(()=>{to();oo();so();lo();$o();z();te();bo=[new Ne,new Te,new Ae,new Ie,new ve]});var Uo=new Set(["__proto__","constructor","prototype"]);function tt(r){if(Uo.has(r))throw new Error(`Invalid state key: "${r}"`)}var _e=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){tt(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let o of t)tt(o);this._history.push({...this._state});for(let o of t)this._state[o]=e[o]}append(e,t){tt(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};var we=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,s]of Object.entries(this.schema)){if(s.required&&!(o in e)&&t.push(`Missing required field: ${o}`),o in e&&s.type){let n=typeof e[o];n!==s.type&&t.push(`Field '${o}' expected ${s.type}, got ${n}`)}if(s.validate&&o in e){let n=s.validate(e[o]);n&&t.push(`Field '${o}': ${n}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
115
129
|
${t.join(`
|
|
116
|
-
`)}`);return e}},
|
|
130
|
+
`)}`);return e}},jo={string:(r=!0)=>({type:"string",required:r}),number:(r=!0)=>({type:"number",required:r}),boolean:(r=!0)=>({type:"boolean",required:r}),array:(r=!0)=>({type:"object",required:r,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(r,e=!0)=>({type:"string",required:e,validate:t=>r.includes(t)?null:`must be one of: ${r.join(", ")}`})};z();le();Ue();import{writeFileSync as _t,readFileSync as Oo,existsSync as To,mkdirSync as Ls}from"node:fs";import{join as wt,dirname as Ds}from"node:path";import He from"chalk";var ne=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 we(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,s=p=>t&&typeof t.get=="function"?t.get(p):e?.[p];if(typeof this.customExecute=="function"){u.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?(u.debug("Validating return value against outputSchema..."),{success:!0,output:this.outputSchema.parse(p),raw:null}):{success:!0,output:p,raw:null}}catch(p){return u.error(`\u274C Node '${this.name}' execution failed: ${p.message}`),p.name==="ZodError"&&u.error(`Schema validation errors: ${JSON.stringify(p.errors,null,2)}`),{success:!1,error:p.message,raw:null}}}let n=typeof this.prompt=="function"?this.prompt(o()):this.prompt,i=s("_skillHints");i&&(n=`${i}
|
|
117
131
|
|
|
118
|
-
${n}`);let a=o(),l=a.cwd||process.cwd(),c=a.sessionPath;try{if(c){let p=
|
|
119
|
-
\u{1F50D} ${
|
|
120
|
-
\u{1F50D} ${
|
|
132
|
+
${n}`);let a=o(),l=a.cwd||process.cwd(),c=a.sessionPath;try{if(c){let p=wt(c,ee);if(To(p)){let S=JSON.parse(Oo(p,"utf-8"));S.currentNode=this.name,_t(p,JSON.stringify(S,null,2),"utf-8")}let f=wt(c,"..",ee);if(To(f))try{let S=JSON.parse(Oo(f,"utf-8"));S.currentNode=this.name,_t(f,JSON.stringify(S,null,2),"utf-8")}catch{}}}catch(p){u.debug(`Could not update session info: ${p.message}`)}let d=null;for(let p=0;p<=this.retries;p++)try{u.debug(`Node.execute attempt ${p} for '${this.name}'`);let f=o(),S=f.config||{},h={state:f},x={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:c,config:S,nodeName:this.name,timeout:this.config?.timeout||3e5},y=e?._coreInvokeAgent;y||(y=(await Promise.resolve().then(()=>(ye(),Pe))).invokeAgent);let w=await y(n,h,x),g,$;if(typeof w=="string"?(g=w,$=null):w.structured?(g=w.raw||JSON.stringify(w.structured,null,2),$=w.structured):(g=w.raw||JSON.stringify(w,null,2),$=w.extracted||null),c)try{let O=wt(c,this.name,"raw_stream_output.txt");Ls(Ds(O),{recursive:!0}),_t(O,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(O){u.debug(`Could not save raw output: ${O.message}`)}if(this.isZodSchema&&$){console.log(`
|
|
133
|
+
\u{1F50D} ${He.cyan("Validated output:")} ${He.white(JSON.stringify($,null,2))}`);let O=$;if(typeof this.onComplete=="function")try{O=await this.onComplete(o(),$)}catch(T){u.warn(`onComplete hook failed: ${T.message}`)}return{success:!0,output:O,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:g}),raw:g}}catch(O){throw new Error(`onComplete failed: ${O.message}`,{cause:O})}if(this.parser){let O=this.parser.parse(g);return console.log(`
|
|
134
|
+
\u{1F50D} ${He.cyan("Parsed output:")} ${He.white(JSON.stringify(O,null,2))}`),U.step("Output parsed"),{success:!0,output:O,raw:g}}return{success:!0,output:g,raw:g}}catch(f){d=f,p<this.retries&&u.info(`Node '${this.name}' failed, retrying (${p+1}/${this.retries})...`)}return{success:!1,error:d.message,raw:null}}},Re=class extends ne{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}}};import{existsSync as Ao,readFileSync as Bs}from"node:fs";import{join as Et,dirname as Io}from"node:path";var Ve=class{static async loadContext(e,t,o={}){let s={},n=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Io(Et(t,e));for(let l of n){let c=await this.findAndMergeContextFiles(l,a,t);if(c){let d=l.replace(/\.[^.]+$/,"").toLowerCase();s[d]=c}}}let i=o.discovery||{};for(let[a,l]of Object.entries(i))try{let c=Et(t,l);if(Ao(c)){let d=await this.loadFile(c);s[a]=d}}catch(c){console.warn(`\u26A0\uFE0F Could not load context '${a}' from '${l}': ${c.message}`)}return s}static async findAndMergeContextFiles(e,t,o){let s=[],n=t;for(;n.startsWith(o);){let i=Et(n,e);if(Ao(i))try{let l=await this.loadFile(i);s.unshift(l)}catch(l){console.warn(`\u26A0\uFE0F Could not load ${e} from ${i}: ${l.message}`)}let a=Io(n);if(a===n)break;n=a}return s.length===0?null:s.every(i=>typeof i=="string")?s.join(`
|
|
121
135
|
|
|
122
136
|
---
|
|
123
137
|
|
|
124
|
-
`):
|
|
138
|
+
`):s.every(i=>typeof i=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=Bs(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),s=await import(o(e).href);return s.default||s}return t}};Ue();le();import{mkdirSync as ko,existsSync as $t,writeFileSync as vo,unlinkSync as Us}from"node:fs";import{join as ie,resolve as No}from"node:path";import{config as js}from"dotenv";import{zodToJsonSchema as Co}from"zod-to-json-schema";import Fs from"handlebars";function Gs({traceFrom:r,sessionId:e,sessionPath:t,idSource:o,mkdirFresh:s}){if(process.env.ZIBBY_SESSION_LOG==="0"||process.env.ZIBBY_SESSION_LOG==="false")return;let n=typeof process.ppid=="number"?process.ppid:"n/a",i=`[zibby:session] from=${r} pid=${process.pid} ppid=${n} sessionId=${e} source=${o} mkdir=${s?"yes":"no"} path=${t}`;if(console.log(i),(process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true")&&process.env.ZIBBY_SESSION_LOG!=="0"&&process.env.ZIBBY_SESSION_LOG!=="false"){let c=(new Error("session trace").stack||"").split(`
|
|
125
139
|
`).slice(2,14).join(`
|
|
126
|
-
`);console.log(`[zibby:session] stack (${
|
|
127
|
-
${c}`)}}function
|
|
128
|
-
\u{1F6D1} Studio stop requested \u2014 ending workflow.`);try{
|
|
129
|
-
${l}`),n.includes(".")||
|
|
140
|
+
`);console.log(`[zibby:session] stack (${r}):
|
|
141
|
+
${c}`)}}function Js(){return process.env.ZIBBY_RUN_SOURCE==="studio"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function Ks(){if(process.env.ZIBBY_RUN_SOURCE!=="studio")return;let r=process.env.ZIBBY_SESSION_PATH;if(!(r==null||String(r).trim()===""))try{return No(String(r).trim())}catch{return String(r).trim()}}function Ys(){Js()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Ws({sessionPath:r,sessionId:e}){r&&typeof r=="string"&&(process.env.ZIBBY_SESSION_PATH=r),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function zs(r={}){let e=Dt.map(n=>process.env[n]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,s=r.paths?.sessionPrefix;return s?`${s}_${o}`:o}function Zs({cwd:r=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let s=t.sessionPath,n=t.sessionTimestamp,i="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let c=No(String(process.env.ZIBBY_SESSION_PATH));c&&(s=c,i="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),n==null&&(n=Date.now());else{let c=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(c)a=c,i="ZIBBY_SESSION_ID";else{let p=e.sessionId!=null?String(e.sessionId).trim():"";p&&p!=="last"?(a=p,i="config.sessionId"):(a=zs(e),i="generated")}n=n??Date.now();let d=e.paths?.output||ce;s=ie(r,d,Lt,a)}let l=!$t(s);return l&&ko(s,{recursive:!0}),Gs({traceFrom:o,sessionId:a,sessionPath:s,idSource:i,mkdirFresh:l}),Ws({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:n}}var Me=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null}setStateSchema(e){return this.stateSchema=e,this}getStateSchema(){return this.stateSchema}addNode(e,t,o={}){let s=t instanceof ne?t:new ne(t);return s.name=e,this.nodes.set(e,s),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}addConditionalNode(e,t){let o=new Re({...t,name:e});return this.nodes.set(e,o),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:o}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:o}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,o,s,n){let i=o;for(let a=e.length-1;a>=0;a--){let l=e[a],c=i;i=()=>l(t,c,s,n)}return i()}serialize(){let e=[],t={};for(let[n,i]of this.nodes){let a=this.nodeTypeMap.get(n)||n;e.push({id:n,type:a,data:{nodeType:a,label:n}});let l=i._isCustomCode||!1,c={};l&&typeof i.execute=="function"&&(c.customCode=i.execute.toString());let d=this.nodePrompts.get(n);if(d&&(c.prompt=d),typeof i.customExecute=="function"&&(c.executeCode=i.customExecute.toString()),i.outputSchema)try{if(typeof i.outputSchema._def<"u"){let S=Co(i.outputSchema,{target:"openApi3"}),h=this._flattenJsonSchemaToVariables(S);c.outputSchema={jsonSchema:S,variables:h}}else c.outputSchema={schema:i.outputSchema}}catch(f){console.warn(`Failed to convert schema for ${n}:`,f.message)}let p=(this.resolvedToolsMap||{})[n];p?.toolIds&&(c.tools=p.toolIds),Object.keys(c).length>0&&(t[n]=c)}let o=[];for(let[n,i]of this.edges)if(typeof i=="string")o.push({source:n,target:i});else if(i.conditional){let a=this.conditionalCodeMap.get(n)||i.routes.toString(),l=this._inferConditionalTargets(i.routes),c=i.labels||{};for(let d of l){let p={source:n,target:d,data:{conditionalCode:a}};c[d]&&(p.label=c[d]),o.push(p)}}let s=null;if(this.stateSchema)try{s=Co(this.stateSchema,{target:"openApi3"})}catch{s=this.stateSchema}return{nodes:e,edges:o,nodeConfigs:t,stateSchema:s}}_inferConditionalTargets(e){let t=e.toString(),o=new Set,s=/return\s+['"]([^'"]+)['"]/g,n;for(;(n=s.exec(t))!==null;)o.add(n[1]);return[...o]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");o=e.definitions[s]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],s=e.properties||{},n=e.required||[];for(let[i,a]of Object.entries(s)){let l=t?`${t}.${i}`:i,c=!n.includes(i);if(o.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(i),optional:c}),a.type==="object"&&a.properties){let d=this._flattenSchema(a,l);o.push(...d)}if(a.type==="array"&&a.items?.type==="object"&&a.items.properties){let d=this._flattenSchema(a.items,`${l}[]`);o.push(...d)}}return o}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let o=[];t.success!==void 0&&o.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,n]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof n=="string"&&n.length<=80)o.push(`${s}: ${n}`);else if(Array.isArray(n)){let i=n.length,a=n.filter(c=>c?.passed===!0).length;if(n.some(c=>c?.passed!==void 0)){let c=i-a;o.push(`${s}: ${a}/${i} passed${c?`, ${c} failed`:""}`)}else o.push(`${s}: ${i} items`)}if(o.length>=4)break}return o}async run(e,t={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let o=t.cwd||process.cwd();js({path:ie(o,".env")});let s=t.config||{};if(!s||Object.keys(s).length===0)try{let T=ie(o,".zibby.config.js");$t(T)&&(s=(await import(T)).default||{})}catch{}process.env.EXECUTION_ID&&!s.agent?.strictMode&&(s.agent={...s.agent,strictMode:!0});let n=t.agentType;if(!n){let T=s?.agent;T?.provider?n=T.provider:T?.gemini?n="gemini":T?.claude?n="claude":T?.cursor?n="cursor":T?.codex?n="codex":n=process.env.AGENT_TYPE||"cursor"}let i=t.contextConfig||e?.config?.contextConfig||e?.config?.context||s?.context||{};if(this.stateSchema){let T=this.stateSchema.safeParse(t);if(!T.success){let C=T.error.issues.map(E=>`${E.path.join(".")}: ${E.message}`);throw console.error("\u274C Initial state validation failed:"),C.forEach(E=>console.error(` - ${E}`)),new Error(`State validation failed: ${C.join(", ")}`)}U.step("State validated against schema")}let a=Ks(),l=t.sessionPath||a;l||Ys();let{sessionPath:c,sessionTimestamp:d,sessionId:p}=Zs({cwd:o,config:s,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:t.sessionTimestamp}});U.step(`Session ${p}`);let f=await Ve.loadContext(t.specPath||"",o,i);Object.keys(f).length>0&&U.step(`Context loaded: ${Object.keys(f).join(", ")}`);let S=t.outputPath;!S&&t.specPath&&(e?.calculateOutputPath?S=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new _e({...t,config:s,agentType:n,outputPath:S,sessionPath:c,sessionTimestamp:d,context:f,resolvedTools:this.resolvedToolsMap||{}}),x=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(X(),lt)),w=new Set;for(let[,T]of this.nodes)for(let C of T.config?.skills||[])w.add(C);for(let T of w){let C=y(T);if(typeof C?.middleware=="function")try{let E=await C.middleware();typeof E=="function"&&x.set(T,E)}catch{}}let g=this.entryPoint,$=[];for(;g&&g!=="END";){let T=ie(c,Be);if($t(T)){console.warn(`
|
|
142
|
+
\u{1F6D1} Studio stop requested \u2014 ending workflow.`);try{Us(T)}catch{}if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch{}return U.step("Workflow stopped by Studio"),{success:!0,state:h.getAll(),executionLog:$,stoppedByStudio:!0}}let C=this.nodes.get(g);if(!C)throw new Error(`Node '${g}' not found in graph`);let E=JSON.stringify({sessionPath:c,sessionTimestamp:d,currentNode:g,createdAt:new Date().toISOString(),config:h.get("config")}),k=ie(c,ee);vo(k,E,"utf-8");let A=h.get("config")?.paths?.output||ce,M=ie(o,A,ee);ko(ie(o,A),{recursive:!0});try{vo(M,E,"utf-8")}catch{}let _=t.onPipelineProgress;if(typeof _=="function")try{_({cwd:o,sessionPath:c,sessionId:p,outputBase:h.get("config")?.paths?.output||ce,currentNode:g})}catch{}let N=(this.resolvedToolsMap||{})[g]||null;h.set("_currentNodeTools",N);let P=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",P[g]||{}),U.nodeStart(g);let m=Date.now(),b=this.nodePrompts.get(g);if(!this._invokeAgent){let R=await Promise.resolve().then(()=>(ye(),Pe));this._invokeAgent=R.invokeAgent}let I=this._invokeAgent,v={state:h,invokeAgent:async(R={},L={})=>{let D=L.prompt||"";if(b)try{D=Fs.compile(b,{noEscape:!0})(R)}catch(W){throw console.error(`\u274C Template rendering failed for node '${g}':`,W.message),new Error(`Template rendering failed: ${W.message}`,{cause:W})}else if(!D)throw new Error(`No prompt template configured for node '${g}' and no prompt provided in options`);let q={state:h.getAll(),images:L.images||[]},ae={model:L.model||h.get("model"),workspace:h.get("workspace"),schema:L.schema,...L};return I(D,q,ae)},_coreInvokeAgent:I,agent:e,nodeId:g,promptTemplate:b,getPromptTemplate:()=>b,...h.getAll()};try{let R=(C.config?.skills||[]).map(Y=>x.get(Y)).filter(Boolean),L=[...this.middleware,...R],D;L.length>0?D=await this._composeMiddleware(L,g,async()=>C.execute(v,h),h.getAll(),h):D=await C.execute(v,h);let q=Date.now()-m;if($.push({node:g,success:D.success,duration:q,timestamp:new Date().toISOString()}),!D.success){if(String(D.error||"").includes("Stopped from Zibby Studio")){if(U.step("Workflow stopped by Studio"),h.set("stoppedByStudio",!0),e&&typeof e.cleanup=="function")try{await e.cleanup()}catch{}return{success:!0,state:h.getAll(),executionLog:$,stoppedByStudio:!0}}h.append("errors",{node:g,error:D.error});let Se=C.config?.retries||0,At=`${g}_retries`,De=h.getAll()[At]||0;if(De<Se){U.stepInfo(`Retrying (attempt ${De+1}/${Se})`),h.update({[At]:De+1,[`${g}_raw`]:D.raw});continue}throw U.nodeFailed(g,D.error,{duration:q}),new Error(`Node '${g}' failed after ${De} attempts: ${D.error}`)}h.update({[g]:D.output});let ae=this._summarizeNodeOutput(g,D.output);U.nodeComplete(g,{duration:q,details:ae});let W=this.edges.get(g);if(!W)g="END";else if(W.conditional){let Y=h.getAll(),Se=W.routes(Y);U.route(g,Se),g=Se}else g=W}catch(R){throw U.isInsideNode&&U.nodeFailed(g,R.message,{duration:Date.now()-m}),h.set("failed",!0),h.set("failedAt",g),R}}U.graphComplete();let O={success:!0,state:h.getAll(),executionLog:$};return e&&typeof e.onComplete=="function"&&await e.onComplete(O),O}};var Le=new Map;function Po(r,e){Le.set(r,e)}function bt(r){return Le.get(r)}function Xe(r){return Le.has(r)}function Hs(){return Array.from(Le.keys())}function xt(r){let e=Le.get(r);return e?e.factory&&typeof e.create=="function"?e.create.toString():typeof e.execute=="function"?e.execute.toString():typeof e=="function"?e.toString():null:null}Po("ai_agent",{name:"ai_agent",factory:!0,create:(r,e={})=>({name:r,execute:async t=>{let o=t?._coreInvokeAgent;o||(o=(await Promise.resolve().then(()=>(ye(),Pe))).invokeAgent);let s=e.extraPromptInstructions||"Execute the task based on the current state.",n=Qs(s,t),i=await o(n,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:i,nodeId:r},raw:typeof i=="string"?i:i.raw}}})});function Vs(r){let e=/@([\w.]+)/g,t=new Set,o;for(;(o=e.exec(r))!==null;)t.add(o[1]);return Array.from(t)}function Xs(r,e){let t=e.split("."),o=r;for(let s of t){if(o==null)return;o=o[s]}return o}function qs(r){return r==null?"[not available]":typeof r=="string"?r:typeof r=="object"?r.raw&&typeof r.raw=="string"?r.raw:JSON.stringify(r,null,2):String(r)}function Qs(r,e){let t=Vs(r);if(t.length===0)return r;let o=[],s=new Set;for(let n of t){let i=n.split(".")[0];if(s.has(i))continue;let a=Xs(e,n);if(a!==void 0){let l=qs(a),c=n.replace(/_/g," ").replace(/\b\w/g,d=>d.toUpperCase());o.push(`## ${c}
|
|
143
|
+
${l}`),n.includes(".")||s.add(i)}}return o.length===0?r:`${r}
|
|
130
144
|
|
|
131
145
|
---
|
|
132
146
|
# Referenced Context
|
|
133
147
|
|
|
134
148
|
${o.join(`
|
|
135
149
|
|
|
136
|
-
`)}`}
|
|
137
|
-
`)}function
|
|
138
|
-
`)}function
|
|
139
|
-
`)}function
|
|
140
|
-
`)}function
|
|
141
|
-
`)}function
|
|
142
|
-
`)}function
|
|
150
|
+
`)}`}X();var qe={};function Tt(r,e){if(Array.isArray(e))return Ot(e);let t=qe[r];return!t||t.length===0?null:Ot(t)}function Ot(r){if(!Array.isArray(r)||r.length===0)return null;let e=[],t={},o=[];for(let s of r){let n=F(s);if(!n){console.warn(`[ToolResolver] Unknown skill "${s}" \u2014 skipping`);continue}o.push(s);for(let i of n.tools||[])e.push({name:i.name,description:i.description,input_schema:i.input_schema||{type:"object",properties:{}}});if(!t[n.serverName])if(typeof n.resolve=="function"){let i=n.resolve();i&&(t[n.serverName]={...i,toolPrefix:s})}else{let i={};for(let a of n.envKeys||[]){let l=process.env[a];l&&(i[a]=l)}t[n.serverName]={command:n.command,args:[...n.args||[]],env:i,toolPrefix:s}}}return o.length===0?null:{toolIds:o,claudeTools:e,mcpServers:t}}z();function er(r,e={}){let{nodes:t,edges:o,nodeConfigs:s={}}=r;if(!Array.isArray(t)||t.length===0)throw new H("Graph must have at least one node");if(!Array.isArray(o))throw new H("Graph edges must be an array");let n=new Me(e);e.stateSchema&&n.setStateSchema(e.stateSchema);let i=new Set,a=new Map,l={};for(let f of t){let S=Qe(f);a.set(f.id,{...f,resolvedType:S}),S==="decision"&&i.add(f.id)}for(let[f,S]of a){if(i.has(f))continue;let h=S.resolvedType,x=s[f]||{},y=x.tools,w=Tt(h,y);w&&(l[f]=w);let g={};x.prompt&&(g.prompt=x.prompt);let $=Xe(h);if(u.debug(`[compiler] Node "${f}" type="${h}" registered=${$} hasCustomCode=${!!x.customCode} hasExecuteCode=${!!x.executeCode}`),x.customCode&&!$)u.debug("[compiler] \u2192 using customCode (unregistered node)"),n.addNode(f,Ro(f,x.customCode,x),g),n.setNodeType(f,h);else if($){u.debug("[compiler] \u2192 using registered implementation");let O=bt(h);O.factory?n.addNode(f,O.create(f,{...x,resolvedTools:w}),g):n.addNode(f,O,g),n.setNodeType(f,h)}else if(x.executeCode)u.debug("[compiler] \u2192 using executeCode (fallback)"),n.addNode(f,Ro(f,x.executeCode,x),g),n.setNodeType(f,h);else throw new H(`Unknown node type "${h}" for node "${f}". Did you forget to register it?`)}n.resolvedToolsMap=l;let c=new Set;for(let f of o)i.has(f.target)||c.add(f.target);let d=t.find(f=>!i.has(f.id)&&!c.has(f.id));if(!d)throw new H("Could not determine entry point: no node without incoming edges found");n.setEntryPoint(d.id);let p=sr(o,"source");for(let f of o){let S=i.has(f.source),h=i.has(f.target);if(!S)if(h){let x=f.target,y=p.get(x)||[];if(y.length===0)throw new H(`Decision node "${x}" has no outgoing edges`);let w=rr(x,y,i);n.addConditionalEdges(f.source,w)}else n.addEdge(f.source,f.target)}return n}function tr(r){let e=[];if(!r||typeof r!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(r.nodes)||r.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(r.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=r.nodeConfigs||{};for(let a of r.nodes){let l=Qe(a);if(l==="decision"||Xe(l))continue;let c=t[a.id]||{};c.customCode||c.executeCode||e.push(`Unknown node type "${l}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let o=new Set(r.nodes.map(a=>a.id));for(let a of r.edges)o.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),o.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let s=new Set(r.nodes.filter(a=>Qe(a)==="decision").map(a=>a.id)),n=new Set;for(let a of r.edges)s.has(a.target)||n.add(a.target);let i=r.nodes.filter(a=>!s.has(a.id)&&!n.has(a.id));i.length===0?e.push("No entry point found (every node has incoming edges)"):i.length>1&&e.push(`Multiple entry points found: ${i.map(a=>a.id).join(", ")}. Graph must have exactly one.`);for(let a of s){let l=r.edges.filter(d=>d.source===a);l.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),l.some(d=>d.data?.conditionalCode||d.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function or(r){return!r||!Array.isArray(r.nodes)?[]:r.nodes.filter(e=>Qe(e)!=="decision").map(e=>e.id)}function Qe(r){let e=r.data?.nodeType||r.data?.type||r.type;return e==="workflowNode"||e==="custom"||e==="default"?r.id:e}function sr(r,e){let t=new Map;for(let o of r){let s=o[e];t.has(s)||t.set(s,[]),t.get(s).push(o)}return t}function rr(r,e,t){let o=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!o)throw new H(`Decision node "${r}" has no conditionalCode on its outgoing edges`);let s=o.data?.conditionalCode||o.conditionalCode,n=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),i;try{let l=new Function(`return (${s})`)();i=c=>{let d=l(c);return n.has(d)||u.warn(`Conditional route from "${r}" returned "${d}" which is not a valid target. Valid: ${[...n].join(", ")}`),d}}catch(a){throw new H(`Failed to compile conditionalCode for decision "${r}": ${a.message}`)}return i}function Ro(r,e,t={}){let o;try{o=new Function("invokeAgent","require","console",`return (${e})`)}catch(i){throw new H(`Failed to compile customCode for node "${r}": ${i.message}`)}let s=o(async(...i)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(ye(),Pe));return a(...i)},typeof et<"u"?et:void 0,console),n=null;return t.outputSchema&&(n=t.outputSchema.jsonSchema||t.outputSchema),{name:r,_isCustomCode:!0,outputSchema:n,execute:async i=>{try{let a=await s(i);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var H=class extends Error{constructor(e){super(e),this.name="CompilationError"}};X();function nr(r,e={}){let{nodes:t,edges:o,nodeConfigs:s={}}=r,n=new Set,i=[],a=new Map;for(let y of t){let w=y.data?.nodeType||y.type;a.set(y.id,w),w==="decision"?n.add(y.id):i.push({id:y.id,nodeType:w,label:y.data?.label||y.id})}let l=i.some(y=>{let w=s[y.id]||{};return!w.customCode&&!w.executeCode}),{toolsPerNode:c,toolIdsByVar:d}=pr(i,s),{simpleEdges:p,conditionalEdges:f}=mr(o,n),S=gr(i,o,n),h=[],x=e.workflowType||"workflow";return h.push(ar(e)),h.push(lr(x,{usesRegisteredNodes:l})),h.push(cr(d)),h.push(ur(x)),h.push(dr(i,s)),h.push(fr(i,S,p,f,c,x)),h.filter(Boolean).join(`
|
|
151
|
+
`)}function ir(r){let e={};for(let[t,o]of Object.entries(r)){let{tools:s,...n}=o;Object.keys(n).length>0&&(e[t]=n)}return e}function ar(r){let e=r.workflowType||"workflow";return["// Generated by Zibby Visual Workflow Editor",`// ${r.projectId?`Project: ${r.projectId} | `:""}Type: ${e} | Version: ${r.version??0}`,`// Downloaded: ${new Date().toISOString()}`,"//",`// Upload back: zibby workflow upload --project <id> --type ${e}`,""].join(`
|
|
152
|
+
`)}function lr(r,{usesRegisteredNodes:e=!0}={}){let t=["import '@zibby/skills';","import { WorkflowGraph } from '@zibby/core/framework/graph.js';","import { invokeAgent } from '@zibby/core';","import { getResolvedToolDefinitions } from '@zibby/core/framework/tool-resolver.js';"];return e&&t.push("import '@zibby/core/templates/register-nodes.js';"),t.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),t.join(`
|
|
153
|
+
`)}function cr(r){if(r.size===0)return"";let e=["// \u2500\u2500 Tool Bindings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Each call resolves skill IDs \u2192 full schemas + MCP server configs","// from the skill registry (populated by @zibby/skills import above)."];for(let[t,o]of r){let s=o.join(", ");e.push(`const ${t} = getResolvedToolDefinitions(${JSON.stringify(o)}); // ${s}`)}return e.push(""),e.join(`
|
|
154
|
+
`)}function ur(r){return["// \u2500\u2500 Node Configs (extra instructions, runtime settings) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","const __filename = fileURLToPath(import.meta.url);","const __dirname = dirname(__filename);",`const configPath = join(__dirname, 'workflow-${r}.config.json');`,"const nodeConfigs = existsSync(configPath)"," ? JSON.parse(readFileSync(configPath, 'utf-8'))"," : {};",""].join(`
|
|
155
|
+
`)}function dr(r,e){let t=["// \u2500\u2500 Node Implementations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Each node's execute function is inlined below.","// Edit any function to customize behavior. The upload command detects","// changes via // @custom markers and persists them to the cloud.",""];for(let o of r){let s=Mo(o.id),n=e[o.id]?.customCode;if(n)t.push(`// @custom \u2014 modified from default "${o.nodeType}" template`),t.push(`const ${s}_execute = ${n};`);else{let i=xt(o.nodeType);i?(t.push(`// Default "${o.nodeType}" implementation`),t.push(`const ${s}_execute = ${i};`)):(t.push(`// No template available for "${o.nodeType}" \u2014 using passthrough`),t.push(`const ${s}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}t.push("")}return t.join(`
|
|
156
|
+
`)}function fr(r,e,t,o,s,n="workflow"){let i=[];i.push("// \u2500\u2500 Graph Builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),i.push("export function buildGraph(options = {}) {"),i.push(" const graph = new WorkflowGraph(options);"),i.push(""),i.push(" // Nodes");for(let l of r){let c=Mo(l.id);i.push(` graph.addNode('${l.id}', { name: '${l.id}', execute: ${c}_execute });`),i.push(` graph.setNodeType('${l.id}', '${l.nodeType}');`)}i.push(""),i.push(" // Entry point"),i.push(` graph.setEntryPoint('${e}');`),i.push(""),(t.length>0||o.length>0)&&i.push(" // Edges");for(let l of t)i.push(` graph.addEdge('${l.source}', '${l.target}');`);for(let l of o){let c=l.code.split(`
|
|
143
157
|
`).map((d,p)=>p===0?d:` ${d}`).join(`
|
|
144
|
-
`);i.push(` graph.addConditionalEdges('${l.source}', ${c});`)}let a=[];for(let l of
|
|
145
|
-
`)}function
|
|
158
|
+
`);i.push(` graph.addConditionalEdges('${l.source}', ${c});`)}let a=[];for(let l of r){let c=s.get(l.id);c&&a.push(` '${l.id}': ${c},`)}if(a.length>0){i.push(""),i.push(" graph.resolvedToolsMap = {");for(let l of a)i.push(` ${l}`);i.push(" };")}return i.push(""),i.push(" return graph;"),i.push("}"),i.push(""),i.push("// \u2500\u2500 Exports \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),i.push("export { nodeConfigs };"),i.push(""),i.join(`
|
|
159
|
+
`)}function pr(r,e){let t=new Map,o=new Map;for(let s of r){let n=e[s.id]?.tools,i;if(Array.isArray(n)&&n.length>0)i=[...n].sort();else{let a=qe[s.nodeType];a&&a.length>0&&(i=[...a].sort())}if(i){let a=`${i.map(l=>l.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;t.set(s.id,a),o.has(a)||o.set(a,i)}}return{toolsPerNode:t,toolIdsByVar:o}}function mr(r,e){let t=[],o=[],s=new Map,n=new Set;for(let i of r){let a=i.source;s.has(a)||s.set(a,[]),s.get(a).push(i)}for(let i of r)if(!e.has(i.source))if(e.has(i.target)){if(n.has(i.target))continue;n.add(i.target);let l=(s.get(i.target)||[]).find(c=>c.data?.conditionalCode||c.conditionalCode);if(l){let c=l.data?.conditionalCode||l.conditionalCode;o.push({source:i.source,code:c})}}else t.push({source:i.source,target:i.target});return{simpleEdges:t,conditionalEdges:o}}function gr(r,e,t){let o=new Set;for(let n of e)t.has(n.target)||o.add(n.target);let s=r.find(n=>!o.has(n.id));return s?s.id:r[0]?.id}function Mo(r){return r.replace(/[^a-zA-Z0-9]/g,"_")}import*as Lo from"acorn";import*as Do from"acorn-walk";function hr(r){if(!r||typeof r!="string")return!1;try{let e=r.trimStart().startsWith("async")?`const __fn = ${r}`:r,t=Lo.parse(e,{ecmaVersion:"latest",sourceType:"module",allowAwaitOutsideModules:!0}),o=!1;return Do.simple(t,{CallExpression(s){if(o)return;let n=s.callee;n.type==="Identifier"&&n.name==="invokeAgent"&&(o=!0),n.type==="MemberExpression"&&n.property.type==="Identifier"&&n.property.name==="invokeAgent"&&(o=!0)}}),o}catch{return!0}}te();ye();export{J as AgentStrategy,H as CompilationError,Re as ConditionalNode,qe as NODE_DEFAULT_TOOLS,ne as Node,we as OutputParser,jo as SchemaTypes,Me as WorkflowGraph,_e as WorkflowState,er as compileGraph,or as extractSteps,ir as generateNodeConfigsJson,nr as generateWorkflowCode,St as getAgentStrategy,Fe as getAllSkills,bt as getNodeImpl,xt as getNodeTemplate,Ot as getResolvedToolDefinitions,F as getSkill,hr as hasAgentCall,Xe as hasNode,jt as hasSkill,xo as invokeAgent,Hs as listNodeTypes,Ft as listSkillIds,Po as registerNode,Ut as registerSkill,Tt as resolveNodeTools,tr as validateGraphConfig};
|