@zibby/cli 0.1.50 → 0.1.52
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/commands/chat.js +16 -14
- package/dist/commands/init.js +13 -13
- package/dist/package.json +1 -1
- package/dist/utils/agent-credentials.js +3 -2
- package/package.json +1 -1
package/dist/commands/chat.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{invokeAgent as xe,getAgentStrategy as ve,getSkill as $t}from"@zibby/core";import{existsSync as gt,readFileSync as oe,readdirSync as Te}from"fs";import{resolve as
|
|
1
|
+
import{invokeAgent as xe,getAgentStrategy as ve,getSkill as $t}from"@zibby/core";import{existsSync as gt,readFileSync as oe,readdirSync as Te}from"fs";import{resolve as lt,join as Dt,dirname as Ce,basename as Ie}from"path";import{createInterface as Pe,moveCursor as M,cursorTo as B,clearLine as G,emitKeypressEvents as Ae}from"readline";import{fileURLToPath as Ee}from"url";import{homedir as Le}from"os";import e from"chalk";import{highlight as ne}from"cli-highlight";import Me from"dotenv";import{getSessionToken as Wt,getUserInfo as Ne,getProjects as Oe,saveSessionToken as Be,saveUserInfo as Re,clearSession as Ue,saveProxyUrl as Fe,getProxyUrl as je,getMem0ProxyUrl as De,saveMem0ProxyUrl as We}from"../config/config.js";import{getApiUrl as re}from"../config/environments.js";import{loadActiveSkills as Ye,loadChatHistory as He,saveActiveSkills as It,saveChatHistory as Pt}from"./chat-session-store.js";import{buildReliabilityInstruction as ze}from"./agent-reliability.js";const Je=Ee(import.meta.url),Ge=Ce(Je),Ze=JSON.parse(oe(Dt(Ge,"../../package.json"),"utf-8")),ie=30,qe=54,Ke=18e3,ce=12e3,ae=42e3;function Ve(n){return new Promise(t=>setTimeout(t,n))}const At=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Yt=[{cmd:"/help",desc:"Show this help"},{cmd:"/skills",desc:"List active & available skills"},{cmd:"/history",desc:"Show conversation history (--all or -n 50)"},{cmd:"/clear",desc:"Clear conversation history"},{cmd:"/memory",desc:"View stored memories, tasks, sessions"},{cmd:"/exit",desc:"Exit the chat"},{cmd:"/quit",desc:"Exit the chat"}];function le(){let n=0,t="thinking...";const s=setInterval(()=>{const h=e.cyan(At[n%At.length]),k=n%3,v=k===0?e.white(".")+e.gray(".")+e.dim("."):k===1?e.dim(".")+e.white(".")+e.gray("."):e.gray(".")+e.dim(".")+e.white("."),C=t.replace(/\.+$/,""),I=` ${h} ${e.gray(C)}${v}`;process.stdout.write(`\r${" ".repeat(80)}\r${I}`),n++},300),o=()=>{clearInterval(s),process.stdout.write(`\r${" ".repeat(80)}\r`)};return o.setLabel=h=>{t=h},o}function Us(n){const t=n?.agent;return t?t.provider?t.provider:t.gemini?"gemini":t.codex?"codex":t.claude?"claude":t.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}function Xe(n){return n.slice(-ie).map(t=>`${t.role==="human"?"H":"AI"}: ${t.content}`).join(`
|
|
2
2
|
`)}function Fs(n,t,s){let o=n;return t.length>0&&(o+=`
|
|
3
3
|
|
|
4
4
|
${Xe(t)}`),o+=`
|
|
5
5
|
H: ${s}
|
|
6
|
-
AI:`,o}function Qe(n){const t=n.filter(s=>!process.env[s]);return{ok:t.length===0,missing:t}}function ts(n){const t=
|
|
6
|
+
AI:`,o}function Qe(n){const t=n.filter(s=>!process.env[s]);return{ok:t.length===0,missing:t}}function ts(n){const t=lt(n,".zibby.config.mjs");if(!gt(t))return{};try{return import(t).then(s=>s.default||{})}catch{return{}}}async function es(n){const t=lt(n,".zibby","chat.mjs");if(gt(t))try{const o=await import(t);if(o.CHAT_CONFIG||o.default)return o.CHAT_CONFIG||o.default}catch{}const s=lt(Le(),".zibby","chat.mjs");if(s!==t&>(s))try{const o=await import(s);if(o.CHAT_CONFIG||o.default)return o.CHAT_CONFIG||o.default}catch{}try{const o=await import("@zibby/core/templates/browser-test-automation/chat.mjs");return o.CHAT_CONFIG||o.default||{}}catch{return{systemPrompt:"You are Zibby, a friendly AI assistant for test automation.",skills:[]}}}function ue(n){try{const t=lt(n,".zibby","commands");return gt(t)?Te(t).filter(s=>s.toLowerCase().endsWith(".md")).sort((s,o)=>s.localeCompare(o)):[]}catch{return[]}}function ss(n,t){const s=String(t||"").trim();if(!s.startsWith("/"))return s;const[o,...h]=s.split(/\s+/),k=h.join(" ").trim(),v=o.slice(1);if(!v)return s;const C=v.toLowerCase().endsWith(".md")?[v]:[v,`${v}.md`],I=lt(n,".zibby","commands"),U=C.find(R=>gt(Dt(I,R)));if(!U)return s;try{const R=oe(Dt(I,U),"utf-8").trim();return k?`${R}
|
|
7
7
|
|
|
8
8
|
${k}`:R}catch{return s}}function os(n){const t=n.slice(-ie),s=[];let o=0;for(let h=t.length-1;h>=0;h--){const k=t[h],v=String(k?.content||""),C=k?.role==="human"?"user":"assistant",I=v.length;if(s.length>=6&&o+I>Ke)break;s.push({role:C,content:v}),o+=I}return s.reverse()}function _t(n,t){const s=String(n||"");return s.length<=t?s:`${s.slice(0,Math.max(0,t-24))}
|
|
9
9
|
|
|
@@ -12,24 +12,26 @@ ${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(n={},t={}){const s=String(t.outputProfile||process.env.ZIBBY_OUTPUT_PROFILE||n.outputProfile||"cli_plain").trim(),o=n?.outputProfiles?.[s];return typeof o=="string"&&o.trim()?o.trim():o&&typeof o.instruction=="string"&&o.instruction.trim()?o.instruction.trim():pe[s]||pe.cli_plain}function Et(n,t){const s=String(n??"");return s.length<=t?s:t<=1?s.slice(0,t):`${s.slice(0,t-1)}\u2026`}function cs(){return!1}function js(n){return n}function as(n){const t=/^```(\w*)\n([\s\S]*?)^```$/gm;return n.replace(t,(s,o,h)=>{const k=h.replace(/\n$/,"");try{const v=o?ne(k,{language:o,ignoreIllegals:!0}):ne(k,{ignoreIllegals:!0}),C=e.gray("\u2500".repeat(Math.min(process.stdout.columns-6||54,72))),I=o?e.dim(` ${o}`):"";return`${C}${I}
|
|
14
14
|
${v}
|
|
15
|
-
${C}`}catch{return k}})}function zt(){const n=Number(process.stdout?.columns)||0,t=n>8?Math.max(30,n-4):
|
|
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++){
|
|
15
|
+
${C}`}catch{return k}})}function zt(){const n=Number(process.stdout?.columns)||0,t=n>8?Math.max(30,n-4):qe;return` ${"\u2500".repeat(t)}`}function de(n=[]){const t=Yt.map(o=>({cmd:o.cmd,source:"builtin",name:o.cmd.slice(1),desc:o.desc})),s=n.map(o=>({cmd:`/${o}`,source:"template",name:o,desc:"Command template"}));return[...t,...s]}function ls(n,t){const s=String(n||""),o=Number.isFinite(t)?t:s.length;return!(!s.startsWith("/")||o!==s.length||s.includes(" "))}function us({userName:n,cwd:t,projectName:s,restoredCount:o,skillsLine:h}){const k=Number(process.stdout?.columns)||0,v=Math.max(40,Math.min(k-8,100)),C=Math.max(20,Math.floor((v-3)*.55)),I=v-C-3,U=n||"there",R=s||"No project linked",ht=Ie(t||process.cwd()),W=[`Restored ${o} messages from previous session.`,"",h],rt=["Workspace details","",`v${Ze.version} | Hi, ${U}`,`Company: ${R}`,`Directory: ~/${ht}`,`Path: ${t}`,"","Use /help for commands"],E=Math.max(W.length,rt.length),V=(()=>{if(W.length>=E)return W;const F=Math.floor((E-W.length)/2),st=E-W.length-F;return[...Array(F).fill(""),...W,...Array(st).fill("")]})(),H="\u2500",L=` \u250C${H.repeat(C+2)}\u252C${H.repeat(I+2)}\u2510`,et=` \u2514${H.repeat(C+2)}\u2534${H.repeat(I+2)}\u2518`;console.log(e.gray(L));for(let F=0;F<E;F++){const st=Et(V[F]||"",C),it=Et(rt[F]||"",I),yt=" ".repeat(Math.max(0,C-st.length)),l=" ".repeat(Math.max(0,I-it.length)),w=` \u2502 ${st}${yt} \u2502 ${it}${l} \u2502`;console.log(e.gray(w))}console.log(e.gray(et)),console.log("")}function ps(){process.stdout?.isTTY&&(M(process.stdout,0,-2),B(process.stdout,4))}function ds(n){const t=!!(process.stdout?.isTTY&&process.stdin?.isTTY);let s=!1,o=!1,h=!1,k=null,v=0,C=0,I=0;function U(){return e.gray(zt())}function R(){k&&(clearInterval(k),k=null)}function ht(l){!t||!s||!o||!h||(process.stdout.write("\x1B7"),M(process.stdout,0,-2),B(process.stdout,0),G(process.stdout,0),process.stdout.write(` ${l}`),process.stdout.write("\x1B8"))}function W(){if(!(!t||!s)&&C!==0){process.stdout.write("\x1B7"),M(process.stdout,0,2);for(let l=0;l<C;l++)B(process.stdout,0),G(process.stdout,0),l<C-1&&M(process.stdout,0,1);process.stdout.write("\x1B8"),C=0,o&&rt()}}function rt(){!t||!s||!o||(process.stdout.write("\x1B7"),M(process.stdout,0,1),B(process.stdout,0),G(process.stdout,0),process.stdout.write(U()),process.stdout.write("\x1B8"))}function E(l,w){if(!t||!s||!o)return;W();const c=l.slice(0,6);if(c.length!==0){M(process.stdout,0,1);for(let y=0;y<c.length;y++)process.stdout.write(`
|
|
16
|
+
`);M(process.stdout,0,-(1+c.length)),process.stdout.write("\x1B7"),M(process.stdout,0,2);for(let y=0;y<c.length;y++){B(process.stdout,0),G(process.stdout,0);const Z=y===w?e.cyan("\u203A"):" ",f=y===w?e.white(c[y]):e.gray(c[y]);process.stdout.write(` ${Z} /${f}`),y<c.length-1&&M(process.stdout,0,1)}process.stdout.write("\x1B8"),C=c.length,rt()}}function V(){if(!t||!s||!o)return;W();const l=process.stdout.columns||80,w=I>0?Math.ceil(I/l):1;B(process.stdout,0),M(process.stdout,0,-w),h&&M(process.stdout,0,-2),process.stdout.write("\x1B[J"),o=!1}function H(l={}){const w=l.preserveInput===!0;if(!t){n.prompt();return}w||(n.line="",n.cursor=0),I=zt().length;const c=U();process.stdout.write(`${c}
|
|
17
17
|
`),n.prompt(),process.stdout.write(`
|
|
18
18
|
${c}
|
|
19
|
-
`),ps(),o=!0}function L(){if(!t||!s||!o)return;const l=process.stdout.columns||80,w=I>0?Math.ceil(I/l):1,c=U();process.stdout.write("\x1B7"),M(process.stdout,0,-w);for(let y=0;y<w;y++)
|
|
19
|
+
`),ps(),o=!0}function L(){if(!t||!s||!o)return;const l=process.stdout.columns||80,w=I>0?Math.ceil(I/l):1,c=U();process.stdout.write("\x1B7"),M(process.stdout,0,-w);for(let y=0;y<w;y++)B(process.stdout,0),G(process.stdout,0),y<w-1&&M(process.stdout,0,1);B(process.stdout,0),process.stdout.write(c),M(process.stdout,0,2),B(process.stdout,0),G(process.stdout,0),process.stdout.write(c);for(let y=1;y<w;y++)M(process.stdout,0,1),B(process.stdout,0),G(process.stdout,0);process.stdout.write("\x1B8"),I=zt().length}function et(){if(!t||!s||!o)return;const l=(()=>{if(typeof n.getCursorPos!="function")return 0;try{return Math.max(0,Number(n.getCursorPos()?.rows||0))}catch{return 0}})();process.stdout.write("\x1B7"),M(process.stdout,0,-(l+1)),B(process.stdout,0),G(process.stdout,0),process.stdout.write(U()),M(process.stdout,0,l+2),B(process.stdout,0),G(process.stdout,0),process.stdout.write(U()),process.stdout.write("\x1B8")}function F(l){R(),V(),console.log();const w=String(l??"").replace(/\r/g,"").split(`
|
|
20
20
|
`);for(;w.length>0&&w[w.length-1]==="";)w.pop();for(const c of w)console.log(c?` ${c}`:"");h=!1}function st(l){const w=String(l??"").replace(/\r/g,"").split(`
|
|
21
21
|
`);w.length===0&&w.push("");const c=[];for(const y of w)c.push(e.bgGray.white(` ${y||" "} `));return c.join(`
|
|
22
22
|
`)}function it(){R();const l=()=>e.gray(`${At[v%At.length]} thinking`);if(!t){console.log(` ${l()}`),h=!0;return}W(),V(),console.log(),console.log(` ${l()}`),H({preserveInput:!0}),h=!0,v+=1,k=setInterval(()=>{h&&(ht(l()),v+=1)},120)}function yt(l){R();const w=String(l??"").replace(/\r/g,"").replace(/⎿/g,"");if(!h){F(w);return}V(),console.log();const c=w.split(`
|
|
23
|
-
`);for(;c.length>0&&c[c.length-1]==="";)c.pop();for(const y of c)console.log(y?` ${y}`:"");console.log(),h=!1}return{enabled:t,mount(){if(!s){if(!t){n.prompt(),s=!0;return}s=!0,H()}},refreshPrompt(l={}){if(t&&s){o&&V(),H(l);return}n.prompt()},pushSystem(l){F(l)},pushUser(l){F(st(l))},pushAssistant(l){yt(l)},showAssistantLoading:it,dismissTransientLoading(){R(),h&&t&&s&&o&&(process.stdout.write("\x1B7"),M(process.stdout,0,-2),
|
|
23
|
+
`);for(;c.length>0&&c[c.length-1]==="";)c.pop();for(const y of c)console.log(y?` ${y}`:"");console.log(),h=!1}return{enabled:t,mount(){if(!s){if(!t){n.prompt(),s=!0;return}s=!0,H()}},refreshPrompt(l={}){if(t&&s){o&&V(),H(l);return}n.prompt()},pushSystem(l){F(l)},pushUser(l){F(st(l))},pushAssistant(l){yt(l)},showAssistantLoading:it,dismissTransientLoading(){R(),h&&t&&s&&o&&(process.stdout.write("\x1B7"),M(process.stdout,0,-2),B(process.stdout,0),G(process.stdout,0),M(process.stdout,0,-1),B(process.stdout,0),G(process.stdout,0),process.stdout.write("\x1B8")),h=!1},touchInputFrame:et,handleResize:L,showCommandDropdown:E,clearCommandDropdown:W}}function fs(){console.log(""),console.log(e.cyan(" Available commands:"));for(const n of Yt)console.log(e.white(` ${n.cmd.padEnd(10)} `)+e.gray(n.desc));console.log(""),console.log(e.cyan(" Chat options:")),console.log(e.white(" --stream, -s ")+e.gray("Enable typewriter effect (default: instant)")),console.log(""),console.log(e.gray(" To install/uninstall skills, just ask naturally:")),console.log(e.gray(' "connect to Jira" \u2022 "add GitHub" \u2022 "remove Slack"')),console.log("")}const ms=Qe;async function Ds(n={}){const t=process.cwd();n.verbose&&(process.env.ZIBBY_VERBOSE="true");const s=n.stream||!1;[lt(t,".env.local"),lt(t,".env")].forEach(c=>{gt(c)&&Me.config({path:c,override:!1})});try{await import("@zibby/skills")}catch{}function h(){const c=Wt();if(!c)return!1;try{const y=JSON.parse(atob(c.split(".")[1]));return y.exp&&y.exp*1e3>Date.now()}catch{return!1}}if(!h()){Ue();const c=re(),{spawn:y}=await import("child_process"),Z=await fetch(`${c}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});Z.ok||(console.log(e.red("\n Could not start login. Try `zibby login`.\n")),process.exit(1));const{deviceCode:f,verificationUrl:r,expiresIn:O,interval:ut}=await Z.json(),ot=process.platform;y(ot==="darwin"?"open":ot==="win32"?"cmd":"xdg-open",ot==="win32"?["/c","start","",r]:[r],{detached:!0,stdio:"ignore"}).unref(),console.log(e.cyan(`
|
|
24
|
+
Opening browser to authorize Zibby CLI...`)),console.log(e.gray(` ${r}
|
|
25
|
+
`));const ct=le();ct.setLabel("waiting for authorization");const pt=(ut||3)*1e3,dt=Math.floor(O/(ut||3));let X=!1;for(let nt=0;nt<dt;nt++){await Ve(pt);try{const Q=await fetch(`${c}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:f})});if(Q.status===202)continue;if(!Q.ok)break;const z=await Q.json();if(z.status==="authorized"){Be(z.token),Re(z.user),z.proxyUrl&&Fe(z.proxyUrl),z.mem0ProxyUrl&&We(z.mem0ProxyUrl),X=!0;break}if(z.status==="denied")break}catch{break}}ct(),X||(console.log(e.red("\n Login failed or timed out. Run `zibby login` to try again.\n")),process.exit(1))}const k=await ts(t),v=await es(t),C=n.agent||"assistant",I=Wt();I&&!process.env.ZIBBY_USER_TOKEN&&(process.env.ZIBBY_USER_TOKEN=I);const U=De()||je();U&&!process.env.ZIBBY_MEM0_OPENAI_BASE_URL&&(process.env.ZIBBY_MEM0_OPENAI_BASE_URL=U),process.env.AGENT_TYPE=C,process.env.ZIBBY_CHAT_OWNER_PID=String(process.pid);try{const{cleanupStalePidFiles:c}=await import("../utils/chat-run-lifecycle.js");c(t,k)}catch{}let R;try{R=ve({state:{agentType:C}})}catch(c){console.log(e.red(`
|
|
24
26
|
${c.message}
|
|
25
|
-
`)),process.exit(1)}const ht=Ne(),rt=
|
|
27
|
+
`)),process.exit(1)}const ht=Ne(),rt=Oe()?.[0]?.name,E=He(t),V=v.skills||[],H=Ye(t),L=H?[...new Set([...V,...H])]:[...V];let et={data:null,timestamp:0};const F=300*1e3,st={jira:"jira",github:"github",slack:"slack",sentry:"sentry"};try{const c=Wt();if(c){const y=re(),Z=await fetch(`${y}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${c}`}});if(Z.ok){const f=await Z.json();for(const[r,O]of Object.entries(st))f[r]?.connected&&!L.includes(O)&&$t(O)&&L.push(O);It(t,L)}}}catch{}const it=L.filter(c=>c!=="skill-installer"&&c!=="core-tools"),yt=it.length>0?`Skills: ${it.join(", ")}`:"Skills: (none)";us({userName:ht?.name?.split(" ")[0],cwd:t,projectName:rt,restoredCount:E.length,skillsLine:yt});let l=ue(t),w=de(l);return new Promise(c=>{const y=process.env.ZIBBY_CHAT_TAB_COMPLETION==="1",Z={input:process.stdin,output:process.stdout,prompt:e.green(" > "),terminal:!0};y&&(Z.completer=u=>{const i=String(u||"");if(!i.startsWith("/"))return[[],i];const m=w.map(P=>P.cmd),$=m.filter(P=>P.startsWith(i));return[$.length>0?$:m,i]});const f=Pe(Z),r=ds(f);let O=null,ut=!1;const ot=[],fe=0,me=1200;let ct=!1,pt=!1,dt=!1,X=!1,nt="",Q=0;const z=typeof f._ttyWrite=="function"?f._ttyWrite.bind(f):null;z&&(f._ttyWrite=(...u)=>{if(!(X||Date.now()<Q))return z(...u)});function ge(){dt||!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004h"),dt=!0)}function Jt(){dt&&(!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004l"),dt=!1))}function he(u){const i="\x1B[200~",m="\x1B[201~";if(!X&&!u.includes(i))return!1;let $=u,P=!1;for(;$.length>0;){if(!X){const A=$.indexOf(i);if(A===-1)break;P=!0,Kt(),X=!0,nt="",$=$.slice(A+i.length);continue}const J=$.indexOf(m);if(J===-1){P=!0,nt+=$;break}P=!0,nt+=$.slice(0,J);const tt=String(nt||"").replace(/\r\n/g,`
|
|
26
28
|
`).replace(/\r/g,`
|
|
27
29
|
`);if(tt.length>0){const A=tt.split(`
|
|
28
|
-
`);for(const
|
|
30
|
+
`);for(const q of A)Rt(q)}vt(),nt="",X=!1,$=$.slice(J+m.length)}return P}function Gt(){if(!ct){ct=!0;try{Pt(t,E),It(t,L)}catch{}try{Jt()}catch{}try{f.close()}catch{}process.exit(0)}}async function Lt(){if(!ct){ct=!0,typeof R?.cleanup=="function"&&await R.cleanup().catch(()=>{});try{const{killAllChatOrchestratedRuns:u}=await import("../utils/chat-run-lifecycle.js"),{postCliInterruptedRunIndex:i}=await import("@zibby/core/utils/run-index-post-cli.js");u(t,process.pid,k),i({cwd:t,config:k})}catch{}Pt(t,E),It(t,L),r.pushSystem(e.gray("Session saved. Goodbye!")),Jt(),f.close(),process.exit(0)}}if(r.mount(),ge(),process.stdout?.isTTY){let u;process.stdout.on("resize",()=>{clearTimeout(u),u=setTimeout(()=>{r.handleResize()},80)})}let Mt=0;const xt=u=>{if(typeof u=="string"?u==="\x1B":u&&typeof u.length=="number"?u.length===1&&u[0]===27:!1){O&&O.abort(),Gt();return}const m=typeof u=="string"?u:u&&typeof u.length=="number"?Buffer.from(u).toString("utf8"):"";if(!m)return;if(he(m)){Mt=Date.now()+1200,Q=Date.now()+1200,Bt();return}const $=(m.includes(`
|
|
29
31
|
`)||m.includes("\r"))&&m!=="\r"&&m!==`
|
|
30
32
|
`&&m!==`\r
|
|
31
|
-
`,P=m.includes("\x1B[200~")||m.includes("\x1B[201~"),J=m.length>=16&&/\s/.test(m)&&!m.startsWith("\x1B");($||P||J)&&(Mt=Date.now()+1200,Q=Date.now()+1200,Kt(),
|
|
32
|
-
`);Nt.push({placeholder:i,text:m});const $=String(x.prefix||"").trimEnd(),P=$?`${$} ${i}`:i;ft(P,{preserveFrame:!0}),mt(f.line)}x.active=!1,x.prefix="",x.lines=[],Q=0}function
|
|
33
|
+
`,P=m.includes("\x1B[200~")||m.includes("\x1B[201~"),J=m.length>=16&&/\s/.test(m)&&!m.startsWith("\x1B");($||P||J)&&(Mt=Date.now()+1200,Q=Date.now()+1200,Kt(),Bt())},N={query:"",matches:[],selected:0},Y={prefix:"",matches:[],nextIndex:0},x={active:!1,prefix:"",lines:[],timer:null},Nt=[];let Zt=0,Ot="";const ye=new Set(Yt.map(u=>u.cmd));function ft(u,{preserveFrame:i=!1}={}){const m=String(u||"");f.line=m,f.cursor=m.length,Ot=m,typeof f._refreshLine=="function"?f._refreshLine():f.prompt(),i&&r.touchInputFrame()}function qt(){Y.prefix="",Y.matches=[],Y.nextIndex=0}function vt(){if(x.timer&&(clearTimeout(x.timer),x.timer=null),x.active&&x.lines.length>0){Zt+=1;const u=x.lines.length,i=`[Pasted text #${Zt} +${u} lines]`,m=x.lines.join(`
|
|
34
|
+
`);Nt.push({placeholder:i,text:m});const $=String(x.prefix||"").trimEnd(),P=$?`${$} ${i}`:i;ft(P,{preserveFrame:!0}),mt(f.line)}x.active=!1,x.prefix="",x.lines=[],Q=0}function Bt(){x.timer&&clearTimeout(x.timer),x.timer=setTimeout(()=>{vt()},180)}function Kt(){x.active||(x.active=!0,x.prefix=String(Ot||f.line||""),x.lines=[],ft(x.prefix,{preserveFrame:!0}))}function Rt(u){return x.active?(x.lines.push(String(u||"")),ft(x.prefix,{preserveFrame:!0}),Bt(),!0):!1}function we(u){let i=String(u||"");for(const m of Nt)i=i.split(m.placeholder).join(m.text);return i}function mt(u){const i=String(u||"");if(!i.startsWith("/")||i.includes(" ")||i.length===0){N.query="",N.matches=[],N.selected=0,r.clearCommandDropdown();return}l=ue(t),w=de(l);const m=i.slice(1).toLowerCase(),$=l.filter(P=>P.toLowerCase().startsWith(m));N.query=m,N.matches=$,N.selected=Math.min(N.selected,Math.max(0,$.length-1)),r.showCommandDropdown($,N.selected)}const Ut=(u,i)=>{if(i?.name==="escape"||i?.sequence==="\x1B"){O&&O.abort(),Gt();return}if((i?.name==="return"||i?.name==="enter")&&(pt=!0),(i?.name==="backspace"||i?.name==="delete")&&r.touchInputFrame(),i?.name==="tab"&&!i?.shift){const P=String(f.line||""),J=Number(f.cursor||P.length);if(!ls(P,J)){qt(),mt(f.line);return}const tt=P.slice(1).toLowerCase();if(Y.prefix!==tt&&(Y.prefix=tt,Y.matches=w.map(q=>q.cmd).filter(q=>q.toLowerCase().startsWith(`/${tt}`)),Y.nextIndex=0),Y.matches.length===0)return;const A=Y.nextIndex%Y.matches.length;Y.nextIndex+=1,ft(Y.matches[A]),mt(f.line);return}const m=String(f.line||""),$=m.startsWith("/")&&!m.includes(" ")&&N.matches.length>0;if(i?.name==="up"||i?.name==="down"){if(!$){mt(f.line);return}const P=i.name==="up"?-1:1,J=N.matches.length;N.selected=(N.selected+P+J)%J;const tt=N.matches[N.selected];ft(`/${tt}`,{preserveFrame:!0}),r.showCommandDropdown(N.matches,N.selected);return}i?.name!=="tab"&&qt(),setTimeout(()=>{mt(f.line),x.active||(Ot=String(f.line||""))},50)};process.stdin?.on&&(Ae(process.stdin,f),process.stdin.on("keypress",Ut)),r.enabled&&process.stdin?.on&&(typeof process.stdin.prependListener=="function"?process.stdin.prependListener("data",xt):process.stdin.on("data",xt)),f.on("line",async u=>{try{let i=String(u||"");const m=pt;if(pt=!1,!m&&(x.active||X||Date.now()<Mt||Date.now()<Q)){if(x.active&&i.length>0){Rt(i);return}x.active&&(vt(),r.refreshPrompt());return}if(x.active&&(vt(),i=String(f.line||i||"")),Rt(i))return;const $=i.trim(),P=N.matches[N.selected];if($.startsWith("/")&&!$.includes(" ")&&N.matches.length>0&&!ye.has($)&&$!==`/${P}`){r.clearCommandDropdown(),r.refreshPrompt(),ft(`/${P}`),mt(`/${P}`);return}r.clearCommandDropdown();const A=String(i||"").replace(/[\u0000-\u001F\u007F-\u009F]/g,"").trim();if(!A){r.enabled&&process.stdout?.isTTY&&(M(process.stdout,0,-1),B(process.stdout,4));return}if(ut&&A!=="/exit"&&A!=="/quit"){O&&O.abort(),ot.push(A),r.pushSystem(e.gray("Processing your message...")),r.refreshPrompt({preserveInput:!0});return}const q=1e4;if(A.length>q){r.pushSystem(e.red(`\u26A0 Input too long (${A.length} chars). Maximum: ${q} characters.`)),r.pushSystem(e.gray("Tip: If you need to share logs, use a file instead:")),r.pushSystem(e.gray(" 1. Save to file: pbpaste > debug.log")),r.pushSystem(e.gray(' 2. Ask: "analyze debug.log in current directory"')),r.refreshPrompt();return}if(A==="/exit"||A==="/quit"){Lt();return}if(A==="/help"){fs(),r.refreshPrompt();return}if(A==="/skills"){const _=$t("skill-installer")?.catalog||{},g=L.filter(b=>b!=="skill-installer");console.log(e.cyan(`
|
|
33
35
|
Active skills:`)),g.length===0&&console.log(e.gray(" (none)"));for(const b of g){const S=_[b]||{};console.log(e.green(` \u2713 ${b}`)+e.gray(S.description?` \u2014 ${S.description}`:""))}const T=Object.keys(_).filter(b=>!L.includes(b));if(T.length>0){console.log(e.cyan(`
|
|
34
36
|
Available:`));for(const b of T){const S=_[b],d=S.envKeys?.length>0?ms(S.envKeys).ok?e.green(" \u2713 configured"):e.yellow(` \u26A0 needs: ${S.envKeys.join(", ")}`):"";console.log(e.white(` - ${b}`)+e.gray(` \u2014 ${S.description}`)+d)}}console.log(e.gray(`
|
|
35
37
|
Just ask to install: "connect to Jira", "add GitHub", etc.
|
|
@@ -59,7 +61,7 @@ ${c}
|
|
|
59
61
|
`)),console.log(e.white(` Facts stored: ${d>0?e.cyan(d):e.gray("0")}`)),console.log(e.white(` Sessions saved: ${p>0?e.cyan(p):e.gray("0")}`)),j&&console.log(e.white(` Task history: ${e.gray(j)}`)),console.log(e.gray(`
|
|
60
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(`
|
|
61
63
|
Memory error: ${b.message}
|
|
62
|
-
`))}r.refreshPrompt();return}r.enabled&&process.stdout?.isTTY&&(M(process.stdout,0,-1),
|
|
64
|
+
`))}r.refreshPrompt();return}r.enabled&&process.stdout?.isTTY&&(M(process.stdout,0,-1),B(process.stdout,0)),r.pushUser(A),r.refreshPrompt(),r.showAssistantLoading();const Vt=we(A),Tt=ss(t,Vt);if(Nt.length=0,!String(Tt||"").trim()){r.dismissTransientLoading(),r.refreshPrompt();return}if(Tt.length>q){r.pushAssistant(e.red(`Input too long after command expansion (${Tt.length} chars).`)),r.pushSystem(e.gray(`Try shortening the command template or user text. Limit: ${q} chars.`)),r.refreshPrompt();return}ut=!0;let K=v.systemPrompt||"You are Zibby, a helpful AI assistant.";const Xt=is(v,n);Xt&&(K+=`
|
|
63
65
|
|
|
64
66
|
${Xt}`);const Qt=ze({activeSkills:L,chatConfig:v,options:n});Qt&&(K+=`
|
|
65
67
|
|
|
@@ -84,6 +86,6 @@ Use provided tools when external data/actions are required. Do not claim actions
|
|
|
84
86
|
- After building: remind user about \`zibby start <name>\` (test), \`zibby deploy <name>\` (deploy), \`zibby logs\` (logs).
|
|
85
87
|
- Use list_workflows to show existing workflows, add_node to extend them, deploy_workflow to ship.`),L.includes("chat-memory"))try{const a=$t("chat-memory");if(typeof a?.buildPromptContext=="function"){const _=Date.now();let g;et.data&&_-et.timestamp<F?(g=et.data,process.env.ZIBBY_VERBOSE==="true"&&r.pushSystem(e.gray("Using cached memory context"))):(g=await a.buildPromptContext({options:{workspace:t}},{}),et={data:g,timestamp:_},process.env.ZIBBY_VERBOSE==="true"&&r.pushSystem(e.gray("Refreshed memory context cache")));const T=String(g?.backend||"dolt");process.env.ZIBBY_VERBOSE==="true"&&(r.pushSystem(e.gray(`memory backend: ${T}`)),r.pushSystem(e.gray(`memory retrieval output: ${Et(JSON.stringify(g?.debugPreview||{}),1400)}`)),g?.error&&r.pushSystem(e.yellow(`memory backend warning: ${g.error}`))),g?.promptContext&&(K+=`
|
|
86
88
|
|
|
87
|
-
${g.promptContext}`)}}catch(a){process.env.ZIBBY_VERBOSE==="true"&&r.pushSystem(e.yellow(`memory backend warning: ${String(a?.message||a)}`))}K=_t(K,ce);const Se=os(E),Ft=ns([{role:"system",content:K},...Se,{role:"user",content:Tt}]),ee=Ht(Ft),ke=Buffer.byteLength(JSON.stringify(Ft),"utf8");process.env.ZIBBY_VERBOSE==="true"&&r.pushSystem(e.gray(`payload estimate: ${ee} chars, ${ke} bytes (~${Math.round(ee/4)} tokens)`)),E.push({role:"human",content:Vt});const wt=r.enabled?(()=>{const a=()=>{};return a.setLabel=()=>{},a})():le();let
|
|
88
|
-
${g}`:g;E.push({role:"ai",content:b}),Pt(t,E),It(t,L)}catch(a){if(
|
|
89
|
-
[Active test runs: ${S.runs.map(p=>`${p.runId}: ${p.ticketKey||p.spec} (${p.status})`).join(", ")}. Use run_status("all") to check progress.]`)}catch{}const g=bt.trim();g?E.push({role:"ai",content:g+_}):E.push({role:"ai",content:`[interrupted \u2014 new message]${_}`})}else{const _=String(a?.message||a||"Unknown error");/413|payload too large|request payload too large/i.test(_)?(r.pushAssistant(e.yellow("Request became too large for the proxy (413).")),r.pushSystem(e.gray("Try: /clear, then retry your command; or shorten command/context."))):r.pushAssistant(e.red(`Error: ${_}`)),E.push({role:"ai",content:`[Error: ${a.message}]`})}}finally{
|
|
89
|
+
${g.promptContext}`)}}catch(a){process.env.ZIBBY_VERBOSE==="true"&&r.pushSystem(e.yellow(`memory backend warning: ${String(a?.message||a)}`))}K=_t(K,ce);const Se=os(E),Ft=ns([{role:"system",content:K},...Se,{role:"user",content:Tt}]),ee=Ht(Ft),ke=Buffer.byteLength(JSON.stringify(Ft),"utf8");process.env.ZIBBY_VERBOSE==="true"&&r.pushSystem(e.gray(`payload estimate: ${ee} chars, ${ke} bytes (~${Math.round(ee/4)} tokens)`)),E.push({role:"human",content:Vt});const wt=r.enabled?(()=>{const a=()=>{};return a.setLabel=()=>{},a})():le();let at=!0;const Ct=[];let se="",bt="";const hs=50,ys=500,ws=3,bs=60,Ss=500,ks=15,$s=25,_s=4,xs=new Set([".","!","?",",",";",":"]),$e=a=>{at&&(wt(),at=!1),bt+=a},_e=(a,_)=>{if(!a){at&&wt.setLabel("thinking...");return}Ct.push(a);const g=70;let T=a;if(_&&typeof _=="object"){const S=Object.values(_).map(p=>typeof p=="string"?p:JSON.stringify(p)).join(", "),d=`${a}(${S})`;d.length<=g?T=d:T=`${a}(${S.slice(0,g-a.length-4)}...)`}T!==se&&(se=T,r.pushSystem(e.gray(`\u23BF ${T}`)),r.refreshPrompt({preserveInput:!0}),at&&r.showAssistantLoading()),at&&wt.setLabel(T)},jt=new AbortController;O=jt;try{const a=await xe("",{state:{agentType:C,config:k,cwd:t,workspace:t}},{model:k?.agent?.assistant?.model||v.model||"auto",workspace:t,skills:L,activeSkills:L,config:k,timeout:v.timeout||3e5,messages:Ft,skipPromptFragments:!0,stream:!0,onToken:$e,onToolCall:_e,signal:jt.signal});at&&wt();const _=typeof a=="string"?a:a?.structured?JSON.stringify(a.structured,null,2):a?.raw||String(a),g=bt&&bt.trim().length>0?bt.trim():_.trim(),T=cs(g,Ct)?g:as(g);r.pushAssistant(T);const b=Ct.length>0?`[tools used: ${Ct.join(", ")}]
|
|
90
|
+
${g}`:g;E.push({role:"ai",content:b}),Pt(t,E),It(t,L)}catch(a){if(at&&wt(),r.dismissTransientLoading(),jt.signal.aborted){ot.length===0&&r.pushAssistant(e.gray("[cancelled]"));let _="";try{const{testRunnerSkill:T}=await import("../../skills/index.js"),b=await T.handleToolCall("run_status",{runId:"all"},{options:{workspace:t}}),S=JSON.parse(b);S.runs?.length>0&&(_=`
|
|
91
|
+
[Active test runs: ${S.runs.map(p=>`${p.runId}: ${p.ticketKey||p.spec} (${p.status})`).join(", ")}. Use run_status("all") to check progress.]`)}catch{}const g=bt.trim();g?E.push({role:"ai",content:g+_}):E.push({role:"ai",content:`[interrupted \u2014 new message]${_}`})}else{const _=String(a?.message||a||"Unknown error");/413|payload too large|request payload too large/i.test(_)?(r.pushAssistant(e.yellow("Request became too large for the proxy (413).")),r.pushSystem(e.gray("Try: /clear, then retry your command; or shorten command/context."))):r.pushAssistant(e.red(`Error: ${_}`)),E.push({role:"ai",content:`[Error: ${a.message}]`})}}finally{O=null,ut=!1}if(r.refreshPrompt(),ot.length>0){const a=ot.shift();pt=!0,setImmediate(()=>f.emit("line",a))}}catch(i){r.pushSystem(e.red(`Input handling error: ${i?.message||String(i)}`)),r.refreshPrompt()}}),f.on("SIGINT",()=>{if(O){O.abort();return}Lt()}),f.on("close",Lt);const be=()=>{process.stdin?.off?(process.stdin.off("data",xt),process.stdin.off("keypress",Ut)):process.stdin?.removeListener&&(process.stdin.removeListener("data",xt),process.stdin.removeListener("keypress",Ut))};f.on("close",be)})}export{Fs as _buildPrompt,Qe as _checkEnvKeys,Xe as _formatHistory,Us as _inferAgentType,Ds as chatCommand};
|
package/dist/commands/init.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{mkdir as S,writeFile as p,readFile as w}from"fs/promises";import{existsSync as h,readdirSync as G}from"fs";import{join as a,resolve as O,dirname as H}from"path";import{homedir as P}from"os";import Y from"inquirer";import e from"chalk";import I from"ora";import{spawn as K,execSync as R}from"child_process";import{fileURLToPath as V}from"url";import{createRequire as Z}from"module";import{AGENT_KEY_MAP as D,saveAgentApiKey as F,readGlobalConfig as W}from"../utils/agent-credentials.js";const U=V(import.meta.url),q=H(U),N=Z(import.meta.url);async function X(){try{const d=process.platform==="win32",o=R("npm config get prefix",{encoding:"utf-8"}).trim(),
|
|
1
|
+
import{mkdir as S,writeFile as p,readFile as w}from"fs/promises";import{existsSync as h,readdirSync as G}from"fs";import{join as a,resolve as O,dirname as H}from"path";import{homedir as P}from"os";import Y from"inquirer";import e from"chalk";import I from"ora";import{spawn as K,execSync as R}from"child_process";import{fileURLToPath as V}from"url";import{createRequire as Z}from"module";import{AGENT_KEY_MAP as D,saveAgentApiKey as F,readGlobalConfig as W}from"../utils/agent-credentials.js";const U=V(import.meta.url),q=H(U),N=Z(import.meta.url);async function X(){try{const d=process.platform==="win32",o=R("npm config get prefix",{encoding:"utf-8"}).trim(),f=d?o:`${o}/bin`,m=f.replace(/^~/,P()),l=d?";":":";if(process.env.PATH.split(l).some(y=>{const x=y.replace(/^~/,P());return x===m||x===f}))return;if(process.env.CI||process.env.ZIBBY_CI||!process.stdin.isTTY){console.log(e.yellow("\u26A0\uFE0F npm global bin not in PATH")),console.log(e.gray(` Location: ${m}`)),console.log(e.gray(` Add it manually: export PATH="${m}:$PATH"
|
|
2
2
|
`));return}console.log(e.yellow("\u26A0\uFE0F npm global bin not in PATH")),console.log(e.gray(` Location: ${m}`)),console.log();const{shouldAddPath:s}=await Y.prompt([{type:"confirm",name:"shouldAddPath",message:"Add npm global bin to your shell PATH automatically?",default:!0}]);if(!s){d?(console.log(e.gray(`
|
|
3
3
|
\u{1F4A1} To add manually on Windows:`)),console.log(e.gray(' 1. Search "Environment Variables" in Start menu')),console.log(e.gray(' 2. Edit "Path" in User variables')),console.log(e.gray(` 3. Add: ${m}
|
|
4
4
|
`))):(console.log(e.gray(`
|
|
5
5
|
\u{1F4A1} To add manually, run:`)),console.log(e.gray(` echo 'export PATH="${m}:$PATH"' >> ~/.zshrc`)),console.log(e.gray(` source ~/.zshrc
|
|
6
6
|
`)));return}if(d){console.log(e.yellow("\u26A0\uFE0F Cannot auto-add PATH on Windows")),console.log(e.gray(" Please add manually:")),console.log(e.gray(' 1. Search "Environment Variables" in Start menu')),console.log(e.gray(' 2. Edit "Path" in User variables')),console.log(e.gray(` 3. Add: ${m}
|
|
7
|
-
`));return}const
|
|
7
|
+
`));return}const C=process.env.SHELL||"";let g="";if(C.includes("zsh"))g=a(P(),".zshrc");else if(C.includes("bash"))g=h(a(P(),".bashrc"))?a(P(),".bashrc"):a(P(),".bash_profile");else{console.log(e.yellow(`\u26A0\uFE0F Unknown shell: ${C}`)),console.log(e.gray(" Please add manually:")),console.log(e.gray(` export PATH="${m}:$PATH"`));return}if(h(g)){const y=await w(g,"utf-8");if(y.includes(m)||y.includes("npm")&&y.includes("global")&&y.includes("bin")){console.log(e.yellow(`\u26A0\uFE0F PATH entry found in ${g} but not active`)),console.log(e.gray(` Run: source ${g}
|
|
8
8
|
`));return}}const v=`
|
|
9
9
|
# npm global bin (added by zibby)
|
|
10
10
|
export PATH="${m}:$PATH"
|
|
@@ -12,7 +12,7 @@ export PATH="${m}:$PATH"
|
|
|
12
12
|
\u{1F4A1} Run this to activate in current session:`)),console.log(e.gray(` source ${g}
|
|
13
13
|
`))}catch{}}async function be(d,o){console.log(e.bold.cyan(`
|
|
14
14
|
\u{1F3AD} Welcome to Zibby Test Automation!
|
|
15
|
-
`));const
|
|
15
|
+
`));const f=!o.skipMemory,m=["dolt","mem0"].includes(String(o.memoryBackend||"").toLowerCase())?String(o.memoryBackend).toLowerCase():"dolt";await X();const l=d?O(process.cwd(),d):process.cwd(),$=d||"zibby-tests",b=!!d;b&&h(l)&&(console.log(e.red(`
|
|
16
16
|
\u274C Directory "${d}" already exists!
|
|
17
17
|
`)),process.exit(1)),!b&&h(a(l,".zibby.config.mjs"))&&!o.force&&(console.log(e.yellow(`
|
|
18
18
|
\u26A0\uFE0F Zibby is already initialized in this directory!
|
|
@@ -20,7 +20,7 @@ export PATH="${m}:$PATH"
|
|
|
20
20
|
`)),process.exit(0)),o.force&&!b&&console.log(e.cyan(`
|
|
21
21
|
Reinitializing Zibby configuration...
|
|
22
22
|
`));let s;if(o.agent&&(o.headed||o.headless))console.log(e.cyan(`Setting up with provided options...
|
|
23
|
-
`)),s={agent:o.agent,browserMode:o.headless?"headless":"headed",apiKey:o.apiKey||null,cloudSync:!!(o.cloudSync||o.apiKey)};else{if(o.agent)s={agent:o.agent};else{const{agent:
|
|
23
|
+
`)),s={agent:o.agent,browserMode:o.headless?"headless":"headed",apiKey:o.apiKey||null,cloudSync:!!(o.cloudSync||o.apiKey)};else{if(o.agent)s={agent:o.agent};else{const{agent:E}=await Y.prompt([{type:"select",name:"agent",message:"Which AI agent do you prefer?",choices:[{name:"Cursor",value:"cursor"},{name:"Claude (Anthropic)",value:"claude"},{name:"Codex (OpenAI)",value:"codex"},{name:"Gemini (Google)",value:"gemini"}],default:"cursor"}]);s={agent:E}}const y=D[s.agent];if(y&&!o.agentKey&&!(process.env.CI||process.env.ZIBBY_CI||!process.stdin.isTTY)){const E=W(),B=process.env[y.envVar]||E.agentKeys?.[y.envVar],A=B?`***${B.slice(-4)}`:null,t=A?`${y.label} found (${A}). Press Enter to keep, or paste a new key:`:`Enter ${y.label} (from ${y.url}, or press Enter to skip):`,{agentKey:i}=await Y.prompt([{type:"password",name:"agentKey",message:t,mask:"*"}]);i&&i.trim()&&(s.agentKey=i.trim())}const x=[];if(!o.headed&&!o.headless&&x.push({type:"select",name:"browserMode",message:"Browser mode during live AI execution?",choices:[{name:"Headed - Visible browser (recommended for development)",value:"headed"},{name:"Headless - Hidden browser (for CI/CD)",value:"headless"}],default:"headed"}),o.apiKey||x.push({type:"input",name:"apiKey",message:"Enable cloud sync? Enter project ZIBBY_API_KEY (or press Enter to skip):"}),x.length>0){const E=await Y.prompt(x);Object.assign(s,E)}s.browserMode=o.headless?"headless":o.headed?"headed":s.browserMode,s.apiKey=o.apiKey||s.apiKey,s.cloudSync=!!(o.cloudSync||o.apiKey||s.apiKey&&s.apiKey.trim())}o.agentKey&&(s.agentKey=o.agentKey);const g=D[s.agent];s.agentKey&&(F(s.agentKey,s.agent),console.log(e.gray(" \u2713 Agent API key saved to ~/.zibby/config.json"))),s.mcp="playwright",s.setupMcp=s.agent==="cursor";const v=I("Setting up Zibby...").start();try{if(b&&await S(l,{recursive:!0}),await S(a(l,"test-specs/examples"),{recursive:!0}),await S(a(l,"tests"),{recursive:!0}),await S(a(l,".zibby/output"),{recursive:!0}),await S(a(l,".zibby/commands"),{recursive:!0}),f&&m==="dolt")try{const{initMemory:t,DoltDB:i}=await import("@zibby/memory");if(i.isAvailable()){const{created:n}=t(l);n&&(v.text="Initialized test memory database (Dolt)...")}else v.text="Dolt not found \u2014 skipping memory database (brew install dolt)"}catch{}v.text="Scaffolding workflow graph...";const{TemplateFactory:y}=await import("@zibby/core/templates"),x=o.template||"browser-test-automation";try{const{graphPath:t,nodesPath:i,readmePath:n,resultHandlerPath:c,template:r}=y.getTemplateFiles(x),u=a(l,".zibby"),M=await w(t,"utf-8");if(await p(a(u,"graph.mjs"),M),c){const k=await w(c,"utf-8");await p(a(u,"result-handler.mjs"),k)}const z=await w(n,"utf-8");await p(a(u,"README.md"),z),await S(a(u,"nodes"),{recursive:!0});const{readdirSync:_}=await import("fs"),T=_(i);for(const k of T){let j=await w(a(i,k),"utf-8");!f&&k==="execute-live.mjs"&&(j=j.replace("skills: [SKILLS.BROWSER, SKILLS.MEMORY],","skills: [SKILLS.BROWSER],")),await p(a(u,"nodes",k),j)}const L=a(r.path,"chat.mjs");if(h(L)){const k=await w(L,"utf-8");await p(a(u,"chat.mjs"),k)}}catch(t){throw v.fail(`Failed to scaffold template: ${t.message}`),t}v.text="Generating configuration files...";const E=J(s,o,{memoryBackend:m});if(await p(a(l,".zibby.config.mjs"),E),await p(a(l,".env.example"),Q(s,m)),s.apiKey&&s.apiKey.trim()){const t=a(l,".env"),i=s.apiKey.trim();if(h(t)){let n=await w(t,"utf8");/^ZIBBY_API_KEY=/m.test(n)?n=n.replace(/^ZIBBY_API_KEY=.*/m,`ZIBBY_API_KEY=${i}`):/^#\s*ZIBBY_API_KEY=/m.test(n)?n=n.replace(/^#\s*ZIBBY_API_KEY=.*/m,`ZIBBY_API_KEY=${i}`):n=`${n.trimEnd()}
|
|
24
24
|
|
|
25
25
|
# Zibby Cloud Sync
|
|
26
26
|
ZIBBY_API_KEY=${i}
|
|
@@ -31,7 +31,7 @@ ${g.envVar}=${i}
|
|
|
31
31
|
`,await p(t,n)}}if(b){const t=te($,s,{memoryBackend:m});await p(a(l,"package.json"),t)}if(!h(a(l,".gitignore"))){const t=ne();await p(a(l,".gitignore"),t)}if(!h(a(l,"playwright.config.js"))){const t=oe("on");await p(a(l,"playwright.config.js"),t)}if(!h(a(l,"test-specs/examples/example-domain.txt"))){const t=se();await p(a(l,"test-specs/examples/example-domain.txt"),t)}const B=O(q,"../../../../examples/.zibby/commands");if(h(B)){const t=G(B).filter(i=>i.toLowerCase().endsWith(".md"));for(const i of t){const n=a(l,".zibby/commands",i);if(o.force||!h(n)){const c=await w(a(B,i),"utf-8");await p(n,c)}}}if(!h(a(l,".zibby/commands/example.md"))){const t=ie();await p(a(l,".zibby/commands/example.md"),t)}if(b){const t=ae($,s);await p(a(l,"README.md"),t)}if(v.succeed(b?"Project created!":"Zibby initialized!"),b&&!o.skipInstall){const t=I("Installing dependencies...").start();await new Promise((i,n)=>{K("npm",["install"],{cwd:l,stdio:"pipe"}).on("close",r=>{r===0?(t.succeed("Dependencies installed!"),i()):(t.fail("Failed to install dependencies"),n(new Error("npm install failed")))})})}else if(!b){const t=["@zibby/cli","@zibby/core"],i=[];for(const n of t)try{Z(a(l,"package.json")).resolve(`${n}/package.json`)}catch{i.push(n)}if(i.length>0){const n=N("../../package.json"),c=i.map(r=>r==="@zibby/cli"?`${r}@latest`:r==="@zibby/core"?`${r}@${n.dependencies?.["@zibby/core"]||"^0.1.29"}`:r);if(o.skipInstall)console.log(e.yellow(`
|
|
32
32
|
Missing required Zibby dependencies in this project:`)),console.log(e.white(` ${i.join(", ")}`)),console.log(e.gray("Install them manually to avoid runtime errors:")),console.log(e.white(` npm install --save-dev ${c.join(" ")}
|
|
33
33
|
`));else{const r=I(`Installing ${c.join(", ")}...`).start();await new Promise(M=>{K("npm",["install","--save-dev",...c],{cwd:l,stdio:"pipe"}).on("close",_=>M(_??1))})===0?r.succeed("Installed missing Zibby dependencies"):(r.warn("Could not auto-install Zibby dependencies"),console.log(e.gray("Run this manually:")),console.log(e.white(` npm install --save-dev ${c.join(" ")}
|
|
34
|
-
`)))}}}if(!b&&
|
|
34
|
+
`)))}}}if(!b&&f&&m==="mem0"&&(console.log(e.yellow(`
|
|
35
35
|
Using mem0 backend requires mem0ai in your project dependencies.`)),console.log(e.gray("Run this manually in your project when ready:")),console.log(e.white(` npm install mem0ai
|
|
36
36
|
`))),!o.skipInstall){const t=I("Installing Playwright browsers...").start();await new Promise(i=>{const n=K("npx",["playwright","install","chromium"],{cwd:l,stdio:"pipe"});let c="";n.stdout.on("data",r=>{c+=r.toString()}),n.stderr.on("data",r=>{c+=r.toString()}),n.on("close",r=>{r===0?(c.includes("already installed")||c.includes("up to date")?t.succeed("Playwright browsers already installed"):t.succeed("Playwright browsers installed!"),i()):(t.warn("Could not verify Playwright browsers"),console.log(e.yellow(`
|
|
37
37
|
\u26A0\uFE0F If tests fail, run: npx playwright install
|
|
@@ -48,10 +48,10 @@ Using mem0 backend requires mem0ai in your project dependencies.`)),console.log(
|
|
|
48
48
|
\u{1F389} All set!
|
|
49
49
|
`)),console.log(e.cyan("Start the Zibby Chat Agent:")),b&&console.log(e.white(` cd ${d}`)),console.log(e.white(` zibby
|
|
50
50
|
`)),console.log(e.cyan("Or run a test directly:")),console.log(e.white(` zibby run test-specs/examples/example-domain.txt
|
|
51
|
-
`)),console.log(e.cyan("Next steps:"));let
|
|
52
|
-
`))}catch(
|
|
53
|
-
\u274C Error: ${
|
|
54
|
-
`)),process.exit(1)}}function J(d,o={},
|
|
51
|
+
`)),console.log(e.cyan("Next steps:"));let A=1;console.log(e.white(` ${A++}. cp .env.example .env ${e.gray("# then add your API keys")}`)),f&&console.log(e.white(` ${A++}. Set ${e.bold("ZIBBY_MEMORY_BACKEND")} in .env ${e.gray(`# currently: ${m}`)}`)),console.log(e.white(` ${A++}. Type ${e.bold("zibby")} to chat with the AI testing assistant`)),console.log(e.white(` ${A++}. Write test specs in test-specs/`)),console.log(e.white(` ${A++}. Run: npx zibby run <spec-file>
|
|
52
|
+
`))}catch(y){v.fail("Failed to create project"),console.error(e.red(`
|
|
53
|
+
\u274C Error: ${y.message}
|
|
54
|
+
`)),process.exit(1)}}function J(d,o={},f={}){const m=["dolt","mem0"].includes(String(f.memoryBackend||"").toLowerCase())?String(f.memoryBackend).toLowerCase():"dolt",l={claude:`
|
|
55
55
|
claude: {
|
|
56
56
|
model: 'auto', // Options: 'auto', 'sonnet-4.6', 'opus-4.6', 'sonnet-4.5', 'opus-4.5'
|
|
57
57
|
maxTokens: 4096,
|
|
@@ -65,7 +65,7 @@ Using mem0 backend requires mem0ai in your project dependencies.`)),console.log(
|
|
|
65
65
|
gemini: {
|
|
66
66
|
model: 'gemini-2.5-pro', // Options: 'auto', 'gemini-2.5-pro', 'gemini-2.5-flash'
|
|
67
67
|
},`},$=d.agent,b=Object.entries(l).filter(([s])=>s!==$).map(([,s])=>s.split(`
|
|
68
|
-
`).map(
|
|
68
|
+
`).map(C=>C.trim()?` // ${C.trimStart()}`:C).join(`
|
|
69
69
|
`)).join(`
|
|
70
70
|
`);return`export default {
|
|
71
71
|
// AI agent settings
|
|
@@ -150,7 +150,7 @@ ${{claude:"ANTHROPIC_API_KEY=sk-ant-your_key_here",cursor:`# Cursor Agent uses c
|
|
|
150
150
|
|
|
151
151
|
# Chat memory backend
|
|
152
152
|
ZIBBY_MEMORY_BACKEND=${o}
|
|
153
|
-
`}function ee(d,o,
|
|
153
|
+
`}function ee(d,o,f="dolt"){return`# Zibby Test Automation - Environment Variables
|
|
154
154
|
|
|
155
155
|
# AI Provider Keys
|
|
156
156
|
${{claude:"ANTHROPIC_API_KEY=sk-ant-your_key_here",cursor:"# Cursor Agent uses cursor-agent CLI \u2014 no API key needed",codex:"OPENAI_API_KEY=sk-your_key_here",gemini:"GEMINI_API_KEY=your_key_here"}[d.agent]||""}
|
|
@@ -164,8 +164,8 @@ ZIBBY_API_KEY=${o}
|
|
|
164
164
|
# ZIBBY_MEMORY_COMPACT_EVERY=1500 # Auto-compact every N runs (0 to disable)
|
|
165
165
|
|
|
166
166
|
# Chat memory backend
|
|
167
|
-
ZIBBY_MEMORY_BACKEND=${
|
|
168
|
-
`}function te(d,o,
|
|
167
|
+
ZIBBY_MEMORY_BACKEND=${f}
|
|
168
|
+
`}function te(d,o,f={}){const l={"@zibby/cli":"latest","@zibby/core":N("../../package.json").dependencies?.["@zibby/core"]||"^0.1.29"};return f.memoryBackend==="mem0"&&(l.mem0ai="^2.4.6"),JSON.stringify({name:d,version:"1.0.0",type:"module",private:!0,scripts:{"test:spec":"zibby run",test:"playwright test","test:headed":"playwright test --headed"},dependencies:l,devDependencies:{"@playwright/test":"^1.49.0",dotenv:"^17.2.3"}},null,2)}function ne(){return`# Dependencies
|
|
169
169
|
node_modules/
|
|
170
170
|
|
|
171
171
|
# Test artifacts
|
package/dist/package.json
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
import{existsSync as a,readFileSync as f,writeFileSync as
|
|
2
|
-
`,"utf-8")}function
|
|
1
|
+
import{existsSync as a,readFileSync as f,writeFileSync as b,mkdirSync as h}from"fs";import{join as i}from"path";import{homedir as u}from"os";const m={cursor:{envVar:"CURSOR_API_KEY",label:"Cursor API Key",url:"https://cursor.com/settings"},claude:{envVar:"ANTHROPIC_API_KEY",label:"Anthropic API Key",url:"https://console.anthropic.com/settings/keys"},codex:{envVar:"OPENAI_API_KEY",label:"OpenAI API Key",url:"https://platform.openai.com/api-keys"},gemini:{envVar:"GEMINI_API_KEY",label:"Gemini API Key",url:"https://aistudio.google.com/app/apikey"}};function v(){return i(u(),".zibby","config.json")}function A(){try{const n=v();return a(n)?JSON.parse(f(n,"utf-8")):{}}catch{return{}}}function V(n,r){const o=i(u(),".zibby");h(o,{recursive:!0});const t=v(),e=A(),s=r?m[r]:null;s&&((!e.agentKeys||typeof e.agentKeys!="object")&&(e.agentKeys={}),e.agentKeys[s.envVar]=String(n).trim()),delete e.agentApiKey,b(t,`${JSON.stringify(e,null,2)}
|
|
2
|
+
`,"utf-8")}function I(n){const r=[i(n,".zibby.config.mjs"),i(u(),".zibby.config.mjs")];for(const o of r)if(a(o))try{const t=f(o,"utf-8");for(const e of["cursor","claude","codex","gemini"])if(new RegExp(`agent\\s*:\\s*\\{[^}]*${e}\\s*:`,"s").test(t))return e}catch{}return null}function _(n){const r=n||process.cwd(),o=I(r);if(!o)return;const t=m[o];if(!t||process.env[t.envVar])return;const e=[i(r,".env.local"),i(r,".env")];for(const l of e)if(a(l))try{for(const d of f(l,"utf-8").split(`
|
|
3
|
+
`)){const c=d.trim();if(c.startsWith("#")||!c.includes("="))continue;const y=c.indexOf("="),K=c.slice(0,y).trim(),g=c.slice(y+1).trim();if(K===t.envVar&&g){process.env[t.envVar]=g;return}}}catch{}const p=A().agentKeys?.[t.envVar];p&&(process.env[t.envVar]=p)}export{m as AGENT_KEY_MAP,_ as bootstrapAgentEnv,I as detectAgentType,A as readGlobalConfig,V as saveAgentApiKey};
|