@zibby/cli 0.1.52 → 0.1.54

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,69 +1,69 @@
1
- import{invokeAgent as xe,getAgentStrategy as ve,getSkill as $t}from"@zibby/core";import{existsSync as gt,readFileSync as oe,readdirSync as Te}from"fs";import{resolve as lt,join as Dt,dirname as Ce,basename as Ie}from"path";import{createInterface as Pe,moveCursor as M,cursorTo as B,clearLine as G,emitKeypressEvents as Ae}from"readline";import{fileURLToPath as Ee}from"url";import{homedir as Le}from"os";import e from"chalk";import{highlight as ne}from"cli-highlight";import Me from"dotenv";import{getSessionToken as Wt,getUserInfo as Ne,getProjects as Oe,saveSessionToken as Be,saveUserInfo as Re,clearSession as Ue,saveProxyUrl as Fe,getProxyUrl as je,getMem0ProxyUrl as De,saveMem0ProxyUrl as We}from"../config/config.js";import{getApiUrl as re}from"../config/environments.js";import{loadActiveSkills as Ye,loadChatHistory as He,saveActiveSkills as It,saveChatHistory as Pt}from"./chat-session-store.js";import{buildReliabilityInstruction as ze}from"./agent-reliability.js";const Je=Ee(import.meta.url),Ge=Ce(Je),Ze=JSON.parse(oe(Dt(Ge,"../../package.json"),"utf-8")),ie=30,qe=54,Ke=18e3,ce=12e3,ae=42e3;function Ve(n){return new Promise(t=>setTimeout(t,n))}const At=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Yt=[{cmd:"/help",desc:"Show this help"},{cmd:"/skills",desc:"List active & available skills"},{cmd:"/history",desc:"Show conversation history (--all or -n 50)"},{cmd:"/clear",desc:"Clear conversation history"},{cmd:"/memory",desc:"View stored memories, tasks, sessions"},{cmd:"/exit",desc:"Exit the chat"},{cmd:"/quit",desc:"Exit the chat"}];function le(){let n=0,t="thinking...";const s=setInterval(()=>{const h=e.cyan(At[n%At.length]),k=n%3,v=k===0?e.white(".")+e.gray(".")+e.dim("."):k===1?e.dim(".")+e.white(".")+e.gray("."):e.gray(".")+e.dim(".")+e.white("."),C=t.replace(/\.+$/,""),I=` ${h} ${e.gray(C)}${v}`;process.stdout.write(`\r${" ".repeat(80)}\r${I}`),n++},300),o=()=>{clearInterval(s),process.stdout.write(`\r${" ".repeat(80)}\r`)};return o.setLabel=h=>{t=h},o}function Us(n){const t=n?.agent;return t?t.provider?t.provider:t.gemini?"gemini":t.codex?"codex":t.claude?"claude":t.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}function Xe(n){return n.slice(-ie).map(t=>`${t.role==="human"?"H":"AI"}: ${t.content}`).join(`
2
- `)}function Fs(n,t,s){let o=n;return t.length>0&&(o+=`
1
+ import{invokeAgent as xe,getAgentStrategy as ve,getSkill as $t}from"@zibby/core";import{existsSync as gt,readFileSync as oe,readdirSync as Te}from"fs";import{resolve as lt,join as Dt,dirname as Ce,basename as Ie}from"path";import{createInterface as Pe,moveCursor as M,cursorTo as B,clearLine as G,emitKeypressEvents as Ae}from"readline";import{fileURLToPath as Ee}from"url";import{homedir as Le}from"os";import e from"chalk";import{highlight as ne}from"cli-highlight";import Me from"dotenv";import{getSessionToken as Wt,getUserInfo as Ne,getProjects as Oe,saveSessionToken as Be,saveUserInfo as Re,clearSession as Ue,saveProxyUrl as Fe,getProxyUrl as je,getMem0ProxyUrl as De,saveMem0ProxyUrl as We}from"../config/config.js";import{getApiUrl as re}from"../config/environments.js";import{loadActiveSkills as Ye,loadChatHistory as He,saveActiveSkills as It,saveChatHistory as Pt}from"./chat-session-store.js";import{buildReliabilityInstruction as ze}from"./agent-reliability.js";const Je=Ee(import.meta.url),Ge=Ce(Je),qe=JSON.parse(oe(Dt(Ge,"../../package.json"),"utf-8")),ie=30,Ze=54,Ke=18e3,ce=12e3,ae=42e3;function Ve(o){return new Promise(t=>setTimeout(t,o))}const At=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Yt=[{cmd:"/help",desc:"Show this help"},{cmd:"/skills",desc:"List active & available skills"},{cmd:"/history",desc:"Show conversation history (--all or -n 50)"},{cmd:"/clear",desc:"Clear conversation history"},{cmd:"/memory",desc:"View stored memories, tasks, sessions"},{cmd:"/exit",desc:"Exit the chat"},{cmd:"/quit",desc:"Exit the chat"}];function le(){let o=0,t="thinking...";const s=setInterval(()=>{const l=e.cyan(At[o%At.length]),k=o%3,v=k===0?e.white(".")+e.gray(".")+e.dim("."):k===1?e.dim(".")+e.white(".")+e.gray("."):e.gray(".")+e.dim(".")+e.white("."),C=t.replace(/\.+$/,""),I=` ${l} ${e.gray(C)}${v}`;process.stdout.write(`\r${" ".repeat(80)}\r${I}`),o++},300),r=()=>{clearInterval(s),process.stdout.write(`\r${" ".repeat(80)}\r`)};return r.setLabel=l=>{t=l},r}function Us(o){const t=o?.agent;return t?t.provider?t.provider:t.gemini?"gemini":t.codex?"codex":t.claude?"claude":t.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}function Xe(o){return o.slice(-ie).map(t=>`${t.role==="human"?"H":"AI"}: ${t.content}`).join(`
2
+ `)}function Fs(o,t,s){let r=o;return t.length>0&&(r+=`
3
3
 
4
- ${Xe(t)}`),o+=`
4
+ ${Xe(t)}`),r+=`
5
5
  H: ${s}
6
- AI:`,o}function Qe(n){const t=n.filter(s=>!process.env[s]);return{ok:t.length===0,missing:t}}function ts(n){const t=lt(n,".zibby.config.mjs");if(!gt(t))return{};try{return import(t).then(s=>s.default||{})}catch{return{}}}async function es(n){const t=lt(n,".zibby","chat.mjs");if(gt(t))try{const o=await import(t);if(o.CHAT_CONFIG||o.default)return o.CHAT_CONFIG||o.default}catch{}const s=lt(Le(),".zibby","chat.mjs");if(s!==t&&gt(s))try{const o=await import(s);if(o.CHAT_CONFIG||o.default)return o.CHAT_CONFIG||o.default}catch{}try{const o=await import("@zibby/core/templates/browser-test-automation/chat.mjs");return o.CHAT_CONFIG||o.default||{}}catch{return{systemPrompt:"You are Zibby, a friendly AI assistant for test automation.",skills:[]}}}function ue(n){try{const t=lt(n,".zibby","commands");return gt(t)?Te(t).filter(s=>s.toLowerCase().endsWith(".md")).sort((s,o)=>s.localeCompare(o)):[]}catch{return[]}}function ss(n,t){const s=String(t||"").trim();if(!s.startsWith("/"))return s;const[o,...h]=s.split(/\s+/),k=h.join(" ").trim(),v=o.slice(1);if(!v)return s;const C=v.toLowerCase().endsWith(".md")?[v]:[v,`${v}.md`],I=lt(n,".zibby","commands"),U=C.find(R=>gt(Dt(I,R)));if(!U)return s;try{const R=oe(Dt(I,U),"utf-8").trim();return k?`${R}
6
+ AI:`,r}function Qe(o){const t=o.filter(s=>!process.env[s]);return{ok:t.length===0,missing:t}}function ts(o){const t=lt(o,".zibby.config.mjs");if(!gt(t))return{};try{return import(t).then(s=>s.default||{})}catch{return{}}}async function es(o){const t=lt(o,".zibby","chat.mjs");if(gt(t)){const l=await import(t);if(l.CHAT_CONFIG||l.default)return l.CHAT_CONFIG||l.default}const s=lt(Le(),".zibby","chat.mjs");if(s!==t&&gt(s)){const l=await import(s);if(l.CHAT_CONFIG||l.default)return l.CHAT_CONFIG||l.default}const r=await import("@zibby/core/templates/browser-test-automation/chat.mjs");return r.CHAT_CONFIG||r.default||{}}function ue(o){try{const t=lt(o,".zibby","commands");return gt(t)?Te(t).filter(s=>s.toLowerCase().endsWith(".md")).sort((s,r)=>s.localeCompare(r)):[]}catch{return[]}}function ss(o,t){const s=String(t||"").trim();if(!s.startsWith("/"))return s;const[r,...l]=s.split(/\s+/),k=l.join(" ").trim(),v=r.slice(1);if(!v)return s;const C=v.toLowerCase().endsWith(".md")?[v]:[v,`${v}.md`],I=lt(o,".zibby","commands"),U=C.find(R=>gt(Dt(I,R)));if(!U)return s;try{const R=oe(Dt(I,U),"utf-8").trim();return k?`${R}
7
7
 
8
- ${k}`:R}catch{return s}}function os(n){const t=n.slice(-ie),s=[];let o=0;for(let h=t.length-1;h>=0;h--){const k=t[h],v=String(k?.content||""),C=k?.role==="human"?"user":"assistant",I=v.length;if(s.length>=6&&o+I>Ke)break;s.push({role:C,content:v}),o+=I}return s.reverse()}function _t(n,t){const s=String(n||"");return s.length<=t?s:`${s.slice(0,Math.max(0,t-24))}
8
+ ${k}`:R}catch{return s}}function os(o){const t=o.slice(-ie),s=[];let r=0;for(let l=t.length-1;l>=0;l--){const k=t[l],v=String(k?.content||""),C=k?.role==="human"?"user":"assistant",I=v.length;if(s.length>=6&&r+I>Ke)break;s.push({role:C,content:v}),r+=I}return s.reverse()}function _t(o,t){const s=String(o||"");return s.length<=t?s:`${s.slice(0,Math.max(0,t-24))}
9
9
 
10
- [truncated for proxy size]`}function Ht(n){return n.reduce((t,s)=>t+String(s?.content||"").length+64,0)}function ns(n){let t=[...n];if(t.length===0||(t[0]?.role==="system"&&(t[0]={...t[0],content:_t(t[0].content,ce)}),Ht(t)<=ae))return t;const s=t[0],o=t[t.length-1],h=t.slice(1,-1).slice(-4).map(k=>({...k,content:_t(k.content,2500)}));return t=[s,...h,o],Ht(t)<=ae||(t=[{...s,content:_t(s?.content,6e3)},{...o,content:_t(o?.content,8e3)}]),t}function rs(n){const t=[];for(const s of n){const o=$t(s),h=String(o?.description||"").trim();if(!h){t.push(`- ${s}`);continue}t.push(`- ${s}: ${Et(h,80)}`)}return t.length===0?"":`## Active skills (call get_skill_context before first use)
10
+ [truncated for proxy size]`}function Ht(o){return o.reduce((t,s)=>t+String(s?.content||"").length+64,0)}function ns(o){let t=[...o];if(t.length===0||(t[0]?.role==="system"&&(t[0]={...t[0],content:_t(t[0].content,ce)}),Ht(t)<=ae))return t;const s=t[0],r=t[t.length-1],l=t.slice(1,-1).slice(-4).map(k=>({...k,content:_t(k.content,2500)}));return t=[s,...l,r],Ht(t)<=ae||(t=[{...s,content:_t(s?.content,6e3)},{...r,content:_t(r?.content,8e3)}]),t}function rs(o){const t=[];for(const s of o){const r=$t(s),l=String(r?.description||"").trim();if(!l){t.push(`- ${s}`);continue}t.push(`- ${s}: ${Et(l,80)}`)}return t.length===0?"":`## Active skills (call get_skill_context before first use)
11
11
  ${t.join(`
12
12
  `)}`}const pe={cli_plain:["## Response format for this channel","- Output plain terminal text with optional fenced code blocks.","- Use fenced code blocks (```language) when showing code or config. Always include the language tag.","- Outside of code blocks, do NOT use Markdown syntax (no **bold**, __underline__, headings, inline backticks, or markdown tables).","- Keep responses concise and readable in a terminal.","- Write in natural, conversational English. Avoid dumping raw JSON, run IDs, or technical jargon.",'- When reporting test results: summarize in plain language (e.g. "Both tests finished \u2014 the checkbox test passed but the login test failed because..."). Include ticket keys but skip internal run IDs unless the user asks.',"- When something fails, explain the root cause simply and suggest a fix."].join(`
13
- `)};function is(n={},t={}){const s=String(t.outputProfile||process.env.ZIBBY_OUTPUT_PROFILE||n.outputProfile||"cli_plain").trim(),o=n?.outputProfiles?.[s];return typeof o=="string"&&o.trim()?o.trim():o&&typeof o.instruction=="string"&&o.instruction.trim()?o.instruction.trim():pe[s]||pe.cli_plain}function Et(n,t){const s=String(n??"");return s.length<=t?s:t<=1?s.slice(0,t):`${s.slice(0,t-1)}\u2026`}function cs(){return!1}function js(n){return n}function as(n){const t=/^```(\w*)\n([\s\S]*?)^```$/gm;return n.replace(t,(s,o,h)=>{const k=h.replace(/\n$/,"");try{const v=o?ne(k,{language:o,ignoreIllegals:!0}):ne(k,{ignoreIllegals:!0}),C=e.gray("\u2500".repeat(Math.min(process.stdout.columns-6||54,72))),I=o?e.dim(` ${o}`):"";return`${C}${I}
13
+ `)};function is(o={},t={}){const s=String(t.outputProfile||process.env.ZIBBY_OUTPUT_PROFILE||o.outputProfile||"cli_plain").trim(),r=o?.outputProfiles?.[s];return typeof r=="string"&&r.trim()?r.trim():r&&typeof r.instruction=="string"&&r.instruction.trim()?r.instruction.trim():pe[s]||pe.cli_plain}function Et(o,t){const s=String(o??"");return s.length<=t?s:t<=1?s.slice(0,t):`${s.slice(0,t-1)}\u2026`}function cs(){return!1}function js(o){return o}function as(o){const t=/^```(\w*)\n([\s\S]*?)^```$/gm;return o.replace(t,(s,r,l)=>{const k=l.replace(/\n$/,"");try{const v=r?ne(k,{language:r,ignoreIllegals:!0}):ne(k,{ignoreIllegals:!0}),C=e.gray("\u2500".repeat(Math.min(process.stdout.columns-6||54,72))),I=r?e.dim(` ${r}`):"";return`${C}${I}
14
14
  ${v}
15
- ${C}`}catch{return k}})}function zt(){const n=Number(process.stdout?.columns)||0,t=n>8?Math.max(30,n-4):qe;return` ${"\u2500".repeat(t)}`}function de(n=[]){const t=Yt.map(o=>({cmd:o.cmd,source:"builtin",name:o.cmd.slice(1),desc:o.desc})),s=n.map(o=>({cmd:`/${o}`,source:"template",name:o,desc:"Command template"}));return[...t,...s]}function ls(n,t){const s=String(n||""),o=Number.isFinite(t)?t:s.length;return!(!s.startsWith("/")||o!==s.length||s.includes(" "))}function us({userName:n,cwd:t,projectName:s,restoredCount:o,skillsLine:h}){const k=Number(process.stdout?.columns)||0,v=Math.max(40,Math.min(k-8,100)),C=Math.max(20,Math.floor((v-3)*.55)),I=v-C-3,U=n||"there",R=s||"No project linked",ht=Ie(t||process.cwd()),W=[`Restored ${o} messages from previous session.`,"",h],rt=["Workspace details","",`v${Ze.version} | Hi, ${U}`,`Company: ${R}`,`Directory: ~/${ht}`,`Path: ${t}`,"","Use /help for commands"],E=Math.max(W.length,rt.length),V=(()=>{if(W.length>=E)return W;const F=Math.floor((E-W.length)/2),st=E-W.length-F;return[...Array(F).fill(""),...W,...Array(st).fill("")]})(),H="\u2500",L=` \u250C${H.repeat(C+2)}\u252C${H.repeat(I+2)}\u2510`,et=` \u2514${H.repeat(C+2)}\u2534${H.repeat(I+2)}\u2518`;console.log(e.gray(L));for(let F=0;F<E;F++){const st=Et(V[F]||"",C),it=Et(rt[F]||"",I),yt=" ".repeat(Math.max(0,C-st.length)),l=" ".repeat(Math.max(0,I-it.length)),w=` \u2502 ${st}${yt} \u2502 ${it}${l} \u2502`;console.log(e.gray(w))}console.log(e.gray(et)),console.log("")}function ps(){process.stdout?.isTTY&&(M(process.stdout,0,-2),B(process.stdout,4))}function ds(n){const t=!!(process.stdout?.isTTY&&process.stdin?.isTTY);let s=!1,o=!1,h=!1,k=null,v=0,C=0,I=0;function U(){return e.gray(zt())}function R(){k&&(clearInterval(k),k=null)}function ht(l){!t||!s||!o||!h||(process.stdout.write("\x1B7"),M(process.stdout,0,-2),B(process.stdout,0),G(process.stdout,0),process.stdout.write(` ${l}`),process.stdout.write("\x1B8"))}function W(){if(!(!t||!s)&&C!==0){process.stdout.write("\x1B7"),M(process.stdout,0,2);for(let l=0;l<C;l++)B(process.stdout,0),G(process.stdout,0),l<C-1&&M(process.stdout,0,1);process.stdout.write("\x1B8"),C=0,o&&rt()}}function rt(){!t||!s||!o||(process.stdout.write("\x1B7"),M(process.stdout,0,1),B(process.stdout,0),G(process.stdout,0),process.stdout.write(U()),process.stdout.write("\x1B8"))}function E(l,w){if(!t||!s||!o)return;W();const c=l.slice(0,6);if(c.length!==0){M(process.stdout,0,1);for(let y=0;y<c.length;y++)process.stdout.write(`
16
- `);M(process.stdout,0,-(1+c.length)),process.stdout.write("\x1B7"),M(process.stdout,0,2);for(let y=0;y<c.length;y++){B(process.stdout,0),G(process.stdout,0);const Z=y===w?e.cyan("\u203A"):" ",f=y===w?e.white(c[y]):e.gray(c[y]);process.stdout.write(` ${Z} /${f}`),y<c.length-1&&M(process.stdout,0,1)}process.stdout.write("\x1B8"),C=c.length,rt()}}function V(){if(!t||!s||!o)return;W();const l=process.stdout.columns||80,w=I>0?Math.ceil(I/l):1;B(process.stdout,0),M(process.stdout,0,-w),h&&M(process.stdout,0,-2),process.stdout.write("\x1B[J"),o=!1}function H(l={}){const w=l.preserveInput===!0;if(!t){n.prompt();return}w||(n.line="",n.cursor=0),I=zt().length;const c=U();process.stdout.write(`${c}
17
- `),n.prompt(),process.stdout.write(`
15
+ ${C}`}catch{return k}})}function zt(){const o=Number(process.stdout?.columns)||0,t=o>8?Math.max(30,o-4):Ze;return` ${"\u2500".repeat(t)}`}function de(o=[]){const t=Yt.map(r=>({cmd:r.cmd,source:"builtin",name:r.cmd.slice(1),desc:r.desc})),s=o.map(r=>({cmd:`/${r}`,source:"template",name:r,desc:"Command template"}));return[...t,...s]}function ls(o,t){const s=String(o||""),r=Number.isFinite(t)?t:s.length;return!(!s.startsWith("/")||r!==s.length||s.includes(" "))}function us({userName:o,cwd:t,projectName:s,restoredCount:r,skillsLine:l}){const k=Number(process.stdout?.columns)||0,v=Math.max(40,Math.min(k-8,100)),C=Math.max(20,Math.floor((v-3)*.55)),I=v-C-3,U=o||"there",R=s||"No project linked",ht=Ie(t||process.cwd()),W=[`Restored ${r} messages from previous session.`,"",l],rt=["Workspace details","",`v${qe.version} | Hi, ${U}`,`Company: ${R}`,`Directory: ~/${ht}`,`Path: ${t}`,"","Use /help for commands"],E=Math.max(W.length,rt.length),V=(()=>{if(W.length>=E)return W;const F=Math.floor((E-W.length)/2),st=E-W.length-F;return[...Array(F).fill(""),...W,...Array(st).fill("")]})(),H="\u2500",L=` \u250C${H.repeat(C+2)}\u252C${H.repeat(I+2)}\u2510`,et=` \u2514${H.repeat(C+2)}\u2534${H.repeat(I+2)}\u2518`;console.log(e.gray(L));for(let F=0;F<E;F++){const st=Et(V[F]||"",C),it=Et(rt[F]||"",I),yt=" ".repeat(Math.max(0,C-st.length)),u=" ".repeat(Math.max(0,I-it.length)),w=` \u2502 ${st}${yt} \u2502 ${it}${u} \u2502`;console.log(e.gray(w))}console.log(e.gray(et)),console.log("")}function ps(){process.stdout?.isTTY&&(M(process.stdout,0,-2),B(process.stdout,4))}function ds(o){const t=!!(process.stdout?.isTTY&&process.stdin?.isTTY);let s=!1,r=!1,l=!1,k=null,v=0,C=0,I=0;function U(){return e.gray(zt())}function R(){k&&(clearInterval(k),k=null)}function ht(u){!t||!s||!r||!l||(process.stdout.write("\x1B7"),M(process.stdout,0,-2),B(process.stdout,0),G(process.stdout,0),process.stdout.write(` ${u}`),process.stdout.write("\x1B8"))}function W(){if(!(!t||!s)&&C!==0){process.stdout.write("\x1B7"),M(process.stdout,0,2);for(let u=0;u<C;u++)B(process.stdout,0),G(process.stdout,0),u<C-1&&M(process.stdout,0,1);process.stdout.write("\x1B8"),C=0,r&&rt()}}function rt(){!t||!s||!r||(process.stdout.write("\x1B7"),M(process.stdout,0,1),B(process.stdout,0),G(process.stdout,0),process.stdout.write(U()),process.stdout.write("\x1B8"))}function E(u,w){if(!t||!s||!r)return;W();const c=u.slice(0,6);if(c.length!==0){M(process.stdout,0,1);for(let y=0;y<c.length;y++)process.stdout.write(`
16
+ `);M(process.stdout,0,-(1+c.length)),process.stdout.write("\x1B7"),M(process.stdout,0,2);for(let y=0;y<c.length;y++){B(process.stdout,0),G(process.stdout,0);const q=y===w?e.cyan("\u203A"):" ",m=y===w?e.white(c[y]):e.gray(c[y]);process.stdout.write(` ${q} /${m}`),y<c.length-1&&M(process.stdout,0,1)}process.stdout.write("\x1B8"),C=c.length,rt()}}function V(){if(!t||!s||!r)return;W();const u=process.stdout.columns||80,w=I>0?Math.ceil(I/u):1;B(process.stdout,0),M(process.stdout,0,-w),l&&M(process.stdout,0,-2),process.stdout.write("\x1B[J"),r=!1}function H(u={}){const w=u.preserveInput===!0;if(!t){o.prompt();return}w||(o.line="",o.cursor=0),I=zt().length;const c=U();process.stdout.write(`${c}
17
+ `),o.prompt(),process.stdout.write(`
18
18
  ${c}
19
- `),ps(),o=!0}function L(){if(!t||!s||!o)return;const l=process.stdout.columns||80,w=I>0?Math.ceil(I/l):1,c=U();process.stdout.write("\x1B7"),M(process.stdout,0,-w);for(let y=0;y<w;y++)B(process.stdout,0),G(process.stdout,0),y<w-1&&M(process.stdout,0,1);B(process.stdout,0),process.stdout.write(c),M(process.stdout,0,2),B(process.stdout,0),G(process.stdout,0),process.stdout.write(c);for(let y=1;y<w;y++)M(process.stdout,0,1),B(process.stdout,0),G(process.stdout,0);process.stdout.write("\x1B8"),I=zt().length}function et(){if(!t||!s||!o)return;const l=(()=>{if(typeof n.getCursorPos!="function")return 0;try{return Math.max(0,Number(n.getCursorPos()?.rows||0))}catch{return 0}})();process.stdout.write("\x1B7"),M(process.stdout,0,-(l+1)),B(process.stdout,0),G(process.stdout,0),process.stdout.write(U()),M(process.stdout,0,l+2),B(process.stdout,0),G(process.stdout,0),process.stdout.write(U()),process.stdout.write("\x1B8")}function F(l){R(),V(),console.log();const w=String(l??"").replace(/\r/g,"").split(`
20
- `);for(;w.length>0&&w[w.length-1]==="";)w.pop();for(const c of w)console.log(c?` ${c}`:"");h=!1}function st(l){const w=String(l??"").replace(/\r/g,"").split(`
19
+ `),ps(),r=!0}function L(){if(!t||!s||!r)return;const u=process.stdout.columns||80,w=I>0?Math.ceil(I/u):1,c=U();process.stdout.write("\x1B7"),M(process.stdout,0,-w);for(let y=0;y<w;y++)B(process.stdout,0),G(process.stdout,0),y<w-1&&M(process.stdout,0,1);B(process.stdout,0),process.stdout.write(c),M(process.stdout,0,2),B(process.stdout,0),G(process.stdout,0),process.stdout.write(c);for(let y=1;y<w;y++)M(process.stdout,0,1),B(process.stdout,0),G(process.stdout,0);process.stdout.write("\x1B8"),I=zt().length}function et(){if(!t||!s||!r)return;const u=(()=>{if(typeof o.getCursorPos!="function")return 0;try{return Math.max(0,Number(o.getCursorPos()?.rows||0))}catch{return 0}})();process.stdout.write("\x1B7"),M(process.stdout,0,-(u+1)),B(process.stdout,0),G(process.stdout,0),process.stdout.write(U()),M(process.stdout,0,u+2),B(process.stdout,0),G(process.stdout,0),process.stdout.write(U()),process.stdout.write("\x1B8")}function F(u){R(),V(),console.log();const w=String(u??"").replace(/\r/g,"").split(`
20
+ `);for(;w.length>0&&w[w.length-1]==="";)w.pop();for(const c of w)console.log(c?` ${c}`:"");l=!1}function st(u){const w=String(u??"").replace(/\r/g,"").split(`
21
21
  `);w.length===0&&w.push("");const c=[];for(const y of w)c.push(e.bgGray.white(` ${y||" "} `));return c.join(`
22
- `)}function it(){R();const l=()=>e.gray(`${At[v%At.length]} thinking`);if(!t){console.log(` ${l()}`),h=!0;return}W(),V(),console.log(),console.log(` ${l()}`),H({preserveInput:!0}),h=!0,v+=1,k=setInterval(()=>{h&&(ht(l()),v+=1)},120)}function yt(l){R();const w=String(l??"").replace(/\r/g,"").replace(/⎿/g,"");if(!h){F(w);return}V(),console.log();const c=w.split(`
23
- `);for(;c.length>0&&c[c.length-1]==="";)c.pop();for(const y of c)console.log(y?` ${y}`:"");console.log(),h=!1}return{enabled:t,mount(){if(!s){if(!t){n.prompt(),s=!0;return}s=!0,H()}},refreshPrompt(l={}){if(t&&s){o&&V(),H(l);return}n.prompt()},pushSystem(l){F(l)},pushUser(l){F(st(l))},pushAssistant(l){yt(l)},showAssistantLoading:it,dismissTransientLoading(){R(),h&&t&&s&&o&&(process.stdout.write("\x1B7"),M(process.stdout,0,-2),B(process.stdout,0),G(process.stdout,0),M(process.stdout,0,-1),B(process.stdout,0),G(process.stdout,0),process.stdout.write("\x1B8")),h=!1},touchInputFrame:et,handleResize:L,showCommandDropdown:E,clearCommandDropdown:W}}function fs(){console.log(""),console.log(e.cyan(" Available commands:"));for(const n of Yt)console.log(e.white(` ${n.cmd.padEnd(10)} `)+e.gray(n.desc));console.log(""),console.log(e.cyan(" Chat options:")),console.log(e.white(" --stream, -s ")+e.gray("Enable typewriter effect (default: instant)")),console.log(""),console.log(e.gray(" To install/uninstall skills, just ask naturally:")),console.log(e.gray(' "connect to Jira" \u2022 "add GitHub" \u2022 "remove Slack"')),console.log("")}const ms=Qe;async function Ds(n={}){const t=process.cwd();n.verbose&&(process.env.ZIBBY_VERBOSE="true");const s=n.stream||!1;[lt(t,".env.local"),lt(t,".env")].forEach(c=>{gt(c)&&Me.config({path:c,override:!1})});try{await import("@zibby/skills")}catch{}function h(){const c=Wt();if(!c)return!1;try{const y=JSON.parse(atob(c.split(".")[1]));return y.exp&&y.exp*1e3>Date.now()}catch{return!1}}if(!h()){Ue();const c=re(),{spawn:y}=await import("child_process"),Z=await fetch(`${c}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});Z.ok||(console.log(e.red("\n Could not start login. Try `zibby login`.\n")),process.exit(1));const{deviceCode:f,verificationUrl:r,expiresIn:O,interval:ut}=await Z.json(),ot=process.platform;y(ot==="darwin"?"open":ot==="win32"?"cmd":"xdg-open",ot==="win32"?["/c","start","",r]:[r],{detached:!0,stdio:"ignore"}).unref(),console.log(e.cyan(`
24
- Opening browser to authorize Zibby CLI...`)),console.log(e.gray(` ${r}
25
- `));const ct=le();ct.setLabel("waiting for authorization");const pt=(ut||3)*1e3,dt=Math.floor(O/(ut||3));let X=!1;for(let nt=0;nt<dt;nt++){await Ve(pt);try{const Q=await fetch(`${c}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:f})});if(Q.status===202)continue;if(!Q.ok)break;const z=await Q.json();if(z.status==="authorized"){Be(z.token),Re(z.user),z.proxyUrl&&Fe(z.proxyUrl),z.mem0ProxyUrl&&We(z.mem0ProxyUrl),X=!0;break}if(z.status==="denied")break}catch{break}}ct(),X||(console.log(e.red("\n Login failed or timed out. Run `zibby login` to try again.\n")),process.exit(1))}const k=await ts(t),v=await es(t),C=n.agent||"assistant",I=Wt();I&&!process.env.ZIBBY_USER_TOKEN&&(process.env.ZIBBY_USER_TOKEN=I);const U=De()||je();U&&!process.env.ZIBBY_MEM0_OPENAI_BASE_URL&&(process.env.ZIBBY_MEM0_OPENAI_BASE_URL=U),process.env.AGENT_TYPE=C,process.env.ZIBBY_CHAT_OWNER_PID=String(process.pid);try{const{cleanupStalePidFiles:c}=await import("../utils/chat-run-lifecycle.js");c(t,k)}catch{}let R;try{R=ve({state:{agentType:C}})}catch(c){console.log(e.red(`
22
+ `)}function it(){R();const u=()=>e.gray(`${At[v%At.length]} thinking`);if(!t){console.log(` ${u()}`),l=!0;return}W(),V(),console.log(),console.log(` ${u()}`),H({preserveInput:!0}),l=!0,v+=1,k=setInterval(()=>{l&&(ht(u()),v+=1)},120)}function yt(u){R();const w=String(u??"").replace(/\r/g,"").replace(/⎿/g,"");if(!l){F(w);return}V(),console.log();const c=w.split(`
23
+ `);for(;c.length>0&&c[c.length-1]==="";)c.pop();for(const y of c)console.log(y?` ${y}`:"");console.log(),l=!1}return{enabled:t,mount(){if(!s){if(!t){o.prompt(),s=!0;return}s=!0,H()}},refreshPrompt(u={}){if(t&&s){r&&V(),H(u);return}o.prompt()},pushSystem(u){F(u)},pushUser(u){F(st(u))},pushAssistant(u){yt(u)},showAssistantLoading:it,dismissTransientLoading(){R(),l&&t&&s&&r&&(process.stdout.write("\x1B7"),M(process.stdout,0,-2),B(process.stdout,0),G(process.stdout,0),M(process.stdout,0,-1),B(process.stdout,0),G(process.stdout,0),process.stdout.write("\x1B8")),l=!1},touchInputFrame:et,handleResize:L,showCommandDropdown:E,clearCommandDropdown:W}}function fs(){console.log(""),console.log(e.cyan(" Available commands:"));for(const o of Yt)console.log(e.white(` ${o.cmd.padEnd(10)} `)+e.gray(o.desc));console.log(""),console.log(e.cyan(" Chat options:")),console.log(e.white(" --stream, -s ")+e.gray("Enable typewriter effect (default: instant)")),console.log(""),console.log(e.gray(" To install/uninstall skills, just ask naturally:")),console.log(e.gray(' "connect to Jira" \u2022 "add GitHub" \u2022 "remove Slack"')),console.log("")}const ms=Qe;async function Ds(o={}){const t=process.cwd();o.verbose&&(process.env.ZIBBY_VERBOSE="true");const s=o.stream||!1;[lt(t,".env.local"),lt(t,".env")].forEach(c=>{gt(c)&&Me.config({path:c,override:!1})});try{await import("@zibby/skills")}catch{}function l(){const c=Wt();if(!c)return!1;try{const y=JSON.parse(atob(c.split(".")[1]));return y.exp&&y.exp*1e3>Date.now()}catch{return!1}}if(!l()){Ue();const c=re(),{spawn:y}=await import("child_process"),q=await fetch(`${c}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});q.ok||(console.log(e.red("\n Could not start login. Try `zibby login`.\n")),process.exit(1));const{deviceCode:m,verificationUrl:n,expiresIn:O,interval:ut}=await q.json(),ot=process.platform;y(ot==="darwin"?"open":ot==="win32"?"cmd":"xdg-open",ot==="win32"?["/c","start","",n]:[n],{detached:!0,stdio:"ignore"}).unref(),console.log(e.cyan(`
24
+ Opening browser to authorize Zibby CLI...`)),console.log(e.gray(` ${n}
25
+ `));const ct=le();ct.setLabel("waiting for authorization");const pt=(ut||3)*1e3,dt=Math.floor(O/(ut||3));let X=!1;for(let nt=0;nt<dt;nt++){await Ve(pt);try{const Q=await fetch(`${c}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:m})});if(Q.status===202)continue;if(!Q.ok)break;const z=await Q.json();if(z.status==="authorized"){Be(z.token),Re(z.user),z.proxyUrl&&Fe(z.proxyUrl),z.mem0ProxyUrl&&We(z.mem0ProxyUrl),X=!0;break}if(z.status==="denied")break}catch{break}}ct(),X||(console.log(e.red("\n Login failed or timed out. Run `zibby login` to try again.\n")),process.exit(1))}const k=await ts(t),v=await es(t),C=o.agent||"assistant",I=Wt();I&&!process.env.ZIBBY_USER_TOKEN&&(process.env.ZIBBY_USER_TOKEN=I);const U=De()||je();U&&!process.env.ZIBBY_MEM0_OPENAI_BASE_URL&&(process.env.ZIBBY_MEM0_OPENAI_BASE_URL=U),process.env.AGENT_TYPE=C,process.env.ZIBBY_CHAT_OWNER_PID=String(process.pid);try{const{cleanupStalePidFiles:c}=await import("../utils/chat-run-lifecycle.js");c(t,k)}catch{}let R;try{R=ve({state:{agentType:C}})}catch(c){console.log(e.red(`
26
26
  ${c.message}
27
- `)),process.exit(1)}const ht=Ne(),rt=Oe()?.[0]?.name,E=He(t),V=v.skills||[],H=Ye(t),L=H?[...new Set([...V,...H])]:[...V];let et={data:null,timestamp:0};const F=300*1e3,st={jira:"jira",github:"github",slack:"slack",sentry:"sentry"};try{const c=Wt();if(c){const y=re(),Z=await fetch(`${y}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${c}`}});if(Z.ok){const f=await Z.json();for(const[r,O]of Object.entries(st))f[r]?.connected&&!L.includes(O)&&$t(O)&&L.push(O);It(t,L)}}}catch{}const it=L.filter(c=>c!=="skill-installer"&&c!=="core-tools"),yt=it.length>0?`Skills: ${it.join(", ")}`:"Skills: (none)";us({userName:ht?.name?.split(" ")[0],cwd:t,projectName:rt,restoredCount:E.length,skillsLine:yt});let l=ue(t),w=de(l);return new Promise(c=>{const y=process.env.ZIBBY_CHAT_TAB_COMPLETION==="1",Z={input:process.stdin,output:process.stdout,prompt:e.green(" > "),terminal:!0};y&&(Z.completer=u=>{const i=String(u||"");if(!i.startsWith("/"))return[[],i];const m=w.map(P=>P.cmd),$=m.filter(P=>P.startsWith(i));return[$.length>0?$:m,i]});const f=Pe(Z),r=ds(f);let O=null,ut=!1;const ot=[],fe=0,me=1200;let ct=!1,pt=!1,dt=!1,X=!1,nt="",Q=0;const z=typeof f._ttyWrite=="function"?f._ttyWrite.bind(f):null;z&&(f._ttyWrite=(...u)=>{if(!(X||Date.now()<Q))return z(...u)});function ge(){dt||!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004h"),dt=!0)}function Jt(){dt&&(!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004l"),dt=!1))}function he(u){const i="\x1B[200~",m="\x1B[201~";if(!X&&!u.includes(i))return!1;let $=u,P=!1;for(;$.length>0;){if(!X){const A=$.indexOf(i);if(A===-1)break;P=!0,Kt(),X=!0,nt="",$=$.slice(A+i.length);continue}const J=$.indexOf(m);if(J===-1){P=!0,nt+=$;break}P=!0,nt+=$.slice(0,J);const tt=String(nt||"").replace(/\r\n/g,`
27
+ `)),process.exit(1)}const ht=Ne(),rt=Oe()?.[0]?.name,E=He(t),V=v.skills||[],H=Ye(t),L=H?[...new Set([...V,...H])]:[...V];let et={data:null,timestamp:0};const F=300*1e3,st={jira:"jira",github:"github",slack:"slack",sentry:"sentry"};try{const c=Wt();if(c){const y=re(),q=await fetch(`${y}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${c}`}});if(q.ok){const m=await q.json();for(const[n,O]of Object.entries(st))m[n]?.connected&&!L.includes(O)&&$t(O)&&L.push(O);It(t,L)}}}catch{}const it=L.filter(c=>c!=="skill-installer"&&c!=="core-tools"),yt=it.length>0?`Skills: ${it.join(", ")}`:"Skills: (none)";us({userName:ht?.name?.split(" ")[0],cwd:t,projectName:rt,restoredCount:E.length,skillsLine:yt});let u=ue(t),w=de(u);return new Promise(c=>{const y=process.env.ZIBBY_CHAT_TAB_COMPLETION==="1",q={input:process.stdin,output:process.stdout,prompt:e.green(" > "),terminal:!0};y&&(q.completer=p=>{const i=String(p||"");if(!i.startsWith("/"))return[[],i];const g=w.map(P=>P.cmd),$=g.filter(P=>P.startsWith(i));return[$.length>0?$:g,i]});const m=Pe(q),n=ds(m);let O=null,ut=!1;const ot=[],fe=0,me=1200;let ct=!1,pt=!1,dt=!1,X=!1,nt="",Q=0;const z=typeof m._ttyWrite=="function"?m._ttyWrite.bind(m):null;z&&(m._ttyWrite=(...p)=>{if(!(X||Date.now()<Q))return z(...p)});function ge(){dt||!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004h"),dt=!0)}function Jt(){dt&&(!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004l"),dt=!1))}function he(p){const i="\x1B[200~",g="\x1B[201~";if(!X&&!p.includes(i))return!1;let $=p,P=!1;for(;$.length>0;){if(!X){const A=$.indexOf(i);if(A===-1)break;P=!0,Kt(),X=!0,nt="",$=$.slice(A+i.length);continue}const J=$.indexOf(g);if(J===-1){P=!0,nt+=$;break}P=!0,nt+=$.slice(0,J);const tt=String(nt||"").replace(/\r\n/g,`
28
28
  `).replace(/\r/g,`
29
29
  `);if(tt.length>0){const A=tt.split(`
30
- `);for(const q of A)Rt(q)}vt(),nt="",X=!1,$=$.slice(J+m.length)}return P}function Gt(){if(!ct){ct=!0;try{Pt(t,E),It(t,L)}catch{}try{Jt()}catch{}try{f.close()}catch{}process.exit(0)}}async function Lt(){if(!ct){ct=!0,typeof R?.cleanup=="function"&&await R.cleanup().catch(()=>{});try{const{killAllChatOrchestratedRuns:u}=await import("../utils/chat-run-lifecycle.js"),{postCliInterruptedRunIndex:i}=await import("@zibby/core/utils/run-index-post-cli.js");u(t,process.pid,k),i({cwd:t,config:k})}catch{}Pt(t,E),It(t,L),r.pushSystem(e.gray("Session saved. Goodbye!")),Jt(),f.close(),process.exit(0)}}if(r.mount(),ge(),process.stdout?.isTTY){let u;process.stdout.on("resize",()=>{clearTimeout(u),u=setTimeout(()=>{r.handleResize()},80)})}let Mt=0;const xt=u=>{if(typeof u=="string"?u==="\x1B":u&&typeof u.length=="number"?u.length===1&&u[0]===27:!1){O&&O.abort(),Gt();return}const m=typeof u=="string"?u:u&&typeof u.length=="number"?Buffer.from(u).toString("utf8"):"";if(!m)return;if(he(m)){Mt=Date.now()+1200,Q=Date.now()+1200,Bt();return}const $=(m.includes(`
31
- `)||m.includes("\r"))&&m!=="\r"&&m!==`
32
- `&&m!==`\r
33
- `,P=m.includes("\x1B[200~")||m.includes("\x1B[201~"),J=m.length>=16&&/\s/.test(m)&&!m.startsWith("\x1B");($||P||J)&&(Mt=Date.now()+1200,Q=Date.now()+1200,Kt(),Bt())},N={query:"",matches:[],selected:0},Y={prefix:"",matches:[],nextIndex:0},x={active:!1,prefix:"",lines:[],timer:null},Nt=[];let Zt=0,Ot="";const ye=new Set(Yt.map(u=>u.cmd));function ft(u,{preserveFrame:i=!1}={}){const m=String(u||"");f.line=m,f.cursor=m.length,Ot=m,typeof f._refreshLine=="function"?f._refreshLine():f.prompt(),i&&r.touchInputFrame()}function qt(){Y.prefix="",Y.matches=[],Y.nextIndex=0}function vt(){if(x.timer&&(clearTimeout(x.timer),x.timer=null),x.active&&x.lines.length>0){Zt+=1;const u=x.lines.length,i=`[Pasted text #${Zt} +${u} lines]`,m=x.lines.join(`
34
- `);Nt.push({placeholder:i,text:m});const $=String(x.prefix||"").trimEnd(),P=$?`${$} ${i}`:i;ft(P,{preserveFrame:!0}),mt(f.line)}x.active=!1,x.prefix="",x.lines=[],Q=0}function Bt(){x.timer&&clearTimeout(x.timer),x.timer=setTimeout(()=>{vt()},180)}function Kt(){x.active||(x.active=!0,x.prefix=String(Ot||f.line||""),x.lines=[],ft(x.prefix,{preserveFrame:!0}))}function Rt(u){return x.active?(x.lines.push(String(u||"")),ft(x.prefix,{preserveFrame:!0}),Bt(),!0):!1}function we(u){let i=String(u||"");for(const m of Nt)i=i.split(m.placeholder).join(m.text);return i}function mt(u){const i=String(u||"");if(!i.startsWith("/")||i.includes(" ")||i.length===0){N.query="",N.matches=[],N.selected=0,r.clearCommandDropdown();return}l=ue(t),w=de(l);const m=i.slice(1).toLowerCase(),$=l.filter(P=>P.toLowerCase().startsWith(m));N.query=m,N.matches=$,N.selected=Math.min(N.selected,Math.max(0,$.length-1)),r.showCommandDropdown($,N.selected)}const Ut=(u,i)=>{if(i?.name==="escape"||i?.sequence==="\x1B"){O&&O.abort(),Gt();return}if((i?.name==="return"||i?.name==="enter")&&(pt=!0),(i?.name==="backspace"||i?.name==="delete")&&r.touchInputFrame(),i?.name==="tab"&&!i?.shift){const P=String(f.line||""),J=Number(f.cursor||P.length);if(!ls(P,J)){qt(),mt(f.line);return}const tt=P.slice(1).toLowerCase();if(Y.prefix!==tt&&(Y.prefix=tt,Y.matches=w.map(q=>q.cmd).filter(q=>q.toLowerCase().startsWith(`/${tt}`)),Y.nextIndex=0),Y.matches.length===0)return;const A=Y.nextIndex%Y.matches.length;Y.nextIndex+=1,ft(Y.matches[A]),mt(f.line);return}const m=String(f.line||""),$=m.startsWith("/")&&!m.includes(" ")&&N.matches.length>0;if(i?.name==="up"||i?.name==="down"){if(!$){mt(f.line);return}const P=i.name==="up"?-1:1,J=N.matches.length;N.selected=(N.selected+P+J)%J;const tt=N.matches[N.selected];ft(`/${tt}`,{preserveFrame:!0}),r.showCommandDropdown(N.matches,N.selected);return}i?.name!=="tab"&&qt(),setTimeout(()=>{mt(f.line),x.active||(Ot=String(f.line||""))},50)};process.stdin?.on&&(Ae(process.stdin,f),process.stdin.on("keypress",Ut)),r.enabled&&process.stdin?.on&&(typeof process.stdin.prependListener=="function"?process.stdin.prependListener("data",xt):process.stdin.on("data",xt)),f.on("line",async u=>{try{let i=String(u||"");const m=pt;if(pt=!1,!m&&(x.active||X||Date.now()<Mt||Date.now()<Q)){if(x.active&&i.length>0){Rt(i);return}x.active&&(vt(),r.refreshPrompt());return}if(x.active&&(vt(),i=String(f.line||i||"")),Rt(i))return;const $=i.trim(),P=N.matches[N.selected];if($.startsWith("/")&&!$.includes(" ")&&N.matches.length>0&&!ye.has($)&&$!==`/${P}`){r.clearCommandDropdown(),r.refreshPrompt(),ft(`/${P}`),mt(`/${P}`);return}r.clearCommandDropdown();const A=String(i||"").replace(/[\u0000-\u001F\u007F-\u009F]/g,"").trim();if(!A){r.enabled&&process.stdout?.isTTY&&(M(process.stdout,0,-1),B(process.stdout,4));return}if(ut&&A!=="/exit"&&A!=="/quit"){O&&O.abort(),ot.push(A),r.pushSystem(e.gray("Processing your message...")),r.refreshPrompt({preserveInput:!0});return}const q=1e4;if(A.length>q){r.pushSystem(e.red(`\u26A0 Input too long (${A.length} chars). Maximum: ${q} characters.`)),r.pushSystem(e.gray("Tip: If you need to share logs, use a file instead:")),r.pushSystem(e.gray(" 1. Save to file: pbpaste > debug.log")),r.pushSystem(e.gray(' 2. Ask: "analyze debug.log in current directory"')),r.refreshPrompt();return}if(A==="/exit"||A==="/quit"){Lt();return}if(A==="/help"){fs(),r.refreshPrompt();return}if(A==="/skills"){const _=$t("skill-installer")?.catalog||{},g=L.filter(b=>b!=="skill-installer");console.log(e.cyan(`
35
- Active skills:`)),g.length===0&&console.log(e.gray(" (none)"));for(const b of g){const S=_[b]||{};console.log(e.green(` \u2713 ${b}`)+e.gray(S.description?` \u2014 ${S.description}`:""))}const T=Object.keys(_).filter(b=>!L.includes(b));if(T.length>0){console.log(e.cyan(`
36
- Available:`));for(const b of T){const S=_[b],d=S.envKeys?.length>0?ms(S.envKeys).ok?e.green(" \u2713 configured"):e.yellow(` \u26A0 needs: ${S.envKeys.join(", ")}`):"";console.log(e.white(` - ${b}`)+e.gray(` \u2014 ${S.description}`)+d)}}console.log(e.gray(`
30
+ `);for(const Z of A)Rt(Z)}vt(),nt="",X=!1,$=$.slice(J+g.length)}return P}function Gt(){if(!ct){ct=!0;try{Pt(t,E),It(t,L)}catch{}try{Jt()}catch{}try{m.close()}catch{}process.exit(0)}}async function Lt(){if(!ct){ct=!0,typeof R?.cleanup=="function"&&await R.cleanup().catch(()=>{});try{const{killAllChatOrchestratedRuns:p}=await import("../utils/chat-run-lifecycle.js"),{postCliInterruptedRunIndex:i}=await import("@zibby/core/utils/run-index-post-cli.js");p(t,process.pid,k),i({cwd:t,config:k})}catch{}Pt(t,E),It(t,L),n.pushSystem(e.gray("Session saved. Goodbye!")),Jt(),m.close(),process.exit(0)}}if(n.mount(),ge(),process.stdout?.isTTY){let p;process.stdout.on("resize",()=>{clearTimeout(p),p=setTimeout(()=>{n.handleResize()},80)})}let Mt=0;const xt=p=>{if(typeof p=="string"?p==="\x1B":p&&typeof p.length=="number"?p.length===1&&p[0]===27:!1){O&&O.abort(),Gt();return}const g=typeof p=="string"?p:p&&typeof p.length=="number"?Buffer.from(p).toString("utf8"):"";if(!g)return;if(he(g)){Mt=Date.now()+1200,Q=Date.now()+1200,Bt();return}const $=(g.includes(`
31
+ `)||g.includes("\r"))&&g!=="\r"&&g!==`
32
+ `&&g!==`\r
33
+ `,P=g.includes("\x1B[200~")||g.includes("\x1B[201~"),J=g.length>=16&&/\s/.test(g)&&!g.startsWith("\x1B");($||P||J)&&(Mt=Date.now()+1200,Q=Date.now()+1200,Kt(),Bt())},N={query:"",matches:[],selected:0},Y={prefix:"",matches:[],nextIndex:0},x={active:!1,prefix:"",lines:[],timer:null},Nt=[];let qt=0,Ot="";const ye=new Set(Yt.map(p=>p.cmd));function ft(p,{preserveFrame:i=!1}={}){const g=String(p||"");m.line=g,m.cursor=g.length,Ot=g,typeof m._refreshLine=="function"?m._refreshLine():m.prompt(),i&&n.touchInputFrame()}function Zt(){Y.prefix="",Y.matches=[],Y.nextIndex=0}function vt(){if(x.timer&&(clearTimeout(x.timer),x.timer=null),x.active&&x.lines.length>0){qt+=1;const p=x.lines.length,i=`[Pasted text #${qt} +${p} lines]`,g=x.lines.join(`
34
+ `);Nt.push({placeholder:i,text:g});const $=String(x.prefix||"").trimEnd(),P=$?`${$} ${i}`:i;ft(P,{preserveFrame:!0}),mt(m.line)}x.active=!1,x.prefix="",x.lines=[],Q=0}function Bt(){x.timer&&clearTimeout(x.timer),x.timer=setTimeout(()=>{vt()},180)}function Kt(){x.active||(x.active=!0,x.prefix=String(Ot||m.line||""),x.lines=[],ft(x.prefix,{preserveFrame:!0}))}function Rt(p){return x.active?(x.lines.push(String(p||"")),ft(x.prefix,{preserveFrame:!0}),Bt(),!0):!1}function we(p){let i=String(p||"");for(const g of Nt)i=i.split(g.placeholder).join(g.text);return i}function mt(p){const i=String(p||"");if(!i.startsWith("/")||i.includes(" ")||i.length===0){N.query="",N.matches=[],N.selected=0,n.clearCommandDropdown();return}u=ue(t),w=de(u);const g=i.slice(1).toLowerCase(),$=u.filter(P=>P.toLowerCase().startsWith(g));N.query=g,N.matches=$,N.selected=Math.min(N.selected,Math.max(0,$.length-1)),n.showCommandDropdown($,N.selected)}const Ut=(p,i)=>{if(i?.name==="escape"||i?.sequence==="\x1B"){O&&O.abort(),Gt();return}if((i?.name==="return"||i?.name==="enter")&&(pt=!0),(i?.name==="backspace"||i?.name==="delete")&&n.touchInputFrame(),i?.name==="tab"&&!i?.shift){const P=String(m.line||""),J=Number(m.cursor||P.length);if(!ls(P,J)){Zt(),mt(m.line);return}const tt=P.slice(1).toLowerCase();if(Y.prefix!==tt&&(Y.prefix=tt,Y.matches=w.map(Z=>Z.cmd).filter(Z=>Z.toLowerCase().startsWith(`/${tt}`)),Y.nextIndex=0),Y.matches.length===0)return;const A=Y.nextIndex%Y.matches.length;Y.nextIndex+=1,ft(Y.matches[A]),mt(m.line);return}const g=String(m.line||""),$=g.startsWith("/")&&!g.includes(" ")&&N.matches.length>0;if(i?.name==="up"||i?.name==="down"){if(!$){mt(m.line);return}const P=i.name==="up"?-1:1,J=N.matches.length;N.selected=(N.selected+P+J)%J;const tt=N.matches[N.selected];ft(`/${tt}`,{preserveFrame:!0}),n.showCommandDropdown(N.matches,N.selected);return}i?.name!=="tab"&&Zt(),setTimeout(()=>{mt(m.line),x.active||(Ot=String(m.line||""))},50)};process.stdin?.on&&(Ae(process.stdin,m),process.stdin.on("keypress",Ut)),n.enabled&&process.stdin?.on&&(typeof process.stdin.prependListener=="function"?process.stdin.prependListener("data",xt):process.stdin.on("data",xt)),m.on("line",async p=>{try{let i=String(p||"");const g=pt;if(pt=!1,!g&&(x.active||X||Date.now()<Mt||Date.now()<Q)){if(x.active&&i.length>0){Rt(i);return}x.active&&(vt(),n.refreshPrompt());return}if(x.active&&(vt(),i=String(m.line||i||"")),Rt(i))return;const $=i.trim(),P=N.matches[N.selected];if($.startsWith("/")&&!$.includes(" ")&&N.matches.length>0&&!ye.has($)&&$!==`/${P}`){n.clearCommandDropdown(),n.refreshPrompt(),ft(`/${P}`),mt(`/${P}`);return}n.clearCommandDropdown();const A=String(i||"").replace(/[\u0000-\u001F\u007F-\u009F]/g,"").trim();if(!A){n.enabled&&process.stdout?.isTTY&&(M(process.stdout,0,-1),B(process.stdout,4));return}if(ut&&A!=="/exit"&&A!=="/quit"){O&&O.abort(),ot.push(A),n.pushSystem(e.gray("Processing your message...")),n.refreshPrompt({preserveInput:!0});return}const Z=1e4;if(A.length>Z){n.pushSystem(e.red(`\u26A0 Input too long (${A.length} chars). Maximum: ${Z} characters.`)),n.pushSystem(e.gray("Tip: If you need to share logs, use a file instead:")),n.pushSystem(e.gray(" 1. Save to file: pbpaste > debug.log")),n.pushSystem(e.gray(' 2. Ask: "analyze debug.log in current directory"')),n.refreshPrompt();return}if(A==="/exit"||A==="/quit"){Lt();return}if(A==="/help"){fs(),n.refreshPrompt();return}if(A==="/skills"){const _=$t("skill-installer")?.catalog||{},h=L.filter(b=>b!=="skill-installer");console.log(e.cyan(`
35
+ Active skills:`)),h.length===0&&console.log(e.gray(" (none)"));for(const b of h){const S=_[b]||{};console.log(e.green(` \u2713 ${b}`)+e.gray(S.description?` \u2014 ${S.description}`:""))}const T=Object.keys(_).filter(b=>!L.includes(b));if(T.length>0){console.log(e.cyan(`
36
+ Available:`));for(const b of T){const S=_[b],f=S.envKeys?.length>0?ms(S.envKeys).ok?e.green(" \u2713 configured"):e.yellow(` \u26A0 needs: ${S.envKeys.join(", ")}`):"";console.log(e.white(` - ${b}`)+e.gray(` \u2014 ${S.description}`)+f)}}console.log(e.gray(`
37
37
  Just ask to install: "connect to Jira", "add GitHub", etc.
38
- `)),r.refreshPrompt();return}if(A.startsWith("/history")){if(E.length===0)console.log(e.gray(`
38
+ `)),n.refreshPrompt();return}if(A.startsWith("/history")){if(E.length===0)console.log(e.gray(`
39
39
  No conversation history.
40
- `));else{const a=A.split(/\s+/).slice(1),_=a.includes("--all"),g=a.indexOf("-n"),T=g>=0&&a[g+1]?parseInt(a[g+1],10):NaN,b=_?E.length:isNaN(T)?10:T,S=E.slice(-b);console.log(e.gray(`
40
+ `));else{const a=A.split(/\s+/).slice(1),_=a.includes("--all"),h=a.indexOf("-n"),T=h>=0&&a[h+1]?parseInt(a[h+1],10):NaN,b=_?E.length:isNaN(T)?10:T,S=E.slice(-b);console.log(e.gray(`
41
41
  Showing ${S.length} of ${E.length} messages${_?" (all)":""}:
42
- `));for(const d of S){const p=d.role==="human"?e.green(" You"):e.cyan(" Zibby"),j=_||T>10?500:100,D=d.content.length>j?`${d.content.substring(0,j)}...`:d.content;console.log(`${p}: ${e.white(D)}`)}console.log("")}r.refreshPrompt();return}if(A==="/clear"){E.length=0,Pt(t,E),console.log(e.gray(`
42
+ `));for(const f of S){const d=f.role==="human"?e.green(" You"):e.cyan(" Zibby"),j=_||T>10?500:100,D=f.content.length>j?`${f.content.substring(0,j)}...`:f.content;console.log(`${d}: ${e.white(D)}`)}console.log("")}n.refreshPrompt();return}if(A==="/clear"){E.length=0,Pt(t,E),console.log(e.gray(`
43
43
  History cleared.
44
- `)),r.refreshPrompt();return}if(A.startsWith("/memory")){const a=L.includes("chat-memory")?$t("chat-memory"):null;if(!a?.handleToolCall){console.log(e.yellow(`
44
+ `)),n.refreshPrompt();return}if(A.startsWith("/memory")){const a=L.includes("chat-memory")?$t("chat-memory"):null;if(!a?.handleToolCall){console.log(e.yellow(`
45
45
  Chat memory not active. Install with: "add chat memory"
46
- `)),r.refreshPrompt();return}const _=A.split(/\s+/).slice(1),g=_[0]||"brief",T={options:{workspace:t}};try{if(g==="facts"||g==="all"){const b=parseInt(_[1],10)||30,S=await a.handleToolCall("memory_recall",{limit:b},T),d=JSON.parse(S);if(console.log(e.cyan(`
47
- Stored memories (${d.total}):
48
- `)),d.total===0)console.log(e.gray(` (empty \u2014 memories are saved as the agent learns things)
49
- `));else{for(const p of d.memories){const j=e.yellow(`[${p.category}]`),D=Number(p.relevance)<1?e.gray(` (${(Number(p.relevance)*100).toFixed(0)}%)`):"",St=p.ticket_key?e.magenta(` ${p.ticket_key}`):"",kt=p.source?e.gray(` via ${p.source}`):"";console.log(` ${j}${St} ${e.white(p.content)}${D}${kt}`)}console.log("")}}else if(g==="tasks"){const b=parseInt(_[1],10)||20,S=await a.handleToolCall("task_history",{limit:b},T),d=JSON.parse(S);if(console.log(e.cyan(`
50
- Task history (${d.total}):
51
- `)),d.total===0)console.log(e.gray(` (no tasks logged yet)
52
- `));else{for(const p of d.tasks){const j=p.status==="passed"?e.green("\u2713"):p.status==="failed"?e.red("\u2717"):e.yellow("\u25CB"),D=p.ticket_key?e.magenta(` ${p.ticket_key}`):"",St=e.gray(`[${p.type}]`),kt=p.result_summary?e.gray(` \u2014 ${p.result_summary.slice(0,80)}`):"";console.log(` ${j} ${St}${D} ${e.white(p.title)}${kt}`)}console.log("")}}else if(g==="sessions"){const b=await a.handleToolCall("memory_brief",{},T),S=JSON.parse(b);if(console.log(e.cyan(`
46
+ `)),n.refreshPrompt();return}const _=A.split(/\s+/).slice(1),h=_[0]||"brief",T={options:{workspace:t}};try{if(h==="facts"||h==="all"){const b=parseInt(_[1],10)||30,S=await a.handleToolCall("memory_recall",{limit:b},T),f=JSON.parse(S);if(console.log(e.cyan(`
47
+ Stored memories (${f.total}):
48
+ `)),f.total===0)console.log(e.gray(` (empty \u2014 memories are saved as the agent learns things)
49
+ `));else{for(const d of f.memories){const j=e.yellow(`[${d.category}]`),D=Number(d.relevance)<1?e.gray(` (${(Number(d.relevance)*100).toFixed(0)}%)`):"",St=d.ticket_key?e.magenta(` ${d.ticket_key}`):"",kt=d.source?e.gray(` via ${d.source}`):"";console.log(` ${j}${St} ${e.white(d.content)}${D}${kt}`)}console.log("")}}else if(h==="tasks"){const b=parseInt(_[1],10)||20,S=await a.handleToolCall("task_history",{limit:b},T),f=JSON.parse(S);if(console.log(e.cyan(`
50
+ Task history (${f.total}):
51
+ `)),f.total===0)console.log(e.gray(` (no tasks logged yet)
52
+ `));else{for(const d of f.tasks){const j=d.status==="passed"?e.green("\u2713"):d.status==="failed"?e.red("\u2717"):e.yellow("\u25CB"),D=d.ticket_key?e.magenta(` ${d.ticket_key}`):"",St=e.gray(`[${d.type}]`),kt=d.result_summary?e.gray(` \u2014 ${d.result_summary.slice(0,80)}`):"";console.log(` ${j} ${St}${D} ${e.white(d.title)}${kt}`)}console.log("")}}else if(h==="sessions"){const b=await a.handleToolCall("memory_brief",{},T),S=JSON.parse(b);if(console.log(e.cyan(`
53
53
  Recent sessions (${S.recentSessions?.length||0}):
54
54
  `)),!S.recentSessions?.length)console.log(e.gray(` (no sessions saved yet)
55
- `));else{for(const d of S.recentSessions){const p=d.tickets?e.magenta(` [${d.tickets}]`):"",j=d.tasks_run>0?e.gray(` \u2014 ${d.tasks_run} tasks (${d.tasks_passed} passed, ${d.tasks_failed} failed)`):"",D=d.created_at?e.gray(` ${d.created_at.split("T")[0]}`):"";if(console.log(` ${e.white(d.summary)}${p}${j}${D}`),d.key_facts)for(const St of d.key_facts.split(";").map(kt=>kt.trim()).filter(Boolean))console.log(e.gray(` \u2192 ${St}`))}console.log("")}}else if(g==="search"){const b=_.slice(1).join(" ");if(!b)console.log(e.yellow(`
55
+ `));else{for(const f of S.recentSessions){const d=f.tickets?e.magenta(` [${f.tickets}]`):"",j=f.tasks_run>0?e.gray(` \u2014 ${f.tasks_run} tasks (${f.tasks_passed} passed, ${f.tasks_failed} failed)`):"",D=f.created_at?e.gray(` ${f.created_at.split("T")[0]}`):"";if(console.log(` ${e.white(f.summary)}${d}${j}${D}`),f.key_facts)for(const St of f.key_facts.split(";").map(kt=>kt.trim()).filter(Boolean))console.log(e.gray(` \u2192 ${St}`))}console.log("")}}else if(h==="search"){const b=_.slice(1).join(" ");if(!b)console.log(e.yellow(`
56
56
  Usage: /memory search <keyword>
57
- `));else{const S=await a.handleToolCall("memory_recall",{query:b,limit:20},T),d=JSON.parse(S);console.log(e.cyan(`
58
- Search "${b}" \u2014 ${d.total} results:
59
- `));for(const p of d.memories){const j=e.yellow(`[${p.category}]`),D=p.ticket_key?e.magenta(` ${p.ticket_key}`):"";console.log(` ${j}${D} ${e.white(p.content)}`)}d.total===0&&console.log(e.gray(" (no matches)")),console.log("")}}else{const b=await a.handleToolCall("memory_brief",{},T),S=JSON.parse(b),d=S.topMemories?.length||0,p=S.recentSessions?.length||0,j=(S.taskStats||[]).map(D=>`${D.type}:${D.status}=${D.cnt}`).join(", ");console.log(e.cyan(`
57
+ `));else{const S=await a.handleToolCall("memory_recall",{query:b,limit:20},T),f=JSON.parse(S);console.log(e.cyan(`
58
+ Search "${b}" \u2014 ${f.total} results:
59
+ `));for(const d of f.memories){const j=e.yellow(`[${d.category}]`),D=d.ticket_key?e.magenta(` ${d.ticket_key}`):"";console.log(` ${j}${D} ${e.white(d.content)}`)}f.total===0&&console.log(e.gray(" (no matches)")),console.log("")}}else{const b=await a.handleToolCall("memory_brief",{},T),S=JSON.parse(b),f=S.topMemories?.length||0,d=S.recentSessions?.length||0,j=(S.taskStats||[]).map(D=>`${D.type}:${D.status}=${D.cnt}`).join(", ");console.log(e.cyan(`
60
60
  Memory overview:
61
- `)),console.log(e.white(` Facts stored: ${d>0?e.cyan(d):e.gray("0")}`)),console.log(e.white(` Sessions saved: ${p>0?e.cyan(p):e.gray("0")}`)),j&&console.log(e.white(` Task history: ${e.gray(j)}`)),console.log(e.gray(`
61
+ `)),console.log(e.white(` Facts stored: ${f>0?e.cyan(f):e.gray("0")}`)),console.log(e.white(` Sessions saved: ${d>0?e.cyan(d):e.gray("0")}`)),j&&console.log(e.white(` Task history: ${e.gray(j)}`)),console.log(e.gray(`
62
62
  Subcommands:`)),console.log(e.gray(" /memory facts [n] \u2014 List all stored memories")),console.log(e.gray(" /memory tasks [n] \u2014 List task history")),console.log(e.gray(" /memory sessions \u2014 List session summaries")),console.log(e.gray(" /memory search <keyword> \u2014 Search memories")),console.log("")}}catch(b){console.log(e.red(`
63
63
  Memory error: ${b.message}
64
- `))}r.refreshPrompt();return}r.enabled&&process.stdout?.isTTY&&(M(process.stdout,0,-1),B(process.stdout,0)),r.pushUser(A),r.refreshPrompt(),r.showAssistantLoading();const Vt=we(A),Tt=ss(t,Vt);if(Nt.length=0,!String(Tt||"").trim()){r.dismissTransientLoading(),r.refreshPrompt();return}if(Tt.length>q){r.pushAssistant(e.red(`Input too long after command expansion (${Tt.length} chars).`)),r.pushSystem(e.gray(`Try shortening the command template or user text. Limit: ${q} chars.`)),r.refreshPrompt();return}ut=!0;let K=v.systemPrompt||"You are Zibby, a helpful AI assistant.";const Xt=is(v,n);Xt&&(K+=`
64
+ `))}n.refreshPrompt();return}n.enabled&&process.stdout?.isTTY&&(M(process.stdout,0,-1),B(process.stdout,0)),n.pushUser(A),n.refreshPrompt(),n.showAssistantLoading();const Vt=we(A),Tt=ss(t,Vt);if(Nt.length=0,!String(Tt||"").trim()){n.dismissTransientLoading(),n.refreshPrompt();return}if(Tt.length>Z){n.pushAssistant(e.red(`Input too long after command expansion (${Tt.length} chars).`)),n.pushSystem(e.gray(`Try shortening the command template or user text. Limit: ${Z} chars.`)),n.refreshPrompt();return}ut=!0;let K=v.systemPrompt||"You are Zibby, a helpful AI assistant.";const Xt=is(v,o);Xt&&(K+=`
65
65
 
66
- ${Xt}`);const Qt=ze({activeSkills:L,chatConfig:v,options:n});Qt&&(K+=`
66
+ ${Xt}`);const Qt=ze({activeSkills:L,chatConfig:v,options:o});Qt&&(K+=`
67
67
 
68
68
  ${Qt}`);const te=rs(L);if(te&&(K+=`
69
69
 
@@ -84,8 +84,8 @@ Use provided tools when external data/actions are required. Do not claim actions
84
84
  - Conversation flow: ask about purpose \u2192 input data \u2192 processing steps \u2192 output format \u2192 conditional logic.
85
85
  - Then call design_workflow to create a spec, review with user, then build_workflow to generate code.
86
86
  - After building: remind user about \`zibby start <name>\` (test), \`zibby deploy <name>\` (deploy), \`zibby logs\` (logs).
87
- - Use list_workflows to show existing workflows, add_node to extend them, deploy_workflow to ship.`),L.includes("chat-memory"))try{const a=$t("chat-memory");if(typeof a?.buildPromptContext=="function"){const _=Date.now();let g;et.data&&_-et.timestamp<F?(g=et.data,process.env.ZIBBY_VERBOSE==="true"&&r.pushSystem(e.gray("Using cached memory context"))):(g=await a.buildPromptContext({options:{workspace:t}},{}),et={data:g,timestamp:_},process.env.ZIBBY_VERBOSE==="true"&&r.pushSystem(e.gray("Refreshed memory context cache")));const T=String(g?.backend||"dolt");process.env.ZIBBY_VERBOSE==="true"&&(r.pushSystem(e.gray(`memory backend: ${T}`)),r.pushSystem(e.gray(`memory retrieval output: ${Et(JSON.stringify(g?.debugPreview||{}),1400)}`)),g?.error&&r.pushSystem(e.yellow(`memory backend warning: ${g.error}`))),g?.promptContext&&(K+=`
87
+ - Use list_workflows to show existing workflows, add_node to extend them, deploy_workflow to ship.`),L.includes("chat-memory"))try{const a=$t("chat-memory");if(typeof a?.buildPromptContext=="function"){const _=Date.now();let h;et.data&&_-et.timestamp<F?(h=et.data,process.env.ZIBBY_VERBOSE==="true"&&n.pushSystem(e.gray("Using cached memory context"))):(h=await a.buildPromptContext({options:{workspace:t}},{}),et={data:h,timestamp:_},process.env.ZIBBY_VERBOSE==="true"&&n.pushSystem(e.gray("Refreshed memory context cache")));const T=String(h?.backend||"dolt");process.env.ZIBBY_VERBOSE==="true"&&(n.pushSystem(e.gray(`memory backend: ${T}`)),n.pushSystem(e.gray(`memory retrieval output: ${Et(JSON.stringify(h?.debugPreview||{}),1400)}`)),h?.error&&n.pushSystem(e.yellow(`memory backend warning: ${h.error}`))),h?.promptContext&&(K+=`
88
88
 
89
- ${g.promptContext}`)}}catch(a){process.env.ZIBBY_VERBOSE==="true"&&r.pushSystem(e.yellow(`memory backend warning: ${String(a?.message||a)}`))}K=_t(K,ce);const Se=os(E),Ft=ns([{role:"system",content:K},...Se,{role:"user",content:Tt}]),ee=Ht(Ft),ke=Buffer.byteLength(JSON.stringify(Ft),"utf8");process.env.ZIBBY_VERBOSE==="true"&&r.pushSystem(e.gray(`payload estimate: ${ee} chars, ${ke} bytes (~${Math.round(ee/4)} tokens)`)),E.push({role:"human",content:Vt});const wt=r.enabled?(()=>{const a=()=>{};return a.setLabel=()=>{},a})():le();let at=!0;const Ct=[];let se="",bt="";const hs=50,ys=500,ws=3,bs=60,Ss=500,ks=15,$s=25,_s=4,xs=new Set([".","!","?",",",";",":"]),$e=a=>{at&&(wt(),at=!1),bt+=a},_e=(a,_)=>{if(!a){at&&wt.setLabel("thinking...");return}Ct.push(a);const g=70;let T=a;if(_&&typeof _=="object"){const S=Object.values(_).map(p=>typeof p=="string"?p:JSON.stringify(p)).join(", "),d=`${a}(${S})`;d.length<=g?T=d:T=`${a}(${S.slice(0,g-a.length-4)}...)`}T!==se&&(se=T,r.pushSystem(e.gray(`\u23BF ${T}`)),r.refreshPrompt({preserveInput:!0}),at&&r.showAssistantLoading()),at&&wt.setLabel(T)},jt=new AbortController;O=jt;try{const a=await xe("",{state:{agentType:C,config:k,cwd:t,workspace:t}},{model:k?.agent?.assistant?.model||v.model||"auto",workspace:t,skills:L,activeSkills:L,config:k,timeout:v.timeout||3e5,messages:Ft,skipPromptFragments:!0,stream:!0,onToken:$e,onToolCall:_e,signal:jt.signal});at&&wt();const _=typeof a=="string"?a:a?.structured?JSON.stringify(a.structured,null,2):a?.raw||String(a),g=bt&&bt.trim().length>0?bt.trim():_.trim(),T=cs(g,Ct)?g:as(g);r.pushAssistant(T);const b=Ct.length>0?`[tools used: ${Ct.join(", ")}]
90
- ${g}`:g;E.push({role:"ai",content:b}),Pt(t,E),It(t,L)}catch(a){if(at&&wt(),r.dismissTransientLoading(),jt.signal.aborted){ot.length===0&&r.pushAssistant(e.gray("[cancelled]"));let _="";try{const{testRunnerSkill:T}=await import("../../skills/index.js"),b=await T.handleToolCall("run_status",{runId:"all"},{options:{workspace:t}}),S=JSON.parse(b);S.runs?.length>0&&(_=`
91
- [Active test runs: ${S.runs.map(p=>`${p.runId}: ${p.ticketKey||p.spec} (${p.status})`).join(", ")}. Use run_status("all") to check progress.]`)}catch{}const g=bt.trim();g?E.push({role:"ai",content:g+_}):E.push({role:"ai",content:`[interrupted \u2014 new message]${_}`})}else{const _=String(a?.message||a||"Unknown error");/413|payload too large|request payload too large/i.test(_)?(r.pushAssistant(e.yellow("Request became too large for the proxy (413).")),r.pushSystem(e.gray("Try: /clear, then retry your command; or shorten command/context."))):r.pushAssistant(e.red(`Error: ${_}`)),E.push({role:"ai",content:`[Error: ${a.message}]`})}}finally{O=null,ut=!1}if(r.refreshPrompt(),ot.length>0){const a=ot.shift();pt=!0,setImmediate(()=>f.emit("line",a))}}catch(i){r.pushSystem(e.red(`Input handling error: ${i?.message||String(i)}`)),r.refreshPrompt()}}),f.on("SIGINT",()=>{if(O){O.abort();return}Lt()}),f.on("close",Lt);const be=()=>{process.stdin?.off?(process.stdin.off("data",xt),process.stdin.off("keypress",Ut)):process.stdin?.removeListener&&(process.stdin.removeListener("data",xt),process.stdin.removeListener("keypress",Ut))};f.on("close",be)})}export{Fs as _buildPrompt,Qe as _checkEnvKeys,Xe as _formatHistory,Us as _inferAgentType,Ds as chatCommand};
89
+ ${h.promptContext}`)}}catch(a){process.env.ZIBBY_VERBOSE==="true"&&n.pushSystem(e.yellow(`memory backend warning: ${String(a?.message||a)}`))}K=_t(K,ce);const Se=os(E),Ft=ns([{role:"system",content:K},...Se,{role:"user",content:Tt}]),ee=Ht(Ft),ke=Buffer.byteLength(JSON.stringify(Ft),"utf8");process.env.ZIBBY_VERBOSE==="true"&&n.pushSystem(e.gray(`payload estimate: ${ee} chars, ${ke} bytes (~${Math.round(ee/4)} tokens)`)),E.push({role:"human",content:Vt});const wt=n.enabled?(()=>{const a=()=>{};return a.setLabel=()=>{},a})():le();let at=!0;const Ct=[];let se="",bt="";const hs=50,ys=500,ws=3,bs=60,Ss=500,ks=15,$s=25,_s=4,xs=new Set([".","!","?",",",";",":"]),$e=a=>{at&&(wt(),at=!1),bt+=a},_e=(a,_)=>{if(!a){at&&wt.setLabel("thinking...");return}Ct.push(a);const h=70;let T=a;if(_&&typeof _=="object"){const S=Object.values(_).map(d=>typeof d=="string"?d:JSON.stringify(d)).join(", "),f=`${a}(${S})`;f.length<=h?T=f:T=`${a}(${S.slice(0,h-a.length-4)}...)`}T!==se&&(se=T,n.pushSystem(e.gray(`\u23BF ${T}`)),n.refreshPrompt({preserveInput:!0}),at&&n.showAssistantLoading()),at&&wt.setLabel(T)},jt=new AbortController;O=jt;try{const a=await xe("",{state:{agentType:C,config:k,cwd:t,workspace:t}},{model:k?.agent?.assistant?.model||v.model||"auto",workspace:t,skills:L,activeSkills:L,config:k,timeout:v.timeout||3e5,messages:Ft,skipPromptFragments:!0,stream:!0,onToken:$e,onToolCall:_e,signal:jt.signal});at&&wt();const _=typeof a=="string"?a:a?.structured?JSON.stringify(a.structured,null,2):a?.raw||String(a),h=bt&&bt.trim().length>0?bt.trim():_.trim(),T=cs(h,Ct)?h:as(h);n.pushAssistant(T);const b=Ct.length>0?`[tools used: ${Ct.join(", ")}]
90
+ ${h}`:h;E.push({role:"ai",content:b}),Pt(t,E),It(t,L)}catch(a){if(at&&wt(),n.dismissTransientLoading(),jt.signal.aborted){ot.length===0&&n.pushAssistant(e.gray("[cancelled]"));let _="";try{const{testRunnerSkill:T}=await import("../../skills/index.js"),b=await T.handleToolCall("run_status",{runId:"all"},{options:{workspace:t}}),S=JSON.parse(b);S.runs?.length>0&&(_=`
91
+ [Active test runs: ${S.runs.map(d=>`${d.runId}: ${d.ticketKey||d.spec} (${d.status})`).join(", ")}. Use run_status("all") to check progress.]`)}catch{}const h=bt.trim();h?E.push({role:"ai",content:h+_}):E.push({role:"ai",content:`[interrupted \u2014 new message]${_}`})}else{const _=String(a?.message||a||"Unknown error");/413|payload too large|request payload too large/i.test(_)?(n.pushAssistant(e.yellow("Request became too large for the proxy (413).")),n.pushSystem(e.gray("Try: /clear, then retry your command; or shorten command/context."))):n.pushAssistant(e.red(`Error: ${_}`)),E.push({role:"ai",content:`[Error: ${a.message}]`})}}finally{O=null,ut=!1}if(n.refreshPrompt(),ot.length>0){const a=ot.shift();pt=!0,setImmediate(()=>m.emit("line",a))}}catch(i){n.pushSystem(e.red(`Input handling error: ${i?.message||String(i)}`)),n.refreshPrompt()}}),m.on("SIGINT",()=>{if(O){O.abort();return}Lt()}),m.on("close",Lt);const be=()=>{process.stdin?.off?(process.stdin.off("data",xt),process.stdin.off("keypress",Ut)):process.stdin?.removeListener&&(process.stdin.removeListener("data",xt),process.stdin.removeListener("keypress",Ut))};m.on("close",be)})}export{Fs as _buildPrompt,Qe as _checkEnvKeys,Xe as _formatHistory,Us as _inferAgentType,Ds as chatCommand};
@@ -28,7 +28,7 @@ ZIBBY_API_KEY=${i}
28
28
 
29
29
  # AI Agent Key
30
30
  ${g.envVar}=${i}
31
- `,await p(t,n)}}if(b){const t=te($,s,{memoryBackend:m});await p(a(l,"package.json"),t)}if(!h(a(l,".gitignore"))){const t=ne();await p(a(l,".gitignore"),t)}if(!h(a(l,"playwright.config.js"))){const t=oe("on");await p(a(l,"playwright.config.js"),t)}if(!h(a(l,"test-specs/examples/example-domain.txt"))){const t=se();await p(a(l,"test-specs/examples/example-domain.txt"),t)}const B=O(q,"../../../../examples/.zibby/commands");if(h(B)){const t=G(B).filter(i=>i.toLowerCase().endsWith(".md"));for(const i of t){const n=a(l,".zibby/commands",i);if(o.force||!h(n)){const c=await w(a(B,i),"utf-8");await p(n,c)}}}if(!h(a(l,".zibby/commands/example.md"))){const t=ie();await p(a(l,".zibby/commands/example.md"),t)}if(b){const t=ae($,s);await p(a(l,"README.md"),t)}if(v.succeed(b?"Project created!":"Zibby initialized!"),b&&!o.skipInstall){const t=I("Installing dependencies...").start();await new Promise((i,n)=>{K("npm",["install"],{cwd:l,stdio:"pipe"}).on("close",r=>{r===0?(t.succeed("Dependencies installed!"),i()):(t.fail("Failed to install dependencies"),n(new Error("npm install failed")))})})}else if(!b){const t=["@zibby/cli","@zibby/core"],i=[];for(const n of t)try{Z(a(l,"package.json")).resolve(`${n}/package.json`)}catch{i.push(n)}if(i.length>0){const n=N("../../package.json"),c=i.map(r=>r==="@zibby/cli"?`${r}@latest`:r==="@zibby/core"?`${r}@${n.dependencies?.["@zibby/core"]||"^0.1.29"}`:r);if(o.skipInstall)console.log(e.yellow(`
31
+ `,await p(t,n)}}if(b){const t=te($,s,{memoryBackend:m});await p(a(l,"package.json"),t)}if(!h(a(l,".gitignore"))){const t=ne();await p(a(l,".gitignore"),t)}if(!h(a(l,"playwright.config.js"))){const t=oe("on");await p(a(l,"playwright.config.js"),t)}if(!h(a(l,"test-specs/examples/example-domain.txt"))){const t=se();await p(a(l,"test-specs/examples/example-domain.txt"),t)}const B=O(q,"../../../../examples/.zibby/commands");if(h(B)){const t=G(B).filter(i=>i.toLowerCase().endsWith(".md"));for(const i of t){const n=a(l,".zibby/commands",i);if(o.force||!h(n)){const c=await w(a(B,i),"utf-8");await p(n,c)}}}if(!h(a(l,".zibby/commands/example.md"))){const t=ie();await p(a(l,".zibby/commands/example.md"),t)}if(b){const t=ae($,s);await p(a(l,"README.md"),t)}if(v.succeed(b?"Project created!":"Zibby initialized!"),b&&!o.skipInstall){const t=I("Installing dependencies...").start();await new Promise((i,n)=>{K("npm",["install"],{cwd:l,stdio:"pipe"}).on("close",r=>{r===0?(t.succeed("Dependencies installed!"),i()):(t.fail("Failed to install dependencies"),n(new Error("npm install failed")))})})}else if(!b){const t=["@zibby/cli","@zibby/core"],i=[];for(const n of t)try{Z(a(l,"package.json")).resolve(`${n}/package.json`)}catch{i.push(n)}if(i.length>0){const n=N("../../package.json"),c=i.map(r=>r==="@zibby/cli"?`${r}@latest`:r==="@zibby/core"?`${r}@${n.dependencies?.["@zibby/core"]||"latest"}`:r);if(o.skipInstall)console.log(e.yellow(`
32
32
  Missing required Zibby dependencies in this project:`)),console.log(e.white(` ${i.join(", ")}`)),console.log(e.gray("Install them manually to avoid runtime errors:")),console.log(e.white(` npm install --save-dev ${c.join(" ")}
33
33
  `));else{const r=I(`Installing ${c.join(", ")}...`).start();await new Promise(M=>{K("npm",["install","--save-dev",...c],{cwd:l,stdio:"pipe"}).on("close",_=>M(_??1))})===0?r.succeed("Installed missing Zibby dependencies"):(r.warn("Could not auto-install Zibby dependencies"),console.log(e.gray("Run this manually:")),console.log(e.white(` npm install --save-dev ${c.join(" ")}
34
34
  `)))}}}if(!b&&f&&m==="mem0"&&(console.log(e.yellow(`
@@ -165,7 +165,7 @@ ZIBBY_API_KEY=${o}
165
165
 
166
166
  # Chat memory backend
167
167
  ZIBBY_MEMORY_BACKEND=${f}
168
- `}function te(d,o,f={}){const l={"@zibby/cli":"latest","@zibby/core":N("../../package.json").dependencies?.["@zibby/core"]||"^0.1.29"};return f.memoryBackend==="mem0"&&(l.mem0ai="^2.4.6"),JSON.stringify({name:d,version:"1.0.0",type:"module",private:!0,scripts:{"test:spec":"zibby run",test:"playwright test","test:headed":"playwright test --headed"},dependencies:l,devDependencies:{"@playwright/test":"^1.49.0",dotenv:"^17.2.3"}},null,2)}function ne(){return`# Dependencies
168
+ `}function te(d,o,f={}){const l={"@zibby/cli":"latest","@zibby/core":N("../../package.json").dependencies?.["@zibby/core"]||"latest"};return f.memoryBackend==="mem0"&&(l.mem0ai="^2.4.6"),JSON.stringify({name:d,version:"1.0.0",type:"module",private:!0,scripts:{"test:spec":"zibby run",test:"playwright test","test:headed":"playwright test --headed"},dependencies:l,devDependencies:{"@playwright/test":"^1.49.0",dotenv:"^17.2.3"}},null,2)}function ne(){return`# Dependencies
169
169
  node_modules/
170
170
 
171
171
  # Test artifacts
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/cli",
3
- "version": "0.1.52",
3
+ "version": "0.1.54",
4
4
  "description": "Zibby CLI - Test automation generator and runner",
5
5
  "type": "module",
6
6
  "bin": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/cli",
3
- "version": "0.1.52",
3
+ "version": "0.1.54",
4
4
  "description": "Zibby CLI - Test automation generator and runner",
5
5
  "type": "module",
6
6
  "bin": {