@zibby/core 0.1.38 → 0.1.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/base.js +47 -40
- package/dist/framework/agents/cursor-strategy.js +29 -22
- package/dist/framework/agents/gemini-strategy.js +11 -11
- package/dist/framework/agents/index.js +45 -38
- package/dist/framework/agents/utils/cursor-output-formatter.js +2 -2
- package/dist/framework/agents/utils/structured-output-formatter.js +1 -1
- package/dist/framework/code-generator.js +33 -26
- package/dist/framework/graph-compiler.js +47 -40
- package/dist/framework/graph.js +50 -43
- package/dist/framework/index.js +23 -16
- package/dist/framework/node-registry.js +39 -32
- package/dist/framework/node.js +43 -36
- package/dist/index.js +47 -40
- package/dist/package.json +1 -1
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var j=class{constructor(t,e,r=0){this.name=t,this.description=e,this.priority=r}async invoke(t,e={}){throw new Error("AgentStrategy.invoke() must be implemented by subclass")}canHandle(t){throw new Error("AgentStrategy.canHandle() must be implemented by subclass")}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}};import{spawn as Zt,execSync as W}from"node:child_process";import{writeFileSync as
|
|
1
|
+
var j=class{constructor(t,e,r=0){this.name=t,this.description=e,this.priority=r}async invoke(t,e={}){throw new Error("AgentStrategy.invoke() must be implemented by subclass")}canHandle(t){throw new Error("AgentStrategy.canHandle() must be implemented by subclass")}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}};import{spawn as Zt,execSync as W}from"node:child_process";import{writeFileSync as $t,readFileSync as xt,mkdirSync as At,existsSync as H,accessSync as It,constants as Tt,unlinkSync as Xt}from"node:fs";import{join as T,resolve as Vt}from"node:path";import{homedir as Y}from"node:os";import G from"chalk";var R={debug:0,info:1,warn:2,error:3,silent:4},tt=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return R.debug;if(process.env.ZIBBY_VERBOSE==="true")return R.info;let t=process.env.LOG_LEVEL?.toLowerCase();return t&&t in R?R[t]:R.info}_shouldLog(t){return R[t]>=this._level}_formatMessage(t,e,r={}){let n=new Date().toISOString(),o=`${this._getPrefix(t)} ${e}`;return Object.keys(r).length>0&&(o+=G.dim(` ${JSON.stringify(r)}`)),o}_getPrefix(t){return{debug:G.gray("[DEBUG]"),info:G.cyan("[INFO]"),warn:G.yellow("[WARN]"),error:G.red("\u274C [ERROR]")}[t]||""}debug(t,e){this._shouldLog("debug")&&console.log(this._formatMessage("debug",t,e))}info(t,e){this._shouldLog("info")&&console.log(this._formatMessage("info",t,e))}warn(t,e){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",t,e))}error(t,e){this._shouldLog("error")&&console.error(this._formatMessage("error",t,e))}setLevel(t){t in R&&(this._level=R[t])}getLevel(){return Object.keys(R).find(t=>R[t]===this._level)}},i=new tt;var 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"};var Z={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var lt=".zibby/output";var at=".session-info.json",ut=".zibby-studio-stop";var ct=new Map;function et(s){return ct.get(s)||null}function ft(){return new Map(ct)}var X=class s{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(t){if(!t)return null;this.buffer+=t;let e=this.buffer.split(`
|
|
2
2
|
`);this.buffer=e.pop()||"";let r="";for(let n of e)if(n.trim())try{let l=JSON.parse(n);this._emitToolCalls(l);let o=this.extractText(l);if(o){if(this.rawText&&o.startsWith(this.rawText)){let a=o.substring(this.rawText.length);this.rawText=o,r+=a}else(!this.rawText.includes(o)||o.length<20)&&(this.rawText+=o,r+=o);this.tryExtractResult(this.rawText)}else this.isValidResult(l)&&(this.rawText+=`${n}
|
|
3
3
|
`,r+=`${n}
|
|
4
|
-
`,this.extractedResult=l)}catch{if(n.includes('"text"')||n.includes('"content"')){let o=n.match(/"text"\s*:\s*"([^"]*)/),a=n.match(/"content"\s*:\s*"([^"]*)/),c=o?o[1]:a?a[1]:null;c&&!this.rawText.includes(c)&&(r+=c,this.rawText+=c)}}return r||null}flush(){if(!this.buffer.trim())return null;let t="";try{let e=JSON.parse(this.buffer);this._emitToolCalls(e);let r=this.extractText(e);r&&(this.rawText+=r,t+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,t+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",t||null}_emitToolCalls(t){if(!this.onToolCall)return;let e=(o,a)=>{if(!o)return;let c=`${o}:${JSON.stringify(a??{})}`;this._lastToolEmit!==c&&(this._lastToolEmit=c,this.onToolCall(o,a??void 0))},r=o=>{if(o!=null){if(typeof o=="object"&&!Array.isArray(o))return o;if(typeof o=="string")try{return JSON.parse(o)}catch{return}}};if(t.type==="tool_use"||t.type==="tool_call"){if(t.name){e(t.name,r(t.input??t.arguments));return}let o=t.tool_call;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=Object.keys(o);if(a.length===1){let c=a[0],
|
|
4
|
+
`,this.extractedResult=l)}catch{if(n.includes('"text"')||n.includes('"content"')){let o=n.match(/"text"\s*:\s*"([^"]*)/),a=n.match(/"content"\s*:\s*"([^"]*)/),c=o?o[1]:a?a[1]:null;c&&!this.rawText.includes(c)&&(r+=c,this.rawText+=c)}}return r||null}flush(){if(!this.buffer.trim())return null;let t="";try{let e=JSON.parse(this.buffer);this._emitToolCalls(e);let r=this.extractText(e);r&&(this.rawText+=r,t+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,t+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",t||null}_emitToolCalls(t){if(!this.onToolCall)return;let e=(o,a)=>{if(!o)return;let c=`${o}:${JSON.stringify(a??{})}`;this._lastToolEmit!==c&&(this._lastToolEmit=c,this.onToolCall(o,a??void 0))},r=o=>{if(o!=null){if(typeof o=="object"&&!Array.isArray(o))return o;if(typeof o=="string")try{return JSON.parse(o)}catch{return}}};if(t.type==="tool_use"||t.type==="tool_call"){if(t.name){e(t.name,r(t.input??t.arguments));return}let o=t.tool_call;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=Object.keys(o);if(a.length===1){let c=a[0],h=o[c],f=h&&typeof h=="object"?h.args??h.input??h:void 0;e(c,r(f))}return}return}if(Array.isArray(t.tool_calls)){for(let o of t.tool_calls)e(o.name,r(o.input??o.arguments));return}let n=t.message??t;if(Array.isArray(n?.tool_calls)){for(let o of n.tool_calls)e(o.name,r(o.input??o.arguments));return}let l=n?.content??t.content;if(Array.isArray(l))for(let o of l)(o.type==="tool_use"||o.type==="tool_call")&&o.name&&e(o.name,r(o.input??o.arguments))}extractText(t){if(t.type==="assistant"&&t.message?.content){let e=t.message.content;if(Array.isArray(e))return e.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return t.type==="thinking"&&t.text||t.text?t.text:t.content&&typeof t.content=="string"?t.content:t.delta?t.delta:null}tryExtractResult(t){if(!t||typeof t!="string")return;let e=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,n;for(;(n=r.exec(t))!==null;){let p=n[1].trim();try{JSON.parse(p),e.push({text:p,source:"markdown"})}catch{}}let l=0,o=0;for(;l<t.length&&(l=t.indexOf("{",l),l!==-1);){let p=0,m=l;for(let O=l;O<t.length;O++)if(t[O]==="{")p++;else if(t[O]==="}"&&(p--,p===0)){m=O,e.push({text:t.substring(l,m+1),source:"brace"}),o++;break}l=m+1}let a=this.extractedResult,c=a?JSON.stringify(a).length:0,h=0,f=-1;for(let p=0;p<e.length;p++){let m=e[p];try{let O=m.text.replace(/,(\s*[}\]])/g,"$1"),x=JSON.parse(O);this.isValidResult(x)&&(h++,c=JSON.stringify(x).length,a=x,f=p)}catch{}}a&&(this.extractedResult=a)}isValidResult(t){if(!t||typeof t!="object"||Array.isArray(t)||t.session_id||t.timestamp_ms||t.type||t.call_id||t.tool_call||t.result&&typeof t.result=="object"&&(t.result.success&&typeof t.result.success=="object"||t.result.error&&typeof t.result.error=="object")||t.args&&typeof t.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(t),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(t,e=null){let r=new s;r.zodSchema=e,r.processChunk(t),r.flush();let n=r.getResult();return!n&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",t?.length||0,"chars"),n}};import{zodToJsonSchema as vt}from"zod-to-json-schema";var V=class{static generateFileOutputInstructions(t,e){let r;typeof t?.parse=="function"?r=vt(t,{target:"openApi3"}):r=t;let n=this._buildExample(r);return`
|
|
5
5
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
6
6
|
\u{1F6A8} MANDATORY: WRITE RESULT TO FILE \u{1F6A8}
|
|
7
7
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
@@ -21,15 +21,15 @@ JSON types (strict \u2014 validators reject wrong types):
|
|
|
21
21
|
- Use true/false without quotes for booleans.
|
|
22
22
|
- Use unquoted null where a field may be null.
|
|
23
23
|
|
|
24
|
-
Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(t){if(!t)return{};let e=t.type;if(e==="object"&&t.properties){let r={};for(let[n,l]of Object.entries(t.properties))r[n]=this._buildExample(l);return r}if(e==="array"&&t.items)return[this._buildExample(t.items)];if(e==="string")return"<string>";if(e==="number"||e==="integer")return 0;if(e==="boolean")return!1;if(t.description)return`<${t.description}>`;if(t.nullable||t.oneOf||t.anyOf){let r=t.oneOf?.find(n=>n.type!=="null")||t.anyOf?.find(n=>n.type!=="null");return r?this._buildExample(r):null}return"<value>"}};import Nt from"axios";import{homedir as Ct}from"node:os";import{join as Pt}from"node:path";import{existsSync as kt,readFileSync as Lt}from"node:fs";import{toJSONSchema as Mt}from"zod";function Ut(){if(process.env.OPENAI_PROXY_TOKEN)return i.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return i.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let s=Pt(Ct(),".zibby","config.json");if(kt(s)){let t=JSON.parse(Lt(s,"utf-8"));if(t.sessionToken)return i.debug("[Auth] Using session token from zibby login"),t.sessionToken}}catch(s){i.debug(`[Auth] Could not read zibby login session: ${s.message}`)}return null}function Dt(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function J(s){if(!(typeof s!="object"||s===null)){if(Object.keys(s).length===0){s.type="object",s.additionalProperties=!0;return}if(s.type||(s.properties?s.type="object":s.items&&(s.type="array")),s.type==="object")if(s.properties){for(let[t,e]of Object.entries(s.properties))e.type==="object"&&e.additionalProperties&&e.additionalProperties!==!1&&(!e.properties||Object.keys(e.properties).length===0)&&(s.properties[t]={type:["object","null"]});s.additionalProperties=!1,s.required=Object.keys(s.properties),Object.values(s.properties).forEach(J)}else"additionalProperties"in s||(s.additionalProperties=!0);s.type==="array"&&s.items&&J(s.items),s.anyOf&&s.anyOf.forEach(J),s.oneOf&&s.oneOf.forEach(J),s.allOf&&s.allOf.forEach(J)}}async function
|
|
24
|
+
Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(t){if(!t)return{};let e=t.type;if(e==="object"&&t.properties){let r={};for(let[n,l]of Object.entries(t.properties))r[n]=this._buildExample(l);return r}if(e==="array"&&t.items)return[this._buildExample(t.items)];if(t.enum&&Array.isArray(t.enum)&&t.enum.length>0)return`<${t.enum.join("|")}>`;if(e==="string")return"<string>";if(e==="number"||e==="integer")return 0;if(e==="boolean")return!1;if(t.description)return`<${t.description}>`;if(t.nullable||t.oneOf||t.anyOf){let r=t.oneOf?.find(n=>n.type!=="null")||t.anyOf?.find(n=>n.type!=="null");return r?this._buildExample(r):null}return"<value>"}};import Nt from"axios";import{homedir as Ct}from"node:os";import{join as Pt}from"node:path";import{existsSync as kt,readFileSync as Lt}from"node:fs";import{toJSONSchema as Mt}from"zod";function Ut(){if(process.env.OPENAI_PROXY_TOKEN)return i.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return i.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let s=Pt(Ct(),".zibby","config.json");if(kt(s)){let t=JSON.parse(Lt(s,"utf-8"));if(t.sessionToken)return i.debug("[Auth] Using session token from zibby login"),t.sessionToken}}catch(s){i.debug(`[Auth] Could not read zibby login session: ${s.message}`)}return null}function Dt(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function J(s){if(!(typeof s!="object"||s===null)){if(Object.keys(s).length===0){s.type="object",s.additionalProperties=!0;return}if(s.type||(s.properties?s.type="object":s.items&&(s.type="array")),s.type==="object")if(s.properties){for(let[t,e]of Object.entries(s.properties))e.type==="object"&&e.additionalProperties&&e.additionalProperties!==!1&&(!e.properties||Object.keys(e.properties).length===0)&&(s.properties[t]={type:["object","null"]});s.additionalProperties=!1,s.required=Object.keys(s.properties),Object.values(s.properties).forEach(J)}else"additionalProperties"in s||(s.additionalProperties=!0);s.type==="array"&&s.items&&J(s.items),s.anyOf&&s.anyOf.forEach(J),s.oneOf&&s.oneOf.forEach(J),s.allOf&&s.allOf.forEach(J)}}async function pt(s,t){i.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let e=Ut();if(!e)throw new Error("Authentication required for structured output processing.\n Local development: Run `zibby login`\n CI/CD: Set ZIBBY_USER_TOKEN environment variable (Personal Access Token from UI settings)");let r=Dt();i.info(`\u{1F517} Using OpenAI proxy: ${r}`);let n=Mt(t),l=n;if(n.$ref&&n.definitions){let f=n.$ref.split("/").pop();l=n.definitions[f]||n,i.debug(`Extracted schema from $ref: ${f}`)}delete l.$schema,J(l);let o=4e5,a=s;s.length>o&&(i.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${s.length} chars) exceeds limit, keeping last ${o} chars`),a=`... [truncated early content] ...
|
|
25
25
|
${s.slice(-o)}`);let c=`Extract and format the following information into structured JSON matching the schema.
|
|
26
26
|
|
|
27
27
|
RAW CONTENT:
|
|
28
28
|
${a}
|
|
29
29
|
|
|
30
|
-
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.`,
|
|
30
|
+
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.`,h={model:K.OPENAI_POSTPROCESSING,messages:[{role:"user",content:c}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:l,strict:!0}}};i.info(`\u{1F4E4} Sending to OpenAI proxy: model=${K.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(l.properties||{}).join(", ")}`),i.debug(` Schema size: ${JSON.stringify(l).length} chars`),i.debug(` Prompt size: ${c.length} chars`);try{let f={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(f["x-proxy-token"]=e,f["x-execution-id"]=process.env.EXECUTION_ID||""):(f.Authorization=`Bearer ${e}`,f["x-api-key"]=process.env.ZIBBY_API_KEY||"",f["x-execution-id"]=process.env.EXECUTION_ID||"");let m=(await Nt.post(r,h,{headers:f,timeout:Z.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!m)throw new Error("OpenAI proxy returned empty response");let O=JSON.parse(m);return i.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:O,raw:s}}catch(f){if(f.response){let p=f.response.status,m=f.response.data;throw i.error(`\u274C OpenAI proxy request failed: ${p}`),i.error(` Status: ${p}`),i.error(` Response: ${JSON.stringify(m,null,2)}`),p===401||p===403?new Error(`Authentication failed for OpenAI proxy.
|
|
31
31
|
Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
|
|
32
|
-
Response: ${JSON.stringify(
|
|
32
|
+
Response: ${JSON.stringify(m)}`,{cause:f}):new Error(`Failed to format Cursor output: ${m?.error?.message||"Unknown error"}`,{cause:f})}throw i.error(`\u274C OpenAI proxy request failed: ${f.message}`),new Error(`Failed to format output: ${f.message}`,{cause:f})}}import $ from"chalk";var Wt="__WORKFLOW_GRAPH_LOG__",z=$.gray("\u2502"),Ft=$.gray("\u250C"),dt=$.gray("\u2514"),rt=$.green("\u25C6"),gt=$.hex("#c084fc")("\u25C6"),ht=$.hex("#2dd4bf")("\u25C6"),ot=$.red("\u25C6"),mt=`${z} `,_t=2;function yt(s){return s<1e3?`${s}ms`:`${(s/1e3).toFixed(1)}s`}function St(s,t){return(e,r,n)=>{if(typeof e!="string")return s(e,r,n);let l=process.stdout.columns||120,o="";for(let a=0;a<e.length;a++){let c=e[a];t.lineStart&&(o+=mt,t.col=_t,t.lineStart=!1),c===`
|
|
33
33
|
`?(o+=c,t.lineStart=!0,t.col=0,t.inEsc=!1):c==="\x1B"?(t.inEsc=!0,o+=c):t.inEsc?(o+=c,(c>="A"&&c<="Z"||c>="a"&&c<="z")&&(t.inEsc=!1)):(t.col++,o+=c,t.col>=l&&(o+=`
|
|
34
34
|
${mt}`,t.col=_t))}return s(o,r,n)}}var st=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null;let t=String(process.env.ZIBBY_RUN_SOURCE||"").trim().toLowerCase(),e=String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1";this._emitWorkflowGraphMarkers=e||t==="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 t={lineStart:!0,col:0,inEsc:!1},e={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=e,process.stdout.write=St(this._origStdoutWrite,t),process.stderr.write=St(this._origStderrWrite,e)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
35
35
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
@@ -40,12 +40,12 @@ ${mt}`,t.col=_t))}return s(o,r,n)}}var st=class{constructor(){this._currentNode=
|
|
|
40
40
|
`)):process.stdout.write.bind(process.stdout)(`${t} ${e}
|
|
41
41
|
`)}step(t){this._origStdoutWrite?this._writeDot(rt,t):process.stdout.write.bind(process.stdout)(`${z} ${rt} ${t}
|
|
42
42
|
`)}stepTool(t){this._origStdoutWrite?this._writeDot(gt,t):process.stdout.write.bind(process.stdout)(`${z} ${gt} ${t}
|
|
43
|
-
`)}stepMemory(t){let e
|
|
44
|
-
`)}stepFail(t){this._origStdoutWrite?this._writeDot(ot
|
|
45
|
-
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${
|
|
43
|
+
`)}stepMemory(t){let e=$.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(ht,e):process.stdout.write.bind(process.stdout)(`${z} ${ht} ${e}
|
|
44
|
+
`)}stepFail(t){this._origStdoutWrite?this._writeDot(ot,$.red(t)):process.stdout.write.bind(process.stdout)(`${z} ${ot} ${$.red(t)}
|
|
45
|
+
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Ft} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:r,details:n}=e;if(n)for(let o of n)this._rawWrite(`${rt} ${o}`);let l=r?$.dim(` ${yt(r)}`):"";this._rawWrite(`${dt} ${$.green("done")}${l}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,r={}){this._stopIntercepting();let{duration:n}=r,l=n?$.dim(` ${yt(n)}`):"";this._rawWrite(`${ot} ${$.red(e)}`),this._rawWrite(`${dt} ${$.red("failed")}${l}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite($.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){this._rawWrite($.green.bold("\u2713 Workflow completed"))}},nt=new st;import{copyFileSync as Bt,existsSync as it,lstatSync as Jt,mkdirSync as Ot,rmSync as Gt,symlinkSync as Kt,unlinkSync as zt}from"node:fs";import{join as N}from"node:path";import{homedir as Ht}from"node:os";import{randomBytes as Yt}from"node:crypto";var jt=["cli-config.json","config.json","auth.json","argv.json"];function Et(s){return!(!s||typeof s!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function wt(s){let t=N(s||process.cwd(),".zibby","tmp");Ot(t,{recursive:!0});let e=`${process.pid}-${Date.now()}-${Yt(4).toString("hex")}`,r=N(t,`cursor-agent-home-${e}`),n=N(r,".cursor");Ot(n,{recursive:!0});let l=Ht(),o=N(l,".cursor");if(it(o))for(let a of jt){let c=N(o,a);if(it(c))try{Bt(c,N(n,a))}catch{}}if(process.platform==="darwin"){let a=N(l,"Library");if(it(a))try{Kt(a,N(r,"Library"))}catch{}}return r}function bt(s){if(!(!s||typeof s!="string"))try{let t=N(s,"Library");try{Jt(t).isSymbolicLink()&&zt(t)}catch{}Gt(s,{recursive:!0,force:!0})}catch{}}var Rt=class extends j{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(t){let e=[T(Y(),".local","bin","cursor-agent"),T(Y(),".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 r of e)try{if(r.startsWith("/")){It(r,Tt.X_OK);let n=W(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(n&&n.length>0)return i.debug(`[Cursor] Found agent at: ${r} (version: ${n.trim().slice(0,50)})`),!0}else{let n=W(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!n)continue;let l=W(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(l&&l.length>0)return i.debug(`[Cursor] Found '${r}' in PATH at ${n} (version: ${l.trim().slice(0,50)})`),!0}}catch{continue}return i.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(t,e={}){let{workspace:r=process.cwd(),print:n=!1,schema:l=null,skills:o=null,sessionPath:a=null,nodeName:c=null,timeout:h=Z.CURSOR_AGENT_DEFAULT,config:f={}}=e,p=f?.agent?.strictMode||!1,m=e.model??f?.agent?.cursor?.model??K.CURSOR;i.debug(`[Cursor] Invoking (model: ${m}, timeout: ${h/1e3}s, skills: ${JSON.stringify(o)})`);let x=(this._setupMcpConfig(a,r,f,o,c)||{}).isolatedMcpHome??null,I=[T(Y(),".local","bin","cursor-agent"),T(Y(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],_=null;for(let S of I)try{if(S.startsWith("/"))It(S,Tt.X_OK),W(`"${S}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!W(`which ${S}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");W(`${S} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}_=S,i.debug(`[Agent] Using binary: ${S}`);break}catch(E){i.debug(`[Agent] Binary '${S}' check failed: ${E.message}`);continue}if(!_)throw new Error(`Cursor Agent CLI not found or not working.
|
|
46
46
|
|
|
47
47
|
Checked paths:
|
|
48
|
-
${I.map(
|
|
48
|
+
${I.map(S=>` - ${S}`).join(`
|
|
49
49
|
`)}
|
|
50
50
|
|
|
51
51
|
Install cursor-agent:
|
|
@@ -54,23 +54,30 @@ Install cursor-agent:
|
|
|
54
54
|
Then add to PATH:
|
|
55
55
|
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
|
|
56
56
|
|
|
57
|
-
Test with: agent --version`);let b=null;if(l){let
|
|
57
|
+
Test with: agent --version`);let b=null;if(l){let S=`zibby-result-${Date.now()}.json`;b=T(r,".zibby","tmp",S);let E=T(r,".zibby","tmp");H(E)||At(E,{recursive:!0});let v=V.generateFileOutputInstructions(l,b);t=`${t}
|
|
58
58
|
|
|
59
59
|
${v}`}let k=process.env.CURSOR_API_KEY,L=k?` | key: ***${k.slice(-4)}`:" | key: not set";console.log(`
|
|
60
|
-
\u25C6 Model: ${
|
|
60
|
+
\u25C6 Model: ${m||"auto"}${L}
|
|
61
61
|
`);let M=(await import("chalk")).default;console.log(`
|
|
62
|
-
${M.bold("Prompt sent to LLM:")}`),console.log(M.dim("\u2500".repeat(60))),console.log(M.dim(t)),console.log(M.dim("\u2500".repeat(60)));let
|
|
63
|
-
`)}catch{}let C,d=null;try{let
|
|
64
|
-
`)
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
${
|
|
68
|
-
|
|
69
|
-
|
|
62
|
+
${M.bold("Prompt sent to LLM:")}`),console.log(M.dim("\u2500".repeat(60))),console.log(M.dim(t)),console.log(M.dim("\u2500".repeat(60)));let F=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",m||"auto"];if(process.env.CURSOR_API_KEY&&F.push("--api-key",process.env.CURSOR_API_KEY),F.push(t),i.debug(`[Agent] Prompt: ${t.length} chars, model: ${m||"auto"}`),i.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${m||"auto"} (from .zibby.config.js agent.cursor.model)
|
|
63
|
+
`)}catch{}let C,d=null;try{let S=a||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);C=await this._spawnWithStreaming(_,F,r,h,null,S,x)}catch(S){d=S}let A=C?.stdout||"";if(l){let S=typeof l.parse=="function",E=null,v=!!(b&&H(b));if(b&&i.info(`[Agent] Result file: ${v?"present":"missing"} at ${b}`),v)try{let u=xt(b,"utf-8").trim();E=JSON.parse(u),i.info(`[Agent] Parsed JSON from result file OK (${u.length} chars) \u2192 object ready for validation`),d&&i.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(u){i.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${u.message}`)}else if(d)i.warn(`[Agent] Result file missing at ${b} (agent process error \u2014 may still recover if strictMode repairs)`);else throw i.error(`\u274C [Agent] Result file was never created at ${b}`),new Error(`Agent did not write required result file at ${b}`);if(E&&S)try{let u=l.parse(E);return i.info("\u2705 [Agent] Zod validation passed for structured result file"),p&&i.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:A,structured:u}}catch(u){let y=u.issues?u.issues.map(g=>` - ${g.path.join(".")}: ${g.message}`).join(`
|
|
64
|
+
`):u.message?.slice(0,400);if(i.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
|
|
65
|
+
${y}`),i.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
|
|
66
|
+
${JSON.stringify(E,null,2).slice(0,500)}`),!p)throw new Error(`Agent output failed schema validation:
|
|
67
|
+
${y}
|
|
68
|
+
|
|
69
|
+
The agent wrote invalid data that doesn't match the required outputSchema.
|
|
70
|
+
Enable strictMode in .zibby.config.js for automatic repair.`,{cause:u})}else{if(E)return i.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),p&&i.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:A,structured:E};v&&i.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(p&&!d){let u=C.parsedText,y=E?JSON.stringify(E):u;i.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${y.length} chars in)`);try{let g=await pt(y,l);if(S){let w=l.parse(g.structured);return i.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:A,structured:w}}return{raw:A,...g}}catch(g){if(i.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${g.message}`),E)return i.warn("[Agent] Using agent's original result file as fallback"),{raw:A,structured:E}}}if(d)throw d;let U=v?E==null?"file existed but JSON.parse failed \u2014 see WARN log above":S?"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 i.error(`\u274C [Agent] No validated structured output: ${U}`),i.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 ${b}. Enable strictMode for proxy fallback.`)}if(d)throw d;return this._extractFinalResult(A)||C?.parsedText||A}_extractFinalResult(t){if(!t)return null;let e=t.split(`
|
|
71
|
+
`),r=null;for(let n of e){let l=n.trim();if(l)try{let o=JSON.parse(l);if(o.type==="assistant"&&o.message?.content){let a=o.message.content;if(Array.isArray(a)){let c=a.filter(h=>h.type==="text"&&h.text).map(h=>h.text).join("");c&&(r=c)}else typeof a=="string"&&a&&(r=a)}}catch{}}return r?.trim()||null}_setupMcpConfig(t,e,r,n=null,l=null){let o=r?.headless,a=T(Y(),".cursor"),c=T(a,"mcp.json"),h={};if(H(c))try{h=JSON.parse(xt(c,"utf-8"))}catch{}let f=h.mcpServers||{},p=r?.paths?.output||lt,m=T(e||process.cwd(),p,at),O=Array.isArray(n)?n.map(_=>et(_)).filter(Boolean):[...ft()].map(([,_])=>_),x=new Set;for(let _ of O)typeof _.resolve=="function"&&(x.has(_.serverName)||(x.add(_.serverName),this._ensureSkillConfigured(f,_,t,m,l,o)));if(t){let _=et("browser");_&&typeof _.resolve=="function"&&!x.has(_.serverName)&&this._ensureSkillConfigured(f,_,t,m,"execute_live",o)}if(Object.keys(f).length===0)return i.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let I=`${JSON.stringify({mcpServers:f},null,2)}
|
|
72
|
+
`;if(Et(t)){let _=wt(e||process.cwd()),b=T(_,".cursor","mcp.json");return $t(b,I,"utf8"),i.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${_} | servers: ${Object.keys(f).join(", ")}`),{isolatedMcpHome:_}}return H(a)||At(a,{recursive:!0}),$t(c,I,"utf8"),i.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(f).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(t,e,r,n,l=null,o){let a=e.cursorKey||e.serverName,c=t[a]?a:t[e.serverName]?e.serverName:null;if(c&&r){let f=typeof e.resolve=="function"?e.resolve({sessionPath:r,nodeName:l,headless:o}):null;f?.args?t[c].args=f.args:t[c].args=(t[c].args||[]).map(O=>O.startsWith("--output-dir=")?`--output-dir=${r}`:O);let p=f?.env||{},m=e.sessionEnvKey?{[e.sessionEnvKey]:n}:{};t[c].env={...t[c].env||{},...p,...m},i.debug(`[MCP] Updated ${c} session \u2192 ${r}`);return}if(c)return;let h=e.resolve({sessionPath:r,nodeName:l,headless:o});h&&(t[a]={...h,...e.sessionEnvKey&&{env:{...h.env||{},[e.sessionEnvKey]:n}}},i.debug(`[MCP] Configured ${a}`))}_spawnWithStreaming(t,e,r,n,l=null,o=null,a=null){return new Promise((c,h)=>{let f=Date.now(),p="",m="",O=Date.now(),x=0,I=!1,_=null,b=!1,k=!1,L=null;if(o)try{L=T(Vt(String(o)),ut)}catch{L=null}let M=!1,F=()=>{M||(M=!0,bt(a))},C={...process.env};a&&(C.HOME=a,process.platform==="win32"&&(C.USERPROFILE=a),i.debug(`[Agent] cursor-agent HOME=${a} (isolated MCP config)`));let d=Zt(t,e,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:C});i.debug(`[Agent] PID: ${d.pid}`),d.stdin.on("error",u=>{u.code!=="EPIPE"&&i.warn(`[Agent] stdin error: ${u.message}`)}),d.stdout.on("error",u=>{u.code!=="EPIPE"&&i.warn(`[Agent] stdout error: ${u.message}`)}),d.stderr.on("error",u=>{u.code!=="EPIPE"&&i.warn(`[Agent] stderr error: ${u.message}`)}),l?(d.stdin.write(l,u=>{u&&u.code!=="EPIPE"&&i.warn(`[Agent] Failed to write to stdin: ${u.message}`),d.stdin.end()}),i.debug(`[Agent] Prompt also piped to stdin (${l.length} chars)`)):d.stdin.end();let A=null;L&&(A=setInterval(()=>{if(!(I||k))try{if(H(L)){I=!0,_="studio-stop";try{Xt(L)}catch{}i.warn("\u{1F6D1} Studio stop requested \u2014 terminating Cursor agent (and MCP browser session)"),d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},2e3)}}catch{}},600));let B=new Set,S=new Date(f).toISOString().replace(/\.\d+Z$/,""),E=setInterval(()=>{let u=Math.round((Date.now()-f)/1e3),y=Math.round((Date.now()-O)/1e3),g=[];try{let D=Math.ceil(u/60)+1,P=W(`find "${r}" -type f -mmin -${D} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(P)for(let q of P.split(`
|
|
73
|
+
`)){let Q=q.replace(`${r}/`,"");B.has(Q)||(B.add(Q),g.push(Q))}}catch{}let w="";g.length>0&&(w=` | \u{1F4C1} new: ${g.map(P=>P.split("/").pop()).join(", ")}`),B.size>0&&(w+=` | \u{1F4E6} total: ${B.size} files`),i.debug(`\u{1F493} [Agent] Running for ${u}s | ${x} lines output${w}`),x===0&&u>=30&&B.size===0&&(u<35&&i.warn(`\u26A0\uFE0F [Agent] No output after ${u}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),u>=60&&(I=!0,_=_||"stall",i.error(`\u274C [Agent] No response after ${u}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},3e3)))},3e4),v=setTimeout(()=>{I=!0,_=_||"timeout";let u=Math.round((Date.now()-f)/1e3);i.error(`\u23F1\uFE0F [Agent] Timeout after ${u}s \u2014 killing process (PID: ${d.pid})`),p.trim()&&i.warn(`\u{1F4E4} [Agent] Partial output (${p.length} chars) before timeout:
|
|
74
|
+
${p.slice(-2e3)}`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},5e3)},n),U=new X;U.onToolCall=(u,y)=>{let g=u,w=y;if(u==="mcpToolCall"&&y?.name)g=y.name.replace(/^mcp_+[^_]+_+/,""),g.includes("-")&&g.split("-")[0]===g.split("-")[1]&&(g=g.split("-")[0]),w=y.args??y.input??y;else{if(u==="readToolCall"||u==="editToolCall"||u==="writeToolCall")return;(u.startsWith("mcp__")||u.includes("ToolCall"))&&(g=u.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(g.includes("memory")?nt.stepMemory(`Tool: ${g}`):nt.stepTool(`Tool: ${g}`),w!=null&&typeof w=="object"&&Object.keys(w).length>0&&!k){let P=JSON.stringify(w),q=P.length>100?`${P.substring(0,100)}...`:P;console.log(` Input: ${q}`)}},d.stdout.on("data",u=>{let y=u.toString();p+=y,O=Date.now(),b||(b=!0);let g=U.processChunk(y);g&&!k&&process.stdout.write(g);let w=y.split(`
|
|
75
|
+
`).filter(D=>D.trim());x+=w.length}),d.stderr.on("data",u=>{let y=u.toString();m+=y,O=Date.now(),b||(b=!0);let g=y.split(`
|
|
76
|
+
`).filter(w=>w.trim());for(let w of g)i.warn(`\u26A0\uFE0F [Agent stderr] ${w}`)}),d.on("close",(u,y)=>{k=!0,F(),clearTimeout(v),clearInterval(E),A&&clearInterval(A),U.flush();let g=Math.round((Date.now()-f)/1e3);if(i.debug(`[Agent] Exited: code=${u}, signal=${y}, elapsed=${g}s, output=${p.length} chars`),I){if(_==="studio-stop"){h(new Error("Stopped from Zibby Studio"));return}h(new Error(`Cursor Agent timed out after ${g}s (limit: ${n/1e3}s). ${x} lines produced. Last output ${Math.round((Date.now()-O)/1e3)}s ago. ${p.trim()?`
|
|
70
77
|
Partial output (last 500 chars):
|
|
71
|
-
${
|
|
72
|
-
Stderr: ${
|
|
73
|
-
Stdout (last 500 chars): ${
|
|
78
|
+
${p.slice(-500)}`:"No output captured."}`));return}if(u!==0){h(new Error(`Cursor Agent failed: exit code ${u}, signal ${y}. ${m.trim()?`
|
|
79
|
+
Stderr: ${m.slice(-1e3)}`:""}${p.trim()?`
|
|
80
|
+
Stdout (last 500 chars): ${p.slice(-500)}`:""}`));return}let w=U.getResult(),D=w?JSON.stringify(w,null,2):U.getRawText()||p||"";c({stdout:p||m||"",parsedText:D})}),d.on("error",u=>{F(),clearTimeout(v),clearInterval(E),A&&clearInterval(A),h(new Error(`Cursor Agent spawn error: ${u.message}
|
|
74
81
|
Binary: ${t}
|
|
75
82
|
This usually means the binary is not in PATH. Try:
|
|
76
83
|
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}};export{Rt as CursorAgentStrategy};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var M=class{constructor(t,r,n=0){this.name=t,this.description=r,this.priority=n}async invoke(t,r={}){throw new Error("AgentStrategy.invoke() must be implemented by subclass")}canHandle(t){throw new Error("AgentStrategy.canHandle() must be implemented by subclass")}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}};import{execSync as tt,spawn as et}from"node:child_process";import{zodToJsonSchema as rt}from"zod-to-json-schema";import{existsSync as B,mkdirSync as H,readFileSync as W,rmSync as nt,writeFileSync as q}from"node:fs";import{join as T}from"node:path";import G from"chalk";var g={debug:0,info:1,warn:2,error:3,silent:4},L=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return g.debug;if(process.env.ZIBBY_VERBOSE==="true")return g.info;let t=process.env.LOG_LEVEL?.toLowerCase();return t&&t in g?g[t]:g.info}_shouldLog(t){return g[t]>=this._level}_formatMessage(t,r,n={}){let
|
|
1
|
+
var M=class{constructor(t,r,n=0){this.name=t,this.description=r,this.priority=n}async invoke(t,r={}){throw new Error("AgentStrategy.invoke() must be implemented by subclass")}canHandle(t){throw new Error("AgentStrategy.canHandle() must be implemented by subclass")}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}};import{execSync as tt,spawn as et}from"node:child_process";import{zodToJsonSchema as rt}from"zod-to-json-schema";import{existsSync as B,mkdirSync as H,readFileSync as W,rmSync as nt,writeFileSync as q}from"node:fs";import{join as T}from"node:path";import G from"chalk";var g={debug:0,info:1,warn:2,error:3,silent:4},L=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return g.debug;if(process.env.ZIBBY_VERBOSE==="true")return g.info;let t=process.env.LOG_LEVEL?.toLowerCase();return t&&t in g?g[t]:g.info}_shouldLog(t){return g[t]>=this._level}_formatMessage(t,r,n={}){let i=new Date().toISOString(),e=`${this._getPrefix(t)} ${r}`;return Object.keys(n).length>0&&(e+=G.dim(` ${JSON.stringify(n)}`)),e}_getPrefix(t){return{debug:G.gray("[DEBUG]"),info:G.cyan("[INFO]"),warn:G.yellow("[WARN]"),error:G.red("\u274C [ERROR]")}[t]||""}debug(t,r){this._shouldLog("debug")&&console.log(this._formatMessage("debug",t,r))}info(t,r){this._shouldLog("info")&&console.log(this._formatMessage("info",t,r))}warn(t,r){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",t,r))}error(t,r){this._shouldLog("error")&&console.error(this._formatMessage("error",t,r))}setLevel(t){t in g&&(this._level=g[t])}getLevel(){return Object.keys(g).find(t=>g[t]===this._level)}},a=new L;var Y={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"};var K={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},ct={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var Q=new Map;function V(f){return Q.get(f)||null}import{zodToJsonSchema as j}from"zod-to-json-schema";var R=class{static generateFileOutputInstructions(t,r){let n;typeof t?.parse=="function"?n=j(t,{target:"openApi3"}):n=t;let i=this._buildExample(n);return`
|
|
2
2
|
\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
|
|
3
3
|
\u{1F6A8} MANDATORY: WRITE RESULT TO FILE \u{1F6A8}
|
|
4
4
|
\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
|
|
@@ -11,24 +11,24 @@ DO NOT just output JSON to stdout. The file MUST exist when you finish.
|
|
|
11
11
|
DO NOT skip this step. The workflow WILL FAIL if the file is missing.
|
|
12
12
|
|
|
13
13
|
Required JSON structure:
|
|
14
|
-
${JSON.stringify(
|
|
14
|
+
${JSON.stringify(i,null,2)}
|
|
15
15
|
|
|
16
16
|
JSON types (strict \u2014 validators reject wrong types):
|
|
17
17
|
- Use bare JSON numbers for numeric fields (e.g. 3000). Do NOT quote them as strings (wrong: "3000").
|
|
18
18
|
- Use true/false without quotes for booleans.
|
|
19
19
|
- Use unquoted null where a field may be null.
|
|
20
20
|
|
|
21
|
-
Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(t){if(!t)return{};let r=t.type;if(r==="object"&&t.properties){let n={};for(let[s
|
|
22
|
-
`);this.buffer=r.pop()||"";let n="";for(let
|
|
23
|
-
`,n+=`${
|
|
24
|
-
`,this.extractedResult=
|
|
21
|
+
Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(t){if(!t)return{};let r=t.type;if(r==="object"&&t.properties){let n={};for(let[i,s]of Object.entries(t.properties))n[i]=this._buildExample(s);return n}if(r==="array"&&t.items)return[this._buildExample(t.items)];if(t.enum&&Array.isArray(t.enum)&&t.enum.length>0)return`<${t.enum.join("|")}>`;if(r==="string")return"<string>";if(r==="number"||r==="integer")return 0;if(r==="boolean")return!1;if(t.description)return`<${t.description}>`;if(t.nullable||t.oneOf||t.anyOf){let n=t.oneOf?.find(i=>i.type!=="null")||t.anyOf?.find(i=>i.type!=="null");return n?this._buildExample(n):null}return"<value>"}};var k=class f{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(t){if(!t)return null;this.buffer+=t;let r=this.buffer.split(`
|
|
22
|
+
`);this.buffer=r.pop()||"";let n="";for(let i of r)if(i.trim())try{let s=JSON.parse(i);this._emitToolCalls(s);let e=this.extractText(s);if(e){if(this.rawText&&e.startsWith(this.rawText)){let o=e.substring(this.rawText.length);this.rawText=e,n+=o}else(!this.rawText.includes(e)||e.length<20)&&(this.rawText+=e,n+=e);this.tryExtractResult(this.rawText)}else this.isValidResult(s)&&(this.rawText+=`${i}
|
|
23
|
+
`,n+=`${i}
|
|
24
|
+
`,this.extractedResult=s)}catch{if(i.includes('"text"')||i.includes('"content"')){let e=i.match(/"text"\s*:\s*"([^"]*)/),o=i.match(/"content"\s*:\s*"([^"]*)/),l=e?e[1]:o?o[1]:null;l&&!this.rawText.includes(l)&&(n+=l,this.rawText+=l)}}return n||null}flush(){if(!this.buffer.trim())return null;let t="";try{let r=JSON.parse(this.buffer);this._emitToolCalls(r);let n=this.extractText(r);n&&(this.rawText+=n,t+=n,this.tryExtractResult(n))}catch{this.rawText+=this.buffer,t+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",t||null}_emitToolCalls(t){if(!this.onToolCall)return;let r=(e,o)=>{if(!e)return;let l=`${e}:${JSON.stringify(o??{})}`;this._lastToolEmit!==l&&(this._lastToolEmit=l,this.onToolCall(e,o??void 0))},n=e=>{if(e!=null){if(typeof e=="object"&&!Array.isArray(e))return e;if(typeof e=="string")try{return JSON.parse(e)}catch{return}}};if(t.type==="tool_use"||t.type==="tool_call"){if(t.name){r(t.name,n(t.input??t.arguments));return}let e=t.tool_call;if(e&&typeof e=="object"&&!Array.isArray(e)){let o=Object.keys(e);if(o.length===1){let l=o[0],u=e[l],m=u&&typeof u=="object"?u.args??u.input??u:void 0;r(l,n(m))}return}return}if(Array.isArray(t.tool_calls)){for(let e of t.tool_calls)r(e.name,n(e.input??e.arguments));return}let i=t.message??t;if(Array.isArray(i?.tool_calls)){for(let e of i.tool_calls)r(e.name,n(e.input??e.arguments));return}let s=i?.content??t.content;if(Array.isArray(s))for(let e of s)(e.type==="tool_use"||e.type==="tool_call")&&e.name&&r(e.name,n(e.input??e.arguments))}extractText(t){if(t.type==="assistant"&&t.message?.content){let r=t.message.content;if(Array.isArray(r))return r.filter(n=>n.type==="text"&&n.text).map(n=>n.text).join("")}return t.type==="thinking"&&t.text||t.text?t.text:t.content&&typeof t.content=="string"?t.content:t.delta?t.delta:null}tryExtractResult(t){if(!t||typeof t!="string")return;let r=[],n=/```json\s*\n?([\s\S]*?)\n?```/g,i;for(;(i=n.exec(t))!==null;){let p=i[1].trim();try{JSON.parse(p),r.push({text:p,source:"markdown"})}catch{}}let s=0,e=0;for(;s<t.length&&(s=t.indexOf("{",s),s!==-1);){let p=0,h=s;for(let d=s;d<t.length;d++)if(t[d]==="{")p++;else if(t[d]==="}"&&(p--,p===0)){h=d,r.push({text:t.substring(s,h+1),source:"brace"}),e++;break}s=h+1}let o=this.extractedResult,l=o?JSON.stringify(o).length:0,u=0,m=-1;for(let p=0;p<r.length;p++){let h=r[p];try{let d=h.text.replace(/,(\s*[}\]])/g,"$1"),O=JSON.parse(d);this.isValidResult(O)&&(u++,l=JSON.stringify(O).length,o=O,m=p)}catch{}}o&&(this.extractedResult=o)}isValidResult(t){if(!t||typeof t!="object"||Array.isArray(t)||t.session_id||t.timestamp_ms||t.type||t.call_id||t.tool_call||t.result&&typeof t.result=="object"&&(t.result.success&&typeof t.result.success=="object"||t.result.error&&typeof t.result.error=="object")||t.args&&typeof t.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(t),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(t,r=null){let n=new f;n.zodSchema=r,n.processChunk(t),n.flush();let i=n.getResult();return!i&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",t?.length||0,"chars"),i}};function it(f){if(!f)return null;let t=String(f),r=t.match(/```(?:json)?\s*([\s\S]*?)```/i);if(r?.[1])try{return JSON.parse(r[1].trim())}catch{}let n=t.indexOf("{");if(n<0)return null;let i=0,s=!1,e=!1,o=-1;for(let l=n;l<t.length;l++){let u=t[l];if(s){e?e=!1:u==="\\"?e=!0:u==='"'&&(s=!1);continue}if(u==='"'){s=!0;continue}if(u==="{"){i===0&&(o=l),i+=1;continue}if(u==="}"){if(i===0)continue;if(i-=1,i===0&&o>=0){let m=t.slice(o,l+1);try{return JSON.parse(m)}catch{o=-1}}}}return null}function st(f){let t=String(f||"").trim();if(!t)return null;try{return JSON.parse(t)}catch{return it(t)}}function ot(f){try{let t=JSON.parse(f);if(typeof t=="string")return t;if(typeof t?.response=="string")return t.response;if(typeof t?.text=="string")return t.text;if(typeof t?.output=="string")return t.output;if(Array.isArray(t?.candidates)&&t.candidates.length>0){let r=t.candidates[0];if(typeof r?.content=="string")return r.content;if(Array.isArray(r?.content?.parts)){let n=r.content.parts.map(i=>typeof i?.text=="string"?i.text:"").join("");if(n.trim())return n}}}catch{}return f}var X=class extends M{constructor(){super("gemini","Gemini (Google)",70)}canHandle(t){if(!!!(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY))return a.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return tt("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return a.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(t,r={}){let{model:n,workspace:i=process.cwd(),schema:s=null,skills:e=null,sessionPath:o=null,nodeName:l=null,timeout:u=600*1e3}=r,m=n;(!m||m==="auto")&&(m=Y.GEMINI);let p=K[m]||m,h=String(process.env.GEMINI_API_KEY||"").trim(),d=String(process.env.GOOGLE_API_KEY||"").trim(),O=this._resolveSkillsToMcp(e,{sessionPath:o,workspace:i,nodeName:l}),U=Object.keys(O).length>0,I=t,P=s&&typeof s.parse=="function",N=null;if(s){let c;try{let x=P?rt(s,{target:"openAi"}):s;c=JSON.stringify(x,null,2)}catch{c="{}"}if(U){I+=`
|
|
25
25
|
|
|
26
26
|
Write valid JSON that matches this schema:
|
|
27
|
-
${
|
|
27
|
+
${c}`;let x=`zibby-result-${Date.now()}.json`,S=T(i,".zibby","tmp");N=T(S,x),H(S,{recursive:!0}),I+=R.generateFileOutputInstructions(s,N)}else I+=`
|
|
28
28
|
|
|
29
29
|
Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
|
|
30
|
-
${
|
|
30
|
+
${c}`}let C=this._createGeminiConfigDir(i,O),E=["--output-format","json"];p&&p!=="auto"&&E.push("--model",p);let $=Object.keys(O);if($.length>0){E.push("--approval-mode","yolo");for(let c of $)E.push("--allowed-mcp-server-names",c);a.info(`[Gemini] Enabling MCP servers: ${$.join(", ")}`)}else e&&e.length>0&&a.warn(`[Gemini] Skills requested but no MCP servers configured: ${e.join(", ")}`);E.push("-p",I);let v={...process.env,GEMINI_CLI_HOME:C};h?(v.GEMINI_API_KEY=h,delete v.GOOGLE_API_KEY):d&&(v.GOOGLE_API_KEY=d,delete v.GEMINI_API_KEY),a.debug(`[Gemini] Command: gemini ${E.slice(0,8).join(" ")}... (${E.length} total args)`),a.debug(`[Gemini] Config home: ${C}`),a.debug(`[Gemini] GEMINI_CLI_HOME env: ${v.GEMINI_CLI_HOME}`);let J="",A=null;try{J=await new Promise((x,S)=>{let b=et("gemini",E,{cwd:i,env:v,stdio:["ignore","pipe","pipe"]}),D="",z="",F=setTimeout(()=>{try{b.kill("SIGTERM")}catch{}},u);b.stdout.on("data",_=>{D+=_.toString()}),b.stderr.on("data",_=>{z+=_.toString()}),b.on("error",_=>{clearTimeout(F),S(_)}),b.on("close",_=>{if(clearTimeout(F),_===0)return x(D.trim());S(new Error(`gemini failed with code ${_}: ${(z||D).trim()}`))})})}catch(c){A=c}finally{try{nt(C,{recursive:!0,force:!0})}catch{}}let y=ot(J).trim();if(!s){if(A)throw A;return y}if(N){let c=B(N);if(a.info(`[Gemini] Result file: ${c?"present":"missing"} at ${N}`),c)try{let x=W(N,"utf-8").trim(),S=JSON.parse(x),b=P?s.parse(S):S;return a.info("[Gemini] Structured output recovered from result file"),{raw:y,structured:b}}catch(x){a.warn(`[Gemini] Result file parse/validation failed: ${x.message}`)}else A||a.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let w=null;if(s){let c=new k;c.zodSchema=s,c.processChunk(y),c.flush(),w=c.getResult()}if(a.info(`[Gemini] Raw stdout length: ${J.length} chars`),a.info(`[Gemini] Extracted text length: ${y.length} chars`),a.info(`[Gemini] StreamParser result: ${w?"extracted":"null"}`),w||(y.length<2e3?a.info(`[Gemini] Raw text preview:
|
|
31
31
|
${y}`):a.info(`[Gemini] Raw text preview (first 1000 chars):
|
|
32
|
-
${y.slice(0,1e3)}`),w=
|
|
33
|
-
`,"utf-8");let m=T(t||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{q(m,`${JSON.stringify(
|
|
34
|
-
`,"utf-8")}catch{}return a.debug(`[Gemini] Created isolated config with ${Object.keys(
|
|
32
|
+
${y.slice(0,1e3)}`),w=st(y)),!w)throw A||(a.error("[Gemini] Failed to extract valid JSON from output"),a.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error("Gemini did not return valid JSON for structured output. Enable strictMode for proxy fallback."));let Z=P?s.parse(w):w;return{raw:y,structured:Z}}_resolveSkillsToMcp(t,r={}){if(!Array.isArray(t)||t.length===0)return{};let n={};for(let i of t){let s=V(i);if(!s||typeof s.resolve!="function")continue;let e=s.resolve(r);if(!e)continue;let o=s.cursorKey||s.serverName||i,l={command:e.command};e.args?.length&&(l.args=e.args),e.env&&Object.keys(e.env).length>0&&(l.env=e.env),e.cwd&&(l.cwd=e.cwd),n[o]=l}return n}_createGeminiConfigDir(t,r){let n=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,i=T(t||process.cwd(),".zibby","tmp",`gemini-home-${n}`),s=T(i,".gemini");H(s,{recursive:!0});let e=T(s,"settings.json"),o={},l=T(process.env.HOME||"",".gemini","settings.json");if(B(l))try{o=JSON.parse(W(l,"utf-8"))}catch{o={}}let u={...o,mcpServers:{...o.mcpServers&&typeof o.mcpServers=="object"?o.mcpServers:{},...r||{}}};q(e,`${JSON.stringify(u,null,2)}
|
|
33
|
+
`,"utf-8");let m=T(t||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{q(m,`${JSON.stringify(u,null,2)}
|
|
34
|
+
`,"utf-8")}catch{}return a.debug(`[Gemini] Created isolated config with ${Object.keys(u.mcpServers||{}).length} MCP servers`),a.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(u.mcpServers||{}),null,2)}`),i}};export{X as GeminiAgentStrategy};
|