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