@zibby/core 0.2.0 → 0.3.0

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.
@@ -1,7 +1,7 @@
1
- import{AgentStrategy as Nt,DEFAULT_OUTPUT_BASE as kt,SESSION_INFO_FILE as Lt,STUDIO_STOP_REQUEST_FILE as Mt,getAllSkills as Ut,getSkill as ut}from"@zibby/agent-workflow";import{spawn as Dt,execSync as F}from"node:child_process";import{writeFileSync as ct,readFileSync as pt,mkdirSync as ft,existsSync as H,accessSync as dt,constants as gt,unlinkSync as Bt}from"node:fs";import{join as v,resolve as Ft}from"node:path";import{homedir as Y}from"node:os";import G from"chalk";var N={debug:0,info:1,warn:2,error:3,silent:4},et=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return N.debug;if(process.env.ZIBBY_VERBOSE==="true")return N.info;let t=process.env.LOG_LEVEL?.toLowerCase();return t&&t in N?N[t]:N.info}_shouldLog(t){return N[t]>=this._level}_formatMessage(t,e,r={}){let s=new Date().toISOString(),n=`${this._getPrefix(t)} ${e}`;return Object.keys(r).length>0&&(n+=G.dim(` ${JSON.stringify(r)}`)),n}_getPrefix(t){return{debug:G.gray("[DEBUG]"),info:G.cyan("[INFO]"),warn:G.yellow("[WARN]"),error:G.red("\u274C [ERROR]")}[t]||""}debug(t,e){this._shouldLog("debug")&&console.log(this._formatMessage("debug",t,e))}info(t,e){this._shouldLog("info")&&console.log(this._formatMessage("info",t,e))}warn(t,e){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",t,e))}error(t,e){this._shouldLog("error")&&console.error(this._formatMessage("error",t,e))}setLevel(t){t in N&&(this._level=N[t])}getLevel(){return Object.keys(N).find(t=>N[t]===this._level)}},o=new et;var z={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"};var W={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var Z=class i{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(t){if(!t)return null;this.buffer+=t;let e=this.buffer.split(`
1
+ import{AgentStrategy as Nt,DEFAULT_OUTPUT_BASE as kt,SESSION_INFO_FILE as Lt,STOP_REQUEST_FILE as Mt,getAllSkills as Ut,getSkill as ut}from"@zibby/agent-workflow";import{spawn as Dt,execSync as F}from"node:child_process";import{writeFileSync as ct,readFileSync as pt,mkdirSync as ft,existsSync as H,accessSync as dt,constants as gt,unlinkSync as Bt}from"node:fs";import{join as v,resolve as Ft}from"node:path";import{homedir as Y}from"node:os";import G from"chalk";var N={debug:0,info:1,warn:2,error:3,silent:4},et=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return N.debug;if(process.env.ZIBBY_VERBOSE==="true")return N.info;let t=process.env.LOG_LEVEL?.toLowerCase();return t&&t in N?N[t]:N.info}_shouldLog(t){return N[t]>=this._level}_formatMessage(t,e,r={}){let s=new Date().toISOString(),n=`${this._getPrefix(t)} ${e}`;return Object.keys(r).length>0&&(n+=G.dim(` ${JSON.stringify(r)}`)),n}_getPrefix(t){return{debug:G.gray("[DEBUG]"),info:G.cyan("[INFO]"),warn:G.yellow("[WARN]"),error:G.red("\u274C [ERROR]")}[t]||""}debug(t,e){this._shouldLog("debug")&&console.log(this._formatMessage("debug",t,e))}info(t,e){this._shouldLog("info")&&console.log(this._formatMessage("info",t,e))}warn(t,e){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",t,e))}error(t,e){this._shouldLog("error")&&console.error(this._formatMessage("error",t,e))}setLevel(t){t in N&&(this._level=N[t])}getLevel(){return Object.keys(N).find(t=>N[t]===this._level)}},o=new et;var z={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"};var W={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var Z=class i{constructor(){this.buffer="",this.extractedResult=null,this.rawText="",this.zodSchema=null,this.lastOutputLength=0,this.onToolCall=null,this._lastToolEmit=null}processChunk(t){if(!t)return null;this.buffer+=t;let e=this.buffer.split(`
2
2
  `);this.buffer=e.pop()||"";let r="";for(let s of e)if(s.trim())try{let l=JSON.parse(s);this._emitToolCalls(l);let n=this.extractText(l);if(n){if(this.rawText&&n.startsWith(this.rawText)){let a=n.substring(this.rawText.length);this.rawText=n,r+=a}else(!this.rawText.includes(n)||n.length<20)&&(this.rawText+=n,r+=n);this.tryExtractResult(this.rawText)}else this.isValidResult(l)&&(this.rawText+=`${s}
3
3
  `,r+=`${s}
4
- `,this.extractedResult=l)}catch{if(s.includes('"text"')||s.includes('"content"')){let n=s.match(/"text"\s*:\s*"([^"]*)/),a=s.match(/"content"\s*:\s*"([^"]*)/),u=n?n[1]:a?a[1]:null;u&&!this.rawText.includes(u)&&(r+=u,this.rawText+=u)}}return r||null}flush(){if(!this.buffer.trim())return null;let t="";try{let e=JSON.parse(this.buffer);this._emitToolCalls(e);let r=this.extractText(e);r&&(this.rawText+=r,t+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,t+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",t||null}_emitToolCalls(t){if(!this.onToolCall)return;let e=(n,a)=>{if(!n)return;let u=`${n}:${JSON.stringify(a??{})}`;this._lastToolEmit!==u&&(this._lastToolEmit=u,this.onToolCall(n,a??void 0))},r=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(t.type==="tool_use"||t.type==="tool_call"){if(t.name){e(t.name,r(t.input??t.arguments));return}let n=t.tool_call;if(n&&typeof n=="object"&&!Array.isArray(n)){let a=Object.keys(n);if(a.length===1){let u=a[0],h=n[u],p=h&&typeof h=="object"?h.args??h.input??h:void 0;e(u,r(p))}return}return}if(Array.isArray(t.tool_calls)){for(let n of t.tool_calls)e(n.name,r(n.input??n.arguments));return}let s=t.message??t;if(Array.isArray(s?.tool_calls)){for(let n of s.tool_calls)e(n.name,r(n.input??n.arguments));return}let l=s?.content??t.content;if(Array.isArray(l))for(let n of l)(n.type==="tool_use"||n.type==="tool_call")&&n.name&&e(n.name,r(n.input??n.arguments))}extractText(t){if(t.type==="assistant"&&t.message?.content){let e=t.message.content;if(Array.isArray(e))return e.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return t.type==="thinking"&&t.text||t.text?t.text:t.content&&typeof t.content=="string"?t.content:t.delta?t.delta:null}tryExtractResult(t){if(!t||typeof t!="string")return;let e=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,s;for(;(s=r.exec(t))!==null;){let m=s[1].trim();try{JSON.parse(m),e.push({text:m,source:"markdown"})}catch{}}let l=0,n=0;for(;l<t.length&&(l=t.indexOf("{",l),l!==-1);){let m=0,d=l;for(let y=l;y<t.length;y++)if(t[y]==="{")m++;else if(t[y]==="}"&&(m--,m===0)){d=y,e.push({text:t.substring(l,d+1),source:"brace"}),n++;break}l=d+1}let a=this.extractedResult,u=a?JSON.stringify(a).length:0,h=0,p=-1;for(let m=0;m<e.length;m++){let d=e[m];try{let y=d.text.replace(/,(\s*[}\]])/g,"$1"),w=JSON.parse(y);this.isValidResult(w)&&(h++,u=JSON.stringify(w).length,a=w,p=m)}catch{}}a&&(this.extractedResult=a)}isValidResult(t){if(!t||typeof t!="object"||Array.isArray(t)||t.session_id||t.timestamp_ms||t.type||t.call_id||t.tool_call||t.result&&typeof t.result=="object"&&(t.result.success&&typeof t.result.success=="object"||t.result.error&&typeof t.result.error=="object")||t.args&&typeof t.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(t),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(t,e=null){let r=new i;r.zodSchema=e,r.processChunk(t),r.flush();let s=r.getResult();return!s&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",t?.length||0,"chars"),s}};import{zodToJsonSchema as ht}from"zod-to-json-schema";var X=class{static generateFileOutputInstructions(t,e){let r;typeof t?.parse=="function"?r=ht(t,{target:"openApi3"}):r=t;let s=this._buildExample(r);return`
4
+ `,this.extractedResult=l)}catch{if(s.includes('"text"')||s.includes('"content"')){let n=s.match(/"text"\s*:\s*"([^"]*)/),a=s.match(/"content"\s*:\s*"([^"]*)/),u=n?n[1]:a?a[1]:null;u&&!this.rawText.includes(u)&&(r+=u,this.rawText+=u)}}return r||null}flush(){if(!this.buffer.trim())return null;let t="";try{let e=JSON.parse(this.buffer);this._emitToolCalls(e);let r=this.extractText(e);r&&(this.rawText+=r,t+=r,this.tryExtractResult(r))}catch{this.rawText+=this.buffer,t+=this.buffer,this.tryExtractResult(this.buffer)}return this.buffer="",t||null}_emitToolCalls(t){if(!this.onToolCall)return;let e=(n,a)=>{if(!n)return;let u=`${n}:${JSON.stringify(a??{})}`;this._lastToolEmit!==u&&(this._lastToolEmit=u,this.onToolCall(n,a??void 0))},r=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(t.type==="tool_use"||t.type==="tool_call"){if(t.name){e(t.name,r(t.input??t.arguments));return}let n=t.tool_call;if(n&&typeof n=="object"&&!Array.isArray(n)){let a=Object.keys(n);if(a.length===1){let u=a[0],h=n[u],p=h&&typeof h=="object"?h.args??h.input??h:void 0;e(u,r(p))}return}return}if(Array.isArray(t.tool_calls)){for(let n of t.tool_calls)e(n.name,r(n.input??n.arguments));return}let s=t.message??t;if(Array.isArray(s?.tool_calls)){for(let n of s.tool_calls)e(n.name,r(n.input??n.arguments));return}let l=s?.content??t.content;if(Array.isArray(l))for(let n of l)(n.type==="tool_use"||n.type==="tool_call")&&n.name&&e(n.name,r(n.input??n.arguments))}extractText(t){if(t.type==="assistant"&&t.message?.content){let e=t.message.content;if(Array.isArray(e))return e.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join("")}return t.type==="thinking"&&t.text||t.text?t.text:t.content&&typeof t.content=="string"?t.content:t.delta?t.delta:null}tryExtractResult(t){if(!t||typeof t!="string")return;let e=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,s;for(;(s=r.exec(t))!==null;){let m=s[1].trim();try{JSON.parse(m),e.push({text:m,source:"markdown"})}catch{}}let l=0,n=0;for(;l<t.length&&(l=t.indexOf("{",l),l!==-1);){let m=0,d=l;for(let y=l;y<t.length;y++)if(t[y]==="{")m++;else if(t[y]==="}"&&(m--,m===0)){d=y,e.push({text:t.substring(l,d+1),source:"brace"}),n++;break}l=d+1}let a=this.extractedResult,u=a?JSON.stringify(a).length:0,h=0,p=-1;for(let m=0;m<e.length;m++){let d=e[m];try{let y=d.text.replace(/,(\s*[}\]])/g,"$1"),T=JSON.parse(y);this.isValidResult(T)&&(h++,u=JSON.stringify(T).length,a=T,p=m)}catch{}}a&&(this.extractedResult=a)}isValidResult(t){if(!t||typeof t!="object"||Array.isArray(t)||t.session_id||t.timestamp_ms||t.type||t.call_id||t.tool_call||t.result&&typeof t.result=="object"&&(t.result.success&&typeof t.result.success=="object"||t.result.error&&typeof t.result.error=="object")||t.args&&typeof t.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(t),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(t,e=null){let r=new i;r.zodSchema=e,r.processChunk(t),r.flush();let s=r.getResult();return!s&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",t?.length||0,"chars"),s}};import{zodToJsonSchema as ht}from"zod-to-json-schema";var X=class{static generateFileOutputInstructions(t,e){let r;typeof t?.parse=="function"?r=ht(t,{target:"openApi3"}):r=t;let s=this._buildExample(r);return`
5
5
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
6
6
  \u{1F6A8} MANDATORY: WRITE RESULT TO FILE \u{1F6A8}
7
7
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
@@ -39,7 +39,7 @@ ${a}
39
39
 
40
40
  Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,h={model:z.OPENAI_POSTPROCESSING,messages:[{role:"user",content:u}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:l,strict:!0}}};o.info(`\u{1F4E4} Sending to OpenAI proxy: model=${z.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(l.properties||{}).join(", ")}`),o.debug(` Schema size: ${JSON.stringify(l).length} chars`),o.debug(` Prompt size: ${u.length} chars`);try{let p={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(p["x-proxy-token"]=e,p["x-execution-id"]=process.env.EXECUTION_ID||""):(p.Authorization=`Bearer ${e}`,p["x-api-key"]=process.env.ZIBBY_API_KEY||"",p["x-execution-id"]=process.env.EXECUTION_ID||"");let d=(await yt.post(r,h,{headers:p,timeout:W.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!d)throw new Error("OpenAI proxy returned empty response");let y=JSON.parse(d);return o.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:y,raw:i}}catch(p){if(p.response){let m=p.response.status,d=p.response.data;throw o.error(`\u274C OpenAI proxy request failed: ${m}`),o.error(` Status: ${m}`),o.error(` Response: ${JSON.stringify(d,null,2)}`),m===401||m===403?new Error(`Authentication failed for OpenAI proxy.
41
41
  Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
42
- Response: ${JSON.stringify(d)}`,{cause:p}):new Error(`Failed to format Cursor output: ${d?.error?.message||"Unknown error"}`,{cause:p})}throw o.error(`\u274C OpenAI proxy request failed: ${p.message}`),new Error(`Failed to format output: ${p.message}`,{cause:p})}}import{timeline as rt,Timeline as se,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as ie}from"@zibby/agent-workflow";import{copyFileSync as Tt,existsSync as nt,lstatSync as xt,mkdirSync as st,rmSync as wt,symlinkSync as $t,unlinkSync as vt}from"node:fs";import{join as L}from"node:path";import{homedir as Rt}from"node:os";import{randomBytes as Pt}from"node:crypto";var Ct=["cli-config.json","config.json","auth.json","argv.json"];function it(i){return!(!i||typeof i!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function lt(i){let t=L(i||process.cwd(),".zibby","tmp");st(t,{recursive:!0});let e=`${process.pid}-${Date.now()}-${Pt(4).toString("hex")}`,r=L(t,`cursor-agent-home-${e}`),s=L(r,".cursor");st(s,{recursive:!0});let l=Rt(),n=L(l,".cursor");if(nt(n))for(let a of Ct){let u=L(n,a);if(nt(u))try{Tt(u,L(s,a))}catch{}}if(process.platform==="darwin"){let a=L(l,"Library");if(nt(a))try{$t(a,L(r,"Library"))}catch{}}return r}function at(i){if(!(!i||typeof i!="string"))try{let t=L(i,"Library");try{xt(t).isSymbolicLink()&&vt(t)}catch{}wt(i,{recursive:!0,force:!0})}catch{}}var mt=class extends Nt{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(t){let e=[v(Y(),".local","bin","cursor-agent"),v(Y(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"];for(let r of e)try{if(r.startsWith("/")){dt(r,gt.X_OK);let s=F(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return o.debug(`[Cursor] Found agent at: ${r} (version: ${s.trim().slice(0,50)})`),!0}else{let s=F(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!s)continue;let l=F(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(l&&l.length>0)return o.debug(`[Cursor] Found '${r}' in PATH at ${s} (version: ${l.trim().slice(0,50)})`),!0}}catch{continue}return o.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(t,e={}){let{workspace:r=process.cwd(),print:s=!1,schema:l=null,skills:n=null,sessionPath:a=null,nodeName:u=null,timeout:h=W.CURSOR_AGENT_DEFAULT,config:p={},signal:m=null}=e,d=p?.agent?.strictMode||!1,y=e.model??p?.agent?.cursor?.model??z.CURSOR;o.debug(`[Cursor] Invoking (model: ${y}, timeout: ${h/1e3}s, skills: ${JSON.stringify(n)})`);let R=(this._setupMcpConfig(a,r,p,n,u)||{}).isolatedMcpHome??null,g=[v(Y(),".local","bin","cursor-agent"),v(Y(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],T=null;for(let E of g)try{if(E.startsWith("/"))dt(E,gt.X_OK),F(`"${E}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!F(`which ${E}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");F(`${E} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}T=E,o.debug(`[Agent] Using binary: ${E}`);break}catch(_){o.debug(`[Agent] Binary '${E}' check failed: ${_.message}`);continue}if(!T)throw new Error(`Cursor Agent CLI not found or not working.
42
+ Response: ${JSON.stringify(d)}`,{cause:p}):new Error(`Failed to format Cursor output: ${d?.error?.message||"Unknown error"}`,{cause:p})}throw o.error(`\u274C OpenAI proxy request failed: ${p.message}`),new Error(`Failed to format output: ${p.message}`,{cause:p})}}import{timeline as rt,Timeline as se,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as ie}from"@zibby/agent-workflow";import{copyFileSync as xt,existsSync as nt,lstatSync as Tt,mkdirSync as st,rmSync as wt,symlinkSync as $t,unlinkSync as vt}from"node:fs";import{join as L}from"node:path";import{homedir as Rt}from"node:os";import{randomBytes as Pt}from"node:crypto";var Ct=["cli-config.json","config.json","auth.json","argv.json"];function it(i){return!(!i||typeof i!="string"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="1"||process.env.ZIBBY_CURSOR_USE_GLOBAL_MCP==="true")}function lt(i){let t=L(i||process.cwd(),".zibby","tmp");st(t,{recursive:!0});let e=`${process.pid}-${Date.now()}-${Pt(4).toString("hex")}`,r=L(t,`cursor-agent-home-${e}`),s=L(r,".cursor");st(s,{recursive:!0});let l=Rt(),n=L(l,".cursor");if(nt(n))for(let a of Ct){let u=L(n,a);if(nt(u))try{xt(u,L(s,a))}catch{}}if(process.platform==="darwin"){let a=L(l,"Library");if(nt(a))try{$t(a,L(r,"Library"))}catch{}}return r}function at(i){if(!(!i||typeof i!="string"))try{let t=L(i,"Library");try{Tt(t).isSymbolicLink()&&vt(t)}catch{}wt(i,{recursive:!0,force:!0})}catch{}}var mt=class extends Nt{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(t){let e=[v(Y(),".local","bin","cursor-agent"),v(Y(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"];for(let r of e)try{if(r.startsWith("/")){dt(r,gt.X_OK);let s=F(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(s&&s.length>0)return o.debug(`[Cursor] Found agent at: ${r} (version: ${s.trim().slice(0,50)})`),!0}else{let s=F(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!s)continue;let l=F(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(l&&l.length>0)return o.debug(`[Cursor] Found '${r}' in PATH at ${s} (version: ${l.trim().slice(0,50)})`),!0}}catch{continue}return o.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(t,e={}){let{workspace:r=process.cwd(),print:s=!1,schema:l=null,skills:n=null,sessionPath:a=null,nodeName:u=null,timeout:h=W.CURSOR_AGENT_DEFAULT,config:p={},signal:m=null}=e,d=p?.agent?.strictMode||!1,y=e.model??p?.agent?.cursor?.model??z.CURSOR;o.debug(`[Cursor] Invoking (model: ${y}, timeout: ${h/1e3}s, skills: ${JSON.stringify(n)})`);let R=(this._setupMcpConfig(a,r,p,n,u)||{}).isolatedMcpHome??null,g=[v(Y(),".local","bin","cursor-agent"),v(Y(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"],w=null;for(let E of g)try{if(E.startsWith("/"))dt(E,gt.X_OK),F(`"${E}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!F(`which ${E}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");F(`${E} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}w=E,o.debug(`[Agent] Using binary: ${E}`);break}catch(_){o.debug(`[Agent] Binary '${E}' check failed: ${_.message}`);continue}if(!w)throw new Error(`Cursor Agent CLI not found or not working.
43
43
 
44
44
  Checked paths:
45
45
  ${g.map(E=>` - ${E}`).join(`
@@ -55,7 +55,7 @@ Test with: agent --version`);let k=new V(t),b=null;if(l){let E=`zibby-result-${D
55
55
  \u25C6 Model: ${y||"auto"}${j}
56
56
  `);let B=(await import("chalk")).default,K=k.getUserPrompt();console.log(`
57
57
  ${B.bold("Prompt sent to LLM:")}`),console.log(B.dim("\u2500".repeat(60))),console.log(B.dim(K)),console.log(B.dim("\u2500".repeat(60)));let O=k.build(),P=k.getStats(),U=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",y||"auto"];if(process.env.CURSOR_API_KEY&&U.push("--api-key",process.env.CURSOR_API_KEY),U.push(O),o.debug(`[Agent] User prompt: ${P.userPromptLength} chars, System instructions: ${P.systemInstructionsLength} chars (${P.instructionCount} blocks), Full: ${P.fullPromptLength} chars, model: ${y||"auto"}`),o.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${y||"auto"} (from .zibby.config.js agent.cursor.model)
58
- `)}catch{}let C,x=null;try{let E=a||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);C=await this._spawnWithStreaming(T,U,r,h,null,E,R,m)}catch(E){x=E}let D=C?.stdout||"";if(l){let E=typeof l.parse=="function",_=null,c=!!(b&&H(b));if(b&&o.info(`[Agent] Result file: ${c?"present":"missing"} at ${b}`),c)try{let f=pt(b,"utf-8").trim();_=JSON.parse(f),o.info(`[Agent] Parsed JSON from result file OK (${f.length} chars) \u2192 object ready for validation`),x&&o.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(f){o.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${f.message}`)}else if(x)o.warn(`[Agent] Result file missing at ${b} (agent process error \u2014 may still recover if strictMode repairs)`);else throw o.error(`\u274C [Agent] Result file was never created at ${b}`),new Error(`Agent did not write required result file at ${b}`);if(_&&E)try{let f=l.parse(_);return o.info("\u2705 [Agent] Zod validation passed for structured result file"),d&&o.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:D,structured:f}}catch(f){let S=f.issues?f.issues.map(I=>` - ${I.path.join(".")}: ${I.message}`).join(`
58
+ `)}catch{}let C,x=null;try{let E=a||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);C=await this._spawnWithStreaming(w,U,r,h,null,E,R,m)}catch(E){x=E}let D=C?.stdout||"";if(l){let E=typeof l.parse=="function",_=null,c=!!(b&&H(b));if(b&&o.info(`[Agent] Result file: ${c?"present":"missing"} at ${b}`),c)try{let f=pt(b,"utf-8").trim();_=JSON.parse(f),o.info(`[Agent] Parsed JSON from result file OK (${f.length} chars) \u2192 object ready for validation`),x&&o.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(f){o.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${f.message}`)}else if(x)o.warn(`[Agent] Result file missing at ${b} (agent process error \u2014 may still recover if strictMode repairs)`);else throw o.error(`\u274C [Agent] Result file was never created at ${b}`),new Error(`Agent did not write required result file at ${b}`);if(_&&E)try{let f=l.parse(_);return o.info("\u2705 [Agent] Zod validation passed for structured result file"),d&&o.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:D,structured:f}}catch(f){let S=f.issues?f.issues.map(I=>` - ${I.path.join(".")}: ${I.message}`).join(`
59
59
  `):f.message?.slice(0,400);if(o.error(`\u274C [Agent] Zod validation FAILED - invalid output schema:
60
60
  ${S}`),o.error(`\u{1F4C4} [Agent] Invalid JSON written to file:
61
61
  ${JSON.stringify(_,null,2).slice(0,500)}`),!d)throw new Error(`Agent output failed schema validation:
@@ -63,12 +63,12 @@ ${S}
63
63
 
64
64
  The agent wrote invalid data that doesn't match the required outputSchema.
65
65
  Enable strictMode in .zibby.config.js for automatic repair.`,{cause:f})}else{if(_)return o.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),d&&o.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:D,structured:_};c&&o.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(d&&!x){let f=C.parsedText,S=_?JSON.stringify(_):f;o.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${S.length} chars in)`);try{let I=await ot(S,l);if(E){let $=l.parse(I.structured);return o.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:D,structured:$}}return{raw:D,...I}}catch(I){if(o.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${I.message}`),_)return o.warn("[Agent] Using agent's original result file as fallback"),{raw:D,structured:_}}}if(x)throw x;let A=c?_==null?"file existed but JSON.parse failed \u2014 see WARN log above":E?"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 o.error(`\u274C [Agent] No validated structured output: ${A}`),o.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(x)throw x;return this._extractFinalResult(D)||C?.parsedText||D}_extractFinalResult(t){if(!t)return null;let e=t.split(`
66
- `),r=null;for(let s of e){let l=s.trim();if(l)try{let n=JSON.parse(l);if(n.type==="assistant"&&n.message?.content){let a=n.message.content;if(Array.isArray(a)){let u=a.filter(h=>h.type==="text"&&h.text).map(h=>h.text).join("");u&&(r=u)}else typeof a=="string"&&a&&(r=a)}}catch{}}return r?.trim()||null}_setupMcpConfig(t,e,r,s=null,l=null){let n=r?.headless,a=v(Y(),".cursor"),u=v(a,"mcp.json"),h={};if(H(u))try{h=JSON.parse(pt(u,"utf-8"))}catch{}let p=h.mcpServers||{},m=r?.paths?.output||kt,d=v(e||process.cwd(),m,Lt),y=Array.isArray(s)?s.map(g=>ut(g)).filter(Boolean):[...Ut()].map(([,g])=>g),w=new Set;for(let g of y)typeof g.resolve=="function"&&(w.has(g.serverName)||(w.add(g.serverName),this._ensureSkillConfigured(p,g,t,d,l,n)));if(t){let g=ut("browser");g&&typeof g.resolve=="function"&&!w.has(g.serverName)&&this._ensureSkillConfigured(p,g,t,d,"execute_live",n)}if(Object.keys(p).length===0)return o.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let R=`${JSON.stringify({mcpServers:p},null,2)}
67
- `;if(it(t)){let g=lt(e||process.cwd()),T=v(g,".cursor","mcp.json");return ct(T,R,"utf8"),o.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${g} | servers: ${Object.keys(p).join(", ")}`),{isolatedMcpHome:g}}return H(a)||ft(a,{recursive:!0}),ct(u,R,"utf8"),o.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(p).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(t,e,r,s,l=null,n){let a=e.cursorKey||e.serverName,u=t[a]?a:t[e.serverName]?e.serverName:null;if(u&&r){let p=typeof e.resolve=="function"?e.resolve({sessionPath:r,nodeName:l,headless:n}):null;p?.args?t[u].args=p.args:t[u].args=(t[u].args||[]).map(y=>y.startsWith("--output-dir=")?`--output-dir=${r}`:y);let m=p?.env||{},d=e.sessionEnvKey?{[e.sessionEnvKey]:s}:{};t[u].env={...t[u].env||{},...m,...d},o.debug(`[MCP] Updated ${u} session \u2192 ${r}`);return}if(u)return;let h=e.resolve({sessionPath:r,nodeName:l,headless:n});h&&(t[a]={...h,...e.sessionEnvKey&&{env:{...h.env||{},[e.sessionEnvKey]:s}}},o.debug(`[MCP] Configured ${a}`))}_spawnWithStreaming(t,e,r,s,l=null,n=null,a=null,u=null){return new Promise((h,p)=>{let m=Date.now(),d="",y="",w=Date.now(),R=0,g=!1,T=null,k=!1,b=!1,M=null;if(n)try{M=v(Ft(String(n)),Mt)}catch{M=null}let j=!1,B=()=>{j||(j=!0,at(a))},K={...process.env};a&&(K.HOME=a,process.platform==="win32"&&(K.USERPROFILE=a),o.debug(`[Agent] cursor-agent HOME=${a} (isolated MCP config)`));let O=Dt(t,e,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:K,...u&&{signal:u}});o.debug(`[Agent] PID: ${O.pid}`);let P=null,U=()=>{g||b||(g=!0,T="aborted",o.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),P=setTimeout(()=>{if(!b){o.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{O.kill("SIGKILL")}catch{}}},5e3))};u&&(u.aborted?U():u.addEventListener("abort",U,{once:!0})),O.stdin.on("error",c=>{c.code!=="EPIPE"&&o.warn(`[Agent] stdin error: ${c.message}`)}),O.stdout.on("error",c=>{c.code!=="EPIPE"&&o.warn(`[Agent] stdout error: ${c.message}`)}),O.stderr.on("error",c=>{c.code!=="EPIPE"&&o.warn(`[Agent] stderr error: ${c.message}`)}),l?(O.stdin.write(l,c=>{c&&c.code!=="EPIPE"&&o.warn(`[Agent] Failed to write to stdin: ${c.message}`),O.stdin.end()}),o.debug(`[Agent] Prompt also piped to stdin (${l.length} chars)`)):O.stdin.end();let C=null;M&&(C=setInterval(()=>{if(!(g||b))try{if(H(M)){g=!0,T="studio-stop";try{Bt(M)}catch{}o.warn("\u{1F6D1} Studio stop requested \u2014 terminating Cursor agent (and MCP browser session)"),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},2e3)}}catch{}},600));let x=new Set,D=new Date(m).toISOString().replace(/\.\d+Z$/,""),q=setInterval(()=>{let c=Math.round((Date.now()-m)/1e3),A=Math.round((Date.now()-w)/1e3),f=[];try{let I=Math.ceil(c/60)+1,$=F(`find "${r}" -type f -mmin -${I} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if($)for(let Q of $.split(`
68
- `)){let tt=Q.replace(`${r}/`,"");x.has(tt)||(x.add(tt),f.push(tt))}}catch{}let S="";f.length>0&&(S=` | \u{1F4C1} new: ${f.map($=>$.split("/").pop()).join(", ")}`),x.size>0&&(S+=` | \u{1F4E6} total: ${x.size} files`),o.debug(`\u{1F493} [Agent] Running for ${c}s | ${R} lines output${S}`),R===0&&c>=30&&x.size===0&&(c<35&&o.warn(`\u26A0\uFE0F [Agent] No output after ${c}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),c>=60&&(g=!0,T=T||"stall",o.error(`\u274C [Agent] No response after ${c}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},3e3)))},3e4),E=setTimeout(()=>{g=!0,T=T||"timeout";let c=Math.round((Date.now()-m)/1e3);o.error(`\u23F1\uFE0F [Agent] Timeout after ${c}s \u2014 killing process (PID: ${O.pid})`),d.trim()&&o.warn(`\u{1F4E4} [Agent] Partial output (${d.length} chars) before timeout:
69
- ${d.slice(-2e3)}`),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},5e3)},s),_=new Z;_.onToolCall=(c,A)=>{let f=c,S=A;if(c==="mcpToolCall"&&A?.name)f=A.name.replace(/^mcp_+[^_]+_+/,""),f.includes("-")&&f.split("-")[0]===f.split("-")[1]&&(f=f.split("-")[0]),S=A.args??A.input??A;else{if(c==="readToolCall"||c==="editToolCall"||c==="writeToolCall")return;(c.startsWith("mcp__")||c.includes("ToolCall"))&&(f=c.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(f.includes("memory")?rt.stepMemory(`Tool: ${f}`):rt.stepTool(`Tool: ${f}`),S!=null&&typeof S=="object"&&Object.keys(S).length>0&&!b){let $=JSON.stringify(S),Q=$.length>100?`${$.substring(0,100)}...`:$;console.log(` Input: ${Q}`)}},O.stdout.on("data",c=>{let A=c.toString();d+=A,w=Date.now(),k||(k=!0);let f=_.processChunk(A);f&&!b&&process.stdout.write(f);let S=A.split(`
70
- `).filter(I=>I.trim());R+=S.length}),O.stderr.on("data",c=>{let A=c.toString();y+=A,w=Date.now(),k||(k=!0);let f=A.split(`
71
- `).filter(S=>S.trim());for(let S of f)o.warn(`\u26A0\uFE0F [Agent stderr] ${S}`)}),O.on("close",(c,A)=>{if(b=!0,B(),clearTimeout(E),clearInterval(q),C&&clearInterval(C),P&&clearTimeout(P),u&&!u.aborted)try{u.removeEventListener("abort",U)}catch{}_.flush();let f=Math.round((Date.now()-m)/1e3);if(o.debug(`[Agent] Exited: code=${c}, signal=${A}, elapsed=${f}s, output=${d.length} chars`),g){if(T==="studio-stop"){p(new Error("Stopped from Zibby Studio"));return}if(T==="aborted"){let $=new Error("Aborted via signal");$.name="AbortError",p($);return}p(new Error(`Cursor Agent timed out after ${f}s (limit: ${s/1e3}s). ${R} lines produced. Last output ${Math.round((Date.now()-w)/1e3)}s ago. ${d.trim()?`
66
+ `),r=null;for(let s of e){let l=s.trim();if(l)try{let n=JSON.parse(l);if(n.type==="assistant"&&n.message?.content){let a=n.message.content;if(Array.isArray(a)){let u=a.filter(h=>h.type==="text"&&h.text).map(h=>h.text).join("");u&&(r=u)}else typeof a=="string"&&a&&(r=a)}}catch{}}return r?.trim()||null}_setupMcpConfig(t,e,r,s=null,l=null){let n=r?.headless,a=v(Y(),".cursor"),u=v(a,"mcp.json"),h={};if(H(u))try{h=JSON.parse(pt(u,"utf-8"))}catch{}let p=h.mcpServers||{},m=r?.paths?.output||kt,d=v(e||process.cwd(),m,Lt),y=Array.isArray(s)?s.map(g=>ut(g)).filter(Boolean):[...Ut()].map(([,g])=>g),T=new Set;for(let g of y)typeof g.resolve=="function"&&(T.has(g.serverName)||(T.add(g.serverName),this._ensureSkillConfigured(p,g,t,d,l,n)));if(t){let g=ut("browser");g&&typeof g.resolve=="function"&&!T.has(g.serverName)&&this._ensureSkillConfigured(p,g,t,d,"execute_live",n)}if(Object.keys(p).length===0)return o.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let R=`${JSON.stringify({mcpServers:p},null,2)}
67
+ `;if(it(t)){let g=lt(e||process.cwd()),w=v(g,".cursor","mcp.json");return ct(w,R,"utf8"),o.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${g} | servers: ${Object.keys(p).join(", ")}`),{isolatedMcpHome:g}}return H(a)||ft(a,{recursive:!0}),ct(u,R,"utf8"),o.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(p).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(t,e,r,s,l=null,n){let a=e.cursorKey||e.serverName,u=t[a]?a:t[e.serverName]?e.serverName:null;if(u&&r){let p=typeof e.resolve=="function"?e.resolve({sessionPath:r,nodeName:l,headless:n}):null;p?.args?t[u].args=p.args:t[u].args=(t[u].args||[]).map(y=>y.startsWith("--output-dir=")?`--output-dir=${r}`:y);let m=p?.env||{},d=e.sessionEnvKey?{[e.sessionEnvKey]:s}:{};t[u].env={...t[u].env||{},...m,...d},o.debug(`[MCP] Updated ${u} session \u2192 ${r}`);return}if(u)return;let h=e.resolve({sessionPath:r,nodeName:l,headless:n});h&&(t[a]={...h,...e.sessionEnvKey&&{env:{...h.env||{},[e.sessionEnvKey]:s}}},o.debug(`[MCP] Configured ${a}`))}_spawnWithStreaming(t,e,r,s,l=null,n=null,a=null,u=null){return new Promise((h,p)=>{let m=Date.now(),d="",y="",T=Date.now(),R=0,g=!1,w=null,k=!1,b=!1,M=null;if(n)try{M=v(Ft(String(n)),Mt)}catch{M=null}let j=!1,B=()=>{j||(j=!0,at(a))},K={...process.env};a&&(K.HOME=a,process.platform==="win32"&&(K.USERPROFILE=a),o.debug(`[Agent] cursor-agent HOME=${a} (isolated MCP config)`));let O=Dt(t,e,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:K,...u&&{signal:u}});o.debug(`[Agent] PID: ${O.pid}`);let P=null,U=()=>{g||b||(g=!0,w="aborted",o.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),P=setTimeout(()=>{if(!b){o.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{O.kill("SIGKILL")}catch{}}},5e3))};u&&(u.aborted?U():u.addEventListener("abort",U,{once:!0})),O.stdin.on("error",c=>{c.code!=="EPIPE"&&o.warn(`[Agent] stdin error: ${c.message}`)}),O.stdout.on("error",c=>{c.code!=="EPIPE"&&o.warn(`[Agent] stdout error: ${c.message}`)}),O.stderr.on("error",c=>{c.code!=="EPIPE"&&o.warn(`[Agent] stderr error: ${c.message}`)}),l?(O.stdin.write(l,c=>{c&&c.code!=="EPIPE"&&o.warn(`[Agent] Failed to write to stdin: ${c.message}`),O.stdin.end()}),o.debug(`[Agent] Prompt also piped to stdin (${l.length} chars)`)):O.stdin.end();let C=null;M&&(C=setInterval(()=>{if(!(g||b))try{if(H(M)){g=!0,w="aborted";try{Bt(M)}catch{}o.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},2e3)}}catch{}},600));let x=new Set,D=new Date(m).toISOString().replace(/\.\d+Z$/,""),q=setInterval(()=>{let c=Math.round((Date.now()-m)/1e3),A=Math.round((Date.now()-T)/1e3),f=[];try{let I=Math.ceil(c/60)+1,$=F(`find "${r}" -type f -mmin -${I} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if($)for(let Q of $.split(`
68
+ `)){let tt=Q.replace(`${r}/`,"");x.has(tt)||(x.add(tt),f.push(tt))}}catch{}let S="";f.length>0&&(S=` | \u{1F4C1} new: ${f.map($=>$.split("/").pop()).join(", ")}`),x.size>0&&(S+=` | \u{1F4E6} total: ${x.size} files`),o.debug(`\u{1F493} [Agent] Running for ${c}s | ${R} lines output${S}`),R===0&&c>=30&&x.size===0&&(c<35&&o.warn(`\u26A0\uFE0F [Agent] No output after ${c}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),c>=60&&(g=!0,w=w||"stall",o.error(`\u274C [Agent] No response after ${c}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},3e3)))},3e4),E=setTimeout(()=>{g=!0,w=w||"timeout";let c=Math.round((Date.now()-m)/1e3);o.error(`\u23F1\uFE0F [Agent] Timeout after ${c}s \u2014 killing process (PID: ${O.pid})`),d.trim()&&o.warn(`\u{1F4E4} [Agent] Partial output (${d.length} chars) before timeout:
69
+ ${d.slice(-2e3)}`),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},5e3)},s),_=new Z;_.onToolCall=(c,A)=>{let f=c,S=A;if(c==="mcpToolCall"&&A?.name)f=A.name.replace(/^mcp_+[^_]+_+/,""),f.includes("-")&&f.split("-")[0]===f.split("-")[1]&&(f=f.split("-")[0]),S=A.args??A.input??A;else{if(c==="readToolCall"||c==="editToolCall"||c==="writeToolCall")return;(c.startsWith("mcp__")||c.includes("ToolCall"))&&(f=c.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(f.includes("memory")?rt.stepMemory(`Tool: ${f}`):rt.stepTool(`Tool: ${f}`),S!=null&&typeof S=="object"&&Object.keys(S).length>0&&!b){let $=JSON.stringify(S),Q=$.length>100?`${$.substring(0,100)}...`:$;console.log(` Input: ${Q}`)}},O.stdout.on("data",c=>{let A=c.toString();d+=A,T=Date.now(),k||(k=!0);let f=_.processChunk(A);f&&!b&&process.stdout.write(f);let S=A.split(`
70
+ `).filter(I=>I.trim());R+=S.length}),O.stderr.on("data",c=>{let A=c.toString();y+=A,T=Date.now(),k||(k=!0);let f=A.split(`
71
+ `).filter(S=>S.trim());for(let S of f)o.warn(`\u26A0\uFE0F [Agent stderr] ${S}`)}),O.on("close",(c,A)=>{if(b=!0,B(),clearTimeout(E),clearInterval(q),C&&clearInterval(C),P&&clearTimeout(P),u&&!u.aborted)try{u.removeEventListener("abort",U)}catch{}_.flush();let f=Math.round((Date.now()-m)/1e3);if(o.debug(`[Agent] Exited: code=${c}, signal=${A}, elapsed=${f}s, output=${d.length} chars`),g){if(w==="aborted"){let $=new Error("Aborted via signal");$.name="AbortError",p($);return}p(new Error(`Cursor Agent timed out after ${f}s (limit: ${s/1e3}s). ${R} lines produced. Last output ${Math.round((Date.now()-T)/1e3)}s ago. ${d.trim()?`
72
72
  Partial output (last 500 chars):
73
73
  ${d.slice(-500)}`:"No output captured."}`));return}if(c!==0){p(new Error(`Cursor Agent failed: exit code ${c}, signal ${u}. ${y.trim()?`
74
74
  Stderr: ${y.slice(-1e3)}`:""}${d.trim()?`
@@ -1,4 +1,4 @@
1
- import{AgentStrategy as Et,DEFAULT_OUTPUT_BASE as wt,SESSION_INFO_FILE as At,STUDIO_STOP_REQUEST_FILE as Ot,getAllSkills as Tt,getSkill as Ge}from"@zibby/agent-workflow";import{spawn as xt,execSync as H}from"node:child_process";import{writeFileSync as je,readFileSync as Fe,mkdirSync as Ye,existsSync as se,accessSync as ze,constants as He,unlinkSync as $t}from"node:fs";import{join as K,resolve as vt}from"node:path";import{homedir as ie}from"node:os";import ne from"chalk";var G={debug:0,info:1,warn:2,error:3,silent:4},xe=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return G.debug;if(process.env.ZIBBY_VERBOSE==="true")return G.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in G?G[e]:G.info}_shouldLog(e){return G[e]>=this._level}_formatMessage(e,t,r={}){let o=new Date().toISOString(),s=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(s+=ne.dim(` ${JSON.stringify(r)}`)),s}_getPrefix(e){return{debug:ne.gray("[DEBUG]"),info:ne.cyan("[INFO]"),warn:ne.yellow("[WARN]"),error:ne.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 G&&(this._level=G[e])}getLevel(){return Object.keys(G).find(e=>G[e]===this._level)}},a=new xe;var J={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"};var $e={auto:"claude-sonnet-4-6","sonnet-4.6":"claude-sonnet-4-6","sonnet-4-6":"claude-sonnet-4-6","opus-4.6":"claude-opus-4-6","opus-4-6":"claude-opus-4-6","sonnet-4.5":"claude-sonnet-4-5-20250929","sonnet-4-5":"claude-sonnet-4-5-20250929","opus-4.5":"claude-opus-4-20250514","opus-4-5":"claude-opus-4-20250514","claude-sonnet-4-6":"claude-sonnet-4-6","claude-opus-4-6":"claude-opus-4-6","claude-sonnet-4-5-20250929":"claude-sonnet-4-5-20250929","claude-opus-4-20250514":"claude-opus-4-20250514"},ve={auto:"o4-mini","o4-mini":"o4-mini",o3:"o3","o3-mini":"o3-mini","codex-mini":"codex-mini-latest","gpt-4o":"gpt-4o","gpt-4o-mini":"gpt-4o-mini","gpt-5.2-codex":"gpt-5.2-codex","gpt-5.2":"gpt-5.2","gpt-5.3":"gpt-5.3","gpt-5.4":"gpt-5.4"},Le={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},ue={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var q=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(`
1
+ import{AgentStrategy as Et,DEFAULT_OUTPUT_BASE as wt,SESSION_INFO_FILE as At,STOP_REQUEST_FILE as Ot,getAllSkills as Tt,getSkill as Ge}from"@zibby/agent-workflow";import{spawn as xt,execSync as H}from"node:child_process";import{writeFileSync as je,readFileSync as Fe,mkdirSync as Ye,existsSync as se,accessSync as ze,constants as He,unlinkSync as $t}from"node:fs";import{join as K,resolve as vt}from"node:path";import{homedir as ie}from"node:os";import ne from"chalk";var G={debug:0,info:1,warn:2,error:3,silent:4},xe=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return G.debug;if(process.env.ZIBBY_VERBOSE==="true")return G.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in G?G[e]:G.info}_shouldLog(e){return G[e]>=this._level}_formatMessage(e,t,r={}){let o=new Date().toISOString(),s=`${this._getPrefix(e)} ${t}`;return Object.keys(r).length>0&&(s+=ne.dim(` ${JSON.stringify(r)}`)),s}_getPrefix(e){return{debug:ne.gray("[DEBUG]"),info:ne.cyan("[INFO]"),warn:ne.yellow("[WARN]"),error:ne.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 G&&(this._level=G[e])}getLevel(){return Object.keys(G).find(e=>G[e]===this._level)}},a=new xe;var J={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"};var $e={auto:"claude-sonnet-4-6","sonnet-4.6":"claude-sonnet-4-6","sonnet-4-6":"claude-sonnet-4-6","opus-4.6":"claude-opus-4-6","opus-4-6":"claude-opus-4-6","sonnet-4.5":"claude-sonnet-4-5-20250929","sonnet-4-5":"claude-sonnet-4-5-20250929","opus-4.5":"claude-opus-4-20250514","opus-4-5":"claude-opus-4-20250514","claude-sonnet-4-6":"claude-sonnet-4-6","claude-opus-4-6":"claude-opus-4-6","claude-sonnet-4-5-20250929":"claude-sonnet-4-5-20250929","claude-opus-4-20250514":"claude-opus-4-20250514"},ve={auto:"o4-mini","o4-mini":"o4-mini",o3:"o3","o3-mini":"o3-mini","codex-mini":"codex-mini-latest","gpt-4o":"gpt-4o","gpt-4o-mini":"gpt-4o-mini","gpt-5.2-codex":"gpt-5.2-codex","gpt-5.2":"gpt-5.2","gpt-5.3":"gpt-5.3","gpt-5.4":"gpt-5.4"},Le={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},ue={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};var q=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 r="";for(let o of t)if(o.trim())try{let n=JSON.parse(o);this._emitToolCalls(n);let s=this.extractText(n);if(s){if(this.rawText&&s.startsWith(this.rawText)){let l=s.substring(this.rawText.length);this.rawText=s,r+=l}else(!this.rawText.includes(s)||s.length<20)&&(this.rawText+=s,r+=s);this.tryExtractResult(this.rawText)}else this.isValidResult(n)&&(this.rawText+=`${o}
3
3
  `,r+=`${o}
4
4
  `,this.extractedResult=n)}catch{if(o.includes('"text"')||o.includes('"content"')){let s=o.match(/"text"\s*:\s*"([^"]*)/),l=o.match(/"content"\s*:\s*"([^"]*)/),c=s?s[1]:l?l[1]:null;c&&!this.rawText.includes(c)&&(r+=c,this.rawText+=c)}}return r||null}flush(){if(!this.buffer.trim())return null;let e="";try{let t=JSON.parse(this.buffer);this._emitToolCalls(t);let r=this.extractText(t);r&&(this.rawText+=r,e+=r,this.tryExtractResult(r))}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=(s,l)=>{if(!s)return;let c=`${s}:${JSON.stringify(l??{})}`;this._lastToolEmit!==c&&(this._lastToolEmit=c,this.onToolCall(s,l??void 0))},r=s=>{if(s!=null){if(typeof s=="object"&&!Array.isArray(s))return s;if(typeof s=="string")try{return JSON.parse(s)}catch{return}}};if(e.type==="tool_use"||e.type==="tool_call"){if(e.name){t(e.name,r(e.input??e.arguments));return}let s=e.tool_call;if(s&&typeof s=="object"&&!Array.isArray(s)){let l=Object.keys(s);if(l.length===1){let c=l[0],f=s[c],u=f&&typeof f=="object"?f.args??f.input??f:void 0;t(c,r(u))}return}return}if(Array.isArray(e.tool_calls)){for(let s of e.tool_calls)t(s.name,r(s.input??s.arguments));return}let o=e.message??e;if(Array.isArray(o?.tool_calls)){for(let s of o.tool_calls)t(s.name,r(s.input??s.arguments));return}let n=o?.content??e.content;if(Array.isArray(n))for(let s of n)(s.type==="tool_use"||s.type==="tool_call")&&s.name&&t(s.name,r(s.input??s.arguments))}extractText(e){if(e.type==="assistant"&&e.message?.content){let t=e.message.content;if(Array.isArray(t))return t.filter(r=>r.type==="text"&&r.text).map(r=>r.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=[],r=/```json\s*\n?([\s\S]*?)\n?```/g,o;for(;(o=r.exec(e))!==null;){let S=o[1].trim();try{JSON.parse(S),t.push({text:S,source:"markdown"})}catch{}}let n=0,s=0;for(;n<e.length&&(n=e.indexOf("{",n),n!==-1);){let S=0,m=n;for(let d=n;d<e.length;d++)if(e[d]==="{")S++;else if(e[d]==="}"&&(S--,S===0)){m=d,t.push({text:e.substring(n,m+1),source:"brace"}),s++;break}n=m+1}let l=this.extractedResult,c=l?JSON.stringify(l).length:0,f=0,u=-1;for(let S=0;S<t.length;S++){let m=t[S];try{let d=m.text.replace(/,(\s*[}\]])/g,"$1"),O=JSON.parse(d);this.isValidResult(O)&&(f++,c=JSON.stringify(O).length,l=O,u=S)}catch{}}l&&(this.extractedResult=l)}isValidResult(e){if(!e||typeof e!="object"||Array.isArray(e)||e.session_id||e.timestamp_ms||e.type||e.call_id||e.tool_call||e.result&&typeof e.result=="object"&&(e.result.success&&typeof e.result.success=="object"||e.result.error&&typeof e.result.error=="object")||e.args&&typeof e.args=="object")return!1;if(this.zodSchema)try{return this.zodSchema.parse(e),!0}catch{return!1}return!0}getResult(){return this.extractedResult}getRawText(){return this.rawText}static extractResult(e,t=null){let r=new i;r.zodSchema=t,r.processChunk(e),r.flush();let o=r.getResult();return!o&&process.env.LOG_LEVEL==="debug"&&console.error("[StreamingParser] No result extracted from",e?.length||0,"chars"),o}};import{zodToJsonSchema as nt}from"zod-to-json-schema";var fe=class{static generateFileOutputInstructions(e,t){let r;typeof e?.parse=="function"?r=nt(e,{target:"openApi3"}):r=e;let o=this._buildExample(r);return`
@@ -64,11 +64,11 @@ ${k}
64
64
  The agent wrote invalid data that doesn't match the required outputSchema.
65
65
  Enable strictMode in .zibby.config.js for automatic repair.`,{cause:_})}else{if(T)return a.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),m&&a.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:v,structured:T};h&&a.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if(m&&!p){let _=A.parsedText,k=T?JSON.stringify(T):_;a.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${k.length} chars in)`);try{let L=await De(k,n);if(y){let D=n.parse(L.structured);return a.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:v,structured:D}}return{raw:v,...L}}catch(L){if(a.warn(`\u26A0\uFE0F [Agent] strictMode proxy failed: ${L.message}`),T)return a.warn("[Agent] Using agent's original result file as fallback"),{raw:v,structured:T}}}if(p)throw p;let B=h?T==null?"file existed but JSON.parse failed \u2014 see WARN log above":y?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw a.error(`\u274C [Agent] No validated structured output: ${B}`),a.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error(`Agent did not produce a valid result file at ${g}. Enable strictMode for proxy fallback.`)}if(p)throw p;return this._extractFinalResult(v)||A?.parsedText||v}_extractFinalResult(e){if(!e)return null;let t=e.split(`
66
66
  `),r=null;for(let o of t){let n=o.trim();if(n)try{let s=JSON.parse(n);if(s.type==="assistant"&&s.message?.content){let l=s.message.content;if(Array.isArray(l)){let c=l.filter(f=>f.type==="text"&&f.text).map(f=>f.text).join("");c&&(r=c)}else typeof l=="string"&&l&&(r=l)}}catch{}}return r?.trim()||null}_setupMcpConfig(e,t,r,o=null,n=null){let s=r?.headless,l=K(ie(),".cursor"),c=K(l,"mcp.json"),f={};if(se(c))try{f=JSON.parse(Fe(c,"utf-8"))}catch{}let u=f.mcpServers||{},S=r?.paths?.output||wt,m=K(t||process.cwd(),S,At),d=Array.isArray(o)?o.map(E=>Ge(E)).filter(Boolean):[...Tt()].map(([,E])=>E),O=new Set;for(let E of d)typeof E.resolve=="function"&&(O.has(E.serverName)||(O.add(E.serverName),this._ensureSkillConfigured(u,E,e,m,n,s)));if(e){let E=Ge("browser");E&&typeof E.resolve=="function"&&!O.has(E.serverName)&&this._ensureSkillConfigured(u,E,e,m,"execute_live",s)}if(Object.keys(u).length===0)return a.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};let I=`${JSON.stringify({mcpServers:u},null,2)}
67
- `;if(Be(e)){let E=Je(t||process.cwd()),w=K(E,".cursor","mcp.json");return je(w,I,"utf8"),a.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${E} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:E}}return se(l)||Ye(l,{recursive:!0}),je(c,I,"utf8"),a.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,o,n=null,s){let l=t.cursorKey||t.serverName,c=e[l]?l:e[t.serverName]?t.serverName:null;if(c&&r){let u=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:n,headless:s}):null;u?.args?e[c].args=u.args:e[c].args=(e[c].args||[]).map(d=>d.startsWith("--output-dir=")?`--output-dir=${r}`:d);let S=u?.env||{},m=t.sessionEnvKey?{[t.sessionEnvKey]:o}:{};e[c].env={...e[c].env||{},...S,...m},a.debug(`[MCP] Updated ${c} session \u2192 ${r}`);return}if(c)return;let f=t.resolve({sessionPath:r,nodeName:n,headless:s});f&&(e[l]={...f,...t.sessionEnvKey&&{env:{...f.env||{},[t.sessionEnvKey]:o}}},a.debug(`[MCP] Configured ${l}`))}_spawnWithStreaming(e,t,r,o,n=null,s=null,l=null,c=null){return new Promise((f,u)=>{let S=Date.now(),m="",d="",O=Date.now(),I=0,E=!1,w=null,$=!1,g=!1,x=null;if(s)try{x=K(vt(String(s)),Ot)}catch{x=null}let U=!1,R=()=>{U||(U=!0,Ke(l))},M={...process.env};l&&(M.HOME=l,process.platform==="win32"&&(M.USERPROFILE=l),a.debug(`[Agent] cursor-agent HOME=${l} (isolated MCP config)`));let b=xt(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:M,...c&&{signal:c}});a.debug(`[Agent] PID: ${b.pid}`);let P=null,C=()=>{E||g||(E=!0,w="aborted",a.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),P=setTimeout(()=>{if(!g){a.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{b.kill("SIGKILL")}catch{}}},5e3))};c&&(c.aborted?C():c.addEventListener("abort",C,{once:!0})),b.stdin.on("error",h=>{h.code!=="EPIPE"&&a.warn(`[Agent] stdin error: ${h.message}`)}),b.stdout.on("error",h=>{h.code!=="EPIPE"&&a.warn(`[Agent] stdout error: ${h.message}`)}),b.stderr.on("error",h=>{h.code!=="EPIPE"&&a.warn(`[Agent] stderr error: ${h.message}`)}),n?(b.stdin.write(n,h=>{h&&h.code!=="EPIPE"&&a.warn(`[Agent] Failed to write to stdin: ${h.message}`),b.stdin.end()}),a.debug(`[Agent] Prompt also piped to stdin (${n.length} chars)`)):b.stdin.end();let A=null;x&&(A=setInterval(()=>{if(!(E||g))try{if(se(x)){E=!0,w="studio-stop";try{$t(x)}catch{}a.warn("\u{1F6D1} Studio stop requested \u2014 terminating Cursor agent (and MCP browser session)"),b.kill("SIGTERM"),setTimeout(()=>{b.killed||b.kill("SIGKILL")},2e3)}}catch{}},600));let p=new Set,v=new Date(S).toISOString().replace(/\.\d+Z$/,""),N=setInterval(()=>{let h=Math.round((Date.now()-S)/1e3),B=Math.round((Date.now()-O)/1e3),_=[];try{let L=Math.ceil(h/60)+1,D=H(`find "${r}" -type f -mmin -${L} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(D)for(let z of D.split(`
67
+ `;if(Be(e)){let E=Je(t||process.cwd()),w=K(E,".cursor","mcp.json");return je(w,I,"utf8"),a.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${E} | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:E}}return se(l)||Ye(l,{recursive:!0}),je(c,I,"utf8"),a.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(u).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(e,t,r,o,n=null,s){let l=t.cursorKey||t.serverName,c=e[l]?l:e[t.serverName]?t.serverName:null;if(c&&r){let u=typeof t.resolve=="function"?t.resolve({sessionPath:r,nodeName:n,headless:s}):null;u?.args?e[c].args=u.args:e[c].args=(e[c].args||[]).map(d=>d.startsWith("--output-dir=")?`--output-dir=${r}`:d);let S=u?.env||{},m=t.sessionEnvKey?{[t.sessionEnvKey]:o}:{};e[c].env={...e[c].env||{},...S,...m},a.debug(`[MCP] Updated ${c} session \u2192 ${r}`);return}if(c)return;let f=t.resolve({sessionPath:r,nodeName:n,headless:s});f&&(e[l]={...f,...t.sessionEnvKey&&{env:{...f.env||{},[t.sessionEnvKey]:o}}},a.debug(`[MCP] Configured ${l}`))}_spawnWithStreaming(e,t,r,o,n=null,s=null,l=null,c=null){return new Promise((f,u)=>{let S=Date.now(),m="",d="",O=Date.now(),I=0,E=!1,w=null,$=!1,g=!1,x=null;if(s)try{x=K(vt(String(s)),Ot)}catch{x=null}let U=!1,R=()=>{U||(U=!0,Ke(l))},M={...process.env};l&&(M.HOME=l,process.platform==="win32"&&(M.USERPROFILE=l),a.debug(`[Agent] cursor-agent HOME=${l} (isolated MCP config)`));let b=xt(e,t,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:M,...c&&{signal:c}});a.debug(`[Agent] PID: ${b.pid}`);let P=null,C=()=>{E||g||(E=!0,w="aborted",a.warn("\u{1F6D1} Abort signal \u2014 terminating cursor-agent (SIGKILL in 5s if SIGTERM trapped)"),P=setTimeout(()=>{if(!g){a.warn("\u{1F6D1} SIGTERM not honored \u2014 sending SIGKILL");try{b.kill("SIGKILL")}catch{}}},5e3))};c&&(c.aborted?C():c.addEventListener("abort",C,{once:!0})),b.stdin.on("error",h=>{h.code!=="EPIPE"&&a.warn(`[Agent] stdin error: ${h.message}`)}),b.stdout.on("error",h=>{h.code!=="EPIPE"&&a.warn(`[Agent] stdout error: ${h.message}`)}),b.stderr.on("error",h=>{h.code!=="EPIPE"&&a.warn(`[Agent] stderr error: ${h.message}`)}),n?(b.stdin.write(n,h=>{h&&h.code!=="EPIPE"&&a.warn(`[Agent] Failed to write to stdin: ${h.message}`),b.stdin.end()}),a.debug(`[Agent] Prompt also piped to stdin (${n.length} chars)`)):b.stdin.end();let A=null;x&&(A=setInterval(()=>{if(!(E||g))try{if(se(x)){E=!0,w="aborted";try{$t(x)}catch{}a.warn("\u{1F6D1} External stop requested \u2014 terminating Cursor agent (and MCP browser session)"),b.kill("SIGTERM"),setTimeout(()=>{b.killed||b.kill("SIGKILL")},2e3)}}catch{}},600));let p=new Set,v=new Date(S).toISOString().replace(/\.\d+Z$/,""),N=setInterval(()=>{let h=Math.round((Date.now()-S)/1e3),B=Math.round((Date.now()-O)/1e3),_=[];try{let L=Math.ceil(h/60)+1,D=H(`find "${r}" -type f -mmin -${L} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(D)for(let z of D.split(`
68
68
  `)){let Z=z.replace(`${r}/`,"");p.has(Z)||(p.add(Z),_.push(Z))}}catch{}let k="";_.length>0&&(k=` | \u{1F4C1} new: ${_.map(D=>D.split("/").pop()).join(", ")}`),p.size>0&&(k+=` | \u{1F4E6} total: ${p.size} files`),a.debug(`\u{1F493} [Agent] Running for ${h}s | ${I} lines output${k}`),I===0&&h>=30&&p.size===0&&(h<35&&a.warn(`\u26A0\uFE0F [Agent] No output after ${h}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),h>=60&&(E=!0,w=w||"stall",a.error(`\u274C [Agent] No response after ${h}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),b.kill("SIGTERM"),setTimeout(()=>{b.killed||b.kill("SIGKILL")},3e3)))},3e4),y=setTimeout(()=>{E=!0,w=w||"timeout";let h=Math.round((Date.now()-S)/1e3);a.error(`\u23F1\uFE0F [Agent] Timeout after ${h}s \u2014 killing process (PID: ${b.pid})`),m.trim()&&a.warn(`\u{1F4E4} [Agent] Partial output (${m.length} chars) before timeout:
69
69
  ${m.slice(-2e3)}`),b.kill("SIGTERM"),setTimeout(()=>{b.killed||b.kill("SIGKILL")},5e3)},o),T=new q;T.onToolCall=(h,B)=>{let _=h,k=B;if(h==="mcpToolCall"&&B?.name)_=B.name.replace(/^mcp_+[^_]+_+/,""),_.includes("-")&&_.split("-")[0]===_.split("-")[1]&&(_=_.split("-")[0]),k=B.args??B.input??B;else{if(h==="readToolCall"||h==="editToolCall"||h==="writeToolCall")return;(h.startsWith("mcp__")||h.includes("ToolCall"))&&(_=h.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(_.includes("memory")?j.stepMemory(`Tool: ${_}`):j.stepTool(`Tool: ${_}`),k!=null&&typeof k=="object"&&Object.keys(k).length>0&&!g){let D=JSON.stringify(k),z=D.length>100?`${D.substring(0,100)}...`:D;console.log(` Input: ${z}`)}},b.stdout.on("data",h=>{let B=h.toString();m+=B,O=Date.now(),$||($=!0);let _=T.processChunk(B);_&&!g&&process.stdout.write(_);let k=B.split(`
70
70
  `).filter(L=>L.trim());I+=k.length}),b.stderr.on("data",h=>{let B=h.toString();d+=B,O=Date.now(),$||($=!0);let _=B.split(`
71
- `).filter(k=>k.trim());for(let k of _)a.warn(`\u26A0\uFE0F [Agent stderr] ${k}`)}),b.on("close",(h,B)=>{if(g=!0,R(),clearTimeout(y),clearInterval(N),A&&clearInterval(A),P&&clearTimeout(P),c&&!c.aborted)try{c.removeEventListener("abort",C)}catch{}T.flush();let _=Math.round((Date.now()-S)/1e3);if(a.debug(`[Agent] Exited: code=${h}, signal=${B}, elapsed=${_}s, output=${m.length} chars`),E){if(w==="studio-stop"){u(new Error("Stopped from Zibby Studio"));return}if(w==="aborted"){let D=new Error("Aborted via signal");D.name="AbortError",u(D);return}u(new Error(`Cursor Agent timed out after ${_}s (limit: ${o/1e3}s). ${I} lines produced. Last output ${Math.round((Date.now()-O)/1e3)}s ago. ${m.trim()?`
71
+ `).filter(k=>k.trim());for(let k of _)a.warn(`\u26A0\uFE0F [Agent stderr] ${k}`)}),b.on("close",(h,B)=>{if(g=!0,R(),clearTimeout(y),clearInterval(N),A&&clearInterval(A),P&&clearTimeout(P),c&&!c.aborted)try{c.removeEventListener("abort",C)}catch{}T.flush();let _=Math.round((Date.now()-S)/1e3);if(a.debug(`[Agent] Exited: code=${h}, signal=${B}, elapsed=${_}s, output=${m.length} chars`),E){if(w==="aborted"){let D=new Error("Aborted via signal");D.name="AbortError",u(D);return}u(new Error(`Cursor Agent timed out after ${_}s (limit: ${o/1e3}s). ${I} lines produced. Last output ${Math.round((Date.now()-O)/1e3)}s ago. ${m.trim()?`
72
72
  Partial output (last 500 chars):
73
73
  ${m.slice(-500)}`:"No output captured."}`));return}if(h!==0){u(new Error(`Cursor Agent failed: exit code ${h}, signal ${c}. ${d.trim()?`
74
74
  Stderr: ${d.slice(-1e3)}`:""}${m.trim()?`
@@ -216,9 +216,11 @@ export function resolveBrowserTestPipelineSessionPathAbs({
216
216
  ? String(sessionId).trim()
217
217
  : null;
218
218
 
219
- const studio = process.env.ZIBBY_RUN_SOURCE === 'studio';
219
+ const pinned =
220
+ process.env.ZIBBY_PIN_SESSION_PATH === '1' ||
221
+ process.env.ZIBBY_PIN_SESSION_PATH === 'true';
220
222
  const envSession = process.env.ZIBBY_SESSION_PATH && String(process.env.ZIBBY_SESSION_PATH).trim();
221
- if (studio && envSession) {
223
+ if (pinned && envSession) {
222
224
  return pathResolve(envSession);
223
225
  }
224
226
 
@@ -1,4 +1,4 @@
1
- import{existsSync as h,readdirSync as F,statSync as Q}from"fs";import{join as a,relative as B,sep as x,resolve as m}from"path";import{appendFileSync as z,readFileSync as H,existsSync as _,mkdirSync as $}from"node:fs";import{join as w}from"node:path";import{DEFAULT_OUTPUT_BASE as E}from"@zibby/agent-workflow";var b="run-index.jsonl";function A(e,t=E){let n=w(e,t);return w(n,b)}function R(e){if(!e||!e.sessionId)return;let t=e.cwd||process.cwd(),n=e.outputBase||E,s=w(t,n);_(s)||$(s,{recursive:!0});let r=w(s,b),i=`${JSON.stringify(e)}
2
- `;z(r,i,"utf8")}function D(e){if(!e||!_(e))return[];let t;try{t=H(e,"utf8")}catch{return[]}let n=[];for(let s of t.split(`
3
- `)){let r=s.trim();if(r)try{n.push(JSON.parse(r))}catch{}}return n}import{existsSync as J,mkdirSync as K,readFileSync as W,readdirSync as pe,statSync as fe,writeFileSync as G}from"node:fs";import{join as V}from"node:path";var X="zibby-run-state.json";function M(e){return V(e,X)}function P(e){if(!e||typeof e!="string")return null;let t=M(e);if(!J(t))return null;try{let n=W(t,"utf8"),s=JSON.parse(n);return s&&typeof s=="object"?s:null}catch{return null}}function v(e,t){if(!e||typeof e!="string")return;try{K(e,{recursive:!0})}catch{return}let s={...P(e)||{v:1},...t,v:1,updatedAt:Date.now()};try{G(M(e),`${JSON.stringify(s)}
4
- `,"utf8")}catch(r){console.warn(`[zibby run-state] ${r.message}`)}}function q(e){return e?.recordKind==="progress"}function O(e){let t=Number(e)||0;return t<=0?0:t<1e12?t*1e3:t}function C(e,t={}){let n=t.maxProgressAgeMs!=null&&Number.isFinite(t.maxProgressAgeMs)?Math.max(0,t.maxProgressAgeMs):21e5,s=typeof t.now=="number"?t.now:Date.now(),{summary:r,progress:i}=e||{};if(!i)return!1;let o=O(i.ts);if(n>0&&o>0&&s-o>n)return!1;if(!r)return o>0;let p=O(r.ts);return o>p}function k(e){let t=new Map;for(let n of e||[]){if(!n?.sessionId)continue;let s=t.get(n.sessionId);s||(s={summary:null,progress:null});let r=Number(n.ts)||0;q(n)?(!s.progress||r>=(Number(s.progress.ts)||0))&&(s.progress=n):(!s.summary||r>=(Number(s.summary.ts)||0))&&(s.summary=n),t.set(n.sessionId,s)}return t}import{DEFAULT_OUTPUT_BASE as I,SESSIONS_DIR as N}from"@zibby/agent-workflow";var y=Object.freeze(["preflight","execute_live","generate_script"]);function T(e){let t=process.env.ZIBBY_STUDIO_TEST_CASE_ID;return t!=null&&String(t).trim()!==""?String(t).trim():e!=null?String(e):""}var ee=[a("generate_script","generated-test.spec.js"),a("generate_script","generated-test.spec.ts"),a("generate_script","playwright.spec.ts"),a("generate_script","test.spec.ts")];function te(e){let t=[a(e,"execute_live","videos"),a(e,"execute_live"),e];for(let n of t){if(!h(n))continue;let s;try{s=F(n)}catch{continue}let r=s.find(i=>i.endsWith(".webm"));if(r)return a(n,r)}return null}function ne(e){let t=[a(e,"execute_live","events.json"),a(e,"events.json")];for(let n of t)if(h(n))return n;return null}function se(e){for(let t of ee){let n=a(e,t);if(h(n))return n}return null}function re(e){return!e||!h(e)?{videoPathAbs:null,eventsPathAbs:null,scriptPathAbs:null}:{videoPathAbs:te(e),eventsPathAbs:ne(e),scriptPathAbs:se(e)}}function U(e){let t=e.cwd||process.cwd(),n=e.outputBase||I,i=((e.result||{}).state||{}).sessionPath;if(!i||typeof i!="string")return null;let o=i.split(/[/\\]/).filter(Boolean).pop();if(!o)return null;let{videoPathAbs:p,eventsPathAbs:f,scriptPathAbs:l}=re(i),d=u=>{if(!u)return null;try{return B(t,u).split(x).join("/")}catch{return null}},c=null;if(e.specPath)try{let u=m(t,e.specPath);c=B(t,u).split(x).join("/")}catch{c=String(e.specPath).split(x).join("/")}return{v:1,recordKind:"summary",ts:Date.now(),sessionId:o,status:e.status??(e.success?"completed":"failed"),cwd:t,outputBase:n,sessionPathAbs:i,sessionDirRel:d(i),videoPathAbs:p||null,eventsPathAbs:f||null,scriptPathAbs:l||null,videoRel:d(p),eventsRel:d(f),scriptRel:d(l),specRel:c,source:process.env.ZIBBY_RUN_SOURCE||"cli",studioTestCaseId:T(o)||null,errorMessage:e.errorMessage||null}}function j({cwd:e,config:t,result:n,success:s,specPath:r,errorMessage:i}){try{let o=U({cwd:e||process.cwd(),result:n,success:s,outputBase:t?.paths?.output||I,specPath:r,errorMessage:i});o&&(R(o),o.sessionPathAbs&&v(o.sessionPathAbs,{sessionId:o.sessionId,studioTestCaseId:o.studioTestCaseId||o.sessionId,status:o.status,activeNode:null,activeStageIndex:null,errorMessage:o.errorMessage||null,runSource:o.source||"cli",cwd:o.cwd,outputBase:o.outputBase,sessionPathAbs:o.sessionPathAbs}))}catch(o){console.warn(`[zibby browser-test run-index] ${o.message}`)}}function oe({sessionPath:e,sessionId:t,cwd:n,outputBase:s=I}={}){let r=n||process.cwd(),i=s||I,o=t!=null&&String(t).trim()!==""?String(t).trim():null,p=process.env.ZIBBY_RUN_SOURCE==="studio",f=process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim();if(p&&f)return m(f);let l=e&&String(e).trim();if(l)return m(l);let d=process.env.ZIBBY_SESSIONS_ROOT&&String(process.env.ZIBBY_SESSIONS_ROOT).trim();return d&&o?m(a(d,o)):process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim()?m(String(process.env.ZIBBY_SESSION_PATH).trim()):m(a(r,i,N,o||"invalid"))}function ie(e){try{let t=e?.currentNode;if(!t||!y.includes(t))return;let n=e.sessionPath,s=e.sessionId||n&&String(n).split(/[/\\]/).filter(Boolean).pop()||null;if(!s)return;let r=e.cwd||process.cwd(),i=e.outputBase||I,o=y.indexOf(t),p=e?.specPath!=null?String(e.specPath).trim():"",f=e?.taskDescription!=null?String(e.taskDescription):"",l=null;if(p)try{let c=m(r,p);l=B(r,c).split(x).join("/")}catch{l=p.split(x).join("/")}let d=oe({sessionPath:n,sessionId:s,cwd:r,outputBase:i});R({v:1,recordKind:"progress",ts:Date.now(),sessionId:s,cwd:r,outputBase:i,sessionPathAbs:d,activeNode:t,activeStageIndex:o,specRel:l,taskDescription:f||null,studioTestCaseId:T(s)||null,source:process.env.ZIBBY_RUN_SOURCE||"cli"}),v(d,{sessionId:s,studioTestCaseId:T(s)||s,status:"running",activeNode:t,activeStageIndex:o,sessionPathAbs:d,cwd:r,outputBase:i,specPath:l||null,task:f||null,taskDescription:f||null,runSource:process.env.ZIBBY_RUN_SOURCE||"cli",pid:typeof process.pid=="number"?process.pid:null})}catch(t){console.warn(`[zibby browser-test run-index progress] ${t.message}`)}}function Y({cwd:e,config:t}={}){let n=e||process.cwd(),s=t?.paths?.output||I;return r=>{ie({cwd:r?.cwd||n,outputBase:r?.outputBase||s,sessionPath:r?.sessionPath,sessionId:r?.sessionId,currentNode:r?.currentNode,specPath:r?.specPath,taskDescription:r?.taskDescription})}}function Z(e={}){try{let t=e.cwd||process.cwd(),n=e.config?.paths?.output||e.outputBase||I,s=A(t,n),r=D(s),i=k(r),o=new Set,p=e.errorMessage||"Run stopped (SIGINT/SIGTERM) before a normal summary was written.",f=(c,u)=>{if(!c||!u||o.has(c))return;o.add(c);let S=U({cwd:t,outputBase:n,result:{state:{sessionPath:u}},success:!1,specPath:null,status:"interrupted",errorMessage:p});S&&(R(S),v(u,{sessionId:c,studioTestCaseId:S.studioTestCaseId||c,status:"interrupted",activeNode:null,activeStageIndex:null,errorMessage:S.errorMessage||null,runSource:S.source||"cli",cwd:t,outputBase:n,sessionPathAbs:u}))};for(let[c,u]of i){if(!C(u))continue;let S=u.progress;if(!S)continue;let g=String(c),L=S.sessionPathAbs&&String(S.sessionPathAbs)||a(t,n,N,g);f(g,L)}let l=a(t,n,N);if(!h(l))return;let d;try{d=F(l)}catch{return}for(let c of d){let u=a(l,c),S;try{S=Q(u)}catch{continue}if(!S.isDirectory())continue;let g=P(u);!g||g.status!=="running"||f(String(c),u)}}catch(t){console.warn(`[zibby browser-test run-index interrupt] ${t.message}`)}}function Te(e){j(e)}function _e(e){Z(e)}function Ee(e){return Y(e)}export{Ee as createCliRunIndexPipelineProgressAppender,_e as postCliInterruptedRunIndex,Te as postCliRunIndex};
1
+ import{existsSync as P,readdirSync as F,statSync as Q}from"fs";import{join as a,relative as B,sep as x,resolve as m}from"path";import{appendFileSync as H,readFileSync as z,existsSync as _,mkdirSync as $}from"node:fs";import{join as h}from"node:path";import{DEFAULT_OUTPUT_BASE as E}from"@zibby/agent-workflow";var b="run-index.jsonl";function A(e,t=E){let n=h(e,t);return h(n,b)}function w(e){if(!e||!e.sessionId)return;let t=e.cwd||process.cwd(),n=e.outputBase||E,s=h(t,n);_(s)||$(s,{recursive:!0});let r=h(s,b),i=`${JSON.stringify(e)}
2
+ `;H(r,i,"utf8")}function D(e){if(!e||!_(e))return[];let t;try{t=z(e,"utf8")}catch{return[]}let n=[];for(let s of t.split(`
3
+ `)){let r=s.trim();if(r)try{n.push(JSON.parse(r))}catch{}}return n}import{existsSync as J,mkdirSync as K,readFileSync as W,readdirSync as de,statSync as fe,writeFileSync as G}from"node:fs";import{join as V}from"node:path";var X="zibby-run-state.json";function M(e){return V(e,X)}function R(e){if(!e||typeof e!="string")return null;let t=M(e);if(!J(t))return null;try{let n=W(t,"utf8"),s=JSON.parse(n);return s&&typeof s=="object"?s:null}catch{return null}}function v(e,t){if(!e||typeof e!="string")return;try{K(e,{recursive:!0})}catch{return}let s={...R(e)||{v:1},...t,v:1,updatedAt:Date.now()};try{G(M(e),`${JSON.stringify(s)}
4
+ `,"utf8")}catch(r){console.warn(`[zibby run-state] ${r.message}`)}}function q(e){return e?.recordKind==="progress"}function O(e){let t=Number(e)||0;return t<=0?0:t<1e12?t*1e3:t}function C(e,t={}){let n=t.maxProgressAgeMs!=null&&Number.isFinite(t.maxProgressAgeMs)?Math.max(0,t.maxProgressAgeMs):21e5,s=typeof t.now=="number"?t.now:Date.now(),{summary:r,progress:i}=e||{};if(!i)return!1;let o=O(i.ts);if(n>0&&o>0&&s-o>n)return!1;if(!r)return o>0;let d=O(r.ts);return o>d}function k(e){let t=new Map;for(let n of e||[]){if(!n?.sessionId)continue;let s=t.get(n.sessionId);s||(s={summary:null,progress:null});let r=Number(n.ts)||0;q(n)?(!s.progress||r>=(Number(s.progress.ts)||0))&&(s.progress=n):(!s.summary||r>=(Number(s.summary.ts)||0))&&(s.summary=n),t.set(n.sessionId,s)}return t}import{DEFAULT_OUTPUT_BASE as I,SESSIONS_DIR as y}from"@zibby/agent-workflow";var N=Object.freeze(["preflight","execute_live","generate_script"]);function T(e){let t=process.env.ZIBBY_STUDIO_TEST_CASE_ID;return t!=null&&String(t).trim()!==""?String(t).trim():e!=null?String(e):""}var ee=[a("generate_script","generated-test.spec.js"),a("generate_script","generated-test.spec.ts"),a("generate_script","playwright.spec.ts"),a("generate_script","test.spec.ts")];function te(e){let t=[a(e,"execute_live","videos"),a(e,"execute_live"),e];for(let n of t){if(!P(n))continue;let s;try{s=F(n)}catch{continue}let r=s.find(i=>i.endsWith(".webm"));if(r)return a(n,r)}return null}function ne(e){let t=[a(e,"execute_live","events.json"),a(e,"events.json")];for(let n of t)if(P(n))return n;return null}function se(e){for(let t of ee){let n=a(e,t);if(P(n))return n}return null}function re(e){return!e||!P(e)?{videoPathAbs:null,eventsPathAbs:null,scriptPathAbs:null}:{videoPathAbs:te(e),eventsPathAbs:ne(e),scriptPathAbs:se(e)}}function j(e){let t=e.cwd||process.cwd(),n=e.outputBase||I,i=((e.result||{}).state||{}).sessionPath;if(!i||typeof i!="string")return null;let o=i.split(/[/\\]/).filter(Boolean).pop();if(!o)return null;let{videoPathAbs:d,eventsPathAbs:f,scriptPathAbs:l}=re(i),p=u=>{if(!u)return null;try{return B(t,u).split(x).join("/")}catch{return null}},c=null;if(e.specPath)try{let u=m(t,e.specPath);c=B(t,u).split(x).join("/")}catch{c=String(e.specPath).split(x).join("/")}return{v:1,recordKind:"summary",ts:Date.now(),sessionId:o,status:e.status??(e.success?"completed":"failed"),cwd:t,outputBase:n,sessionPathAbs:i,sessionDirRel:p(i),videoPathAbs:d||null,eventsPathAbs:f||null,scriptPathAbs:l||null,videoRel:p(d),eventsRel:p(f),scriptRel:p(l),specRel:c,source:process.env.ZIBBY_RUN_SOURCE||"cli",studioTestCaseId:T(o)||null,errorMessage:e.errorMessage||null}}function U({cwd:e,config:t,result:n,success:s,specPath:r,errorMessage:i}){try{let o=j({cwd:e||process.cwd(),result:n,success:s,outputBase:t?.paths?.output||I,specPath:r,errorMessage:i});o&&(w(o),o.sessionPathAbs&&v(o.sessionPathAbs,{sessionId:o.sessionId,studioTestCaseId:o.studioTestCaseId||o.sessionId,status:o.status,activeNode:null,activeStageIndex:null,errorMessage:o.errorMessage||null,runSource:o.source||"cli",cwd:o.cwd,outputBase:o.outputBase,sessionPathAbs:o.sessionPathAbs}))}catch(o){console.warn(`[zibby browser-test run-index] ${o.message}`)}}function oe({sessionPath:e,sessionId:t,cwd:n,outputBase:s=I}={}){let r=n||process.cwd(),i=s||I,o=t!=null&&String(t).trim()!==""?String(t).trim():null,d=process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true",f=process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim();if(d&&f)return m(f);let l=e&&String(e).trim();if(l)return m(l);let p=process.env.ZIBBY_SESSIONS_ROOT&&String(process.env.ZIBBY_SESSIONS_ROOT).trim();return p&&o?m(a(p,o)):process.env.ZIBBY_SESSION_PATH&&String(process.env.ZIBBY_SESSION_PATH).trim()?m(String(process.env.ZIBBY_SESSION_PATH).trim()):m(a(r,i,y,o||"invalid"))}function ie(e){try{let t=e?.currentNode;if(!t||!N.includes(t))return;let n=e.sessionPath,s=e.sessionId||n&&String(n).split(/[/\\]/).filter(Boolean).pop()||null;if(!s)return;let r=e.cwd||process.cwd(),i=e.outputBase||I,o=N.indexOf(t),d=e?.specPath!=null?String(e.specPath).trim():"",f=e?.taskDescription!=null?String(e.taskDescription):"",l=null;if(d)try{let c=m(r,d);l=B(r,c).split(x).join("/")}catch{l=d.split(x).join("/")}let p=oe({sessionPath:n,sessionId:s,cwd:r,outputBase:i});w({v:1,recordKind:"progress",ts:Date.now(),sessionId:s,cwd:r,outputBase:i,sessionPathAbs:p,activeNode:t,activeStageIndex:o,specRel:l,taskDescription:f||null,studioTestCaseId:T(s)||null,source:process.env.ZIBBY_RUN_SOURCE||"cli"}),v(p,{sessionId:s,studioTestCaseId:T(s)||s,status:"running",activeNode:t,activeStageIndex:o,sessionPathAbs:p,cwd:r,outputBase:i,specPath:l||null,task:f||null,taskDescription:f||null,runSource:process.env.ZIBBY_RUN_SOURCE||"cli",pid:typeof process.pid=="number"?process.pid:null})}catch(t){console.warn(`[zibby browser-test run-index progress] ${t.message}`)}}function Y({cwd:e,config:t}={}){let n=e||process.cwd(),s=t?.paths?.output||I;return r=>{ie({cwd:r?.cwd||n,outputBase:r?.outputBase||s,sessionPath:r?.sessionPath,sessionId:r?.sessionId,currentNode:r?.currentNode,specPath:r?.specPath,taskDescription:r?.taskDescription})}}function Z(e={}){try{let t=e.cwd||process.cwd(),n=e.config?.paths?.output||e.outputBase||I,s=A(t,n),r=D(s),i=k(r),o=new Set,d=e.errorMessage||"Run stopped (SIGINT/SIGTERM) before a normal summary was written.",f=(c,u)=>{if(!c||!u||o.has(c))return;o.add(c);let S=j({cwd:t,outputBase:n,result:{state:{sessionPath:u}},success:!1,specPath:null,status:"interrupted",errorMessage:d});S&&(w(S),v(u,{sessionId:c,studioTestCaseId:S.studioTestCaseId||c,status:"interrupted",activeNode:null,activeStageIndex:null,errorMessage:S.errorMessage||null,runSource:S.source||"cli",cwd:t,outputBase:n,sessionPathAbs:u}))};for(let[c,u]of i){if(!C(u))continue;let S=u.progress;if(!S)continue;let g=String(c),L=S.sessionPathAbs&&String(S.sessionPathAbs)||a(t,n,y,g);f(g,L)}let l=a(t,n,y);if(!P(l))return;let p;try{p=F(l)}catch{return}for(let c of p){let u=a(l,c),S;try{S=Q(u)}catch{continue}if(!S.isDirectory())continue;let g=R(u);!g||g.status!=="running"||f(String(c),u)}}catch(t){console.warn(`[zibby browser-test run-index interrupt] ${t.message}`)}}function Te(e){U(e)}function _e(e){Z(e)}function Ee(e){return Y(e)}export{Ee as createCliRunIndexPipelineProgressAppender,_e as postCliInterruptedRunIndex,Te as postCliRunIndex};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/core",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Core test automation engine with multi-agent and multi-MCP support",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -69,7 +69,7 @@
69
69
  "node": ">=18.0.0"
70
70
  },
71
71
  "dependencies": {
72
- "@zibby/agent-workflow": "^0.2.0",
72
+ "@zibby/agent-workflow": "^0.3.0",
73
73
  "@anthropic-ai/claude-agent-sdk": "^0.2.104",
74
74
  "@anthropic-ai/sdk": "^0.88.0",
75
75
  "@modelcontextprotocol/sdk": "^1.29.0",
@@ -216,9 +216,11 @@ export function resolveBrowserTestPipelineSessionPathAbs({
216
216
  ? String(sessionId).trim()
217
217
  : null;
218
218
 
219
- const studio = process.env.ZIBBY_RUN_SOURCE === 'studio';
219
+ const pinned =
220
+ process.env.ZIBBY_PIN_SESSION_PATH === '1' ||
221
+ process.env.ZIBBY_PIN_SESSION_PATH === 'true';
220
222
  const envSession = process.env.ZIBBY_SESSION_PATH && String(process.env.ZIBBY_SESSION_PATH).trim();
221
- if (studio && envSession) {
223
+ if (pinned && envSession) {
222
224
  return pathResolve(envSession);
223
225
  }
224
226