@zibby/cli 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +2 -2
  2. package/dist/auth/cli-login.js +7 -7
  3. package/dist/auth/ensure-auth.js +6 -6
  4. package/dist/bin/zibby.js +3 -3
  5. package/dist/commands/chat-agents.js +1 -0
  6. package/dist/commands/chat-sandbox-attach.js +5 -0
  7. package/dist/commands/chat.js +79 -69
  8. package/dist/commands/credentials-api.js +1 -0
  9. package/dist/commands/credentials-file.js +1 -0
  10. package/dist/commands/creds.js +1 -0
  11. package/dist/commands/init.js +83 -75
  12. package/dist/commands/list-projects.js +5 -5
  13. package/dist/commands/memory.js +28 -18
  14. package/dist/commands/project.js +3 -3
  15. package/dist/commands/run.js +52 -55
  16. package/dist/commands/studio.js +1 -1
  17. package/dist/commands/template.js +9 -0
  18. package/dist/commands/upload.js +4 -4
  19. package/dist/commands/workflow.js +23 -23
  20. package/dist/commands/workflows/dedicated-egress.js +6 -6
  21. package/dist/commands/workflows/delete.js +4 -4
  22. package/dist/commands/workflows/deploy.js +19 -19
  23. package/dist/commands/workflows/env.js +7 -7
  24. package/dist/commands/workflows/generate.js +13 -13
  25. package/dist/commands/workflows/list.js +6 -6
  26. package/dist/commands/workflows/run-local.js +15 -15
  27. package/dist/commands/workflows/start.js +16 -16
  28. package/dist/commands/workflows/trigger.js +7 -7
  29. package/dist/config/environments.js +1 -1
  30. package/dist/package.json +4 -4
  31. package/dist/templates/zibby-workflow-claude/claude/commands/zibby-static-ip.md +1 -1
  32. package/dist/utils/agent-credentials.js +4 -3
  33. package/dist/utils/credentials-loader.js +1 -0
  34. package/package.json +4 -4
@@ -1,91 +1,101 @@
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 re={};gn(re,{cleanupStalePidFiles:()=>Mn,killAllChatOrchestratedRuns:()=>On,killPidTreeBestEffort:()=>Ze,registerChatOrchestratedRun:()=>Ln,unregisterChatOrchestratedRun:()=>Bn});import{existsSync as ne,mkdirSync as Tn,readFileSync as Pn,readdirSync as Cn,unlinkSync as oe,writeFileSync as He}from"fs";import{join as Ft}from"path";import{execSync as We}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 se(e,t,n){let s=jt(e,t,n);if(!ne(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=se(e,l,r);y.includes(c)||y.push(c),He(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(!ne(d))return;let y=se(e,l,r).filter(L=>L!==c);if(y.length===0)try{oe(d)}catch{}else He(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=We(`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 ze(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{We(`taskkill /PID ${t} /T /F`,{stdio:"ignore",windowsHide:!0})}catch{}}function Ze(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)return;if(process.platform==="win32"){Rn(t);return}ze(t,"SIGTERM");let n=setTimeout(()=>{ze(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=se(e,r,s);for(let d of l)d!==process.pid&&Ze(d);try{ne(c)&&oe(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{oe(Ft(s,c))}catch{}}}var Fn,ie=mn(()=>{Fn=/^\.zibby-chat-run-pids-(\d+)\.json$/});import{invokeAgent as jn,getAgentStrategy as Dn}from"@zibby/core";import{getSkill as Pt}from"@zibby/skills";import{existsSync as yt,readFileSync as Qe,readdirSync as Yn}from"fs";import{resolve as ft,join as le,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 Je}from"cli-highlight";import Vn from"dotenv";import{existsSync as ke,mkdirSync as hn,readFileSync as yn,writeFileSync as bn}from"fs";import{homedir as _e}from"os";import{join as Rt}from"path";function ve(){return process.env.ZIBBY_CONFIG_DIR||Rt(_e(),".zibby")}function $e(){return Rt(ve(),"config.json")}var wn=Rt(_e(),".zibby"),Eo=Rt(wn,"config.json");function Sn(){let e=ve();ke(e)||hn(e,{recursive:!0})}function X(){try{let e=$e();if(ke(e)){let t=yn(e,"utf-8");return JSON.parse(t)}}catch{}return{}}function vt(e){Sn(),bn($e(),JSON.stringify(e,null,2))}function Ot(){return X().sessionToken||null}function Ie(e){let t=X();t.sessionToken=e,vt(t)}function Ae(){return X().user||null}function Te(e){let t=X();t.user=e,vt(t)}function Pe(){let e=X();delete e.sessionToken,delete e.user,delete e.mem0ProxyUrl,vt(e)}function Ce(){return X().proxyUrl||null}function Ne(e){let t=X();t.proxyUrl=e,vt(t)}function Le(){return X().mem0ProxyUrl||null}function Be(e){let t=X();t.mem0ProxyUrl=e,vt(t)}function Ee(){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 Qt(){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 te,mkdirSync as xn,readFileSync as Re,writeFileSync as Oe,unlinkSync as Fo}from"fs";import{resolve as It}from"path";import{homedir as Do}from"os";var kn=30;function Ue(e){let t=It(e,".zibby","output");return te(t)||xn(t,{recursive:!0}),t}function Fe(e){let t=It(e,".zibby","output","chat-history.json");if(!te(t))return[];try{let n=JSON.parse(Re(t,"utf-8"));return Array.isArray(n)?n:[]}catch{return[]}}function At(e,t){let n=Ue(e),s=It(n,"chat-history.json");try{Oe(s,JSON.stringify((t||[]).slice(-kn*2),null,2),"utf-8")}catch{}}function Me(e){let t=It(e,".zibby","output","active-skills.json");if(!te(t))return null;try{let n=JSON.parse(Re(t,"utf-8"));return Array.isArray(n)?n:null}catch{return null}}function Tt(e,t){let n=Ue(e),s=It(n,"active-skills.json");try{Oe(s,JSON.stringify(Array.isArray(t)?t:[]),"utf-8")}catch{}}var ee={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:{}}},De=2e3,je=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=De){let n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-14)).trimEnd()}
1
+ var Go=Object.defineProperty;var $e=(t,e)=>()=>(t&&(e=t(t=0)),e);var ve=(t,e)=>{for(var o in e)Go(t,o,{get:e[o],enumerable:!0})};var so={};ve(so,{_resetLoaderCacheForTests:()=>mn,loadCredentialsIntoEnv:()=>gn});import oo from"node:fs";import ln from"node:path";import un from"node:os";async function no(){if(!(process.env.__ZIBBY_CLAUDE_PLAN||process.platform!=="darwin"||!(process.env.CLAUDE_CODE_OAUTH_TOKEN||process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL||process.env.ANTHROPIC_AUTH_TOKEN)))try{let{execSync:e}=await import("node:child_process"),o=e('security find-generic-password -s "Claude Code-credentials" -w',{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(o){let r=JSON.parse(o)?.claudeAiOauth?.subscriptionType;r&&(process.env.__ZIBBY_CLAUDE_PLAN=r)}}catch{}}function fn(t){try{if(!oo.existsSync(t))return{};let e=oo.readFileSync(t,"utf-8"),o=JSON.parse(e);return o&&o.agentKeys&&typeof o.agentKeys=="object"?o.agentKeys:{}}catch{return{}}}async function gn(t={}){let{verbose:e=!1,force:o=!1,configPath:n}=t;if(Ze&&!o)return Ae;if(!!(process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL||process.env.ANTHROPIC_API_KEY_POOL||process.env.CLAUDE_CODE_OAUTH_TOKEN||process.env.ANTHROPIC_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN))return await no(),Ze=!0,Ae={oauthCount:0,apiCount:0,source:"cloud-env"},e&&console.log("[credentials-loader] env vars already set \u2014 skipping local discovery"),Ae;let s=n||ln.join(un.homedir(),".zibby","config.json"),a=fn(s),c="none",l=0,p=0;for(let $ of dn)a[$]&&!process.env[$]&&(process.env[$]=String(a[$]).trim(),c="config.json",$.endsWith("_POOL")?l+=String(a[$]).split(",").filter(z=>z.trim()).length:l+=1);for(let $ of pn)a[$]&&!process.env[$]&&(process.env[$]=String(a[$]).trim(),c="config.json",$.endsWith("_POOL")?p+=String(a[$]).split(",").filter(z=>z.trim()).length:p+=1);return await no(),Ze=!0,Ae={oauthCount:l,apiCount:p,source:c},e&&l+p>0&&console.log(`[credentials-loader] loaded ${l} OAuth + ${p} API from ${c} (~/.zibby/config.json)`),Ae}function mn(){Ze=!1,Ae=null}var Ze,Ae,dn,pn,ro=$e(()=>{Ze=!1,Ae=null,dn=["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN_POOL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_AUTH_TOKEN_POOL"],pn=["ANTHROPIC_API_KEY","ANTHROPIC_API_KEY_POOL"]});var pt={};ve(pt,{cleanupStalePidFiles:()=>kn,killAllChatOrchestratedRuns:()=>vn,killPidTreeBestEffort:()=>lo,registerChatOrchestratedRun:()=>_n,unregisterChatOrchestratedRun:()=>Sn});import{existsSync as lt,mkdirSync as hn,readFileSync as yn,readdirSync as bn,unlinkSync as ut,writeFileSync as ao}from"fs";import{join as Ke}from"path";import{execSync as co}from"child_process";import{DEFAULT_OUTPUT_BASE as wn}from"@zibby/core";function We(t){return t?.paths?.output||wn}function Je(t,e,o){return Ke(t,e,`.zibby-chat-run-pids-${o}.json`)}function dt(t,e,o){let n=Je(t,e,o);if(!lt(n))return[];try{let r=JSON.parse(yn(n,"utf8"));return(Array.isArray(r?.pids)?r.pids:[]).map(a=>Number(a)).filter(a=>Number.isFinite(a)&&a>0)}catch{return[]}}function _n(t,e,o,n={}){let r=Number(e),s=Number(o);if(!Number.isFinite(r)||r<=0||!Number.isFinite(s)||s<=0)return;let a=We(n),c=Ke(t,a);hn(c,{recursive:!0});let l=dt(t,a,r);l.includes(s)||l.push(s),ao(Je(t,a,r),`${JSON.stringify({v:1,pids:l})}
2
+ `,"utf8")}function Sn(t,e,o,n={}){let r=Number(e),s=Number(o);if(!Number.isFinite(r)||r<=0||!Number.isFinite(s)||s<=0)return;let a=We(n),c=Je(t,a,r);if(!lt(c))return;let l=dt(t,a,r).filter(p=>p!==s);if(l.length===0)try{ut(c)}catch{}else ao(c,`${JSON.stringify({v:1,pids:l})}
3
+ `,"utf8")}function xn(t){let e=Number(t);if(!Number.isFinite(e)||e<=0)return[];try{let o=co(`pgrep -P ${e}`,{encoding:"utf8",stdio:["ignore","pipe","ignore"],maxBuffer:524288}).trim();return o?o.split(/\n/).map(n=>parseInt(n.trim(),10)).filter(n=>Number.isFinite(n)&&n>0):[]}catch{return[]}}function io(t,e){let o=Number(t);if(!Number.isFinite(o)||o<=0)return;let n=new Set;function r(s){if(!n.has(s)){n.add(s);for(let a of xn(s))r(a);try{process.kill(s,e)}catch{}}}r(o)}function $n(t){let e=Number(t);if(!(!Number.isFinite(e)||e<=0))try{co(`taskkill /PID ${e} /T /F`,{stdio:"ignore",windowsHide:!0})}catch{}}function lo(t){let e=Number(t);if(!Number.isFinite(e)||e<=0)return;if(process.platform==="win32"){$n(e);return}io(e,"SIGTERM");let o=setTimeout(()=>{io(e,"SIGKILL")},800);typeof o.unref=="function"&&o.unref()}function vn(t,e,o={}){let n=Number(e);if(!Number.isFinite(n)||n<=0)return;let r=We(o),s=Je(t,r,n),a=dt(t,r,n);for(let c of a)c!==process.pid&&lo(c);try{lt(s)&&ut(s)}catch{}}function An(t){try{return process.kill(t,0),!0}catch{return!1}}function kn(t,e={}){let o=We(e),n=Ke(t,o),r;try{r=bn(n)}catch{return}for(let s of r){let a=Cn.exec(s);if(!a)continue;let c=Number(a[1]);if(!(!Number.isFinite(c)||c<=0)&&!An(c))try{ut(Ke(n,s))}catch{}}}var Cn,ft=$e(()=>{Cn=/^\.zibby-chat-run-pids-(\d+)\.json$/});var mo={};ve(mo,{DEFAULT_CONFIG_PATH:()=>uo,discoverCredentials:()=>En,maskToken:()=>On,parseConfigJson:()=>fo,readCredentialsConfig:()=>go});import In from"node:fs/promises";import Tn from"node:path";import Pn from"node:os";function fo(t){if(!t)return[];let e;try{e=JSON.parse(t)}catch{return[]}let o=e?.agentKeys;if(!o||typeof o!="object")return[];let n=[],r=new Set;for(let[s,a]of Object.entries(po)){let c=o[s];if(!c||typeof c!="string")continue;let l=s.endsWith("_POOL")?c.split(",").map(p=>p.trim()).filter(Boolean):[c.trim()];for(let p of l)p.length<8||r.has(p)||(r.add(p),n.push({type:a,token:p,source_var:s}))}return n}async function go(t=uo){let e;try{e=await In.readFile(t,"utf8")}catch(o){if(o.code==="ENOENT")return[];throw o}return fo(e)}async function En({filepath:t,env:e=process.env}={}){let o=await go(t),n=new Set(o.map(s=>s.token)),r=[];for(let[s,a]of Object.entries(po)){let c=e[s];if(!c)continue;let l=s.endsWith("_POOL")?c.split(",").map(p=>p.trim()).filter(Boolean):[c];for(let p of l)p.length<8||n.has(p)||(n.add(p),r.push({type:a,token:p,source_var:s,source:"process.env"}))}return{config:o.map(s=>({...s,source:"config.json"})),env:r,all:[...o.map(s=>({...s,source:"config.json"})),...r]}}function On(t){return!t||typeof t!="string"||t.length<=4?"***":`***${t.slice(-4)}`}var uo,po,ho=$e(()=>{uo=Tn.join(Pn.homedir(),".zibby","config.json"),po={CLAUDE_CODE_OAUTH_TOKEN:"oauth",CLAUDE_CODE_OAUTH_TOKEN_POOL:"oauth",ANTHROPIC_AUTH_TOKEN:"oauth",ANTHROPIC_API_KEY:"api",ANTHROPIC_API_KEY_POOL:"api"}});var bo={};ve(bo,{addCredential:()=>yo,deleteCredential:()=>Un,listCredentials:()=>Nn,syncFromLocal:()=>Ln});function gt(t,e=""){return`${String(t).replace(/\/+$/,"")}/agents/credentials${e}`}function mt(){let t=new Error("Session expired \u2014 run zibby login");return t.code="AUTH_EXPIRED",t}async function Nn({apiUrl:t,sessionToken:e}){if(!e)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let o=await fetch(gt(t),{headers:{Authorization:`Bearer ${e}`}});if(o.status===401)throw mt();if(o.status===404)return{credentials:[],by_type:{oauth:[],api:[]},total:0};if(!o.ok){let n=new Error(`List credentials failed (${o.status})`);throw n.status=o.status,n}return o.json()}async function yo({apiUrl:t,sessionToken:e,type:o,token:n,source:r="~/.zibby/config.json"}){if(!e)throw new Error("No session token \u2014 run zibby login first");let s=await fetch(gt(t),{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({type:o,token:n,source:r})});if(s.status===401)throw mt();if(!s.ok){let a=`Add credential failed (${s.status})`;try{let l=await s.json();l?.error&&(a=`${a}: ${l.error}`)}catch{}let c=new Error(a);throw c.status=s.status,c}return s.json()}async function Un({apiUrl:t,sessionToken:e,type:o,index:n}){if(!e)throw new Error("No session token \u2014 run zibby login first");let r=await fetch(gt(t,`/${encodeURIComponent(o)}/${encodeURIComponent(n)}`),{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(r.status===401)throw mt();if(!r.ok){let s=new Error(`Delete credential failed (${r.status})`);throw s.status=r.status,s}return r.json()}async function Ln({apiUrl:t,sessionToken:e,credentials:o}){let n=0,r=0,s=[];for(let a of o)try{let c=await yo({apiUrl:t,sessionToken:e,type:a.type,token:a.token,source:a.source_var||a.source||"local"});c.deduped?r+=1:c.added&&(n+=1)}catch(c){s.push({masked:a.token?`***${a.token.slice(-4)}`:"***",error:c.message})}return{added:n,deduped:r,errors:s}}var wo=$e(()=>{});var vo={};ve(vo,{AGENTS:()=>Le,deleteAgentSession:()=>Yn,fetchMyAgentSessions:()=>xo,formatRelativeTime:()=>$o,handleClaudeCodeAddon:()=>Dn,pickAgent:()=>Bn,pickAgentWithSessions:()=>Rn,upsertAgentSession:()=>Fn});import{select as So,confirm as ht,Separator as _o}from"@inquirer/prompts";import u from"chalk";async function Rn({apiUrl:t,sessionToken:e,currentAgentId:o="zibby"}={}){let n;try{n=await xo({apiUrl:t,sessionToken:e})}catch(s){if(/login/i.test(s.message))throw s;console.warn(u.gray(` (could not fetch sessions: ${s.message})`)),n=[]}let r=[];if(n.length>0){for(let s of n){let c=Le.find(z=>z.id===s.agent_type)?.name||s.agent_type,l=$o(s.last_active),p=typeof s.message_count=="number"&&s.message_count>0?u.gray(` \xB7 ${s.message_count} msg`):"",$=s.label?u.gray(` \xB7 "${s.label}"`):"";r.push({name:`${u.cyan("\u2726")} ${c} ${u.gray(`(${l})`)}${$}${p}`,value:{action:"resume",agentType:s.agent_type,sessionId:s.session_id,session:s},description:u.gray(` Resume your ${c} session`)})}r.push(new _o)}for(let s of Le)s.id!=="zibby"&&r.push({name:`${u.dim("+")} New ${s.name} session${s.pricePerMonth>0?u.yellow(` (+$${s.pricePerMonth}/mo)`):""}`,value:{action:"create",agentType:s.id},description:u.gray(` ${s.description}`)});r.push(new _o),r.push({name:`${u.green("\u2190")} Back to Zibby Chat (default)${o==="zibby"?u.dim(" [current]"):""}`,value:{action:"switch",agentType:"zibby"},description:u.gray(" Built-in chat using Anthropic SDK directly")});try{return await So({message:"Select chat agent:",choices:r})}catch(s){if(s?.name==="ExitPromptError")return{action:"cancel"};throw s}}async function Bn(t="zibby"){let e=await So({message:"Select chat agent for this workspace:",default:t,choices:Le.map(o=>{let n=o.pricePerMonth===0?u.green(" (included)"):u.yellow(` (+$${o.pricePerMonth}/mo)`),r=o.id===t?u.dim(" [current]"):"";return{name:`${o.name}${n}${r}`,value:o.id,description:u.gray(` ${o.description}`)}})});return Le.find(o=>o.id===e)}async function Dn({workspaceId:t,sessionToken:e,apiUrl:o}){let n=await jn({addon:"claude-code",workspaceId:t,sessionToken:e,apiUrl:o});if(n.configured&&n.sandboxState==="ready")return console.log(""),console.log(u.green(" \u2713 Claude Code is already deployed for your team.")),console.log(u.gray(` Sandbox: ${n.sandboxId} \xB7 state: ${n.sandboxState}`)),console.log(""),{ready:!0,sandboxId:n.sandboxId};if(n.configured&&n.sandboxState!=="ready")return console.log(""),console.log(u.cyan(` \u2699 Claude Code sandbox is ${n.sandboxState}...`)),console.log(u.gray(" You can keep using Zibby Chat \u2014 we'll switch when it's ready.")),console.log(""),{ready:!1,provisioning:!0,sandboxId:n.sandboxId};if(console.log(""),console.log(u.yellow(" Claude Code add-on is not enabled for your workspace.")),console.log(""),console.log(u.white(" About this add-on:")),console.log(u.gray(" \u2022 Anthropic's official Claude Code CLI runs in YOUR isolated sandbox")),console.log(u.gray(" \u2022 YOU provide your own Anthropic credentials (in ~/.zibby/config.json)")),console.log(u.gray(" \u2022 Zibby NEVER accesses Anthropic on your behalf \u2014 your tokens, your API calls")),console.log(u.gray(" \u2022 Zibby stores credentials KMS-encrypted, decrypts only inside YOUR sandbox")),console.log(u.gray(" \u2022 You're responsible for ToS compliance with the credentials you provide:")),console.log(u.gray(" https://www.anthropic.com/legal/commercial-terms")),console.log(""),console.log(u.cyan(" Pricing:")),console.log(u.white(" $20 / month per workspace ")+u.gray("\xB7 Zibby infrastructure fee, billed via Stripe")),console.log(u.gray(" Your Anthropic usage bills directly to your Anthropic account")),console.log(""),!await ht({message:"Do you agree to Anthropic's Commercial Terms of Service?",default:!1}))return console.log(u.gray(" Cancelled. Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0};if(!await ht({message:"Enable Claude Code add-on at $20/month?",default:!1}))return console.log(u.gray(" Cancelled. Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0};console.log(""),console.log(u.cyan(" Enabling Claude Code add-on..."));let a;try{a=await zn({addon:"claude-code",workspaceId:t,sessionToken:e,apiUrl:o,accept:{tos:!0,billing:!0}})}catch(c){if(c?.code==="BILLING_REQUIRED"){console.log("");let l=c.upgradeUrl?.startsWith("http")?c.upgradeUrl:"https://zibby.dev/billing";return c.needsSubscription?(console.log(u.yellow(" \u26A0 You need an active Pro subscription to enable Claude Code.")),console.log(u.gray(` Upgrade here: ${l}`))):c.needsPaymentMethod?(console.log(u.yellow(" \u26A0 Your card was declined or no payment method is on file.")),console.log(u.gray(` Update billing: ${l}`))):(console.log(u.yellow(` \u26A0 ${c.message}`)),console.log(u.gray(` Manage billing: ${l}`))),console.log(""),console.log(u.gray(" Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0,billingRequired:!0}}throw c}return console.log(""),console.log(u.green(" \u2713 Stripe subscription created")),console.log(u.gray(` sub_id: ${a.subscriptionId}`)),console.log(u.green(" \u2713 Lambda invoked: zibby-prod-provision-sandbox")),console.log(u.gray(` request: ${a.requestId}`)),console.log(u.cyan(" \u2699 Fargate task launching: zibby/agent-runtime:claude-code-v1")),console.log(u.gray(` sandbox_id: ${a.sandboxId}`)),console.log(""),await Mn({apiUrl:o,sessionToken:e}),console.log(""),console.log(u.gray(" Sandbox provisioning in the background. Zibby Chat (default) is active until ready.")),console.log(""),{ready:!1,provisioning:!0,sandboxId:a.sandboxId,deploymentId:a.requestId}}async function Mn({apiUrl:t,sessionToken:e}){let o;try{let{discoverCredentials:s}=await Promise.resolve().then(()=>(ho(),mo));o=await s()}catch(s){console.log(u.gray(` (could not scan local credentials: ${s.message})`));return}let n=o.all.length;if(n===0){console.log(u.yellow(" \u26A0 No Anthropic credentials found locally.")),console.log(""),console.log(u.white(" Two ways to authenticate Claude Code in your sandbox:")),console.log(""),console.log(u.bold(" Option A \u2014 provide your own (recommended):")),console.log(u.gray(" 1. Run: zibby init")),console.log(u.gray(" Pick Claude \u2192 Subscription (OAuth) or API key")),console.log(u.gray(" 2. Run: zibby creds sync (uploads to your workspace)")),console.log(u.gray(" 3. Re-run /agents in chat")),console.log(""),console.log(u.bold(" Option B \u2014 in-sandbox login (legacy):")),console.log(u.gray(" Skip this step. When sandbox is ready and you start")),console.log(u.gray(" Claude Code, it will prompt you to open a URL in your")),console.log(u.gray(" laptop browser to authenticate.")),console.log("");return}console.log(u.green(` \u2713 Found ${n} Anthropic ${n===1?"credential":"credentials"} in your local environment:`));for(let s of o.all){let a=s.source==="config.json"?`~/.zibby/config.json (${s.source_var})`:`process.env.${s.source_var}`;console.log(u.gray(` ${s.type} ***${s.token.slice(-4)} ${a}`))}if(console.log(""),console.log(u.white(" By proceeding you confirm:")),console.log(u.gray(" \u2022 These are YOUR credentials to use")),console.log(u.gray(" \u2022 You comply with Anthropic's ToS for the tier of these tokens")),console.log(u.gray(" \u2022 Zibby will store encrypted (AWS KMS) and inject into YOUR sandbox only")),console.log(""),!await ht({message:"Upload these credentials to your Zibby workspace?",default:!0})){console.log(u.gray(" Skipped credential upload. Sandbox will fall back to in-sandbox login."));return}console.log(""),console.log(u.cyan(" Uploading (KMS-encrypted)..."));try{let{syncFromLocal:s}=await Promise.resolve().then(()=>(wo(),bo)),a=await s({apiUrl:t,sessionToken:e,credentials:o.all});console.log(u.green(` \u2713 ${a.added} new, ${a.deduped} already stored`)),a.errors.length>0&&console.log(u.yellow(` ${a.errors.length} failed \u2014 retry with 'zibby creds sync'`))}catch(s){console.log(u.red(` \u2717 Upload failed: ${s.message}`)),console.log(u.gray(" Sandbox will fall back to in-sandbox login when ready."))}}async function jn({addon:t,sessionToken:e,apiUrl:o}){let n=process.env.ZIBBY_CLAUDE_CODE_STUB_STATUS;if(n==="ready")return{configured:!0,sandboxState:"ready",sandboxId:"sb_stub_acme_001"};if(n==="provisioning")return{configured:!0,sandboxState:"provisioning",sandboxId:"sb_stub_acme_001"};if(!o||!e)return{configured:!1,sandboxState:null,sandboxId:null};let r=`${String(o).replace(/\/+$/,"")}/agents/addons/${encodeURIComponent(t)}`,s;try{s=await fetch(r,{headers:{Authorization:`Bearer ${e}`}})}catch{return{configured:!1,sandboxState:null,sandboxId:null}}if(s.status===401){let c=new Error("Session expired \u2014 run zibby login");throw c.code="AUTH_EXPIRED",c}if(s.status===404)return{configured:!1,sandboxState:null,sandboxId:null};if(!s.ok)return{configured:!1,sandboxState:null,sandboxId:null};let a=await s.json();return{configured:!!a.configured,sandboxState:a.sandbox_state||null,sandboxId:a.sandbox_id||null,subscriptionId:a.subscription_id||null,enabledAt:a.enabled_at||null}}async function zn({addon:t,workspaceId:e,sessionToken:o,apiUrl:n}){if(!n||!o)return await new Promise(c=>setTimeout(c,500)),{subscriptionId:`sub_${Math.random().toString(36).slice(2,10)}`,sandboxId:`sb_${Math.random().toString(36).slice(2,10)}`,requestId:`req_offline_${Date.now().toString(36)}`};let r=`${String(n).replace(/\/+$/,"")}/agents/addons/${encodeURIComponent(t)}/enable`,s=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({workspace_id:e||null})});if(s.status===401){let c=new Error("Session expired \u2014 run zibby login");throw c.code="AUTH_EXPIRED",c}if(s.status===402){let c;try{c=await s.json()}catch{c={}}let l;try{l=typeof c.error=="string"?JSON.parse(c.error):c.error||c}catch{l={message:c.error||"Payment required"}}let p=new Error(l.message||"Payment required");throw p.code="BILLING_REQUIRED",p.status=402,p.needsSubscription=!!l.needs_subscription,p.needsPaymentMethod=!!l.needs_payment_method,p.upgradeUrl=l.upgrade_url||"/billing",p}if(!s.ok){let c=new Error(`Enable addon failed (${s.status})`);throw c.status=s.status,c}let a=await s.json();return{subscriptionId:a.subscription_id||null,sandboxId:a.sandbox_id||null,stripeSubscriptionItemId:a.stripe_subscription_item_id||null,requestId:a.request_id||`req_${Date.now().toString(36)}`}}function yt(t,e){let o=String(t).replace(/\/+$/,"");return e?`${o}/agents/sessions/${encodeURIComponent(e)}`:`${o}/agents/sessions`}async function xo({apiUrl:t,sessionToken:e}){if(!e)return[];let o=await fetch(yt(t),{headers:{Authorization:`Bearer ${e}`}});if(o.status===401)throw new Error("Not authenticated. Run `zibby login` again.");if(o.status===404)return[];if(!o.ok){let r=await o.text().catch(()=>"");throw new Error(`Failed to list agent sessions (${o.status}): ${r.slice(0,200)}`)}let n=await o.json();return Array.isArray(n.sessions)?n.sessions:[]}async function Fn({apiUrl:t,sessionToken:e,agentType:o,fields:n={}}){if(!e)throw new Error("Not authenticated");let r=await fetch(yt(t,o),{method:"PUT",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let a=await r.text().catch(()=>"");throw new Error(`Failed to save agent session (${r.status}): ${a.slice(0,200)}`)}return(await r.json()).session}async function Yn({apiUrl:t,sessionToken:e,agentType:o}){if(!e)throw new Error("Not authenticated");let n=await fetch(yt(t,o),{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Failed to delete agent session (${n.status}): ${s.slice(0,200)}`)}return(await n.json()).deleted===!0}function $o(t){if(!t)return"never";let e=new Date(t).getTime();if(Number.isNaN(e))return"unknown";let o=Math.max(0,(Date.now()-e)/1e3);if(o<60)return"just now";let n=o/60;if(n<60)return`${Math.round(n)}m ago`;let r=n/60;if(r<24)return`${Math.round(r)}h ago`;let s=r/24;if(s<30)return`${Math.round(s)}d ago`;let a=s/30;return`${Math.round(a)}mo ago`}var Le,Ao=$e(()=>{Le=[{id:"zibby",name:"Zibby Chat",short:"default",description:"Built-in chat using Anthropic SDK directly \xB7 BYOK \xB7 included with workspace",pricePerMonth:0,deployment:"instant"},{id:"claude-code",name:"Claude Code",short:"add-on",description:"Anthropic's Claude Code CLI deployed in your private sandbox",pricePerMonth:20,deployment:"fargate-warm"}]});var bt={};ve(bt,{attachToSession:()=>To,spawnAgentSession:()=>Io,spawnAndAttach:()=>Zn});import Co from"ws";import ko from"chalk";function Hn({sandboxEndpoint:t,sessionId:e,useTls:o=!1}){return`${o?"wss":"ws"}://${t}/stream/${encodeURIComponent(e)}`}async function Io({sandboxEndpoint:t,sessionToken:e,agentType:o="claude-code",args:n=[],cwd:r="/workspace",useTls:s=!1}){let c=`${s?"https":"http"}://${t}/spawn`,l=await fetch(c,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({agent_type:o,args:n,cwd:r})});if(!l.ok){let $=await l.text().catch(()=>"");throw new Error(`spawn failed (${l.status}): ${$}`)}return await l.json()}async function To({sandboxEndpoint:t,sessionId:e,sessionToken:o,useTls:n=!1,showBanner:r=!0}){let s=Hn({sandboxEndpoint:t,sessionId:e,useTls:n}),a=new Co(s,{headers:{Authorization:`Bearer ${o}`}});return new Promise((c,l)=>{let p=!1,$=!1,z=null,Y=null,W=A=>{if(!p){p=!0;try{process.stdin.isTTY&&process.stdin.setRawMode&&process.stdin.setRawMode($)}catch{}z&&process.stdin.off("data",z),Y&&process.stdout.off("resize",Y);try{process.stdin.pause()}catch{}try{a.close()}catch{}c(A)}};a.on("open",()=>{r&&(process.stdout.write(ko.green(`
4
+ \u2713 Connected to cloud sandbox session ${e}
5
+ `)),process.stdout.write(ko.gray(` Press Ctrl+\\ to detach (session keeps running).
4
6
 
5
- [truncated]`}function pt(e,t=[],n=De){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=ee[n]||ee.cli_reliable_v1,c=vn(s),l=c?$n(r,c):r;return{name:n,defaults:l}}function Ye({activeSkills:e=[],chatConfig:t={},options:n={}}={}){let s=An(t,n);if(s.text)return s.text;let r=s.defaults||ee.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
+ `)));let A=()=>{let R=process.stdout.columns||80,B=process.stdout.rows||24;try{a.send(JSON.stringify({type:"resize",cols:R,rows:B}))}catch{}};A(),Y=()=>A(),process.stdout.on("resize",Y),process.stdin.isTTY&&process.stdin.setRawMode&&($=!!process.stdin.isRaw,process.stdin.setRawMode(!0)),process.stdin.resume();try{process.stdin.setEncoding("utf8")}catch{}z=R=>{let B=R.toString("utf8");if(B.includes("")){W({reason:"detach"});return}try{a.send(B)}catch{}},process.stdin.on("data",z)}),a.on("message",A=>{let R=A.toString("utf8");if(R.startsWith("{")&&R.endsWith("}"))try{let B=JSON.parse(R);if(B&&B.type==="exit"){W({reason:"remote-exit",exitCode:B.exitCode,signal:B.signal});return}}catch{}try{process.stdout.write(R)}catch{}}),a.on("close",()=>{W({reason:"remote-close"})}),a.on("error",A=>{p||W({reason:"ws-error",message:A?.message||String(A)})}),setTimeout(()=>{if(a.readyState===Co.CONNECTING){try{a.terminate()}catch{}p||(p=!0,l(new Error("WS connect timed out after 30s")))}},3e4).unref()})}async function Zn({sandboxEndpoint:t,sessionToken:e,agentType:o,args:n,cwd:r,useTls:s}){let a=await Io({sandboxEndpoint:t,sessionToken:e,agentType:o,args:n,cwd:r,useTls:s});return{...await To({sandboxEndpoint:t,sessionId:a.session_id,sessionToken:e,useTls:s}),sessionId:a.session_id}}var wt=$e(()=>{});import{invokeAgent as Kn,getAgentStrategy as Wn}from"@zibby/core";import{getSkill as Re}from"@zibby/skills";import{existsSync as Ce,readFileSync as Ro,readdirSync as Jn}from"fs";import{resolve as me,join as St,dirname as Gn,basename as qn}from"path";import{createInterface as Vn,moveCursor as j,cursorTo as K,clearLine as Q,emitKeypressEvents as Xn}from"readline";import{fileURLToPath as Qn}from"url";import{homedir as es}from"os";import i from"chalk";import{highlight as Po}from"cli-highlight";import ts from"dotenv";import{existsSync as Lt,mkdirSync as qo,readFileSync as Vo,writeFileSync as Xo}from"fs";import{homedir as Rt}from"os";import{join as Fe}from"path";function Bt(){return process.env.ZIBBY_CONFIG_DIR||Fe(Rt(),".zibby")}function Dt(){return Fe(Bt(),"config.json")}var Qo=Fe(Rt(),".zibby"),Ms=Fe(Qo,"config.json");function en(){let t=Bt();Lt(t)||qo(t,{recursive:!0})}function se(){try{let t=Dt();if(Lt(t)){let e=Vo(t,"utf-8");return JSON.parse(e)}}catch{}return{}}function Pe(t){en(),Xo(Dt(),JSON.stringify(t,null,2))}function Ye(){return se().sessionToken||null}function Mt(t){let e=se();e.sessionToken=t,Pe(e)}function jt(){return se().user||null}function zt(t){let e=se();e.user=t,Pe(e)}function Ft(){let t=se();delete t.sessionToken,delete t.user,delete t.mem0ProxyUrl,Pe(t)}function Yt(){return se().proxyUrl||null}function Ht(t){let e=se();e.proxyUrl=t,Pe(e)}function Zt(){return se().mem0ProxyUrl||null}function Kt(t){let e=se();e.mem0ProxyUrl=t,Pe(e)}function Wt(){return se().projects||[]}var Ee={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.dev",description:"Production environment"}};function le(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";Ee[e]?t=Ee[e].apiUrl:t=Ee.prod.apiUrl}try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),Ee.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),Ee.prod.apiUrl}}import{existsSync as at,mkdirSync as tn,readFileSync as Jt,writeFileSync as Gt,unlinkSync as Ys}from"fs";import{resolve as Oe}from"path";import{homedir as Ks}from"os";var on=30;function qt(t){let e=Oe(t,".zibby","output");return at(e)||tn(e,{recursive:!0}),e}function Vt(t){let e=Oe(t,".zibby","output","chat-history.json");if(!at(e))return[];try{let o=JSON.parse(Jt(e,"utf-8"));return Array.isArray(o)?o:[]}catch{return[]}}function Ne(t,e){let o=qt(t),n=Oe(o,"chat-history.json");try{Gt(n,JSON.stringify((e||[]).slice(-on*2),null,2),"utf-8")}catch{}}function Xt(t){let e=Oe(t,".zibby","output","active-skills.json");if(!at(e))return null;try{let o=JSON.parse(Jt(e,"utf-8"));return Array.isArray(o)?o:null}catch{return null}}function Ue(t,e){let o=qt(t),n=Oe(o,"active-skills.json");try{Gt(n,JSON.stringify(Array.isArray(e)?e:[]),"utf-8")}catch{}}var ct={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:{}}},eo=2e3,Qt=12e3;function He(t=[]){if(!Array.isArray(t))return[];let e=new Set,o=[];for(let n of t){let r=String(n||"").replace(/\s+/g," ").trim();r&&(e.has(r)||(e.add(r),o.push(r)))}return o}function nn(t,e=eo){let o=String(t||"");return o.length<=e?o:`${o.slice(0,Math.max(0,e-14)).trimEnd()}
7
8
 
8
- `).trim();return y.length<=je?y:`${y.slice(0,Math.max(0,je-14)).trimEnd()}
9
+ [truncated]`}function ge(t,e=[],o=eo){let n=He(e);if(n.length===0)return"";let r=[`## ${t}`,...n.map(s=>`- ${s}`)].join(`
10
+ `);return nn(r,o)}function sn(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function rn(t,e){let o={...t,...e},n=["operatingRules","rules","executionSafety","investigationLoop","responseQuality","incidentTemplate"];for(let r of n)Array.isArray(e?.[r])?o[r]=[...He(t?.[r]||[]),...He(e[r])]:Array.isArray(t?.[r])&&(o[r]=[...He(t[r])]);return o.skillRunbooks={...t?.skillRunbooks||{},...e?.skillRunbooks||{}},o}function an(t={},e={}){let o=Array.isArray(t?.reliabilityAppendSections)?t.reliabilityAppendSections:[],n=Array.isArray(e?.reliabilityAppendSections)?e.reliabilityAppendSections:[];return[...o,...n].map(r=>{if(typeof r=="string")return{title:"Additional reliability guidance",lines:[r]};if(!r||typeof r!="object")return null;let s=String(r.title||"Additional reliability guidance").trim(),a=Array.isArray(r.lines)?r.lines:[];return{title:s,lines:a}}).filter(Boolean)}function cn(t={},e={}){let o=String(e.reliabilityProfile||process.env.ZIBBY_RELIABILITY_PROFILE||t.reliabilityProfile||"cli_reliable_v1").trim(),n=t?.reliabilityProfiles?.[o];if(typeof n=="string"&&n.trim())return{name:o,text:n.trim()};if(n&&typeof n.instruction=="string"&&n.instruction.trim())return{name:o,text:n.instruction.trim()};let r=ct[o]||ct.cli_reliable_v1,s=sn(n),a=s?rn(r,s):r;return{name:o,defaults:a}}function to({activeSkills:t=[],chatConfig:e={},options:o={}}={}){let n=cn(e,o);if(n.text)return n.text;let r=n.defaults||ct.cli_reliable_v1,s=[ge(r.title||"Reliability contract",r.operatingRules||r.rules||[]),ge("Execution safety",r.executionSafety||[]),ge("Investigation loop",r.investigationLoop||[]),ge("Response quality",r.responseQuality||[]),ge("Failure reporting format",r.incidentTemplate||[])],a=r.skillRunbooks||{};for(let p of t)a[p]&&s.push(ge(`Runbook: ${p}`,a[p]));let c=an(e,o);for(let p of c)s.push(ge(p.title,p.lines));let l=s.filter(Boolean).join(`
9
11
 
10
- [truncated]`}var qn=Jn(import.meta.url),Kn=zn(qn),Xn=JSON.parse(Qe(le(Kn,"../../package.json"),"utf-8")),tn=30,Qn=54,to=18e3,en=12e3,Ge=42e3;function eo(e){return new Promise(t=>setTimeout(t,e))}var Dt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],ue=[{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 Ve(){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 ls(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(-tn).map(t=>`${t.role==="human"?"H":"AI"}: ${t.content}`).join(`
11
- `)}function as(e,t,n){let s=e;return t.length>0&&(s+=`
12
+ `).trim();return l.length<=Qt?l:`${l.slice(0,Math.max(0,Qt-14)).trimEnd()}
12
13
 
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 qe(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(le(y,F)));if(!L)return n;try{let F=Qe(le(y,L),"utf-8").trim();return c?`${F}
14
+ [truncated]`}var os=Qn(import.meta.url),ns=Gn(os),ss=JSON.parse(Ro(St(ns,"../../package.json"),"utf-8")),Bo=30,rs=54,is=18e3,Do=12e3,Eo=42e3;function as(t){return new Promise(e=>setTimeout(e,t))}var Ge=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],$t=[{cmd:"/help",desc:"Show this help"},{cmd:"/agents",desc:"Choose chat agent (Zibby default or Claude Code add-on)"},{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 Oo(){let t=0,e="thinking...",o=setInterval(()=>{let r=i.cyan(Ge[t%Ge.length]),s=t%3,a=s===0?i.white(".")+i.gray(".")+i.dim("."):s===1?i.dim(".")+i.white(".")+i.gray("."):i.gray(".")+i.dim(".")+i.white("."),c=e.replace(/\.+$/,""),l=` ${r} ${i.gray(c)}${a}`;process.stdout.write(`\r${" ".repeat(80)}\r${l}`),t++},300),n=()=>{clearInterval(o),process.stdout.write(`\r${" ".repeat(80)}\r`)};return n.setLabel=r=>{e=r},n}function $r(t){let e=t?.agent;return e?e.provider?e.provider:e.gemini?"gemini":e.codex?"codex":e.claude?"claude":e.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}function cs(t){return t.slice(-Bo).map(e=>`${e.role==="human"?"H":"AI"}: ${e.content}`).join(`
15
+ `)}function vr(t,e,o){let n=t;return e.length>0&&(n+=`
16
16
 
17
- ${c}`:F}catch{return n}}function co(e){let t=e.slice(-tn),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))}
17
+ ${cs(e)}`),n+=`
18
+ H: ${o}
19
+ AI:`,n}function ls(t){let e=t.filter(o=>!process.env[o]);return{ok:e.length===0,missing:e}}function us(t){let e=me(t,".zibby.config.mjs");if(!Ce(e))return{};try{return import(e).then(o=>o.default||{})}catch{return{}}}async function ds(t){let e=me(t,".zibby","chat.mjs");if(Ce(e)){let r=await import(e);if(r.CHAT_CONFIG||r.default)return r.CHAT_CONFIG||r.default}let o=me(es(),".zibby","chat.mjs");if(o!==e&&Ce(o)){let r=await import(o);if(r.CHAT_CONFIG||r.default)return r.CHAT_CONFIG||r.default}let n=await import("@zibby/core/templates/browser-test-automation/chat.mjs");return n.CHAT_CONFIG||n.default||{}}function No(t){try{let e=me(t,".zibby","commands");return Ce(e)?Jn(e).filter(o=>o.toLowerCase().endsWith(".md")).sort((o,n)=>o.localeCompare(n)):[]}catch{return[]}}function ps(t,e){let o=String(e||"").trim();if(!o.startsWith("/"))return o;let[n,...r]=o.split(/\s+/),s=r.join(" ").trim(),a=n.slice(1);if(!a)return o;let c=a.toLowerCase().endsWith(".md")?[a]:[a,`${a}.md`],l=me(t,".zibby","commands"),p=c.find($=>Ce(St(l,$)));if(!p)return o;try{let $=Ro(St(l,p),"utf-8").trim();return s?`${$}
18
20
 
19
- [truncated for proxy size]`}function ae(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,en)}),ae(t)<=Ge))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],ae(t)<=Ge||(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)
20
- ${t.join(`
21
- `)}`}var Ke={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():Ke[n]||Ke.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?Je(c,{language:s,ignoreIllegals:!0}):Je(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 ce(){let e=Number(process.stdout?.columns)||0,t=e>8?Math.max(30,e-4):Qn;return` ${"\u2500".repeat(t)}`}function Xe(e=[]){let t=ue.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(ce())}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=ce().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=ce().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 ue)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 us(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()){Pe();let u=Qt(),{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=Ve();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"){Ie(Z.token),Te(Z.user),Z.proxyUrl&&Ne(Z.proxyUrl),Z.mem0ProxyUrl&&Be(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=Le()||Ce();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(()=>(ie(),re));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=Ae(),ct=Ee()?.[0]?.name,N=Fe(t),Q=l.skills||[],W=Me(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=Qt(),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),zt=Pt(O);tt&&z===-1&&zt?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=qe(t),k=Xe(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=[],zt=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 pe(){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,ge(),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,`
21
+ ${s}`:$}catch{return o}}function fs(t){let e=t.slice(-Bo),o=[],n=0;for(let r=e.length-1;r>=0;r--){let s=e[r],a=String(s?.content||""),c=s?.role==="human"?"user":"assistant",l=a.length;if(o.length>=6&&n+l>is)break;o.push({role:c,content:a}),n+=l}return o.reverse()}function Be(t,e){let o=String(t||"");return o.length<=e?o:`${o.slice(0,Math.max(0,e-24))}
22
+
23
+ [truncated for proxy size]`}function xt(t){return t.reduce((e,o)=>e+String(o?.content||"").length+64,0)}function gs(t){let e=[...t];if(e.length===0||(e[0]?.role==="system"&&(e[0]={...e[0],content:Be(e[0].content,Do)}),xt(e)<=Eo))return e;let o=e[0],n=e[e.length-1],r=e.slice(1,-1).slice(-4).map(s=>({...s,content:Be(s.content,2500)}));return e=[o,...r,n],xt(e)<=Eo||(e=[{...o,content:Be(o?.content,6e3)},{...n,content:Be(n?.content,8e3)}]),e}function ms(t){let e=[];for(let o of t){let n=Re(o),r=String(n?.description||"").trim();if(!r){e.push(`- ${o}`);continue}e.push(`- ${o}: ${qe(r,80)}`)}return e.length===0?"":`## Active skills (call get_skill_context before first use)
24
+ ${e.join(`
25
+ `)}`}var Uo={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(`
26
+ `)};function hs(t={},e={}){let o=String(e.outputProfile||process.env.ZIBBY_OUTPUT_PROFILE||t.outputProfile||"cli_plain").trim(),n=t?.outputProfiles?.[o];return typeof n=="string"&&n.trim()?n.trim():n&&typeof n.instruction=="string"&&n.instruction.trim()?n.instruction.trim():Uo[o]||Uo.cli_plain}function qe(t,e){let o=String(t??"");return o.length<=e?o:e<=1?o.slice(0,e):`${o.slice(0,e-1)}\u2026`}function ys(){return!1}function bs(t){let e=/^```(\w*)\n([\s\S]*?)^```$/gm;return t.replace(e,(o,n,r)=>{let s=r.replace(/\n$/,"");try{let a=n?Po(s,{language:n,ignoreIllegals:!0}):Po(s,{ignoreIllegals:!0}),c=i.gray("\u2500".repeat(Math.min(process.stdout.columns-6||54,72))),l=n?i.dim(` ${n}`):"";return`${c}${l}
27
+ ${a}
28
+ ${c}`}catch{return s}})}function _t(){let t=Number(process.stdout?.columns)||0,e=t>8?Math.max(30,t-4):rs;return` ${"\u2500".repeat(e)}`}function Lo(t=[]){let e=$t.map(n=>({cmd:n.cmd,source:"builtin",name:n.cmd.slice(1),desc:n.desc})),o=t.map(n=>({cmd:`/${n}`,source:"template",name:n,desc:"Command template"}));return[...e,...o]}function ws(t,e){let o=String(t||""),n=Number.isFinite(e)?e:o.length;return!(!o.startsWith("/")||n!==o.length||o.includes(" "))}function _s({userName:t,cwd:e,projectName:o,restoredCount:n,skillsLine:r}){let s=Number(process.stdout?.columns)||0,a=Math.max(40,Math.min(s-8,100)),c=Math.max(20,Math.floor((a-3)*.55)),l=a-c-3,p=t||"there",$=o||"No project linked",z=qn(e||process.cwd()),Y=[`Restored ${n} messages from previous session.`,"",r],W=["Workspace details","",`v${ss.version} | Hi, ${p}`,`Company: ${$}`,`Directory: ~/${z}`,`Path: ${e}`,"","Use /help for commands"],A=Math.max(Y.length,W.length),R=(()=>{if(Y.length>=A)return Y;let H=Math.floor((A-Y.length)/2),ue=A-Y.length-H;return[...Array(H).fill(""),...Y,...Array(ue).fill("")]})(),B="\u2500",he=` \u250C${B.repeat(c+2)}\u252C${B.repeat(l+2)}\u2510`,L=` \u2514${B.repeat(c+2)}\u2534${B.repeat(l+2)}\u2518`;console.log(i.gray(he));for(let H=0;H<A;H++){let ue=qe(R[H]||"",c),ye=qe(W[H]||"",l),be=" ".repeat(Math.max(0,c-ue.length)),_=" ".repeat(Math.max(0,l-ye.length)),k=` \u2502 ${ue}${be} \u2502 ${ye}${_} \u2502`;console.log(i.gray(k))}console.log(i.gray(L)),console.log("")}function Ss(){process.stdout?.isTTY&&(j(process.stdout,0,-2),K(process.stdout,4))}function xs(t){let e=!!(process.stdout?.isTTY&&process.stdin?.isTTY),o=!1,n=!1,r=!1,s=null,a=0,c=0,l=0;function p(){return i.gray(_t())}function $(){s&&(clearInterval(s),s=null)}function z(_){!e||!o||!n||!r||(process.stdout.write("\x1B7"),j(process.stdout,0,-2),K(process.stdout,0),Q(process.stdout,0),process.stdout.write(` ${_}`),process.stdout.write("\x1B8"))}function Y(){if(!(!e||!o)&&c!==0){process.stdout.write("\x1B7"),j(process.stdout,0,2);for(let _=0;_<c;_++)K(process.stdout,0),Q(process.stdout,0),_<c-1&&j(process.stdout,0,1);process.stdout.write("\x1B8"),c=0,n&&W()}}function W(){!e||!o||!n||(process.stdout.write("\x1B7"),j(process.stdout,0,1),K(process.stdout,0),Q(process.stdout,0),process.stdout.write(p()),process.stdout.write("\x1B8"))}function A(_,k){if(!e||!o||!n)return;Y();let I=_.slice(0,6);if(I.length!==0){j(process.stdout,0,1);for(let b=0;b<I.length;b++)process.stdout.write(`
29
+ `);j(process.stdout,0,-(1+I.length)),process.stdout.write("\x1B7"),j(process.stdout,0,2);for(let b=0;b<I.length;b++){K(process.stdout,0),Q(process.stdout,0);let ee=b===k?i.cyan("\u203A"):" ",te=b===k?i.white(I[b]):i.gray(I[b]);process.stdout.write(` ${ee} /${te}`),b<I.length-1&&j(process.stdout,0,1)}process.stdout.write("\x1B8"),c=I.length,W()}}function R(){if(!e||!o||!n)return;Y();let _=process.stdout.columns||80,k=l>0?Math.ceil(l/_):1;K(process.stdout,0),j(process.stdout,0,-k),r&&j(process.stdout,0,-2),process.stdout.write("\x1B[J"),n=!1}function B(_={}){let k=_.preserveInput===!0;if(!e){t.prompt();return}k||(t.line="",t.cursor=0),l=_t().length;let I=p();process.stdout.write(`${I}
30
+ `),t.prompt(),process.stdout.write(`
31
+ ${I}
32
+ `),Ss(),n=!0}function he(){if(!e||!o||!n)return;let _=process.stdout.columns||80,k=l>0?Math.ceil(l/_):1,I=p();process.stdout.write("\x1B7"),j(process.stdout,0,-k);for(let b=0;b<k;b++)K(process.stdout,0),Q(process.stdout,0),b<k-1&&j(process.stdout,0,1);K(process.stdout,0),process.stdout.write(I),j(process.stdout,0,2),K(process.stdout,0),Q(process.stdout,0),process.stdout.write(I);for(let b=1;b<k;b++)j(process.stdout,0,1),K(process.stdout,0),Q(process.stdout,0);process.stdout.write("\x1B8"),l=_t().length}function L(){if(!e||!o||!n)return;let _=(()=>{if(typeof t.getCursorPos!="function")return 0;try{return Math.max(0,Number(t.getCursorPos()?.rows||0))}catch{return 0}})();process.stdout.write("\x1B7"),j(process.stdout,0,-(_+1)),K(process.stdout,0),Q(process.stdout,0),process.stdout.write(p()),j(process.stdout,0,_+2),K(process.stdout,0),Q(process.stdout,0),process.stdout.write(p()),process.stdout.write("\x1B8")}function H(_){$(),R(),console.log();let k=String(_??"").replace(/\r/g,"").split(`
33
+ `);for(;k.length>0&&k[k.length-1]==="";)k.pop();for(let I of k)console.log(I?` ${I}`:"");r=!1}function ue(_){let k=String(_??"").replace(/\r/g,"").split(`
34
+ `);k.length===0&&k.push("");let I=[];for(let b of k)I.push(i.bgGray.white(` ${b||" "} `));return I.join(`
35
+ `)}function ye(){$();let _=()=>i.gray(`${Ge[a%Ge.length]} thinking`);if(!e){console.log(` ${_()}`),r=!0;return}Y(),R(),console.log(),console.log(` ${_()}`),B({preserveInput:!0}),r=!0,a+=1,s=setInterval(()=>{r&&(z(_()),a+=1)},120)}function be(_){$();let k=String(_??"").replace(/\r/g,"").replace(/⎿/g,"");if(!r){H(k);return}R(),console.log();let I=k.split(`
36
+ `);for(;I.length>0&&I[I.length-1]==="";)I.pop();for(let b of I)console.log(b?` ${b}`:"");console.log(),r=!1}return{enabled:e,mount(){if(!o){if(!e){t.prompt(),o=!0;return}o=!0,B()}},refreshPrompt(_={}){if(e&&o){n&&R(),B(_);return}t.prompt()},pushSystem(_){H(_)},pushUser(_){H(ue(_))},pushAssistant(_){be(_)},showAssistantLoading:ye,dismissTransientLoading(){$(),r&&e&&o&&n&&(process.stdout.write("\x1B7"),j(process.stdout,0,-2),K(process.stdout,0),Q(process.stdout,0),j(process.stdout,0,-1),K(process.stdout,0),Q(process.stdout,0),process.stdout.write("\x1B8")),r=!1},touchInputFrame:L,handleResize:he,showCommandDropdown:A,clearCommandDropdown:Y}}function $s(){console.log(""),console.log(i.cyan(" Available commands:"));for(let t of $t)console.log(i.white(` ${t.cmd.padEnd(10)} `)+i.gray(t.desc));console.log(""),console.log(i.cyan(" Chat options:")),console.log(i.white(" --stream, -s ")+i.gray("Enable typewriter effect (default: instant)")),console.log(""),console.log(i.gray(" To install/uninstall skills, just ask naturally:")),console.log(i.gray(' "connect to Jira" \u2022 "add GitHub" \u2022 "remove Slack"')),console.log("")}var vs=ls;async function Ar(t={}){let e=process.cwd();t.verbose&&(process.env.ZIBBY_VERBOSE="true");let o=t.stream||!1;[me(e,".env.local"),me(e,".env")].forEach(b=>{Ce(b)&&ts.config({path:b,override:!1})});try{let{loadCredentialsIntoEnv:b}=await Promise.resolve().then(()=>(ro(),so));await b({verbose:!!process.env.ZIBBY_DEBUG})}catch{}try{await import("@zibby/skills")}catch{}function r(){let b=Ye();if(!b)return!1;try{let ee=JSON.parse(atob(b.split(".")[1]));return ee.exp&&ee.exp*1e3>Date.now()}catch{return!1}}if(!r()){Ft();let b=le(),{spawn:ee}=await import("child_process"),te=await fetch(`${b}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});te.ok||(console.log(i.red("\n Could not start login. Try `zibby login`.\n")),process.exit(1));let{deviceCode:C,verificationUrl:d,expiresIn:Z,interval:re}=await te.json(),J=process.platform;ee(J==="darwin"?"open":J==="win32"?"cmd":"xdg-open",J==="win32"?["/c","start","",d]:[d],{detached:!0,stdio:"ignore"}).unref(),console.log(i.cyan(`
37
+ Opening browser to authorize Zibby CLI...`)),console.log(i.gray(` ${d}
38
+ `));let pe=Oo();pe.setLabel("waiting for authorization");let we=(re||3)*1e3,_e=Math.floor(Z/(re||3)),ie=!1;for(let de=0;de<_e;de++){await as(we);try{let ae=await fetch(`${b}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:C})});if(ae.status===202)continue;if(!ae.ok)break;let q=await ae.json();if(q.status==="authorized"){Mt(q.token),zt(q.user),q.proxyUrl&&Ht(q.proxyUrl),q.mem0ProxyUrl&&Kt(q.mem0ProxyUrl),ie=!0;break}if(q.status==="denied")break}catch{break}}pe(),ie||(console.log(i.red("\n Login failed or timed out. Run `zibby login` to try again.\n")),process.exit(1))}let s=await us(e),a=await ds(e),c=t.agent||"assistant",l=Ye();l&&!process.env.ZIBBY_USER_TOKEN&&(process.env.ZIBBY_USER_TOKEN=l);let p=Zt()||Yt();p&&!process.env.ZIBBY_MEM0_OPENAI_BASE_URL&&(process.env.ZIBBY_MEM0_OPENAI_BASE_URL=p),process.env.AGENT_TYPE=c,process.env.ZIBBY_CHAT_OWNER_PID=String(process.pid);try{let{cleanupStalePidFiles:b}=await Promise.resolve().then(()=>(ft(),pt));b(e,s)}catch{}let $;try{$=Wn({state:{agentType:c}})}catch(b){console.log(i.red(`
39
+ ${b.message}
40
+ `)),process.exit(1)}let z=jt(),W=Wt()?.[0]?.name,A=Vt(e),R="zibby",B=a.skills||[],he=Xt(e),L=he?[...new Set([...B,...he])]:[...B],H={data:null,timestamp:0},ue=300*1e3,ye={jira:"jira",github:"github",slack:"slack",sentry:"sentry"};try{let b=Ye();if(b){let ee=le(),te=await fetch(`${ee}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${b}`}});if(te.ok){let C=await te.json();for(let[d,Z]of Object.entries(ye)){let re=C[d]?.connected,J=L.indexOf(Z),Ve=Re(Z);re&&J===-1&&Ve?L.push(Z):!re&&J!==-1&&L.splice(J,1)}Ue(e,L)}}}catch{}let be=L.filter(b=>b!=="skill-installer"&&b!=="core-tools"),_=be.length>0?`Skills: ${be.join(", ")}`:"Skills: (none)";_s({userName:z?.name?.split(" ")[0],cwd:e,projectName:W,restoredCount:A.length,skillsLine:_});let k=No(e),I=Lo(k);return new Promise(b=>{let ee=process.env.ZIBBY_CHAT_TAB_COMPLETION==="1",te={input:process.stdin,output:process.stdout,prompt:i.green(" > "),terminal:!0};ee&&(te.completer=S=>{let g=String(S||"");if(!g.startsWith("/"))return[[],g];let v=I.map(U=>U.cmd),P=v.filter(U=>U.startsWith(g));return[P.length>0?P:v,g]});let C=Vn(te),d=xs(C),Z=null,re=!1,J=[],Ve=0,Mo=1200,pe=!1,we=!1,_e=!1,ie=!1,de="",ae=0,q=typeof C._ttyWrite=="function"?C._ttyWrite.bind(C):null;q&&(C._ttyWrite=(...S)=>{if(!(ie||Date.now()<ae))return q(...S)});function jo(){_e||!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004h"),_e=!0)}function vt(){_e&&(!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004l"),_e=!1))}function zo(S){let g="\x1B[200~",v="\x1B[201~";if(!ie&&!S.includes(g))return!1;let P=S,U=!1;for(;P.length>0;){if(!ie){let N=P.indexOf(g);if(N===-1)break;U=!0,It(),ie=!0,de="",P=P.slice(N+g.length);continue}let V=P.indexOf(v);if(V===-1){U=!0,de+=P;break}U=!0,de+=P.slice(0,V);let ce=String(de||"").replace(/\r\n/g,`
37
41
  `).replace(/\r/g,`
38
- `);if(ot.length>0){let C=ot.split(`
39
- `);for(let q of C)Vt(q)}Lt(),it="",et=!1,$=$.slice(J+w.length)}return P}function fe(){if(!at){at=!0;try{At(t,N),Tt(t,B)}catch{}try{pe()}catch{}try{b.close()}catch{}process.exit(0)}}async function Ht(){if(!at){at=!0,typeof F?.cleanup=="function"&&await F.cleanup().catch(()=>{});try{let{killAllChatOrchestratedRuns:m}=await Promise.resolve().then(()=>(ie(),re)),{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!")),pe(),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 Wt=0,Nt=m=>{if(typeof m=="string"?m==="\x1B":m&&typeof m.length=="number"?m.length===1&&m[0]===27:!1){O&&O.abort(),fe();return}let w=typeof m=="string"?m:m&&typeof m.length=="number"?Buffer.from(m).toString("utf8"):"";if(!w)return;if(sn(w)){Wt=Date.now()+1200,nt=Date.now()+1200,Gt();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)&&(Wt=Date.now()+1200,nt=Date.now()+1200,ge(),Gt())},R={query:"",matches:[],selected:0},H={prefix:"",matches:[],nextIndex:0},A={active:!1,prefix:"",lines:[],timer:null},Zt=[],de=0,Jt="",rn=new Set(ue.map(m=>m.cmd));function gt(m,{preserveFrame:a=!1}={}){let w=String(m||"");b.line=w,b.cursor=w.length,Jt=w,typeof b._refreshLine=="function"?b._refreshLine():b.prompt(),a&&i.touchInputFrame()}function me(){H.prefix="",H.matches=[],H.nextIndex=0}function Lt(){if(A.timer&&(clearTimeout(A.timer),A.timer=null),A.active&&A.lines.length>0){de+=1;let m=A.lines.length,a=`[Pasted text #${de} +${m} lines]`,w=A.lines.join(`
43
- `);Zt.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 Gt(){A.timer&&clearTimeout(A.timer),A.timer=setTimeout(()=>{Lt()},180)}function ge(){A.active||(A.active=!0,A.prefix=String(Jt||b.line||""),A.lines=[],gt(A.prefix,{preserveFrame:!0}))}function Vt(m){return A.active?(A.lines.push(String(m||"")),gt(A.prefix,{preserveFrame:!0}),Gt(),!0):!1}function cn(m){let a=String(m||"");for(let w of Zt)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=qe(t),k=Xe(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 qt=(m,a)=>{if(a?.name==="escape"||a?.sequence==="\x1B"){O&&O.abort(),fe();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)){me(),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"&&me(),setTimeout(()=>{ht(b.line),A.active||(Jt=String(b.line||""))},50)};process.stdin?.on&&(Zn(process.stdin,b),process.stdin.on("keypress",qt)),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()<Wt||Date.now()<nt)){if(A.active&&a.length>0){Vt(a);return}A.active&&(Lt(),i.refreshPrompt());return}if(A.active&&(Lt(),a=String(b.line||a||"")),Vt(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"){Ht();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(`
42
+ `);if(ce.length>0){let N=ce.split(`
43
+ `);for(let oe of N)nt(oe)}Me(),de="",ie=!1,P=P.slice(V+v.length)}return U}function At(){if(!pe){pe=!0;try{Ne(e,A),Ue(e,L)}catch{}try{vt()}catch{}try{C.close()}catch{}process.exit(0)}}async function Xe(){if(!pe){pe=!0,typeof $?.cleanup=="function"&&await $.cleanup().catch(()=>{});try{let{killAllChatOrchestratedRuns:S}=await Promise.resolve().then(()=>(ft(),pt)),{postCliInterruptedRunIndex:g}=await import("@zibby/core/utils/run-index-post-cli.js");S(e,process.pid,s),g({cwd:e,config:s})}catch{}Ne(e,A),Ue(e,L),d.pushSystem(i.gray("Session saved. Goodbye!")),vt(),C.close(),process.exit(0)}}if(d.mount(),jo(),process.stdout?.isTTY){let S;process.stdout.on("resize",()=>{clearTimeout(S),S=setTimeout(()=>{d.handleResize()},80)})}let Qe=0,De=S=>{if(typeof S=="string"?S==="\x1B":S&&typeof S.length=="number"?S.length===1&&S[0]===27:!1){Z&&Z.abort(),At();return}let v=typeof S=="string"?S:S&&typeof S.length=="number"?Buffer.from(S).toString("utf8"):"";if(!v)return;if(zo(v)){Qe=Date.now()+1200,ae=Date.now()+1200,ot();return}let P=(v.includes(`
44
+ `)||v.includes("\r"))&&v!=="\r"&&v!==`
45
+ `&&v!==`\r
46
+ `,U=v.includes("\x1B[200~")||v.includes("\x1B[201~"),V=v.length>=16&&/\s/.test(v)&&!v.startsWith("\x1B");(P||U||V)&&(Qe=Date.now()+1200,ae=Date.now()+1200,It(),ot())},F={query:"",matches:[],selected:0},G={prefix:"",matches:[],nextIndex:0},O={active:!1,prefix:"",lines:[],timer:null},et=[],Ct=0,tt="",Fo=new Set($t.map(S=>S.cmd));function Se(S,{preserveFrame:g=!1}={}){let v=String(S||"");C.line=v,C.cursor=v.length,tt=v,typeof C._refreshLine=="function"?C._refreshLine():C.prompt(),g&&d.touchInputFrame()}function kt(){G.prefix="",G.matches=[],G.nextIndex=0}function Me(){if(O.timer&&(clearTimeout(O.timer),O.timer=null),O.active&&O.lines.length>0){Ct+=1;let S=O.lines.length,g=`[Pasted text #${Ct} +${S} lines]`,v=O.lines.join(`
47
+ `);et.push({placeholder:g,text:v});let P=String(O.prefix||"").trimEnd(),U=P?`${P} ${g}`:g;Se(U,{preserveFrame:!0}),xe(C.line)}O.active=!1,O.prefix="",O.lines=[],ae=0}function ot(){O.timer&&clearTimeout(O.timer),O.timer=setTimeout(()=>{Me()},180)}function It(){O.active||(O.active=!0,O.prefix=String(tt||C.line||""),O.lines=[],Se(O.prefix,{preserveFrame:!0}))}function nt(S){return O.active?(O.lines.push(String(S||"")),Se(O.prefix,{preserveFrame:!0}),ot(),!0):!1}function Yo(S){let g=String(S||"");for(let v of et)g=g.split(v.placeholder).join(v.text);return g}function xe(S){let g=String(S||"");if(!g.startsWith("/")||g.includes(" ")||g.length===0){F.query="",F.matches=[],F.selected=0,d.clearCommandDropdown();return}k=No(e),I=Lo(k);let v=g.slice(1).toLowerCase(),P=k.filter(U=>U.toLowerCase().startsWith(v));F.query=v,F.matches=P,F.selected=Math.min(F.selected,Math.max(0,P.length-1)),d.showCommandDropdown(P,F.selected)}let st=(S,g)=>{if(g?.name==="escape"||g?.sequence==="\x1B"){Z&&Z.abort(),At();return}if((g?.name==="return"||g?.name==="enter")&&(we=!0),(g?.name==="backspace"||g?.name==="delete")&&d.touchInputFrame(),g?.name==="tab"&&!g?.shift){let U=String(C.line||""),V=Number(C.cursor||U.length);if(!ws(U,V)){kt(),xe(C.line);return}let ce=U.slice(1).toLowerCase();if(G.prefix!==ce&&(G.prefix=ce,G.matches=I.map(oe=>oe.cmd).filter(oe=>oe.toLowerCase().startsWith(`/${ce}`)),G.nextIndex=0),G.matches.length===0)return;let N=G.nextIndex%G.matches.length;G.nextIndex+=1,Se(G.matches[N]),xe(C.line);return}let v=String(C.line||""),P=v.startsWith("/")&&!v.includes(" ")&&F.matches.length>0;if(g?.name==="up"||g?.name==="down"){if(!P){xe(C.line);return}let U=g.name==="up"?-1:1,V=F.matches.length;F.selected=(F.selected+U+V)%V;let ce=F.matches[F.selected];Se(`/${ce}`,{preserveFrame:!0}),d.showCommandDropdown(F.matches,F.selected);return}g?.name!=="tab"&&kt(),setTimeout(()=>{xe(C.line),O.active||(tt=String(C.line||""))},50)};process.stdin?.on&&(Xn(process.stdin,C),process.stdin.on("keypress",st)),d.enabled&&process.stdin?.on&&(typeof process.stdin.prependListener=="function"?process.stdin.prependListener("data",De):process.stdin.on("data",De)),C.on("line",async S=>{try{let g=String(S||""),v=we;if(we=!1,!v&&(O.active||ie||Date.now()<Qe||Date.now()<ae)){if(O.active&&g.length>0){nt(g);return}O.active&&(Me(),d.refreshPrompt());return}if(O.active&&(Me(),g=String(C.line||g||"")),nt(g))return;let P=g.trim(),U=F.matches[F.selected];if(P.startsWith("/")&&!P.includes(" ")&&F.matches.length>0&&!Fo.has(P)&&P!==`/${U}`){d.clearCommandDropdown(),d.refreshPrompt(),Se(`/${U}`),xe(`/${U}`);return}d.clearCommandDropdown();let N=String(g||"").replace(/[\u0000-\u001F\u007F-\u009F]/g,"").trim();if(!N){d.enabled&&process.stdout?.isTTY&&(j(process.stdout,0,-1),K(process.stdout,4));return}if(re&&N!=="/exit"&&N!=="/quit"){Z&&Z.abort(),J.push(N),d.pushSystem(i.gray("Processing your message...")),d.refreshPrompt({preserveInput:!0});return}let oe=1e4;if(N.length>oe){d.pushSystem(i.red(`\u26A0 Input too long (${N.length} chars). Maximum: ${oe} characters.`)),d.pushSystem(i.gray("Tip: If you need to share logs, use a file instead:")),d.pushSystem(i.gray(" 1. Save to file: pbpaste > debug.log")),d.pushSystem(i.gray(' 2. Ask: "analyze debug.log in current directory"')),d.refreshPrompt();return}if(N==="/exit"||N==="/quit"){Xe();return}if(N==="/help"){$s(),d.refreshPrompt();return}if(N==="/agents"){try{let{pickAgentWithSessions:m,handleClaudeCodeAddon:T,upsertAgentSession:x,AGENTS:E}=await Promise.resolve().then(()=>(Ao(),vo));console.log("");let y=await m({apiUrl:le(),sessionToken:l,currentAgentId:R});if(y.action==="cancel"){console.log(i.gray(" Cancelled.")),console.log(""),d.refreshPrompt();return}if(y.action==="switch"&&y.agentType==="zibby"){R==="zibby"?console.log(i.gray(" Already using Zibby Chat.")):(R="zibby",console.log(i.green(" \u2713 Switched to Zibby Chat (default)"))),console.log(""),d.refreshPrompt();return}if(y.action==="resume"){let w=E.find(h=>h.id===y.agentType),f=y.session?.sandbox_endpoint||process.env.ZIBBY_SANDBOX_ENDPOINT||null;if(!f||!y.sessionId){console.log(i.yellow(` Cannot resume \u2014 sandbox endpoint or session_id missing for ${w?.name||y.agentType}.`)),console.log(i.gray(" (Sandbox manager Lambda must record sandbox_endpoint in /agents/sessions when provisioning ready.)")),console.log(""),d.refreshPrompt();return}try{let{attachToSession:h}=await Promise.resolve().then(()=>(wt(),bt)),D=/^https/.test(le()),M=await h({sandboxEndpoint:f,sessionId:y.sessionId,sessionToken:l,useTls:D});M.reason==="detach"?console.log(i.gray(`
48
+ Detached from ${w?.name}. Session continues running in the cloud.`)):M.reason==="remote-exit"?console.log(i.gray(`
49
+ ${w?.name} session exited (code ${M.exitCode??"?"}).`)):M.reason==="ws-error"&&console.log(i.red(`
50
+ Connection error: ${M.message}`))}catch(h){console.log(i.red(` Attach failed: ${h.message}`))}console.log(""),d.refreshPrompt();return}if(y.action==="create"){let w=E.find(f=>f.id===y.agentType);if(y.agentType==="claude-code"){let f=await T({workspaceId:z?.account_id||"workspace-default",sessionToken:l,apiUrl:le()});if(!f.cancelled){if(f.ready||f.provisioning){try{await x({apiUrl:le(),sessionToken:l,agentType:"claude-code",fields:{sandbox_id:f.sandboxId,workspace_id:z?.account_id}})}catch(D){console.warn(i.gray(` (could not save session metadata: ${D.message})`))}let h=f.sandboxEndpoint||process.env.ZIBBY_SANDBOX_ENDPOINT||null;if(f.ready&&h)try{let{spawnAndAttach:D}=await Promise.resolve().then(()=>(wt(),bt)),M=/^https/.test(le()),X=await D({sandboxEndpoint:h,sessionToken:l,agentType:"claude-code",useTls:M});X.reason==="detach"?console.log(i.gray(`
51
+ Detached from ${w.name}. Session continues in the cloud.`)):X.reason==="remote-exit"?console.log(i.gray(`
52
+ ${w.name} session exited (code ${X.exitCode??"?"}).`)):X.reason==="ws-error"&&console.log(i.red(`
53
+ Connection error: ${X.message}`))}catch(D){console.log(i.red(` Spawn/attach failed: ${D.message}`))}else R="claude-code",console.log(i.green(f.ready?` \u2713 Active agent: ${w.name}`:` Provisioning ${w.name} \u2014 re-run /agents in ~30s when ready`));console.log("")}}}else{try{await x({apiUrl:le(),sessionToken:l,agentType:y.agentType,fields:{workspace_id:z?.account_id}})}catch(f){console.warn(i.gray(` (could not save session metadata: ${f.message})`))}R=y.agentType,console.log(i.green(` \u2713 New ${w?.name||y.agentType} session`)),console.log(i.gray(" (Live agent connect \u2014 wiring up in next slice.)")),console.log("")}d.refreshPrompt();return}}catch(m){m?.name==="ExitPromptError"?(console.log(i.gray(" Cancelled.")),console.log("")):/zibby login/i.test(m?.message||"")?(console.log(i.yellow(" Session expired \u2014 please run `zibby login` again.")),console.log("")):(console.log(i.red(` Agent selection failed: ${m.message}`)),console.log(""))}d.refreshPrompt();return}if(N==="/skills"){let T=Re("skill-installer")?.catalog||{},x=L.filter(y=>y!=="skill-installer");console.log(i.cyan(`
54
+ Active skills:`)),x.length===0&&console.log(i.gray(" (none)"));for(let y of x){let w=T[y]||{};console.log(i.green(` \u2713 ${y}`)+i.gray(w.description?` \u2014 ${w.description}`:""))}let E=Object.keys(T).filter(y=>!L.includes(y));if(E.length>0){console.log(i.cyan(`
55
+ Available:`));for(let y of E){let w=T[y],f=w.envKeys?.length>0?vs(w.envKeys).ok?i.green(" \u2713 configured"):i.yellow(` \u26A0 needs: ${w.envKeys.join(", ")}`):"";console.log(i.white(` - ${y}`)+i.gray(` \u2014 ${w.description}`)+f)}}console.log(i.gray(`
46
56
  Just ask to install: "connect to Jira", "add GitHub", etc.
47
- `)),i.refreshPrompt();return}if(C.startsWith("/history")){if(N.length===0)console.log(o.gray(`
57
+ `)),d.refreshPrompt();return}if(N.startsWith("/history")){if(A.length===0)console.log(i.gray(`
48
58
  No conversation history.
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(`
59
+ `));else{let m=N.split(/\s+/).slice(1),T=m.includes("--all"),x=m.indexOf("-n"),E=x>=0&&m[x+1]?parseInt(m[x+1],10):NaN,y=T?A.length:isNaN(E)?10:E,w=A.slice(-y);console.log(i.gray(`
60
+ Showing ${w.length} of ${A.length} messages${T?" (all)":""}:
61
+ `));for(let f of w){let h=f.role==="human"?i.green(" You"):i.cyan(" Zibby"),D=T||E>10?500:100,M=f.content.length>D?`${f.content.substring(0,D)}...`:f.content;console.log(`${h}: ${i.white(M)}`)}console.log("")}d.refreshPrompt();return}if(N==="/clear"){A.length=0,Ne(e,A),console.log(i.gray(`
52
62
  History cleared.
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(`
63
+ `)),d.refreshPrompt();return}if(N.startsWith("/memory")){let m=L.includes("chat-memory")?Re("chat-memory"):null;if(!m?.handleToolCall){console.log(i.yellow(`
54
64
  Chat memory not active. Install with: "add chat memory"
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(`
65
+ `)),d.refreshPrompt();return}let T=N.split(/\s+/).slice(1),x=T[0]||"brief",E={options:{workspace:e}};try{if(x==="facts"||x==="all"){let y=parseInt(T[1],10)||30,w=await m.handleToolCall("memory_recall",{limit:y},E),f=JSON.parse(w);if(console.log(i.cyan(`
66
+ Stored memories (${f.total}):
67
+ `)),f.total===0)console.log(i.gray(` (empty \u2014 memories are saved as the agent learns things)
68
+ `));else{for(let h of f.memories){let D=i.yellow(`[${h.category}]`),M=Number(h.relevance)<1?i.gray(` (${(Number(h.relevance)*100).toFixed(0)}%)`):"",X=h.ticket_key?i.magenta(` ${h.ticket_key}`):"",Te=h.source?i.gray(` via ${h.source}`):"";console.log(` ${D}${X} ${i.white(h.content)}${M}${Te}`)}console.log("")}}else if(x==="tasks"){let y=parseInt(T[1],10)||20,w=await m.handleToolCall("task_history",{limit:y},E),f=JSON.parse(w);if(console.log(i.cyan(`
69
+ Task history (${f.total}):
70
+ `)),f.total===0)console.log(i.gray(` (no tasks logged yet)
71
+ `));else{for(let h of f.tasks){let D=h.status==="passed"?i.green("\u2713"):h.status==="failed"?i.red("\u2717"):i.yellow("\u25CB"),M=h.ticket_key?i.magenta(` ${h.ticket_key}`):"",X=i.gray(`[${h.type}]`),Te=h.result_summary?i.gray(` \u2014 ${h.result_summary.slice(0,80)}`):"";console.log(` ${D} ${X}${M} ${i.white(h.title)}${Te}`)}console.log("")}}else if(x==="sessions"){let y=await m.handleToolCall("memory_brief",{},E),w=JSON.parse(y);if(console.log(i.cyan(`
72
+ Recent sessions (${w.recentSessions?.length||0}):
73
+ `)),!w.recentSessions?.length)console.log(i.gray(` (no sessions saved yet)
74
+ `));else{for(let f of w.recentSessions){let h=f.tickets?i.magenta(` [${f.tickets}]`):"",D=f.tasks_run>0?i.gray(` \u2014 ${f.tasks_run} tasks (${f.tasks_passed} passed, ${f.tasks_failed} failed)`):"",M=f.created_at?i.gray(` ${f.created_at.split("T")[0]}`):"";if(console.log(` ${i.white(f.summary)}${h}${D}${M}`),f.key_facts)for(let X of f.key_facts.split(";").map(Te=>Te.trim()).filter(Boolean))console.log(i.gray(` \u2192 ${X}`))}console.log("")}}else if(x==="search"){let y=T.slice(1).join(" ");if(!y)console.log(i.yellow(`
65
75
  Usage: /memory search <keyword>
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(`
76
+ `));else{let w=await m.handleToolCall("memory_recall",{query:y,limit:20},E),f=JSON.parse(w);console.log(i.cyan(`
77
+ Search "${y}" \u2014 ${f.total} results:
78
+ `));for(let h of f.memories){let D=i.yellow(`[${h.category}]`),M=h.ticket_key?i.magenta(` ${h.ticket_key}`):"";console.log(` ${D}${M} ${i.white(h.content)}`)}f.total===0&&console.log(i.gray(" (no matches)")),console.log("")}}else{let y=await m.handleToolCall("memory_brief",{},E),w=JSON.parse(y),f=w.topMemories?.length||0,h=w.recentSessions?.length||0,D=(w.taskStats||[]).map(M=>`${M.type}:${M.status}=${M.cnt}`).join(", ");console.log(i.cyan(`
69
79
  Memory overview:
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 he=cn(C),Bt=io(t,he);if(Zt.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.",ye=uo(l,e);ye&&(K+=`
80
+ `)),console.log(i.white(` Facts stored: ${f>0?i.cyan(f):i.gray("0")}`)),console.log(i.white(` Sessions saved: ${h>0?i.cyan(h):i.gray("0")}`)),D&&console.log(i.white(` Task history: ${i.gray(D)}`)),console.log(i.gray(`
81
+ Subcommands:`)),console.log(i.gray(" /memory facts [n] \u2014 List all stored memories")),console.log(i.gray(" /memory tasks [n] \u2014 List task history")),console.log(i.gray(" /memory sessions \u2014 List session summaries")),console.log(i.gray(" /memory search <keyword> \u2014 Search memories")),console.log("")}}catch(y){console.log(i.red(`
82
+ Memory error: ${y.message}
83
+ `))}d.refreshPrompt();return}d.enabled&&process.stdout?.isTTY&&(j(process.stdout,0,-1),K(process.stdout,0)),d.pushUser(N),d.refreshPrompt(),d.showAssistantLoading();let Tt=Yo(N),je=ps(e,Tt);if(et.length=0,!String(je||"").trim()){d.dismissTransientLoading(),d.refreshPrompt();return}if(je.length>oe){d.pushAssistant(i.red(`Input too long after command expansion (${je.length} chars).`)),d.pushSystem(i.gray(`Try shortening the command template or user text. Limit: ${oe} chars.`)),d.refreshPrompt();return}re=!0;let ne=a.systemPrompt||"You are Zibby, a helpful AI assistant.",Pt=hs(a,t);Pt&&(ne+=`
74
84
 
75
- ${ye}`);let be=Ye({activeSkills:B,chatConfig:l,options:e});be&&(K+=`
85
+ ${Pt}`);let Et=to({activeSkills:L,chatConfig:a,options:t});Et&&(ne+=`
76
86
 
77
- ${be}`);let we=ao(B);if(we&&(K+=`
87
+ ${Et}`);let Ot=ms(L);if(Ot&&(ne+=`
78
88
 
79
- ${we}`),K+=`
89
+ ${Ot}`),ne+=`
80
90
 
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+=`
91
+ Use provided tools when external data/actions are required. Do not claim actions without tool calls. Before using a skill's tools for the first time in a conversation, call get_skill_context(skillId) to load its full guidance.`,L.includes("chat-memory")&&(ne+=`
82
92
 
83
93
  ### Memory Tool Usage (chat-memory)
84
94
  - At conversation start: call memory_brief to load recent context.
85
95
  - Before answering memory-dependent questions: call memory_recall with focused query terms.
86
96
  - When learning durable user/project facts or decisions: call memory_store.
87
97
  - Avoid storing transient chatter, filler text, or duplicate facts.
88
- - Prefer updating strong existing facts over creating near-duplicates when possible.`),B.includes("workflow-builder")&&(K+=`
98
+ - Prefer updating strong existing facts over creating near-duplicates when possible.`),L.includes("workflow-builder")&&(ne+=`
89
99
 
90
100
  ### Workflow Builder (workflow-builder)
91
101
  - When users want to create, build, or scaffold an AI workflow, use the workflow-builder tools.
@@ -93,8 +103,8 @@ Use provided tools when external data/actions are required. Do not claim actions
93
103
  - Conversation flow: ask about purpose \u2192 input data \u2192 processing steps \u2192 output format \u2192 conditional logic.
94
104
  - Then call design_workflow to create a spec, review with user, then build_workflow to generate code.
95
105
  - After building: remind user about \`zibby workflow run <name>\` (run locally), \`zibby workflow deploy <name>\` (deploy), \`zibby workflow logs <uuid>\` (logs).
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+=`
106
+ - Use list_workflows to show existing workflows, add_node to extend them, deploy_workflow to ship.`),L.includes("chat-memory"))try{let m=Re("chat-memory");if(typeof m?.buildPromptContext=="function"){let T=Date.now(),x;H.data&&T-H.timestamp<ue?(x=H.data,process.env.ZIBBY_VERBOSE==="true"&&d.pushSystem(i.gray("Using cached memory context"))):(x=await m.buildPromptContext({options:{workspace:e}},{}),H={data:x,timestamp:T},process.env.ZIBBY_VERBOSE==="true"&&d.pushSystem(i.gray("Refreshed memory context cache")));let E=String(x?.backend||"dolt");process.env.ZIBBY_VERBOSE==="true"&&(d.pushSystem(i.gray(`memory backend: ${E}`)),d.pushSystem(i.gray(`memory retrieval output: ${qe(JSON.stringify(x?.debugPreview||{}),1400)}`)),x?.error&&d.pushSystem(i.yellow(`memory backend warning: ${x.error}`))),x?.promptContext&&(ne+=`
97
107
 
98
- ${S.promptContext}`)}}catch(p){process.env.ZIBBY_VERBOSE==="true"&&i.pushSystem(o.yellow(`memory backend warning: ${String(p?.message||p)}`))}K=Ct(K,en);let an=co(N),Kt=lo([{role:"system",content:K},...an,{role:"user",content:Bt}]),Se=ae(Kt),un=Buffer.byteLength(JSON.stringify(Kt),"utf8");process.env.ZIBBY_VERBOSE==="true"&&i.pushSystem(o.gray(`payload estimate: ${Se} chars, ${un} bytes (~${Math.round(Se/4)} tokens)`)),N.push({role:"human",content:he});let St=i.enabled?(()=>{let p=()=>{};return p.setLabel=()=>{},p})():Ve(),ut=!0,Et=[],xe="",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!==xe&&(xe=T,i.pushSystem(o.gray(`\u23BF ${T}`)),i.refreshPrompt({preserveInput:!0}),ut&&i.showAssistantLoading()),ut&&St.setLabel(T)},Xt=new AbortController;O=Xt;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:Kt,skipPromptFragments:!0,stream:!0,onToken:pn,onToolCall:fn,signal:Xt.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(),Xt.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}Ht()}),b.on("close",Ht);let ln=()=>{process.stdin?.off?(process.stdin.off("data",Nt),process.stdin.off("keypress",qt)):process.stdin?.removeListener&&(process.stdin.removeListener("data",Nt),process.stdin.removeListener("keypress",qt))};b.on("close",ln)})}export{as as _buildPrompt,oo as _checkEnvKeys,no as _formatHistory,ls as _inferAgentType,us as chatCommand};
108
+ ${x.promptContext}`)}}catch(m){process.env.ZIBBY_VERBOSE==="true"&&d.pushSystem(i.yellow(`memory backend warning: ${String(m?.message||m)}`))}ne=Be(ne,Do);let Zo=fs(A),rt=gs([{role:"system",content:ne},...Zo,{role:"user",content:je}]),Nt=xt(rt),Ko=Buffer.byteLength(JSON.stringify(rt),"utf8");process.env.ZIBBY_VERBOSE==="true"&&d.pushSystem(i.gray(`payload estimate: ${Nt} chars, ${Ko} bytes (~${Math.round(Nt/4)} tokens)`)),A.push({role:"human",content:Tt});let ke=d.enabled?(()=>{let m=()=>{};return m.setLabel=()=>{},m})():Oo(),fe=!0,ze=[],Ut="",Ie="",Cs=50,ks=500,Is=3,Ts=60,Ps=500,Es=15,Os=25,Ns=4,Us=new Set([".","!","?",",",";",":"]),Wo=m=>{fe&&(ke(),fe=!1),Ie+=m},Jo=(m,T)=>{if(!m){fe&&ke.setLabel("thinking...");return}ze.push(m);let x=70,E=m;if(T&&typeof T=="object"){let w=Object.values(T).map(h=>typeof h=="string"?h:JSON.stringify(h)).join(", "),f=`${m}(${w})`;f.length<=x?E=f:E=`${m}(${w.slice(0,x-m.length-4)}...)`}E!==Ut&&(Ut=E,d.pushSystem(i.gray(`\u23BF ${E}`)),d.refreshPrompt({preserveInput:!0}),fe&&d.showAssistantLoading()),fe&&ke.setLabel(E)},it=new AbortController;Z=it;try{let m=await Kn("",{state:{agentType:c,config:s,cwd:e,workspace:e}},{model:s?.agent?.assistant?.model||a.model||"auto",workspace:e,skills:L,activeSkills:L,config:s,timeout:a.timeout||3e5,messages:rt,skipPromptFragments:!0,stream:!0,onToken:Wo,onToolCall:Jo,signal:it.signal});fe&&ke();let T=typeof m=="string"?m:m?.structured?JSON.stringify(m.structured,null,2):m?.raw||String(m),x=Ie&&Ie.trim().length>0?Ie.trim():T.trim(),E=ys(x,ze)?x:bs(x);d.pushAssistant(E);let y=ze.length>0?`[tools used: ${ze.join(", ")}]
109
+ ${x}`:x;A.push({role:"ai",content:y}),Ne(e,A),Ue(e,L)}catch(m){if(fe&&ke(),d.dismissTransientLoading(),it.signal.aborted){J.length===0&&d.pushAssistant(i.gray("[cancelled]"));let T="";try{let{testRunnerSkill:E}=await import("../../skills/index.js"),y=await E.handleToolCall("run_status",{runId:"all"},{options:{workspace:e}}),w=JSON.parse(y);w.runs?.length>0&&(T=`
110
+ [Active test runs: ${w.runs.map(h=>`${h.runId}: ${h.ticketKey||h.spec} (${h.status})`).join(", ")}. Use run_status("all") to check progress.]`)}catch{}let x=Ie.trim();x?A.push({role:"ai",content:x+T}):A.push({role:"ai",content:`[interrupted \u2014 new message]${T}`})}else{let T=String(m?.message||m||"Unknown error");/413|payload too large|request payload too large/i.test(T)?(d.pushAssistant(i.yellow("Request became too large for the proxy (413).")),d.pushSystem(i.gray("Try: /clear, then retry your command; or shorten command/context."))):d.pushAssistant(i.red(`Error: ${T}`)),A.push({role:"ai",content:`[Error: ${m.message}]`})}}finally{Z=null,re=!1}if(d.refreshPrompt(),J.length>0){let m=J.shift();we=!0,setImmediate(()=>C.emit("line",m))}}catch(g){d.pushSystem(i.red(`Input handling error: ${g?.message||String(g)}`)),d.refreshPrompt()}}),C.on("SIGINT",()=>{if(Z){Z.abort();return}Xe()}),C.on("close",Xe);let Ho=()=>{process.stdin?.off?(process.stdin.off("data",De),process.stdin.off("keypress",st)):process.stdin?.removeListener&&(process.stdin.removeListener("data",De),process.stdin.removeListener("keypress",st))};C.on("close",Ho)})}export{vr as _buildPrompt,ls as _checkEnvKeys,cs as _formatHistory,$r as _inferAgentType,Ar as chatCommand};
@@ -0,0 +1 @@
1
+ function c(e,r=""){return`${String(e).replace(/\/+$/,"")}/agents/credentials${r}`}function u(){let e=new Error("Session expired \u2014 run zibby login");return e.code="AUTH_EXPIRED",e}async function f({apiUrl:e,sessionToken:r}){if(!r)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let t=await fetch(c(e),{headers:{Authorization:`Bearer ${r}`}});if(t.status===401)throw u();if(t.status===404)return{credentials:[],by_type:{oauth:[],api:[]},total:0};if(!t.ok){let a=new Error(`List credentials failed (${t.status})`);throw a.status=t.status,a}return t.json()}async function l({apiUrl:e,sessionToken:r,type:t,token:a,source:n="~/.zibby/config.json"}){if(!r)throw new Error("No session token \u2014 run zibby login first");let o=await fetch(c(e),{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify({type:t,token:a,source:n})});if(o.status===401)throw u();if(!o.ok){let s=`Add credential failed (${o.status})`;try{let d=await o.json();d?.error&&(s=`${s}: ${d.error}`)}catch{}let i=new Error(s);throw i.status=o.status,i}return o.json()}async function h({apiUrl:e,sessionToken:r,type:t,index:a}){if(!r)throw new Error("No session token \u2014 run zibby login first");let n=await fetch(c(e,`/${encodeURIComponent(t)}/${encodeURIComponent(a)}`),{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(n.status===401)throw u();if(!n.ok){let o=new Error(`Delete credential failed (${n.status})`);throw o.status=n.status,o}return n.json()}async function y({apiUrl:e,sessionToken:r,credentials:t}){let a=0,n=0,o=[];for(let s of t)try{let i=await l({apiUrl:e,sessionToken:r,type:s.type,token:s.token,source:s.source_var||s.source||"local"});i.deduped?n+=1:i.added&&(a+=1)}catch(i){o.push({masked:s.token?`***${s.token.slice(-4)}`:"***",error:i.message})}return{added:a,deduped:n,errors:o}}export{l as addCredential,h as deleteCredential,f as listCredentials,y as syncFromLocal};
@@ -0,0 +1 @@
1
+ import p from"node:fs/promises";import O from"node:path";import _ from"node:os";var m=O.join(_.homedir(),".zibby","config.json"),u={CLAUDE_CODE_OAUTH_TOKEN:"oauth",CLAUDE_CODE_OAUTH_TOKEN_POOL:"oauth",ANTHROPIC_AUTH_TOKEN:"oauth",ANTHROPIC_API_KEY:"api",ANTHROPIC_API_KEY_POOL:"api"};function h(n){if(!n)return[];let s;try{s=JSON.parse(n)}catch{return[]}let e=s?.agentKeys;if(!e||typeof e!="object")return[];let c=[],i=new Set;for(let[t,f]of Object.entries(u)){let r=e[t];if(!r||typeof r!="string")continue;let a=t.endsWith("_POOL")?r.split(",").map(o=>o.trim()).filter(Boolean):[r.trim()];for(let o of a)o.length<8||i.has(o)||(i.add(o),c.push({type:f,token:o,source_var:t}))}return c}async function l(n=m){let s;try{s=await p.readFile(n,"utf8")}catch(e){if(e.code==="ENOENT")return[];throw e}return h(s)}async function E({filepath:n,env:s=process.env}={}){let e=await l(n),c=new Set(e.map(t=>t.token)),i=[];for(let[t,f]of Object.entries(u)){let r=s[t];if(!r)continue;let a=t.endsWith("_POOL")?r.split(",").map(o=>o.trim()).filter(Boolean):[r];for(let o of a)o.length<8||c.has(o)||(c.add(o),i.push({type:f,token:o,source_var:t,source:"process.env"}))}return{config:e.map(t=>({...t,source:"config.json"})),env:i,all:[...e.map(t=>({...t,source:"config.json"})),...i]}}function d(n){return!n||typeof n!="string"||n.length<=4?"***":`***${n.slice(-4)}`}export{m as DEFAULT_CONFIG_PATH,E as discoverCredentials,d as maskToken,h as parseConfigJson,l as readCredentialsConfig};
@@ -0,0 +1 @@
1
+ import t from"chalk";function y(o,e=""){return`${String(o).replace(/\/+$/,"")}/agents/credentials${e}`}function h(){let o=new Error("Session expired \u2014 run zibby login");return o.code="AUTH_EXPIRED",o}async function m({apiUrl:o,sessionToken:e}){if(!e)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let r=await fetch(y(o),{headers:{Authorization:`Bearer ${e}`}});if(r.status===401)throw h();if(r.status===404)return{credentials:[],by_type:{oauth:[],api:[]},total:0};if(!r.ok){let c=new Error(`List credentials failed (${r.status})`);throw c.status=r.status,c}return r.json()}async function O({apiUrl:o,sessionToken:e,type:r,token:c,source:s="~/.zibby/config.json"}){if(!e)throw new Error("No session token \u2014 run zibby login first");let n=await fetch(y(o),{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({type:r,token:c,source:s})});if(n.status===401)throw h();if(!n.ok){let i=`Add credential failed (${n.status})`;try{let d=await n.json();d?.error&&(i=`${i}: ${d.error}`)}catch{}let l=new Error(i);throw l.status=n.status,l}return n.json()}async function _({apiUrl:o,sessionToken:e,type:r,index:c}){if(!e)throw new Error("No session token \u2014 run zibby login first");let s=await fetch(y(o,`/${encodeURIComponent(r)}/${encodeURIComponent(c)}`),{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(s.status===401)throw h();if(!s.ok){let n=new Error(`Delete credential failed (${s.status})`);throw n.status=s.status,n}return s.json()}async function U({apiUrl:o,sessionToken:e,credentials:r}){let c=0,s=0,n=[];for(let i of r)try{let l=await O({apiUrl:o,sessionToken:e,type:i.type,token:i.token,source:i.source_var||i.source||"local"});l.deduped?s+=1:l.added&&(c+=1)}catch(l){n.push({masked:i.token?`***${i.token.slice(-4)}`:"***",error:l.message})}return{added:c,deduped:s,errors:n}}import $ from"node:fs/promises";import C from"node:path";import A from"node:os";var p=C.join(A.homedir(),".zibby","config.json"),v={CLAUDE_CODE_OAUTH_TOKEN:"oauth",CLAUDE_CODE_OAUTH_TOKEN_POOL:"oauth",ANTHROPIC_AUTH_TOKEN:"oauth",ANTHROPIC_API_KEY:"api",ANTHROPIC_API_KEY_POOL:"api"};function k(o){if(!o)return[];let e;try{e=JSON.parse(o)}catch{return[]}let r=e?.agentKeys;if(!r||typeof r!="object")return[];let c=[],s=new Set;for(let[n,i]of Object.entries(v)){let l=r[n];if(!l||typeof l!="string")continue;let d=n.endsWith("_POOL")?l.split(",").map(a=>a.trim()).filter(Boolean):[l.trim()];for(let a of d)a.length<8||s.has(a)||(s.add(a),c.push({type:i,token:a,source_var:n}))}return c}async function N(o=p){let e;try{e=await $.readFile(o,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}return k(e)}async function w({filepath:o,env:e=process.env}={}){let r=await N(o),c=new Set(r.map(n=>n.token)),s=[];for(let[n,i]of Object.entries(v)){let l=e[n];if(!l)continue;let d=n.endsWith("_POOL")?l.split(",").map(a=>a.trim()).filter(Boolean):[l];for(let a of d)a.length<8||c.has(a)||(c.add(a),s.push({type:i,token:a,source_var:n,source:"process.env"}))}return{config:r.map(n=>({...n,source:"config.json"})),env:s,all:[...r.map(n=>({...n,source:"config.json"})),...s]}}var u={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.dev",description:"Production environment"}};function f(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";u[e]?o=u[e].apiUrl:o=u.prod.apiUrl}try{let e=new URL(o);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),u.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),u.prod.apiUrl}}import{existsSync as E,mkdirSync as G,readFileSync as P,writeFileSync as J}from"fs";import{homedir as x}from"os";import{join as g}from"path";function R(){return process.env.ZIBBY_CONFIG_DIR||g(x(),".zibby")}function T(){return g(R(),"config.json")}var B=g(x(),".zibby"),X=g(B,"config.json");function z(){try{let o=T();if(E(o)){let e=P(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function I(){return z().sessionToken||null}function b(){let o=I();return o||(console.log(t.red("Not logged in. Run `zibby login` first.")),process.exit(1)),o}async function L(){let o=b(),e=f();console.log(""),console.log(t.cyan(" Stored credentials in your Zibby workspace")),console.log(t.gray(` Source file: ${p}`)),console.log("");let r;try{r=await m({apiUrl:e,sessionToken:o})}catch(s){console.log(t.red(` Failed: ${s.message}`)),process.exit(1)}let{by_type:c}=r;for(let s of["oauth","api"]){let n=c[s]||[];if(console.log(t.bold(` ${s} pool (${n.length} ${n.length===1?"token":"tokens"}):`)),n.length===0)console.log(t.gray(" (none)"));else for(let i of n){let l=i.uploaded_at?new Date(i.uploaded_at).toISOString().slice(0,10):"?",d=i.uploaded_by||"?";console.log(` [${i.index}] ${t.cyan(i.masked)} `+t.gray(`uploaded ${l} by ${d} source: ${i.source||"unknown"}`))}console.log("")}r.total===0&&(console.log(t.gray(" No credentials yet. Run `zibby init` to set them up \u2014 Claude has")),console.log(t.gray(" both OAuth subscription and API key options. Then re-run sync.")),console.log("")),console.log(t.gray(" Same file, same credentials, used by every zibby command:")),console.log(t.gray(" zibby test (test automation)")),console.log(t.gray(" zibby chat (interactive chat + cloud Claude Code sandbox)")),console.log(t.gray(" zibby workflow run (local execution)")),console.log(t.gray(" zibby workflow start (local dev server)")),console.log("")}async function S(){let o=b(),e=f();console.log(""),console.log(t.cyan(" Scanning your local credentials...")),console.log(t.gray(` ${p}`));let r=await w(),c=r.all.length;if(c===0){console.log(""),console.log(t.yellow(" No credentials found in ~/.zibby/config.json.")),console.log(""),console.log(t.white(" Run `zibby init` first to choose API key or OAuth subscription.")),console.log(t.gray(" Or export tokens in your shell \u2014 Zibby reads process.env too.")),console.log("");return}console.log(t.green(` \u2713 Found ${c} ${c===1?"credential":"credentials"}:`));for(let n of r.all)console.log(t.gray(` ${n.type} ***${n.token.slice(-4)} source: ${n.source_var} (${n.source})`));console.log(""),console.log(t.cyan(" Uploading to Zibby (KMS-encrypted)..."));let s=await U({apiUrl:e,sessionToken:o,credentials:r.all});if(console.log(""),console.log(t.green(` \u2713 ${s.added} new, ${s.deduped} already present`)),s.errors.length>0){console.log(t.red(` \u2717 ${s.errors.length} failed:`));for(let n of s.errors)console.log(t.red(` ${n.masked}: ${n.error}`))}console.log("")}async function D(o,e){let r=b(),c=f();(!o||!e)&&(console.log(t.red("Usage: zibby creds remove <type> <index>")),console.log(t.gray(" e.g. zibby creds remove oauth 0")),process.exit(1)),console.log(""),console.log(t.cyan(` Removing ${o} credential at index ${e}...`));try{await _({apiUrl:c,sessionToken:r,type:o,index:e})}catch(s){console.log(t.red(` Failed: ${s.message}`)),process.exit(1)}console.log(t.green(" \u2713 Removed.")),console.log(""),console.log(t.gray(" Note: this only deletes Zibby's encrypted copy. To revoke")),console.log(t.gray(" the actual token, do that on the upstream provider where")),console.log(t.gray(" it was issued.")),console.log("")}async function ro(o,...e){switch(o){case"list":return L();case"sync":return S();case"remove":return D(e[0],e[1]);default:console.log(t.red(`Unknown subcommand: ${o}`)),console.log(t.gray(" zibby creds list")),console.log(t.gray(" zibby creds sync")),console.log(t.gray(" zibby creds remove <type> <index>")),process.exit(1)}}export{ro as credsCmd,L as listCmd,D as removeCmd,S as syncCmd};