@zibby/cli 0.1.57 → 0.1.59
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/auth/cli-login.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import e from"chalk";import y from"ora";import{spawn as U}from"child_process";import{getApiUrl as p}from"../config/environments.js";import{saveSessionToken as $,saveUserInfo as x,saveProxyUrl as P,saveMem0ProxyUrl as C,getSessionToken as
|
|
1
|
+
import e from"chalk";import y from"ora";import{spawn as U}from"child_process";import{getApiUrl as p}from"../config/environments.js";import{saveSessionToken as $,saveUserInfo as x,saveProxyUrl as P,saveMem0ProxyUrl as C,getSessionToken as S,getUserInfo as A,clearSession as T,saveProjects as z}from"../config/config.js";import{clearActiveSkills as L}from"../commands/chat-session-store.js";function N(n){const o=process.platform;try{let t,r;return o==="darwin"?(t="open",r=[n]):o==="win32"?(t="cmd",r=["/c","start","",n]):(t="xdg-open",r=[n]),U(t,r,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function h(){const n=S(),o=A();return n&&o?{loggedIn:!0,user:o,token:n}:{loggedIn:!1}}async function G(){try{console.log(e.cyan(`
|
|
2
2
|
\u{1F510} Initiating login...
|
|
3
3
|
`));const n=h();if(n.loggedIn){console.log(e.green("\u2705 Already logged in!")),console.log(e.gray(`User: ${n.user.email}`)),console.log(e.gray(`Name: ${n.user.name}
|
|
4
4
|
`));const{createInterface:o}=await import("readline"),t=o({input:process.stdin,output:process.stdout});return new Promise((r,c)=>{const s=()=>{t.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},i=()=>{console.log(e.yellow(`
|
|
5
5
|
|
|
6
6
|
\u26A0\uFE0F Login cancelled
|
|
7
7
|
`)),s(),process.exit(0)};process.on("SIGINT",i),t.question(e.yellow("Continue with this session? (Y/n): "),async a=>{process.removeListener("SIGINT",i),s();try{if(a.toLowerCase()==="n"||a.toLowerCase()==="no"){console.log(e.gray(`Starting new login...
|
|
8
|
-
`));const d=await
|
|
9
|
-
`)),r({success:!0,...n})}catch(d){c(d)}})})}return await
|
|
10
|
-
\u274C Login failed:`,n.message)),{success:!1,error:n.message}}}async function
|
|
8
|
+
`));const d=await v();r(d)}else console.log(e.green(`Using existing session.
|
|
9
|
+
`)),r({success:!0,...n})}catch(d){c(d)}})})}return await v()}catch(n){return console.error(e.red(`
|
|
10
|
+
\u274C Login failed:`,n.message)),{success:!1,error:n.message}}}async function E(n){const o=p();try{const t=await fetch(`${o}/projects`,{headers:{Authorization:`Bearer ${n}`}});if(t.ok){const c=((await t.json()).projects||[]).map(s=>({name:s.name,projectId:s.projectId,apiToken:s.apiToken}));return z(c),c}}catch(t){console.log(e.gray(`\u26A0\uFE0F Could not fetch projects: ${t.message}`))}return[]}async function v(){const n=p(),o=y("Requesting login code...").start(),t=await fetch(`${n}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){o.fail("Failed to request login code");const u=await t.json();throw new Error(u.error||"Failed to initiate login")}const{deviceCode:r,userCode:c,verificationUrl:s,expiresIn:i,interval:a}=await t.json();o.succeed("Login code generated"),console.log(""),console.log(e.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")),console.log(e.cyan("\u2551")+e.white.bold(" Complete login in your browser ")+e.cyan("\u2551")),console.log(e.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")),console.log(""),console.log(e.white("Opening browser to login page...")),console.log(e.gray(`Code expires in ${Math.floor(i/60)} minutes`)),console.log(""),await N(s)||(console.log(e.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(e.white("Please open this URL manually: ")+e.blue(s)),console.log(""));const g=y("Waiting for authorization...").start(),I=(a||3)*1e3,b=Math.floor(i/(a||3));let w=0,m=!1;const k=()=>{m=!0,g.stop(),console.log(e.yellow(`
|
|
11
11
|
|
|
12
12
|
\u26A0\uFE0F Login cancelled
|
|
13
|
-
`)),process.exit(0)};process.on("SIGINT",k);try{for(;w<b&&!m;){await
|
|
14
|
-
`)),{success:!0,loggedIn:!0,user:l.user,token:l.token}}if(l.status==="denied")throw g.fail("Authorization denied"),new Error("User denied authorization")}throw g.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",k)}}function
|
|
13
|
+
`)),process.exit(0)};process.on("SIGINT",k);try{for(;w<b&&!m;){await B(I),w++;const u=await fetch(`${n}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:r})});if(u.status===202)continue;if(!u.ok){g.fail("Authorization failed");const f=await u.json();throw new Error(f.error||"Authorization failed")}const l=await u.json();if(l.status==="authorized"){g.succeed(e.white("Authorization successful!")),$(l.token),x(l.user),l.proxyUrl&&P(l.proxyUrl),l.mem0ProxyUrl&&C(l.mem0ProxyUrl),console.log(""),console.log(e.gray(`User: ${l.user.email}`));const f=y("Fetching projects...").start(),j=await E(l.token);return f.succeed(`Fetched ${j.length} project${j.length!==1?"s":""}`),console.log(e.gray(`Session saved to: ~/.zibby/config.json
|
|
14
|
+
`)),{success:!0,loggedIn:!0,user:l.user,token:l.token}}if(l.status==="denied")throw g.fail("Authorization denied"),new Error("User denied authorization")}throw g.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",k)}}function J(){if(!h().loggedIn){console.log(e.yellow(`
|
|
15
15
|
\u26A0\uFE0F Not logged in.
|
|
16
|
-
`));return}
|
|
17
|
-
`))}async function
|
|
18
|
-
`));return}if(console.log(e.green("\u2705 Authenticated")),console.log(""),console.log(e.bold.white("User Details:")),o.user?(console.log(e.gray(` Email: ${o.user.email}`)),o.user.userId&&console.log(e.gray(` User ID: ${o.user.userId}`)),o.user.name&&console.log(e.gray(` Name: ${o.user.name}`))):t&&console.log(e.gray(" (User details not available with PAT token)")),console.log(""),console.log(e.bold.white("Token Source:")),t?(console.log(e.gray(" Type: Personal Access Token (PAT)")),console.log(e.gray(" Location: ZIBBY_USER_TOKEN environment variable")),console.log(e.gray(` Preview: ${t.substring(0,8)}\u2022\u2022\u2022\u2022`))):(console.log(e.gray(" Type: Session Token (JWT)")),console.log(e.gray(" Location: ~/.zibby/config.json")),o.token&&console.log(e.gray(` Preview: ${o.token.substring(0,8)}\u2022\u2022\u2022\u2022`))),console.log(""),c)try{const s=(await import("ora")).default,i=s("Verifying authentication...").start(),a=await fetch(`${r}/projects`,{headers:{Authorization:`Bearer ${c}`}});if(a.ok){const g=((await a.json()).projects||[]).length;i.succeed(e.white("Token verified")),console.log(e.gray(` Projects: ${g} accessible`))}else i.fail(e.white("Token verification failed")),console.log(e.yellow(` Status: Invalid or expired (HTTP ${a.status})`))}catch(s){console.log(e.yellow(` Status: Could not verify (${s.message})`))}console.log(""),console.log(e.gray("\u{1F4A1} Run 'zibby list' to see your projects")),console.log("")}async function
|
|
16
|
+
`));return}T(),L(),console.log(e.green("\u2714")+e.white(" Logged out successfully!")),console.log(e.gray(`Session cleared from ~/.zibby/config.json
|
|
17
|
+
`))}async function M(n={}){const o=h(),t=process.env.ZIBBY_USER_TOKEN,r=p(),c=t||o.token;if(n.json){const s={authenticated:!!(o.loggedIn||t),user:o.user||null,tokenSource:t?"environment":o.token?"session":null,tokenType:t?"PAT":o.token?"JWT":null,apiUrl:r,configPath:o.loggedIn?"~/.zibby/config.json":null};if(c)try{const i=await fetch(`${r}/projects`,{headers:{Authorization:`Bearer ${c}`}});if(s.tokenValid=i.ok,i.ok){const a=await i.json();s.projectCount=(a.projects||[]).length}}catch(i){s.tokenValid=!1,s.error=i.message}else s.tokenValid=!1;console.log(JSON.stringify(s,null,2));return}if(console.log(""),!o.loggedIn&&!t){console.log(e.yellow("\u26A0\uFE0F Not authenticated")),console.log(""),console.log(e.white("To authenticate:")),console.log(e.gray(" Local: zibby login")),console.log(e.gray(` CI/CD: Set ZIBBY_USER_TOKEN env variable
|
|
18
|
+
`));return}if(console.log(e.green("\u2705 Authenticated")),console.log(""),console.log(e.bold.white("User Details:")),o.user?(console.log(e.gray(` Email: ${o.user.email}`)),o.user.userId&&console.log(e.gray(` User ID: ${o.user.userId}`)),o.user.name&&console.log(e.gray(` Name: ${o.user.name}`))):t&&console.log(e.gray(" (User details not available with PAT token)")),console.log(""),console.log(e.bold.white("Token Source:")),t?(console.log(e.gray(" Type: Personal Access Token (PAT)")),console.log(e.gray(" Location: ZIBBY_USER_TOKEN environment variable")),console.log(e.gray(` Preview: ${t.substring(0,8)}\u2022\u2022\u2022\u2022`))):(console.log(e.gray(" Type: Session Token (JWT)")),console.log(e.gray(" Location: ~/.zibby/config.json")),o.token&&console.log(e.gray(` Preview: ${o.token.substring(0,8)}\u2022\u2022\u2022\u2022`))),console.log(""),c)try{const s=(await import("ora")).default,i=s("Verifying authentication...").start(),a=await fetch(`${r}/projects`,{headers:{Authorization:`Bearer ${c}`}});if(a.ok){const g=((await a.json()).projects||[]).length;i.succeed(e.white("Token verified")),console.log(e.gray(` Projects: ${g} accessible`))}else i.fail(e.white("Token verification failed")),console.log(e.yellow(` Status: Invalid or expired (HTTP ${a.status})`))}catch(s){console.log(e.yellow(` Status: Could not verify (${s.message})`))}console.log(""),console.log(e.gray("\u{1F4A1} Run 'zibby list' to see your projects")),console.log("")}async function V(){const n=S();if(!n)return{valid:!1};const o=p();try{return(await fetch(`${o}/projects`,{headers:{Authorization:`Bearer ${n}`}})).ok?{valid:!0}:(T(),{valid:!1})}catch{return{valid:!1}}}function B(n){return new Promise(o=>setTimeout(o,n))}export{h as checkExistingSession,G as loginCli,J as logoutCli,M as showLoginStatus,V as validateSession};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as o,mkdirSync as a,readFileSync as
|
|
1
|
+
import{existsSync as o,mkdirSync as a,readFileSync as c,writeFileSync as u,unlinkSync as l}from"fs";import{resolve as s}from"path";import{homedir as y}from"os";const p=30;function e(r){const t=s(r,".zibby","output");return o(t)||a(t,{recursive:!0}),t}function v(r){const t=s(r,".zibby","output","chat-history.json");if(!o(t))return[];try{const i=JSON.parse(c(t,"utf-8"));return Array.isArray(i)?i:[]}catch{return[]}}function b(r,t){const i=e(r),n=s(i,"chat-history.json");try{u(n,JSON.stringify((t||[]).slice(-p*2),null,2),"utf-8")}catch{}}function d(r){const t=s(r,".zibby","output","active-skills.json");if(!o(t))return null;try{const i=JSON.parse(c(t,"utf-8"));return Array.isArray(i)?i:null}catch{return null}}function k(r,t){const i=e(r),n=s(i,"active-skills.json");try{u(n,JSON.stringify(Array.isArray(t)?t:[]),"utf-8")}catch{}}function A(){const r=[s(process.cwd(),".zibby","output","active-skills.json"),s(y(),".zibby","output","active-skills.json")];for(const t of r)try{o(t)&&l(t)}catch{}}export{A as clearActiveSkills,d as loadActiveSkills,v as loadChatHistory,k as saveActiveSkills,b as saveChatHistory};
|
package/dist/commands/chat.js
CHANGED
|
@@ -1,58 +1,58 @@
|
|
|
1
|
-
import{invokeAgent as
|
|
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
2
|
`)}function Fs(o,t,s){let r=o;return t.length>0&&(r+=`
|
|
3
3
|
|
|
4
4
|
${Xe(t)}`),r+=`
|
|
5
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=
|
|
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&>(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}
|
|
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
|
|
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))}
|
|
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:
|
|
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)
|
|
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
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 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],
|
|
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),
|
|
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
17
|
`),o.prompt(),process.stdout.write(`
|
|
18
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),
|
|
20
|
-
`);for(;w.length>0&&w[w.length-1]==="";)w.pop();for(const c of w)console.log(c?` ${c}`:"");l=!1}function
|
|
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
21
|
`);w.length===0&&w.push("");const c=[];for(const y of w)c.push(e.bgGray.white(` ${y||" "} `));return c.join(`
|
|
22
|
-
`)}function
|
|
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,
|
|
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
24
|
Opening browser to authorize Zibby CLI...`)),console.log(e.gray(` ${n}
|
|
25
|
-
`));const
|
|
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
26
|
${c.message}
|
|
27
|
-
`)),process.exit(1)}const ht=Ne(),
|
|
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,`
|
|
28
28
|
`).replace(/\r/g,`
|
|
29
|
-
`);if(
|
|
30
|
-
`);for(const
|
|
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
31
|
`)||g.includes("\r"))&&g!=="\r"&&g!==`
|
|
32
32
|
`&&g!==`\r
|
|
33
|
-
`,P=g.includes("\x1B[200~")||g.includes("\x1B[201~"),
|
|
34
|
-
`);Nt.push({placeholder:i,text:g});const $=String(
|
|
35
|
-
Active skills:`)),h.length===0&&console.log(e.gray(" (none)"));for(const b of h){const S=
|
|
36
|
-
Available:`));for(const b of T){const S=
|
|
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(`
|
|
37
37
|
Just ask to install: "connect to Jira", "add GitHub", etc.
|
|
38
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),
|
|
41
|
-
Showing ${S.length} of ${E.length} messages${
|
|
42
|
-
`));for(const f of S){const d=f.role==="human"?e.green(" You"):e.cyan(" Zibby"),j=
|
|
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(`
|
|
43
43
|
History cleared.
|
|
44
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
|
-
`)),n.refreshPrompt();return}const
|
|
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
47
|
Stored memories (${f.total}):
|
|
48
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(
|
|
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
50
|
Task history (${f.total}):
|
|
51
51
|
`)),f.total===0)console.log(e.gray(` (no tasks logged yet)
|
|
52
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 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=
|
|
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(`
|
|
56
56
|
Usage: /memory search <keyword>
|
|
57
57
|
`));else{const S=await a.handleToolCall("memory_recall",{query:b,limit:20},T),f=JSON.parse(S);console.log(e.cyan(`
|
|
58
58
|
Search "${b}" \u2014 ${f.total} results:
|
|
@@ -61,22 +61,22 @@ ${c}
|
|
|
61
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
|
-
`))}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>
|
|
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+=`
|
|
65
65
|
|
|
66
|
-
${Xt}`);const Qt=ze({activeSkills:L,chatConfig:v,options:o});Qt&&(
|
|
66
|
+
${Xt}`);const Qt=ze({activeSkills:L,chatConfig:v,options:o});Qt&&(V+=`
|
|
67
67
|
|
|
68
|
-
${Qt}`);const te=rs(L);if(te&&(
|
|
68
|
+
${Qt}`);const te=rs(L);if(te&&(V+=`
|
|
69
69
|
|
|
70
|
-
${te}`),
|
|
70
|
+
${te}`),V+=`
|
|
71
71
|
|
|
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")&&(
|
|
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+=`
|
|
73
73
|
|
|
74
74
|
### Memory Tool Usage (chat-memory)
|
|
75
75
|
- At conversation start: call memory_brief to load recent context.
|
|
76
76
|
- Before answering memory-dependent questions: call memory_recall with focused query terms.
|
|
77
77
|
- When learning durable user/project facts or decisions: call memory_store.
|
|
78
78
|
- 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")&&(
|
|
79
|
+
- Prefer updating strong existing facts over creating near-duplicates when possible.`),L.includes("workflow-builder")&&(V+=`
|
|
80
80
|
|
|
81
81
|
### Workflow Builder (workflow-builder)
|
|
82
82
|
- When users want to create, build, or scaffold an AI workflow, use the workflow-builder tools.
|
|
@@ -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
|
|
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+=`
|
|
88
88
|
|
|
89
|
-
${h.promptContext}`)}}catch(a){process.env.ZIBBY_VERBOSE==="true"&&n.pushSystem(e.yellow(`memory backend warning: ${String(a?.message||a)}`))}
|
|
90
|
-
${h}`:h;E.push({role:"ai",content:b}),Pt(t,E),It(t,L)}catch(a){if(
|
|
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+
|
|
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};
|
package/dist/package.json
CHANGED