@zibby/cli 0.1.60 → 0.1.61

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.
Files changed (39) hide show
  1. package/dist/auth/cli-login.js +12 -12
  2. package/dist/commands/agent-reliability.js +4 -4
  3. package/dist/commands/analyze-graph.js +14 -14
  4. package/dist/commands/chat-session-store.js +1 -1
  5. package/dist/commands/chat.js +71 -62
  6. package/dist/commands/ci-setup.js +3 -3
  7. package/dist/commands/generate.js +60 -21
  8. package/dist/commands/implement.js +15 -15
  9. package/dist/commands/init.js +87 -67
  10. package/dist/commands/list-projects.js +9 -9
  11. package/dist/commands/memory.js +13 -13
  12. package/dist/commands/project.js +8 -8
  13. package/dist/commands/run-capacity-queue-cli.js +2 -2
  14. package/dist/commands/run.js +52 -50
  15. package/dist/commands/setup-scripts.js +6 -6
  16. package/dist/commands/studio.js +21 -15
  17. package/dist/commands/uninstall.js +10 -10
  18. package/dist/commands/upload.js +15 -15
  19. package/dist/commands/video.js +1 -1
  20. package/dist/commands/workflow.js +35 -35
  21. package/dist/commands/workflows/deploy.js +10 -10
  22. package/dist/commands/workflows/generate.js +17 -17
  23. package/dist/commands/workflows/list.js +15 -15
  24. package/dist/commands/workflows/logs.js +13 -13
  25. package/dist/commands/workflows/run.js +7 -7
  26. package/dist/commands/workflows/start.js +6 -6
  27. package/dist/commands/workflows/trigger.js +7 -7
  28. package/dist/config/config-loader.js +1 -1
  29. package/dist/config/config.js +1 -1
  30. package/dist/config/environments.js +1 -1
  31. package/dist/package.json +4 -4
  32. package/dist/utils/agent-credentials.js +3 -3
  33. package/dist/utils/chat-run-lifecycle.js +3 -3
  34. package/dist/utils/execution-context.js +1 -1
  35. package/dist/utils/progress-reporter.js +1 -1
  36. package/dist/utils/studio-cli-log-mirror.js +1 -1
  37. package/dist/utils/studio-installer.js +5 -5
  38. package/dist/utils/studio-launcher.js +1 -1
  39. package/package.json +1 -1
@@ -1,82 +1,91 @@
1
- import{invokeAgent as _e,getAgentStrategy as ve,getSkill as $t}from"@zibby/core";import{existsSync as gt,readFileSync as oe,readdirSync as Te}from"fs";import{resolve as ut,join as Dt,dirname as Ce,basename as Ie}from"path";import{createInterface as Pe,moveCursor as M,cursorTo as B,clearLine as q,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+=`
1
+ var dn=Object.defineProperty;var mn=(e,t)=>()=>(e&&(t=e(e=0)),t);var gn=(e,t)=>{for(var n in t)dn(e,n,{get:t[n],enumerable:!0})};var se={};gn(se,{cleanupStalePidFiles:()=>Mn,killAllChatOrchestratedRuns:()=>On,killPidTreeBestEffort:()=>We,registerChatOrchestratedRun:()=>Ln,unregisterChatOrchestratedRun:()=>Bn});import{existsSync as ee,mkdirSync as Tn,readFileSync as Pn,readdirSync as Cn,unlinkSync as ne,writeFileSync as ze}from"fs";import{join as Ft}from"path";import{execSync as He}from"child_process";import{DEFAULT_OUTPUT_BASE as Nn}from"@zibby/core";function Mt(e){return e?.paths?.output||Nn}function jt(e,t,n){return Ft(e,t,`.zibby-chat-run-pids-${n}.json`)}function oe(e,t,n){let s=jt(e,t,n);if(!ee(s))return[];try{let r=JSON.parse(Pn(s,"utf8"));return(Array.isArray(r?.pids)?r.pids:[]).map(l=>Number(l)).filter(l=>Number.isFinite(l)&&l>0)}catch{return[]}}function Ln(e,t,n,s={}){let r=Number(t),c=Number(n);if(!Number.isFinite(r)||r<=0||!Number.isFinite(c)||c<=0)return;let l=Mt(s),d=Ft(e,l);Tn(d,{recursive:!0});let y=oe(e,l,r);y.includes(c)||y.push(c),ze(jt(e,l,r),`${JSON.stringify({v:1,pids:y})}
2
+ `,"utf8")}function Bn(e,t,n,s={}){let r=Number(t),c=Number(n);if(!Number.isFinite(r)||r<=0||!Number.isFinite(c)||c<=0)return;let l=Mt(s),d=jt(e,l,r);if(!ee(d))return;let y=oe(e,l,r).filter(L=>L!==c);if(y.length===0)try{ne(d)}catch{}else ze(d,`${JSON.stringify({v:1,pids:y})}
3
+ `,"utf8")}function En(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)return[];try{let n=He(`pgrep -P ${t}`,{encoding:"utf8",stdio:["ignore","pipe","ignore"],maxBuffer:524288}).trim();return n?n.split(/\n/).map(s=>parseInt(s.trim(),10)).filter(s=>Number.isFinite(s)&&s>0):[]}catch{return[]}}function Ye(e,t){let n=Number(e);if(!Number.isFinite(n)||n<=0)return;let s=new Set;function r(c){if(!s.has(c)){s.add(c);for(let l of En(c))r(l);try{process.kill(c,t)}catch{}}}r(n)}function Rn(e){let t=Number(e);if(!(!Number.isFinite(t)||t<=0))try{He(`taskkill /PID ${t} /T /F`,{stdio:"ignore",windowsHide:!0})}catch{}}function We(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)return;if(process.platform==="win32"){Rn(t);return}Ye(t,"SIGTERM");let n=setTimeout(()=>{Ye(t,"SIGKILL")},800);typeof n.unref=="function"&&n.unref()}function On(e,t,n={}){let s=Number(t);if(!Number.isFinite(s)||s<=0)return;let r=Mt(n),c=jt(e,r,s),l=oe(e,r,s);for(let d of l)d!==process.pid&&We(d);try{ee(c)&&ne(c)}catch{}}function Un(e){try{return process.kill(e,0),!0}catch{return!1}}function Mn(e,t={}){let n=Mt(t),s=Ft(e,n),r;try{r=Cn(s)}catch{return}for(let c of r){let l=Fn.exec(c);if(!l)continue;let d=Number(l[1]);if(!(!Number.isFinite(d)||d<=0)&&!Un(d))try{ne(Ft(s,c))}catch{}}}var Fn,re=mn(()=>{Fn=/^\.zibby-chat-run-pids-(\d+)\.json$/});import{invokeAgent as jn,getAgentStrategy as Dn,getSkill as Pt}from"@zibby/core";import{existsSync as yt,readFileSync as Xe,readdirSync as Yn}from"fs";import{resolve as ft,join as ce,dirname as zn,basename as Hn}from"path";import{createInterface as Wn,moveCursor as E,cursorTo as U,clearLine as G,emitKeypressEvents as Zn}from"readline";import{fileURLToPath as Jn}from"url";import{homedir as Gn}from"os";import o from"chalk";import{highlight as Ze}from"cli-highlight";import Vn from"dotenv";import{existsSync as xe,mkdirSync as hn,readFileSync as yn,writeFileSync as bn}from"fs";import{homedir as ke}from"os";import{join as Rt}from"path";function _e(){return process.env.ZIBBY_CONFIG_DIR||Rt(ke(),".zibby")}function ve(){return Rt(_e(),"config.json")}var wn=Rt(ke(),".zibby"),Eo=Rt(wn,"config.json");function Sn(){let e=_e();xe(e)||hn(e,{recursive:!0})}function X(){try{let e=ve();if(xe(e)){let t=yn(e,"utf-8");return JSON.parse(t)}}catch{}return{}}function vt(e){Sn(),bn(ve(),JSON.stringify(e,null,2))}function Ot(){return X().sessionToken||null}function $e(e){let t=X();t.sessionToken=e,vt(t)}function Ie(){return X().user||null}function Ae(e){let t=X();t.user=e,vt(t)}function Te(){let e=X();delete e.sessionToken,delete e.user,delete e.mem0ProxyUrl,vt(e)}function Pe(){return X().proxyUrl||null}function Ce(e){let t=X();t.proxyUrl=e,vt(t)}function Ne(){return X().mem0ProxyUrl||null}function Le(e){let t=X();t.mem0ProxyUrl=e,vt(t)}function Be(){return X().projects||[]}var $t={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.app",description:"Production environment"}};function Xt(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let t=process.env.ZIBBY_ENV||"prod";$t[t]?e=$t[t].apiUrl:e=$t.prod.apiUrl}try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${t.protocol} (only http/https allowed)`),$t.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),$t.prod.apiUrl}}import{existsSync as Qt,mkdirSync as xn,readFileSync as Ee,writeFileSync as Re,unlinkSync as Fo}from"fs";import{resolve as It}from"path";var kn=30;function Oe(e){let t=It(e,".zibby","output");return Qt(t)||xn(t,{recursive:!0}),t}function Ue(e){let t=It(e,".zibby","output","chat-history.json");if(!Qt(t))return[];try{let n=JSON.parse(Ee(t,"utf-8"));return Array.isArray(n)?n:[]}catch{return[]}}function At(e,t){let n=Oe(e),s=It(n,"chat-history.json");try{Re(s,JSON.stringify((t||[]).slice(-kn*2),null,2),"utf-8")}catch{}}function Fe(e){let t=It(e,".zibby","output","active-skills.json");if(!Qt(t))return null;try{let n=JSON.parse(Ee(t,"utf-8"));return Array.isArray(n)?n:null}catch{return null}}function Tt(e,t){let n=Oe(e),s=It(n,"active-skills.json");try{Re(s,JSON.stringify(Array.isArray(t)?t:[]),"utf-8")}catch{}}var te={cli_reliable_v1:{title:"General intelligence reliability contract",operatingRules:["Evidence-first reasoning: ground conclusions in observed outputs or tool evidence, not guesses.","No false completion: never claim success for a state-changing action until verification confirms it.","Execution integrity: do not claim any external action unless the matching tool call actually happened.","Bounded recovery: for transient failures, retry with adjusted parameters up to 2 times, then escalate with blocker + next step.",'Binary-answer discipline: for yes/no questions, verify the exact asked condition before answering; do not answer "yes" from a broader or approximate match.'],executionSafety:["Prefer low-blast-radius, reversible actions first.","Before irreversible or high-impact actions, confirm explicit user intent unless already authorized.","If verification cannot be run, state that limitation explicitly."],investigationLoop:["For unclear failures, follow this loop: detect -> gather evidence -> form hypothesis -> test hypothesis -> conclude.","If evidence is insufficient, explicitly collect more before proposing a root cause.","Prefer smallest validating action first before broad or costly retries."],responseQuality:["State assumptions explicitly when certainty is low.","Differentiate facts, hypotheses, and next actions.","Keep reports concise but decision-useful.","If related-but-not-identical matches exist, report them separately as context, not as the direct yes/no answer."],incidentTemplate:["ONLY when diagnosing failures or errors (never for successful actions), structure your response as: Root cause, Evidence, Attempted fixes, Current status, Next action."],skillRunbooks:{}}},je=2e3,Me=12e3;function Ut(e=[]){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let s of e){let r=String(s||"").replace(/\s+/g," ").trim();r&&(t.has(r)||(t.add(r),n.push(r)))}return n}function _n(e,t=je){let n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-14)).trimEnd()}
3
4
 
4
- ${Xe(t)}`),r+=`
5
- H: ${s}
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=ut(o,".zibby.config.mjs");if(!gt(t))return{};try{return import(t).then(s=>s.default||{})}catch{return{}}}async function es(o){const t=ut(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=ut(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=ut(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=ut(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}
5
+ [truncated]`}function pt(e,t=[],n=je){let s=Ut(t);if(s.length===0)return"";let r=[`## ${e}`,...s.map(c=>`- ${c}`)].join(`
6
+ `);return _n(r,n)}function vn(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function $n(e,t){let n={...e,...t},s=["operatingRules","rules","executionSafety","investigationLoop","responseQuality","incidentTemplate"];for(let r of s)Array.isArray(t?.[r])?n[r]=[...Ut(e?.[r]||[]),...Ut(t[r])]:Array.isArray(e?.[r])&&(n[r]=[...Ut(e[r])]);return n.skillRunbooks={...e?.skillRunbooks||{},...t?.skillRunbooks||{}},n}function In(e={},t={}){let n=Array.isArray(e?.reliabilityAppendSections)?e.reliabilityAppendSections:[],s=Array.isArray(t?.reliabilityAppendSections)?t.reliabilityAppendSections:[];return[...n,...s].map(r=>{if(typeof r=="string")return{title:"Additional reliability guidance",lines:[r]};if(!r||typeof r!="object")return null;let c=String(r.title||"Additional reliability guidance").trim(),l=Array.isArray(r.lines)?r.lines:[];return{title:c,lines:l}}).filter(Boolean)}function An(e={},t={}){let n=String(t.reliabilityProfile||process.env.ZIBBY_RELIABILITY_PROFILE||e.reliabilityProfile||"cli_reliable_v1").trim(),s=e?.reliabilityProfiles?.[n];if(typeof s=="string"&&s.trim())return{name:n,text:s.trim()};if(s&&typeof s.instruction=="string"&&s.instruction.trim())return{name:n,text:s.instruction.trim()};let r=te[n]||te.cli_reliable_v1,c=vn(s),l=c?$n(r,c):r;return{name:n,defaults:l}}function De({activeSkills:e=[],chatConfig:t={},options:n={}}={}){let s=An(t,n);if(s.text)return s.text;let r=s.defaults||te.cli_reliable_v1,c=[pt(r.title||"Reliability contract",r.operatingRules||r.rules||[]),pt("Execution safety",r.executionSafety||[]),pt("Investigation loop",r.investigationLoop||[]),pt("Response quality",r.responseQuality||[]),pt("Failure reporting format",r.incidentTemplate||[])],l=r.skillRunbooks||{};for(let L of e)l[L]&&c.push(pt(`Runbook: ${L}`,l[L]));let d=In(t,n);for(let L of d)c.push(pt(L.title,L.lines));let y=c.filter(Boolean).join(`
7
7
 
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 xt(o,t){const s=String(o||"");return s.length<=t?s:`${s.slice(0,Math.max(0,t-24))}
8
+ `).trim();return y.length<=Me?y:`${y.slice(0,Math.max(0,Me-14)).trimEnd()}
9
9
 
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:xt(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:xt(k.content,2500)}));return t=[s,...l,r],Ht(t)<=ae||(t=[{...s,content:xt(s?.content,6e3)},{...r,content:xt(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)
10
+ [truncated]`}var qn=Jn(import.meta.url),Kn=zn(qn),Xn=JSON.parse(Xe(ce(Kn,"../../package.json"),"utf-8")),Qe=30,Qn=54,to=18e3,tn=12e3,Je=42e3;function eo(e){return new Promise(t=>setTimeout(t,e))}var Dt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],ae=[{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 Ge(){let e=0,t="thinking...",n=setInterval(()=>{let r=o.cyan(Dt[e%Dt.length]),c=e%3,l=c===0?o.white(".")+o.gray(".")+o.dim("."):c===1?o.dim(".")+o.white(".")+o.gray("."):o.gray(".")+o.dim(".")+o.white("."),d=t.replace(/\.+$/,""),y=` ${r} ${o.gray(d)}${l}`;process.stdout.write(`\r${" ".repeat(80)}\r${y}`),e++},300),s=()=>{clearInterval(n),process.stdout.write(`\r${" ".repeat(80)}\r`)};return s.setLabel=r=>{t=r},s}function rs(e){let t=e?.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 no(e){return e.slice(-Qe).map(t=>`${t.role==="human"?"H":"AI"}: ${t.content}`).join(`
11
+ `)}function is(e,t,n){let s=e;return t.length>0&&(s+=`
12
+
13
+ ${no(t)}`),s+=`
14
+ H: ${n}
15
+ AI:`,s}function oo(e){let t=e.filter(n=>!process.env[n]);return{ok:t.length===0,missing:t}}function so(e){let t=ft(e,".zibby.config.mjs");if(!yt(t))return{};try{return import(t).then(n=>n.default||{})}catch{return{}}}async function ro(e){let t=ft(e,".zibby","chat.mjs");if(yt(t)){let r=await import(t);if(r.CHAT_CONFIG||r.default)return r.CHAT_CONFIG||r.default}let n=ft(Gn(),".zibby","chat.mjs");if(n!==t&&yt(n)){let r=await import(n);if(r.CHAT_CONFIG||r.default)return r.CHAT_CONFIG||r.default}let s=await import("@zibby/core/templates/browser-test-automation/chat.mjs");return s.CHAT_CONFIG||s.default||{}}function Ve(e){try{let t=ft(e,".zibby","commands");return yt(t)?Yn(t).filter(n=>n.toLowerCase().endsWith(".md")).sort((n,s)=>n.localeCompare(s)):[]}catch{return[]}}function io(e,t){let n=String(t||"").trim();if(!n.startsWith("/"))return n;let[s,...r]=n.split(/\s+/),c=r.join(" ").trim(),l=s.slice(1);if(!l)return n;let d=l.toLowerCase().endsWith(".md")?[l]:[l,`${l}.md`],y=ft(e,".zibby","commands"),L=d.find(F=>yt(ce(y,F)));if(!L)return n;try{let F=Xe(ce(y,L),"utf-8").trim();return c?`${F}
16
+
17
+ ${c}`:F}catch{return n}}function co(e){let t=e.slice(-Qe),n=[],s=0;for(let r=t.length-1;r>=0;r--){let c=t[r],l=String(c?.content||""),d=c?.role==="human"?"user":"assistant",y=l.length;if(n.length>=6&&s+y>to)break;n.push({role:d,content:l}),s+=y}return n.reverse()}function Ct(e,t){let n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-24))}
18
+
19
+ [truncated for proxy size]`}function le(e){return e.reduce((t,n)=>t+String(n?.content||"").length+64,0)}function lo(e){let t=[...e];if(t.length===0||(t[0]?.role==="system"&&(t[0]={...t[0],content:Ct(t[0].content,tn)}),le(t)<=Je))return t;let n=t[0],s=t[t.length-1],r=t.slice(1,-1).slice(-4).map(c=>({...c,content:Ct(c.content,2500)}));return t=[n,...r,s],le(t)<=Je||(t=[{...n,content:Ct(n?.content,6e3)},{...s,content:Ct(s?.content,8e3)}]),t}function ao(e){let t=[];for(let n of e){let s=Pt(n),r=String(s?.description||"").trim();if(!r){t.push(`- ${n}`);continue}t.push(`- ${n}: ${Yt(r,80)}`)}return t.length===0?"":`## Active skills (call get_skill_context before first use)
11
20
  ${t.join(`
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(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
- ${v}
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],it=["Workspace details","",`v${qe.version} | Hi, ${U}`,`Company: ${R}`,`Directory: ~/${ht}`,`Path: ${t}`,"","Use /help for commands"],E=Math.max(W.length,it.length),X=(()=>{if(W.length>=E)return W;const F=Math.floor((E-W.length)/2),nt=E-W.length-F;return[...Array(F).fill(""),...W,...Array(nt).fill("")]})(),z="\u2500",L=` \u250C${z.repeat(C+2)}\u252C${z.repeat(I+2)}\u2510`,ot=` \u2514${z.repeat(C+2)}\u2534${z.repeat(I+2)}\u2518`;console.log(e.gray(L));for(let F=0;F<E;F++){const nt=Et(X[F]||"",C),ct=Et(it[F]||"",I),yt=" ".repeat(Math.max(0,C-nt.length)),u=" ".repeat(Math.max(0,I-ct.length)),w=` \u2502 ${nt}${yt} \u2502 ${ct}${u} \u2502`;console.log(e.gray(w))}console.log(e.gray(ot)),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),q(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),q(process.stdout,0),u<C-1&&M(process.stdout,0,1);process.stdout.write("\x1B8"),C=0,r&&it()}}function it(){!t||!s||!r||(process.stdout.write("\x1B7"),M(process.stdout,0,1),B(process.stdout,0),q(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),q(process.stdout,0);const Z=y===w?e.cyan("\u203A"):" ",m=y===w?e.white(c[y]):e.gray(c[y]);process.stdout.write(` ${Z} /${m}`),y<c.length-1&&M(process.stdout,0,1)}process.stdout.write("\x1B8"),C=c.length,it()}}function X(){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 z(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
- ${c}
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),q(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),q(process.stdout,0),process.stdout.write(c);for(let y=1;y<w;y++)M(process.stdout,0,1),B(process.stdout,0),q(process.stdout,0);process.stdout.write("\x1B8"),I=zt().length}function ot(){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),q(process.stdout,0),process.stdout.write(U()),M(process.stdout,0,u+2),B(process.stdout,0),q(process.stdout,0),process.stdout.write(U()),process.stdout.write("\x1B8")}function F(u){R(),X(),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 nt(u){const w=String(u??"").replace(/\r/g,"").split(`
21
- `);w.length===0&&w.push("");const c=[];for(const y of w)c.push(e.bgGray.white(` ${y||" "} `));return c.join(`
22
- `)}function ct(){R();const u=()=>e.gray(`${At[v%At.length]} thinking`);if(!t){console.log(` ${u()}`),l=!0;return}W(),X(),console.log(),console.log(` ${u()}`),z({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}X(),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,z()}},refreshPrompt(u={}){if(t&&s){r&&X(),z(u);return}o.prompt()},pushSystem(u){F(u)},pushUser(u){F(nt(u))},pushAssistant(u){yt(u)},showAssistantLoading:ct,dismissTransientLoading(){R(),l&&t&&s&&r&&(process.stdout.write("\x1B7"),M(process.stdout,0,-2),B(process.stdout,0),q(process.stdout,0),M(process.stdout,0,-1),B(process.stdout,0),q(process.stdout,0),process.stdout.write("\x1B8")),l=!1},touchInputFrame:ot,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;[ut(t,".env.local"),ut(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"),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:m,verificationUrl:n,expiresIn:O,interval:Q}=await Z.json(),Y=process.platform;y(Y==="darwin"?"open":Y==="win32"?"cmd":"xdg-open",Y==="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 at=le();at.setLabel("waiting for authorization");const pt=(Q||3)*1e3,dt=Math.floor(O/(Q||3));let tt=!1;for(let rt=0;rt<dt;rt++){await Ve(pt);try{const et=await fetch(`${c}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:m})});if(et.status===202)continue;if(!et.ok)break;const J=await et.json();if(J.status==="authorized"){Be(J.token),Re(J.user),J.proxyUrl&&Fe(J.proxyUrl),J.mem0ProxyUrl&&We(J.mem0ProxyUrl),tt=!0;break}if(J.status==="denied")break}catch{break}}at(),tt||(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
- ${c.message}
27
- `)),process.exit(1)}const ht=Ne(),it=Oe()?.[0]?.name,E=He(t),X=v.skills||[],z=Ye(t),L=z?[...new Set([...X,...z])]:[...X];let ot={data:null,timestamp:0};const F=300*1e3,nt={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 m=await Z.json();for(const[n,O]of Object.entries(nt)){const Q=m[n]?.connected,Y=L.indexOf(O);Q&&Y===-1&&$t(O)?L.push(O):!Q&&Y!==-1&&L.splice(Y,1)}It(t,L)}}}catch{}const ct=L.filter(c=>c!=="skill-installer"&&c!=="core-tools"),yt=ct.length>0?`Skills: ${ct.join(", ")}`:"Skills: (none)";us({userName:ht?.name?.split(" ")[0],cwd:t,projectName:it,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",Z={input:process.stdin,output:process.stdout,prompt:e.green(" > "),terminal:!0};y&&(Z.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(Z),n=ds(m);let O=null,Q=!1;const Y=[],fe=0,me=1200;let at=!1,pt=!1,dt=!1,tt=!1,rt="",et=0;const J=typeof m._ttyWrite=="function"?m._ttyWrite.bind(m):null;J&&(m._ttyWrite=(...p)=>{if(!(tt||Date.now()<et))return J(...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(!tt&&!p.includes(i))return!1;let $=p,P=!1;for(;$.length>0;){if(!tt){const A=$.indexOf(i);if(A===-1)break;P=!0,Kt(),tt=!0,rt="",$=$.slice(A+i.length);continue}const G=$.indexOf(g);if(G===-1){P=!0,rt+=$;break}P=!0,rt+=$.slice(0,G);const st=String(rt||"").replace(/\r\n/g,`
21
+ `)}`}var qe={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(`
22
+ `)};function uo(e={},t={}){let n=String(t.outputProfile||process.env.ZIBBY_OUTPUT_PROFILE||e.outputProfile||"cli_plain").trim(),s=e?.outputProfiles?.[n];return typeof s=="string"&&s.trim()?s.trim():s&&typeof s.instruction=="string"&&s.instruction.trim()?s.instruction.trim():qe[n]||qe.cli_plain}function Yt(e,t){let n=String(e??"");return n.length<=t?n:t<=1?n.slice(0,t):`${n.slice(0,t-1)}\u2026`}function po(){return!1}function fo(e){let t=/^```(\w*)\n([\s\S]*?)^```$/gm;return e.replace(t,(n,s,r)=>{let c=r.replace(/\n$/,"");try{let l=s?Ze(c,{language:s,ignoreIllegals:!0}):Ze(c,{ignoreIllegals:!0}),d=o.gray("\u2500".repeat(Math.min(process.stdout.columns-6||54,72))),y=s?o.dim(` ${s}`):"";return`${d}${y}
23
+ ${l}
24
+ ${d}`}catch{return c}})}function ie(){let e=Number(process.stdout?.columns)||0,t=e>8?Math.max(30,e-4):Qn;return` ${"\u2500".repeat(t)}`}function Ke(e=[]){let t=ae.map(s=>({cmd:s.cmd,source:"builtin",name:s.cmd.slice(1),desc:s.desc})),n=e.map(s=>({cmd:`/${s}`,source:"template",name:s,desc:"Command template"}));return[...t,...n]}function mo(e,t){let n=String(e||""),s=Number.isFinite(t)?t:n.length;return!(!n.startsWith("/")||s!==n.length||n.includes(" "))}function go({userName:e,cwd:t,projectName:n,restoredCount:s,skillsLine:r}){let c=Number(process.stdout?.columns)||0,l=Math.max(40,Math.min(c-8,100)),d=Math.max(20,Math.floor((l-3)*.55)),y=l-d-3,L=e||"there",F=n||"No project linked",bt=Hn(t||process.cwd()),Y=[`Restored ${s} messages from previous session.`,"",r],ct=["Workspace details","",`v${Xn.version} | Hi, ${L}`,`Company: ${F}`,`Directory: ~/${bt}`,`Path: ${t}`,"","Use /help for commands"],N=Math.max(Y.length,ct.length),Q=(()=>{if(Y.length>=N)return Y;let M=Math.floor((N-Y.length)/2),rt=N-Y.length-M;return[...Array(M).fill(""),...Y,...Array(rt).fill("")]})(),W="\u2500",B=` \u250C${W.repeat(d+2)}\u252C${W.repeat(y+2)}\u2510`,st=` \u2514${W.repeat(d+2)}\u2534${W.repeat(y+2)}\u2518`;console.log(o.gray(B));for(let M=0;M<N;M++){let rt=Yt(Q[M]||"",d),lt=Yt(ct[M]||"",y),wt=" ".repeat(Math.max(0,d-rt.length)),f=" ".repeat(Math.max(0,y-lt.length)),k=` \u2502 ${rt}${wt} \u2502 ${lt}${f} \u2502`;console.log(o.gray(k))}console.log(o.gray(st)),console.log("")}function ho(){process.stdout?.isTTY&&(E(process.stdout,0,-2),U(process.stdout,4))}function yo(e){let t=!!(process.stdout?.isTTY&&process.stdin?.isTTY),n=!1,s=!1,r=!1,c=null,l=0,d=0,y=0;function L(){return o.gray(ie())}function F(){c&&(clearInterval(c),c=null)}function bt(f){!t||!n||!s||!r||(process.stdout.write("\x1B7"),E(process.stdout,0,-2),U(process.stdout,0),G(process.stdout,0),process.stdout.write(` ${f}`),process.stdout.write("\x1B8"))}function Y(){if(!(!t||!n)&&d!==0){process.stdout.write("\x1B7"),E(process.stdout,0,2);for(let f=0;f<d;f++)U(process.stdout,0),G(process.stdout,0),f<d-1&&E(process.stdout,0,1);process.stdout.write("\x1B8"),d=0,s&&ct()}}function ct(){!t||!n||!s||(process.stdout.write("\x1B7"),E(process.stdout,0,1),U(process.stdout,0),G(process.stdout,0),process.stdout.write(L()),process.stdout.write("\x1B8"))}function N(f,k){if(!t||!n||!s)return;Y();let u=f.slice(0,6);if(u.length!==0){E(process.stdout,0,1);for(let x=0;x<u.length;x++)process.stdout.write(`
25
+ `);E(process.stdout,0,-(1+u.length)),process.stdout.write("\x1B7"),E(process.stdout,0,2);for(let x=0;x<u.length;x++){U(process.stdout,0),G(process.stdout,0);let V=x===k?o.cyan("\u203A"):" ",b=x===k?o.white(u[x]):o.gray(u[x]);process.stdout.write(` ${V} /${b}`),x<u.length-1&&E(process.stdout,0,1)}process.stdout.write("\x1B8"),d=u.length,ct()}}function Q(){if(!t||!n||!s)return;Y();let f=process.stdout.columns||80,k=y>0?Math.ceil(y/f):1;U(process.stdout,0),E(process.stdout,0,-k),r&&E(process.stdout,0,-2),process.stdout.write("\x1B[J"),s=!1}function W(f={}){let k=f.preserveInput===!0;if(!t){e.prompt();return}k||(e.line="",e.cursor=0),y=ie().length;let u=L();process.stdout.write(`${u}
26
+ `),e.prompt(),process.stdout.write(`
27
+ ${u}
28
+ `),ho(),s=!0}function B(){if(!t||!n||!s)return;let f=process.stdout.columns||80,k=y>0?Math.ceil(y/f):1,u=L();process.stdout.write("\x1B7"),E(process.stdout,0,-k);for(let x=0;x<k;x++)U(process.stdout,0),G(process.stdout,0),x<k-1&&E(process.stdout,0,1);U(process.stdout,0),process.stdout.write(u),E(process.stdout,0,2),U(process.stdout,0),G(process.stdout,0),process.stdout.write(u);for(let x=1;x<k;x++)E(process.stdout,0,1),U(process.stdout,0),G(process.stdout,0);process.stdout.write("\x1B8"),y=ie().length}function st(){if(!t||!n||!s)return;let f=(()=>{if(typeof e.getCursorPos!="function")return 0;try{return Math.max(0,Number(e.getCursorPos()?.rows||0))}catch{return 0}})();process.stdout.write("\x1B7"),E(process.stdout,0,-(f+1)),U(process.stdout,0),G(process.stdout,0),process.stdout.write(L()),E(process.stdout,0,f+2),U(process.stdout,0),G(process.stdout,0),process.stdout.write(L()),process.stdout.write("\x1B8")}function M(f){F(),Q(),console.log();let k=String(f??"").replace(/\r/g,"").split(`
29
+ `);for(;k.length>0&&k[k.length-1]==="";)k.pop();for(let u of k)console.log(u?` ${u}`:"");r=!1}function rt(f){let k=String(f??"").replace(/\r/g,"").split(`
30
+ `);k.length===0&&k.push("");let u=[];for(let x of k)u.push(o.bgGray.white(` ${x||" "} `));return u.join(`
31
+ `)}function lt(){F();let f=()=>o.gray(`${Dt[l%Dt.length]} thinking`);if(!t){console.log(` ${f()}`),r=!0;return}Y(),Q(),console.log(),console.log(` ${f()}`),W({preserveInput:!0}),r=!0,l+=1,c=setInterval(()=>{r&&(bt(f()),l+=1)},120)}function wt(f){F();let k=String(f??"").replace(/\r/g,"").replace(/⎿/g,"");if(!r){M(k);return}Q(),console.log();let u=k.split(`
32
+ `);for(;u.length>0&&u[u.length-1]==="";)u.pop();for(let x of u)console.log(x?` ${x}`:"");console.log(),r=!1}return{enabled:t,mount(){if(!n){if(!t){e.prompt(),n=!0;return}n=!0,W()}},refreshPrompt(f={}){if(t&&n){s&&Q(),W(f);return}e.prompt()},pushSystem(f){M(f)},pushUser(f){M(rt(f))},pushAssistant(f){wt(f)},showAssistantLoading:lt,dismissTransientLoading(){F(),r&&t&&n&&s&&(process.stdout.write("\x1B7"),E(process.stdout,0,-2),U(process.stdout,0),G(process.stdout,0),E(process.stdout,0,-1),U(process.stdout,0),G(process.stdout,0),process.stdout.write("\x1B8")),r=!1},touchInputFrame:st,handleResize:B,showCommandDropdown:N,clearCommandDropdown:Y}}function bo(){console.log(""),console.log(o.cyan(" Available commands:"));for(let e of ae)console.log(o.white(` ${e.cmd.padEnd(10)} `)+o.gray(e.desc));console.log(""),console.log(o.cyan(" Chat options:")),console.log(o.white(" --stream, -s ")+o.gray("Enable typewriter effect (default: instant)")),console.log(""),console.log(o.gray(" To install/uninstall skills, just ask naturally:")),console.log(o.gray(' "connect to Jira" \u2022 "add GitHub" \u2022 "remove Slack"')),console.log("")}var wo=oo;async function cs(e={}){let t=process.cwd();e.verbose&&(process.env.ZIBBY_VERBOSE="true");let n=e.stream||!1;[ft(t,".env.local"),ft(t,".env")].forEach(u=>{yt(u)&&Vn.config({path:u,override:!1})});try{await import("@zibby/skills")}catch{}function r(){let u=Ot();if(!u)return!1;try{let x=JSON.parse(atob(u.split(".")[1]));return x.exp&&x.exp*1e3>Date.now()}catch{return!1}}if(!r()){Te();let u=Xt(),{spawn:x}=await import("child_process"),V=await fetch(`${u}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});V.ok||(console.log(o.red("\n Could not start login. Try `zibby login`.\n")),process.exit(1));let{deviceCode:b,verificationUrl:i,expiresIn:O,interval:tt}=await V.json(),z=process.platform;x(z==="darwin"?"open":z==="win32"?"cmd":"xdg-open",z==="win32"?["/c","start","",i]:[i],{detached:!0,stdio:"ignore"}).unref(),console.log(o.cyan(`
33
+ Opening browser to authorize Zibby CLI...`)),console.log(o.gray(` ${i}
34
+ `));let at=Ge();at.setLabel("waiting for authorization");let dt=(tt||3)*1e3,mt=Math.floor(O/(tt||3)),et=!1;for(let it=0;it<mt;it++){await eo(dt);try{let nt=await fetch(`${u}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:b})});if(nt.status===202)continue;if(!nt.ok)break;let Z=await nt.json();if(Z.status==="authorized"){$e(Z.token),Ae(Z.user),Z.proxyUrl&&Ce(Z.proxyUrl),Z.mem0ProxyUrl&&Le(Z.mem0ProxyUrl),et=!0;break}if(Z.status==="denied")break}catch{break}}at(),et||(console.log(o.red("\n Login failed or timed out. Run `zibby login` to try again.\n")),process.exit(1))}let c=await so(t),l=await ro(t),d=e.agent||"assistant",y=Ot();y&&!process.env.ZIBBY_USER_TOKEN&&(process.env.ZIBBY_USER_TOKEN=y);let L=Ne()||Pe();L&&!process.env.ZIBBY_MEM0_OPENAI_BASE_URL&&(process.env.ZIBBY_MEM0_OPENAI_BASE_URL=L),process.env.AGENT_TYPE=d,process.env.ZIBBY_CHAT_OWNER_PID=String(process.pid);try{let{cleanupStalePidFiles:u}=await Promise.resolve().then(()=>(re(),se));u(t,c)}catch{}let F;try{F=Dn({state:{agentType:d}})}catch(u){console.log(o.red(`
35
+ ${u.message}
36
+ `)),process.exit(1)}let bt=Ie(),ct=Be()?.[0]?.name,N=Ue(t),Q=l.skills||[],W=Fe(t),B=W?[...new Set([...Q,...W])]:[...Q],st={data:null,timestamp:0},M=300*1e3,rt={jira:"jira",github:"github",slack:"slack",sentry:"sentry"};try{let u=Ot();if(u){let x=Xt(),V=await fetch(`${x}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${u}`}});if(V.ok){let b=await V.json();for(let[i,O]of Object.entries(rt)){let tt=b[i]?.connected,z=B.indexOf(O);tt&&z===-1&&Pt(O)?B.push(O):!tt&&z!==-1&&B.splice(z,1)}Tt(t,B)}}}catch{}let lt=B.filter(u=>u!=="skill-installer"&&u!=="core-tools"),wt=lt.length>0?`Skills: ${lt.join(", ")}`:"Skills: (none)";go({userName:bt?.name?.split(" ")[0],cwd:t,projectName:ct,restoredCount:N.length,skillsLine:wt});let f=Ve(t),k=Ke(f);return new Promise(u=>{let x=process.env.ZIBBY_CHAT_TAB_COMPLETION==="1",V={input:process.stdin,output:process.stdout,prompt:o.green(" > "),terminal:!0};x&&(V.completer=m=>{let a=String(m||"");if(!a.startsWith("/"))return[[],a];let w=k.map(P=>P.cmd),$=w.filter(P=>P.startsWith(a));return[$.length>0?$:w,a]});let b=Wn(V),i=yo(b),O=null,tt=!1,z=[],en=0,nn=1200,at=!1,dt=!1,mt=!1,et=!1,it="",nt=0,Z=typeof b._ttyWrite=="function"?b._ttyWrite.bind(b):null;Z&&(b._ttyWrite=(...m)=>{if(!(et||Date.now()<nt))return Z(...m)});function on(){mt||!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004h"),mt=!0)}function ue(){mt&&(!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004l"),mt=!1))}function sn(m){let a="\x1B[200~",w="\x1B[201~";if(!et&&!m.includes(a))return!1;let $=m,P=!1;for(;$.length>0;){if(!et){let C=$.indexOf(a);if(C===-1)break;P=!0,me(),et=!0,it="",$=$.slice(C+a.length);continue}let J=$.indexOf(w);if(J===-1){P=!0,it+=$;break}P=!0,it+=$.slice(0,J);let ot=String(it||"").replace(/\r\n/g,`
28
37
  `).replace(/\r/g,`
29
- `);if(st.length>0){const A=st.split(`
30
- `);for(const K of A)Rt(K)}vt(),rt="",tt=!1,$=$.slice(G+g.length)}return P}function Gt(){if(!at){at=!0;try{Pt(t,E),It(t,L)}catch{}try{Jt()}catch{}try{m.close()}catch{}process.exit(0)}}async function Lt(){if(!at){at=!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 _t=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,et=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~"),G=g.length>=16&&/\s/.test(g)&&!g.startsWith("\x1B");($||P||G)&&(Mt=Date.now()+1200,et=Date.now()+1200,Kt(),Bt())},N={query:"",matches:[],selected:0},H={prefix:"",matches:[],nextIndex:0},_={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(){H.prefix="",H.matches=[],H.nextIndex=0}function vt(){if(_.timer&&(clearTimeout(_.timer),_.timer=null),_.active&&_.lines.length>0){qt+=1;const p=_.lines.length,i=`[Pasted text #${qt} +${p} lines]`,g=_.lines.join(`
34
- `);Nt.push({placeholder:i,text:g});const $=String(_.prefix||"").trimEnd(),P=$?`${$} ${i}`:i;ft(P,{preserveFrame:!0}),mt(m.line)}_.active=!1,_.prefix="",_.lines=[],et=0}function Bt(){_.timer&&clearTimeout(_.timer),_.timer=setTimeout(()=>{vt()},180)}function Kt(){_.active||(_.active=!0,_.prefix=String(Ot||m.line||""),_.lines=[],ft(_.prefix,{preserveFrame:!0}))}function Rt(p){return _.active?(_.lines.push(String(p||"")),ft(_.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||""),G=Number(m.cursor||P.length);if(!ls(P,G)){Zt(),mt(m.line);return}const st=P.slice(1).toLowerCase();if(H.prefix!==st&&(H.prefix=st,H.matches=w.map(K=>K.cmd).filter(K=>K.toLowerCase().startsWith(`/${st}`)),H.nextIndex=0),H.matches.length===0)return;const A=H.nextIndex%H.matches.length;H.nextIndex+=1,ft(H.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,G=N.matches.length;N.selected=(N.selected+P+G)%G;const st=N.matches[N.selected];ft(`/${st}`,{preserveFrame:!0}),n.showCommandDropdown(N.matches,N.selected);return}i?.name!=="tab"&&Zt(),setTimeout(()=>{mt(m.line),_.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",_t):process.stdin.on("data",_t)),m.on("line",async p=>{try{let i=String(p||"");const g=pt;if(pt=!1,!g&&(_.active||tt||Date.now()<Mt||Date.now()<et)){if(_.active&&i.length>0){Rt(i);return}_.active&&(vt(),n.refreshPrompt());return}if(_.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(Q&&A!=="/exit"&&A!=="/quit"){O&&O.abort(),Y.push(A),n.pushSystem(e.gray("Processing your message...")),n.refreshPrompt({preserveInput:!0});return}const K=1e4;if(A.length>K){n.pushSystem(e.red(`\u26A0 Input too long (${A.length} chars). Maximum: ${K} 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 x=$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=x[b]||{};console.log(e.green(` \u2713 ${b}`)+e.gray(S.description?` \u2014 ${S.description}`:""))}const T=Object.keys(x).filter(b=>!L.includes(b));if(T.length>0){console.log(e.cyan(`
36
- Available:`));for(const b of T){const S=x[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(`
38
+ `);if(ot.length>0){let C=ot.split(`
39
+ `);for(let q of C)Gt(q)}Lt(),it="",et=!1,$=$.slice(J+w.length)}return P}function pe(){if(!at){at=!0;try{At(t,N),Tt(t,B)}catch{}try{ue()}catch{}try{b.close()}catch{}process.exit(0)}}async function zt(){if(!at){at=!0,typeof F?.cleanup=="function"&&await F.cleanup().catch(()=>{});try{let{killAllChatOrchestratedRuns:m}=await Promise.resolve().then(()=>(re(),se)),{postCliInterruptedRunIndex:a}=await import("@zibby/core/utils/run-index-post-cli.js");m(t,process.pid,c),a({cwd:t,config:c})}catch{}At(t,N),Tt(t,B),i.pushSystem(o.gray("Session saved. Goodbye!")),ue(),b.close(),process.exit(0)}}if(i.mount(),on(),process.stdout?.isTTY){let m;process.stdout.on("resize",()=>{clearTimeout(m),m=setTimeout(()=>{i.handleResize()},80)})}let Ht=0,Nt=m=>{if(typeof m=="string"?m==="\x1B":m&&typeof m.length=="number"?m.length===1&&m[0]===27:!1){O&&O.abort(),pe();return}let w=typeof m=="string"?m:m&&typeof m.length=="number"?Buffer.from(m).toString("utf8"):"";if(!w)return;if(sn(w)){Ht=Date.now()+1200,nt=Date.now()+1200,Jt();return}let $=(w.includes(`
40
+ `)||w.includes("\r"))&&w!=="\r"&&w!==`
41
+ `&&w!==`\r
42
+ `,P=w.includes("\x1B[200~")||w.includes("\x1B[201~"),J=w.length>=16&&/\s/.test(w)&&!w.startsWith("\x1B");($||P||J)&&(Ht=Date.now()+1200,nt=Date.now()+1200,me(),Jt())},R={query:"",matches:[],selected:0},H={prefix:"",matches:[],nextIndex:0},A={active:!1,prefix:"",lines:[],timer:null},Wt=[],fe=0,Zt="",rn=new Set(ae.map(m=>m.cmd));function gt(m,{preserveFrame:a=!1}={}){let w=String(m||"");b.line=w,b.cursor=w.length,Zt=w,typeof b._refreshLine=="function"?b._refreshLine():b.prompt(),a&&i.touchInputFrame()}function de(){H.prefix="",H.matches=[],H.nextIndex=0}function Lt(){if(A.timer&&(clearTimeout(A.timer),A.timer=null),A.active&&A.lines.length>0){fe+=1;let m=A.lines.length,a=`[Pasted text #${fe} +${m} lines]`,w=A.lines.join(`
43
+ `);Wt.push({placeholder:a,text:w});let $=String(A.prefix||"").trimEnd(),P=$?`${$} ${a}`:a;gt(P,{preserveFrame:!0}),ht(b.line)}A.active=!1,A.prefix="",A.lines=[],nt=0}function Jt(){A.timer&&clearTimeout(A.timer),A.timer=setTimeout(()=>{Lt()},180)}function me(){A.active||(A.active=!0,A.prefix=String(Zt||b.line||""),A.lines=[],gt(A.prefix,{preserveFrame:!0}))}function Gt(m){return A.active?(A.lines.push(String(m||"")),gt(A.prefix,{preserveFrame:!0}),Jt(),!0):!1}function cn(m){let a=String(m||"");for(let w of Wt)a=a.split(w.placeholder).join(w.text);return a}function ht(m){let a=String(m||"");if(!a.startsWith("/")||a.includes(" ")||a.length===0){R.query="",R.matches=[],R.selected=0,i.clearCommandDropdown();return}f=Ve(t),k=Ke(f);let w=a.slice(1).toLowerCase(),$=f.filter(P=>P.toLowerCase().startsWith(w));R.query=w,R.matches=$,R.selected=Math.min(R.selected,Math.max(0,$.length-1)),i.showCommandDropdown($,R.selected)}let Vt=(m,a)=>{if(a?.name==="escape"||a?.sequence==="\x1B"){O&&O.abort(),pe();return}if((a?.name==="return"||a?.name==="enter")&&(dt=!0),(a?.name==="backspace"||a?.name==="delete")&&i.touchInputFrame(),a?.name==="tab"&&!a?.shift){let P=String(b.line||""),J=Number(b.cursor||P.length);if(!mo(P,J)){de(),ht(b.line);return}let ot=P.slice(1).toLowerCase();if(H.prefix!==ot&&(H.prefix=ot,H.matches=k.map(q=>q.cmd).filter(q=>q.toLowerCase().startsWith(`/${ot}`)),H.nextIndex=0),H.matches.length===0)return;let C=H.nextIndex%H.matches.length;H.nextIndex+=1,gt(H.matches[C]),ht(b.line);return}let w=String(b.line||""),$=w.startsWith("/")&&!w.includes(" ")&&R.matches.length>0;if(a?.name==="up"||a?.name==="down"){if(!$){ht(b.line);return}let P=a.name==="up"?-1:1,J=R.matches.length;R.selected=(R.selected+P+J)%J;let ot=R.matches[R.selected];gt(`/${ot}`,{preserveFrame:!0}),i.showCommandDropdown(R.matches,R.selected);return}a?.name!=="tab"&&de(),setTimeout(()=>{ht(b.line),A.active||(Zt=String(b.line||""))},50)};process.stdin?.on&&(Zn(process.stdin,b),process.stdin.on("keypress",Vt)),i.enabled&&process.stdin?.on&&(typeof process.stdin.prependListener=="function"?process.stdin.prependListener("data",Nt):process.stdin.on("data",Nt)),b.on("line",async m=>{try{let a=String(m||""),w=dt;if(dt=!1,!w&&(A.active||et||Date.now()<Ht||Date.now()<nt)){if(A.active&&a.length>0){Gt(a);return}A.active&&(Lt(),i.refreshPrompt());return}if(A.active&&(Lt(),a=String(b.line||a||"")),Gt(a))return;let $=a.trim(),P=R.matches[R.selected];if($.startsWith("/")&&!$.includes(" ")&&R.matches.length>0&&!rn.has($)&&$!==`/${P}`){i.clearCommandDropdown(),i.refreshPrompt(),gt(`/${P}`),ht(`/${P}`);return}i.clearCommandDropdown();let C=String(a||"").replace(/[\u0000-\u001F\u007F-\u009F]/g,"").trim();if(!C){i.enabled&&process.stdout?.isTTY&&(E(process.stdout,0,-1),U(process.stdout,4));return}if(tt&&C!=="/exit"&&C!=="/quit"){O&&O.abort(),z.push(C),i.pushSystem(o.gray("Processing your message...")),i.refreshPrompt({preserveInput:!0});return}let q=1e4;if(C.length>q){i.pushSystem(o.red(`\u26A0 Input too long (${C.length} chars). Maximum: ${q} characters.`)),i.pushSystem(o.gray("Tip: If you need to share logs, use a file instead:")),i.pushSystem(o.gray(" 1. Save to file: pbpaste > debug.log")),i.pushSystem(o.gray(' 2. Ask: "analyze debug.log in current directory"')),i.refreshPrompt();return}if(C==="/exit"||C==="/quit"){zt();return}if(C==="/help"){bo(),i.refreshPrompt();return}if(C==="/skills"){let I=Pt("skill-installer")?.catalog||{},S=B.filter(_=>_!=="skill-installer");console.log(o.cyan(`
44
+ Active skills:`)),S.length===0&&console.log(o.gray(" (none)"));for(let _ of S){let v=I[_]||{};console.log(o.green(` \u2713 ${_}`)+o.gray(v.description?` \u2014 ${v.description}`:""))}let T=Object.keys(I).filter(_=>!B.includes(_));if(T.length>0){console.log(o.cyan(`
45
+ Available:`));for(let _ of T){let v=I[_],h=v.envKeys?.length>0?wo(v.envKeys).ok?o.green(" \u2713 configured"):o.yellow(` \u26A0 needs: ${v.envKeys.join(", ")}`):"";console.log(o.white(` - ${_}`)+o.gray(` \u2014 ${v.description}`)+h)}}console.log(o.gray(`
37
46
  Just ask to install: "connect to Jira", "add GitHub", etc.
38
- `)),n.refreshPrompt();return}if(A.startsWith("/history")){if(E.length===0)console.log(e.gray(`
47
+ `)),i.refreshPrompt();return}if(C.startsWith("/history")){if(N.length===0)console.log(o.gray(`
39
48
  No conversation history.
40
- `));else{const a=A.split(/\s+/).slice(1),x=a.includes("--all"),h=a.indexOf("-n"),T=h>=0&&a[h+1]?parseInt(a[h+1],10):NaN,b=x?E.length:isNaN(T)?10:T,S=E.slice(-b);console.log(e.gray(`
41
- Showing ${S.length} of ${E.length} messages${x?" (all)":""}:
42
- `));for(const f of S){const d=f.role==="human"?e.green(" You"):e.cyan(" Zibby"),j=x||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(`
49
+ `));else{let p=C.split(/\s+/).slice(1),I=p.includes("--all"),S=p.indexOf("-n"),T=S>=0&&p[S+1]?parseInt(p[S+1],10):NaN,_=I?N.length:isNaN(T)?10:T,v=N.slice(-_);console.log(o.gray(`
50
+ Showing ${v.length} of ${N.length} messages${I?" (all)":""}:
51
+ `));for(let h of v){let g=h.role==="human"?o.green(" You"):o.cyan(" Zibby"),j=I||T>10?500:100,D=h.content.length>j?`${h.content.substring(0,j)}...`:h.content;console.log(`${g}: ${o.white(D)}`)}console.log("")}i.refreshPrompt();return}if(C==="/clear"){N.length=0,At(t,N),console.log(o.gray(`
43
52
  History cleared.
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(`
53
+ `)),i.refreshPrompt();return}if(C.startsWith("/memory")){let p=B.includes("chat-memory")?Pt("chat-memory"):null;if(!p?.handleToolCall){console.log(o.yellow(`
45
54
  Chat memory not active. Install with: "add chat memory"
46
- `)),n.refreshPrompt();return}const x=A.split(/\s+/).slice(1),h=x[0]||"brief",T={options:{workspace:t}};try{if(h==="facts"||h==="all"){const b=parseInt(x[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(x[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
- Recent sessions (${S.recentSessions?.length||0}):
54
- `)),!S.recentSessions?.length)console.log(e.gray(` (no sessions saved yet)
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=x.slice(1).join(" ");if(!b)console.log(e.yellow(`
55
+ `)),i.refreshPrompt();return}let I=C.split(/\s+/).slice(1),S=I[0]||"brief",T={options:{workspace:t}};try{if(S==="facts"||S==="all"){let _=parseInt(I[1],10)||30,v=await p.handleToolCall("memory_recall",{limit:_},T),h=JSON.parse(v);if(console.log(o.cyan(`
56
+ Stored memories (${h.total}):
57
+ `)),h.total===0)console.log(o.gray(` (empty \u2014 memories are saved as the agent learns things)
58
+ `));else{for(let g of h.memories){let j=o.yellow(`[${g.category}]`),D=Number(g.relevance)<1?o.gray(` (${(Number(g.relevance)*100).toFixed(0)}%)`):"",kt=g.ticket_key?o.magenta(` ${g.ticket_key}`):"",_t=g.source?o.gray(` via ${g.source}`):"";console.log(` ${j}${kt} ${o.white(g.content)}${D}${_t}`)}console.log("")}}else if(S==="tasks"){let _=parseInt(I[1],10)||20,v=await p.handleToolCall("task_history",{limit:_},T),h=JSON.parse(v);if(console.log(o.cyan(`
59
+ Task history (${h.total}):
60
+ `)),h.total===0)console.log(o.gray(` (no tasks logged yet)
61
+ `));else{for(let g of h.tasks){let j=g.status==="passed"?o.green("\u2713"):g.status==="failed"?o.red("\u2717"):o.yellow("\u25CB"),D=g.ticket_key?o.magenta(` ${g.ticket_key}`):"",kt=o.gray(`[${g.type}]`),_t=g.result_summary?o.gray(` \u2014 ${g.result_summary.slice(0,80)}`):"";console.log(` ${j} ${kt}${D} ${o.white(g.title)}${_t}`)}console.log("")}}else if(S==="sessions"){let _=await p.handleToolCall("memory_brief",{},T),v=JSON.parse(_);if(console.log(o.cyan(`
62
+ Recent sessions (${v.recentSessions?.length||0}):
63
+ `)),!v.recentSessions?.length)console.log(o.gray(` (no sessions saved yet)
64
+ `));else{for(let h of v.recentSessions){let g=h.tickets?o.magenta(` [${h.tickets}]`):"",j=h.tasks_run>0?o.gray(` \u2014 ${h.tasks_run} tasks (${h.tasks_passed} passed, ${h.tasks_failed} failed)`):"",D=h.created_at?o.gray(` ${h.created_at.split("T")[0]}`):"";if(console.log(` ${o.white(h.summary)}${g}${j}${D}`),h.key_facts)for(let kt of h.key_facts.split(";").map(_t=>_t.trim()).filter(Boolean))console.log(o.gray(` \u2192 ${kt}`))}console.log("")}}else if(S==="search"){let _=I.slice(1).join(" ");if(!_)console.log(o.yellow(`
56
65
  Usage: /memory search <keyword>
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(`
66
+ `));else{let v=await p.handleToolCall("memory_recall",{query:_,limit:20},T),h=JSON.parse(v);console.log(o.cyan(`
67
+ Search "${_}" \u2014 ${h.total} results:
68
+ `));for(let g of h.memories){let j=o.yellow(`[${g.category}]`),D=g.ticket_key?o.magenta(` ${g.ticket_key}`):"";console.log(` ${j}${D} ${o.white(g.content)}`)}h.total===0&&console.log(o.gray(" (no matches)")),console.log("")}}else{let _=await p.handleToolCall("memory_brief",{},T),v=JSON.parse(_),h=v.topMemories?.length||0,g=v.recentSessions?.length||0,j=(v.taskStats||[]).map(D=>`${D.type}:${D.status}=${D.cnt}`).join(", ");console.log(o.cyan(`
60
69
  Memory overview:
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
- 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
- Memory error: ${b.message}
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>K){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: ${K} chars.`)),n.refreshPrompt();return}Q=!0;let V=v.systemPrompt||"You are Zibby, a helpful AI assistant.";const Xt=is(v,o);Xt&&(V+=`
70
+ `)),console.log(o.white(` Facts stored: ${h>0?o.cyan(h):o.gray("0")}`)),console.log(o.white(` Sessions saved: ${g>0?o.cyan(g):o.gray("0")}`)),j&&console.log(o.white(` Task history: ${o.gray(j)}`)),console.log(o.gray(`
71
+ Subcommands:`)),console.log(o.gray(" /memory facts [n] \u2014 List all stored memories")),console.log(o.gray(" /memory tasks [n] \u2014 List task history")),console.log(o.gray(" /memory sessions \u2014 List session summaries")),console.log(o.gray(" /memory search <keyword> \u2014 Search memories")),console.log("")}}catch(_){console.log(o.red(`
72
+ Memory error: ${_.message}
73
+ `))}i.refreshPrompt();return}i.enabled&&process.stdout?.isTTY&&(E(process.stdout,0,-1),U(process.stdout,0)),i.pushUser(C),i.refreshPrompt(),i.showAssistantLoading();let ge=cn(C),Bt=io(t,ge);if(Wt.length=0,!String(Bt||"").trim()){i.dismissTransientLoading(),i.refreshPrompt();return}if(Bt.length>q){i.pushAssistant(o.red(`Input too long after command expansion (${Bt.length} chars).`)),i.pushSystem(o.gray(`Try shortening the command template or user text. Limit: ${q} chars.`)),i.refreshPrompt();return}tt=!0;let K=l.systemPrompt||"You are Zibby, a helpful AI assistant.",he=uo(l,e);he&&(K+=`
65
74
 
66
- ${Xt}`);const Qt=ze({activeSkills:L,chatConfig:v,options:o});Qt&&(V+=`
75
+ ${he}`);let ye=De({activeSkills:B,chatConfig:l,options:e});ye&&(K+=`
67
76
 
68
- ${Qt}`);const te=rs(L);if(te&&(V+=`
77
+ ${ye}`);let be=ao(B);if(be&&(K+=`
69
78
 
70
- ${te}`),V+=`
79
+ ${be}`),K+=`
71
80
 
72
- Use provided tools when external data/actions are required. Do not claim actions without tool calls. Before using a skill's tools for the first time in a conversation, call get_skill_context(skillId) to load its full guidance.`,L.includes("chat-memory")&&(V+=`
81
+ Use provided tools when external data/actions are required. Do not claim actions without tool calls. Before using a skill's tools for the first time in a conversation, call get_skill_context(skillId) to load its full guidance.`,B.includes("chat-memory")&&(K+=`
73
82
 
74
83
  ### Memory Tool Usage (chat-memory)
75
84
  - At conversation start: call memory_brief to load recent context.
76
85
  - Before answering memory-dependent questions: call memory_recall with focused query terms.
77
86
  - When learning durable user/project facts or decisions: call memory_store.
78
87
  - Avoid storing transient chatter, filler text, or duplicate facts.
79
- - Prefer updating strong existing facts over creating near-duplicates when possible.`),L.includes("workflow-builder")&&(V+=`
88
+ - Prefer updating strong existing facts over creating near-duplicates when possible.`),B.includes("workflow-builder")&&(K+=`
80
89
 
81
90
  ### Workflow Builder (workflow-builder)
82
91
  - When users want to create, build, or scaffold an AI workflow, use the workflow-builder tools.
@@ -84,8 +93,8 @@ Use provided tools when external data/actions are required. Do not claim actions
84
93
  - Conversation flow: ask about purpose \u2192 input data \u2192 processing steps \u2192 output format \u2192 conditional logic.
85
94
  - Then call design_workflow to create a spec, review with user, then build_workflow to generate code.
86
95
  - 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 x=Date.now();let h;ot.data&&x-ot.timestamp<F?(h=ot.data,process.env.ZIBBY_VERBOSE==="true"&&n.pushSystem(e.gray("Using cached memory context"))):(h=await a.buildPromptContext({options:{workspace:t}},{}),ot={data:h,timestamp:x},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&&(V+=`
96
+ - Use list_workflows to show existing workflows, add_node to extend them, deploy_workflow to ship.`),B.includes("chat-memory"))try{let p=Pt("chat-memory");if(typeof p?.buildPromptContext=="function"){let I=Date.now(),S;st.data&&I-st.timestamp<M?(S=st.data,process.env.ZIBBY_VERBOSE==="true"&&i.pushSystem(o.gray("Using cached memory context"))):(S=await p.buildPromptContext({options:{workspace:t}},{}),st={data:S,timestamp:I},process.env.ZIBBY_VERBOSE==="true"&&i.pushSystem(o.gray("Refreshed memory context cache")));let T=String(S?.backend||"dolt");process.env.ZIBBY_VERBOSE==="true"&&(i.pushSystem(o.gray(`memory backend: ${T}`)),i.pushSystem(o.gray(`memory retrieval output: ${Yt(JSON.stringify(S?.debugPreview||{}),1400)}`)),S?.error&&i.pushSystem(o.yellow(`memory backend warning: ${S.error}`))),S?.promptContext&&(K+=`
88
97
 
89
- ${h.promptContext}`)}}catch(a){process.env.ZIBBY_VERBOSE==="true"&&n.pushSystem(e.yellow(`memory backend warning: ${String(a?.message||a)}`))}V=xt(V,ce);const Se=os(E),Ft=ns([{role:"system",content:V},...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 lt=!0;const Ct=[];let se="",bt="";const hs=50,ys=500,ws=3,bs=60,Ss=500,ks=15,$s=25,xs=4,_s=new Set([".","!","?",",",";",":"]),$e=a=>{lt&&(wt(),lt=!1),bt+=a},xe=(a,x)=>{if(!a){lt&&wt.setLabel("thinking...");return}Ct.push(a);const h=70;let T=a;if(x&&typeof x=="object"){const S=Object.values(x).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}),lt&&n.showAssistantLoading()),lt&&wt.setLabel(T)},jt=new AbortController;O=jt;try{const a=await _e("",{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:xe,signal:jt.signal});lt&&wt();const x=typeof a=="string"?a:a?.structured?JSON.stringify(a.structured,null,2):a?.raw||String(a),h=bt&&bt.trim().length>0?bt.trim():x.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(lt&&wt(),n.dismissTransientLoading(),jt.signal.aborted){Y.length===0&&n.pushAssistant(e.gray("[cancelled]"));let x="";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&&(x=`
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+x}):E.push({role:"ai",content:`[interrupted \u2014 new message]${x}`})}else{const x=String(a?.message||a||"Unknown error");/413|payload too large|request payload too large/i.test(x)?(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: ${x}`)),E.push({role:"ai",content:`[Error: ${a.message}]`})}}finally{O=null,Q=!1}if(n.refreshPrompt(),Y.length>0){const a=Y.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",_t),process.stdin.off("keypress",Ut)):process.stdin?.removeListener&&(process.stdin.removeListener("data",_t),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};
98
+ ${S.promptContext}`)}}catch(p){process.env.ZIBBY_VERBOSE==="true"&&i.pushSystem(o.yellow(`memory backend warning: ${String(p?.message||p)}`))}K=Ct(K,tn);let an=co(N),qt=lo([{role:"system",content:K},...an,{role:"user",content:Bt}]),we=le(qt),un=Buffer.byteLength(JSON.stringify(qt),"utf8");process.env.ZIBBY_VERBOSE==="true"&&i.pushSystem(o.gray(`payload estimate: ${we} chars, ${un} bytes (~${Math.round(we/4)} tokens)`)),N.push({role:"human",content:ge});let St=i.enabled?(()=>{let p=()=>{};return p.setLabel=()=>{},p})():Ge(),ut=!0,Et=[],Se="",xt="",xo=50,ko=500,_o=3,vo=60,$o=500,Io=15,Ao=25,To=4,Po=new Set([".","!","?",",",";",":"]),pn=p=>{ut&&(St(),ut=!1),xt+=p},fn=(p,I)=>{if(!p){ut&&St.setLabel("thinking...");return}Et.push(p);let S=70,T=p;if(I&&typeof I=="object"){let v=Object.values(I).map(g=>typeof g=="string"?g:JSON.stringify(g)).join(", "),h=`${p}(${v})`;h.length<=S?T=h:T=`${p}(${v.slice(0,S-p.length-4)}...)`}T!==Se&&(Se=T,i.pushSystem(o.gray(`\u23BF ${T}`)),i.refreshPrompt({preserveInput:!0}),ut&&i.showAssistantLoading()),ut&&St.setLabel(T)},Kt=new AbortController;O=Kt;try{let p=await jn("",{state:{agentType:d,config:c,cwd:t,workspace:t}},{model:c?.agent?.assistant?.model||l.model||"auto",workspace:t,skills:B,activeSkills:B,config:c,timeout:l.timeout||3e5,messages:qt,skipPromptFragments:!0,stream:!0,onToken:pn,onToolCall:fn,signal:Kt.signal});ut&&St();let I=typeof p=="string"?p:p?.structured?JSON.stringify(p.structured,null,2):p?.raw||String(p),S=xt&&xt.trim().length>0?xt.trim():I.trim(),T=po(S,Et)?S:fo(S);i.pushAssistant(T);let _=Et.length>0?`[tools used: ${Et.join(", ")}]
99
+ ${S}`:S;N.push({role:"ai",content:_}),At(t,N),Tt(t,B)}catch(p){if(ut&&St(),i.dismissTransientLoading(),Kt.signal.aborted){z.length===0&&i.pushAssistant(o.gray("[cancelled]"));let I="";try{let{testRunnerSkill:T}=await import("../../skills/index.js"),_=await T.handleToolCall("run_status",{runId:"all"},{options:{workspace:t}}),v=JSON.parse(_);v.runs?.length>0&&(I=`
100
+ [Active test runs: ${v.runs.map(g=>`${g.runId}: ${g.ticketKey||g.spec} (${g.status})`).join(", ")}. Use run_status("all") to check progress.]`)}catch{}let S=xt.trim();S?N.push({role:"ai",content:S+I}):N.push({role:"ai",content:`[interrupted \u2014 new message]${I}`})}else{let I=String(p?.message||p||"Unknown error");/413|payload too large|request payload too large/i.test(I)?(i.pushAssistant(o.yellow("Request became too large for the proxy (413).")),i.pushSystem(o.gray("Try: /clear, then retry your command; or shorten command/context."))):i.pushAssistant(o.red(`Error: ${I}`)),N.push({role:"ai",content:`[Error: ${p.message}]`})}}finally{O=null,tt=!1}if(i.refreshPrompt(),z.length>0){let p=z.shift();dt=!0,setImmediate(()=>b.emit("line",p))}}catch(a){i.pushSystem(o.red(`Input handling error: ${a?.message||String(a)}`)),i.refreshPrompt()}}),b.on("SIGINT",()=>{if(O){O.abort();return}zt()}),b.on("close",zt);let ln=()=>{process.stdin?.off?(process.stdin.off("data",Nt),process.stdin.off("keypress",Vt)):process.stdin?.removeListener&&(process.stdin.removeListener("data",Nt),process.stdin.removeListener("keypress",Vt))};b.on("close",ln)})}export{is as _buildPrompt,oo as _checkEnvKeys,no as _formatHistory,rs as _inferAgentType,cs as chatCommand};
@@ -1,12 +1,12 @@
1
1
  import{patchCursorAgentForCI as i,checkCursorAgentPatched as p,getApprovalKeys as g,saveApprovalKeys as y}from"@zibby/core";import{resolve as c}from"path";import e from"chalk";import n from"ora";async function v(r){console.log(e.bold.cyan(`
2
2
  \u{1F527} Setting up CI/CD for Cursor Agent
3
- `)),console.log(e.gray("\u2501".repeat(50)));const t=p();if(t.installed||(console.log(e.red(`
3
+ `)),console.log(e.gray("\u2501".repeat(50)));let t=p();if(t.installed||(console.log(e.red(`
4
4
  \u274C cursor-agent is not installed!
5
5
  `)),console.log(e.white("To install:")),console.log(e.gray(` curl https://cursor.com/install -fsS | bash
6
6
  `)),process.exit(1)),t.patched)console.log(e.green(`\u2705 cursor-agent is already patched for CI/CD
7
- `));else{const s=n("Patching cursor-agent...").start();try{await i(),s.succeed("cursor-agent patched successfully")}catch(o){s.fail("Failed to patch cursor-agent"),console.log(e.red(`
7
+ `));else{let s=n("Patching cursor-agent...").start();try{await i(),s.succeed("cursor-agent patched successfully")}catch(o){s.fail("Failed to patch cursor-agent"),console.log(e.red(`
8
8
  \u274C Error: ${o.message}
9
- `)),process.exit(1)}}if(r.getKeys){const s=n("Getting approval keys...").start();try{const o=await g(c(process.cwd()));s.succeed("Approval keys retrieved"),console.log(e.cyan(`
9
+ `)),process.exit(1)}}if(r.getKeys){let s=n("Getting approval keys...").start();try{let o=await g(c(process.cwd()));s.succeed("Approval keys retrieved"),console.log(e.cyan(`
10
10
  \u{1F4CB} Approval Keys:
11
11
  `)),Object.entries(o.keys).forEach(([a,l])=>{console.log(e.white(` ${a}: ${e.gray(l)}`))}),r.save?y(c(process.cwd()),o.keys):(console.log(e.gray(`
12
12
  To save these keys, run:`)),console.log(e.white(` zibby ci-setup --get-keys --save