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