@zibby/cli 0.1.95 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/auth/cli-login.js +7 -7
- package/dist/auth/ensure-auth.js +6 -6
- package/dist/bin/zibby.js +3 -3
- package/dist/commands/chat-agents.js +1 -0
- package/dist/commands/chat-sandbox-attach.js +5 -0
- package/dist/commands/chat.js +79 -69
- package/dist/commands/credentials-api.js +1 -0
- package/dist/commands/credentials-file.js +1 -0
- package/dist/commands/creds.js +1 -0
- package/dist/commands/init.js +1 -1
- package/dist/commands/list-projects.js +5 -5
- package/dist/commands/project.js +3 -3
- package/dist/commands/run.js +54 -54
- package/dist/commands/studio.js +2 -2
- package/dist/commands/upload.js +4 -4
- package/dist/commands/workflow.js +23 -23
- package/dist/commands/workflows/dedicated-egress.js +6 -6
- package/dist/commands/workflows/delete.js +4 -4
- package/dist/commands/workflows/deploy.js +19 -19
- package/dist/commands/workflows/env.js +7 -7
- package/dist/commands/workflows/generate.js +1 -1
- package/dist/commands/workflows/list.js +6 -6
- package/dist/commands/workflows/run-local.js +19 -19
- package/dist/commands/workflows/start.js +15 -15
- package/dist/commands/workflows/trigger.js +7 -7
- package/dist/config/environments.js +1 -1
- package/dist/package.json +5 -5
- package/dist/templates/zibby-workflow-claude/claude/commands/zibby-static-ip.md +1 -1
- package/dist/utils/credentials-loader.js +1 -0
- package/package.json +5 -5
package/dist/commands/chat.js
CHANGED
|
@@ -1,91 +1,101 @@
|
|
|
1
|
-
var
|
|
2
|
-
`,"utf8")}function
|
|
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 Ko=Object.defineProperty;var ve=(t,e)=>()=>(t&&(e=t(t=0)),e);var ke=(t,e)=>{for(var o in e)Ko(t,o,{get:e[o],enumerable:!0})};var co={};ke(co,{DEFAULT_CREDENTIALS_PATH:()=>so,discoverCredentials:()=>lt,maskToken:()=>dn,parseCredentialsEnv:()=>io,readCredentialsFile:()=>ao});import cn from"node:fs/promises";import ln from"node:path";import un from"node:os";function io(t){if(!t)return[];let e=[],o=new Set,n=String(t).split(/\r?\n/);for(let r of n){let s=r.trim();if(!s||s.startsWith("#"))continue;let a=s.indexOf("=");if(a<1)continue;let c=s.slice(0,a).trim(),l=s.slice(a+1).trim();if((l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),!l)continue;let f=ro[c];if(!f)continue;let N=c.endsWith("_POOL")?l.split(",").map(A=>A.trim()).filter(Boolean):[l];for(let A of N)A.length<8||o.has(A)||(o.add(A),e.push({type:f,token:A,source_var:c}))}return e}async function ao(t=so){let e;try{e=await cn.readFile(t,"utf8")}catch(o){if(o.code==="ENOENT")return[];throw o}return io(e)}async function lt({filepath:t,env:e=process.env}={}){let o=await ao(t),n=new Set(o.map(s=>s.token)),r=[];for(let[s,a]of Object.entries(ro)){let c=e[s];if(!c)continue;let l=s.endsWith("_POOL")?c.split(",").map(f=>f.trim()).filter(Boolean):[c];for(let f of l)f.length<8||n.has(f)||(n.add(f),r.push({type:a,token:f,source_var:s,source:"process.env"}))}return{file:o.map(s=>({...s,source:"file"})),env:r,all:[...o.map(s=>({...s,source:"file"})),...r]}}function dn(t){return!t||typeof t!="string"||t.length<=4?"***":`***${t.slice(-4)}`}var so,ro,ut=ve(()=>{so=ln.join(un.homedir(),".zibby","credentials.env"),ro={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 lo={};ke(lo,{_resetLoaderCacheForTests:()=>fn,loadCredentialsIntoEnv:()=>pn});async function pn(t={}){let{verbose:e=!1,force:o=!1,filepath:n}=t;if(Re&&!o)return pe;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))return Re=!0,pe={oauthCount:0,apiCount:0,source:"cloud-env"},e&&console.log("[credentials-loader] env vars already set \u2014 skipping local discovery"),pe;let s;try{s=await lt(n?{filepath:n}:void 0)}catch(A){return e&&console.warn(`[credentials-loader] discovery failed: ${A.message}`),Re=!0,pe={oauthCount:0,apiCount:0,source:"none"},pe}let a=s.all.filter(A=>A.type==="oauth").map(A=>A.token),c=s.all.filter(A=>A.type==="api").map(A=>A.token);a.length>0&&(process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL=a.join(",")),c.length>0&&(process.env.ANTHROPIC_API_KEY_POOL=c.join(","));let l=s.file.length,f=s.env.length,N=l>0&&f>0?"local-file+shell-env":l>0?"local-file":f>0?"shell-env":"none";return Re=!0,pe={oauthCount:a.length,apiCount:c.length,source:N},e&&(a.length||c.length)&&console.log(`[credentials-loader] loaded ${a.length} OAuth + ${c.length} API from ${N} (~/.zibby/credentials.env)`),pe}function fn(){Re=!1,pe=null}var Re,pe,uo=ve(()=>{ut();Re=!1,pe=null});var gt={};ke(gt,{cleanupStalePidFiles:()=>kn,killAllChatOrchestratedRuns:()=>_n,killPidTreeBestEffort:()=>mo,registerChatOrchestratedRun:()=>bn,unregisterChatOrchestratedRun:()=>wn});import{existsSync as dt,mkdirSync as gn,readFileSync as mn,readdirSync as hn,unlinkSync as pt,writeFileSync as fo}from"fs";import{join as Ze}from"path";import{execSync as go}from"child_process";import{DEFAULT_OUTPUT_BASE as yn}from"@zibby/core";function Je(t){return t?.paths?.output||yn}function Ke(t,e,o){return Ze(t,e,`.zibby-chat-run-pids-${o}.json`)}function ft(t,e,o){let n=Ke(t,e,o);if(!dt(n))return[];try{let r=JSON.parse(mn(n,"utf8"));return(Array.isArray(r?.pids)?r.pids:[]).map(a=>Number(a)).filter(a=>Number.isFinite(a)&&a>0)}catch{return[]}}function bn(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=Je(n),c=Ze(t,a);gn(c,{recursive:!0});let l=ft(t,a,r);l.includes(s)||l.push(s),fo(Ke(t,a,r),`${JSON.stringify({v:1,pids:l})}
|
|
2
|
+
`,"utf8")}function wn(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=Je(n),c=Ke(t,a,r);if(!dt(c))return;let l=ft(t,a,r).filter(f=>f!==s);if(l.length===0)try{pt(c)}catch{}else fo(c,`${JSON.stringify({v:1,pids:l})}
|
|
3
|
+
`,"utf8")}function Sn(t){let e=Number(t);if(!Number.isFinite(e)||e<=0)return[];try{let o=go(`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 po(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 Sn(s))r(a);try{process.kill(s,e)}catch{}}}r(o)}function xn(t){let e=Number(t);if(!(!Number.isFinite(e)||e<=0))try{go(`taskkill /PID ${e} /T /F`,{stdio:"ignore",windowsHide:!0})}catch{}}function mo(t){let e=Number(t);if(!Number.isFinite(e)||e<=0)return;if(process.platform==="win32"){xn(e);return}po(e,"SIGTERM");let o=setTimeout(()=>{po(e,"SIGKILL")},800);typeof o.unref=="function"&&o.unref()}function _n(t,e,o={}){let n=Number(e);if(!Number.isFinite(n)||n<=0)return;let r=Je(o),s=Ke(t,r,n),a=ft(t,r,n);for(let c of a)c!==process.pid&&mo(c);try{dt(s)&&pt(s)}catch{}}function $n(t){try{return process.kill(t,0),!0}catch{return!1}}function kn(t,e={}){let o=Je(e),n=Ze(t,o),r;try{r=hn(n)}catch{return}for(let s of r){let a=vn.exec(s);if(!a)continue;let c=Number(a[1]);if(!(!Number.isFinite(c)||c<=0)&&!$n(c))try{pt(Ze(n,s))}catch{}}}var vn,mt=ve(()=>{vn=/^\.zibby-chat-run-pids-(\d+)\.json$/});var yo={};ke(yo,{addCredential:()=>ho,deleteCredential:()=>Cn,listCredentials:()=>An,syncFromLocal:()=>In});function ht(t,e=""){return`${String(t).replace(/\/+$/,"")}/agents/credentials${e}`}function yt(){let t=new Error("Session expired \u2014 run zibby login");return t.code="AUTH_EXPIRED",t}async function An({apiUrl:t,sessionToken:e}){if(!e)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let o=await fetch(ht(t),{headers:{Authorization:`Bearer ${e}`}});if(o.status===401)throw yt();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 ho({apiUrl:t,sessionToken:e,type:o,token:n,source:r="~/.zibby/credentials.env"}){if(!e)throw new Error("No session token \u2014 run zibby login first");let s=await fetch(ht(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 yt();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 Cn({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(ht(t,`/${encodeURIComponent(o)}/${encodeURIComponent(n)}`),{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(r.status===401)throw yt();if(!r.ok){let s=new Error(`Delete credential failed (${r.status})`);throw s.status=r.status,s}return r.json()}async function In({apiUrl:t,sessionToken:e,credentials:o}){let n=0,r=0,s=[];for(let a of o)try{let c=await ho({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 bo=ve(()=>{});var $o={};ke($o,{AGENTS:()=>Le,deleteAgentSession:()=>Ln,fetchMyAgentSessions:()=>xo,formatRelativeTime:()=>_o,handleClaudeCodeAddon:()=>En,pickAgent:()=>Pn,pickAgentWithSessions:()=>Tn,upsertAgentSession:()=>Rn});import{select as So,confirm as bt,Separator as wo}from"@inquirer/prompts";import u from"chalk";async function Tn({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(A=>A.id===s.agent_type)?.name||s.agent_type,l=_o(s.last_active),f=typeof s.message_count=="number"&&s.message_count>0?u.gray(` \xB7 ${s.message_count} msg`):"",N=s.label?u.gray(` \xB7 "${s.label}"`):"";r.push({name:`${u.cyan("\u2726")} ${c} ${u.gray(`(${l})`)}${N}${f}`,value:{action:"resume",agentType:s.agent_type,sessionId:s.session_id,session:s},description:u.gray(` Resume your ${c} session`)})}r.push(new wo)}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 wo),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 Pn(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 En({workspaceId:t,sessionToken:e,apiUrl:o}){let n=await On({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/credentials.env)")),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 bt({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 bt({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 Un({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 Nn({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 Nn({apiUrl:t,sessionToken:e}){let o;try{let{discoverCredentials:s}=await Promise.resolve().then(()=>(ut(),co));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. Create ~/.zibby/credentials.env with:")),console.log(u.gray(" CLAUDE_CODE_OAUTH_TOKEN=<your-token>")),console.log(u.gray(" 2. Run: zibby creds sync")),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==="file"?`~/.zibby/credentials.env (${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 bt({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(()=>(bo(),yo)),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 On({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 Un({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 f=new Error(l.message||"Payment required");throw f.code="BILLING_REQUIRED",f.status=402,f.needsSubscription=!!l.needs_subscription,f.needsPaymentMethod=!!l.needs_payment_method,f.upgradeUrl=l.upgrade_url||"/billing",f}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 wt(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(wt(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 Rn({apiUrl:t,sessionToken:e,agentType:o,fields:n={}}){if(!e)throw new Error("Not authenticated");let r=await fetch(wt(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 Ln({apiUrl:t,sessionToken:e,agentType:o}){if(!e)throw new Error("Not authenticated");let n=await fetch(wt(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,vo=ve(()=>{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 St={};ke(St,{attachToSession:()=>Io,spawnAgentSession:()=>Co,spawnAndAttach:()=>Mn});import ko from"ws";import Ao from"chalk";function Bn({sandboxEndpoint:t,sessionId:e,useTls:o=!1}){return`${o?"wss":"ws"}://${t}/stream/${encodeURIComponent(e)}`}async function Co({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 N=await l.text().catch(()=>"");throw new Error(`spawn failed (${l.status}): ${N}`)}return await l.json()}async function Io({sandboxEndpoint:t,sessionId:e,sessionToken:o,useTls:n=!1,showBanner:r=!0}){let s=Bn({sandboxEndpoint:t,sessionId:e,useTls:n}),a=new ko(s,{headers:{Authorization:`Bearer ${o}`}});return new Promise((c,l)=>{let f=!1,N=!1,A=null,Y=null,J=v=>{if(!f){f=!0;try{process.stdin.isTTY&&process.stdin.setRawMode&&process.stdin.setRawMode(N)}catch{}A&&process.stdin.off("data",A),Y&&process.stdout.off("resize",Y);try{process.stdin.pause()}catch{}try{a.close()}catch{}c(v)}};a.on("open",()=>{r&&(process.stdout.write(Ao.green(`
|
|
4
|
+
\u2713 Connected to cloud sandbox session ${e}
|
|
5
|
+
`)),process.stdout.write(Ao.gray(` Press Ctrl+\\ to detach (session keeps running).
|
|
4
6
|
|
|
5
|
-
|
|
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 v=()=>{let B=process.stdout.columns||80,M=process.stdout.rows||24;try{a.send(JSON.stringify({type:"resize",cols:B,rows:M}))}catch{}};v(),Y=()=>v(),process.stdout.on("resize",Y),process.stdin.isTTY&&process.stdin.setRawMode&&(N=!!process.stdin.isRaw,process.stdin.setRawMode(!0)),process.stdin.resume();try{process.stdin.setEncoding("utf8")}catch{}A=B=>{let M=B.toString("utf8");if(M.includes("")){J({reason:"detach"});return}try{a.send(M)}catch{}},process.stdin.on("data",A)}),a.on("message",v=>{let B=v.toString("utf8");if(B.startsWith("{")&&B.endsWith("}"))try{let M=JSON.parse(B);if(M&&M.type==="exit"){J({reason:"remote-exit",exitCode:M.exitCode,signal:M.signal});return}}catch{}try{process.stdout.write(B)}catch{}}),a.on("close",()=>{J({reason:"remote-close"})}),a.on("error",v=>{f||J({reason:"ws-error",message:v?.message||String(v)})}),setTimeout(()=>{if(a.readyState===ko.CONNECTING){try{a.terminate()}catch{}f||(f=!0,l(new Error("WS connect timed out after 30s")))}},3e4).unref()})}async function Mn({sandboxEndpoint:t,sessionToken:e,agentType:o,args:n,cwd:r,useTls:s}){let a=await Co({sandboxEndpoint:t,sessionToken:e,agentType:o,args:n,cwd:r,useTls:s});return{...await Io({sandboxEndpoint:t,sessionId:a.session_id,sessionToken:e,useTls:s}),sessionId:a.session_id}}var xt=ve(()=>{});import{invokeAgent as Dn,getAgentStrategy as zn}from"@zibby/core";import{getSkill as Be}from"@zibby/skills";import{existsSync as Ae,readFileSync as Ro,readdirSync as Fn}from"fs";import{resolve as he,join as $t,dirname as jn,basename as Yn}from"path";import{createInterface as Hn,moveCursor as F,cursorTo as Z,clearLine as Q,emitKeypressEvents as Wn}from"readline";import{fileURLToPath as Zn}from"url";import{homedir as Jn}from"os";import i from"chalk";import{highlight as To}from"cli-highlight";import Kn from"dotenv";import{existsSync as Bt,mkdirSync as qo,readFileSync as Go,writeFileSync as Vo}from"fs";import{homedir as Mt}from"os";import{join as Ye}from"path";function Dt(){return process.env.ZIBBY_CONFIG_DIR||Ye(Mt(),".zibby")}function zt(){return Ye(Dt(),"config.json")}var Xo=Ye(Mt(),".zibby"),Ns=Ye(Xo,"config.json");function Qo(){let t=Dt();Bt(t)||qo(t,{recursive:!0})}function se(){try{let t=zt();if(Bt(t)){let e=Go(t,"utf-8");return JSON.parse(e)}}catch{}return{}}function Pe(t){Qo(),Vo(zt(),JSON.stringify(t,null,2))}function He(){return se().sessionToken||null}function Ft(t){let e=se();e.sessionToken=t,Pe(e)}function jt(){return se().user||null}function Yt(t){let e=se();e.user=t,Pe(e)}function Ht(){let t=se();delete t.sessionToken,delete t.user,delete t.mem0ProxyUrl,Pe(t)}function Wt(){return se().proxyUrl||null}function Zt(t){let e=se();e.proxyUrl=t,Pe(e)}function Jt(){return se().mem0ProxyUrl||null}function Kt(t){let e=se();e.mem0ProxyUrl=t,Pe(e)}function qt(){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 en,readFileSync as Gt,writeFileSync as Vt,unlinkSync as Ls}from"fs";import{resolve as Ne}from"path";import{homedir as Ds}from"os";var tn=30;function Xt(t){let e=Ne(t,".zibby","output");return at(e)||en(e,{recursive:!0}),e}function Qt(t){let e=Ne(t,".zibby","output","chat-history.json");if(!at(e))return[];try{let o=JSON.parse(Gt(e,"utf-8"));return Array.isArray(o)?o:[]}catch{return[]}}function Oe(t,e){let o=Xt(t),n=Ne(o,"chat-history.json");try{Vt(n,JSON.stringify((e||[]).slice(-tn*2),null,2),"utf-8")}catch{}}function eo(t){let e=Ne(t,".zibby","output","active-skills.json");if(!at(e))return null;try{let o=JSON.parse(Gt(e,"utf-8"));return Array.isArray(o)?o:null}catch{return null}}function Ue(t,e){let o=Xt(t),n=Ne(o,"active-skills.json");try{Vt(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:{}}},oo=2e3,to=12e3;function We(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 on(t,e=oo){let o=String(t||"");return o.length<=e?o:`${o.slice(0,Math.max(0,e-14)).trimEnd()}
|
|
7
8
|
|
|
8
|
-
`)
|
|
9
|
+
[truncated]`}function me(t,e=[],o=oo){let n=We(e);if(n.length===0)return"";let r=[`## ${t}`,...n.map(s=>`- ${s}`)].join(`
|
|
10
|
+
`);return on(r,o)}function nn(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function sn(t,e){let o={...t,...e},n=["operatingRules","rules","executionSafety","investigationLoop","responseQuality","incidentTemplate"];for(let r of n)Array.isArray(e?.[r])?o[r]=[...We(t?.[r]||[]),...We(e[r])]:Array.isArray(t?.[r])&&(o[r]=[...We(t[r])]);return o.skillRunbooks={...t?.skillRunbooks||{},...e?.skillRunbooks||{}},o}function rn(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 an(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=nn(n),a=s?sn(r,s):r;return{name:o,defaults:a}}function no({activeSkills:t=[],chatConfig:e={},options:o={}}={}){let n=an(e,o);if(n.text)return n.text;let r=n.defaults||ct.cli_reliable_v1,s=[me(r.title||"Reliability contract",r.operatingRules||r.rules||[]),me("Execution safety",r.executionSafety||[]),me("Investigation loop",r.investigationLoop||[]),me("Response quality",r.responseQuality||[]),me("Failure reporting format",r.incidentTemplate||[])],a=r.skillRunbooks||{};for(let f of t)a[f]&&s.push(me(`Runbook: ${f}`,a[f]));let c=rn(e,o);for(let f of c)s.push(me(f.title,f.lines));let l=s.filter(Boolean).join(`
|
|
9
11
|
|
|
10
|
-
|
|
11
|
-
`)}function as(e,t,n){let s=e;return t.length>0&&(s+=`
|
|
12
|
+
`).trim();return l.length<=to?l:`${l.slice(0,Math.max(0,to-14)).trimEnd()}
|
|
12
13
|
|
|
13
|
-
${
|
|
14
|
-
|
|
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 qn=Zn(import.meta.url),Gn=jn(qn),Vn=JSON.parse(Ro($t(Gn,"../../package.json"),"utf-8")),Lo=30,Xn=54,Qn=18e3,Bo=12e3,Po=42e3;function es(t){return new Promise(e=>setTimeout(e,t))}var qe=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],kt=[{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 Eo(){let t=0,e="thinking...",o=setInterval(()=>{let r=i.cyan(qe[t%qe.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 gr(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 ts(t){return t.slice(-Lo).map(e=>`${e.role==="human"?"H":"AI"}: ${e.content}`).join(`
|
|
15
|
+
`)}function mr(t,e,o){let n=t;return e.length>0&&(n+=`
|
|
16
16
|
|
|
17
|
-
${
|
|
17
|
+
${ts(e)}`),n+=`
|
|
18
|
+
H: ${o}
|
|
19
|
+
AI:`,n}function os(t){let e=t.filter(o=>!process.env[o]);return{ok:e.length===0,missing:e}}function ns(t){let e=he(t,".zibby.config.mjs");if(!Ae(e))return{};try{return import(e).then(o=>o.default||{})}catch{return{}}}async function ss(t){let e=he(t,".zibby","chat.mjs");if(Ae(e)){let r=await import(e);if(r.CHAT_CONFIG||r.default)return r.CHAT_CONFIG||r.default}let o=he(Jn(),".zibby","chat.mjs");if(o!==e&&Ae(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=he(t,".zibby","commands");return Ae(e)?Fn(e).filter(o=>o.toLowerCase().endsWith(".md")).sort((o,n)=>o.localeCompare(n)):[]}catch{return[]}}function rs(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=he(t,".zibby","commands"),f=c.find(N=>Ae($t(l,N)));if(!f)return o;try{let N=Ro($t(l,f),"utf-8").trim();return s?`${N}
|
|
18
20
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
`),e.
|
|
27
|
-
${
|
|
28
|
-
`),
|
|
29
|
-
|
|
30
|
-
`);
|
|
31
|
-
`)
|
|
32
|
-
`);
|
|
33
|
-
|
|
34
|
-
`));let
|
|
35
|
-
${
|
|
36
|
-
`))
|
|
21
|
+
${s}`:N}catch{return o}}function is(t){let e=t.slice(-Lo),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>Qn)break;o.push({role:c,content:a}),n+=l}return o.reverse()}function Me(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 vt(t){return t.reduce((e,o)=>e+String(o?.content||"").length+64,0)}function as(t){let e=[...t];if(e.length===0||(e[0]?.role==="system"&&(e[0]={...e[0],content:Me(e[0].content,Bo)}),vt(e)<=Po))return e;let o=e[0],n=e[e.length-1],r=e.slice(1,-1).slice(-4).map(s=>({...s,content:Me(s.content,2500)}));return e=[o,...r,n],vt(e)<=Po||(e=[{...o,content:Me(o?.content,6e3)},{...n,content:Me(n?.content,8e3)}]),e}function cs(t){let e=[];for(let o of t){let n=Be(o),r=String(n?.description||"").trim();if(!r){e.push(`- ${o}`);continue}e.push(`- ${o}: ${Ge(r,80)}`)}return e.length===0?"":`## Active skills (call get_skill_context before first use)
|
|
24
|
+
${e.join(`
|
|
25
|
+
`)}`}var Oo={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 ls(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():Oo[o]||Oo.cli_plain}function Ge(t,e){let o=String(t??"");return o.length<=e?o:e<=1?o.slice(0,e):`${o.slice(0,e-1)}\u2026`}function us(){return!1}function ds(t){let e=/^```(\w*)\n([\s\S]*?)^```$/gm;return t.replace(e,(o,n,r)=>{let s=r.replace(/\n$/,"");try{let a=n?To(s,{language:n,ignoreIllegals:!0}):To(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):Xn;return` ${"\u2500".repeat(e)}`}function Uo(t=[]){let e=kt.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 ps(t,e){let o=String(t||""),n=Number.isFinite(e)?e:o.length;return!(!o.startsWith("/")||n!==o.length||o.includes(" "))}function fs({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,f=t||"there",N=o||"No project linked",A=Yn(e||process.cwd()),Y=[`Restored ${n} messages from previous session.`,"",r],J=["Workspace details","",`v${Vn.version} | Hi, ${f}`,`Company: ${N}`,`Directory: ~/${A}`,`Path: ${e}`,"","Use /help for commands"],v=Math.max(Y.length,J.length),B=(()=>{if(Y.length>=v)return Y;let H=Math.floor((v-Y.length)/2),ue=v-Y.length-H;return[...Array(H).fill(""),...Y,...Array(ue).fill("")]})(),M="\u2500",ye=` \u250C${M.repeat(c+2)}\u252C${M.repeat(l+2)}\u2510`,L=` \u2514${M.repeat(c+2)}\u2534${M.repeat(l+2)}\u2518`;console.log(i.gray(ye));for(let H=0;H<v;H++){let ue=Ge(B[H]||"",c),be=Ge(J[H]||"",l),we=" ".repeat(Math.max(0,c-ue.length)),S=" ".repeat(Math.max(0,l-be.length)),C=` \u2502 ${ue}${we} \u2502 ${be}${S} \u2502`;console.log(i.gray(C))}console.log(i.gray(L)),console.log("")}function gs(){process.stdout?.isTTY&&(F(process.stdout,0,-2),Z(process.stdout,4))}function ms(t){let e=!!(process.stdout?.isTTY&&process.stdin?.isTTY),o=!1,n=!1,r=!1,s=null,a=0,c=0,l=0;function f(){return i.gray(_t())}function N(){s&&(clearInterval(s),s=null)}function A(S){!e||!o||!n||!r||(process.stdout.write("\x1B7"),F(process.stdout,0,-2),Z(process.stdout,0),Q(process.stdout,0),process.stdout.write(` ${S}`),process.stdout.write("\x1B8"))}function Y(){if(!(!e||!o)&&c!==0){process.stdout.write("\x1B7"),F(process.stdout,0,2);for(let S=0;S<c;S++)Z(process.stdout,0),Q(process.stdout,0),S<c-1&&F(process.stdout,0,1);process.stdout.write("\x1B8"),c=0,n&&J()}}function J(){!e||!o||!n||(process.stdout.write("\x1B7"),F(process.stdout,0,1),Z(process.stdout,0),Q(process.stdout,0),process.stdout.write(f()),process.stdout.write("\x1B8"))}function v(S,C){if(!e||!o||!n)return;Y();let I=S.slice(0,6);if(I.length!==0){F(process.stdout,0,1);for(let b=0;b<I.length;b++)process.stdout.write(`
|
|
29
|
+
`);F(process.stdout,0,-(1+I.length)),process.stdout.write("\x1B7"),F(process.stdout,0,2);for(let b=0;b<I.length;b++){Z(process.stdout,0),Q(process.stdout,0);let ee=b===C?i.cyan("\u203A"):" ",te=b===C?i.white(I[b]):i.gray(I[b]);process.stdout.write(` ${ee} /${te}`),b<I.length-1&&F(process.stdout,0,1)}process.stdout.write("\x1B8"),c=I.length,J()}}function B(){if(!e||!o||!n)return;Y();let S=process.stdout.columns||80,C=l>0?Math.ceil(l/S):1;Z(process.stdout,0),F(process.stdout,0,-C),r&&F(process.stdout,0,-2),process.stdout.write("\x1B[J"),n=!1}function M(S={}){let C=S.preserveInput===!0;if(!e){t.prompt();return}C||(t.line="",t.cursor=0),l=_t().length;let I=f();process.stdout.write(`${I}
|
|
30
|
+
`),t.prompt(),process.stdout.write(`
|
|
31
|
+
${I}
|
|
32
|
+
`),gs(),n=!0}function ye(){if(!e||!o||!n)return;let S=process.stdout.columns||80,C=l>0?Math.ceil(l/S):1,I=f();process.stdout.write("\x1B7"),F(process.stdout,0,-C);for(let b=0;b<C;b++)Z(process.stdout,0),Q(process.stdout,0),b<C-1&&F(process.stdout,0,1);Z(process.stdout,0),process.stdout.write(I),F(process.stdout,0,2),Z(process.stdout,0),Q(process.stdout,0),process.stdout.write(I);for(let b=1;b<C;b++)F(process.stdout,0,1),Z(process.stdout,0),Q(process.stdout,0);process.stdout.write("\x1B8"),l=_t().length}function L(){if(!e||!o||!n)return;let S=(()=>{if(typeof t.getCursorPos!="function")return 0;try{return Math.max(0,Number(t.getCursorPos()?.rows||0))}catch{return 0}})();process.stdout.write("\x1B7"),F(process.stdout,0,-(S+1)),Z(process.stdout,0),Q(process.stdout,0),process.stdout.write(f()),F(process.stdout,0,S+2),Z(process.stdout,0),Q(process.stdout,0),process.stdout.write(f()),process.stdout.write("\x1B8")}function H(S){N(),B(),console.log();let C=String(S??"").replace(/\r/g,"").split(`
|
|
33
|
+
`);for(;C.length>0&&C[C.length-1]==="";)C.pop();for(let I of C)console.log(I?` ${I}`:"");r=!1}function ue(S){let C=String(S??"").replace(/\r/g,"").split(`
|
|
34
|
+
`);C.length===0&&C.push("");let I=[];for(let b of C)I.push(i.bgGray.white(` ${b||" "} `));return I.join(`
|
|
35
|
+
`)}function be(){N();let S=()=>i.gray(`${qe[a%qe.length]} thinking`);if(!e){console.log(` ${S()}`),r=!0;return}Y(),B(),console.log(),console.log(` ${S()}`),M({preserveInput:!0}),r=!0,a+=1,s=setInterval(()=>{r&&(A(S()),a+=1)},120)}function we(S){N();let C=String(S??"").replace(/\r/g,"").replace(/⎿/g,"");if(!r){H(C);return}B(),console.log();let I=C.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,M()}},refreshPrompt(S={}){if(e&&o){n&&B(),M(S);return}t.prompt()},pushSystem(S){H(S)},pushUser(S){H(ue(S))},pushAssistant(S){we(S)},showAssistantLoading:be,dismissTransientLoading(){N(),r&&e&&o&&n&&(process.stdout.write("\x1B7"),F(process.stdout,0,-2),Z(process.stdout,0),Q(process.stdout,0),F(process.stdout,0,-1),Z(process.stdout,0),Q(process.stdout,0),process.stdout.write("\x1B8")),r=!1},touchInputFrame:L,handleResize:ye,showCommandDropdown:v,clearCommandDropdown:Y}}function hs(){console.log(""),console.log(i.cyan(" Available commands:"));for(let t of kt)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 ys=os;async function hr(t={}){let e=process.cwd();t.verbose&&(process.env.ZIBBY_VERBOSE="true");let o=t.stream||!1;[he(e,".env.local"),he(e,".env")].forEach(b=>{Ae(b)&&Kn.config({path:b,override:!1})});try{let{loadCredentialsIntoEnv:b}=await Promise.resolve().then(()=>(uo(),lo));await b({verbose:!!process.env.ZIBBY_DEBUG})}catch{}try{await import("@zibby/skills")}catch{}function r(){let b=He();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()){Ht();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:k,verificationUrl:d,expiresIn:W,interval:re}=await te.json(),K=process.platform;ee(K==="darwin"?"open":K==="win32"?"cmd":"xdg-open",K==="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 fe=Eo();fe.setLabel("waiting for authorization");let Se=(re||3)*1e3,xe=Math.floor(W/(re||3)),ie=!1;for(let de=0;de<xe;de++){await es(Se);try{let ae=await fetch(`${b}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:k})});if(ae.status===202)continue;if(!ae.ok)break;let G=await ae.json();if(G.status==="authorized"){Ft(G.token),Yt(G.user),G.proxyUrl&&Zt(G.proxyUrl),G.mem0ProxyUrl&&Kt(G.mem0ProxyUrl),ie=!0;break}if(G.status==="denied")break}catch{break}}fe(),ie||(console.log(i.red("\n Login failed or timed out. Run `zibby login` to try again.\n")),process.exit(1))}let s=await ns(e),a=await ss(e),c=t.agent||"assistant",l=He();l&&!process.env.ZIBBY_USER_TOKEN&&(process.env.ZIBBY_USER_TOKEN=l);let f=Jt()||Wt();f&&!process.env.ZIBBY_MEM0_OPENAI_BASE_URL&&(process.env.ZIBBY_MEM0_OPENAI_BASE_URL=f),process.env.AGENT_TYPE=c,process.env.ZIBBY_CHAT_OWNER_PID=String(process.pid);try{let{cleanupStalePidFiles:b}=await Promise.resolve().then(()=>(mt(),gt));b(e,s)}catch{}let N;try{N=zn({state:{agentType:c}})}catch(b){console.log(i.red(`
|
|
39
|
+
${b.message}
|
|
40
|
+
`)),process.exit(1)}let A=jt(),J=qt()?.[0]?.name,v=Qt(e),B="zibby",M=a.skills||[],ye=eo(e),L=ye?[...new Set([...M,...ye])]:[...M],H={data:null,timestamp:0},ue=300*1e3,be={jira:"jira",github:"github",slack:"slack",sentry:"sentry"};try{let b=He();if(b){let ee=le(),te=await fetch(`${ee}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${b}`}});if(te.ok){let k=await te.json();for(let[d,W]of Object.entries(be)){let re=k[d]?.connected,K=L.indexOf(W),Ve=Be(W);re&&K===-1&&Ve?L.push(W):!re&&K!==-1&&L.splice(K,1)}Ue(e,L)}}}catch{}let we=L.filter(b=>b!=="skill-installer"&&b!=="core-tools"),S=we.length>0?`Skills: ${we.join(", ")}`:"Skills: (none)";fs({userName:A?.name?.split(" ")[0],cwd:e,projectName:J,restoredCount:v.length,skillsLine:S});let C=No(e),I=Uo(C);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=x=>{let g=String(x||"");if(!g.startsWith("/"))return[[],g];let $=I.map(R=>R.cmd),P=$.filter(R=>R.startsWith(g));return[P.length>0?P:$,g]});let k=Hn(te),d=ms(k),W=null,re=!1,K=[],Ve=0,Mo=1200,fe=!1,Se=!1,xe=!1,ie=!1,de="",ae=0,G=typeof k._ttyWrite=="function"?k._ttyWrite.bind(k):null;G&&(k._ttyWrite=(...x)=>{if(!(ie||Date.now()<ae))return G(...x)});function Do(){xe||!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004h"),xe=!0)}function At(){xe&&(!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004l"),xe=!1))}function zo(x){let g="\x1B[200~",$="\x1B[201~";if(!ie&&!x.includes(g))return!1;let P=x,R=!1;for(;P.length>0;){if(!ie){let U=P.indexOf(g);if(U===-1)break;R=!0,Pt(),ie=!0,de="",P=P.slice(U+g.length);continue}let V=P.indexOf($);if(V===-1){R=!0,de+=P;break}R=!0,de+=P.slice(0,V);let ce=String(de||"").replace(/\r\n/g,`
|
|
37
41
|
`).replace(/\r/g,`
|
|
38
|
-
`);if(
|
|
39
|
-
`);for(let
|
|
40
|
-
`)
|
|
41
|
-
|
|
42
|
-
`,
|
|
43
|
-
`);
|
|
44
|
-
|
|
45
|
-
|
|
42
|
+
`);if(ce.length>0){let U=ce.split(`
|
|
43
|
+
`);for(let oe of U)nt(oe)}ze(),de="",ie=!1,P=P.slice(V+$.length)}return R}function Ct(){if(!fe){fe=!0;try{Oe(e,v),Ue(e,L)}catch{}try{At()}catch{}try{k.close()}catch{}process.exit(0)}}async function Xe(){if(!fe){fe=!0,typeof N?.cleanup=="function"&&await N.cleanup().catch(()=>{});try{let{killAllChatOrchestratedRuns:x}=await Promise.resolve().then(()=>(mt(),gt)),{postCliInterruptedRunIndex:g}=await import("@zibby/core/utils/run-index-post-cli.js");x(e,process.pid,s),g({cwd:e,config:s})}catch{}Oe(e,v),Ue(e,L),d.pushSystem(i.gray("Session saved. Goodbye!")),At(),k.close(),process.exit(0)}}if(d.mount(),Do(),process.stdout?.isTTY){let x;process.stdout.on("resize",()=>{clearTimeout(x),x=setTimeout(()=>{d.handleResize()},80)})}let Qe=0,De=x=>{if(typeof x=="string"?x==="\x1B":x&&typeof x.length=="number"?x.length===1&&x[0]===27:!1){W&&W.abort(),Ct();return}let $=typeof x=="string"?x:x&&typeof x.length=="number"?Buffer.from(x).toString("utf8"):"";if(!$)return;if(zo($)){Qe=Date.now()+1200,ae=Date.now()+1200,ot();return}let P=($.includes(`
|
|
44
|
+
`)||$.includes("\r"))&&$!=="\r"&&$!==`
|
|
45
|
+
`&&$!==`\r
|
|
46
|
+
`,R=$.includes("\x1B[200~")||$.includes("\x1B[201~"),V=$.length>=16&&/\s/.test($)&&!$.startsWith("\x1B");(P||R||V)&&(Qe=Date.now()+1200,ae=Date.now()+1200,Pt(),ot())},j={query:"",matches:[],selected:0},q={prefix:"",matches:[],nextIndex:0},O={active:!1,prefix:"",lines:[],timer:null},et=[],It=0,tt="",Fo=new Set(kt.map(x=>x.cmd));function _e(x,{preserveFrame:g=!1}={}){let $=String(x||"");k.line=$,k.cursor=$.length,tt=$,typeof k._refreshLine=="function"?k._refreshLine():k.prompt(),g&&d.touchInputFrame()}function Tt(){q.prefix="",q.matches=[],q.nextIndex=0}function ze(){if(O.timer&&(clearTimeout(O.timer),O.timer=null),O.active&&O.lines.length>0){It+=1;let x=O.lines.length,g=`[Pasted text #${It} +${x} lines]`,$=O.lines.join(`
|
|
47
|
+
`);et.push({placeholder:g,text:$});let P=String(O.prefix||"").trimEnd(),R=P?`${P} ${g}`:g;_e(R,{preserveFrame:!0}),$e(k.line)}O.active=!1,O.prefix="",O.lines=[],ae=0}function ot(){O.timer&&clearTimeout(O.timer),O.timer=setTimeout(()=>{ze()},180)}function Pt(){O.active||(O.active=!0,O.prefix=String(tt||k.line||""),O.lines=[],_e(O.prefix,{preserveFrame:!0}))}function nt(x){return O.active?(O.lines.push(String(x||"")),_e(O.prefix,{preserveFrame:!0}),ot(),!0):!1}function jo(x){let g=String(x||"");for(let $ of et)g=g.split($.placeholder).join($.text);return g}function $e(x){let g=String(x||"");if(!g.startsWith("/")||g.includes(" ")||g.length===0){j.query="",j.matches=[],j.selected=0,d.clearCommandDropdown();return}C=No(e),I=Uo(C);let $=g.slice(1).toLowerCase(),P=C.filter(R=>R.toLowerCase().startsWith($));j.query=$,j.matches=P,j.selected=Math.min(j.selected,Math.max(0,P.length-1)),d.showCommandDropdown(P,j.selected)}let st=(x,g)=>{if(g?.name==="escape"||g?.sequence==="\x1B"){W&&W.abort(),Ct();return}if((g?.name==="return"||g?.name==="enter")&&(Se=!0),(g?.name==="backspace"||g?.name==="delete")&&d.touchInputFrame(),g?.name==="tab"&&!g?.shift){let R=String(k.line||""),V=Number(k.cursor||R.length);if(!ps(R,V)){Tt(),$e(k.line);return}let ce=R.slice(1).toLowerCase();if(q.prefix!==ce&&(q.prefix=ce,q.matches=I.map(oe=>oe.cmd).filter(oe=>oe.toLowerCase().startsWith(`/${ce}`)),q.nextIndex=0),q.matches.length===0)return;let U=q.nextIndex%q.matches.length;q.nextIndex+=1,_e(q.matches[U]),$e(k.line);return}let $=String(k.line||""),P=$.startsWith("/")&&!$.includes(" ")&&j.matches.length>0;if(g?.name==="up"||g?.name==="down"){if(!P){$e(k.line);return}let R=g.name==="up"?-1:1,V=j.matches.length;j.selected=(j.selected+R+V)%V;let ce=j.matches[j.selected];_e(`/${ce}`,{preserveFrame:!0}),d.showCommandDropdown(j.matches,j.selected);return}g?.name!=="tab"&&Tt(),setTimeout(()=>{$e(k.line),O.active||(tt=String(k.line||""))},50)};process.stdin?.on&&(Wn(process.stdin,k),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)),k.on("line",async x=>{try{let g=String(x||""),$=Se;if(Se=!1,!$&&(O.active||ie||Date.now()<Qe||Date.now()<ae)){if(O.active&&g.length>0){nt(g);return}O.active&&(ze(),d.refreshPrompt());return}if(O.active&&(ze(),g=String(k.line||g||"")),nt(g))return;let P=g.trim(),R=j.matches[j.selected];if(P.startsWith("/")&&!P.includes(" ")&&j.matches.length>0&&!Fo.has(P)&&P!==`/${R}`){d.clearCommandDropdown(),d.refreshPrompt(),_e(`/${R}`),$e(`/${R}`);return}d.clearCommandDropdown();let U=String(g||"").replace(/[\u0000-\u001F\u007F-\u009F]/g,"").trim();if(!U){d.enabled&&process.stdout?.isTTY&&(F(process.stdout,0,-1),Z(process.stdout,4));return}if(re&&U!=="/exit"&&U!=="/quit"){W&&W.abort(),K.push(U),d.pushSystem(i.gray("Processing your message...")),d.refreshPrompt({preserveInput:!0});return}let oe=1e4;if(U.length>oe){d.pushSystem(i.red(`\u26A0 Input too long (${U.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(U==="/exit"||U==="/quit"){Xe();return}if(U==="/help"){hs(),d.refreshPrompt();return}if(U==="/agents"){try{let{pickAgentWithSessions:m,handleClaudeCodeAddon:T,upsertAgentSession:_,AGENTS:E}=await Promise.resolve().then(()=>(vo(),$o));console.log("");let y=await m({apiUrl:le(),sessionToken:l,currentAgentId:B});if(y.action==="cancel"){console.log(i.gray(" Cancelled.")),console.log(""),d.refreshPrompt();return}if(y.action==="switch"&&y.agentType==="zibby"){B==="zibby"?console.log(i.gray(" Already using Zibby Chat.")):(B="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),p=y.session?.sandbox_endpoint||process.env.ZIBBY_SANDBOX_ENDPOINT||null;if(!p||!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(()=>(xt(),St)),D=/^https/.test(le()),z=await h({sandboxEndpoint:p,sessionId:y.sessionId,sessionToken:l,useTls:D});z.reason==="detach"?console.log(i.gray(`
|
|
48
|
+
Detached from ${w?.name}. Session continues running in the cloud.`)):z.reason==="remote-exit"?console.log(i.gray(`
|
|
49
|
+
${w?.name} session exited (code ${z.exitCode??"?"}).`)):z.reason==="ws-error"&&console.log(i.red(`
|
|
50
|
+
Connection error: ${z.message}`))}catch(h){console.log(i.red(` Attach failed: ${h.message}`))}console.log(""),d.refreshPrompt();return}if(y.action==="create"){let w=E.find(p=>p.id===y.agentType);if(y.agentType==="claude-code"){let p=await T({workspaceId:A?.account_id||"workspace-default",sessionToken:l,apiUrl:le()});if(!p.cancelled){if(p.ready||p.provisioning){try{await _({apiUrl:le(),sessionToken:l,agentType:"claude-code",fields:{sandbox_id:p.sandboxId,workspace_id:A?.account_id}})}catch(D){console.warn(i.gray(` (could not save session metadata: ${D.message})`))}let h=p.sandboxEndpoint||process.env.ZIBBY_SANDBOX_ENDPOINT||null;if(p.ready&&h)try{let{spawnAndAttach:D}=await Promise.resolve().then(()=>(xt(),St)),z=/^https/.test(le()),X=await D({sandboxEndpoint:h,sessionToken:l,agentType:"claude-code",useTls:z});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 B="claude-code",console.log(i.green(p.ready?` \u2713 Active agent: ${w.name}`:` Provisioning ${w.name} \u2014 re-run /agents in ~30s when ready`));console.log("")}}}else{try{await _({apiUrl:le(),sessionToken:l,agentType:y.agentType,fields:{workspace_id:A?.account_id}})}catch(p){console.warn(i.gray(` (could not save session metadata: ${p.message})`))}B=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(U==="/skills"){let T=Be("skill-installer")?.catalog||{},_=L.filter(y=>y!=="skill-installer");console.log(i.cyan(`
|
|
54
|
+
Active skills:`)),_.length===0&&console.log(i.gray(" (none)"));for(let y of _){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],p=w.envKeys?.length>0?ys(w.envKeys).ok?i.green(" \u2713 configured"):i.yellow(` \u26A0 needs: ${w.envKeys.join(", ")}`):"";console.log(i.white(` - ${y}`)+i.gray(` \u2014 ${w.description}`)+p)}}console.log(i.gray(`
|
|
46
56
|
Just ask to install: "connect to Jira", "add GitHub", etc.
|
|
47
|
-
`)),
|
|
57
|
+
`)),d.refreshPrompt();return}if(U.startsWith("/history")){if(v.length===0)console.log(i.gray(`
|
|
48
58
|
No conversation history.
|
|
49
|
-
`));else{let
|
|
50
|
-
Showing ${
|
|
51
|
-
`));for(let
|
|
59
|
+
`));else{let m=U.split(/\s+/).slice(1),T=m.includes("--all"),_=m.indexOf("-n"),E=_>=0&&m[_+1]?parseInt(m[_+1],10):NaN,y=T?v.length:isNaN(E)?10:E,w=v.slice(-y);console.log(i.gray(`
|
|
60
|
+
Showing ${w.length} of ${v.length} messages${T?" (all)":""}:
|
|
61
|
+
`));for(let p of w){let h=p.role==="human"?i.green(" You"):i.cyan(" Zibby"),D=T||E>10?500:100,z=p.content.length>D?`${p.content.substring(0,D)}...`:p.content;console.log(`${h}: ${i.white(z)}`)}console.log("")}d.refreshPrompt();return}if(U==="/clear"){v.length=0,Oe(e,v),console.log(i.gray(`
|
|
52
62
|
History cleared.
|
|
53
|
-
`)),
|
|
63
|
+
`)),d.refreshPrompt();return}if(U.startsWith("/memory")){let m=L.includes("chat-memory")?Be("chat-memory"):null;if(!m?.handleToolCall){console.log(i.yellow(`
|
|
54
64
|
Chat memory not active. Install with: "add chat memory"
|
|
55
|
-
`)),
|
|
56
|
-
Stored memories (${
|
|
57
|
-
`)),
|
|
58
|
-
`));else{for(let
|
|
59
|
-
Task history (${
|
|
60
|
-
`)),
|
|
61
|
-
`));else{for(let
|
|
62
|
-
Recent sessions (${
|
|
63
|
-
`)),!
|
|
64
|
-
`));else{for(let
|
|
65
|
+
`)),d.refreshPrompt();return}let T=U.split(/\s+/).slice(1),_=T[0]||"brief",E={options:{workspace:e}};try{if(_==="facts"||_==="all"){let y=parseInt(T[1],10)||30,w=await m.handleToolCall("memory_recall",{limit:y},E),p=JSON.parse(w);if(console.log(i.cyan(`
|
|
66
|
+
Stored memories (${p.total}):
|
|
67
|
+
`)),p.total===0)console.log(i.gray(` (empty \u2014 memories are saved as the agent learns things)
|
|
68
|
+
`));else{for(let h of p.memories){let D=i.yellow(`[${h.category}]`),z=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)}${z}${Te}`)}console.log("")}}else if(_==="tasks"){let y=parseInt(T[1],10)||20,w=await m.handleToolCall("task_history",{limit:y},E),p=JSON.parse(w);if(console.log(i.cyan(`
|
|
69
|
+
Task history (${p.total}):
|
|
70
|
+
`)),p.total===0)console.log(i.gray(` (no tasks logged yet)
|
|
71
|
+
`));else{for(let h of p.tasks){let D=h.status==="passed"?i.green("\u2713"):h.status==="failed"?i.red("\u2717"):i.yellow("\u25CB"),z=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}${z} ${i.white(h.title)}${Te}`)}console.log("")}}else if(_==="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 p of w.recentSessions){let h=p.tickets?i.magenta(` [${p.tickets}]`):"",D=p.tasks_run>0?i.gray(` \u2014 ${p.tasks_run} tasks (${p.tasks_passed} passed, ${p.tasks_failed} failed)`):"",z=p.created_at?i.gray(` ${p.created_at.split("T")[0]}`):"";if(console.log(` ${i.white(p.summary)}${h}${D}${z}`),p.key_facts)for(let X of p.key_facts.split(";").map(Te=>Te.trim()).filter(Boolean))console.log(i.gray(` \u2192 ${X}`))}console.log("")}}else if(_==="search"){let y=T.slice(1).join(" ");if(!y)console.log(i.yellow(`
|
|
65
75
|
Usage: /memory search <keyword>
|
|
66
|
-
`));else{let
|
|
67
|
-
Search "${
|
|
68
|
-
`));for(let
|
|
76
|
+
`));else{let w=await m.handleToolCall("memory_recall",{query:y,limit:20},E),p=JSON.parse(w);console.log(i.cyan(`
|
|
77
|
+
Search "${y}" \u2014 ${p.total} results:
|
|
78
|
+
`));for(let h of p.memories){let D=i.yellow(`[${h.category}]`),z=h.ticket_key?i.magenta(` ${h.ticket_key}`):"";console.log(` ${D}${z} ${i.white(h.content)}`)}p.total===0&&console.log(i.gray(" (no matches)")),console.log("")}}else{let y=await m.handleToolCall("memory_brief",{},E),w=JSON.parse(y),p=w.topMemories?.length||0,h=w.recentSessions?.length||0,D=(w.taskStats||[]).map(z=>`${z.type}:${z.status}=${z.cnt}`).join(", ");console.log(i.cyan(`
|
|
69
79
|
Memory overview:
|
|
70
|
-
`)),console.log(
|
|
71
|
-
Subcommands:`)),console.log(
|
|
72
|
-
Memory error: ${
|
|
73
|
-
`))}
|
|
80
|
+
`)),console.log(i.white(` Facts stored: ${p>0?i.cyan(p):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&&(F(process.stdout,0,-1),Z(process.stdout,0)),d.pushUser(U),d.refreshPrompt(),d.showAssistantLoading();let Et=jo(U),Fe=rs(e,Et);if(et.length=0,!String(Fe||"").trim()){d.dismissTransientLoading(),d.refreshPrompt();return}if(Fe.length>oe){d.pushAssistant(i.red(`Input too long after command expansion (${Fe.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.",Nt=ls(a,t);Nt&&(ne+=`
|
|
74
84
|
|
|
75
|
-
${
|
|
85
|
+
${Nt}`);let Ot=no({activeSkills:L,chatConfig:a,options:t});Ot&&(ne+=`
|
|
76
86
|
|
|
77
|
-
${
|
|
87
|
+
${Ot}`);let Ut=cs(L);if(Ut&&(ne+=`
|
|
78
88
|
|
|
79
|
-
${
|
|
89
|
+
${Ut}`),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.`,
|
|
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.`),
|
|
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.`),
|
|
106
|
+
- Use list_workflows to show existing workflows, add_node to extend them, deploy_workflow to ship.`),L.includes("chat-memory"))try{let m=Be("chat-memory");if(typeof m?.buildPromptContext=="function"){let T=Date.now(),_;H.data&&T-H.timestamp<ue?(_=H.data,process.env.ZIBBY_VERBOSE==="true"&&d.pushSystem(i.gray("Using cached memory context"))):(_=await m.buildPromptContext({options:{workspace:e}},{}),H={data:_,timestamp:T},process.env.ZIBBY_VERBOSE==="true"&&d.pushSystem(i.gray("Refreshed memory context cache")));let E=String(_?.backend||"dolt");process.env.ZIBBY_VERBOSE==="true"&&(d.pushSystem(i.gray(`memory backend: ${E}`)),d.pushSystem(i.gray(`memory retrieval output: ${Ge(JSON.stringify(_?.debugPreview||{}),1400)}`)),_?.error&&d.pushSystem(i.yellow(`memory backend warning: ${_.error}`))),_?.promptContext&&(ne+=`
|
|
97
107
|
|
|
98
|
-
${
|
|
99
|
-
${
|
|
100
|
-
[Active test runs: ${
|
|
108
|
+
${_.promptContext}`)}}catch(m){process.env.ZIBBY_VERBOSE==="true"&&d.pushSystem(i.yellow(`memory backend warning: ${String(m?.message||m)}`))}ne=Me(ne,Bo);let Ho=is(v),rt=as([{role:"system",content:ne},...Ho,{role:"user",content:Fe}]),Rt=vt(rt),Wo=Buffer.byteLength(JSON.stringify(rt),"utf8");process.env.ZIBBY_VERBOSE==="true"&&d.pushSystem(i.gray(`payload estimate: ${Rt} chars, ${Wo} bytes (~${Math.round(Rt/4)} tokens)`)),v.push({role:"human",content:Et});let Ce=d.enabled?(()=>{let m=()=>{};return m.setLabel=()=>{},m})():Eo(),ge=!0,je=[],Lt="",Ie="",ws=50,Ss=500,xs=3,_s=60,$s=500,vs=15,ks=25,As=4,Cs=new Set([".","!","?",",",";",":"]),Zo=m=>{ge&&(Ce(),ge=!1),Ie+=m},Jo=(m,T)=>{if(!m){ge&&Ce.setLabel("thinking...");return}je.push(m);let _=70,E=m;if(T&&typeof T=="object"){let w=Object.values(T).map(h=>typeof h=="string"?h:JSON.stringify(h)).join(", "),p=`${m}(${w})`;p.length<=_?E=p:E=`${m}(${w.slice(0,_-m.length-4)}...)`}E!==Lt&&(Lt=E,d.pushSystem(i.gray(`\u23BF ${E}`)),d.refreshPrompt({preserveInput:!0}),ge&&d.showAssistantLoading()),ge&&Ce.setLabel(E)},it=new AbortController;W=it;try{let m=await Dn("",{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:Zo,onToolCall:Jo,signal:it.signal});ge&&Ce();let T=typeof m=="string"?m:m?.structured?JSON.stringify(m.structured,null,2):m?.raw||String(m),_=Ie&&Ie.trim().length>0?Ie.trim():T.trim(),E=us(_,je)?_:ds(_);d.pushAssistant(E);let y=je.length>0?`[tools used: ${je.join(", ")}]
|
|
109
|
+
${_}`:_;v.push({role:"ai",content:y}),Oe(e,v),Ue(e,L)}catch(m){if(ge&&Ce(),d.dismissTransientLoading(),it.signal.aborted){K.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 _=Ie.trim();_?v.push({role:"ai",content:_+T}):v.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}`)),v.push({role:"ai",content:`[Error: ${m.message}]`})}}finally{W=null,re=!1}if(d.refreshPrompt(),K.length>0){let m=K.shift();Se=!0,setImmediate(()=>k.emit("line",m))}}catch(g){d.pushSystem(i.red(`Input handling error: ${g?.message||String(g)}`)),d.refreshPrompt()}}),k.on("SIGINT",()=>{if(W){W.abort();return}Xe()}),k.on("close",Xe);let Yo=()=>{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))};k.on("close",Yo)})}export{mr as _buildPrompt,os as _checkEnvKeys,ts as _formatHistory,gr as _inferAgentType,hr as chatCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function c(e,r=""){return`${String(e).replace(/\/+$/,"")}/agents/credentials${r}`}function d(){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 d();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/credentials.env"}){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 d();if(!o.ok){let s=`Add credential failed (${o.status})`;try{let u=await o.json();u?.error&&(s=`${s}: ${u.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 d();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 m from"node:fs/promises";import O from"node:path";import _ from"node:os";var h=O.join(_.homedir(),".zibby","credentials.env"),l={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 d(e){if(!e)return[];let r=[],o=new Set,u=String(e).split(/\r?\n/);for(let a of u){let t=a.trim();if(!t||t.startsWith("#"))continue;let f=t.indexOf("=");if(f<1)continue;let s=t.slice(0,f).trim(),n=t.slice(f+1).trim();if((n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),!n)continue;let i=l[s];if(!i)continue;let p=s.endsWith("_POOL")?n.split(",").map(c=>c.trim()).filter(Boolean):[n];for(let c of p)c.length<8||o.has(c)||(o.add(c),r.push({type:i,token:c,source_var:s}))}return r}async function E(e=h){let r;try{r=await m.readFile(e,"utf8")}catch(o){if(o.code==="ENOENT")return[];throw o}return d(r)}async function P({filepath:e,env:r=process.env}={}){let o=await E(e),u=new Set(o.map(t=>t.token)),a=[];for(let[t,f]of Object.entries(l)){let s=r[t];if(!s)continue;let n=t.endsWith("_POOL")?s.split(",").map(i=>i.trim()).filter(Boolean):[s];for(let i of n)i.length<8||u.has(i)||(u.add(i),a.push({type:f,token:i,source_var:t,source:"process.env"}))}return{file:o.map(t=>({...t,source:"file"})),env:a,all:[...o.map(t=>({...t,source:"file"})),...a]}}function v(e){return!e||typeof e!="string"||e.length<=4?"***":`***${e.slice(-4)}`}export{h as DEFAULT_CREDENTIALS_PATH,P as discoverCredentials,v as maskToken,d as parseCredentialsEnv,E as readCredentialsFile};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"chalk";function h(o,n=""){return`${String(o).replace(/\/+$/,"")}/agents/credentials${n}`}function b(){let o=new Error("Session expired \u2014 run zibby login");return o.code="AUTH_EXPIRED",o}async function _({apiUrl:o,sessionToken:n}){if(!n)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let r=await fetch(h(o),{headers:{Authorization:`Bearer ${n}`}});if(r.status===401)throw b();if(r.status===404)return{credentials:[],by_type:{oauth:[],api:[]},total:0};if(!r.ok){let i=new Error(`List credentials failed (${r.status})`);throw i.status=r.status,i}return r.json()}async function w({apiUrl:o,sessionToken:n,type:r,token:i,source:s="~/.zibby/credentials.env"}){if(!n)throw new Error("No session token \u2014 run zibby login first");let t=await fetch(h(o),{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({type:r,token:i,source:s})});if(t.status===401)throw b();if(!t.ok){let c=`Add credential failed (${t.status})`;try{let a=await t.json();a?.error&&(c=`${c}: ${a.error}`)}catch{}let l=new Error(c);throw l.status=t.status,l}return t.json()}async function U({apiUrl:o,sessionToken:n,type:r,index:i}){if(!n)throw new Error("No session token \u2014 run zibby login first");let s=await fetch(h(o,`/${encodeURIComponent(r)}/${encodeURIComponent(i)}`),{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(s.status===401)throw b();if(!s.ok){let t=new Error(`Delete credential failed (${s.status})`);throw t.status=s.status,t}return s.json()}async function v({apiUrl:o,sessionToken:n,credentials:r}){let i=0,s=0,t=[];for(let c of r)try{let l=await w({apiUrl:o,sessionToken:n,type:c.type,token:c.token,source:c.source_var||c.source||"local"});l.deduped?s+=1:l.added&&(i+=1)}catch(l){t.push({masked:c.token?`***${c.token.slice(-4)}`:"***",error:l.message})}return{added:i,deduped:s,errors:t}}import C from"node:fs/promises";import x from"node:path";import P from"node:os";var f=x.join(P.homedir(),".zibby","credentials.env"),E={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 T(o){if(!o)return[];let n=[],r=new Set,i=String(o).split(/\r?\n/);for(let s of i){let t=s.trim();if(!t||t.startsWith("#"))continue;let c=t.indexOf("=");if(c<1)continue;let l=t.slice(0,c).trim(),a=t.slice(c+1).trim();if((a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),!a)continue;let d=E[l];if(!d)continue;let k=l.endsWith("_POOL")?a.split(",").map(u=>u.trim()).filter(Boolean):[a];for(let u of k)u.length<8||r.has(u)||(r.add(u),n.push({type:d,token:u,source_var:l}))}return n}async function N(o=f){let n;try{n=await C.readFile(o,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}return T(n)}async function O({filepath:o,env:n=process.env}={}){let r=await N(o),i=new Set(r.map(t=>t.token)),s=[];for(let[t,c]of Object.entries(E)){let l=n[t];if(!l)continue;let a=t.endsWith("_POOL")?l.split(",").map(d=>d.trim()).filter(Boolean):[l];for(let d of a)d.length<8||i.has(d)||(i.add(d),s.push({type:c,token:d,source_var:t,source:"process.env"}))}return{file:r.map(t=>({...t,source:"file"})),env:s,all:[...r.map(t=>({...t,source:"file"})),...s]}}var p={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 g(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let n=process.env.ZIBBY_ENV||"prod";p[n]?o=p[n].apiUrl:o=p.prod.apiUrl}try{let n=new URL(o);return n.protocol!=="http:"&&n.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${n.protocol} (only http/https allowed)`),p.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),p.prod.apiUrl}}import{existsSync as $,mkdirSync as G,readFileSync as L,writeFileSync as J}from"fs";import{homedir as A}from"os";import{join as y}from"path";function R(){return process.env.ZIBBY_CONFIG_DIR||y(A(),".zibby")}function B(){return y(R(),"config.json")}var z=y(A(),".zibby"),Q=y(z,"config.json");function D(){try{let o=B();if($(o)){let n=L(o,"utf-8");return JSON.parse(n)}}catch{}return{}}function I(){return D().sessionToken||null}function m(){let o=I();return o||(console.log(e.red("Not logged in. Run `zibby login` first.")),process.exit(1)),o}async function S(){let o=m(),n=g();console.log(""),console.log(e.cyan(" Stored credentials in your Zibby workspace")),console.log(e.gray(` Source file: ${f}`)),console.log("");let r;try{r=await _({apiUrl:n,sessionToken:o})}catch(s){console.log(e.red(` Failed: ${s.message}`)),process.exit(1)}let{by_type:i}=r;for(let s of["oauth","api"]){let t=i[s]||[];if(console.log(e.bold(` ${s} pool (${t.length} ${t.length===1?"token":"tokens"}):`)),t.length===0)console.log(e.gray(" (none)"));else for(let c of t){let l=c.uploaded_at?new Date(c.uploaded_at).toISOString().slice(0,10):"?",a=c.uploaded_by||"?";console.log(` [${c.index}] ${e.cyan(c.masked)} `+e.gray(`uploaded ${l} by ${a} source: ${c.source||"unknown"}`))}console.log("")}r.total===0&&(console.log(e.gray(" No credentials yet. Put any of these in ~/.zibby/credentials.env:")),console.log(e.gray(" CLAUDE_CODE_OAUTH_TOKEN=<your-token> # subscription billing")),console.log(e.gray(" CLAUDE_CODE_OAUTH_TOKEN_POOL=tok_a,tok_b,tok_c # multiple subs")),console.log(e.gray(" ANTHROPIC_API_KEY=<your-key> # API per-token billing")),console.log(e.gray(" Then run `zibby creds sync` to upload.")),console.log("")),console.log(e.gray(" Same file, same credentials, used by every zibby command:")),console.log(e.gray(" zibby test (test automation)")),console.log(e.gray(" zibby chat (interactive chat + cloud Claude Code sandbox)")),console.log(e.gray(" zibby workflow run (local execution)")),console.log(e.gray(" zibby workflow start (local dev server)")),console.log("")}async function F(){let o=m(),n=g();console.log(""),console.log(e.cyan(" Scanning your local credentials file...")),console.log(e.gray(` ${f}`));let r=await O(),i=r.all.length;if(i===0){console.log(""),console.log(e.yellow(" No credentials found.")),console.log(""),console.log(e.white(" Put one or more credentials in ~/.zibby/credentials.env:")),console.log(e.gray(" CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-... # subscription")),console.log(e.gray(" CLAUDE_CODE_OAUTH_TOKEN_POOL=tok1,tok2,tok3 # subscription pool")),console.log(e.gray(" ANTHROPIC_API_KEY=sk-ant-api03-... # API per-token")),console.log(""),console.log(e.gray(" Or export the same vars in your shell \u2014 Zibby reads both.")),console.log("");return}console.log(e.green(` \u2713 Found ${i} ${i===1?"credential":"credentials"}:`));for(let t of r.all)console.log(e.gray(` ${t.type} ***${t.token.slice(-4)} source: ${t.source_var} (${t.source})`));console.log(""),console.log(e.cyan(" Uploading to Zibby (KMS-encrypted)..."));let s=await v({apiUrl:n,sessionToken:o,credentials:r.all});if(console.log(""),console.log(e.green(` \u2713 ${s.added} new, ${s.deduped} already present`)),s.errors.length>0){console.log(e.red(` \u2717 ${s.errors.length} failed:`));for(let t of s.errors)console.log(e.red(` ${t.masked}: ${t.error}`))}console.log("")}async function Y(o,n){let r=m(),i=g();(!o||!n)&&(console.log(e.red("Usage: zibby creds remove <type> <index>")),console.log(e.gray(" e.g. zibby creds remove oauth 0")),process.exit(1)),console.log(""),console.log(e.cyan(` Removing ${o} credential at index ${n}...`));try{await U({apiUrl:i,sessionToken:r,type:o,index:n})}catch(s){console.log(e.red(` Failed: ${s.message}`)),process.exit(1)}console.log(e.green(" \u2713 Removed.")),console.log(""),console.log(e.gray(" Note: this only deletes Zibby's encrypted copy. To revoke")),console.log(e.gray(" the actual token, do that on the upstream provider where")),console.log(e.gray(" it was issued.")),console.log("")}async function co(o,...n){switch(o){case"list":return S();case"sync":return F();case"remove":return Y(n[0],n[1]);default:console.log(e.red(`Unknown subcommand: ${o}`)),console.log(e.gray(" zibby creds list")),console.log(e.gray(" zibby creds sync")),console.log(e.gray(" zibby creds remove <type> <index>")),process.exit(1)}}export{co as credsCmd,S as listCmd,Y as removeCmd,F as syncCmd};
|
package/dist/commands/init.js
CHANGED
|
@@ -161,7 +161,7 @@ ${{claude:"ANTHROPIC_API_KEY=sk-ant-your_key_here",cursor:`# Cursor Agent uses c
|
|
|
161
161
|
# Install: curl https://cursor.com/install -fsS | bash`,codex:"OPENAI_API_KEY=sk-your_key_here",gemini:"GEMINI_API_KEY=your_key_here"}[t.agent]||""}
|
|
162
162
|
|
|
163
163
|
# Zibby Cloud Sync (for uploading test results & videos)
|
|
164
|
-
# Get your API key from: https://zibby.
|
|
164
|
+
# Get your API key from: https://zibby.dev/settings/tokens
|
|
165
165
|
# ZIBBY_API_KEY=zby_your_api_key_here
|
|
166
166
|
|
|
167
167
|
# Test Memory (Dolt DB) - Auto-compaction settings
|