@zibby/cli 0.1.62 → 0.1.63
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/commands/chat.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
var dn=Object.defineProperty;var mn=(e,t)=>()=>(e&&(t=e(e=0)),t);var gn=(e,t)=>{for(var n in t)dn(e,n,{get:t[n],enumerable:!0})};var se={};gn(se,{cleanupStalePidFiles:()=>Mn,killAllChatOrchestratedRuns:()=>On,killPidTreeBestEffort:()=>We,registerChatOrchestratedRun:()=>Ln,unregisterChatOrchestratedRun:()=>Bn});import{existsSync as ee,mkdirSync as Tn,readFileSync as Pn,readdirSync as Cn,unlinkSync as ne,writeFileSync as ze}from"fs";import{join as Ft}from"path";import{execSync as He}from"child_process";import{DEFAULT_OUTPUT_BASE as Nn}from"@zibby/core";function Mt(e){return e?.paths?.output||Nn}function jt(e,t,n){return Ft(e,t,`.zibby-chat-run-pids-${n}.json`)}function oe(e,t,n){let s=jt(e,t,n);if(!ee(s))return[];try{let r=JSON.parse(Pn(s,"utf8"));return(Array.isArray(r?.pids)?r.pids:[]).map(l=>Number(l)).filter(l=>Number.isFinite(l)&&l>0)}catch{return[]}}function Ln(e,t,n,s={}){let r=Number(t),c=Number(n);if(!Number.isFinite(r)||r<=0||!Number.isFinite(c)||c<=0)return;let l=Mt(s),d=Ft(e,l);Tn(d,{recursive:!0});let y=oe(e,l,r);y.includes(c)||y.push(c),ze(jt(e,l,r),`${JSON.stringify({v:1,pids:y})}
|
|
2
2
|
`,"utf8")}function Bn(e,t,n,s={}){let r=Number(t),c=Number(n);if(!Number.isFinite(r)||r<=0||!Number.isFinite(c)||c<=0)return;let l=Mt(s),d=jt(e,l,r);if(!ee(d))return;let y=oe(e,l,r).filter(L=>L!==c);if(y.length===0)try{ne(d)}catch{}else ze(d,`${JSON.stringify({v:1,pids:y})}
|
|
3
|
-
`,"utf8")}function En(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)return[];try{let n=He(`pgrep -P ${t}`,{encoding:"utf8",stdio:["ignore","pipe","ignore"],maxBuffer:524288}).trim();return n?n.split(/\n/).map(s=>parseInt(s.trim(),10)).filter(s=>Number.isFinite(s)&&s>0):[]}catch{return[]}}function Ye(e,t){let n=Number(e);if(!Number.isFinite(n)||n<=0)return;let s=new Set;function r(c){if(!s.has(c)){s.add(c);for(let l of En(c))r(l);try{process.kill(c,t)}catch{}}}r(n)}function Rn(e){let t=Number(e);if(!(!Number.isFinite(t)||t<=0))try{He(`taskkill /PID ${t} /T /F`,{stdio:"ignore",windowsHide:!0})}catch{}}function We(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)return;if(process.platform==="win32"){Rn(t);return}Ye(t,"SIGTERM");let n=setTimeout(()=>{Ye(t,"SIGKILL")},800);typeof n.unref=="function"&&n.unref()}function On(e,t,n={}){let s=Number(t);if(!Number.isFinite(s)||s<=0)return;let r=Mt(n),c=jt(e,r,s),l=oe(e,r,s);for(let d of l)d!==process.pid&&We(d);try{ee(c)&&ne(c)}catch{}}function Un(e){try{return process.kill(e,0),!0}catch{return!1}}function Mn(e,t={}){let n=Mt(t),s=Ft(e,n),r;try{r=Cn(s)}catch{return}for(let c of r){let l=Fn.exec(c);if(!l)continue;let d=Number(l[1]);if(!(!Number.isFinite(d)||d<=0)&&!Un(d))try{ne(Ft(s,c))}catch{}}}var Fn,re=mn(()=>{Fn=/^\.zibby-chat-run-pids-(\d+)\.json$/});import{invokeAgent as jn,getAgentStrategy as Dn,getSkill as Pt}from"@zibby/core";import{existsSync as yt,readFileSync as Xe,readdirSync as Yn}from"fs";import{resolve as ft,join as ce,dirname as zn,basename as Hn}from"path";import{createInterface as Wn,moveCursor as E,cursorTo as U,clearLine as G,emitKeypressEvents as Zn}from"readline";import{fileURLToPath as Jn}from"url";import{homedir as Gn}from"os";import o from"chalk";import{highlight as Ze}from"cli-highlight";import Vn from"dotenv";import{existsSync as xe,mkdirSync as hn,readFileSync as yn,writeFileSync as bn}from"fs";import{homedir as ke}from"os";import{join as Rt}from"path";function _e(){return process.env.ZIBBY_CONFIG_DIR||Rt(ke(),".zibby")}function ve(){return Rt(_e(),"config.json")}var wn=Rt(ke(),".zibby"),Eo=Rt(wn,"config.json");function Sn(){let e=_e();xe(e)||hn(e,{recursive:!0})}function X(){try{let e=ve();if(xe(e)){let t=yn(e,"utf-8");return JSON.parse(t)}}catch{}return{}}function vt(e){Sn(),bn(ve(),JSON.stringify(e,null,2))}function Ot(){return X().sessionToken||null}function $e(e){let t=X();t.sessionToken=e,vt(t)}function Ie(){return X().user||null}function Ae(e){let t=X();t.user=e,vt(t)}function Te(){let e=X();delete e.sessionToken,delete e.user,delete e.mem0ProxyUrl,vt(e)}function Pe(){return X().proxyUrl||null}function Ce(e){let t=X();t.proxyUrl=e,vt(t)}function Ne(){return X().mem0ProxyUrl||null}function Le(e){let t=X();t.mem0ProxyUrl=e,vt(t)}function Be(){return X().projects||[]}var $t={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.app",description:"Production environment"}};function Xt(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let t=process.env.ZIBBY_ENV||"prod";$t[t]?e=$t[t].apiUrl:e=$t.prod.apiUrl}try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${t.protocol} (only http/https allowed)`),$t.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),$t.prod.apiUrl}}import{existsSync as Qt,mkdirSync as xn,readFileSync as Ee,writeFileSync as Re,unlinkSync as Fo}from"fs";import{resolve as It}from"path";var kn=30;function Oe(e){let t=It(e,".zibby","output");return Qt(t)||xn(t,{recursive:!0}),t}function Ue(e){let t=It(e,".zibby","output","chat-history.json");if(!Qt(t))return[];try{let n=JSON.parse(Ee(t,"utf-8"));return Array.isArray(n)?n:[]}catch{return[]}}function At(e,t){let n=Oe(e),s=It(n,"chat-history.json");try{Re(s,JSON.stringify((t||[]).slice(-kn*2),null,2),"utf-8")}catch{}}function Fe(e){let t=It(e,".zibby","output","active-skills.json");if(!Qt(t))return null;try{let n=JSON.parse(Ee(t,"utf-8"));return Array.isArray(n)?n:null}catch{return null}}function Tt(e,t){let n=Oe(e),s=It(n,"active-skills.json");try{Re(s,JSON.stringify(Array.isArray(t)?t:[]),"utf-8")}catch{}}var te={cli_reliable_v1:{title:"General intelligence reliability contract",operatingRules:["Evidence-first reasoning: ground conclusions in observed outputs or tool evidence, not guesses.","No false completion: never claim success for a state-changing action until verification confirms it.","Execution integrity: do not claim any external action unless the matching tool call actually happened.","Bounded recovery: for transient failures, retry with adjusted parameters up to 2 times, then escalate with blocker + next step.",'Binary-answer discipline: for yes/no questions, verify the exact asked condition before answering; do not answer "yes" from a broader or approximate match.'],executionSafety:["Prefer low-blast-radius, reversible actions first.","Before irreversible or high-impact actions, confirm explicit user intent unless already authorized.","If verification cannot be run, state that limitation explicitly."],investigationLoop:["For unclear failures, follow this loop: detect -> gather evidence -> form hypothesis -> test hypothesis -> conclude.","If evidence is insufficient, explicitly collect more before proposing a root cause.","Prefer smallest validating action first before broad or costly retries."],responseQuality:["State assumptions explicitly when certainty is low.","Differentiate facts, hypotheses, and next actions.","Keep reports concise but decision-useful.","If related-but-not-identical matches exist, report them separately as context, not as the direct yes/no answer."],incidentTemplate:["ONLY when diagnosing failures or errors (never for successful actions), structure your response as: Root cause, Evidence, Attempted fixes, Current status, Next action."],skillRunbooks:{}}},je=2e3,Me=12e3;function Ut(e=[]){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let s of e){let r=String(s||"").replace(/\s+/g," ").trim();r&&(t.has(r)||(t.add(r),n.push(r)))}return n}function _n(e,t=je){let n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-14)).trimEnd()}
|
|
3
|
+
`,"utf8")}function En(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)return[];try{let n=He(`pgrep -P ${t}`,{encoding:"utf8",stdio:["ignore","pipe","ignore"],maxBuffer:524288}).trim();return n?n.split(/\n/).map(s=>parseInt(s.trim(),10)).filter(s=>Number.isFinite(s)&&s>0):[]}catch{return[]}}function Ye(e,t){let n=Number(e);if(!Number.isFinite(n)||n<=0)return;let s=new Set;function r(c){if(!s.has(c)){s.add(c);for(let l of En(c))r(l);try{process.kill(c,t)}catch{}}}r(n)}function Rn(e){let t=Number(e);if(!(!Number.isFinite(t)||t<=0))try{He(`taskkill /PID ${t} /T /F`,{stdio:"ignore",windowsHide:!0})}catch{}}function We(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)return;if(process.platform==="win32"){Rn(t);return}Ye(t,"SIGTERM");let n=setTimeout(()=>{Ye(t,"SIGKILL")},800);typeof n.unref=="function"&&n.unref()}function On(e,t,n={}){let s=Number(t);if(!Number.isFinite(s)||s<=0)return;let r=Mt(n),c=jt(e,r,s),l=oe(e,r,s);for(let d of l)d!==process.pid&&We(d);try{ee(c)&&ne(c)}catch{}}function Un(e){try{return process.kill(e,0),!0}catch{return!1}}function Mn(e,t={}){let n=Mt(t),s=Ft(e,n),r;try{r=Cn(s)}catch{return}for(let c of r){let l=Fn.exec(c);if(!l)continue;let d=Number(l[1]);if(!(!Number.isFinite(d)||d<=0)&&!Un(d))try{ne(Ft(s,c))}catch{}}}var Fn,re=mn(()=>{Fn=/^\.zibby-chat-run-pids-(\d+)\.json$/});import{invokeAgent as jn,getAgentStrategy as Dn,getSkill as Pt}from"@zibby/core";import{existsSync as yt,readFileSync as Xe,readdirSync as Yn}from"fs";import{resolve as ft,join as ce,dirname as zn,basename as Hn}from"path";import{createInterface as Wn,moveCursor as E,cursorTo as U,clearLine as G,emitKeypressEvents as Zn}from"readline";import{fileURLToPath as Jn}from"url";import{homedir as Gn}from"os";import o from"chalk";import{highlight as Ze}from"cli-highlight";import Vn from"dotenv";import{existsSync as xe,mkdirSync as hn,readFileSync as yn,writeFileSync as bn}from"fs";import{homedir as ke}from"os";import{join as Rt}from"path";function _e(){return process.env.ZIBBY_CONFIG_DIR||Rt(ke(),".zibby")}function ve(){return Rt(_e(),"config.json")}var wn=Rt(ke(),".zibby"),Eo=Rt(wn,"config.json");function Sn(){let e=_e();xe(e)||hn(e,{recursive:!0})}function X(){try{let e=ve();if(xe(e)){let t=yn(e,"utf-8");return JSON.parse(t)}}catch{}return{}}function vt(e){Sn(),bn(ve(),JSON.stringify(e,null,2))}function Ot(){return X().sessionToken||null}function $e(e){let t=X();t.sessionToken=e,vt(t)}function Ie(){return X().user||null}function Ae(e){let t=X();t.user=e,vt(t)}function Te(){let e=X();delete e.sessionToken,delete e.user,delete e.mem0ProxyUrl,vt(e)}function Pe(){return X().proxyUrl||null}function Ce(e){let t=X();t.proxyUrl=e,vt(t)}function Ne(){return X().mem0ProxyUrl||null}function Le(e){let t=X();t.mem0ProxyUrl=e,vt(t)}function Be(){return X().projects||[]}var $t={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.app",description:"Production environment"}};function Xt(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let t=process.env.ZIBBY_ENV||"prod";$t[t]?e=$t[t].apiUrl:e=$t.prod.apiUrl}try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${t.protocol} (only http/https allowed)`),$t.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),$t.prod.apiUrl}}import{existsSync as Qt,mkdirSync as xn,readFileSync as Ee,writeFileSync as Re,unlinkSync as Fo}from"fs";import{resolve as It}from"path";import{homedir as Do}from"os";var kn=30;function Oe(e){let t=It(e,".zibby","output");return Qt(t)||xn(t,{recursive:!0}),t}function Ue(e){let t=It(e,".zibby","output","chat-history.json");if(!Qt(t))return[];try{let n=JSON.parse(Ee(t,"utf-8"));return Array.isArray(n)?n:[]}catch{return[]}}function At(e,t){let n=Oe(e),s=It(n,"chat-history.json");try{Re(s,JSON.stringify((t||[]).slice(-kn*2),null,2),"utf-8")}catch{}}function Fe(e){let t=It(e,".zibby","output","active-skills.json");if(!Qt(t))return null;try{let n=JSON.parse(Ee(t,"utf-8"));return Array.isArray(n)?n:null}catch{return null}}function Tt(e,t){let n=Oe(e),s=It(n,"active-skills.json");try{Re(s,JSON.stringify(Array.isArray(t)?t:[]),"utf-8")}catch{}}var te={cli_reliable_v1:{title:"General intelligence reliability contract",operatingRules:["Evidence-first reasoning: ground conclusions in observed outputs or tool evidence, not guesses.","No false completion: never claim success for a state-changing action until verification confirms it.","Execution integrity: do not claim any external action unless the matching tool call actually happened.","Bounded recovery: for transient failures, retry with adjusted parameters up to 2 times, then escalate with blocker + next step.",'Binary-answer discipline: for yes/no questions, verify the exact asked condition before answering; do not answer "yes" from a broader or approximate match.'],executionSafety:["Prefer low-blast-radius, reversible actions first.","Before irreversible or high-impact actions, confirm explicit user intent unless already authorized.","If verification cannot be run, state that limitation explicitly."],investigationLoop:["For unclear failures, follow this loop: detect -> gather evidence -> form hypothesis -> test hypothesis -> conclude.","If evidence is insufficient, explicitly collect more before proposing a root cause.","Prefer smallest validating action first before broad or costly retries."],responseQuality:["State assumptions explicitly when certainty is low.","Differentiate facts, hypotheses, and next actions.","Keep reports concise but decision-useful.","If related-but-not-identical matches exist, report them separately as context, not as the direct yes/no answer."],incidentTemplate:["ONLY when diagnosing failures or errors (never for successful actions), structure your response as: Root cause, Evidence, Attempted fixes, Current status, Next action."],skillRunbooks:{}}},je=2e3,Me=12e3;function Ut(e=[]){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let s of e){let r=String(s||"").replace(/\s+/g," ").trim();r&&(t.has(r)||(t.add(r),n.push(r)))}return n}function _n(e,t=je){let n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-14)).trimEnd()}
|
|
4
4
|
|
|
5
5
|
[truncated]`}function pt(e,t=[],n=je){let s=Ut(t);if(s.length===0)return"";let r=[`## ${e}`,...s.map(c=>`- ${c}`)].join(`
|
|
6
6
|
`);return _n(r,n)}function vn(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function $n(e,t){let n={...e,...t},s=["operatingRules","rules","executionSafety","investigationLoop","responseQuality","incidentTemplate"];for(let r of s)Array.isArray(t?.[r])?n[r]=[...Ut(e?.[r]||[]),...Ut(t[r])]:Array.isArray(e?.[r])&&(n[r]=[...Ut(e[r])]);return n.skillRunbooks={...e?.skillRunbooks||{},...t?.skillRunbooks||{}},n}function In(e={},t={}){let n=Array.isArray(e?.reliabilityAppendSections)?e.reliabilityAppendSections:[],s=Array.isArray(t?.reliabilityAppendSections)?t.reliabilityAppendSections:[];return[...n,...s].map(r=>{if(typeof r=="string")return{title:"Additional reliability guidance",lines:[r]};if(!r||typeof r!="object")return null;let c=String(r.title||"Additional reliability guidance").trim(),l=Array.isArray(r.lines)?r.lines:[];return{title:c,lines:l}}).filter(Boolean)}function An(e={},t={}){let n=String(t.reliabilityProfile||process.env.ZIBBY_RELIABILITY_PROFILE||e.reliabilityProfile||"cli_reliable_v1").trim(),s=e?.reliabilityProfiles?.[n];if(typeof s=="string"&&s.trim())return{name:n,text:s.trim()};if(s&&typeof s.instruction=="string"&&s.instruction.trim())return{name:n,text:s.instruction.trim()};let r=te[n]||te.cli_reliable_v1,c=vn(s),l=c?$n(r,c):r;return{name:n,defaults:l}}function De({activeSkills:e=[],chatConfig:t={},options:n={}}={}){let s=An(t,n);if(s.text)return s.text;let r=s.defaults||te.cli_reliable_v1,c=[pt(r.title||"Reliability contract",r.operatingRules||r.rules||[]),pt("Execution safety",r.executionSafety||[]),pt("Investigation loop",r.investigationLoop||[]),pt("Response quality",r.responseQuality||[]),pt("Failure reporting format",r.incidentTemplate||[])],l=r.skillRunbooks||{};for(let L of e)l[L]&&c.push(pt(`Runbook: ${L}`,l[L]));let d=In(t,n);for(let L of d)c.push(pt(L.title,L.lines));let y=c.filter(Boolean).join(`
|
|
7
7
|
|
|
8
8
|
`).trim();return y.length<=Me?y:`${y.slice(0,Math.max(0,Me-14)).trimEnd()}
|
|
9
9
|
|
|
10
|
-
[truncated]`}var qn=Jn(import.meta.url),Kn=zn(qn),Xn=JSON.parse(Xe(ce(Kn,"../../package.json"),"utf-8")),Qe=30,Qn=54,to=18e3,tn=12e3,Je=42e3;function eo(e){return new Promise(t=>setTimeout(t,e))}var Dt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],ae=[{cmd:"/help",desc:"Show this help"},{cmd:"/skills",desc:"List active & available skills"},{cmd:"/history",desc:"Show conversation history (--all or -n 50)"},{cmd:"/clear",desc:"Clear conversation history"},{cmd:"/memory",desc:"View stored memories, tasks, sessions"},{cmd:"/exit",desc:"Exit the chat"},{cmd:"/quit",desc:"Exit the chat"}];function Ge(){let e=0,t="thinking...",n=setInterval(()=>{let r=o.cyan(Dt[e%Dt.length]),c=e%3,l=c===0?o.white(".")+o.gray(".")+o.dim("."):c===1?o.dim(".")+o.white(".")+o.gray("."):o.gray(".")+o.dim(".")+o.white("."),d=t.replace(/\.+$/,""),y=` ${r} ${o.gray(d)}${l}`;process.stdout.write(`\r${" ".repeat(80)}\r${y}`),e++},300),s=()=>{clearInterval(n),process.stdout.write(`\r${" ".repeat(80)}\r`)};return s.setLabel=r=>{t=r},s}function
|
|
11
|
-
`)}function
|
|
10
|
+
[truncated]`}var qn=Jn(import.meta.url),Kn=zn(qn),Xn=JSON.parse(Xe(ce(Kn,"../../package.json"),"utf-8")),Qe=30,Qn=54,to=18e3,tn=12e3,Je=42e3;function eo(e){return new Promise(t=>setTimeout(t,e))}var Dt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],ae=[{cmd:"/help",desc:"Show this help"},{cmd:"/skills",desc:"List active & available skills"},{cmd:"/history",desc:"Show conversation history (--all or -n 50)"},{cmd:"/clear",desc:"Clear conversation history"},{cmd:"/memory",desc:"View stored memories, tasks, sessions"},{cmd:"/exit",desc:"Exit the chat"},{cmd:"/quit",desc:"Exit the chat"}];function Ge(){let e=0,t="thinking...",n=setInterval(()=>{let r=o.cyan(Dt[e%Dt.length]),c=e%3,l=c===0?o.white(".")+o.gray(".")+o.dim("."):c===1?o.dim(".")+o.white(".")+o.gray("."):o.gray(".")+o.dim(".")+o.white("."),d=t.replace(/\.+$/,""),y=` ${r} ${o.gray(d)}${l}`;process.stdout.write(`\r${" ".repeat(80)}\r${y}`),e++},300),s=()=>{clearInterval(n),process.stdout.write(`\r${" ".repeat(80)}\r`)};return s.setLabel=r=>{t=r},s}function cs(e){let t=e?.agent;return t?t.provider?t.provider:t.gemini?"gemini":t.codex?"codex":t.claude?"claude":t.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}function no(e){return e.slice(-Qe).map(t=>`${t.role==="human"?"H":"AI"}: ${t.content}`).join(`
|
|
11
|
+
`)}function ls(e,t,n){let s=e;return t.length>0&&(s+=`
|
|
12
12
|
|
|
13
13
|
${no(t)}`),s+=`
|
|
14
14
|
H: ${n}
|
|
@@ -29,7 +29,7 @@ ${u}
|
|
|
29
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
30
|
`);k.length===0&&k.push("");let u=[];for(let x of k)u.push(o.bgGray.white(` ${x||" "} `));return u.join(`
|
|
31
31
|
`)}function lt(){F();let f=()=>o.gray(`${Dt[l%Dt.length]} thinking`);if(!t){console.log(` ${f()}`),r=!0;return}Y(),Q(),console.log(),console.log(` ${f()}`),W({preserveInput:!0}),r=!0,l+=1,c=setInterval(()=>{r&&(bt(f()),l+=1)},120)}function wt(f){F();let k=String(f??"").replace(/\r/g,"").replace(/⎿/g,"");if(!r){M(k);return}Q(),console.log();let u=k.split(`
|
|
32
|
-
`);for(;u.length>0&&u[u.length-1]==="";)u.pop();for(let x of u)console.log(x?` ${x}`:"");console.log(),r=!1}return{enabled:t,mount(){if(!n){if(!t){e.prompt(),n=!0;return}n=!0,W()}},refreshPrompt(f={}){if(t&&n){s&&Q(),W(f);return}e.prompt()},pushSystem(f){M(f)},pushUser(f){M(rt(f))},pushAssistant(f){wt(f)},showAssistantLoading:lt,dismissTransientLoading(){F(),r&&t&&n&&s&&(process.stdout.write("\x1B7"),E(process.stdout,0,-2),U(process.stdout,0),G(process.stdout,0),E(process.stdout,0,-1),U(process.stdout,0),G(process.stdout,0),process.stdout.write("\x1B8")),r=!1},touchInputFrame:st,handleResize:B,showCommandDropdown:N,clearCommandDropdown:Y}}function bo(){console.log(""),console.log(o.cyan(" Available commands:"));for(let e of ae)console.log(o.white(` ${e.cmd.padEnd(10)} `)+o.gray(e.desc));console.log(""),console.log(o.cyan(" Chat options:")),console.log(o.white(" --stream, -s ")+o.gray("Enable typewriter effect (default: instant)")),console.log(""),console.log(o.gray(" To install/uninstall skills, just ask naturally:")),console.log(o.gray(' "connect to Jira" \u2022 "add GitHub" \u2022 "remove Slack"')),console.log("")}var wo=oo;async function
|
|
32
|
+
`);for(;u.length>0&&u[u.length-1]==="";)u.pop();for(let x of u)console.log(x?` ${x}`:"");console.log(),r=!1}return{enabled:t,mount(){if(!n){if(!t){e.prompt(),n=!0;return}n=!0,W()}},refreshPrompt(f={}){if(t&&n){s&&Q(),W(f);return}e.prompt()},pushSystem(f){M(f)},pushUser(f){M(rt(f))},pushAssistant(f){wt(f)},showAssistantLoading:lt,dismissTransientLoading(){F(),r&&t&&n&&s&&(process.stdout.write("\x1B7"),E(process.stdout,0,-2),U(process.stdout,0),G(process.stdout,0),E(process.stdout,0,-1),U(process.stdout,0),G(process.stdout,0),process.stdout.write("\x1B8")),r=!1},touchInputFrame:st,handleResize:B,showCommandDropdown:N,clearCommandDropdown:Y}}function bo(){console.log(""),console.log(o.cyan(" Available commands:"));for(let e of ae)console.log(o.white(` ${e.cmd.padEnd(10)} `)+o.gray(e.desc));console.log(""),console.log(o.cyan(" Chat options:")),console.log(o.white(" --stream, -s ")+o.gray("Enable typewriter effect (default: instant)")),console.log(""),console.log(o.gray(" To install/uninstall skills, just ask naturally:")),console.log(o.gray(' "connect to Jira" \u2022 "add GitHub" \u2022 "remove Slack"')),console.log("")}var wo=oo;async function as(e={}){let t=process.cwd();e.verbose&&(process.env.ZIBBY_VERBOSE="true");let n=e.stream||!1;[ft(t,".env.local"),ft(t,".env")].forEach(u=>{yt(u)&&Vn.config({path:u,override:!1})});try{await import("@zibby/skills")}catch{}function r(){let u=Ot();if(!u)return!1;try{let x=JSON.parse(atob(u.split(".")[1]));return x.exp&&x.exp*1e3>Date.now()}catch{return!1}}if(!r()){Te();let u=Xt(),{spawn:x}=await import("child_process"),V=await fetch(`${u}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});V.ok||(console.log(o.red("\n Could not start login. Try `zibby login`.\n")),process.exit(1));let{deviceCode:b,verificationUrl:i,expiresIn:O,interval:tt}=await V.json(),z=process.platform;x(z==="darwin"?"open":z==="win32"?"cmd":"xdg-open",z==="win32"?["/c","start","",i]:[i],{detached:!0,stdio:"ignore"}).unref(),console.log(o.cyan(`
|
|
33
33
|
Opening browser to authorize Zibby CLI...`)),console.log(o.gray(` ${i}
|
|
34
34
|
`));let at=Ge();at.setLabel("waiting for authorization");let dt=(tt||3)*1e3,mt=Math.floor(O/(tt||3)),et=!1;for(let it=0;it<mt;it++){await eo(dt);try{let nt=await fetch(`${u}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:b})});if(nt.status===202)continue;if(!nt.ok)break;let Z=await nt.json();if(Z.status==="authorized"){$e(Z.token),Ae(Z.user),Z.proxyUrl&&Ce(Z.proxyUrl),Z.mem0ProxyUrl&&Le(Z.mem0ProxyUrl),et=!0;break}if(Z.status==="denied")break}catch{break}}at(),et||(console.log(o.red("\n Login failed or timed out. Run `zibby login` to try again.\n")),process.exit(1))}let c=await so(t),l=await ro(t),d=e.agent||"assistant",y=Ot();y&&!process.env.ZIBBY_USER_TOKEN&&(process.env.ZIBBY_USER_TOKEN=y);let L=Ne()||Pe();L&&!process.env.ZIBBY_MEM0_OPENAI_BASE_URL&&(process.env.ZIBBY_MEM0_OPENAI_BASE_URL=L),process.env.AGENT_TYPE=d,process.env.ZIBBY_CHAT_OWNER_PID=String(process.pid);try{let{cleanupStalePidFiles:u}=await Promise.resolve().then(()=>(re(),se));u(t,c)}catch{}let F;try{F=Dn({state:{agentType:d}})}catch(u){console.log(o.red(`
|
|
35
35
|
${u.message}
|
|
@@ -97,4 +97,4 @@ Use provided tools when external data/actions are required. Do not claim actions
|
|
|
97
97
|
|
|
98
98
|
${S.promptContext}`)}}catch(p){process.env.ZIBBY_VERBOSE==="true"&&i.pushSystem(o.yellow(`memory backend warning: ${String(p?.message||p)}`))}K=Ct(K,tn);let an=co(N),qt=lo([{role:"system",content:K},...an,{role:"user",content:Bt}]),we=le(qt),un=Buffer.byteLength(JSON.stringify(qt),"utf8");process.env.ZIBBY_VERBOSE==="true"&&i.pushSystem(o.gray(`payload estimate: ${we} chars, ${un} bytes (~${Math.round(we/4)} tokens)`)),N.push({role:"human",content:ge});let St=i.enabled?(()=>{let p=()=>{};return p.setLabel=()=>{},p})():Ge(),ut=!0,Et=[],Se="",xt="",xo=50,ko=500,_o=3,vo=60,$o=500,Io=15,Ao=25,To=4,Po=new Set([".","!","?",",",";",":"]),pn=p=>{ut&&(St(),ut=!1),xt+=p},fn=(p,I)=>{if(!p){ut&&St.setLabel("thinking...");return}Et.push(p);let S=70,T=p;if(I&&typeof I=="object"){let v=Object.values(I).map(g=>typeof g=="string"?g:JSON.stringify(g)).join(", "),h=`${p}(${v})`;h.length<=S?T=h:T=`${p}(${v.slice(0,S-p.length-4)}...)`}T!==Se&&(Se=T,i.pushSystem(o.gray(`\u23BF ${T}`)),i.refreshPrompt({preserveInput:!0}),ut&&i.showAssistantLoading()),ut&&St.setLabel(T)},Kt=new AbortController;O=Kt;try{let p=await jn("",{state:{agentType:d,config:c,cwd:t,workspace:t}},{model:c?.agent?.assistant?.model||l.model||"auto",workspace:t,skills:B,activeSkills:B,config:c,timeout:l.timeout||3e5,messages:qt,skipPromptFragments:!0,stream:!0,onToken:pn,onToolCall:fn,signal:Kt.signal});ut&&St();let I=typeof p=="string"?p:p?.structured?JSON.stringify(p.structured,null,2):p?.raw||String(p),S=xt&&xt.trim().length>0?xt.trim():I.trim(),T=po(S,Et)?S:fo(S);i.pushAssistant(T);let _=Et.length>0?`[tools used: ${Et.join(", ")}]
|
|
99
99
|
${S}`:S;N.push({role:"ai",content:_}),At(t,N),Tt(t,B)}catch(p){if(ut&&St(),i.dismissTransientLoading(),Kt.signal.aborted){z.length===0&&i.pushAssistant(o.gray("[cancelled]"));let I="";try{let{testRunnerSkill:T}=await import("../../skills/index.js"),_=await T.handleToolCall("run_status",{runId:"all"},{options:{workspace:t}}),v=JSON.parse(_);v.runs?.length>0&&(I=`
|
|
100
|
-
[Active test runs: ${v.runs.map(g=>`${g.runId}: ${g.ticketKey||g.spec} (${g.status})`).join(", ")}. Use run_status("all") to check progress.]`)}catch{}let S=xt.trim();S?N.push({role:"ai",content:S+I}):N.push({role:"ai",content:`[interrupted \u2014 new message]${I}`})}else{let I=String(p?.message||p||"Unknown error");/413|payload too large|request payload too large/i.test(I)?(i.pushAssistant(o.yellow("Request became too large for the proxy (413).")),i.pushSystem(o.gray("Try: /clear, then retry your command; or shorten command/context."))):i.pushAssistant(o.red(`Error: ${I}`)),N.push({role:"ai",content:`[Error: ${p.message}]`})}}finally{O=null,tt=!1}if(i.refreshPrompt(),z.length>0){let p=z.shift();dt=!0,setImmediate(()=>b.emit("line",p))}}catch(a){i.pushSystem(o.red(`Input handling error: ${a?.message||String(a)}`)),i.refreshPrompt()}}),b.on("SIGINT",()=>{if(O){O.abort();return}zt()}),b.on("close",zt);let ln=()=>{process.stdin?.off?(process.stdin.off("data",Nt),process.stdin.off("keypress",Vt)):process.stdin?.removeListener&&(process.stdin.removeListener("data",Nt),process.stdin.removeListener("keypress",Vt))};b.on("close",ln)})}export{
|
|
100
|
+
[Active test runs: ${v.runs.map(g=>`${g.runId}: ${g.ticketKey||g.spec} (${g.status})`).join(", ")}. Use run_status("all") to check progress.]`)}catch{}let S=xt.trim();S?N.push({role:"ai",content:S+I}):N.push({role:"ai",content:`[interrupted \u2014 new message]${I}`})}else{let I=String(p?.message||p||"Unknown error");/413|payload too large|request payload too large/i.test(I)?(i.pushAssistant(o.yellow("Request became too large for the proxy (413).")),i.pushSystem(o.gray("Try: /clear, then retry your command; or shorten command/context."))):i.pushAssistant(o.red(`Error: ${I}`)),N.push({role:"ai",content:`[Error: ${p.message}]`})}}finally{O=null,tt=!1}if(i.refreshPrompt(),z.length>0){let p=z.shift();dt=!0,setImmediate(()=>b.emit("line",p))}}catch(a){i.pushSystem(o.red(`Input handling error: ${a?.message||String(a)}`)),i.refreshPrompt()}}),b.on("SIGINT",()=>{if(O){O.abort();return}zt()}),b.on("close",zt);let ln=()=>{process.stdin?.off?(process.stdin.off("data",Nt),process.stdin.off("keypress",Vt)):process.stdin?.removeListener&&(process.stdin.removeListener("data",Nt),process.stdin.removeListener("keypress",Vt))};b.on("close",ln)})}export{ls as _buildPrompt,oo as _checkEnvKeys,no as _formatHistory,cs as _inferAgentType,as as chatCommand};
|
package/dist/commands/run.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{runTest as Ve,logger as U,DEFAULT_OUTPUT_BASE as He,SESSIONS_DIR as We}from"@zibby/core";import{zibbyScratchSpecsDir as ce}from"@zibby/core/constants/zibby-scratch.js";import{createCliRunIndexPipelineProgressAppender as qe,postCliInterruptedRunIndex as _e}from"@zibby/core/utils/run-index-post-cli.js";import{createWriteStream as Ne,mkdirSync as ke}from"fs";import{join as ue,isAbsolute as Be}from"path";var Oe="studio-cli.log";function Re(t,o){if(!t||typeof t!="string")return null;let s=t.trim();return s?Be(s)?s:ue(o,s):null}function je(t){if(!t)return()=>{};ke(t,{recursive:!0});let o=ue(t,Oe),s=Ne(o,{flags:"a"}),l=process.stdout.write.bind(process.stdout),c=process.stderr.write.bind(process.stderr),a=n=>function(g,b,O){typeof b=="function"&&(O=b,b=void 0);try{Buffer.isBuffer(g)?s.write(g):s.write(String(g),b||"utf8")}catch{}return n(g,b,O)};return process.stdout.write=a(l),process.stderr.write=a(c),()=>{process.stdout.write=l,process.stderr.write=c;try{s.end()}catch{}}}function Q(t,o,s){let l=null;function c(a){if(!l&&a?.sessionPath){let n=Re(a.sessionPath,o);n&&(l=je(n))}typeof t=="function"&&t(a)}return c.dispose=()=>{typeof l=="function"&&(l(),l=null)},c}import{existsSync as de,mkdirSync as Ye,readFileSync as Fe,readdirSync as vo,unlinkSync as Le,writeFileSync as pe}from"fs";import{join as fe}from"path";import{DEFAULT_OUTPUT_BASE as De}from"@zibby/core";function ge(t){return t?.paths?.output||De}function ee(t,o,s){return fe(t,o,`.zibby-chat-run-pids-${s}.json`)}function he(t,o,s){let l=ee(t,o,s);if(!de(l))return[];try{let c=JSON.parse(Fe(l,"utf8"));return(Array.isArray(c?.pids)?c.pids:[]).map(n=>Number(n)).filter(n=>Number.isFinite(n)&&n>0)}catch{return[]}}function ye(t,o,s,l={}){let c=Number(o),a=Number(s);if(!Number.isFinite(c)||c<=0||!Number.isFinite(a)||a<=0)return;let n=ge(l),_=fe(t,n);Ye(_,{recursive:!0});let g=he(t,n,c);g.includes(a)||g.push(a),pe(ee(t,n,c),`${JSON.stringify({v:1,pids:g})}
|
|
1
|
+
import{runTest as Ve,logger as U,DEFAULT_OUTPUT_BASE as He,SESSIONS_DIR as We}from"@zibby/core";import{zibbyScratchSpecsDir as ce}from"@zibby/core/constants/zibby-scratch.js";import{createCliRunIndexPipelineProgressAppender as qe,postCliInterruptedRunIndex as _e}from"@zibby/core/utils/run-index-post-cli.js";import{createWriteStream as Ne,mkdirSync as ke}from"fs";import{join as ue,isAbsolute as Be}from"path";var Oe="studio-cli.log";function Re(t,o){if(!t||typeof t!="string")return null;let s=t.trim();return s?Be(s)?s:ue(o,s):null}function je(t){if(!t)return()=>{};ke(t,{recursive:!0});let o=ue(t,Oe),s=Ne(o,{flags:"a"}),l=process.stdout.write.bind(process.stdout),c=process.stderr.write.bind(process.stderr),a=n=>function(g,b,O){typeof b=="function"&&(O=b,b=void 0);try{Buffer.isBuffer(g)?s.write(g):s.write(String(g),b||"utf8")}catch{}return n(g,b,O)};return process.stdout.write=a(l),process.stderr.write=a(c),()=>{process.stdout.write=l,process.stderr.write=c;try{s.end()}catch{}}}function Q(t,o,s){let l=null;function c(a){if(!l&&a?.sessionPath){let n=Re(a.sessionPath,o);n&&(l=je(n))}typeof t=="function"&&t(a)}return c.dispose=()=>{typeof l=="function"&&(l(),l=null)},c}import{existsSync as de,mkdirSync as Ye,readFileSync as Fe,readdirSync as vo,unlinkSync as Le,writeFileSync as pe}from"fs";import{join as fe}from"path";import{execSync as Po}from"child_process";import{DEFAULT_OUTPUT_BASE as De}from"@zibby/core";function ge(t){return t?.paths?.output||De}function ee(t,o,s){return fe(t,o,`.zibby-chat-run-pids-${s}.json`)}function he(t,o,s){let l=ee(t,o,s);if(!de(l))return[];try{let c=JSON.parse(Fe(l,"utf8"));return(Array.isArray(c?.pids)?c.pids:[]).map(n=>Number(n)).filter(n=>Number.isFinite(n)&&n>0)}catch{return[]}}function ye(t,o,s,l={}){let c=Number(o),a=Number(s);if(!Number.isFinite(c)||c<=0||!Number.isFinite(a)||a<=0)return;let n=ge(l),_=fe(t,n);Ye(_,{recursive:!0});let g=he(t,n,c);g.includes(a)||g.push(a),pe(ee(t,n,c),`${JSON.stringify({v:1,pids:g})}
|
|
2
2
|
`,"utf8")}function me(t,o,s,l={}){let c=Number(o),a=Number(s);if(!Number.isFinite(c)||c<=0||!Number.isFinite(a)||a<=0)return;let n=ge(l),_=ee(t,n,c);if(!de(_))return;let g=he(t,n,c).filter(b=>b!==a);if(g.length===0)try{Le(_)}catch{}else pe(_,`${JSON.stringify({v:1,pids:g})}
|
|
3
|
-
`,"utf8")}import{readFileSync as A,existsSync as m,statSync as xe,mkdirSync as Pe,writeFileSync as be,appendFileSync as Je,rmSync as Ae}from"fs";import{resolve as k,join as C,dirname as Xe,isAbsolute as Ee}from"path";import{fileURLToPath as Qe}from"url";import{glob as q}from"glob";import e from"chalk";import Ue from"ora";import eo from"dotenv";import oo from"open";var S={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 H(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";S[o]?t=S[o].apiUrl:t=S.prod.apiUrl}try{let o=new URL(t);return o.protocol!=="http:"&&o.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${o.protocol} (only http/https allowed)`),S.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),S.prod.apiUrl}}function Ie(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let t=process.env.ZIBBY_ENV||"prod";return(S[t]||S.prod).accountApiUrl}function oe(){let t=process.env.ZIBBY_ENV||"prod";return S[t]||S.prod}function te(){let t;if(process.env.ZIBBY_FRONTEND_URL)t=process.env.ZIBBY_FRONTEND_URL;else{let o=process.env.ZIBBY_ENV||"prod";S[o]?t=S[o].frontendUrl:t=S.prod.frontendUrl}try{let o=new URL(t);if(o.protocol!=="http:"&&o.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${o.protocol} (only http/https allowed)`),S.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let l=["zibby.app","studio.zibby.app","studio-staging.zibby.app"],c=o.hostname;if(!l.some(n=>c===n||c.endsWith(`.${n}`))&&!c.includes("localhost")&&c!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${c}`),"https://studio.zibby.app"}return t}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${t}`),S.local.frontendUrl}}import{existsSync as Ge,mkdirSync as
|
|
3
|
+
`,"utf8")}import{readFileSync as A,existsSync as m,statSync as xe,mkdirSync as Pe,writeFileSync as be,appendFileSync as Je,rmSync as Ae}from"fs";import{resolve as k,join as C,dirname as Xe,isAbsolute as Ee}from"path";import{fileURLToPath as Qe}from"url";import{glob as q}from"glob";import e from"chalk";import Ue from"ora";import eo from"dotenv";import oo from"open";var S={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 H(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";S[o]?t=S[o].apiUrl:t=S.prod.apiUrl}try{let o=new URL(t);return o.protocol!=="http:"&&o.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${o.protocol} (only http/https allowed)`),S.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),S.prod.apiUrl}}function Ie(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let t=process.env.ZIBBY_ENV||"prod";return(S[t]||S.prod).accountApiUrl}function oe(){let t=process.env.ZIBBY_ENV||"prod";return S[t]||S.prod}function te(){let t;if(process.env.ZIBBY_FRONTEND_URL)t=process.env.ZIBBY_FRONTEND_URL;else{let o=process.env.ZIBBY_ENV||"prod";S[o]?t=S[o].frontendUrl:t=S.prod.frontendUrl}try{let o=new URL(t);if(o.protocol!=="http:"&&o.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${o.protocol} (only http/https allowed)`),S.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let l=["zibby.app","studio.zibby.app","studio-staging.zibby.app"],c=o.hostname;if(!l.some(n=>c===n||c.endsWith(`.${n}`))&&!c.includes("localhost")&&c!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${c}`),"https://studio.zibby.app"}return t}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${t}`),S.local.frontendUrl}}import{existsSync as Ge,mkdirSync as Uo,readFileSync as ze,writeFileSync as $o}from"fs";import{homedir as we}from"os";import{join as W}from"path";function Ke(){return process.env.ZIBBY_CONFIG_DIR||W(we(),".zibby")}function Me(){return W(Ke(),"config.json")}var Ze=W(we(),".zibby"),No=W(Ze,"config.json");function ve(){try{let t=Me();if(Ge(t)){let o=ze(t,"utf-8");return JSON.parse(o)}}catch{}return{}}function ne(){return ve().sessionToken||null}function se(){return ve().user||null}var to=Qe(import.meta.url),no=Xe(to),so=JSON.parse(A(C(no,"../../package.json"),"utf-8"));function ro(t){let o=s=>s?typeof s.message=="string"&&s.message.includes("Interrupted by user")?!0:Array.isArray(s.errors)?s.errors.some(o):s.cause?o(s.cause):!1:!1;return o(t)}function Se(t,o){if(t==null)return null;let s=String(t).trim();return s?Ee(s)?s:k(o,s):null}function io(t,o){try{if(!t||!m(t))return;let s=C(t,"studio-cli.log"),l=`
|
|
4
4
|
[CLI_FATAL] ${new Date().toISOString()}
|
|
5
5
|
Error: ${String(o?.message||o)}
|
|
6
6
|
${o?.stack?`${String(o.stack)}
|
|
@@ -1,30 +1,36 @@
|
|
|
1
|
-
import o from"chalk";import{readFileSync as
|
|
1
|
+
import o from"chalk";import{readFileSync as x,existsSync as S}from"fs";import{homedir as I}from"os";import{join as j}from"path";var b="https://logs.workflows.zibby.app";function T(n){let r=j(I(),".zibby","config.json");S(r)||(console.log(o.red(`
|
|
2
2
|
Not authenticated`)),console.log(o.gray(` Run: zibby login
|
|
3
|
-
`)),process.exit(1));let t;try{t=JSON.parse(
|
|
3
|
+
`)),process.exit(1));let t;try{t=JSON.parse(x(r,"utf-8"))}catch{console.log(o.red(`
|
|
4
4
|
Config file corrupt`)),console.log(o.gray(` Run: zibby login
|
|
5
5
|
`)),process.exit(1)}let l=t.sessionToken;l||(console.log(o.red(`
|
|
6
6
|
Not authenticated`)),console.log(o.gray(` Run: zibby login
|
|
7
|
-
`)),process.exit(1));let c=n.project;return{token:l,projectId:c}}function
|
|
7
|
+
`)),process.exit(1));let c=n.project;return{token:l,projectId:c}}function h(n){return new Date(n).toISOString().replace("T"," ").replace("Z","")}function P(n){return n==="running"?o.yellow(n):n==="completed"?o.green(n):o.red(n||"unknown")}function $(n){return n?.length>16?n.slice(0,16):n}async function k(n,r){let t=await fetch(n,{headers:{Authorization:`Bearer ${r}`}});if(!t.ok){let l=await t.text();throw new Error(`API ${t.status}: ${l}`)}return t.json()}async function E(n,r,t,l){if(n)return n;l||(console.log(o.red(`
|
|
8
8
|
Job ID or --project is required`)),console.log(o.gray(" Usage: zibby logs <uuid>")),console.log(o.gray(` zibby logs --workflow ticket-triage --project <id>
|
|
9
9
|
`)),process.exit(1));let c=r.workflow;c||(console.log(o.red(`
|
|
10
10
|
Job ID or --workflow is required`)),console.log(o.gray(" Usage: zibby logs <uuid>")),console.log(o.gray(" zibby logs --workflow ticket-triage --project <id>")),console.log(o.gray(` zibby logs --workflow ticket-triage --all --project <id>
|
|
11
|
-
`)),process.exit(1));let
|
|
11
|
+
`)),process.exit(1));let u=new URLSearchParams({workflow:c,limit:"10"}),{jobs:i}=await k(`${b}/jobs/${l}?${u}`,t);(!i||i.length===0)&&(console.log(o.yellow(`
|
|
12
12
|
No jobs found for workflow "${c}".`)),process.exit(0)),console.log(o.gray(`
|
|
13
13
|
Recent runs for ${o.cyan(c)}:
|
|
14
|
-
`));for(let
|
|
15
|
-
Tailing latest: ${o.cyan(
|
|
16
|
-
`)),
|
|
17
|
-
`));let
|
|
18
|
-
|
|
19
|
-
`)),
|
|
20
|
-
|
|
14
|
+
`));for(let m of i.slice(0,5))console.log(o.gray(` ${$(m.jobId)} ${P(m.status)} ${m.createdAt||""}`));let a=i[0];return console.log(o.gray(`
|
|
15
|
+
Tailing latest: ${o.cyan($(a.jobId))}
|
|
16
|
+
`)),a.jobId}async function z({token:n,projectId:r,workflowUuid:t,follow:l,limit:c}){console.log(o.gray(` Tailing all executions for workflow ${o.cyan(t)}...`)),console.log(o.gray(" Showing live logs from all runs (interleaved by timestamp).")),console.log(o.gray(` Press Ctrl+C to stop.
|
|
17
|
+
`));let u=new Set,i=new Set,a=null,m=!1,y=()=>{m=!0,console.log(o.gray(`
|
|
18
|
+
Stopped tailing.
|
|
19
|
+
`)),process.exit(0)};for(process.on("SIGINT",y),process.on("SIGTERM",y);!m;)try{let d=r?`${b}/logs/${r}/${t}`:`${b}/job/${t}`,p=new URLSearchParams({limit:String(c)}),s=await k(`${d}?${p}`,n);if(s.executions)for(let e of s.executions)i.has(e.jobId)||(i.size>0&&console.log(o.yellow(`
|
|
20
|
+
\u26A1 New execution: ${$(e.jobId)}
|
|
21
|
+
`)),i.add(e.jobId));let g=[];for(let e of s.lines||[]){let f=`${e.jobId}:${e.timestamp}:${e.message}`;u.has(f)||(u.add(f),g.push(e))}g.sort((e,f)=>e.timestamp-f.timestamp);for(let e of g){let f=e.jobId||e.executionId;f!==a&&(a!==null&&console.log(""),console.log(o.dim(` \u2500\u2500 Execution: ${$(f)} \u2500\u2500`)),a=f);let w=o.gray(h(e.timestamp));console.log(`${w} ${e.message.replace(/\n$/,"")}`)}if(!l)break;await new Promise(e=>setTimeout(e,2e3))}catch(d){if(d.name==="AbortError")break;console.error(o.red(` Error: ${d.message}`)),l||process.exit(1),await new Promise(p=>setTimeout(p,3e3))}}async function R({token:n,projectId:r,jobId:t,follow:l,limit:c}){let u=r?`${b}/logs/${r}/${t}`:`${b}/job/${t}`,i=null,a=0,m=new Set,y=!1,d=()=>{y=!0,console.log(o.gray(`
|
|
22
|
+
Stopped tailing.
|
|
23
|
+
`)),process.exit(0)};for(process.on("SIGINT",d),process.on("SIGTERM",d),console.log(o.gray(` Tailing logs for job ${o.cyan(t)}...`)),console.log(l?o.gray(` Press Ctrl+C to stop.
|
|
24
|
+
`):"");!y;)try{let p=new URLSearchParams({limit:String(c)});i&&p.set("nextToken",i);let s=await k(`${u}?${p}`,n);s.message&&s.lines?.length===0&&a===0&&console.log(o.gray(` ${s.message}`)),s.status==="starting"&&s.lines?.length===0&&a===0&&console.log(o.gray(" Container starting..."));for(let e of s.lines||[]){let f=`${e.timestamp}:${e.message}`;if(m.has(f))continue;m.add(f);let w=o.gray(h(e.timestamp));console.log(`${w} ${e.message.replace(/\n$/,"")}`)}if(a=s.lines?.length>0?0:a+1,i=s.nextForwardToken||null,s.status==="completed"||s.status==="failed"){let e=s.status==="completed"?o.green:o.red;console.log(e(`
|
|
21
25
|
Job ${s.status}.`)),process.exit(s.status==="completed"?0:1)}if(!l){s.status&&console.log(o.gray(`
|
|
22
|
-
Status: ${s.status}`));break}await new Promise(e=>setTimeout(e,
|
|
26
|
+
Status: ${s.status}`));break}await new Promise(e=>setTimeout(e,a>5?5e3:2e3))}catch(p){if(p.name==="AbortError")break;console.error(o.red(` Error: ${p.message}`)),l||process.exit(1),await new Promise(s=>setTimeout(s,3e3))}}async function C({token:n,projectId:r,workflow:t,follow:l,limit:c}){let u=`${b}/all/${r}`,i=null,a=0,m=new Set,y=null,d=!1,p=()=>{d=!0,console.log(o.gray(`
|
|
27
|
+
Stopped tailing.
|
|
28
|
+
`)),process.exit(0)};for(process.on("SIGINT",p),process.on("SIGTERM",p),console.log(o.gray(`
|
|
23
29
|
Tailing all runs for ${o.cyan(t)}...`)),console.log(l?o.gray(` Press Ctrl+C to stop.
|
|
24
|
-
`):"")
|
|
25
|
-
... more logs available. Run again or use --follow to stream.`)),g.jobCount&&console.log(o.gray(` ${g.jobCount} job(s) found.`));break}if(!g.hasRunning&&!a
|
|
26
|
-
No running jobs. All caught up.`));break}await new Promise(e=>setTimeout(e,
|
|
30
|
+
`):"");!d;)try{let s=new URLSearchParams({workflow:t,limit:String(c)});i&&s.set("nextToken",i);let g=await k(`${u}?${s}`,n);g.message&&g.lines?.length===0&&a===0&&console.log(o.gray(` ${g.message}`));for(let e of g.lines||[]){let f=`${e.timestamp}:${e.jobId}:${e.message}`;if(m.has(f))continue;m.add(f),e.jobId!==y&&(y!==null&&console.log(""),console.log(o.dim(` \u2500\u2500 ${$(e.jobId)} \u2500\u2500`)),y=e.jobId);let w=o.gray(h(e.timestamp));console.log(`${w} ${e.message.replace(/\n$/,"")}`)}if(a=g.lines?.length>0?0:a+1,i=g.nextToken||null,!l){i&&console.log(o.gray(`
|
|
31
|
+
... more logs available. Run again or use --follow to stream.`)),g.jobCount&&console.log(o.gray(` ${g.jobCount} job(s) found.`));break}if(!g.hasRunning&&!i&&a>2){console.log(o.gray(`
|
|
32
|
+
No running jobs. All caught up.`));break}await new Promise(e=>setTimeout(e,a>5?5e3:2e3))}catch(s){if(s.name==="AbortError")break;console.error(o.red(` Error: ${s.message}`)),l||process.exit(1),await new Promise(g=>setTimeout(g,3e3))}}async function G(n,r){let{token:t,projectId:l}=T(r),c=r.follow!==!1,u=r.lines?parseInt(r.lines,10):500;if(r.all){let a=r.workflow;return a||(console.log(o.red(`
|
|
27
33
|
--workflow is required with --all`)),console.log(o.gray(` Example: zibby logs --workflow ticket-triage --all --project <id>
|
|
28
|
-
`)),process.exit(1)),
|
|
34
|
+
`)),process.exit(1)),C({token:t,projectId:l,workflow:a,follow:c,limit:u})}if(r.tailLatest)return n||(console.log(o.red(`
|
|
29
35
|
Workflow UUID is required with --tail-latest`)),console.log(o.gray(` Example: zibby logs <workflowUuid> -t
|
|
30
|
-
`)),process.exit(1)),
|
|
36
|
+
`)),process.exit(1)),z({token:t,projectId:l,workflowUuid:n,follow:c,limit:u});let i=await E(n,r,t,l);return R({token:t,projectId:l,jobId:i,follow:c,limit:u})}export{G as logsCommand};
|
|
@@ -1,16 +1,22 @@
|
|
|
1
|
-
import
|
|
1
|
+
import j from"ora";import{select as m}from"@inquirer/prompts";import{readFileSync as U,existsSync as v}from"fs";import{homedir as B}from"os";import{join as _}from"path";var $={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 y(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";$[e]?o=$[e].apiUrl:o=$.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)`),$.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),$.prod.apiUrl}}function b(){let o=_(B(),".zibby","config.json");if(v(o))try{let s=JSON.parse(U(o,"utf-8"));if(s.sessionToken)return s.sessionToken}catch{}let e=process.env.ZIBBY_API_KEY;if(e)return e;console.log(`
|
|
2
2
|
Not authenticated`),console.log(" Run: zibby login"),console.log(` OR set ZIBBY_API_KEY env var (for CI/CD)
|
|
3
|
-
`),process.exit(1)}async function
|
|
4
|
-
\u2713 Found workflow "${
|
|
5
|
-
`);
|
|
3
|
+
`),process.exit(1)}async function E(o){let e=y(),s=j("Fetching projects...").start();try{let p=await fetch(`${e}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}});p.ok||(s.fail("Failed to fetch projects"),process.exit(1));let t=await p.json();Array.isArray(t)||(t.projects?t=t.projects:t.data&&(t=t.data)),(!t||t.length===0)&&(s.fail("No projects found"),process.exit(1)),s.succeed(`Found ${t.length} project${t.length===1?"":"s"}`),console.log("");let n=t.map(r=>({name:`${r.name||"Unnamed"} (${r.projectId||r.id})`,value:r.projectId||r.id}));return await m({message:"Select a project:",choices:n})}catch(p){s.fail(`Error: ${p.message}`),process.exit(1)}}async function k(o,e){let s=y(),p=j("Fetching deployed workflows...").start();try{let t=["analysis","implementation","run_test"],n=[];for(let l of t){let d=await fetch(`${s}/projects/${o}/workflows/${l}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}});if(d.ok){let i=await d.json();i.graph&&n.push({name:l,version:i.version||0,isDefault:i.isDefault!==!1})}}n.length===0&&(p.fail("No deployed workflows found for this project"),process.exit(1)),p.succeed(`Found ${n.length} deployed workflow${n.length===1?"":"s"}`),console.log("");let r=n.map(l=>({name:`${l.name} (v${l.version})${l.isDefault?" [default]":""}`,value:l.name}));return await m({message:"Select a workflow to trigger:",choices:r})}catch(t){p.fail(`Error: ${t.message}`),process.exit(1)}}async function Y(o,e={}){let s=b(),t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(o),n=e.project||process.env.ZIBBY_PROJECT_ID,r=o;if(o&&t){let i=y();try{let a=await fetch(`${i}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}});if(a.ok){let f=(await a.json()).projects||[];for(let c of f){let u=await fetch(`${i}/projects/${c.projectId}/workflows`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}});if(u.ok){let I=(await u.json()).find(w=>w.uuid===o);if(I){n=c.projectId,r=I.workflowType||I.name,console.log(`
|
|
4
|
+
\u2713 Found workflow "${r}" (UUID: ${o})
|
|
5
|
+
`);break}}}(!r||r===o)&&(console.log(`
|
|
6
|
+
Error: Workflow with UUID "${o}" not found`),console.log(` Check: zibby workflow list
|
|
7
|
+
`),process.exit(1))}}catch(a){console.log(`
|
|
8
|
+
Error looking up workflow UUID: ${a.message}
|
|
9
|
+
`),process.exit(1)}}else if(o&&!n){let i=y();try{let a=await fetch(`${i}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}});if(a.ok){let f=(await a.json()).projects||[],c=[];for(let u of f){let h=await fetch(`${i}/projects/${u.projectId}/workflows`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}});h.ok&&(await h.json()).some(w=>w.workflowType===o)&&c.push(u)}if(c.length===1)n=c[0].projectId,console.log(`
|
|
10
|
+
\u2713 Found workflow "${o}" in project: ${c[0].name||n}
|
|
11
|
+
`);else if(c.length>1){console.log(`
|
|
6
12
|
Workflow "${o}" is deployed to multiple projects:
|
|
7
|
-
`);let u=
|
|
13
|
+
`);let u=c.map(h=>({name:`${h.name||"Unnamed"} (${h.projectId})`,value:h.projectId}));n=await m({message:"Select a project:",choices:u})}else console.log(`
|
|
8
14
|
Error: Workflow "${o}" not found in any of your projects`),console.log(` Deploy it first with: zibby deploy ${o}
|
|
9
|
-
`),process.exit(1)}}catch{}}n||(console.log(""),n=await
|
|
10
|
-
Error: Invalid JSON in --input`),console.log(` ${
|
|
15
|
+
`),process.exit(1)}}catch{}}n||(console.log(""),n=await E(s)),r||(console.log(""),r=await k(n,s));let l={};if(e.input)try{l=JSON.parse(e.input)}catch(i){console.log(`
|
|
16
|
+
Error: Invalid JSON in --input`),console.log(` ${i.message}
|
|
11
17
|
`),process.exit(1)}console.log(`
|
|
12
18
|
Triggering Workflow
|
|
13
|
-
`),console.log(" ".padEnd(60,"-")),console.log(` Workflow: ${
|
|
14
|
-
Your workflow execution quota has been exceeded`),
|
|
15
|
-
`),process.exit(1)}let
|
|
16
|
-
`),process.exit(1)}}export{
|
|
19
|
+
`),console.log(" ".padEnd(60,"-")),console.log(` Workflow: ${r}`),console.log(` Project: ${n}`),Object.keys(l).length>0&&console.log(` Input: ${JSON.stringify(l).substring(0,50)}...`),e.idempotencyKey&&console.log(` Idempotency: ${e.idempotencyKey}`),console.log(" ".padEnd(60,"-")),console.log("");let d=j("Triggering workflow execution...").start();try{let i=y(),a={input:l};e.idempotencyKey&&(a.idempotencyKey=e.idempotencyKey);let g=await fetch(`${i}/projects/${n}/workflows/${r}/trigger`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(a)});if(!g.ok){let c=await g.json().catch(()=>({}));g.status===429&&(d.fail("Quota exceeded"),console.log(`
|
|
20
|
+
Your workflow execution quota has been exceeded`),c.quotaInfo&&(console.log(` Used: ${c.quotaInfo.used}/${c.quotaInfo.limit} executions`),console.log(` Plan: ${c.quotaInfo.planId}`),c.quotaInfo.periodEnd&&console.log(` Resets: ${new Date(c.quotaInfo.periodEnd).toLocaleDateString()}`)),console.log(""),process.exit(1)),d.fail("Trigger failed"),console.log(` Error: ${c.message||g.statusText}
|
|
21
|
+
`),process.exit(1)}let f=await g.json();d.succeed("Workflow triggered successfully"),console.log(""),console.log(" Job Details:"),console.log(` Job ID: ${f.jobId}`),console.log(` Status: ${f.status}`),console.log(` Version: ${f.version}`),console.log(` Triggered: ${new Date(f.triggeredAt).toLocaleString()}`),console.log(""),console.log(" Monitor execution:"),console.log(` zibby logs ${f.jobId}`),console.log(` zibby logs --workflow ${r}`),console.log("")}catch(i){d.fail("Trigger failed"),console.log(` Error: ${i.message}
|
|
22
|
+
`),process.exit(1)}}export{Y as triggerWorkflowCommand};
|
package/dist/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn as m,execFileSync as p}from"child_process";import l from"os";import S from"path";import{existsSync as h,mkdirSync as b,writeFileSync as g}from"fs";import c from"os";import s from"path";import{existsSync as w,readFileSync as O,readdirSync as y,createWriteStream as j,mkdirSync as A,rmSync as D,unlinkSync as R}from"fs";import F from"chalk";var
|
|
1
|
+
import{spawn as m,execFileSync as p}from"child_process";import l from"os";import S from"path";import{existsSync as h,mkdirSync as b,writeFileSync as g}from"fs";import c from"os";import s from"path";import{existsSync as w,readFileSync as O,readdirSync as y,createWriteStream as j,mkdirSync as A,rmSync as D,unlinkSync as R}from"fs";import{execFileSync as F}from"child_process";import _ from"chalk";var z=process.env.ZIBBY_STUDIO_CDN||"https://dl.zibby.app",a=s.join(c.homedir(),".zibby","studio");function d(){if(c.platform()==="darwin")return s.join(a,"Zibby Studio.app");if(c.platform()==="win32")return s.join(a,"Zibby Studio.exe");if(c.platform()==="linux"){if(!w(a))return null;let o=y(a).find(t=>t.endsWith(".AppImage"));return o?s.join(a,o):null}return null}var u=S.join(l.homedir(),".zibby","studio-launch.json");function x(o){let t={};o.projectRoot&&(t.projectRoot=o.projectRoot),o.port&&(t.port=o.port),t.launchedAt=Date.now();let n=S.dirname(u);b(n,{recursive:!0}),g(u,JSON.stringify(t,null,2))}function I(o){if(l.platform()==="darwin"){try{p("xattr",["-cr",o])}catch{}try{p("spctl",["--add","--label","ZibbyStudio",o])}catch{}}}function f(o,t){return new Promise(n=>{let e=m("open",["-a",o,"--env",`ZIBBY_STUDIO_PROJECT_ROOT=${t.projectRoot}`],{stdio:["ignore","pipe","pipe"]}),r="";e.stderr?.on("data",i=>{r+=i.toString()}),e.on("close",i=>n({code:i,stderr:r})),e.on("error",i=>n({code:1,stderr:i.message}))})}async function M(o={}){let t=d();if(!t)throw new Error("Studio not installed");if(!h(t))throw new Error(`Studio app not found at ${t}`);x(o);let n=o.projectRoot||process.cwd();if(l.platform()==="darwin"){let e=await f(t,{projectRoot:n});if(e.code!==0&&e.stderr.includes("Launch failed")&&(I(t),e=await f(t,{projectRoot:n})),e.code!==0){let r=e.stderr.trim();r&&console.error(`[Studio Desktop] ${r}`),console.error(`Zibby Studio exited with code ${e.code}`)}}else{let e=m(t,[],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,ZIBBY_STUDIO_PROJECT_ROOT:n}});e.unref(),e.stderr?.on("data",r=>{let i=r.toString().trim();i&&console.error(`[Studio Desktop] ${i}`)}),e.on("error",r=>{console.error(`Failed to open Zibby Studio: ${r.message}`)})}}export{M as launchStudio};
|