@zibby/core 0.1.38 → 0.1.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/base.js +47 -40
- package/dist/framework/agents/cursor-strategy.js +29 -22
- package/dist/framework/agents/gemini-strategy.js +11 -11
- package/dist/framework/agents/index.js +45 -38
- package/dist/framework/agents/utils/cursor-output-formatter.js +2 -2
- package/dist/framework/agents/utils/structured-output-formatter.js +1 -1
- package/dist/framework/code-generator.js +33 -26
- package/dist/framework/graph-compiler.js +47 -40
- package/dist/framework/graph.js +50 -43
- package/dist/framework/index.js +23 -16
- package/dist/framework/node-registry.js +39 -32
- package/dist/framework/node.js +43 -36
- package/dist/index.js +47 -40
- package/dist/package.json +1 -1
- package/package.json +1 -1
package/dist/agents/base.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var vo=Object.defineProperty;var R=(i,e)=>()=>(i&&(e=i(i=0)),e);var Pe=(i,e)=>{for(var t in e)vo(i,t,{get:e[t],enumerable:!0})};var X,Re=R(()=>{X=class i{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(e){if(!e)return null;this.buffer+=e;let t=this.buffer.split(`
|
|
2
2
|
`);this.buffer=t.pop()||"";let o="";for(let s of t)if(s.trim())try{let r=JSON.parse(s);this._emitToolCalls(r);let n=this.extractText(r);if(n){if(this.rawText&&n.startsWith(this.rawText)){let a=n.substring(this.rawText.length);this.rawText=n,o+=a}else(!this.rawText.includes(n)||n.length<20)&&(this.rawText+=n,o+=n);this.tryExtractResult(this.rawText)}else this.isValidResult(r)&&(this.rawText+=`${s}
|
|
3
3
|
`,o+=`${s}
|
|
4
|
-
`,this.extractedResult=r)}catch{if(s.includes('"text"')||s.includes('"content"')){let n=s.match(/"text"\s*:\s*"([^"]*)/),a=s.match(/"content"\s*:\s*"([^"]*)/),l=n?n[1]:a?a[1]:null;l&&!this.rawText.includes(l)&&(o+=l,this.rawText+=l)}}return o||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let o=this.extractText(t);o&&(this.rawText+=o,e+=o,this.tryExtractResult(o))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(n,a)=>{if(!n)return;let l=`${n}:${JSON.stringify(a??{})}`;this._lastToolEmit!==l&&(this._lastToolEmit=l,this.onToolCall(n,a??void 0))},o=n=>{if(n!=null){if(typeof n=="object"&&!Array.isArray(n))return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,o(e.input??e.arguments));return}let n=e.tool_call;if(n&&typeof n=="object"&&!Array.isArray(n)){let a=Object.keys(n);if(a.length===1){let l=a[0],c=n[l],f=c&&typeof c=="object"?c.args??c.input??c:void 0;t(l,o(f))}return}return}if(Array.isArray(e.tool_calls)){for(let n of e.tool_calls)t(n.name,o(n.input??n.arguments));return}let s=e.message??e;if(Array.isArray(s?.tool_calls)){for(let n of s.tool_calls)t(n.name,o(n.input??n.arguments));return}let r=s?.content??e.content;if(Array.isArray(r))for(let n of r)(n.type==="tool_use"||n.type==="tool_call")&&n.name&&t(n.name,o(n.input??n.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(o=>o.type==="text"&&o.text).map(o=>o.text).join("")}return e.type==="thinking"&&e.text||e.text?e.text:e.content&&typeof e.content=="string"?e.content:e.delta?e.delta:null}tryExtractResult(e){if(!e||typeof e!="string")return;let t=[],o=/```json\s*\n?([\s\S]*?)\n?```/g,s;for(;(s=o.exec(e))!==null;){let p=s[1].trim();try{JSON.parse(p),t.push({text:p,source:"markdown"})}catch{}}let r=0,n=0;for(;r<e.length&&(r=e.indexOf("{",r),r!==-1);){let p=0,d=r;for(let _=r;_<e.length;_++)if(e[_]==="{")p++;else if(e[_]==="}"&&(p--,p===0)){d=_,t.push({text:e.substring(r,d+1),source:"brace"}),n++;break}r=d+1}let a=this.extractedResult,l=a?JSON.stringify(a).length:0,c=0,f=-1;for(let p=0;p<t.length;p++){let d=t[p];try{let _=d.text.replace(/,(\s*[}\]])/g,"$1"),
|
|
4
|
+
`,this.extractedResult=r)}catch{if(s.includes('"text"')||s.includes('"content"')){let n=s.match(/"text"\s*:\s*"([^"]*)/),a=s.match(/"content"\s*:\s*"([^"]*)/),l=n?n[1]:a?a[1]:null;l&&!this.rawText.includes(l)&&(o+=l,this.rawText+=l)}}return o||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let o=this.extractText(t);o&&(this.rawText+=o,e+=o,this.tryExtractResult(o))}catch{this.rawText+=this.buffer,e+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",e||null}_emitToolCalls(e){if(!this.onToolCall)return;let t=(n,a)=>{if(!n)return;let l=`${n}:${JSON.stringify(a??{})}`;this._lastToolEmit!==l&&(this._lastToolEmit=l,this.onToolCall(n,a??void 0))},o=n=>{if(n!=null){if(typeof n=="object"&&!Array.isArray(n))return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,o(e.input??e.arguments));return}let n=e.tool_call;if(n&&typeof n=="object"&&!Array.isArray(n)){let a=Object.keys(n);if(a.length===1){let l=a[0],c=n[l],f=c&&typeof c=="object"?c.args??c.input??c:void 0;t(l,o(f))}return}return}if(Array.isArray(e.tool_calls)){for(let n of e.tool_calls)t(n.name,o(n.input??n.arguments));return}let s=e.message??e;if(Array.isArray(s?.tool_calls)){for(let n of s.tool_calls)t(n.name,o(n.input??n.arguments));return}let r=s?.content??e.content;if(Array.isArray(r))for(let n of r)(n.type==="tool_use"||n.type==="tool_call")&&n.name&&t(n.name,o(n.input??n.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(o=>o.type==="text"&&o.text).map(o=>o.text).join("")}return e.type==="thinking"&&e.text||e.text?e.text:e.content&&typeof e.content=="string"?e.content:e.delta?e.delta:null}tryExtractResult(e){if(!e||typeof e!="string")return;let t=[],o=/```json\s*\n?([\s\S]*?)\n?```/g,s;for(;(s=o.exec(e))!==null;){let p=s[1].trim();try{JSON.parse(p),t.push({text:p,source:"markdown"})}catch{}}let r=0,n=0;for(;r<e.length&&(r=e.indexOf("{",r),r!==-1);){let p=0,d=r;for(let _=r;_<e.length;_++)if(e[_]==="{")p++;else if(e[_]==="}"&&(p--,p===0)){d=_,t.push({text:e.substring(r,d+1),source:"brace"}),n++;break}r=d+1}let a=this.extractedResult,l=a?JSON.stringify(a).length:0,c=0,f=-1;for(let p=0;p<t.length;p++){let d=t[p];try{let _=d.text.replace(/,(\s*[}\]])/g,"$1"),y=JSON.parse(_);this.isValidResult(y)&&(c++,l=JSON.stringify(y).length,a=y,f=p)}catch{}}a&&(this.extractedResult=a)}isValidResult(e){if(!e||typeof e!="object"||Array.isArray(e)||e.session_id||e.timestamp_ms||e.type||e.call_id||e.tool_call||e.result&&typeof e.result=="object"&&(e.result.success&&typeof e.result.success=="object"||e.result.error&&typeof e.result.error=="object")||e.args&&typeof e.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(e),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(e,t=null){let o=new i;o.zodSchema=t,o.processChunk(e),o.flush();let s=o.getResult();return!s&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),s}}});var q,Me,W,Le,Tt,he=R(()=>{q=".zibby/output",Me="sessions",W=".session-info.json",Le=".zibby-studio-stop",Tt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"]});var vt={};Pe(vt,{WorkflowState:()=>ye});function qe(i){if(Ro.has(i))throw new Error(`Invalid state key: "${i}"`)}var Ro,ye,Ve=R(()=>{Ro=new Set(["__proto__","constructor","prototype"]);ye=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){qe(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let o of t)qe(o);this._history.push({...this._state});for(let o of t)this._state[o]=e[o]}append(e,t){qe(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}}});var De,Ct=R(()=>{De=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let o=e.match(/\{[\s\S]*\}/);return o?this.validate(JSON.parse(o[0])):this.validate({result:e.trim()})}validate(e){let t=[];for(let[o,s]of Object.entries(this.schema)){if(s.required&&!(o in e)&&t.push(`Missing required field: ${o}`),o in e&&s.type){let r=typeof e[o];r!==s.type&&t.push(`Field '${o}' expected ${s.type}, got ${r}`)}if(s.validate&&o in e){let r=s.validate(e[o]);r&&t.push(`Field '${o}': ${r}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
5
5
|
${t.join(`
|
|
6
6
|
`)}`);return e}}});import Se from"chalk";var z,Qe,u,H=R(()=>{z={debug:0,info:1,warn:2,error:3,silent:4},Qe=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return z.debug;if(process.env.ZIBBY_VERBOSE==="true")return z.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in z?z[e]:z.info}_shouldLog(e){return z[e]>=this._level}_formatMessage(e,t,o={}){let s=new Date().toISOString(),n=`${this._getPrefix(e)} ${t}`;return Object.keys(o).length>0&&(n+=Se.dim(` ${JSON.stringify(o)}`)),n}_getPrefix(e){return{debug:Se.gray("[DEBUG]"),info:Se.cyan("[INFO]"),warn:Se.yellow("[WARN]"),error:Se.red("\u274C [ERROR]")}[e]||""}debug(e,t){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,t))}info(e,t){this._shouldLog("info")&&console.log(this._formatMessage("info",e,t))}warn(e,t){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,t))}error(e,t){this._shouldLog("error")&&console.error(this._formatMessage("error",e,t))}setLevel(e){e in z&&(this._level=z[e])}getLevel(){return Object.keys(z).find(e=>z[e]===this._level)}},u=new Qe});import U from"chalk";function Lt(i){return i<1e3?`${i}ms`:`${(i/1e3).toFixed(1)}s`}function Dt(i,e){return(t,o,s)=>{if(typeof t!="string")return i(t,o,s);let r=process.stdout.columns||120,n="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(n+=Rt,e.col=Mt,e.lineStart=!1),l===`
|
|
7
7
|
`?(n+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,n+=l):e.inEsc?(n+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,n+=l,e.col>=r&&(n+=`
|
|
@@ -36,7 +36,7 @@ JSON types (strict \u2014 validators reject wrong types):
|
|
|
36
36
|
- Use true/false without quotes for booleans.
|
|
37
37
|
- Use unquoted null where a field may be null.
|
|
38
38
|
|
|
39
|
-
Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(e){if(!e)return{};let t=e.type;if(t==="object"&&e.properties){let o={};for(let[s,r]of Object.entries(e.properties))o[s]=this._buildExample(r);return o}if(t==="array"&&e.items)return[this._buildExample(e.items)];if(t==="string")return"<string>";if(t==="number"||t==="integer")return 0;if(t==="boolean")return!1;if(e.description)return`<${e.description}>`;if(e.nullable||e.oneOf||e.anyOf){let o=e.oneOf?.find(s=>s.type!=="null")||e.anyOf?.find(s=>s.type!=="null");return o?this._buildExample(o):null}return"<value>"}}});import Fo from"axios";import{homedir as Jo}from"node:os";import{join as Go}from"node:path";import{existsSync as Ko,readFileSync as Yo}from"node:fs";import{toJSONSchema as Wo}from"zod";function zo(){if(process.env.OPENAI_PROXY_TOKEN)return u.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return u.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let i=Go(Jo(),".zibby","config.json");if(Ko(i)){let e=JSON.parse(Yo(i,"utf-8"));if(e.sessionToken)return u.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(i){u.debug(`[Auth] Could not read zibby login session: ${i.message}`)}return null}function Ho(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function ce(i){if(!(typeof i!="object"||i===null)){if(Object.keys(i).length===0){i.type="object",i.additionalProperties=!0;return}if(i.type||(i.properties?i.type="object":i.items&&(i.type="array")),i.type==="object")if(i.properties){for(let[e,t]of Object.entries(i.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(i.properties[e]={type:["object","null"]});i.additionalProperties=!1,i.required=Object.keys(i.properties),Object.values(i.properties).forEach(ce)}else"additionalProperties"in i||(i.additionalProperties=!0);i.type==="array"&&i.items&&ce(i.items),i.anyOf&&i.anyOf.forEach(ce),i.oneOf&&i.oneOf.forEach(ce),i.allOf&&i.allOf.forEach(ce)}}async function Ut(i,e){u.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=zo();if(!t)throw new Error("Authentication required for structured output processing.\n Local development: Run `zibby login`\n CI/CD: Set ZIBBY_USER_TOKEN environment variable (Personal Access Token from UI settings)");let o=Ho();u.info(`\u{1F517} Using OpenAI proxy: ${o}`);let s=Wo(e),r=s;if(s.$ref&&s.definitions){let f=s.$ref.split("/").pop();r=s.definitions[f]||s,u.debug(`Extracted schema from $ref: ${f}`)}delete r.$schema,ce(r);let n=4e5,a=i;i.length>n&&(u.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${i.length} chars) exceeds limit, keeping last ${n} chars`),a=`... [truncated early content] ...
|
|
39
|
+
Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(e){if(!e)return{};let t=e.type;if(t==="object"&&e.properties){let o={};for(let[s,r]of Object.entries(e.properties))o[s]=this._buildExample(r);return o}if(t==="array"&&e.items)return[this._buildExample(e.items)];if(e.enum&&Array.isArray(e.enum)&&e.enum.length>0)return`<${e.enum.join("|")}>`;if(t==="string")return"<string>";if(t==="number"||t==="integer")return 0;if(t==="boolean")return!1;if(e.description)return`<${e.description}>`;if(e.nullable||e.oneOf||e.anyOf){let o=e.oneOf?.find(s=>s.type!=="null")||e.anyOf?.find(s=>s.type!=="null");return o?this._buildExample(o):null}return"<value>"}}});import Fo from"axios";import{homedir as Jo}from"node:os";import{join as Go}from"node:path";import{existsSync as Ko,readFileSync as Yo}from"node:fs";import{toJSONSchema as Wo}from"zod";function zo(){if(process.env.OPENAI_PROXY_TOKEN)return u.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return u.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{let i=Go(Jo(),".zibby","config.json");if(Ko(i)){let e=JSON.parse(Yo(i,"utf-8"));if(e.sessionToken)return u.debug("[Auth] Using session token from zibby login"),e.sessionToken}}catch(i){u.debug(`[Auth] Could not read zibby login session: ${i.message}`)}return null}function Ho(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function ce(i){if(!(typeof i!="object"||i===null)){if(Object.keys(i).length===0){i.type="object",i.additionalProperties=!0;return}if(i.type||(i.properties?i.type="object":i.items&&(i.type="array")),i.type==="object")if(i.properties){for(let[e,t]of Object.entries(i.properties))t.type==="object"&&t.additionalProperties&&t.additionalProperties!==!1&&(!t.properties||Object.keys(t.properties).length===0)&&(i.properties[e]={type:["object","null"]});i.additionalProperties=!1,i.required=Object.keys(i.properties),Object.values(i.properties).forEach(ce)}else"additionalProperties"in i||(i.additionalProperties=!0);i.type==="array"&&i.items&&ce(i.items),i.anyOf&&i.anyOf.forEach(ce),i.oneOf&&i.oneOf.forEach(ce),i.allOf&&i.allOf.forEach(ce)}}async function Ut(i,e){u.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");let t=zo();if(!t)throw new Error("Authentication required for structured output processing.\n Local development: Run `zibby login`\n CI/CD: Set ZIBBY_USER_TOKEN environment variable (Personal Access Token from UI settings)");let o=Ho();u.info(`\u{1F517} Using OpenAI proxy: ${o}`);let s=Wo(e),r=s;if(s.$ref&&s.definitions){let f=s.$ref.split("/").pop();r=s.definitions[f]||s,u.debug(`Extracted schema from $ref: ${f}`)}delete r.$schema,ce(r);let n=4e5,a=i;i.length>n&&(u.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${i.length} chars) exceeds limit, keeping last ${n} chars`),a=`... [truncated early content] ...
|
|
40
40
|
${i.slice(-n)}`);let l=`Extract and format the following information into structured JSON matching the schema.
|
|
41
41
|
|
|
42
42
|
RAW CONTENT:
|
|
@@ -44,10 +44,10 @@ ${a}
|
|
|
44
44
|
|
|
45
45
|
Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,c={model:j.OPENAI_POSTPROCESSING,messages:[{role:"user",content:l}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:r,strict:!0}}};u.info(`\u{1F4E4} Sending to OpenAI proxy: model=${j.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(r.properties||{}).join(", ")}`),u.debug(` Schema size: ${JSON.stringify(r).length} chars`),u.debug(` Prompt size: ${l.length} chars`);try{let f={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(f["x-proxy-token"]=t,f["x-execution-id"]=process.env.EXECUTION_ID||""):(f.Authorization=`Bearer ${t}`,f["x-api-key"]=process.env.ZIBBY_API_KEY||"",f["x-execution-id"]=process.env.EXECUTION_ID||"");let d=(await Fo.post(o,c,{headers:f,timeout:Be.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!d)throw new Error("OpenAI proxy returned empty response");let _=JSON.parse(d);return u.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:_,raw:i}}catch(f){if(f.response){let p=f.response.status,d=f.response.data;throw u.error(`\u274C OpenAI proxy request failed: ${p}`),u.error(` Status: ${p}`),u.error(` Response: ${JSON.stringify(d,null,2)}`),p===401||p===403?new Error(`Authentication failed for OpenAI proxy.
|
|
46
46
|
Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
|
|
47
|
-
Response: ${JSON.stringify(d)}`,{cause:f}):new Error(`Failed to format Cursor output: ${d?.error?.message||"Unknown error"}`,{cause:f})}throw u.error(`\u274C OpenAI proxy request failed: ${f.message}`),new Error(`Failed to format output: ${f.message}`,{cause:f})}}var jt=R(()=>{H();te()});import{copyFileSync as Zo,existsSync as lt,lstatSync as Xo,mkdirSync as Ft,rmSync as qo,symlinkSync as Vo,unlinkSync as Qo}from"node:fs";import{join as V}from"node:path";import{homedir as es}from"node:os";import{randomBytes as ts}from"node:crypto";function Jt(i){return!(!i||typeof i!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function Gt(i){let e=V(i||process.cwd(),".zibby","tmp");Ft(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${ts(4).toString("hex")}`,o=V(e,`cursor-agent-home-${t}`),s=V(o,".cursor");Ft(s,{recursive:!0});let r=es(),n=V(r,".cursor");if(lt(n))for(let a of os){let l=V(n,a);if(lt(l))try{Zo(l,V(s,a))}catch{}}if(process.platform==="darwin"){let a=V(r,"Library");if(lt(a))try{Vo(a,V(o,"Library"))}catch{}}return o}function Kt(i){if(!(!i||typeof i!="string"))try{let e=V(i,"Library");try{Xo(e).isSymbolicLink()&&Qo(e)}catch{}qo(i,{recursive:!0,force:!0})}catch{}}var os,Yt=R(()=>{os=["cli-config.json","config.json","auth.json","argv.json"]});import{spawn as ss,execSync as oe}from"node:child_process";import{writeFileSync as Wt,readFileSync as zt,mkdirSync as Ht,existsSync as Ee,accessSync as Zt,constants as Xt,unlinkSync as rs}from"node:fs";import{join as Y,resolve as ns}from"node:path";import{homedir as Oe}from"node:os";var be,qt=R(()=>{ee();H();te();he();Q();Re();at();jt();ae();Yt();be=class extends J{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[Y(Oe(),".local","bin","cursor-agent"),Y(Oe(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"];for(let o of t)try{if(o.startsWith("/")){Zt(o,Xt.X_OK);let s=oe(`"${o}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return u.debug(`[Cursor] Found agent at: ${o} (version: ${s.trim().slice(0,50)})`),!0}else{let s=oe(`which ${o}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!s)continue;let r=oe(`${o} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(r&&r.length>0)return u.debug(`[Cursor] Found '${o}' in PATH at ${s} (version: ${r.trim().slice(0,50)})`),!0}}catch{continue}return u.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:o=process.cwd(),print:s=!1,schema:r=null,skills:n=null,sessionPath:a=null,nodeName:l=null,timeout:c=Be.CURSOR_AGENT_DEFAULT,config:f={}}=t,p=f?.agent?.strictMode||!1,d=t.model??f?.agent?.cursor?.model??j.CURSOR;u.debug(`[Cursor] Invoking (model: ${d}, timeout: ${c/1e3}s, skills: ${JSON.stringify(n)})`);let
|
|
47
|
+
Response: ${JSON.stringify(d)}`,{cause:f}):new Error(`Failed to format Cursor output: ${d?.error?.message||"Unknown error"}`,{cause:f})}throw u.error(`\u274C OpenAI proxy request failed: ${f.message}`),new Error(`Failed to format output: ${f.message}`,{cause:f})}}var jt=R(()=>{H();te()});import{copyFileSync as Zo,existsSync as lt,lstatSync as Xo,mkdirSync as Ft,rmSync as qo,symlinkSync as Vo,unlinkSync as Qo}from"node:fs";import{join as V}from"node:path";import{homedir as es}from"node:os";import{randomBytes as ts}from"node:crypto";function Jt(i){return!(!i||typeof i!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function Gt(i){let e=V(i||process.cwd(),".zibby","tmp");Ft(e,{recursive:!0});let t=`${process.pid}-${Date.now()}-${ts(4).toString("hex")}`,o=V(e,`cursor-agent-home-${t}`),s=V(o,".cursor");Ft(s,{recursive:!0});let r=es(),n=V(r,".cursor");if(lt(n))for(let a of os){let l=V(n,a);if(lt(l))try{Zo(l,V(s,a))}catch{}}if(process.platform==="darwin"){let a=V(r,"Library");if(lt(a))try{Vo(a,V(o,"Library"))}catch{}}return o}function Kt(i){if(!(!i||typeof i!="string"))try{let e=V(i,"Library");try{Xo(e).isSymbolicLink()&&Qo(e)}catch{}qo(i,{recursive:!0,force:!0})}catch{}}var os,Yt=R(()=>{os=["cli-config.json","config.json","auth.json","argv.json"]});import{spawn as ss,execSync as oe}from"node:child_process";import{writeFileSync as Wt,readFileSync as zt,mkdirSync as Ht,existsSync as Ee,accessSync as Zt,constants as Xt,unlinkSync as rs}from"node:fs";import{join as Y,resolve as ns}from"node:path";import{homedir as Oe}from"node:os";var be,qt=R(()=>{ee();H();te();he();Q();Re();at();jt();ae();Yt();be=class extends J{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(e){let t=[Y(Oe(),".local","bin","cursor-agent"),Y(Oe(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"];for(let o of t)try{if(o.startsWith("/")){Zt(o,Xt.X_OK);let s=oe(`"${o}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return u.debug(`[Cursor] Found agent at: ${o} (version: ${s.trim().slice(0,50)})`),!0}else{let s=oe(`which ${o}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!s)continue;let r=oe(`${o} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(r&&r.length>0)return u.debug(`[Cursor] Found '${o}' in PATH at ${s} (version: ${r.trim().slice(0,50)})`),!0}}catch{continue}return u.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(e,t={}){let{workspace:o=process.cwd(),print:s=!1,schema:r=null,skills:n=null,sessionPath:a=null,nodeName:l=null,timeout:c=Be.CURSOR_AGENT_DEFAULT,config:f={}}=t,p=f?.agent?.strictMode||!1,d=t.model??f?.agent?.cursor?.model??j.CURSOR;u.debug(`[Cursor] Invoking (model: ${d}, timeout: ${c/1e3}s, skills: ${JSON.stringify(n)})`);let y=(this._setupMcpConfig(a,o,f,n,l)||{}).isolatedMcpHome??null,N=[Y(Oe(),".local","bin","cursor-agent"),Y(Oe(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],S=null;for(let I of N)try{if(I.startsWith("/"))Zt(I,Xt.X_OK),oe(`"${I}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!oe(`which ${I}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");oe(`${I} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}S=I,u.debug(`[Agent] Using binary: ${I}`);break}catch(h){u.debug(`[Agent] Binary '${I}' check failed: ${h.message}`);continue}if(!S)throw new Error(`Cursor Agent CLI not found or not working.
|
|
48
48
|
|
|
49
49
|
Checked paths:
|
|
50
|
-
${
|
|
50
|
+
${N.map(I=>` - ${I}`).join(`
|
|
51
51
|
`)}
|
|
52
52
|
|
|
53
53
|
Install cursor-agent:
|
|
@@ -56,54 +56,61 @@ Install cursor-agent:
|
|
|
56
56
|
Then add to PATH:
|
|
57
57
|
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
|
|
58
58
|
|
|
59
|
-
Test with: agent --version`);let b=null;if(r){let I=`zibby-result-${Date.now()}.json`;b=Y(o,".zibby","tmp",I);let
|
|
59
|
+
Test with: agent --version`);let b=null;if(r){let I=`zibby-result-${Date.now()}.json`;b=Y(o,".zibby","tmp",I);let h=Y(o,".zibby","tmp");Ee(h)||Ht(h,{recursive:!0});let A=le.generateFileOutputInstructions(r,b);e=`${e}
|
|
60
60
|
|
|
61
|
-
${
|
|
61
|
+
${A}`}let g=process.env.CURSOR_API_KEY,O=g?` | key: ***${g.slice(-4)}`:" | key: not set";console.log(`
|
|
62
62
|
\u25C6 Model: ${d||"auto"}${O}
|
|
63
63
|
`);let E=(await import("chalk")).default;console.log(`
|
|
64
64
|
${E.bold("Prompt sent to LLM:")}`),console.log(E.dim("\u2500".repeat(60))),console.log(E.dim(e)),console.log(E.dim("\u2500".repeat(60)));let $=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",d||"auto"];if(process.env.CURSOR_API_KEY&&$.push("--api-key",process.env.CURSOR_API_KEY),$.push(e),u.debug(`[Agent] Prompt: ${e.length} chars, model: ${d||"auto"}`),u.debug(`[Agent] Workspace: ${o}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${d||"auto"} (from .zibby.config.js agent.cursor.model)
|
|
65
|
-
`)}catch{}let x,w=null;try{let I=a||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);x=await this._spawnWithStreaming(S,$,o,c,null,I,
|
|
66
|
-
`)
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
${
|
|
70
|
-
|
|
71
|
-
|
|
65
|
+
`)}catch{}let x,w=null;try{let I=a||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);x=await this._spawnWithStreaming(S,$,o,c,null,I,y)}catch(I){w=I}let C=x?.stdout||"";if(r){let I=typeof r.parse=="function",h=null,A=!!(b&&Ee(b));if(b&&u.info(`[Agent] Result file: ${A?"present":"missing"} at ${b}`),A)try{let m=zt(b,"utf-8").trim();h=JSON.parse(m),u.info(`[Agent] Parsed JSON from result file OK (${m.length} chars) \u2192 object ready for validation`),w&&u.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(m){u.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${m.message}`)}else if(w)u.warn(`[Agent] Result file missing at ${b} (agent process error \u2014 may still recover if strictMode repairs)`);else throw u.error(`\u274C [Agent] Result file was never created at ${b}`),new Error(`Agent did not write required result file at ${b}`);if(h&&I)try{let m=r.parse(h);return u.info("\u2705 [Agent] Zod validation passed for structured result file"),p&&u.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:C,structured:m}}catch(m){let v=m.issues?m.issues.map(P=>` - ${P.path.join(".")}: ${P.message}`).join(`
|
|
66
|
+
`):m.message?.slice(0,400);if(u.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
|
|
67
|
+
${v}`),u.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
|
|
68
|
+
${JSON.stringify(h,null,2).slice(0,500)}`),!p)throw new Error(`Agent output failed schema validation:
|
|
69
|
+
${v}
|
|
70
|
+
|
|
71
|
+
The agent wrote invalid data that doesn't match the required outputSchema.
|
|
72
|
+
Enable strictMode in .zibby.config.js for automatic repair.`,{cause:m})}else{if(h)return u.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),p&&u.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:C,structured:h};A&&u.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(p&&!w){let m=x.parsedText,v=h?JSON.stringify(h):m;u.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${v.length} chars in)`);try{let P=await Ut(v,r);if(I){let D=r.parse(P.structured);return u.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:C,structured:D}}return{raw:C,...P}}catch(P){if(u.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${P.message}`),h)return u.warn("[Agent] Using agent's original result file as fallback"),{raw:C,structured:h}}}if(w)throw w;let k=A?h==null?"file existed but JSON.parse failed \u2014 see WARN log above":I?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw u.error(`\u274C [Agent] No validated structured output: ${k}`),u.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error(`Agent did not produce a valid result file at ${b}. Enable strictMode for proxy fallback.`)}if(w)throw w;return this._extractFinalResult(C)||x?.parsedText||C}_extractFinalResult(e){if(!e)return null;let t=e.split(`
|
|
73
|
+
`),o=null;for(let s of t){let r=s.trim();if(r)try{let n=JSON.parse(r);if(n.type==="assistant"&&n.message?.content){let a=n.message.content;if(Array.isArray(a)){let l=a.filter(c=>c.type==="text"&&c.text).map(c=>c.text).join("");l&&(o=l)}else typeof a=="string"&&a&&(o=a)}}catch{}}return o?.trim()||null}_setupMcpConfig(e,t,o,s=null,r=null){let n=o?.headless,a=Y(Oe(),".cursor"),l=Y(a,"mcp.json"),c={};if(Ee(l))try{c=JSON.parse(zt(l,"utf-8"))}catch{}let f=c.mcpServers||{},p=o?.paths?.output||q,d=Y(t||process.cwd(),p,W),_=Array.isArray(s)?s.map(S=>F(S)).filter(Boolean):[...nt()].map(([,S])=>S),y=new Set;for(let S of _)typeof S.resolve=="function"&&(y.has(S.serverName)||(y.add(S.serverName),this._ensureSkillConfigured(f,S,e,d,r,n)));if(e){let S=F("browser");S&&typeof S.resolve=="function"&&!y.has(S.serverName)&&this._ensureSkillConfigured(f,S,e,d,"execute_live",n)}if(Object.keys(f).length===0)return u.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let N=`${JSON.stringify({mcpServers:f},null,2)}
|
|
74
|
+
`;if(Jt(e)){let S=Gt(t||process.cwd()),b=Y(S,".cursor","mcp.json");return Wt(b,N,"utf8"),u.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${S} | servers: ${Object.keys(f).join(", ")}`),{isolatedMcpHome:S}}return Ee(a)||Ht(a,{recursive:!0}),Wt(l,N,"utf8"),u.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(f).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,o,s,r=null,n){let a=t.cursorKey||t.serverName,l=e[a]?a:e[t.serverName]?t.serverName:null;if(l&&o){let f=typeof t.resolve=="function"?t.resolve({sessionPath:o,nodeName:r,headless:n}):null;f?.args?e[l].args=f.args:e[l].args=(e[l].args||[]).map(_=>_.startsWith("--output-dir=")?`--output-dir=${o}`:_);let p=f?.env||{},d=t.sessionEnvKey?{[t.sessionEnvKey]:s}:{};e[l].env={...e[l].env||{},...p,...d},u.debug(`[MCP] Updated ${l} session \u2192 ${o}`);return}if(l)return;let c=t.resolve({sessionPath:o,nodeName:r,headless:n});c&&(e[a]={...c,...t.sessionEnvKey&&{env:{...c.env||{},[t.sessionEnvKey]:s}}},u.debug(`[MCP] Configured ${a}`))}_spawnWithStreaming(e,t,o,s,r=null,n=null,a=null){return new Promise((l,c)=>{let f=Date.now(),p="",d="",_=Date.now(),y=0,N=!1,S=null,b=!1,g=!1,O=null;if(n)try{O=Y(ns(String(n)),Le)}catch{O=null}let E=!1,$=()=>{E||(E=!0,Kt(a))},x={...process.env};a&&(x.HOME=a,process.platform==="win32"&&(x.USERPROFILE=a),u.debug(`[Agent] cursor-agent HOME=${a} (isolated MCP config)`));let w=ss(e,t,{cwd:o,shell:!1,stdio:["pipe","pipe","pipe"],env:x});u.debug(`[Agent] PID: ${w.pid}`),w.stdin.on("error",m=>{m.code!=="EPIPE"&&u.warn(`[Agent] stdin error: ${m.message}`)}),w.stdout.on("error",m=>{m.code!=="EPIPE"&&u.warn(`[Agent] stdout error: ${m.message}`)}),w.stderr.on("error",m=>{m.code!=="EPIPE"&&u.warn(`[Agent] stderr error: ${m.message}`)}),r?(w.stdin.write(r,m=>{m&&m.code!=="EPIPE"&&u.warn(`[Agent] Failed to write to stdin: ${m.message}`),w.stdin.end()}),u.debug(`[Agent] Prompt also piped to stdin (${r.length} chars)`)):w.stdin.end();let C=null;O&&(C=setInterval(()=>{if(!(N||g))try{if(Ee(O)){N=!0,S="studio-stop";try{rs(O)}catch{}u.warn("\u{1F6D1} Studio stop requested \u2014 terminating Cursor agent (and MCP browser session)"),w.kill("SIGTERM"),setTimeout(()=>{w.killed||w.kill("SIGKILL")},2e3)}}catch{}},600));let T=new Set,I=new Date(f).toISOString().replace(/\.\d+Z$/,""),h=setInterval(()=>{let m=Math.round((Date.now()-f)/1e3),v=Math.round((Date.now()-_)/1e3),P=[];try{let G=Math.ceil(m/60)+1,M=oe(`find "${o}" -type f -mmin -${G} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(M)for(let K of M.split(`
|
|
75
|
+
`)){let B=K.replace(`${o}/`,"");T.has(B)||(T.add(B),P.push(B))}}catch{}let D="";P.length>0&&(D=` | \u{1F4C1} new: ${P.map(M=>M.split("/").pop()).join(", ")}`),T.size>0&&(D+=` | \u{1F4E6} total: ${T.size} files`),u.debug(`\u{1F493} [Agent] Running for ${m}s | ${y} lines output${D}`),y===0&&m>=30&&T.size===0&&(m<35&&u.warn(`\u26A0\uFE0F [Agent] No output after ${m}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),m>=60&&(N=!0,S=S||"stall",u.error(`\u274C [Agent] No response after ${m}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),w.kill("SIGTERM"),setTimeout(()=>{w.killed||w.kill("SIGKILL")},3e3)))},3e4),A=setTimeout(()=>{N=!0,S=S||"timeout";let m=Math.round((Date.now()-f)/1e3);u.error(`\u23F1\uFE0F [Agent] Timeout after ${m}s \u2014 killing process (PID: ${w.pid})`),p.trim()&&u.warn(`\u{1F4E4} [Agent] Partial output (${p.length} chars) before timeout:
|
|
76
|
+
${p.slice(-2e3)}`),w.kill("SIGTERM"),setTimeout(()=>{w.killed||w.kill("SIGKILL")},5e3)},s),k=new X;k.onToolCall=(m,v)=>{let P=m,D=v;if(m==="mcpToolCall"&&v?.name)P=v.name.replace(/^mcp_+[^_]+_+/,""),P.includes("-")&&P.split("-")[0]===P.split("-")[1]&&(P=P.split("-")[0]),D=v.args??v.input??v;else{if(m==="readToolCall"||m==="editToolCall"||m==="writeToolCall")return;(m.startsWith("mcp__")||m.includes("ToolCall"))&&(P=m.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(P.includes("memory")?L.stepMemory(`Tool: ${P}`):L.stepTool(`Tool: ${P}`),D!=null&&typeof D=="object"&&Object.keys(D).length>0&&!g){let M=JSON.stringify(D),K=M.length>100?`${M.substring(0,100)}...`:M;console.log(` Input: ${K}`)}},w.stdout.on("data",m=>{let v=m.toString();p+=v,_=Date.now(),b||(b=!0);let P=k.processChunk(v);P&&!g&&process.stdout.write(P);let D=v.split(`
|
|
77
|
+
`).filter(G=>G.trim());y+=D.length}),w.stderr.on("data",m=>{let v=m.toString();d+=v,_=Date.now(),b||(b=!0);let P=v.split(`
|
|
78
|
+
`).filter(D=>D.trim());for(let D of P)u.warn(`\u26A0\uFE0F [Agent stderr] ${D}`)}),w.on("close",(m,v)=>{g=!0,$(),clearTimeout(A),clearInterval(h),C&&clearInterval(C),k.flush();let P=Math.round((Date.now()-f)/1e3);if(u.debug(`[Agent] Exited: code=${m}, signal=${v}, elapsed=${P}s, output=${p.length} chars`),N){if(S==="studio-stop"){c(new Error("Stopped from Zibby Studio"));return}c(new Error(`Cursor Agent timed out after ${P}s (limit: ${s/1e3}s). ${y} lines produced. Last output ${Math.round((Date.now()-_)/1e3)}s ago. ${p.trim()?`
|
|
72
79
|
Partial output (last 500 chars):
|
|
73
|
-
${p.slice(-500)}`:"No output captured."}`));return}if(m!==0){c(new Error(`Cursor Agent failed: exit code ${m}, signal ${
|
|
80
|
+
${p.slice(-500)}`:"No output captured."}`));return}if(m!==0){c(new Error(`Cursor Agent failed: exit code ${m}, signal ${v}. ${d.trim()?`
|
|
74
81
|
Stderr: ${d.slice(-1e3)}`:""}${p.trim()?`
|
|
75
|
-
Stdout (last 500 chars): ${p.slice(-500)}`:""}`));return}let D=
|
|
82
|
+
Stdout (last 500 chars): ${p.slice(-500)}`:""}`));return}let D=k.getResult(),G=D?JSON.stringify(D,null,2):k.getRawText()||p||"";l({stdout:p||d||"",parsedText:G})}),w.on("error",m=>{$(),clearTimeout(A),clearInterval(h),C&&clearInterval(C),c(new Error(`Cursor Agent spawn error: ${m.message}
|
|
76
83
|
Binary: ${e}
|
|
77
84
|
This usually means the binary is not in PATH. Try:
|
|
78
|
-
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}}});import{query as is}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as as}from"zod-to-json-schema";var $e,Vt=R(()=>{ee();H();ae();te();Q();$e=class extends J{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!process.env.ANTHROPIC_API_KEY;return t||u.debug("ClaudeAgentStrategy: ANTHROPIC_API_KEY not set"),t}async invoke(e,t={}){let{model:o,workspace:s=process.cwd(),schema:r=null,images:n=[],skills:a=null,sessionPath:l=null,nodeName:c=null,timeout:f,config:p={}}=t,d=o;(!d||d==="auto")&&(u.debug(`Model is '${d||"undefined"}', using default: ${j.CLAUDE}`),d=j.CLAUDE);let _=st[d]||d;st[d]&&d!==_&&u.debug(`Mapped model: ${d} \u2192 ${_}`),u.debug(`Invoking Claude Agent SDK with model: ${_}, skills: ${JSON.stringify(a)}`);let
|
|
79
|
-
\u25C6 Model: ${_}${
|
|
85
|
+
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}}});import{query as is}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as as}from"zod-to-json-schema";var $e,Vt=R(()=>{ee();H();ae();te();Q();$e=class extends J{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let t=!!process.env.ANTHROPIC_API_KEY;return t||u.debug("ClaudeAgentStrategy: ANTHROPIC_API_KEY not set"),t}async invoke(e,t={}){let{model:o,workspace:s=process.cwd(),schema:r=null,images:n=[],skills:a=null,sessionPath:l=null,nodeName:c=null,timeout:f,config:p={}}=t,d=o;(!d||d==="auto")&&(u.debug(`Model is '${d||"undefined"}', using default: ${j.CLAUDE}`),d=j.CLAUDE);let _=st[d]||d;st[d]&&d!==_&&u.debug(`Mapped model: ${d} \u2192 ${_}`),u.debug(`Invoking Claude Agent SDK with model: ${_}, skills: ${JSON.stringify(a)}`);let y=process.env.ANTHROPIC_API_KEY,N=y?` | key: ***${y.slice(-4)}`:" | key: not set";console.log(`
|
|
86
|
+
\u25C6 Model: ${_}${N}
|
|
80
87
|
`);let S=(await import("chalk")).default;console.log(`
|
|
81
|
-
${S.bold("Prompt sent to LLM:")}`),console.log(S.dim("\u2500".repeat(60))),console.log(S.dim(e)),console.log(S.dim("\u2500".repeat(60)));let{allowedTools:b,mcpServers:g}=this._resolveSkills(a,{sessionPath:l,workspace:s,nodeName:c});try{let O={cwd:s,allowedTools:b,permissionMode:"bypassPermissions",model:_,...Object.keys(g).length>0&&{mcpServers:g}};if(r){let
|
|
82
|
-
\u25C6 Model: ${_}${
|
|
88
|
+
${S.bold("Prompt sent to LLM:")}`),console.log(S.dim("\u2500".repeat(60))),console.log(S.dim(e)),console.log(S.dim("\u2500".repeat(60)));let{allowedTools:b,mcpServers:g}=this._resolveSkills(a,{sessionPath:l,workspace:s,nodeName:c});try{let O={cwd:s,allowedTools:b,permissionMode:"bypassPermissions",model:_,...Object.keys(g).length>0&&{mcpServers:g}};if(r){let A=typeof r.parse=="function"?as(r,{target:"openApi3"}):r;O.outputFormat={type:"json_schema",schema:A},u.debug("Structured output enforced via SDK outputFormat")}u.debug(`Agent SDK options: ${JSON.stringify({cwd:O.cwd,toolCount:b.length,permissionMode:O.permissionMode,model:O.model,hasOutputFormat:!!O.outputFormat})}`);let E="",$=0,x=[];u.debug("Starting Claude Agent SDK query stream");let w;try{w=is({prompt:e,options:O})}catch(h){throw u.error(`Failed to initialize Claude Agent SDK: ${h.message}`),h}let C=null,T=0,I=3;try{for await(let h of w){if(x.push(h),h.type==="error"||h.error){let k=h.error?.message||h.error||h.message||"Unknown API error";throw new Error(typeof k=="string"?k:JSON.stringify(k))}let A=JSON.stringify(h.message?.content||h.text||"").slice(0,200);if(A===C){if(T++,T>=I){let k=(h.message?.content?.[0]?.text||h.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${T}x repeated): ${k}`)}}else C=A,T=1;if(h.type==="assistant"||h.constructor?.name==="AssistantMessage"){let k=h.message?.content||h.content||[];for(let m of k)if(m.type==="thinking"&&m.thinking)console.log(`${m.thinking.substring(0,200)}${m.thinking.length>200?"...":""}`);else if(m.type==="text"&&m.text)E+=m.text,m.text.length<500?console.log(`${m.text}`):console.log(`${m.text.substring(0,200)}... (${m.text.length} chars)`);else if(m.type==="tool_use"){$++,m.name.includes("memory")?L.stepMemory(`Tool: ${m.name}`):L.stepTool(`Tool: ${m.name}`);let P=JSON.stringify(m.input).substring(0,100);console.log(` Input: ${P}${JSON.stringify(m.input).length>100?"...":""}`)}}else if(!(h.type==="user"&&h.tool_use_result)){if(h.type==="result"||h.constructor?.name==="ResultMessage"){let k=h.result||h.text||h.content||E;if(r){if(h.structured_output){u.debug("Using SDK native structured_output");let v=typeof r.parse=="function"?r.parse(h.structured_output):h.structured_output;return{raw:k,structured:v}}if(k){let m=this._extractJson(k,r);if(m)return{raw:k,structured:m}}u.warn(`Could not extract structured output \u2014 returning raw text (${(k||"").length} chars)`)}return k||""}}}if(u.warn(`Agent SDK ended without result. Collected ${x.length} messages`),E.length>0)return u.debug("Returning accumulated text from messages"),E;throw new Error("Claude Agent SDK query ended without result")}catch(h){throw u.error(`Error during query stream: ${h.message}`),h}}catch(O){throw u.error("Claude Agent SDK call failed",{error:O.message}),O}}_resolveSkills(e,t){if(e===null)return u.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return u.debug("Default IDE skills for code generation"),{allowedTools:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};let o=[],s={};for(let r of e){let n=F(r);if(!n){u.warn(`Unknown skill "${r}" \u2014 skipping`);continue}if(n.allowedTools&&o.push(...n.allowedTools),typeof n.resolve=="function"){let a=n.resolve(t);a&&(s[n.serverName]=a,u.debug(`MCP: ${n.serverName} \u2192 ${a.command} ${a.args[0]}`))}}return{allowedTools:o,mcpServers:s}}_extractJson(e,t){let o=[()=>{if(e.includes("===JSON_START===")){let s=e.indexOf("===JSON_START===")+16,r=e.indexOf("===JSON_END===");return e.substring(s,r).trim()}},()=>e.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!e.startsWith("{"))return e.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>e.trim(),()=>{let s=e.indexOf("{"),r=e.lastIndexOf("}");if(s!==-1&&r>s)return e.substring(s,r+1)}];for(let s of o)try{let r=s();if(!r)continue;let n=JSON.parse(r);if(typeof n!="object"||n===null)continue;return typeof t.parse=="function"?t.parse(n):n}catch{}return null}}});import{execSync as ls}from"node:child_process";import{zodToJsonSchema as cs}from"zod-to-json-schema";var xe,Qt=R(()=>{ee();H();ae();te();Q();xe=class extends J{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(e){if(!!!(process.env.OPENAI_API_KEY||process.env.CODEX_API_KEY))return u.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return ls("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return u.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(e,t={}){let{model:o,workspace:s=process.cwd(),schema:r=null,skills:n=null,sessionPath:a=null,nodeName:l=null,timeout:c,config:f={}}=t,{Codex:p}=await import("@openai/codex-sdk"),d=o;(!d||d==="auto")&&(u.debug(`Model is '${d||"undefined"}', using default: ${j.CODEX}`),d=j.CODEX);let _=rt[d]||d;rt[d]&&d!==_&&u.debug(`Mapped model: ${d} \u2192 ${_}`),u.debug(`Invoking Codex SDK with model: ${_}, skills: ${JSON.stringify(n)}`);let y=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;y&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=y);let N=y?` | key: ***${y.slice(-4)}`:" | key: not set";console.log(`
|
|
89
|
+
\u25C6 Model: ${_}${N}
|
|
83
90
|
`);let S=(await import("chalk")).default;console.log(`
|
|
84
|
-
${S.bold("Prompt sent to LLM:")}`),console.log(S.dim("\u2500".repeat(60))),console.log(S.dim(e)),console.log(S.dim("\u2500".repeat(60)));let b=this._resolveSkillsToMcp(n,{sessionPath:a,workspace:s,nodeName:l}),g={};Object.keys(b).length>0&&(g.mcp_servers=b,u.debug(`[Codex] MCP servers: ${Object.keys(b).join(", ")}`));let E=new p({...Object.keys(g).length>0&&{config:g}}).startThread({workingDirectory:s,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),$=r&&typeof r.parse=="function",x={};if(r)try{let w=$?cs(r,{target:"openAi"}):r;x.outputSchema=w,u.debug("Structured output via SDK outputSchema")}catch(w){u.warn(`[Codex] Schema conversion failed, will extract from text: ${w.message}`)}try{let{events:w}=await E.runStreamed(e,x),
|
|
91
|
+
${S.bold("Prompt sent to LLM:")}`),console.log(S.dim("\u2500".repeat(60))),console.log(S.dim(e)),console.log(S.dim("\u2500".repeat(60)));let b=this._resolveSkillsToMcp(n,{sessionPath:a,workspace:s,nodeName:l}),g={};Object.keys(b).length>0&&(g.mcp_servers=b,u.debug(`[Codex] MCP servers: ${Object.keys(b).join(", ")}`));let E=new p({...Object.keys(g).length>0&&{config:g}}).startThread({workingDirectory:s,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),$=r&&typeof r.parse=="function",x={};if(r)try{let w=$?cs(r,{target:"openAi"}):r;x.outputSchema=w,u.debug("Structured output via SDK outputSchema")}catch(w){u.warn(`[Codex] Schema conversion failed, will extract from text: ${w.message}`)}try{let{events:w}=await E.runStreamed(e,x),C=0,T="";for await(let I of w){let h=I.type;if(h==="item.completed"){let A=I.item,k=A?.type;if(k==="mcp_tool_call"){C++;let m=`${A.server}/${A.tool}`;if(L.stepTool(`Tool: ${m}`),A.arguments){let v=JSON.stringify(A.arguments),P=v.length>100?`${v.substring(0,100)}...`:v;console.log(` Input: ${P}`)}}else if(k==="tool_call"||k==="function_call"||k==="command_execution"){C++;let m=A.name||A.tool||A.command||"unknown";L.stepTool(`Tool: ${m}`)}else k==="agent_message"&&(T=A.text||"",T.length<500?console.log(T):console.log(`${T.substring(0,200)}... (${T.length} chars)`))}else h==="turn.completed"?u.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(I.usage||{})}`):u.debug(`[Codex] Event: ${h} ${JSON.stringify(I).slice(0,300)}`)}if(u.debug(`[Codex] Last agent message (${T.length} chars): ${T.slice(0,500)}`),r){if(!T)throw new Error("Codex agent returned no response");let I=JSON.parse(T),h=$?r.parse(I):I;return u.debug("\u2705 [Codex] Structured output validated"),{raw:T,structured:h}}return T||""}catch(w){let C=w.message||String(w);throw u.error(`\u274C [Codex] SDK call failed: ${C}`),C.includes("exited with code")&&(u.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),u.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),w}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let o={};for(let s of e){let r=F(s);if(!r){u.warn(`[Codex] Unknown skill "${s}" \u2014 skipping`);continue}if(typeof r.resolve!="function")continue;let n=r.resolve(t);if(!n)continue;let a=r.serverName||s,l={command:n.command};n.args?.length&&(l.args=n.args),n.env&&Object.keys(n.env).length>0&&(l.env=n.env),o[a]=l,u.debug(`[Codex] MCP: ${a} \u2192 ${n.command} ${(n.args||[]).join(" ")}`)}return o}}});import{execSync as us,spawn as fs}from"node:child_process";import{zodToJsonSchema as ps}from"zod-to-json-schema";import{existsSync as eo,mkdirSync as to,readFileSync as oo,rmSync as ds,writeFileSync as so}from"node:fs";import{join as se}from"node:path";function ms(i){if(!i)return null;let e=String(i),t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t?.[1])try{return JSON.parse(t[1].trim())}catch{}let o=e.indexOf("{");if(o<0)return null;let s=0,r=!1,n=!1,a=-1;for(let l=o;l<e.length;l++){let c=e[l];if(r){n?n=!1:c==="\\"?n=!0:c==='"'&&(r=!1);continue}if(c==='"'){r=!0;continue}if(c==="{"){s===0&&(a=l),s+=1;continue}if(c==="}"){if(s===0)continue;if(s-=1,s===0&&a>=0){let f=e.slice(a,l+1);try{return JSON.parse(f)}catch{a=-1}}}}return null}function gs(i){let e=String(i||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return ms(e)}}function hs(i){try{let e=JSON.parse(i);if(typeof e=="string")return e;if(typeof e?.response=="string")return e.response;if(typeof e?.text=="string")return e.text;if(typeof e?.output=="string")return e.output;if(Array.isArray(e?.candidates)&&e.candidates.length>0){let t=e.candidates[0];if(typeof t?.content=="string")return t.content;if(Array.isArray(t?.content?.parts)){let o=t.content.parts.map(s=>typeof s?.text=="string"?s.text:"").join("");if(o.trim())return o}}}catch{}return i}var Ie,ro=R(()=>{ee();H();te();Q();at();Re();Ie=class extends J{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY))return u.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return us("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return u.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,t={}){let{model:o,workspace:s=process.cwd(),schema:r=null,skills:n=null,sessionPath:a=null,nodeName:l=null,timeout:c=600*1e3}=t,f=o;(!f||f==="auto")&&(f=j.GEMINI);let p=Bt[f]||f,d=String(process.env.GEMINI_API_KEY||"").trim(),_=String(process.env.GOOGLE_API_KEY||"").trim(),y=this._resolveSkillsToMcp(n,{sessionPath:a,workspace:s,nodeName:l}),N=Object.keys(y).length>0,S=e,b=r&&typeof r.parse=="function",g=null;if(r){let A;try{let k=b?ps(r,{target:"openAi"}):r;A=JSON.stringify(k,null,2)}catch{A="{}"}if(N){S+=`
|
|
85
92
|
|
|
86
93
|
Write valid JSON that matches this schema:
|
|
87
|
-
${
|
|
94
|
+
${A}`;let k=`zibby-result-${Date.now()}.json`,m=se(s,".zibby","tmp");g=se(m,k),to(m,{recursive:!0}),S+=le.generateFileOutputInstructions(r,g)}else S+=`
|
|
88
95
|
|
|
89
96
|
Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
|
|
90
|
-
${
|
|
91
|
-
${
|
|
92
|
-
${
|
|
97
|
+
${A}`}let O=this._createGeminiConfigDir(s,y),E=["--output-format","json"];p&&p!=="auto"&&E.push("--model",p);let $=Object.keys(y);if($.length>0){E.push("--approval-mode","yolo");for(let A of $)E.push("--allowed-mcp-server-names",A);u.info(`[Gemini] Enabling MCP servers: ${$.join(", ")}`)}else n&&n.length>0&&u.warn(`[Gemini] Skills requested but no MCP servers configured: ${n.join(", ")}`);E.push("-p",S);let x={...process.env,GEMINI_CLI_HOME:O};d?(x.GEMINI_API_KEY=d,delete x.GOOGLE_API_KEY):_&&(x.GOOGLE_API_KEY=_,delete x.GEMINI_API_KEY),u.debug(`[Gemini] Command: gemini ${E.slice(0,8).join(" ")}... (${E.length} total args)`),u.debug(`[Gemini] Config home: ${O}`),u.debug(`[Gemini] GEMINI_CLI_HOME env: ${x.GEMINI_CLI_HOME}`);let w="",C=null;try{w=await new Promise((k,m)=>{let v=fs("gemini",E,{cwd:s,env:x,stdio:["ignore","pipe","pipe"]}),P="",D="",G=setTimeout(()=>{try{v.kill("SIGTERM")}catch{}},c);v.stdout.on("data",M=>{P+=M.toString()}),v.stderr.on("data",M=>{D+=M.toString()}),v.on("error",M=>{clearTimeout(G),m(M)}),v.on("close",M=>{if(clearTimeout(G),M===0)return k(P.trim());m(new Error(`gemini failed with code ${M}: ${(D||P).trim()}`))})})}catch(A){C=A}finally{try{ds(O,{recursive:!0,force:!0})}catch{}}let T=hs(w).trim();if(!r){if(C)throw C;return T}if(g){let A=eo(g);if(u.info(`[Gemini] Result file: ${A?"present":"missing"} at ${g}`),A)try{let k=oo(g,"utf-8").trim(),m=JSON.parse(k),v=b?r.parse(m):m;return u.info("[Gemini] Structured output recovered from result file"),{raw:T,structured:v}}catch(k){u.warn(`[Gemini] Result file parse/validation failed: ${k.message}`)}else C||u.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let I=null;if(r){let A=new X;A.zodSchema=r,A.processChunk(T),A.flush(),I=A.getResult()}if(u.info(`[Gemini] Raw stdout length: ${w.length} chars`),u.info(`[Gemini] Extracted text length: ${T.length} chars`),u.info(`[Gemini] StreamParser result: ${I?"extracted":"null"}`),I||(T.length<2e3?u.info(`[Gemini] Raw text preview:
|
|
98
|
+
${T}`):u.info(`[Gemini] Raw text preview (first 1000 chars):
|
|
99
|
+
${T.slice(0,1e3)}`),I=gs(T)),!I)throw C||(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 h=b?r.parse(I):I;return{raw:T,structured:h}}_resolveSkillsToMcp(e,t={}){if(!Array.isArray(e)||e.length===0)return{};let o={};for(let s of e){let r=F(s);if(!r||typeof r.resolve!="function")continue;let n=r.resolve(t);if(!n)continue;let a=r.cursorKey||r.serverName||s,l={command:n.command};n.args?.length&&(l.args=n.args),n.env&&Object.keys(n.env).length>0&&(l.env=n.env),n.cwd&&(l.cwd=n.cwd),o[a]=l}return o}_createGeminiConfigDir(e,t){let o=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,s=se(e||process.cwd(),".zibby","tmp",`gemini-home-${o}`),r=se(s,".gemini");to(r,{recursive:!0});let n=se(r,"settings.json"),a={},l=se(process.env.HOME||"",".gemini","settings.json");if(eo(l))try{a=JSON.parse(oo(l,"utf-8"))}catch{a={}}let c={...a,mcpServers:{...a.mcpServers&&typeof a.mcpServers=="object"?a.mcpServers:{},...t||{}}};so(n,`${JSON.stringify(c,null,2)}
|
|
93
100
|
`,"utf-8");let f=se(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{so(f,`${JSON.stringify(c,null,2)}
|
|
94
|
-
`,"utf-8")}catch{}return u.debug(`[Gemini] Created isolated config with ${Object.keys(c.mcpServers||{}).length} MCP servers`),u.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(c.mcpServers||{}),null,2)}`),s}}});var
|
|
101
|
+
`,"utf-8")}catch{}return u.debug(`[Gemini] Created isolated config with ${Object.keys(c.mcpServers||{}).length} MCP servers`),u.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(c.mcpServers||{}),null,2)}`),s}}});var Ae,ct=R(()=>{Ae=class{formatTools(e){throw new Error("formatTools() must be implemented")}hasToolCalls(e){throw new Error("hasToolCalls() must be implemented")}parseToolCalls(e){throw new Error("parseToolCalls() must be implemented")}getTextContent(e){throw new Error("getTextContent() must be implemented")}buildAssistantMessage(e){throw new Error("buildAssistantMessage() must be implemented")}buildToolResultMessage(e,t){throw new Error("buildToolResultMessage() must be implemented")}injectToolsIntoBody(e,t){throw new Error("injectToolsIntoBody() must be implemented")}}});var ue,no=R(()=>{ct();ue=class extends Ae{formatTools(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters||t.input_schema||{type:"object",properties:{}}}}))}hasToolCalls(e){let t=e.choices?.[0]?.message;return!!(t?.tool_calls&&t.tool_calls.length>0)}parseToolCalls(e){return(e.choices?.[0]?.message?.tool_calls||[]).map(o=>({id:o.id,name:o.function.name,args:JSON.parse(o.function.arguments||"{}")}))}getTextContent(e){return e.choices?.[0]?.message?.content||""}buildAssistantMessage(e){return e.choices?.[0]?.message}buildToolResultMessage(e,t){return{role:"tool",tool_call_id:e,content:typeof t=="string"?t:JSON.stringify(t)}}injectToolsIntoBody(e,t){return t.length>0&&(e.tools=t),e}}});var Te,ut=R(()=>{Te=class{async fetchCompletion(e,t,o={}){throw new Error("fetchCompletion() must be implemented")}async fetchStreamingCompletion(e,t,o={}){throw new Error("fetchStreamingCompletion() must be implemented")}}});function Ue(i){return Buffer.byteLength(JSON.stringify(i),"utf8")}function je(i,e){let t=String(i||"");if(t.length<=e)return t;let o=Math.max(0,e-28);return`${t.slice(0,o)}
|
|
95
102
|
|
|
96
|
-
[truncated for size budget]`}function ft(i,e=0){if(!i||typeof i!="object"||e>8)return i;if(Array.isArray(i))return i.map(o=>ft(o,e+1));let t={};for(let[o,s]of Object.entries(i))o==="description"||o==="title"||o==="examples"||o==="default"||(t[o]=ft(s,e+1));return t}function ys(i=[]){return i.map(e=>({...e,function:{...e.function,description:je(e.function?.description||"",180),parameters:ft(e.function?.parameters||{type:"object",properties:{}})}}))}function io(i){let e=new Set;for(let s of i)if(s.role==="assistant"&&Array.isArray(s.tool_calls))for(let r of s.tool_calls)e.add(r.id);let t=i.filter(s=>s.role==="tool"?e.has(s.tool_call_id):!0),o=new Set;for(let s of t)s.role==="tool"&&o.add(s.tool_call_id);return t.map(s=>{if(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.every(l=>o.has(l.id)))return s;let{tool_calls:n,...a}=s;return{...a,content:a.content||""}})}function pt(i,e={}){let t=e.maxBytes||49e3,o=e.systemMaxChars||12e3,s={...i,messages:Array.isArray(i.messages)?[...i.messages]:[],tools:Array.isArray(i.tools)?ys(i.tools):i.tools};s.messages.length>0&&s.messages[0]?.role==="system"&&(s.messages[0]={...s.messages[0],content:je(s.messages[0].content,o)});let r=!1;for(;Ue(s)>t&&s.messages.length>2;)s.messages.splice(1,1),r=!0;if(r&&(s.messages=io(s.messages)),Ue(s)>t&&s.messages.length>0&&(s.messages[0]={...s.messages[0],content:je(s.messages[0].content,6e3)},r=!0),Ue(s)>t){let n=s.messages.find(l=>l.role==="system")||s.messages[0],a=s.messages.slice(-2);s.messages=io([n,...a].filter(Boolean).map((l,c)=>({...l,content:je(l.content,c===0?4e3:8e3)}))),r=!0}return{body:s,meta:{bytes:Ue(s),trimmed:r,maxBytes:t,messageCount:s.messages.length}}}var ao=R(()=>{});var lo,fe,co=R(()=>{ut();ao();lo=i=>Buffer.byteLength(JSON.stringify(i),"utf8"),fe=class extends
|
|
97
|
-
`);_=g.pop();for(let O of g){if(!O.startsWith("data: "))continue;let E=O.slice(6).trim();if(E==="[DONE]")continue;let $;try{$=JSON.parse(E)}catch{continue}let x=$.choices?.[0]?.delta;if(x&&(x.content&&(
|
|
103
|
+
[truncated for size budget]`}function ft(i,e=0){if(!i||typeof i!="object"||e>8)return i;if(Array.isArray(i))return i.map(o=>ft(o,e+1));let t={};for(let[o,s]of Object.entries(i))o==="description"||o==="title"||o==="examples"||o==="default"||(t[o]=ft(s,e+1));return t}function ys(i=[]){return i.map(e=>({...e,function:{...e.function,description:je(e.function?.description||"",180),parameters:ft(e.function?.parameters||{type:"object",properties:{}})}}))}function io(i){let e=new Set;for(let s of i)if(s.role==="assistant"&&Array.isArray(s.tool_calls))for(let r of s.tool_calls)e.add(r.id);let t=i.filter(s=>s.role==="tool"?e.has(s.tool_call_id):!0),o=new Set;for(let s of t)s.role==="tool"&&o.add(s.tool_call_id);return t.map(s=>{if(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.every(l=>o.has(l.id)))return s;let{tool_calls:n,...a}=s;return{...a,content:a.content||""}})}function pt(i,e={}){let t=e.maxBytes||49e3,o=e.systemMaxChars||12e3,s={...i,messages:Array.isArray(i.messages)?[...i.messages]:[],tools:Array.isArray(i.tools)?ys(i.tools):i.tools};s.messages.length>0&&s.messages[0]?.role==="system"&&(s.messages[0]={...s.messages[0],content:je(s.messages[0].content,o)});let r=!1;for(;Ue(s)>t&&s.messages.length>2;)s.messages.splice(1,1),r=!0;if(r&&(s.messages=io(s.messages)),Ue(s)>t&&s.messages.length>0&&(s.messages[0]={...s.messages[0],content:je(s.messages[0].content,6e3)},r=!0),Ue(s)>t){let n=s.messages.find(l=>l.role==="system")||s.messages[0],a=s.messages.slice(-2);s.messages=io([n,...a].filter(Boolean).map((l,c)=>({...l,content:je(l.content,c===0?4e3:8e3)}))),r=!0}return{body:s,meta:{bytes:Ue(s),trimmed:r,maxBytes:t,messageCount:s.messages.length}}}var ao=R(()=>{});var lo,fe,co=R(()=>{ut();ao();lo=i=>Buffer.byteLength(JSON.stringify(i),"utf8"),fe=class extends Te{async fetchCompletion(e,t,o={}){let s=lo(e),{body:r,meta:n}=pt(e,o.payloadCompaction);o.onBudget?.({streaming:!1,beforeBytes:s,meta:n});let a=this.#e(o),l=`${t.baseUrl}${o.chatCompletionsPath||"/v1/chat/completions"}`,c=await fetch(l,{method:"POST",headers:t.headers,body:JSON.stringify(r),signal:a});if(!c.ok){let f=await c.text();throw c.status===401||c.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${c.status}: ${f}`)}return c.json()}async fetchStreamingCompletion(e,t,o={}){let s={...e,stream:!0},r=lo(s),{body:n,meta:a}=pt(s,o.payloadCompaction);o.onBudget?.({streaming:!0,beforeBytes:r,meta:a});let l=this.#e(o),c=`${t.baseUrl}${o.chatCompletionsPath||"/v1/chat/completions"}`,f=await fetch(c,{method:"POST",headers:t.headers,body:JSON.stringify(n),signal:l});if(!f.ok){let S=await f.text();throw f.status===401||f.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${f.status}: ${S}`)}let p=f.body.getReader(),d=new TextDecoder,_="",y="",N=new Map;for(;;){let{done:S,value:b}=await p.read();if(S)break;_+=d.decode(b,{stream:!0});let g=_.split(`
|
|
104
|
+
`);_=g.pop();for(let O of g){if(!O.startsWith("data: "))continue;let E=O.slice(6).trim();if(E==="[DONE]")continue;let $;try{$=JSON.parse(E)}catch{continue}let x=$.choices?.[0]?.delta;if(x&&(x.content&&(y+=x.content,o.onToken&&o.onToken(x.content)),x.tool_calls))for(let w of x.tool_calls){let C=w.index??0;N.has(C)||N.set(C,{id:"",name:"",args:""});let T=N.get(C);w.id&&(T.id=w.id),w.function?.name&&(T.name=w.function.name),w.function?.arguments!=null&&(T.args+=w.function.arguments)}}}if(N.size>0){let S=[...N.entries()].sort(([b],[g])=>b-g).map(([,b])=>({id:b.id,type:"function",function:{name:b.name,arguments:b.args}}));return{choices:[{message:{role:"assistant",content:y||null,tool_calls:S}}]}}return{choices:[{message:{role:"assistant",content:y}}]}}#e(e={}){let t=[e.signal,e.timeout?AbortSignal.timeout(e.timeout):null].filter(Boolean);return t.length>1?AbortSignal.any(t):t[0]||void 0}}});var uo=R(()=>{ct();no();ut();co()});import{Client as Ss}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as _s}from"@modelcontextprotocol/sdk/client/stdio.js";var Fe,fo=R(()=>{H();Fe=class{#e=new Map;async ensureServer(e,t){if(this.#e.has(e))return this.#e.get(e);let{command:o,args:s=[],env:r={}}=t;u.debug(`[MCP] Starting ${e}: ${o} ${s.join(" ")}`);let n=new _s({command:o,args:s,env:{...process.env,...r}}),a=new Ss({name:`zibby-chat-${e}`,version:"1.0.0"},{capabilities:{}});await a.connect(n);let l={client:a,transport:n,serverConfig:t};return this.#e.set(e,l),l}async callTool(e,t,o={}){let s=this.#e.get(e);if(!s)throw new Error(`MCP server "${e}" not running`);u.debug(`[MCP] ${e}.${t}(${JSON.stringify(o).slice(0,200)})`);let r=await s.client.callTool({name:t,arguments:o});return{text:r.content?.filter(a=>a.type==="text").map(a=>a.text).join(`
|
|
98
105
|
`)||"",isError:r.isError||!1}}isRunning(e){return this.#e.has(e)}async stopServer(e){let t=this.#e.get(e);if(t){try{await t.client.close()}catch(o){u.debug(`[MCP] Error closing ${e}: ${o.message}`)}this.#e.delete(e)}}async stopAll(){let e=[...this.#e.keys()];await Promise.allSettled(e.map(t=>this.stopServer(t)))}}});import{existsSync as ws,readFileSync as Es}from"node:fs";import{join as Os}from"node:path";import{homedir as bs}from"node:os";function $s(){try{let i=Os(bs(),".zibby","config.json");return ws(i)?JSON.parse(Es(i,"utf-8")):{}}catch{return{}}}function Je(i){return String(i||"").replace(/\/v1\/?$/,"")}function xs(i,e){let t=process.env.OPENAI_PROXY_URL;if(t)return Je(t);if(i==="session")return e.proxyUrl?Je(e.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(i==="byok"){let o=process.env.OPENAI_BASE_URL;return Je(o||"https://api.openai.com")}return Je(t||"")}function dt(){let i=$s(),e=process.env.ZIBBY_USER_TOKEN||i.sessionToken||null,t=process.env.OPENAI_API_KEY||null,o=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),s=process.env.OPENAI_PROXY_NO_AUTH==="true",r=process.env.OPENAI_PROXY_URL,n="session";o==="byok"||o==="local"||o==="session"?n=o:e?n="session":t?n="byok":r&&s&&(n="local");let a=xs(n,i),l={"Content-Type":"application/json"};if(n==="session"){if(!e)return{ok:!1,mode:n,reason:"missing_session_token"};l.Authorization=`Bearer ${e}`}else if(n==="byok"){if(!t)return{ok:!1,mode:n,reason:"missing_openai_api_key"};l.Authorization=`Bearer ${t}`}else if(n==="local"){if(!a)return{ok:!1,mode:n,reason:"missing_openai_proxy_url"};!s&&t&&(l.Authorization=`Bearer ${t}`)}return a?{ok:!0,mode:n,baseUrl:a,headers:l,tokenPreview:l.Authorization?`***${l.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:n,reason:"missing_base_url"}}var po=R(()=>{});function Ge(i,e){let t=String(i??"");return t.length<=e?t:`${t.slice(0,Math.max(0,e-30))}
|
|
99
106
|
|
|
100
|
-
[tool result truncated for size]`}function Is(i,e){if(typeof i=="string")return Ge(i,e);try{return Ge(JSON.stringify(i),e)}catch{return Ge(String(i),e)}}function mo(i){let e=new Set;for(let s of i)if(s.role==="assistant"&&Array.isArray(s.tool_calls))for(let r of s.tool_calls)e.add(r.id);let t=i.filter(s=>s.role==="tool"?e.has(s.tool_call_id):!0),o=new Set;for(let s of t)s.role==="tool"&&o.add(s.tool_call_id);return t.map(s=>{if(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.every(l=>o.has(l.id)))return s;let{tool_calls:n,...a}=s;return{...a,content:a.content||""}})}function
|
|
107
|
+
[tool result truncated for size]`}function Is(i,e){if(typeof i=="string")return Ge(i,e);try{return Ge(JSON.stringify(i),e)}catch{return Ge(String(i),e)}}function mo(i){let e=new Set;for(let s of i)if(s.role==="assistant"&&Array.isArray(s.tool_calls))for(let r of s.tool_calls)e.add(r.id);let t=i.filter(s=>s.role==="tool"?e.has(s.tool_call_id):!0),o=new Set;for(let s of t)s.role==="tool"&&o.add(s.tool_call_id);return t.map(s=>{if(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.every(l=>o.has(l.id)))return s;let{tool_calls:n,...a}=s;return{...a,content:a.content||""}})}function As(i){let e=Array.isArray(i?.messages)?i.messages:[],t=e.find(r=>r.role==="system"),o=e.slice(-4).map(r=>({...r,content:Ge(r.content,r.role==="tool"?1200:2500)}));o=mo(o);let s={...i,messages:[t,...o].filter(Boolean)};return delete s.tools,s}async function Ts({body:i,streaming:e,auth:t,options:o,fetchCompletion:s,fetchStreamingCompletion:r,onFallbackLog:n}){try{return e?await r(i,t,o):await s(i,t,o)}catch(a){let l=String(a?.message||a||"");if(!/proxy error 413|payload too large/i.test(l))throw a;let c=As(i);return typeof n=="function"&&n(i,c),{data:e?await r(c,t,o):await s(c,t,o),fallback:c}}}async function go({body:i,auth:e,options:t,streaming:o,toolContext:s,activeSkills:r,round:n,verbose:a,dependencies:l,config:c={}}){let f=c.maxToolResultChars||3e3,{fetchCompletion:p,fetchStreamingCompletion:d,onFallbackLog:_,hasToolCalls:y,getTextContent:N,parseToolCalls:S,buildAssistantMessage:b,buildToolResultMessage:g,executeTool:O,onToolCallLog:E,injectTools:$}=l;Array.isArray(i?.messages)&&(i.messages=mo(i.messages));let x=await Ts({body:i,streaming:o,auth:e,options:t,fetchCompletion:p,fetchStreamingCompletion:d,onFallbackLog:_}),w=x?.data||x;if(!y(w))return{done:!0,text:N(w),body:x?.fallback||i};let C=S(w),T=x?.fallback||i;T.messages.push(b(w)),a&&typeof E=="function"&&E(C);let I=await Promise.all(C.map((h,A)=>(typeof t.onToolCall=="function"&&t.onToolCall(h.name,h.args,{round:n,index:A,total:C.length}),O(h,s))));for(let h=0;h<C.length;h++){let k=C[h].name==="get_skill_context"?typeof I[h]=="string"?I[h]:JSON.stringify(I[h]):Is(I[h],f);T.messages.push(g(C[h].id,k))}return typeof t.onToolCall=="function"&&t.onToolCall(null),$(T,r),{done:!1,body:T}}var ho=R(()=>{});function de(i){!i||typeof i!="object"||(i.type==="object"&&i.properties&&(i.required=Object.keys(i.properties),i.additionalProperties=!1,Object.values(i.properties).forEach(de)),i.type==="array"&&i.items&&de(i.items),i.anyOf&&i.anyOf.forEach(de),i.oneOf&&i.oneOf.forEach(de),i.allOf&&i.allOf.forEach(de))}function Ke(i){return Array.isArray(i)?new Set(i.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function Ns(i){return Array.isArray(i)?i.map(e=>String(e||"").trim()).filter(Boolean):[]}var vs,Cs,mt,yo,pe,ks,ve,So=R(()=>{ee();H();te();uo();fo();Q();po();ho();vs=j.ASSISTANT,Cs=15,mt="get_skill_context";yo={maxBytes:49e3,systemMaxChars:12e3},pe=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",ks=i=>Buffer.byteLength(JSON.stringify(i),"utf8");ve=class extends J{#e;#t;#o=new Fe;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new ue,this.#t=e.completionProvider||new fe):(this.#e=e||new ue,this.#t=new fe)}canHandle(e){return dt().ok}async invoke(e,t={}){let o=t.model&&t.model!=="auto"?t.model:vs,s=dt();if(!s.ok)throw s.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):s.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):s.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${s.reason}).`);let r=t.messages||[{role:"user",content:e}],n=s.baseUrl,a=pe();if(a?await this.#m(r,o,n,s.tokenPreview||"none"):u.debug(`[Assistant] ${n} | model: ${o} | messages: ${r.length}`),t.schema)return this.#c(o,r,s,t);let l=t.activeSkills||[],c=this.#f(t),f=this.#p(l,c),p=this.#d(f),d=this.#u(t),_={...t,payloadCompaction:d},y={activeSkills:f,options:_,executionRegistry:p,capabilityPolicy:c},N=!!t.stream,S={model:o,messages:[...r],stream:!1};this.#r(S,f,c);for(let b=0;b<Cs;b++){if(t.signal?.aborted)throw new Error("Aborted");let g=await go({body:S,auth:s,options:_,streaming:N,toolContext:y,activeSkills:f,round:b,verbose:a,dependencies:{fetchCompletion:this.#n.bind(this),fetchStreamingCompletion:this.#l.bind(this),onFallbackLog:(O,E)=>{pe()&&console.log(`413 fallback: messages ${O.messages.length} -> ${E.messages.length}, bytes=${ks(E)}`)},hasToolCalls:O=>this.#e.hasToolCalls(O),getTextContent:O=>this.#e.getTextContent(O),parseToolCalls:O=>this.#e.parseToolCalls(O),buildAssistantMessage:O=>this.#e.buildAssistantMessage(O),buildToolResultMessage:(O,E)=>this.#e.buildToolResultMessage(O,E),executeTool:(O,E)=>this.#a(O,E),onToolCallLog:async O=>{let E=(await import("chalk")).default;console.log(E.dim(` ${O.map($=>`${$.name}(${JSON.stringify($.args).slice(0,80)})`).join(", ")}`))},injectTools:(O,E)=>this.#r(O,E,c)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(g.done)return g.text;S.messages=g.body.messages,g.body.tools?S.tools=g.body.tools:delete S.tools}return"I hit my tool-calling limit for this turn. Please try again."}async cleanup(){await this.#o.stopAll()}#r(e,t,o=null){let s=this.#i(t,o),r=this.#e.formatTools(s);this.#e.injectToolsIntoBody(e,r)}#i(e,t=null){let o=[],s=new Set;for(let r of e){let n=F(r);if(n?.tools?.length)for(let a of n.tools)this.#s(a.name,t)&&(s.has(a.name)||(s.add(a.name),o.push({name:a.name,description:a.description,parameters:a.parameters||a.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#s(mt,t)&&o.push({name:mt,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),o}async#a(e,t){let{activeSkills:o,options:s,executionRegistry:r,capabilityPolicy:n}=t;if(!this.#s(e.name,n))return`Tool "${e.name}" blocked by policy`;if(e.name===mt){let c=String(e.args?.skillId||"").trim();if(!c)return JSON.stringify({error:"skillId is required"});if(!o.includes(c))return JSON.stringify({error:`Skill "${c}" is not active`,activeSkills:o});let f=F(c);if(!f)return JSON.stringify({error:`Skill "${c}" not found`});let p=typeof f.promptFragment=="function"?f.promptFragment():f.promptFragment||"",d=(f.tools||[]).map(y=>y.name),_=JSON.stringify({skillId:c,description:f.description||"",toolNames:d,promptFragment:p||""});return pe()&&(console.log(`
|
|
101
108
|
\u{1F4D6} get_skill_context("${c}") \u2192 ${_.length} chars (fragment: ${p.length} chars)`),console.log(` tools: [${d.join(", ")}]`),console.log(` fragment preview: ${p.slice(0,200).replace(/\n/g,"\\n")}\u2026
|
|
102
109
|
`)),_}let a=r?.get(e.name)||null;if(!a)return`Unknown tool: ${e.name}`;let l=F(a.skillId);if(!l)return`Skill "${a.skillId}" not found for tool "${e.name}"`;if(a.mode==="handler")try{return l.handleToolCall(e.name,e.args,t)}catch(c){return`Error in ${e.name}: ${c.message}`}if(a.mode==="mcp")try{if(!this.#o.isRunning(l.serverName)){let f=l.resolve(s);if(!f)return`Skill "${a.skillId}" is not available (cannot start server)`;await this.#o.ensureServer(l.serverName,f)}let c=await this.#o.callTool(l.serverName,e.name,e.args);return c.text||(c.isError?"Tool call failed":"Done")}catch(c){return`MCP error (${l.serverName}): ${c.message}`}return`Skill "${a.skillId}" owns tool "${e.name}" but has no execution mode`}async#l(e,t,o){return this.#t.fetchStreamingCompletion(e,t,{...o,onBudget:({beforeBytes:s,meta:r})=>{pe()&&console.log(`payload bytes (stream) before=${s} after=${r.bytes} trimmed=${r.trimmed} messages=${r.messageCount}`)}})}async#n(e,t,o){return this.#t.fetchCompletion(e,t,{...o,onBudget:({beforeBytes:s,meta:r})=>{pe()&&console.log(`payload bytes before=${s} after=${r.bytes} trimmed=${r.trimmed} messages=${r.messageCount}`)}})}async#c(e,t,o,s){let{zodToJsonSchema:r}=await import("zod-to-json-schema"),n=typeof s.schema?.parse=="function",a=n?r(s.schema):s.schema;delete a.$schema,de(a);let l={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:a,strict:!0}}},c=await this.#n(l,o,s),f=this.#e.getTextContent(c),p=JSON.parse(f),d=n?s.schema.parse(p):p;return{raw:f,structured:d}}#u(e={}){let t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||yo.maxBytes),systemMaxChars:Number(t.systemMaxChars||yo.systemMaxChars)}}#f(e={}){let t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:Ke(t.allowTools||e.allowTools),denyTools:Ke(t.denyTools||e.denyTools),denyPrefixes:Ns(t.denyPrefixes||e.denyToolPrefixes),includeSkills:Ke(t.includeSkills||e.includeSkills),excludeSkills:Ke(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#p(e,t){let o=t?.includeSkills||new Set,s=t?.excludeSkills||new Set;return o.size===0&&s.size===0?e:e.filter(r=>!(o.size>0&&!o.has(r)||s.has(r)))}#s(e,t){let o=String(e||"").trim();if(!o)return!1;let s=t?.allowTools;if(s&&s.size>0&&!s.has(o))return!1;let r=t?.denyTools;return!(r&&r.has(o)||(t?.denyPrefixes||[]).some(a=>o.startsWith(a)))}#d(e){let t=new Map,o=[];for(let s of e){let r=F(s);if(!r?.tools?.length)continue;let n=typeof r.handleToolCall=="function"?"handler":r.serverName&&typeof r.resolve=="function"?"mcp":null;if(n)for(let a of r.tools){let l=String(a?.name||"").trim();if(l){if(t.has(l)){o.push({tool:l,winner:t.get(l).skillId,skipped:s});continue}t.set(l,{skillId:s,mode:n})}}}if(o.length>0&&pe()){let s=o.slice(0,5).map(r=>`${r.tool}:${r.winner}>${r.skipped}`).join(", ");console.log(`tool registry collisions: ${s}${o.length>5?" ...":""}`)}return t}async#m(e,t,o,s){console.log(`
|
|
103
110
|
\u25C6 Model: ${t} | proxy: ${o} | token: ${s||"none"}
|
|
104
|
-
`);let r=(await import("chalk")).default;console.log(r.bold("Prompt sent to LLM:")),console.log(r.dim("\u2500".repeat(60)));let n=!1;for(let a of e)if(a.role==="system")console.log(r.dim(`[System] ${a.content||""}`));else{n||(console.log(r.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),n=!0);let l=a.role==="user"?"Human":"AI",c=a.content?.length>200?`${a.content.slice(0,200)}...`:a.content||"";console.log(r.dim(`[${l}] ${c}`))}console.log(r.dim("\u2500".repeat(60)))}}});var gt={};Pe(gt,{AgentStrategy:()=>J,AssistantStrategy:()=>ve,ClaudeAgentStrategy:()=>$e,CodexAgentStrategy:()=>xe,CursorAgentStrategy:()=>be,GeminiAgentStrategy:()=>Ie,getAgentStrategy:()=>wo,invokeAgent:()=>Ps});function wo(i={}){let{state:e={},preferredAgent:t=null}=i,o=t||e.agentType||process.env.AGENT_TYPE;if(!o)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");u.debug(`Agent selection: requested=${o}`);let s=_o.find(r=>r.getName()===o);if(!s)throw new Error(`Unknown agent '${o}'. Available: ${_o.map(r=>r.getName()).join(", ")}`);if(u.debug(`Checking if ${o} can handle this environment...`),!s.canHandle(i)){let n={assistant:"Run `zibby login` to authenticate",claude:"Set ANTHROPIC_API_KEY in .env",cursor:"Install cursor-agent CLI or set CURSOR_API_KEY",codex:"Install codex CLI (npm i -g @openai/codex) and set OPENAI_API_KEY in .env",gemini:"Install gemini CLI (npm i -g @google/gemini-cli) and set GEMINI_API_KEY in .env"}[o]||"Check your environment configuration";throw new Error(`Agent '${o}' is not available. ${n}`)}return u.debug(`Using agent: ${s.getName()}`),s}async function Ps(i,e={},t={}){try{await import("@zibby/skills")}catch{}let o=wo(e),s=e.state?.config||t.config||{},r=s.models||{},n=t.nodeName&&r[t.nodeName]||null,a=r.default||null,l=o.name,c=s.agent?.[l]?.model||null,f=n||a||c||t.model||null,p={...t,model:f,workspace:e.state?.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:s},d=p.skills||[];if(d.length>0&&!t.skipPromptFragments){let{getSkill:
|
|
111
|
+
`);let r=(await import("chalk")).default;console.log(r.bold("Prompt sent to LLM:")),console.log(r.dim("\u2500".repeat(60)));let n=!1;for(let a of e)if(a.role==="system")console.log(r.dim(`[System] ${a.content||""}`));else{n||(console.log(r.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),n=!0);let l=a.role==="user"?"Human":"AI",c=a.content?.length>200?`${a.content.slice(0,200)}...`:a.content||"";console.log(r.dim(`[${l}] ${c}`))}console.log(r.dim("\u2500".repeat(60)))}}});var gt={};Pe(gt,{AgentStrategy:()=>J,AssistantStrategy:()=>ve,ClaudeAgentStrategy:()=>$e,CodexAgentStrategy:()=>xe,CursorAgentStrategy:()=>be,GeminiAgentStrategy:()=>Ie,getAgentStrategy:()=>wo,invokeAgent:()=>Ps});function wo(i={}){let{state:e={},preferredAgent:t=null}=i,o=t||e.agentType||process.env.AGENT_TYPE;if(!o)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");u.debug(`Agent selection: requested=${o}`);let s=_o.find(r=>r.getName()===o);if(!s)throw new Error(`Unknown agent '${o}'. Available: ${_o.map(r=>r.getName()).join(", ")}`);if(u.debug(`Checking if ${o} can handle this environment...`),!s.canHandle(i)){let n={assistant:"Run `zibby login` to authenticate",claude:"Set ANTHROPIC_API_KEY in .env",cursor:"Install cursor-agent CLI or set CURSOR_API_KEY",codex:"Install codex CLI (npm i -g @openai/codex) and set OPENAI_API_KEY in .env",gemini:"Install gemini CLI (npm i -g @google/gemini-cli) and set GEMINI_API_KEY in .env"}[o]||"Check your environment configuration";throw new Error(`Agent '${o}' is not available. ${n}`)}return u.debug(`Using agent: ${s.getName()}`),s}async function Ps(i,e={},t={}){try{await import("@zibby/skills")}catch{}let o=wo(e),s=e.state?.config||t.config||{},r=s.models||{},n=t.nodeName&&r[t.nodeName]||null,a=r.default||null,l=o.name,c=s.agent?.[l]?.model||null,f=n||a||c||t.model||null,p={...t,model:f,workspace:e.state?.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:s},d=p.skills||[];if(d.length>0&&!t.skipPromptFragments){let{getSkill:y}=await Promise.resolve().then(()=>(Q(),it)),N=d.map(S=>{let b=y(S)?.promptFragment;return typeof b=="function"?b():b}).filter(Boolean);N.length>0&&(i+=`
|
|
105
112
|
|
|
106
|
-
${
|
|
113
|
+
${N.join(`
|
|
107
114
|
|
|
108
115
|
`)}`)}let _=e.state?._currentNodeConfig?.extraPromptInstructions?.trim();return _&&(i+=`
|
|
109
116
|
|
|
@@ -115,17 +122,17 @@ ${_}
|
|
|
115
122
|
`),u.debug(`Prompt length: ${i.length} chars`),process.env.STAGE!=="prod"&&u.debug(`Full prompt:
|
|
116
123
|
${i}`),o.invoke(i,p)}var _o,ht=R(()=>{qt();Vt();Qt();ro();So();H();ee();_o=[new ve,new be,new $e,new xe,new Ie]});var bo={};Pe(bo,{ConditionalNode:()=>Ce,Node:()=>re});import{writeFileSync as yt,readFileSync as Eo,existsSync as Oo,mkdirSync as Rs}from"node:fs";import{join as St,dirname as Ms}from"node:path";import Ye from"chalk";var re,Ce,_t=R(()=>{Ct();H();ae();he();re=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new De(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){let o=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=p=>t&&typeof t.get=="function"?t.get(p):e?.[p];if(typeof this.customExecute=="function"){u.info("\u26A1 Using custom execute method (skipping LLM)");try{let p=await this.customExecute(e);return typeof p=="object"&&p!==null&&p.success===!1?{success:!1,error:p.error||"Node execution failed",raw:p.raw||null}:this.isZodSchema?(u.debug("Validating return value against outputSchema..."),{success:!0,output:this.outputSchema.parse(p),raw:null}):{success:!0,output:p,raw:null}}catch(p){return u.error(`\u274C Node '${this.name}' execution failed: ${p.message}`),p.name==="ZodError"&&u.error(`Schema validation errors: ${JSON.stringify(p.errors,null,2)}`),{success:!1,error:p.message,raw:null}}}let r=typeof this.prompt=="function"?this.prompt(o()):this.prompt,n=s("_skillHints");n&&(r=`${n}
|
|
117
124
|
|
|
118
|
-
${r}`);let a=o(),l=a.cwd||process.cwd(),c=a.sessionPath;try{if(c){let p=St(c,W);if(Oo(p)){let _=JSON.parse(Eo(p,"utf-8"));_.currentNode=this.name,yt(p,JSON.stringify(_,null,2),"utf-8")}let d=St(c,"..",W);if(Oo(d))try{let _=JSON.parse(Eo(d,"utf-8"));_.currentNode=this.name,yt(d,JSON.stringify(_,null,2),"utf-8")}catch{}}}catch(p){u.debug(`Could not update session info: ${p.message}`)}let f=null;for(let p=0;p<=this.retries;p++)try{u.debug(`Node.execute attempt ${p} for '${this.name}'`);let d=o(),_=d.config||{},
|
|
125
|
+
${r}`);let a=o(),l=a.cwd||process.cwd(),c=a.sessionPath;try{if(c){let p=St(c,W);if(Oo(p)){let _=JSON.parse(Eo(p,"utf-8"));_.currentNode=this.name,yt(p,JSON.stringify(_,null,2),"utf-8")}let d=St(c,"..",W);if(Oo(d))try{let _=JSON.parse(Eo(d,"utf-8"));_.currentNode=this.name,yt(d,JSON.stringify(_,null,2),"utf-8")}catch{}}}catch(p){u.debug(`Could not update session info: ${p.message}`)}let f=null;for(let p=0;p<=this.retries;p++)try{u.debug(`Node.execute attempt ${p} for '${this.name}'`);let d=o(),_=d.config||{},y={state:d},N={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:c,config:_,nodeName:this.name,timeout:this.config?.timeout||3e5},S=e?._coreInvokeAgent;S||(S=(await Promise.resolve().then(()=>(ht(),gt))).invokeAgent);let b=await S(r,y,N),g,O;if(typeof b=="string"?(g=b,O=null):b.structured?(g=b.raw||JSON.stringify(b.structured,null,2),O=b.structured):(g=b.raw||JSON.stringify(b,null,2),O=b.extracted||null),c)try{let E=St(c,this.name,"raw_stream_output.txt");Rs(Ms(E),{recursive:!0}),yt(E,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(E){u.debug(`Could not save raw output: ${E.message}`)}if(this.isZodSchema&&O){console.log(`
|
|
119
126
|
\u{1F50D} ${Ye.cyan("Validated output:")} ${Ye.white(JSON.stringify(O,null,2))}`);let E=O;if(typeof this.onComplete=="function")try{E=await this.onComplete(o(),O)}catch($){u.warn(`onComplete hook failed: ${$.message}`)}return{success:!0,output:E,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:g}),raw:g}}catch(E){throw new Error(`onComplete failed: ${E.message}`,{cause:E})}if(this.parser){let E=this.parser.parse(g);return console.log(`
|
|
120
|
-
\u{1F50D} ${Ye.cyan("Parsed output:")} ${Ye.white(JSON.stringify(E,null,2))}`),L.step("Output parsed"),{success:!0,output:E,raw:g}}return{success:!0,output:g,raw:g}}catch(d){f=d,p<this.retries&&u.info(`Node '${this.name}' failed, retrying (${p+1}/${this.retries})...`)}return{success:!1,error:f.message,raw:null}}},Ce=class extends re{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,t){let o=t&&typeof t.getAll=="function"?t.getAll():e;return{success:!0,output:{nextNode:this.condition(o)},raw:null}}}});import{spawn as Ws}from"node:child_process";import{mkdirSync as
|
|
127
|
+
\u{1F50D} ${Ye.cyan("Parsed output:")} ${Ye.white(JSON.stringify(E,null,2))}`),L.step("Output parsed"),{success:!0,output:E,raw:g}}return{success:!0,output:g,raw:g}}catch(d){f=d,p<this.retries&&u.info(`Node '${this.name}' failed, retrying (${p+1}/${this.retries})...`)}return{success:!1,error:f.message,raw:null}}},Ce=class extends re{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,t){let o=t&&typeof t.getAll=="function"?t.getAll():e;return{success:!0,output:{nextNode:this.condition(o)},raw:null}}}});import{spawn as Ws}from"node:child_process";import{mkdirSync as To,existsSync as zs,writeFileSync as Hs}from"node:fs";import{join as Et}from"node:path";import{existsSync as $t,readFileSync as Co}from"node:fs";import{join as He,dirname as xt}from"node:path";var ie=class{static async loadContext(e,t,o={}){let s={},r=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=xt(He(t,e));for(let l of r){let c=await this.findAndMergeContextFiles(l,a,t);if(c){let f=l.replace(/\.[^.]+$/,"").toLowerCase();s[f]=c}}}let n=o.discovery||{};for(let[a,l]of Object.entries(n))try{let c=He(t,l);if($t(c)){let f=await this.loadFile(c);s[a]=f}}catch(c){console.warn(`\u26A0\uFE0F Could not load context '${a}' from '${l}': ${c.message}`)}return s}static async findAndMergeContextFiles(e,t,o){let s=[],r=t;for(;r.startsWith(o);){let n=He(r,e);if($t(n))try{let l=await this.loadFile(n);s.unshift(l)}catch(l){console.warn(`\u26A0\uFE0F Could not load ${e} from ${n}: ${l.message}`)}let a=xt(r);if(a===r)break;r=a}return s.length===0?null:s.every(n=>typeof n=="string")?s.join(`
|
|
121
128
|
|
|
122
129
|
---
|
|
123
130
|
|
|
124
|
-
`):s.every(n=>typeof n=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=Co(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),s=await import(o(e).href);return s.default||s}return t}};Re();import{exec as ko}from"node:child_process";import{promisify as No}from"node:util";import{existsSync as Po}from"node:fs";import{join as Ze}from"node:path";import{homedir as Xe}from"node:os";var It=No(ko);async function
|
|
131
|
+
`):s.every(n=>typeof n=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=Co(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),s=await import(o(e).href);return s.default||s}return t}};Re();import{exec as ko}from"node:child_process";import{promisify as No}from"node:util";import{existsSync as Po}from"node:fs";import{join as Ze}from"node:path";import{homedir as Xe}from"node:os";var It=No(ko);async function At(){try{return await It("cursor-agent --version"),"cursor-agent"}catch{let e=[Ze(Xe(),".local","bin","cursor-agent"),Ze(Xe(),".cursor","bin","cursor-agent"),Ze(Xe(),".cursor-agent","bin","cursor-agent")];for(let t of e)if(Po(t))try{return await It(`"${t}" --version`),t}catch{}return null}}he();Ve();_t();he();ae();import{mkdirSync as Io,existsSync as wt,writeFileSync as $o,unlinkSync as Ls}from"node:fs";import{join as ne,resolve as Ao}from"node:path";import{config as Ds}from"dotenv";import{zodToJsonSchema as xo}from"zod-to-json-schema";import Bs from"handlebars";function Us({traceFrom:i,sessionId:e,sessionPath:t,idSource:o,mkdirFresh:s}){if(process.env.ZIBBY_SESSION_LOG==="0"||process.env.ZIBBY_SESSION_LOG==="false")return;let r=typeof process.ppid=="number"?process.ppid:"n/a",n=`[zibby:session] from=${i} pid=${process.pid} ppid=${r} sessionId=${e} source=${o} mkdir=${s?"yes":"no"} path=${t}`;if(console.log(n),(process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true")&&process.env.ZIBBY_SESSION_LOG!=="0"&&process.env.ZIBBY_SESSION_LOG!=="false"){let c=(new Error("session trace").stack||"").split(`
|
|
125
132
|
`).slice(2,14).join(`
|
|
126
133
|
`);console.log(`[zibby:session] stack (${i}):
|
|
127
|
-
${c}`)}}function js(){return process.env.ZIBBY_RUN_SOURCE==="studio"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function Fs(){if(process.env.ZIBBY_RUN_SOURCE!=="studio")return;let i=process.env.ZIBBY_SESSION_PATH;if(!(i==null||String(i).trim()===""))try{return
|
|
128
|
-
\u{1F6D1} Studio stop requested \u2014 ending workflow.`);try{Ls($)}catch{}if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch{}return L.step("Workflow stopped by Studio"),{success:!0,state:
|
|
134
|
+
${c}`)}}function js(){return process.env.ZIBBY_RUN_SOURCE==="studio"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function Fs(){if(process.env.ZIBBY_RUN_SOURCE!=="studio")return;let i=process.env.ZIBBY_SESSION_PATH;if(!(i==null||String(i).trim()===""))try{return Ao(String(i).trim())}catch{return String(i).trim()}}function Js(){js()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Gs({sessionPath:i,sessionId:e}){i&&typeof i=="string"&&(process.env.ZIBBY_SESSION_PATH=i),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Ks(i={}){let e=Tt.map(r=>process.env[r]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,s=i.paths?.sessionPrefix;return s?`${s}_${o}`:o}function Ys({cwd:i=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let s=t.sessionPath,r=t.sessionTimestamp,n="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let c=Ao(String(process.env.ZIBBY_SESSION_PATH));c&&(s=c,n="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),r==null&&(r=Date.now());else{let c=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(c)a=c,n="ZIBBY_SESSION_ID";else{let p=e.sessionId!=null?String(e.sessionId).trim():"";p&&p!=="last"?(a=p,n="config.sessionId"):(a=Ks(e),n="generated")}r=r??Date.now();let f=e.paths?.output||q;s=ne(i,f,Me,a)}let l=!wt(s);return l&&Io(s,{recursive:!0}),Us({traceFrom:o,sessionId:a,sessionPath:s,idSource:n,mkdirFresh:l}),Gs({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:r}}var We=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null}setStateSchema(e){return this.stateSchema=e,this}getStateSchema(){return this.stateSchema}addNode(e,t,o={}){let s=t instanceof re?t:new re(t);return s.name=e,this.nodes.set(e,s),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}addConditionalNode(e,t){let o=new Ce({...t,name:e});return this.nodes.set(e,o),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:o}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:o}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,o,s,r){let n=o;for(let a=e.length-1;a>=0;a--){let l=e[a],c=n;n=()=>l(t,c,s,r)}return n()}serialize(){let e=[],t={};for(let[r,n]of this.nodes){let a=this.nodeTypeMap.get(r)||r;e.push({id:r,type:a,data:{nodeType:a,label:r}});let l=n._isCustomCode||!1,c={};l&&typeof n.execute=="function"&&(c.customCode=n.execute.toString());let f=this.nodePrompts.get(r);if(f&&(c.prompt=f),typeof n.customExecute=="function"&&(c.executeCode=n.customExecute.toString()),n.outputSchema)try{if(typeof n.outputSchema._def<"u"){let _=xo(n.outputSchema,{target:"openApi3"}),y=this._flattenJsonSchemaToVariables(_);c.outputSchema={jsonSchema:_,variables:y}}else c.outputSchema={schema:n.outputSchema}}catch(d){console.warn(`Failed to convert schema for ${r}:`,d.message)}let p=(this.resolvedToolsMap||{})[r];p?.toolIds&&(c.tools=p.toolIds),Object.keys(c).length>0&&(t[r]=c)}let o=[];for(let[r,n]of this.edges)if(typeof n=="string")o.push({source:r,target:n});else if(n.conditional){let a=this.conditionalCodeMap.get(r)||n.routes.toString(),l=this._inferConditionalTargets(n.routes),c=n.labels||{};for(let f of l){let p={source:r,target:f,data:{conditionalCode:a}};c[f]&&(p.label=c[f]),o.push(p)}}let s=null;if(this.stateSchema)try{s=xo(this.stateSchema,{target:"openApi3"})}catch{s=this.stateSchema}return{nodes:e,edges:o,nodeConfigs:t,stateSchema:s}}_inferConditionalTargets(e){let t=e.toString(),o=new Set,s=/return\s+['"]([^'"]+)['"]/g,r;for(;(r=s.exec(t))!==null;)o.add(r[1]);return[...o]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");o=e.definitions[s]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],s=e.properties||{},r=e.required||[];for(let[n,a]of Object.entries(s)){let l=t?`${t}.${n}`:n,c=!r.includes(n);if(o.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(n),optional:c}),a.type==="object"&&a.properties){let f=this._flattenSchema(a,l);o.push(...f)}if(a.type==="array"&&a.items?.type==="object"&&a.items.properties){let f=this._flattenSchema(a.items,`${l}[]`);o.push(...f)}}return o}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let o=[];t.success!==void 0&&o.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,r]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof r=="string"&&r.length<=80)o.push(`${s}: ${r}`);else if(Array.isArray(r)){let n=r.length,a=r.filter(c=>c?.passed===!0).length;if(r.some(c=>c?.passed!==void 0)){let c=n-a;o.push(`${s}: ${a}/${n} passed${c?`, ${c} failed`:""}`)}else o.push(`${s}: ${n} items`)}if(o.length>=4)break}return o}async run(e,t={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let o=t.cwd||process.cwd();Ds({path:ne(o,".env")});let s=t.config||{};if(!s||Object.keys(s).length===0)try{let $=ne(o,".zibby.config.js");wt($)&&(s=(await import($)).default||{})}catch{}process.env.EXECUTION_ID&&!s.agent?.strictMode&&(s.agent={...s.agent,strictMode:!0});let r=t.agentType;if(!r){let $=s?.agent;$?.provider?r=$.provider:$?.gemini?r="gemini":$?.claude?r="claude":$?.cursor?r="cursor":$?.codex?r="codex":r=process.env.AGENT_TYPE||"cursor"}let n=t.contextConfig||e?.config?.contextConfig||e?.config?.context||s?.context||{};if(this.stateSchema){let $=this.stateSchema.safeParse(t);if(!$.success){let x=$.error.issues.map(w=>`${w.path.join(".")}: ${w.message}`);throw console.error("\u274C Initial state validation failed:"),x.forEach(w=>console.error(` - ${w}`)),new Error(`State validation failed: ${x.join(", ")}`)}L.step("State validated against schema")}let a=Fs(),l=t.sessionPath||a;l||Js();let{sessionPath:c,sessionTimestamp:f,sessionId:p}=Ys({cwd:o,config:s,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:t.sessionTimestamp}});L.step(`Session ${p}`);let d=await ie.loadContext(t.specPath||"",o,n);Object.keys(d).length>0&&L.step(`Context loaded: ${Object.keys(d).join(", ")}`);let _=t.outputPath;!_&&t.specPath&&(e?.calculateOutputPath?_=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let y=new ye({...t,config:s,agentType:r,outputPath:_,sessionPath:c,sessionTimestamp:f,context:d,resolvedTools:this.resolvedToolsMap||{}}),N=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:S}=await Promise.resolve().then(()=>(Q(),it)),b=new Set;for(let[,$]of this.nodes)for(let x of $.config?.skills||[])b.add(x);for(let $ of b){let x=S($);if(typeof x?.middleware=="function")try{let w=await x.middleware();typeof w=="function"&&N.set($,w)}catch{}}let g=this.entryPoint,O=[];for(;g&&g!=="END";){let $=ne(c,Le);if(wt($)){console.warn(`
|
|
135
|
+
\u{1F6D1} Studio stop requested \u2014 ending workflow.`);try{Ls($)}catch{}if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch{}return L.step("Workflow stopped by Studio"),{success:!0,state:y.getAll(),executionLog:O,stoppedByStudio:!0}}let x=this.nodes.get(g);if(!x)throw new Error(`Node '${g}' not found in graph`);let w=JSON.stringify({sessionPath:c,sessionTimestamp:f,currentNode:g,createdAt:new Date().toISOString(),config:y.get("config")}),C=ne(c,W);$o(C,w,"utf-8");let T=y.get("config")?.paths?.output||q,I=ne(o,T,W);Io(ne(o,T),{recursive:!0});try{$o(I,w,"utf-8")}catch{}let h=t.onPipelineProgress;if(typeof h=="function")try{h({cwd:o,sessionPath:c,sessionId:p,outputBase:y.get("config")?.paths?.output||q,currentNode:g})}catch{}let A=(this.resolvedToolsMap||{})[g]||null;y.set("_currentNodeTools",A);let k=y.get("nodeConfigs")||{};y.set("_currentNodeConfig",k[g]||{}),L.nodeStart(g);let m=Date.now(),v=this.nodePrompts.get(g);if(!this._invokeAgent){let M=await Promise.resolve().then(()=>(ht(),gt));this._invokeAgent=M.invokeAgent}let P=this._invokeAgent,G={state:y,invokeAgent:async(M={},K={})=>{let B=K.prompt||"";if(v)try{B=Bs.compile(v,{noEscape:!0})(M)}catch(Z){throw console.error(`\u274C Template rendering failed for node '${g}':`,Z.message),new Error(`Template rendering failed: ${Z.message}`,{cause:Z})}else if(!B)throw new Error(`No prompt template configured for node '${g}' and no prompt provided in options`);let me={state:y.getAll(),images:K.images||[]},ze={model:K.model||y.get("model"),workspace:y.get("workspace"),schema:K.schema,...K};return P(B,me,ze)},_coreInvokeAgent:P,agent:e,nodeId:g,promptTemplate:v,getPromptTemplate:()=>v,...y.getAll()};try{let M=(x.config?.skills||[]).map(ke=>N.get(ke)).filter(Boolean),K=[...this.middleware,...M],B;K.length>0?B=await this._composeMiddleware(K,g,async()=>x.execute(G,y),y.getAll(),y):B=await x.execute(G,y);let me=Date.now()-m;if(O.push({node:g,success:B.success,duration:me,timestamp:new Date().toISOString()}),!B.success){if(String(B.error||"").includes("Stopped from Zibby Studio")){if(L.step("Workflow stopped by Studio"),y.set("stoppedByStudio",!0),e&&typeof e.cleanup=="function")try{await e.cleanup()}catch{}return{success:!0,state:y.getAll(),executionLog:O,stoppedByStudio:!0}}y.append("errors",{node:g,error:B.error});let ge=x.config?.retries||0,bt=`${g}_retries`,Ne=y.getAll()[bt]||0;if(Ne<ge){L.stepInfo(`Retrying (attempt ${Ne+1}/${ge})`),y.update({[bt]:Ne+1,[`${g}_raw`]:B.raw});continue}throw L.nodeFailed(g,B.error,{duration:me}),new Error(`Node '${g}' failed after ${Ne} attempts: ${B.error}`)}y.update({[g]:B.output});let ze=this._summarizeNodeOutput(g,B.output);L.nodeComplete(g,{duration:me,details:ze});let Z=this.edges.get(g);if(!Z)g="END";else if(Z.conditional){let ke=y.getAll(),ge=Z.routes(ke);L.route(g,ge),g=ge}else g=Z}catch(M){throw L.isInsideNode&&L.nodeFailed(g,M.message,{duration:Date.now()-m}),y.set("failed",!0),y.set("failedAt",g),M}}L.graphComplete();let E={success:!0,state:y.getAll(),executionLog:O};return e&&typeof e.onComplete=="function"&&await e.onComplete(E),E}};var Ot=class i{constructor(e={}){this.config=e,this.adapter=null,this.paths=e.paths||{specs:"test-specs",generated:"tests"},this.agentCommand=e.agentCommand||"cursor-agent",this.buildArgs=e.buildArgs||((t,o=!0)=>{let s=["-p",t,"--approve-mcps","--force"];return o&&(s.push("--output-format","stream-json"),s.push("--stream-partial-output")),s})}static extractJsonFromStream(e){return X.extractResult(e)}async initialize(e){this.adapter=e,e&&!e.isConnected()&&await e.connect()}buildGraph(){throw new Error("buildGraph() must be implemented by subclass")}async onComplete(e){}async run(e,t={}){let o=this.buildGraph(),s=typeof e=="object"&&!Array.isArray(e)?{input:e,...e,...t}:{input:e,...t};return await o.run(this,s)}async executeNode(e,t){let{prompt:o,outputSchema:s,model:r}=e,n=typeof o=="function"?o(t):o;console.log(`
|
|
129
136
|
\u{1F4DD} Prompt:
|
|
130
137
|
${n}
|
|
131
138
|
`);let a=await this.executePrompt(n,t.cwd,3e5,r);console.log(`
|
|
@@ -134,11 +141,11 @@ ${a}
|
|
|
134
141
|
`);let l=null;if(s)try{if(l=i.extractJsonFromStream(a),!l)throw new Error("No valid result JSON found in output");console.log(`
|
|
135
142
|
\u2705 Parsed Output:
|
|
136
143
|
${JSON.stringify(l,null,2)}
|
|
137
|
-
`)}catch(c){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${c.message}`)}return{success:!0,output:l,raw:a}}async cleanup(){this.adapter&&this.adapter.isConnected()&&await this.adapter.disconnect()}async executePrompt(e,t=process.cwd(),o=3e5,s=null,r=!0){let n=this.agentCommand;if(n==="cursor-agent"){let a=await
|
|
138
|
-
\u23F1\uFE0F Timeout reached (${o/1e3}s) - killing agent...`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||(console.log("\u26A0\uFE0F Forcing kill (SIGKILL)..."),d.kill("SIGKILL"))},2e3),l(new Error(`Agent timed out after ${o/1e3}s. The agent may be stuck or waiting for user input.`))},o),
|
|
144
|
+
`)}catch(c){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${c.message}`)}return{success:!0,output:l,raw:a}}async cleanup(){this.adapter&&this.adapter.isConnected()&&await this.adapter.disconnect()}async executePrompt(e,t=process.cwd(),o=3e5,s=null,r=!0){let n=this.agentCommand;if(n==="cursor-agent"){let a=await At();a&&(n=a)}return new Promise((a,l)=>{let c="",f=this.buildArgs(e,r);s&&f.push("--model",s);let p={...process.env},d=Ws(n,f,{cwd:t,env:p,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),_=setTimeout(()=>{console.log(`
|
|
145
|
+
\u23F1\uFE0F Timeout reached (${o/1e3}s) - killing agent...`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||(console.log("\u26A0\uFE0F Forcing kill (SIGKILL)..."),d.kill("SIGKILL"))},2e3),l(new Error(`Agent timed out after ${o/1e3}s. The agent may be stuck or waiting for user input.`))},o),y=0,N=Date.now(),S=setInterval(()=>{if(c.length>y)y=c.length,N=Date.now();else{let E=Date.now()-N;E>1e4&&console.log(`\u23F3 AI agent is thinking... (${Math.floor(E/1e3)}s, ${c.length} bytes so far)`)}},1e4),b=()=>{clearTimeout(_),clearInterval(S),d&&!d.killed&&(d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},2e3))},g=()=>{console.log(`
|
|
139
146
|
|
|
140
|
-
\u{1F6D1} Interrupted by user (Ctrl+C)`),b(),l(new Error("Interrupted by user"))};process.on("SIGINT",g);let O=new X;d.stdout.on("data",E=>{let $=E.toString();c+=$;let x=O.processChunk($);x&&(process.stdout.write(x,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),
|
|
147
|
+
\u{1F6D1} Interrupted by user (Ctrl+C)`),b(),l(new Error("Interrupted by user"))};process.on("SIGINT",g);let O=new X;d.stdout.on("data",E=>{let $=E.toString();c+=$;let x=O.processChunk($);x&&(process.stdout.write(x,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),N=Date.now(),y+=x.length)}),d.on("close",E=>{process.off("SIGINT",g),clearTimeout(_),clearInterval(S);let $=O.flush();$&&process.stdout.write($),c=O.getRawText();let x=O.getResult();E===0?a({raw:c,extracted:x}):l(new Error(`Agent exited with code ${E}`))}),d.on("error",E=>{process.off("SIGINT",g),clearTimeout(_),clearInterval(S),l(new Error(`Failed to spawn agent: ${E.message}`))})})}async runSingleNode(e,t,o){let s=t[e];if(!s)throw new Error(`Unknown node: ${e}. Available nodes: ${Object.keys(t).join(", ")}`);let{cwd:r}=o;if(!r)throw new Error("cwd is required for single node execution");let n=o.sessionPath,a=o.sessionTimestamp,l=o.config||{};if(!n){let g=process.env.CI_JOB_ID||process.env.GITHUB_RUN_ID||process.env.CIRCLE_WORKFLOW_ID||process.env.BUILD_ID||Date.now().toString(),O=l.paths?.sessionPrefix,E=O?`${O}_${g}`:g;a=a||Date.now();let $=l.paths?.output||q;n=Et(r,$,Me,E),zs(n)||To(n,{recursive:!0})}let c=l.paths?.output||q,f=Et(r,c,W);To(Et(r,c),{recursive:!0}),Hs(f,JSON.stringify({sessionPath:n,sessionTimestamp:a||n.split("/").pop(),currentNode:e,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
|
|
141
148
|
${"=".repeat(80)}`),console.log(`\u{1F3AF} SINGLE NODE EXECUTION: ${e}`),console.log(`\u{1F4C1} Session: ${n.split("/").pop()}${o.sessionPath?" (reusing)":""}`),console.log(`${"=".repeat(80)}
|
|
142
|
-
`);let p=await ie.loadContext(o.specPath||"",r,o.contextConfig||{}),{Node:d}=await Promise.resolve().then(()=>(_t(),bo)),{WorkflowState:_}=await Promise.resolve().then(()=>(Ve(),vt)),
|
|
149
|
+
`);let p=await ie.loadContext(o.specPath||"",r,o.contextConfig||{}),{Node:d}=await Promise.resolve().then(()=>(_t(),bo)),{WorkflowState:_}=await Promise.resolve().then(()=>(Ve(),vt)),y=new _({...o,sessionPath:n,sessionTimestamp:a,context:p}),S=await new d(s).execute(this,y);return console.log(`
|
|
143
150
|
${"=".repeat(80)}`),console.log(`\u2705 Node ${e} completed`),console.log(`${"=".repeat(80)}
|
|
144
|
-
`),{success:!0,output:S.output,outputPath:o.outputPath,state:S}}calculateOutputPath(e){let{specs:t,generated:o}=this.paths;if(!e)return`${o}/generated-test.spec.js`;let s=e.replace(new RegExp(`^${t}/`),"").replace(/\.[^.]+$/,".spec.js");return`${o}/${s}`.replace(/\/+/g,"/")}};function
|
|
151
|
+
`),{success:!0,output:S.output,outputPath:o.outputPath,state:S}}calculateOutputPath(e){let{specs:t,generated:o}=this.paths;if(!e)return`${o}/generated-test.spec.js`;let s=e.replace(new RegExp(`^${t}/`),"").replace(/\.[^.]+$/,".spec.js");return`${o}/${s}`.replace(/\/+/g,"/")}};function Ti(i,e={}){let t=new Ot(e);return t.buildGraph=function(){let o=new We;return i(o),o},e.onComplete&&(t.onComplete=e.onComplete),t}export{Ot as WorkflowAgent,Ti as workflow};
|