@zibby/cli 0.4.35 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/cli-login.js +1 -1
- package/dist/auth/ensure-auth.js +3 -3
- package/dist/bin/zibby.js +2 -2
- package/dist/commands/chat.js +1 -1
- package/dist/commands/creds.js +1 -1
- package/dist/commands/init.js +1 -1
- package/dist/commands/list-projects.js +1 -1
- package/dist/commands/mcp.js +6 -0
- package/dist/commands/memory.js +1 -1
- package/dist/commands/project.js +1 -1
- package/dist/commands/run.js +1 -1
- package/dist/commands/studio.js +1 -1
- package/dist/commands/upload.js +1 -1
- package/dist/commands/workflow.js +1 -1
- package/dist/commands/workflows/dedicated-egress.js +15 -15
- package/dist/commands/workflows/delete.js +1 -1
- package/dist/commands/workflows/deploy.js +1 -1
- package/dist/commands/workflows/download.js +1 -1
- package/dist/commands/workflows/env.js +1 -1
- package/dist/commands/workflows/generate.js +1 -1
- package/dist/commands/workflows/list.js +1 -1
- package/dist/commands/workflows/schedule.js +1 -1
- package/dist/commands/workflows/trigger.js +1 -1
- package/dist/config/environments.js +1 -1
- package/dist/package.json +1 -1
- package/package.json +1 -1
package/dist/auth/cli-login.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import n from"chalk";import I from"ora";import{spawn as q}from"child_process";var y={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://
|
|
1
|
+
import n from"chalk";import I from"ora";import{spawn as q}from"child_process";var y={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function h(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";y[e]?o=y[e].apiUrl:o=y.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)`),y.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),y.prod.apiUrl}}import{existsSync as P,mkdirSync as Z,readFileSync as F,writeFileSync as V}from"fs";import{homedir as T}from"os";import{join as m}from"path";function A(){return process.env.ZIBBY_CONFIG_DIR||m(T(),".zibby")}function _(){return m(A(),"config.json")}var J=m(T(),".zibby"),ro=m(J,"config.json");function M(){let o=A();P(o)||Z(o,{recursive:!0})}function u(){try{let o=_();if(P(o)){let e=F(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function f(o){M(),V(_(),JSON.stringify(o,null,2))}function w(){return u().sessionToken||null}function B(o){let e=u();e.sessionToken=o,f(e)}function N(){return u().user||null}function L(o){let e=u();e.user=o,f(e)}function U(){let o=u();delete o.sessionToken,delete o.user,delete o.mem0ProxyUrl,f(o)}function C(o){let e=u();e.proxyUrl=o,f(e)}function R(o){let e=u();e.mem0ProxyUrl=o,f(e)}function z(o){let e=u();e.projects=o,f(e)}import{existsSync as G,mkdirSync as co,readFileSync as lo,writeFileSync as ao,unlinkSync as H}from"fs";import{resolve as $}from"path";import{homedir as W}from"os";function O(){let o=[$(process.cwd(),".zibby","output","active-skills.json"),$(W(),".zibby","output","active-skills.json")];for(let e of o)try{G(e)&&H(e)}catch{}}function K(o){let e=process.platform;try{let t,s;return e==="darwin"?(t="open",s=[o]):e==="win32"?(t="cmd",s=["/c","start","",o]):(t="xdg-open",s=[o]),q(t,s,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function b(){let o=w(),e=N();return o&&e?{loggedIn:!0,user:e,token:o}:{loggedIn:!1}}async function Uo(){try{console.log(n.cyan(`
|
|
2
2
|
\u{1F510} Initiating login...
|
|
3
3
|
`));let o=b();if(o.loggedIn){console.log(n.green("\u2705 Already logged in!")),console.log(n.gray(`User: ${o.user.email}`)),console.log(n.gray(`Name: ${o.user.name}
|
|
4
4
|
`));let{createInterface:e}=await import("readline"),t=e({input:process.stdin,output:process.stdout});return new Promise((s,a)=>{let r=()=>{t.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},i=()=>{console.log(n.yellow(`
|
package/dist/auth/ensure-auth.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync as X,readFileSync as Q}from"fs";import{join as oo}from"path";import U from"chalk";import{confirm as eo}from"@inquirer/prompts";import t from"chalk";import w from"ora";import{spawn as M}from"child_process";var f={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://
|
|
1
|
+
import{existsSync as X,readFileSync as Q}from"fs";import{join as oo}from"path";import U from"chalk";import{confirm as eo}from"@inquirer/prompts";import t from"chalk";import w from"ora";import{spawn as M}from"child_process";var f={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function v(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";f[e]?o=f[e].apiUrl:o=f.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)`),f.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),f.prod.apiUrl}}import{existsSync as T,mkdirSync as F,readFileSync as Z,writeFileSync as J}from"fs";import{homedir as P}from"os";import{join as h}from"path";function A(){return process.env.ZIBBY_CONFIG_DIR||h(P(),".zibby")}function j(){return h(A(),"config.json")}var K=h(P(),".zibby"),io=h(K,"config.json");function V(){let o=A();T(o)||F(o,{recursive:!0})}function l(){try{let o=j();if(T(o)){let e=Z(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function d(o){V(),J(j(),JSON.stringify(o,null,2))}function _(){return l().sessionToken||null}function B(o){let e=l();e.sessionToken=o,d(e)}function N(){return l().user||null}function L(o){let e=l();e.user=o,d(e)}function R(o){let e=l();e.proxyUrl=o,d(e)}function C(o){let e=l();e.mem0ProxyUrl=o,d(e)}function z(o){let e=l();e.projects=o,d(e)}import{existsSync as ao,mkdirSync as uo,readFileSync as po,writeFileSync as go,unlinkSync as fo}from"fs";import{resolve as ho}from"path";import{homedir as vo}from"os";function G(o){let e=process.platform;try{let n,r;return e==="darwin"?(n="open",r=[o]):e==="win32"?(n="cmd",r=["/c","start","",o]):(n="xdg-open",r=[o]),M(n,r,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function H(){let o=_(),e=N();return o&&e?{loggedIn:!0,user:e,token:o}:{loggedIn:!1}}async function $(){try{console.log(t.cyan(`
|
|
2
2
|
\u{1F510} Initiating login...
|
|
3
3
|
`));let o=H();if(o.loggedIn){console.log(t.green("\u2705 Already logged in!")),console.log(t.gray(`User: ${o.user.email}`)),console.log(t.gray(`Name: ${o.user.name}
|
|
4
4
|
`));let{createInterface:e}=await import("readline"),n=e({input:process.stdin,output:process.stdout});return new Promise((r,a)=>{let i=()=>{n.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},u=()=>{console.log(t.yellow(`
|
|
@@ -7,10 +7,10 @@ import{existsSync as X,readFileSync as Q}from"fs";import{join as oo}from"path";i
|
|
|
7
7
|
`)),i(),process.exit(0)};process.on("SIGINT",u),n.question(t.yellow("Continue with this session? (Y/n): "),async p=>{process.removeListener("SIGINT",u),i();try{if(p.toLowerCase()==="n"||p.toLowerCase()==="no"){console.log(t.gray(`Starting new login...
|
|
8
8
|
`));let y=await O();r(y)}else console.log(t.green(`Using existing session.
|
|
9
9
|
`)),r({success:!0,...o})}catch(y){a(y)}})})}return await O()}catch(o){return console.error(t.red(`
|
|
10
|
-
\u274C Login failed:`,o.message)),{success:!1,error:o.message}}}async function W(o){let e=v();try{let n=await fetch(`${e}/projects`,{headers:{Authorization:`Bearer ${o}`}});if(n.ok){let a=((await n.json()).projects||[]).map(i=>({name:i.name,projectId:i.projectId,apiToken:i.apiToken}));return z(a),a}}catch(n){console.log(t.gray(`\u26A0\uFE0F Could not fetch projects: ${n.message}`))}return[]}async function O(){let o=v(),e=w("Requesting login code...").start(),n=await fetch(`${o}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!n.ok){e.fail("Failed to request login code");let
|
|
10
|
+
\u274C Login failed:`,o.message)),{success:!1,error:o.message}}}async function W(o){let e=v();try{let n=await fetch(`${e}/projects`,{headers:{Authorization:`Bearer ${o}`}});if(n.ok){let a=((await n.json()).projects||[]).map(i=>({name:i.name,projectId:i.projectId,apiToken:i.apiToken}));return z(a),a}}catch(n){console.log(t.gray(`\u26A0\uFE0F Could not fetch projects: ${n.message}`))}return[]}async function O(){let o=v(),e=w("Requesting login code...").start(),n=await fetch(`${o}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!n.ok){e.fail("Failed to request login code");let c=await n.json();throw new Error(c.error||"Failed to initiate login")}let{deviceCode:r,userCode:a,verificationUrl:i,expiresIn:u,interval:p}=await n.json();e.succeed("Login code generated"),console.log(""),console.log(t.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")),console.log(t.cyan("\u2551")+t.white.bold(" Complete login in your browser ")+t.cyan("\u2551")),console.log(t.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")),console.log(""),console.log(t.white("Opening browser to login page...")),console.log(t.gray(`Code expires in ${Math.floor(u/60)} minutes`)),console.log(""),await G(i)||(console.log(t.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(t.white("Please open this URL manually: ")+t.blue(i)),console.log(""));let g=w("Waiting for authorization...").start(),Y=(p||3)*1e3,D=Math.floor(u/(p||3)),b=0,k=!1,S=()=>{k=!0,g.stop(),console.log(t.yellow(`
|
|
11
11
|
|
|
12
12
|
\u26A0\uFE0F Login cancelled
|
|
13
|
-
`)),process.exit(0)};process.on("SIGINT",S);try{for(;b<D&&!k;){await q(Y),b++;let
|
|
13
|
+
`)),process.exit(0)};process.on("SIGINT",S);try{for(;b<D&&!k;){await q(Y),b++;let c=await fetch(`${o}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:r})});if(c.status===202)continue;if(!c.ok){g.fail("Authorization failed");let m=await c.json();throw new Error(m.error||"Authorization failed")}let s=await c.json();if(s.status==="authorized"){g.succeed(t.white("Authorization successful!")),B(s.token),L(s.user),s.proxyUrl&&R(s.proxyUrl),s.mem0ProxyUrl&&C(s.mem0ProxyUrl),console.log(""),console.log(t.gray(`User: ${s.user.email}`));let m=w("Fetching projects...").start(),x=await W(s.token);return m.succeed(`Fetched ${x.length} project${x.length!==1?"s":""}`),console.log(t.gray(`Session saved to: ~/.zibby/config.json
|
|
14
14
|
`)),{success:!0,loggedIn:!0,user:s.user,token:s.token}}if(s.status==="denied")throw g.fail("Authorization denied"),new Error("User denied authorization")}throw g.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",S)}}function q(o){return new Promise(e=>setTimeout(e,o))}function E(){try{let o=process.env.HOME||process.env.USERPROFILE;if(!o)return null;let e=oo(o,".zibby","config.json");return X(e)&&JSON.parse(Q(e,"utf-8")).sessionToken||null}catch{return null}}function I(){console.log(`
|
|
15
15
|
Not authenticated.`),console.log(` Run ${U.cyan("zibby login")} or set ${U.cyan("ZIBBY_API_KEY")} in your environment.
|
|
16
16
|
`)}async function Ro(o={}){let e=o.apiKey||process.env.ZIBBY_API_KEY||null,n=E();if(n||e)return{sessionToken:n,apiKey:e};if(!process.stdin.isTTY){if(o.optional)return{sessionToken:null,apiKey:null};I(),process.exit(1)}console.log(U.yellow(`
|
package/dist/bin/zibby.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
process.stdout.on("error",e=>{e.code}),process.stderr.on("error",e=>{e.code}),process.env.DOTENV_CONFIG_QUIET="true";import"@zibby/skills";import{Command as h}from"commander";import{initCommand as k}from"../commands/init.js";import{runCommand as b}from"../commands/run.js";import{videoCommand as v}from"../commands/video.js";import{uploadCommand as C}from"../commands/upload.js";import{ciSetupCommand as I}from"../commands/ci-setup.js";import{setupPlaywrightMcpCommand as P,setupCiCommand as S,testWithVideoCommand as A}from"../commands/setup-scripts.js";import{readFileSync as
|
|
2
|
+
process.stdout.on("error",e=>{e.code}),process.stderr.on("error",e=>{e.code}),process.env.DOTENV_CONFIG_QUIET="true";import"@zibby/skills";import{Command as h}from"commander";import{initCommand as k}from"../commands/init.js";import{runCommand as b}from"../commands/run.js";import{videoCommand as v}from"../commands/video.js";import{uploadCommand as C}from"../commands/upload.js";import{ciSetupCommand as I}from"../commands/ci-setup.js";import{setupPlaywrightMcpCommand as P,setupCiCommand as S,testWithVideoCommand as A}from"../commands/setup-scripts.js";import{readFileSync as x}from"fs";import{fileURLToPath as j}from"url";import{dirname as B,join as _}from"path";import{bootstrapAgentEnv as z}from"../utils/agent-credentials.js";const E=j(import.meta.url),D=B(E),u=JSON.parse(x(_(D,"../package.json"),"utf-8"));function s(e,o){return o.push(e),o}function f(e){if(e===void 0||e===!0||e==="")return 1;const o=parseInt(e,10);if(!Number.isFinite(o)||o<1||o>5)throw new Error(`--warm must be an integer 1-5 (got "${e}"). Omit the flag to disable warm pool.`);return o}const w=`zibby v${u.version}`,i=process.argv.slice(2),R=i.includes("-h")||i.includes("--help"),Z=i.includes("-v")||i.includes("-V")||i.includes("--version");Z&&(console.log(w),process.exit(0));const y=i[0],O=i[1],Y=["logs","uninstall"],L=y==="workflow"&&O==="list";!Y.includes(y)&&!L&&console.log(`${w}
|
|
3
3
|
`),z(process.cwd());const M=i[0]==="chat",U=["--verbose","--agent","--stream","-s"],W=i.length>0&&i.every(e=>U.includes(e)||i[i.indexOf(e)-1]==="--agent"),J=i.length===0||M||W;if(J&&!R){const e={},o=i.indexOf("--agent");o!==-1&&i[o+1]&&(e.agent=i[o+1]),i.includes("--verbose")&&(e.verbose=!0),(i.includes("--stream")||i.includes("-s"))&&(e.stream=!0);const{chatCommand:t}=await import("../commands/chat.js");await t(e),process.exit(0)}const n=new h;n.name("zibby").description("Zibby \u2014 the cloud pipeline for Claude Code, Cursor, Codex, and Gemini. Compose them into structured workflows with schema-enforced handoff.").version(u.version,"-V, --version"),n.configureHelp({visibleCommands:()=>[]}),n.addHelpText("after",`
|
|
4
4
|
Workflow (the platform):
|
|
5
5
|
workflow new <name> Scaffold a new workflow at .zibby/workflows/<name>/
|
|
@@ -45,4 +45,4 @@ Examples:
|
|
|
45
45
|
|
|
46
46
|
Docs: https://docs.zibby.app
|
|
47
47
|
GitHub: https://github.com/ZibbyHQ/zibby-agent
|
|
48
|
-
`),n.command("init").description("Initialize a Zibby project (config + credentials only \u2014 pass -t <name> to also scaffold a workflow template)").argument("[project-name]","Project name (optional, uses current directory if not provided)").option("--agent <type>","Agent to use (claude, cursor, codex, gemini)").option("--memory-backend <backend>","Memory backend to configure (dolt, mem0)","dolt").option("-t, --template <name>","Workflow template to scaffold into .zibby/ (see `zibby template list`). Default: none \u2014 init only sets up config and credentials.").option("--skip-install","Skip npm install").option("--skip-memory","Skip test memory setup during initialization").option("-f, --force","Force reinitialize (overwrite existing config)").option("--headed","Run MCP browser in headed mode (visible browser)").option("--headless","Run MCP browser in headless mode (hidden browser)").option("--api-key <key>","Zibby API key for cloud sync").option("--cloud-sync","Enable cloud sync and install Zibby MCP").option("--agent-key <key>","Agent API key (non-interactive). For Claude this is the per-token API key").option("--agent-oauth-token <token>","Claude OAuth subscription token (non-interactive). Saves to ~/.zibby/config.json").action(k),n.command("test").description("Run a test specification").argument("[spec-path]","Path to test spec file or inline test description in quotes").option("--sources <ids>","Comma-separated test case IDs to fetch from cloud").option("--execution <id>","Execution ID containing the test cases (required with --sources)").option("--agent <type>","Agent to use (claude, cursor, codex, gemini) - overrides config").option("--workflow <name>","Workflow to use (e.g., QuickSmokeWorkflow, quick-smoke)").option("--headless","Run browser in headless mode").option("--node <name>","Run only a specific node (e.g., execute_live, generate_script)").option("--session <id>",'Use existing session (e.g., 1768974629717 or "last") - requires --node').option("--session-path <dir>","Use this session folder (absolute or relative to cwd); Studio pins artifacts here").option("--project <id>","Project ID (optional, auto-detected from ZIBBY_API_KEY)").option("--collection <id-or-name>","Collection ID or name (creates new if name doesn't exist)").option("--folder <path>","Folder path within collection (optional, requires --collection)").option("--sync","Force upload to cloud (overrides cloudSync: false)").option("--no-sync","Skip upload to cloud (overrides cloudSync: true)").option("--config <path>","Path to config file",".zibby.config.mjs").option("--auto-approve","Auto-approve MCP tools (for CI/CD)").option("-o, --open","Open test results in browser after completion").option("--verbose","Show info level logs").option("--debug","Show debug level logs (most verbose)").option("-m, --mem","Enable test memory (Dolt-backed knowledge from previous runs)").action((e,o)=>(o.debug?process.env.ZIBBY_DEBUG="true":o.verbose&&(process.env.ZIBBY_VERBOSE="true"),b(e,o))),n.command("implement").description("Implement a Jira ticket using AI agent (runs in ECS container)").action(async(...e)=>{const{implementCommand:o}=await import("../commands/implement.js");return o(...e)}),n.command("analyze").description("Analyze a Jira ticket against the codebase (runs in ECS container)").option("--workflow <path>","Path to a local workflow JSON file (e.g., .zibby/workflow-analysis.json)").action(async(...e)=>{const{analyzeCommand:o}=await import("../commands/analyze-graph.js");return o(...e)}),n.command("video").description("Organize test videos next to test files").action(v),n.command("upload <spec-path>").description("Upload existing test artifacts to Zibby Cloud").option("--project <id>","Project ID (REQUIRED - use flag or ZIBBY_PROJECT_ID env)").option("--collection <id-or-name>","Collection ID or name (creates new if name doesn't exist)").option("--folder <path>","Folder path within collection (optional)").option("--agent <type>","Agent used (for metadata)").action(C),n.command("login").description("Log in to Zibby (opens browser for authentication)").action(async()=>{const{loginCli:e}=await import("../auth/cli-login.js");await e(),process.exit(0)}),n.command("logout").description("Log out from Zibby (clears saved session)").action(async()=>{const{logoutCli:e}=await import("../auth/cli-login.js");e(),process.exit(0)}),n.command("status").description("Show current authentication status and token details").option("--json","Output in JSON format (for scripts)").action(async e=>{const{showLoginStatus:o}=await import("../auth/cli-login.js");await o(e),process.exit(0)}),n.command("list").description("List your projects and API tokens").action(async()=>{const{listProjectsCommand:e}=await import("../commands/list-projects.js");await e()}),n.command("ci-setup").description("Setup Cursor Agent for CI/CD (patch and configure)").option("--get-keys","Get MCP approval keys").option("--save","Save approval keys to project").action(I),n.command("setup-playwright").description("Setup official Playwright MCP (from cursor-agent-package)").option("--headed","Configure MCP in headed mode (visible browser)").option("--viewport-width <width>","Viewport width (default: 1280)","1280").option("--viewport-height <height>","Viewport height (default: 720)","720").action(e=>{const o={width:parseInt(e.viewportWidth,10)||1280,height:parseInt(e.viewportHeight,10)||720};return P({...e,viewport:o})}),n.command("setup-ci-full").description("Complete CI/CD setup from scratch").action(S),n.command("test-video").description("Run Playwright tests with video recording").argument("[test-file]","Test file to run (default: tests/)").option("--headed","Run in headed mode (visible browser)").action(A),n.command("generate").description("Generate test specs from a ticket + codebase (local analysis using real AI agent)").option("-t, --ticket <key>","Jira ticket key (fetches automatically)").option("-i, --input <file>","Input file with ticket description/requirements").option("-d, --description <text>","Inline ticket description").option("--repo <path>","Path to the codebase (default: current directory)").option("--agent <type>","Agent to use (codex, claude, cursor, gemini)").option("--model <model>","Model override").option("-o, --output <dir>","Output directory for spec files (default: test-specs)").action(async e=>{const{generateCommand:o}=await import("../commands/generate.js");return o(e)}),n.command("studio").description("Launch Zibby Studio desktop (installs from CDN if needed). Uses this folder as the Zibby project.").option("-p, --port <port>","Port for the Studio API bridge (default: 3847)").option("--no-open","Start the API only; do not launch desktop app").option("--update","Force re-download of the latest Studio binary").action(async e=>{const{studioCommand:o}=await import("../commands/studio.js");return o(e)});const m=n.command("creds").description("Manage credentials Zibby has stored for your workspace (KMS-encrypted)");m.command("list").description("List credentials stored for your workspace (masked)").action(async()=>{const{listCmd:e}=await import("../commands/creds.js");await e(),process.exit(0)}),m.command("sync").description("Re-read ~/.zibby/credentials.env and upload any new tokens").action(async()=>{const{syncCmd:e}=await import("../commands/creds.js");await e(),process.exit(0)}),m.command("remove <type> <index>").description("Remove a stored credential. e.g. zibby creds remove oauth 0").action(async(e,o)=>{const{removeCmd:t}=await import("../commands/creds.js");await t(e,o),process.exit(0)});const F=n.command("g").description("Generate scaffolds");F.command("workflow [name]").description("Scaffold a new custom workflow in .zibby/workflows/<name>/ (auto-generates name if omitted)").option("-t, --template <name>","Scaffold from a template (see `zibby template list`). Future: also accepts npm package / git URL identifiers.").option("--skip-install","Skip running `npm install` in the new workflow folder").option("--skip-init-check","Skip the first-run init prompt that fires when ~/.zibby/config.json is missing (CI/scripted setups)").option("--agent-helpers [list]",'Install agent helpers (Claude Code / Cursor slash commands). List = comma-separated, e.g. "claude" or "claude,cursor". Bare flag defaults to claude.').option("--no-agent-helpers","Skip agent helpers even if .zibby.config.mjs says install").option("--agent <agent>","(legacy) Set up agent helpers: claude | cursor | codex | all | none. Prefer --agent-helpers.").option("--force-agents","Overwrite user-edited agent helper files (use with --agent-helpers)").action(async(e,o)=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(e,o)}),n.command("start <workflow-name>").description("Start a local dev server for a custom workflow").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(e,o)=>{const{startWorkflowCommand:t}=await import("../commands/workflows/start.js");return t(e,o)}),n.command("run <workflow-name>").description("Run a workflow locally \u2014 one-shot (alias of `zibby workflow run`)").option("-p, --param <key=value>","Input param (repeatable)",s,[]).option("--input <json>","Input as JSON string").option("--input-file <path>","Input as JSON file").action(async(e,o)=>{const{runLocalWorkflowCommand:t}=await import("../commands/workflows/run-local.js");return t(e,o)}),n.command("deploy [workflow-name]").description("Deploy a custom workflow to Zibby Cloud (interactive selection if workflow-name not provided)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--dedicated-ip <action>","Manage dedicated egress IP addon: enable | status | disable | use | unuse").option("--env <path>","Path to a .env file to sync into per-workflow env vars after deploy (repeatable)",s,[]).option("--verbose","Show raw CodeBuild logs during the bundle build").option("--no-creds-check","Skip the project secrets sanity check (CI/CD when the secret is provisioned out-of-band)").option("--force","Deploy even if the source checksum matches the last deployed version (bypasses the unchanged check)").option("--warm [count]","Enable warm-pool execution for this workflow (default 1, max 5). Skips ~60s Fargate cold-start by routing triggers to a per-account pool of always-on tasks. Pricing applies (paid feature).",f).option("--ai-agent <agent>","Per-workflow AI agent override (claude | cursor | codex | gemini). Falls back to the project default when omitted.").action(async(e,o)=>{if(o.dedicatedIp){const{dedicatedEgressCommand:r}=await import("../commands/workflows/dedicated-egress.js");return r(o.dedicatedIp,o.project)}o.aiAgent&&!["claude","cursor","codex","gemini"].includes(o.aiAgent)&&(console.error(chalk.red(`Invalid --ai-agent: ${o.aiAgent}. Must be one of: claude, cursor, codex, gemini.`)),process.exit(1));const{deployWorkflowCommand:t}=await import("../commands/workflows/deploy.js");return t(e,o)}),n.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (interactive selection if not provided). Get UUIDs from `zibby workflow list`.").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").option("-t, --follow","Stream logs in real-time after triggering (no need to run `logs -t` separately)").action(async(e,o)=>{const{triggerWorkflowCommand:t}=await import("../commands/workflows/trigger.js");return t(e,o)}),n.command("logs [jobId]").description("Fetch and display logs from a workflow execution (use -t to stream in real-time)").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (fetches the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --follow","Stream logs in real-time (like Heroku logs -t)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(e,o)=>{const{logsCommand:t}=await import("../commands/workflows/logs.js");return t(e,o)}),n.command("run-workflow").description("Run a deployed workflow from S3 sources (used by ECS containers)").action(async()=>{const{runWorkflowCommand:e}=await import("../commands/workflows/run.js");return e()});const g=n.command("template").description("Manage workflow templates in this project");g.command("list").description("List available workflow templates").action(async()=>{const{templateListCommand:e}=await import("../commands/template.js");return e()}),g.command("add",{hidden:!0}).argument("<name>","Template name (see `zibby template list`)").description("(deprecated \u2014 `zibby test` auto-installs the template) Copy a template into .zibby/, overwriting existing files").option("--skip-memory","Strip SKILLS.MEMORY from copied execute-live.mjs (browser-test only)").action(async(e,o)=>{const{templateAddCommand:t}=await import("../commands/template.js");return t(e,{enableMemory:!o.skipMemory})});const c=n.command("memory").description("Test memory database \u2014 version-controlled knowledge from runs");c.command("stats").description("Show memory database statistics").action(async()=>{const{memoryStatsCommand:e}=await import("../commands/memory.js");return e()}),c.command("init").description("Initialize the memory database (Dolt)").action(async()=>{const{memoryInitCommand:e}=await import("../commands/memory.js");return e()}),c.command("compact").description("Prune old data and run Dolt GC to reclaim storage").option("--max-runs <n>","Keep last N runs per spec (default: 50)",parseInt).option("--max-age <days>","Remove data older than N days (default: 90)",parseInt).action(async e=>{const{memoryCompactCommand:o}=await import("../commands/memory.js");return o(e)}),c.command("reset").description("Wipe the memory database").option("-f, --force","Confirm reset").action(async e=>{const{memoryResetCommand:o}=await import("../commands/memory.js");return o(e)}),c.command("cost").description("Show real LLM token usage from past runs (input/output/cache)").action(async()=>{const{memoryCostCommand:e}=await import("../commands/memory.js");return e()});const p=c.command("remote").description("Configure a remote so the team shares cross-spec memory");p.command("add").argument("<url>","Remote URL: aws://, gs://, https://, file:///").option("--name <name>","Remote name (default: origin)","origin").description("Point the local memory DB at a shared remote (S3/GCS/DoltHub/filesystem)").action(async(e,o)=>{const{memoryRemoteAddCommand:t}=await import("../commands/memory.js");return t(e,o)}),p.command("use").description("Switch to a managed remote backend. Currently: --hosted (Zibby-managed S3, signed-in users only).").option("--hosted","Use Zibby-managed S3 (allocates a tenant-scoped prefix per-project)").option("--project-id <id>","Override the projectId from .zibby.config.mjs").action(async e=>{e.hosted||(console.log("Pass --hosted. (Other backends will be added later.)"),process.exit(1));const{memoryRemoteUseHostedCommand:o}=await import("../commands/memory.js");return o(e)}),p.command("info").description("Show the configured memory remote (if any)").action(async()=>{const{memoryRemoteInfoCommand:e}=await import("../commands/memory.js");return e()}),p.command("remove").argument("[name]","Remote name (default: origin)").description("Remove a configured memory remote (memory becomes local-only)").action(async e=>{const{memoryRemoteRemoveCommand:o}=await import("../commands/memory.js");return o(e)}),c.command("pull").description("Pull latest team memory from the configured remote").action(async()=>{const{memoryPullCommand:e}=await import("../commands/memory.js");return e()}),c.command("push").description("Push local memory to the configured remote (auto-runs after passing tests)").action(async()=>{const{memoryPushCommand:e}=await import("../commands/memory.js");return e()});const T=n.command("agents").description("Manage Claude/Cursor/Codex helper files for working with Zibby workflows");T.command("add [agent]").description("Add agent helpers (claude | cursor | codex | all). Prompts if no agent given.").option("--force","Overwrite user-edited helper files").action(async(e,o)=>{const{runAgentHelpers:t,addAgent:r}=await import("../commands/workflows/agent-helpers.js");if(e){const l=["claude","cursor","codex","all","none"];l.includes(e)||(console.error(`Unknown agent "${e}". Valid: ${l.join(", ")}`),process.exit(1)),e==="none"?await t({forcedAgents:["none"],force:o.force===!0}):e==="all"?await t({forcedAgents:["claude","cursor","codex"],force:o.force===!0}):await r(e,{force:o.force===!0})}else await t({forcedAgents:void 0,force:o.force===!0,forcePrompt:!0})});const a=n.command("workflow").description("Manage workflow graphs \u2014 new, start, deploy, trigger, logs, list, download, delete");a.command("new [name]").description("Scaffold a new custom workflow (alias of `zibby g workflow`)").option("-t, --template <name>","Scaffold from a template (see `zibby template list`). Future: also accepts npm package / git URL identifiers.").option("--skip-install","Skip running `npm install` in the new workflow folder").option("--skip-init-check","Skip the first-run init prompt that fires when ~/.zibby/config.json is missing (CI/scripted setups)").option("--agent-helpers [list]",'Install agent helpers (Claude Code / Cursor slash commands). List = comma-separated, e.g. "claude" or "claude,cursor". Bare flag defaults to claude.').option("--no-agent-helpers","Skip agent helpers even if .zibby.config.mjs says install").option("--agent <agent>","(legacy) Set up agent helpers: claude | cursor | codex | all | none. Prefer --agent-helpers.").option("--force-agents","Overwrite user-edited agent helper files (use with --agent-helpers)").action(async(e,o)=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(e,o)}),a.command("run <workflow-name>").description("Run a workflow locally \u2014 one-shot, same input flags as `workflow trigger`").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON file \u2014 lowest precedence").action(async(e,o)=>{const{runLocalWorkflowCommand:t}=await import("../commands/workflows/run-local.js");return t(e,o)}),a.command("start <workflow-name>").description("Start a long-lived local dev server (Studio integration). Prefer `workflow run` for one-shots.").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(e,o)=>{const{startWorkflowCommand:t}=await import("../commands/workflows/start.js");return t(e,o)}),a.command("deploy [workflow-name]").description("Deploy a workflow to Zibby Cloud (alias of `zibby deploy`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--env <path>","Path to a .env file to sync into per-workflow env vars after deploy (repeatable)",s,[]).option("--verbose","Show raw CodeBuild logs during the bundle build").option("--no-creds-check","Skip the project secrets sanity check (CI/CD when the secret is provisioned out-of-band)").option("--force","Deploy even if the source checksum matches the last deployed version (bypasses the unchanged check)").option("--warm [count]","Enable warm-pool execution for this workflow (default 1, max 5). Skips ~60s Fargate cold-start by routing triggers to a per-account pool of always-on tasks. Pricing applies (paid feature).",f).action(async(e,o)=>{const{deployWorkflowCommand:t}=await import("../commands/workflows/deploy.js");return t(e,o)}),a.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (alias of `zibby trigger`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").option("-t, --follow","Stream logs in real-time after triggering (no need to run `logs -t` separately)").action(async(e,o)=>{const{triggerWorkflowCommand:t}=await import("../commands/workflows/trigger.js");return t(e,o)}),a.command("logs [jobId]").description("Tail logs from a workflow execution (alias of `zibby logs`)").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (fetches the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --follow","Stream logs in real-time (like Heroku logs -t)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(e,o)=>{const{logsCommand:t}=await import("../commands/workflows/logs.js");return t(e,o)}),a.command("download <uuid>").description("Download a deployed workflow back to local (edit it, then re-deploy with `zibby workflow deploy`)").option("--dest <path>","Destination directory (default: ./workflows/<name> when run inside a .zibby project)").option("--force","Overwrite without prompting; bypass uuid-mismatch guard").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{downloadWorkflowCommand:t}=await import("../commands/workflows/download.js");return t(e,o)}),a.command("list").description("List all workflows (local + remote if credentials available)").option("--local-only","Show only local workflows").option("--remote-only","Show only remote workflows (requires --project)").option("--project <id>","Project ID (optional, uses ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async e=>{if(e.remoteOnly){const{workflowListCommand:t}=await import("../commands/workflow.js");return t(e)}if(e.localOnly){const{listLocalWorkflowsCommand:t}=await import("../commands/workflows/list.js");return t(e)}const{listAllWorkflowsCommand:o}=await import("../commands/workflows/list.js");return o(e)}),a.command("validate <name>").description("Static-check a local workflow (.zibby/workflows/<name>/). Catches schema/topology/skill errors in ~30ms before you run anything.").option("--verbose","Print stack traces on graph.mjs import errors").action(async(e,o)=>{const{validateCommand:t}=await import("../commands/workflows/validate.js");return t(e,o)}),a.command("schedule <uuid> [action] [cron]").description(`Manage a workflow's cron schedule. Actions: get (default) | set <cron> | clear. Cron is Unix 5-field, e.g. "0 9 * * 1-5".`).option("--tz <iana>","IANA timezone for the schedule (default: UTC)").option("-p, --param <key=value>","Fixed input param for every scheduled run (repeatable)",s,[]).option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o,t,r)=>{const{scheduleCommand:l}=await import("../commands/workflows/schedule.js");return l(e,o,t,r)}),a.command("delete <uuid>").description("Delete a deployed workflow by UUID").action(async e=>{const{deleteWorkflowCommand:o}=await import("../commands/workflows/delete.js");return o(e,{})});const d=a.command("env").description("Manage per-workflow encrypted env vars (set ANTHROPIC_API_KEY, DATABASE_URL, etc. per workflow)");d.command("list <uuid>").description("List env var key names for a workflow (values never returned)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{listEnvCommand:t}=await import("../commands/workflows/env.js");return t(e,o)}),d.command("set <uuid> <kv>").description("Set or update one env var: zibby workflow env set <uuid> KEY=value").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o,t)=>{const{setEnvCommand:r}=await import("../commands/workflows/env.js");return r(e,o,t)}),d.command("unset <uuid> <key>").description("Remove one env var from a workflow").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o,t)=>{const{unsetEnvCommand:r}=await import("../commands/workflows/env.js");return r(e,o,t)}),d.command("push <uuid>").description("Bulk-replace env from one or more .env files (later files override). Removes any keys not in the new map.").option("--file <path>","Path to a .env file (repeatable, e.g. --file .env --file .env.prod)",s,[]).option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{pushEnvCommand:t}=await import("../commands/workflows/env.js");return t(e,o)});const K=n.command("project").description("Manage Zibby projects");K.command("list").description("List all projects").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async e=>{const{projectListCommand:o}=await import("../commands/project.js");return o(e)});const N=n.command("run-queue").description("Parallel capacity \u2014 on-disk wait queue (see parallel.waitWhenAtCapacity in .zibby.config.mjs)");N.command("list").description("List CLI processes waiting for a run slot").option("--config <path>","Path to config file",".zibby.config.mjs").action(async e=>{const{runCapacityQueueListCommand:o}=await import("../commands/run-capacity-queue-cli.js");await o(e),process.exit(0)}),n.command("uninstall").description("Remove all Zibby data: global CLI, ~/.zibby, Cursor MCP config, Studio, and current project").option("--dry-run","Show what would be deleted without deleting").option("--deep","Also remove npx cache dirs containing zibby").action(async e=>{const{uninstallCommand:o}=await import("../commands/uninstall.js");await o(e),process.exit(0)}),n.parse();
|
|
48
|
+
`),n.command("init").description("Initialize a Zibby project (config + credentials only \u2014 pass -t <name> to also scaffold a workflow template)").argument("[project-name]","Project name (optional, uses current directory if not provided)").option("--agent <type>","Agent to use (claude, cursor, codex, gemini)").option("--memory-backend <backend>","Memory backend to configure (dolt, mem0)","dolt").option("-t, --template <name>","Workflow template to scaffold into .zibby/ (see `zibby template list`). Default: none \u2014 init only sets up config and credentials.").option("--skip-install","Skip npm install").option("--skip-memory","Skip test memory setup during initialization").option("-f, --force","Force reinitialize (overwrite existing config)").option("--headed","Run MCP browser in headed mode (visible browser)").option("--headless","Run MCP browser in headless mode (hidden browser)").option("--api-key <key>","Zibby API key for cloud sync").option("--cloud-sync","Enable cloud sync and install Zibby MCP").option("--agent-key <key>","Agent API key (non-interactive). For Claude this is the per-token API key").option("--agent-oauth-token <token>","Claude OAuth subscription token (non-interactive). Saves to ~/.zibby/config.json").action(k),n.command("test").description("Run a test specification").argument("[spec-path]","Path to test spec file or inline test description in quotes").option("--sources <ids>","Comma-separated test case IDs to fetch from cloud").option("--execution <id>","Execution ID containing the test cases (required with --sources)").option("--agent <type>","Agent to use (claude, cursor, codex, gemini) - overrides config").option("--workflow <name>","Workflow to use (e.g., QuickSmokeWorkflow, quick-smoke)").option("--headless","Run browser in headless mode").option("--node <name>","Run only a specific node (e.g., execute_live, generate_script)").option("--session <id>",'Use existing session (e.g., 1768974629717 or "last") - requires --node').option("--session-path <dir>","Use this session folder (absolute or relative to cwd); Studio pins artifacts here").option("--project <id>","Project ID (optional, auto-detected from ZIBBY_API_KEY)").option("--collection <id-or-name>","Collection ID or name (creates new if name doesn't exist)").option("--folder <path>","Folder path within collection (optional, requires --collection)").option("--sync","Force upload to cloud (overrides cloudSync: false)").option("--no-sync","Skip upload to cloud (overrides cloudSync: true)").option("--config <path>","Path to config file",".zibby.config.mjs").option("--auto-approve","Auto-approve MCP tools (for CI/CD)").option("-o, --open","Open test results in browser after completion").option("--verbose","Show info level logs").option("--debug","Show debug level logs (most verbose)").option("-m, --mem","Enable test memory (Dolt-backed knowledge from previous runs)").action((e,o)=>(o.debug?process.env.ZIBBY_DEBUG="true":o.verbose&&(process.env.ZIBBY_VERBOSE="true"),b(e,o))),n.command("implement").description("Implement a Jira ticket using AI agent (runs in ECS container)").action(async(...e)=>{const{implementCommand:o}=await import("../commands/implement.js");return o(...e)}),n.command("analyze").description("Analyze a Jira ticket against the codebase (runs in ECS container)").option("--workflow <path>","Path to a local workflow JSON file (e.g., .zibby/workflow-analysis.json)").action(async(...e)=>{const{analyzeCommand:o}=await import("../commands/analyze-graph.js");return o(...e)}),n.command("video").description("Organize test videos next to test files").action(v),n.command("upload <spec-path>").description("Upload existing test artifacts to Zibby Cloud").option("--project <id>","Project ID (REQUIRED - use flag or ZIBBY_PROJECT_ID env)").option("--collection <id-or-name>","Collection ID or name (creates new if name doesn't exist)").option("--folder <path>","Folder path within collection (optional)").option("--agent <type>","Agent used (for metadata)").action(C),n.command("login").description("Log in to Zibby (opens browser for authentication)").action(async()=>{const{loginCli:e}=await import("../auth/cli-login.js");await e(),process.exit(0)}),n.command("logout").description("Log out from Zibby (clears saved session)").action(async()=>{const{logoutCli:e}=await import("../auth/cli-login.js");e(),process.exit(0)}),n.command("status").description("Show current authentication status and token details").option("--json","Output in JSON format (for scripts)").action(async e=>{const{showLoginStatus:o}=await import("../auth/cli-login.js");await o(e),process.exit(0)}),n.command("list").description("List your projects and API tokens").action(async()=>{const{listProjectsCommand:e}=await import("../commands/list-projects.js");await e()}),n.command("ci-setup").description("Setup Cursor Agent for CI/CD (patch and configure)").option("--get-keys","Get MCP approval keys").option("--save","Save approval keys to project").action(I),n.command("setup-playwright").description("Setup official Playwright MCP (from cursor-agent-package)").option("--headed","Configure MCP in headed mode (visible browser)").option("--viewport-width <width>","Viewport width (default: 1280)","1280").option("--viewport-height <height>","Viewport height (default: 720)","720").action(e=>{const o={width:parseInt(e.viewportWidth,10)||1280,height:parseInt(e.viewportHeight,10)||720};return P({...e,viewport:o})}),n.command("setup-ci-full").description("Complete CI/CD setup from scratch").action(S),n.command("test-video").description("Run Playwright tests with video recording").argument("[test-file]","Test file to run (default: tests/)").option("--headed","Run in headed mode (visible browser)").action(A),n.command("generate").description("Generate test specs from a ticket + codebase (local analysis using real AI agent)").option("-t, --ticket <key>","Jira ticket key (fetches automatically)").option("-i, --input <file>","Input file with ticket description/requirements").option("-d, --description <text>","Inline ticket description").option("--repo <path>","Path to the codebase (default: current directory)").option("--agent <type>","Agent to use (codex, claude, cursor, gemini)").option("--model <model>","Model override").option("-o, --output <dir>","Output directory for spec files (default: test-specs)").action(async e=>{const{generateCommand:o}=await import("../commands/generate.js");return o(e)}),n.command("studio").description("Launch Zibby Studio desktop (installs from CDN if needed). Uses this folder as the Zibby project.").option("-p, --port <port>","Port for the Studio API bridge (default: 3847)").option("--no-open","Start the API only; do not launch desktop app").option("--update","Force re-download of the latest Studio binary").action(async e=>{const{studioCommand:o}=await import("../commands/studio.js");return o(e)});const m=n.command("creds").description("Manage credentials Zibby has stored for your workspace (KMS-encrypted)");m.command("list").description("List credentials stored for your workspace (masked)").action(async()=>{const{listCmd:e}=await import("../commands/creds.js");await e(),process.exit(0)}),m.command("sync").description("Re-read ~/.zibby/credentials.env and upload any new tokens").action(async()=>{const{syncCmd:e}=await import("../commands/creds.js");await e(),process.exit(0)}),m.command("remove <type> <index>").description("Remove a stored credential. e.g. zibby creds remove oauth 0").action(async(e,o)=>{const{removeCmd:t}=await import("../commands/creds.js");await t(e,o),process.exit(0)});const F=n.command("g").description("Generate scaffolds");F.command("workflow [name]").description("Scaffold a new custom workflow in .zibby/workflows/<name>/ (auto-generates name if omitted)").option("-t, --template <name>","Scaffold from a template (see `zibby template list`). Future: also accepts npm package / git URL identifiers.").option("--skip-install","Skip running `npm install` in the new workflow folder").option("--skip-init-check","Skip the first-run init prompt that fires when ~/.zibby/config.json is missing (CI/scripted setups)").option("--agent-helpers [list]",'Install agent helpers (Claude Code / Cursor slash commands). List = comma-separated, e.g. "claude" or "claude,cursor". Bare flag defaults to claude.').option("--no-agent-helpers","Skip agent helpers even if .zibby.config.mjs says install").option("--agent <agent>","(legacy) Set up agent helpers: claude | cursor | codex | all | none. Prefer --agent-helpers.").option("--force-agents","Overwrite user-edited agent helper files (use with --agent-helpers)").action(async(e,o)=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(e,o)}),n.command("start <workflow-name>").description("Start a local dev server for a custom workflow").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(e,o)=>{const{startWorkflowCommand:t}=await import("../commands/workflows/start.js");return t(e,o)}),n.command("run <workflow-name>").description("Run a workflow locally \u2014 one-shot (alias of `zibby workflow run`)").option("-p, --param <key=value>","Input param (repeatable)",s,[]).option("--input <json>","Input as JSON string").option("--input-file <path>","Input as JSON file").action(async(e,o)=>{const{runLocalWorkflowCommand:t}=await import("../commands/workflows/run-local.js");return t(e,o)}),n.command("deploy [workflow-name]").description("Deploy a custom workflow to Zibby Cloud (interactive selection if workflow-name not provided)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--dedicated-ip <action>","Manage dedicated egress IP addon: enable | status | disable | use | unuse").option("--env <path>","Path to a .env file to sync into per-workflow env vars after deploy (repeatable)",s,[]).option("--verbose","Show raw CodeBuild logs during the bundle build").option("--no-creds-check","Skip the project secrets sanity check (CI/CD when the secret is provisioned out-of-band)").option("--force","Deploy even if the source checksum matches the last deployed version (bypasses the unchanged check)").option("--warm [count]","Enable warm-pool execution for this workflow (default 1, max 5). Skips ~60s Fargate cold-start by routing triggers to a per-account pool of always-on tasks. Pricing applies (paid feature).",f).option("--ai-agent <agent>","Per-workflow AI agent override (claude | cursor | codex | gemini). Falls back to the project default when omitted.").action(async(e,o)=>{if(o.dedicatedIp){const{dedicatedEgressCommand:r}=await import("../commands/workflows/dedicated-egress.js");return r(o.dedicatedIp,o.project)}o.aiAgent&&!["claude","cursor","codex","gemini"].includes(o.aiAgent)&&(console.error(chalk.red(`Invalid --ai-agent: ${o.aiAgent}. Must be one of: claude, cursor, codex, gemini.`)),process.exit(1));const{deployWorkflowCommand:t}=await import("../commands/workflows/deploy.js");return t(e,o)}),n.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (interactive selection if not provided). Get UUIDs from `zibby workflow list`.").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").option("-t, --follow","Stream logs in real-time after triggering (no need to run `logs -t` separately)").action(async(e,o)=>{const{triggerWorkflowCommand:t}=await import("../commands/workflows/trigger.js");return t(e,o)}),n.command("logs [jobId]").description("Fetch and display logs from a workflow execution (use -t to stream in real-time)").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (fetches the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --follow","Stream logs in real-time (like Heroku logs -t)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(e,o)=>{const{logsCommand:t}=await import("../commands/workflows/logs.js");return t(e,o)}),n.command("run-workflow").description("Run a deployed workflow from S3 sources (used by ECS containers)").action(async()=>{const{runWorkflowCommand:e}=await import("../commands/workflows/run.js");return e()});const g=n.command("template").description("Manage workflow templates in this project");g.command("list").description("List available workflow templates").action(async()=>{const{templateListCommand:e}=await import("../commands/template.js");return e()}),g.command("add",{hidden:!0}).argument("<name>","Template name (see `zibby template list`)").description("(deprecated \u2014 `zibby test` auto-installs the template) Copy a template into .zibby/, overwriting existing files").option("--skip-memory","Strip SKILLS.MEMORY from copied execute-live.mjs (browser-test only)").action(async(e,o)=>{const{templateAddCommand:t}=await import("../commands/template.js");return t(e,{enableMemory:!o.skipMemory})});const c=n.command("memory").description("Test memory database \u2014 version-controlled knowledge from runs");c.command("stats").description("Show memory database statistics").action(async()=>{const{memoryStatsCommand:e}=await import("../commands/memory.js");return e()}),c.command("init").description("Initialize the memory database (Dolt)").action(async()=>{const{memoryInitCommand:e}=await import("../commands/memory.js");return e()}),c.command("compact").description("Prune old data and run Dolt GC to reclaim storage").option("--max-runs <n>","Keep last N runs per spec (default: 50)",parseInt).option("--max-age <days>","Remove data older than N days (default: 90)",parseInt).action(async e=>{const{memoryCompactCommand:o}=await import("../commands/memory.js");return o(e)}),c.command("reset").description("Wipe the memory database").option("-f, --force","Confirm reset").action(async e=>{const{memoryResetCommand:o}=await import("../commands/memory.js");return o(e)}),c.command("cost").description("Show real LLM token usage from past runs (input/output/cache)").action(async()=>{const{memoryCostCommand:e}=await import("../commands/memory.js");return e()});const p=c.command("remote").description("Configure a remote so the team shares cross-spec memory");p.command("add").argument("<url>","Remote URL: aws://, gs://, https://, file:///").option("--name <name>","Remote name (default: origin)","origin").description("Point the local memory DB at a shared remote (S3/GCS/DoltHub/filesystem)").action(async(e,o)=>{const{memoryRemoteAddCommand:t}=await import("../commands/memory.js");return t(e,o)}),p.command("use").description("Switch to a managed remote backend. Currently: --hosted (Zibby-managed S3, signed-in users only).").option("--hosted","Use Zibby-managed S3 (allocates a tenant-scoped prefix per-project)").option("--project-id <id>","Override the projectId from .zibby.config.mjs").action(async e=>{e.hosted||(console.log("Pass --hosted. (Other backends will be added later.)"),process.exit(1));const{memoryRemoteUseHostedCommand:o}=await import("../commands/memory.js");return o(e)}),p.command("info").description("Show the configured memory remote (if any)").action(async()=>{const{memoryRemoteInfoCommand:e}=await import("../commands/memory.js");return e()}),p.command("remove").argument("[name]","Remote name (default: origin)").description("Remove a configured memory remote (memory becomes local-only)").action(async e=>{const{memoryRemoteRemoveCommand:o}=await import("../commands/memory.js");return o(e)}),c.command("pull").description("Pull latest team memory from the configured remote").action(async()=>{const{memoryPullCommand:e}=await import("../commands/memory.js");return e()}),c.command("push").description("Push local memory to the configured remote (auto-runs after passing tests)").action(async()=>{const{memoryPushCommand:e}=await import("../commands/memory.js");return e()});const T=n.command("agents").description("Manage Claude/Cursor/Codex helper files for working with Zibby workflows");T.command("add [agent]").description("Add agent helpers (claude | cursor | codex | all). Prompts if no agent given.").option("--force","Overwrite user-edited helper files").action(async(e,o)=>{const{runAgentHelpers:t,addAgent:r}=await import("../commands/workflows/agent-helpers.js");if(e){const l=["claude","cursor","codex","all","none"];l.includes(e)||(console.error(`Unknown agent "${e}". Valid: ${l.join(", ")}`),process.exit(1)),e==="none"?await t({forcedAgents:["none"],force:o.force===!0}):e==="all"?await t({forcedAgents:["claude","cursor","codex"],force:o.force===!0}):await r(e,{force:o.force===!0})}else await t({forcedAgents:void 0,force:o.force===!0,forcePrompt:!0})});const a=n.command("workflow").description("Manage workflow graphs \u2014 new, start, deploy, trigger, logs, list, download, delete");a.command("new [name]").description("Scaffold a new custom workflow (alias of `zibby g workflow`)").option("-t, --template <name>","Scaffold from a template (see `zibby template list`). Future: also accepts npm package / git URL identifiers.").option("--skip-install","Skip running `npm install` in the new workflow folder").option("--skip-init-check","Skip the first-run init prompt that fires when ~/.zibby/config.json is missing (CI/scripted setups)").option("--agent-helpers [list]",'Install agent helpers (Claude Code / Cursor slash commands). List = comma-separated, e.g. "claude" or "claude,cursor". Bare flag defaults to claude.').option("--no-agent-helpers","Skip agent helpers even if .zibby.config.mjs says install").option("--agent <agent>","(legacy) Set up agent helpers: claude | cursor | codex | all | none. Prefer --agent-helpers.").option("--force-agents","Overwrite user-edited agent helper files (use with --agent-helpers)").action(async(e,o)=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(e,o)}),a.command("run <workflow-name>").description("Run a workflow locally \u2014 one-shot, same input flags as `workflow trigger`").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON file \u2014 lowest precedence").action(async(e,o)=>{const{runLocalWorkflowCommand:t}=await import("../commands/workflows/run-local.js");return t(e,o)}),a.command("start <workflow-name>").description("Start a long-lived local dev server (Studio integration). Prefer `workflow run` for one-shots.").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(e,o)=>{const{startWorkflowCommand:t}=await import("../commands/workflows/start.js");return t(e,o)}),a.command("deploy [workflow-name]").description("Deploy a workflow to Zibby Cloud (alias of `zibby deploy`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--env <path>","Path to a .env file to sync into per-workflow env vars after deploy (repeatable)",s,[]).option("--verbose","Show raw CodeBuild logs during the bundle build").option("--no-creds-check","Skip the project secrets sanity check (CI/CD when the secret is provisioned out-of-band)").option("--force","Deploy even if the source checksum matches the last deployed version (bypasses the unchanged check)").option("--warm [count]","Enable warm-pool execution for this workflow (default 1, max 5). Skips ~60s Fargate cold-start by routing triggers to a per-account pool of always-on tasks. Pricing applies (paid feature).",f).action(async(e,o)=>{const{deployWorkflowCommand:t}=await import("../commands/workflows/deploy.js");return t(e,o)}),a.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (alias of `zibby trigger`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").option("-t, --follow","Stream logs in real-time after triggering (no need to run `logs -t` separately)").action(async(e,o)=>{const{triggerWorkflowCommand:t}=await import("../commands/workflows/trigger.js");return t(e,o)}),a.command("logs [jobId]").description("Tail logs from a workflow execution (alias of `zibby logs`)").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (fetches the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --follow","Stream logs in real-time (like Heroku logs -t)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(e,o)=>{const{logsCommand:t}=await import("../commands/workflows/logs.js");return t(e,o)}),a.command("download <uuid>").description("Download a deployed workflow back to local (edit it, then re-deploy with `zibby workflow deploy`)").option("--dest <path>","Destination directory (default: ./workflows/<name> when run inside a .zibby project)").option("--force","Overwrite without prompting; bypass uuid-mismatch guard").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{downloadWorkflowCommand:t}=await import("../commands/workflows/download.js");return t(e,o)}),a.command("list").description("List all workflows (local + remote if credentials available)").option("--local-only","Show only local workflows").option("--remote-only","Show only remote workflows (requires --project)").option("--project <id>","Project ID (optional, uses ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async e=>{if(e.remoteOnly){const{workflowListCommand:t}=await import("../commands/workflow.js");return t(e)}if(e.localOnly){const{listLocalWorkflowsCommand:t}=await import("../commands/workflows/list.js");return t(e)}const{listAllWorkflowsCommand:o}=await import("../commands/workflows/list.js");return o(e)}),a.command("validate <name>").description("Static-check a local workflow (.zibby/workflows/<name>/). Catches schema/topology/skill errors in ~30ms before you run anything.").option("--verbose","Print stack traces on graph.mjs import errors").action(async(e,o)=>{const{validateCommand:t}=await import("../commands/workflows/validate.js");return t(e,o)}),a.command("schedule <uuid> [action] [cron]").description(`Manage a workflow's cron schedule. Actions: get (default) | set <cron> | clear. Cron is Unix 5-field, e.g. "0 9 * * 1-5".`).option("--tz <iana>","IANA timezone for the schedule (default: UTC)").option("-p, --param <key=value>","Fixed input param for every scheduled run (repeatable)",s,[]).option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o,t,r)=>{const{scheduleCommand:l}=await import("../commands/workflows/schedule.js");return l(e,o,t,r)}),a.command("delete <uuid>").description("Delete a deployed workflow by UUID").action(async e=>{const{deleteWorkflowCommand:o}=await import("../commands/workflows/delete.js");return o(e,{})});const d=a.command("env").description("Manage per-workflow encrypted env vars (set ANTHROPIC_API_KEY, DATABASE_URL, etc. per workflow)");d.command("list <uuid>").description("List env var key names for a workflow (values never returned)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{listEnvCommand:t}=await import("../commands/workflows/env.js");return t(e,o)}),d.command("set <uuid> <kv>").description("Set or update one env var: zibby workflow env set <uuid> KEY=value").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o,t)=>{const{setEnvCommand:r}=await import("../commands/workflows/env.js");return r(e,o,t)}),d.command("unset <uuid> <key>").description("Remove one env var from a workflow").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o,t)=>{const{unsetEnvCommand:r}=await import("../commands/workflows/env.js");return r(e,o,t)}),d.command("push <uuid>").description("Bulk-replace env from one or more .env files (later files override). Removes any keys not in the new map.").option("--file <path>","Path to a .env file (repeatable, e.g. --file .env --file .env.prod)",s,[]).option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{pushEnvCommand:t}=await import("../commands/workflows/env.js");return t(e,o)});const K=n.command("project").description("Manage Zibby projects");K.command("list").description("List all projects").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async e=>{const{projectListCommand:o}=await import("../commands/project.js");return o(e)});const N=n.command("run-queue").description("Parallel capacity \u2014 on-disk wait queue (see parallel.waitWhenAtCapacity in .zibby.config.mjs)");N.command("list").description("List CLI processes waiting for a run slot").option("--config <path>","Path to config file",".zibby.config.mjs").action(async e=>{const{runCapacityQueueListCommand:o}=await import("../commands/run-capacity-queue-cli.js");await o(e),process.exit(0)});const G=n.command("mcp").description("Manage the Zibby Remote MCP integration in your AI agent");G.command("install").description("Auto-configure Zibby MCP into your AI agent (Claude Code/Desktop, Cursor, Codex, Gemini)").option("--agent <name>","claude-code | claude-desktop | cursor | codex | gemini").option("--all","Install for every supported agent on this machine").option("--force","Overwrite the existing zibby block even if unchanged").action(async e=>{const{mcpInstallCommand:o}=await import("../commands/mcp.js");await o(e),process.exit(0)}),n.command("uninstall").description("Remove all Zibby data: global CLI, ~/.zibby, Cursor MCP config, Studio, and current project").option("--dry-run","Show what would be deleted without deleting").option("--deep","Also remove npx cache dirs containing zibby").action(async e=>{const{uninstallCommand:o}=await import("../commands/uninstall.js");await o(e),process.exit(0)}),n.parse();
|
package/dist/commands/chat.js
CHANGED
|
@@ -4,7 +4,7 @@ var Go=Object.defineProperty;var $e=(t,e)=>()=>(t&&(e=t(t=0)),e);var ve=(t,e)=>{
|
|
|
4
4
|
\u2713 Connected to cloud sandbox session ${e}
|
|
5
5
|
`)),process.stdout.write(ko.gray(` Press Ctrl+\\ to detach (session keeps running).
|
|
6
6
|
|
|
7
|
-
`)));let A=()=>{let R=process.stdout.columns||80,B=process.stdout.rows||24;try{a.send(JSON.stringify({type:"resize",cols:R,rows:B}))}catch{}};A(),Y=()=>A(),process.stdout.on("resize",Y),process.stdin.isTTY&&process.stdin.setRawMode&&($=!!process.stdin.isRaw,process.stdin.setRawMode(!0)),process.stdin.resume();try{process.stdin.setEncoding("utf8")}catch{}z=R=>{let B=R.toString("utf8");if(B.includes("")){W({reason:"detach"});return}try{a.send(B)}catch{}},process.stdin.on("data",z)}),a.on("message",A=>{let R=A.toString("utf8");if(R.startsWith("{")&&R.endsWith("}"))try{let B=JSON.parse(R);if(B&&B.type==="exit"){W({reason:"remote-exit",exitCode:B.exitCode,signal:B.signal});return}}catch{}try{process.stdout.write(R)}catch{}}),a.on("close",()=>{W({reason:"remote-close"})}),a.on("error",A=>{p||W({reason:"ws-error",message:A?.message||String(A)})}),setTimeout(()=>{if(a.readyState===Co.CONNECTING){try{a.terminate()}catch{}p||(p=!0,l(new Error("WS connect timed out after 30s")))}},3e4).unref()})}async function Zn({sandboxEndpoint:t,sessionToken:e,agentType:o,args:n,cwd:r,useTls:s}){let a=await Io({sandboxEndpoint:t,sessionToken:e,agentType:o,args:n,cwd:r,useTls:s});return{...await To({sandboxEndpoint:t,sessionId:a.session_id,sessionToken:e,useTls:s}),sessionId:a.session_id}}var wt=$e(()=>{});import{invokeAgent as Kn,getAgentStrategy as Wn}from"@zibby/core";import{getSkill as Re}from"@zibby/skills";import{existsSync as Ce,readFileSync as Ro,readdirSync as Jn}from"fs";import{resolve as me,join as St,dirname as Gn,basename as qn}from"path";import{createInterface as Vn,moveCursor as j,cursorTo as K,clearLine as Q,emitKeypressEvents as Xn}from"readline";import{fileURLToPath as Qn}from"url";import{homedir as es}from"os";import i from"chalk";import{highlight as Po}from"cli-highlight";import ts from"dotenv";import{existsSync as Lt,mkdirSync as qo,readFileSync as Vo,writeFileSync as Xo}from"fs";import{homedir as Rt}from"os";import{join as Fe}from"path";function Bt(){return process.env.ZIBBY_CONFIG_DIR||Fe(Rt(),".zibby")}function Dt(){return Fe(Bt(),"config.json")}var Qo=Fe(Rt(),".zibby"),Ms=Fe(Qo,"config.json");function en(){let t=Bt();Lt(t)||qo(t,{recursive:!0})}function se(){try{let t=Dt();if(Lt(t)){let e=Vo(t,"utf-8");return JSON.parse(e)}}catch{}return{}}function Pe(t){en(),Xo(Dt(),JSON.stringify(t,null,2))}function Ye(){return se().sessionToken||null}function Mt(t){let e=se();e.sessionToken=t,Pe(e)}function jt(){return se().user||null}function zt(t){let e=se();e.user=t,Pe(e)}function Ft(){let t=se();delete t.sessionToken,delete t.user,delete t.mem0ProxyUrl,Pe(t)}function Yt(){return se().proxyUrl||null}function Ht(t){let e=se();e.proxyUrl=t,Pe(e)}function Zt(){return se().mem0ProxyUrl||null}function Kt(t){let e=se();e.mem0ProxyUrl=t,Pe(e)}function Wt(){return se().projects||[]}var Ee={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://
|
|
7
|
+
`)));let A=()=>{let R=process.stdout.columns||80,B=process.stdout.rows||24;try{a.send(JSON.stringify({type:"resize",cols:R,rows:B}))}catch{}};A(),Y=()=>A(),process.stdout.on("resize",Y),process.stdin.isTTY&&process.stdin.setRawMode&&($=!!process.stdin.isRaw,process.stdin.setRawMode(!0)),process.stdin.resume();try{process.stdin.setEncoding("utf8")}catch{}z=R=>{let B=R.toString("utf8");if(B.includes("")){W({reason:"detach"});return}try{a.send(B)}catch{}},process.stdin.on("data",z)}),a.on("message",A=>{let R=A.toString("utf8");if(R.startsWith("{")&&R.endsWith("}"))try{let B=JSON.parse(R);if(B&&B.type==="exit"){W({reason:"remote-exit",exitCode:B.exitCode,signal:B.signal});return}}catch{}try{process.stdout.write(R)}catch{}}),a.on("close",()=>{W({reason:"remote-close"})}),a.on("error",A=>{p||W({reason:"ws-error",message:A?.message||String(A)})}),setTimeout(()=>{if(a.readyState===Co.CONNECTING){try{a.terminate()}catch{}p||(p=!0,l(new Error("WS connect timed out after 30s")))}},3e4).unref()})}async function Zn({sandboxEndpoint:t,sessionToken:e,agentType:o,args:n,cwd:r,useTls:s}){let a=await Io({sandboxEndpoint:t,sessionToken:e,agentType:o,args:n,cwd:r,useTls:s});return{...await To({sandboxEndpoint:t,sessionId:a.session_id,sessionToken:e,useTls:s}),sessionId:a.session_id}}var wt=$e(()=>{});import{invokeAgent as Kn,getAgentStrategy as Wn}from"@zibby/core";import{getSkill as Re}from"@zibby/skills";import{existsSync as Ce,readFileSync as Ro,readdirSync as Jn}from"fs";import{resolve as me,join as St,dirname as Gn,basename as qn}from"path";import{createInterface as Vn,moveCursor as j,cursorTo as K,clearLine as Q,emitKeypressEvents as Xn}from"readline";import{fileURLToPath as Qn}from"url";import{homedir as es}from"os";import i from"chalk";import{highlight as Po}from"cli-highlight";import ts from"dotenv";import{existsSync as Lt,mkdirSync as qo,readFileSync as Vo,writeFileSync as Xo}from"fs";import{homedir as Rt}from"os";import{join as Fe}from"path";function Bt(){return process.env.ZIBBY_CONFIG_DIR||Fe(Rt(),".zibby")}function Dt(){return Fe(Bt(),"config.json")}var Qo=Fe(Rt(),".zibby"),Ms=Fe(Qo,"config.json");function en(){let t=Bt();Lt(t)||qo(t,{recursive:!0})}function se(){try{let t=Dt();if(Lt(t)){let e=Vo(t,"utf-8");return JSON.parse(e)}}catch{}return{}}function Pe(t){en(),Xo(Dt(),JSON.stringify(t,null,2))}function Ye(){return se().sessionToken||null}function Mt(t){let e=se();e.sessionToken=t,Pe(e)}function jt(){return se().user||null}function zt(t){let e=se();e.user=t,Pe(e)}function Ft(){let t=se();delete t.sessionToken,delete t.user,delete t.mem0ProxyUrl,Pe(t)}function Yt(){return se().proxyUrl||null}function Ht(t){let e=se();e.proxyUrl=t,Pe(e)}function Zt(){return se().mem0ProxyUrl||null}function Kt(t){let e=se();e.mem0ProxyUrl=t,Pe(e)}function Wt(){return se().projects||[]}var Ee={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function le(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";Ee[e]?t=Ee[e].apiUrl:t=Ee.prod.apiUrl}try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),Ee.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),Ee.prod.apiUrl}}import{existsSync as at,mkdirSync as tn,readFileSync as Jt,writeFileSync as Gt,unlinkSync as Ys}from"fs";import{resolve as Oe}from"path";import{homedir as Ks}from"os";var on=30;function qt(t){let e=Oe(t,".zibby","output");return at(e)||tn(e,{recursive:!0}),e}function Vt(t){let e=Oe(t,".zibby","output","chat-history.json");if(!at(e))return[];try{let o=JSON.parse(Jt(e,"utf-8"));return Array.isArray(o)?o:[]}catch{return[]}}function Ne(t,e){let o=qt(t),n=Oe(o,"chat-history.json");try{Gt(n,JSON.stringify((e||[]).slice(-on*2),null,2),"utf-8")}catch{}}function Xt(t){let e=Oe(t,".zibby","output","active-skills.json");if(!at(e))return null;try{let o=JSON.parse(Jt(e,"utf-8"));return Array.isArray(o)?o:null}catch{return null}}function Ue(t,e){let o=qt(t),n=Oe(o,"active-skills.json");try{Gt(n,JSON.stringify(Array.isArray(e)?e:[]),"utf-8")}catch{}}var ct={cli_reliable_v1:{title:"General intelligence reliability contract",operatingRules:["Evidence-first reasoning: ground conclusions in observed outputs or tool evidence, not guesses.","No false completion: never claim success for a state-changing action until verification confirms it.","Execution integrity: do not claim any external action unless the matching tool call actually happened.","Bounded recovery: for transient failures, retry with adjusted parameters up to 2 times, then escalate with blocker + next step.",'Binary-answer discipline: for yes/no questions, verify the exact asked condition before answering; do not answer "yes" from a broader or approximate match.'],executionSafety:["Prefer low-blast-radius, reversible actions first.","Before irreversible or high-impact actions, confirm explicit user intent unless already authorized.","If verification cannot be run, state that limitation explicitly."],investigationLoop:["For unclear failures, follow this loop: detect -> gather evidence -> form hypothesis -> test hypothesis -> conclude.","If evidence is insufficient, explicitly collect more before proposing a root cause.","Prefer smallest validating action first before broad or costly retries."],responseQuality:["State assumptions explicitly when certainty is low.","Differentiate facts, hypotheses, and next actions.","Keep reports concise but decision-useful.","If related-but-not-identical matches exist, report them separately as context, not as the direct yes/no answer."],incidentTemplate:["ONLY when diagnosing failures or errors (never for successful actions), structure your response as: Root cause, Evidence, Attempted fixes, Current status, Next action."],skillRunbooks:{}}},eo=2e3,Qt=12e3;function He(t=[]){if(!Array.isArray(t))return[];let e=new Set,o=[];for(let n of t){let r=String(n||"").replace(/\s+/g," ").trim();r&&(e.has(r)||(e.add(r),o.push(r)))}return o}function nn(t,e=eo){let o=String(t||"");return o.length<=e?o:`${o.slice(0,Math.max(0,e-14)).trimEnd()}
|
|
8
8
|
|
|
9
9
|
[truncated]`}function ge(t,e=[],o=eo){let n=He(e);if(n.length===0)return"";let r=[`## ${t}`,...n.map(s=>`- ${s}`)].join(`
|
|
10
10
|
`);return nn(r,o)}function sn(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function rn(t,e){let o={...t,...e},n=["operatingRules","rules","executionSafety","investigationLoop","responseQuality","incidentTemplate"];for(let r of n)Array.isArray(e?.[r])?o[r]=[...He(t?.[r]||[]),...He(e[r])]:Array.isArray(t?.[r])&&(o[r]=[...He(t[r])]);return o.skillRunbooks={...t?.skillRunbooks||{},...e?.skillRunbooks||{}},o}function an(t={},e={}){let o=Array.isArray(t?.reliabilityAppendSections)?t.reliabilityAppendSections:[],n=Array.isArray(e?.reliabilityAppendSections)?e.reliabilityAppendSections:[];return[...o,...n].map(r=>{if(typeof r=="string")return{title:"Additional reliability guidance",lines:[r]};if(!r||typeof r!="object")return null;let s=String(r.title||"Additional reliability guidance").trim(),a=Array.isArray(r.lines)?r.lines:[];return{title:s,lines:a}}).filter(Boolean)}function cn(t={},e={}){let o=String(e.reliabilityProfile||process.env.ZIBBY_RELIABILITY_PROFILE||t.reliabilityProfile||"cli_reliable_v1").trim(),n=t?.reliabilityProfiles?.[o];if(typeof n=="string"&&n.trim())return{name:o,text:n.trim()};if(n&&typeof n.instruction=="string"&&n.instruction.trim())return{name:o,text:n.instruction.trim()};let r=ct[o]||ct.cli_reliable_v1,s=sn(n),a=s?rn(r,s):r;return{name:o,defaults:a}}function to({activeSkills:t=[],chatConfig:e={},options:o={}}={}){let n=cn(e,o);if(n.text)return n.text;let r=n.defaults||ct.cli_reliable_v1,s=[ge(r.title||"Reliability contract",r.operatingRules||r.rules||[]),ge("Execution safety",r.executionSafety||[]),ge("Investigation loop",r.investigationLoop||[]),ge("Response quality",r.responseQuality||[]),ge("Failure reporting format",r.incidentTemplate||[])],a=r.skillRunbooks||{};for(let p of t)a[p]&&s.push(ge(`Runbook: ${p}`,a[p]));let c=an(e,o);for(let p of c)s.push(ge(p.title,p.lines));let l=s.filter(Boolean).join(`
|
package/dist/commands/creds.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"chalk";function y(o,e=""){return`${String(o).replace(/\/+$/,"")}/agents/credentials${e}`}function h(){let o=new Error("Session expired \u2014 run zibby login");return o.code="AUTH_EXPIRED",o}async function m({apiUrl:o,sessionToken:e}){if(!e)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let r=await fetch(y(o),{headers:{Authorization:`Bearer ${e}`}});if(r.status===401)throw h();if(r.status===404)return{credentials:[],by_type:{oauth:[],api:[]},total:0};if(!r.ok){let c=new Error(`List credentials failed (${r.status})`);throw c.status=r.status,c}return r.json()}async function $({apiUrl:o,sessionToken:e,type:r,token:c,source:s="~/.zibby/config.json"}){if(!e)throw new Error("No session token \u2014 run zibby login first");let n=await fetch(y(o),{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({type:r,token:c,source:s})});if(n.status===401)throw h();if(!n.ok){let i=`Add credential failed (${n.status})`;try{let d=await n.json();d?.error&&(i=`${i}: ${d.error}`)}catch{}let l=new Error(i);throw l.status=n.status,l}return n.json()}async function _({apiUrl:o,sessionToken:e,type:r,index:c}){if(!e)throw new Error("No session token \u2014 run zibby login first");let s=await fetch(y(o,`/${encodeURIComponent(r)}/${encodeURIComponent(c)}`),{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(s.status===401)throw h();if(!s.ok){let n=new Error(`Delete credential failed (${s.status})`);throw n.status=s.status,n}return s.json()}async function U({apiUrl:o,sessionToken:e,credentials:r}){let c=0,s=0,n=[];for(let i of r)try{let l=await $({apiUrl:o,sessionToken:e,type:i.type,token:i.token,source:i.source_var||i.source||"local"});l.deduped?s+=1:l.added&&(c+=1)}catch(l){n.push({masked:i.token?`***${i.token.slice(-4)}`:"***",error:l.message})}return{added:c,deduped:s,errors:n}}import O from"node:fs/promises";import C from"node:path";import A from"node:os";var p=C.join(A.homedir(),".zibby","config.json"),v={CLAUDE_CODE_OAUTH_TOKEN:"oauth",CLAUDE_CODE_OAUTH_TOKEN_POOL:"oauth",ANTHROPIC_AUTH_TOKEN:"oauth",ANTHROPIC_API_KEY:"api",ANTHROPIC_API_KEY_POOL:"api"};function k(o){if(!o)return[];let e;try{e=JSON.parse(o)}catch{return[]}let r=e?.agentKeys;if(!r||typeof r!="object")return[];let c=[],s=new Set;for(let[n,i]of Object.entries(v)){let l=r[n];if(!l||typeof l!="string")continue;let d=n.endsWith("_POOL")?l.split(",").map(a=>a.trim()).filter(Boolean):[l.trim()];for(let a of d)a.length<8||s.has(a)||(s.add(a),c.push({type:i,token:a,source_var:n}))}return c}async function N(o=p){let e;try{e=await O.readFile(o,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}return k(e)}async function w({filepath:o,env:e=process.env}={}){let r=await N(o),c=new Set(r.map(n=>n.token)),s=[];for(let[n,i]of Object.entries(v)){let l=e[n];if(!l)continue;let d=n.endsWith("_POOL")?l.split(",").map(a=>a.trim()).filter(Boolean):[l];for(let a of d)a.length<8||c.has(a)||(c.add(a),s.push({type:i,token:a,source_var:n,source:"process.env"}))}return{config:r.map(n=>({...n,source:"config.json"})),env:s,all:[...r.map(n=>({...n,source:"config.json"})),...s]}}var u={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://
|
|
1
|
+
import t from"chalk";function y(o,e=""){return`${String(o).replace(/\/+$/,"")}/agents/credentials${e}`}function h(){let o=new Error("Session expired \u2014 run zibby login");return o.code="AUTH_EXPIRED",o}async function m({apiUrl:o,sessionToken:e}){if(!e)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let r=await fetch(y(o),{headers:{Authorization:`Bearer ${e}`}});if(r.status===401)throw h();if(r.status===404)return{credentials:[],by_type:{oauth:[],api:[]},total:0};if(!r.ok){let c=new Error(`List credentials failed (${r.status})`);throw c.status=r.status,c}return r.json()}async function $({apiUrl:o,sessionToken:e,type:r,token:c,source:s="~/.zibby/config.json"}){if(!e)throw new Error("No session token \u2014 run zibby login first");let n=await fetch(y(o),{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({type:r,token:c,source:s})});if(n.status===401)throw h();if(!n.ok){let i=`Add credential failed (${n.status})`;try{let d=await n.json();d?.error&&(i=`${i}: ${d.error}`)}catch{}let l=new Error(i);throw l.status=n.status,l}return n.json()}async function _({apiUrl:o,sessionToken:e,type:r,index:c}){if(!e)throw new Error("No session token \u2014 run zibby login first");let s=await fetch(y(o,`/${encodeURIComponent(r)}/${encodeURIComponent(c)}`),{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(s.status===401)throw h();if(!s.ok){let n=new Error(`Delete credential failed (${s.status})`);throw n.status=s.status,n}return s.json()}async function U({apiUrl:o,sessionToken:e,credentials:r}){let c=0,s=0,n=[];for(let i of r)try{let l=await $({apiUrl:o,sessionToken:e,type:i.type,token:i.token,source:i.source_var||i.source||"local"});l.deduped?s+=1:l.added&&(c+=1)}catch(l){n.push({masked:i.token?`***${i.token.slice(-4)}`:"***",error:l.message})}return{added:c,deduped:s,errors:n}}import O from"node:fs/promises";import C from"node:path";import A from"node:os";var p=C.join(A.homedir(),".zibby","config.json"),v={CLAUDE_CODE_OAUTH_TOKEN:"oauth",CLAUDE_CODE_OAUTH_TOKEN_POOL:"oauth",ANTHROPIC_AUTH_TOKEN:"oauth",ANTHROPIC_API_KEY:"api",ANTHROPIC_API_KEY_POOL:"api"};function k(o){if(!o)return[];let e;try{e=JSON.parse(o)}catch{return[]}let r=e?.agentKeys;if(!r||typeof r!="object")return[];let c=[],s=new Set;for(let[n,i]of Object.entries(v)){let l=r[n];if(!l||typeof l!="string")continue;let d=n.endsWith("_POOL")?l.split(",").map(a=>a.trim()).filter(Boolean):[l.trim()];for(let a of d)a.length<8||s.has(a)||(s.add(a),c.push({type:i,token:a,source_var:n}))}return c}async function N(o=p){let e;try{e=await O.readFile(o,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}return k(e)}async function w({filepath:o,env:e=process.env}={}){let r=await N(o),c=new Set(r.map(n=>n.token)),s=[];for(let[n,i]of Object.entries(v)){let l=e[n];if(!l)continue;let d=n.endsWith("_POOL")?l.split(",").map(a=>a.trim()).filter(Boolean):[l];for(let a of d)a.length<8||c.has(a)||(c.add(a),s.push({type:i,token:a,source_var:n,source:"process.env"}))}return{config:r.map(n=>({...n,source:"config.json"})),env:s,all:[...r.map(n=>({...n,source:"config.json"})),...s]}}var u={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function f(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";u[e]?o=u[e].apiUrl:o=u.prod.apiUrl}try{let e=new URL(o);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),u.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),u.prod.apiUrl}}import{existsSync as E,mkdirSync as G,readFileSync as P,writeFileSync as J}from"fs";import{homedir as x}from"os";import{join as g}from"path";function R(){return process.env.ZIBBY_CONFIG_DIR||g(x(),".zibby")}function T(){return g(R(),"config.json")}var B=g(x(),".zibby"),X=g(B,"config.json");function z(){try{let o=T();if(E(o)){let e=P(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function I(){return z().sessionToken||null}function b(){let o=I();return o||(console.log(t.red("Not logged in. Run `zibby login` first.")),process.exit(1)),o}async function L(){let o=b(),e=f();console.log(""),console.log(t.cyan(" Stored credentials in your Zibby workspace")),console.log(t.gray(` Source file: ${p}`)),console.log("");let r;try{r=await m({apiUrl:e,sessionToken:o})}catch(s){console.log(t.red(` Failed: ${s.message}`)),process.exit(1)}let{by_type:c}=r;for(let s of["oauth","api"]){let n=c[s]||[];if(console.log(t.bold(` ${s} pool (${n.length} ${n.length===1?"token":"tokens"}):`)),n.length===0)console.log(t.gray(" (none)"));else for(let i of n){let l=i.uploaded_at?new Date(i.uploaded_at).toISOString().slice(0,10):"?",d=i.uploaded_by||"?";console.log(` [${i.index}] ${t.cyan(i.masked)} ${t.gray(`uploaded ${l} by ${d} source: ${i.source||"unknown"}`)}`)}console.log("")}r.total===0&&(console.log(t.gray(" No credentials yet. Run `zibby init` to set them up \u2014 Claude has")),console.log(t.gray(" both OAuth subscription and API key options. Then re-run sync.")),console.log("")),console.log(t.gray(" Same file, same credentials, used by every zibby command:")),console.log(t.gray(" zibby test (test automation)")),console.log(t.gray(" zibby chat (interactive chat + cloud Claude Code sandbox)")),console.log(t.gray(" zibby workflow run (local execution)")),console.log(t.gray(" zibby workflow start (local dev server)")),console.log("")}async function S(){let o=b(),e=f();console.log(""),console.log(t.cyan(" Scanning your local credentials...")),console.log(t.gray(` ${p}`));let r=await w(),c=r.all.length;if(c===0){console.log(""),console.log(t.yellow(" No credentials found in ~/.zibby/config.json.")),console.log(""),console.log(t.white(" Run `zibby init` first to choose API key or OAuth subscription.")),console.log(t.gray(" Or export tokens in your shell \u2014 Zibby reads process.env too.")),console.log("");return}console.log(t.green(` \u2713 Found ${c} ${c===1?"credential":"credentials"}:`));for(let n of r.all)console.log(t.gray(` ${n.type} ***${n.token.slice(-4)} source: ${n.source_var} (${n.source})`));console.log(""),console.log(t.cyan(" Uploading to Zibby (KMS-encrypted)..."));let s=await U({apiUrl:e,sessionToken:o,credentials:r.all});if(console.log(""),console.log(t.green(` \u2713 ${s.added} new, ${s.deduped} already present`)),s.errors.length>0){console.log(t.red(` \u2717 ${s.errors.length} failed:`));for(let n of s.errors)console.log(t.red(` ${n.masked}: ${n.error}`))}console.log("")}async function D(o,e){let r=b(),c=f();(!o||!e)&&(console.log(t.red("Usage: zibby creds remove <type> <index>")),console.log(t.gray(" e.g. zibby creds remove oauth 0")),process.exit(1)),console.log(""),console.log(t.cyan(` Removing ${o} credential at index ${e}...`));try{await _({apiUrl:c,sessionToken:r,type:o,index:e})}catch(s){console.log(t.red(` Failed: ${s.message}`)),process.exit(1)}console.log(t.green(" \u2713 Removed.")),console.log(""),console.log(t.gray(" Note: this only deletes Zibby's encrypted copy. To revoke")),console.log(t.gray(" the actual token, do that on the upstream provider where")),console.log(t.gray(" it was issued.")),console.log("")}async function ro(o,...e){switch(o){case"list":return L();case"sync":return S();case"remove":return D(e[0],e[1]);default:console.log(t.red(`Unknown subcommand: ${o}`)),console.log(t.gray(" zibby creds list")),console.log(t.gray(" zibby creds sync")),console.log(t.gray(" zibby creds remove <type> <index>")),process.exit(1)}}export{ro as credsCmd,L as listCmd,D as removeCmd,S as syncCmd};
|
package/dist/commands/init.js
CHANGED
|
@@ -6,7 +6,7 @@ var ko=Object.defineProperty;var j=(e,o)=>()=>(e&&(o=e(e=0)),o);var L=(e,o)=>{fo
|
|
|
6
6
|
`)),console.log(x.gray(" Run `zibby init` first to bootstrap the project.\n")),process.exit(1));let s;try{s=await Pe(t,e,{enableMemory:o.enableMemory!==!1})}catch(n){console.log(x.red(`
|
|
7
7
|
${n.message}
|
|
8
8
|
`)),console.log(x.gray(` See available templates: zibby template list
|
|
9
|
-
`)),process.exit(1)}console.log(""),console.log(x.green(` \u2713 Added template ${x.bold(s.template.name)}`)),console.log(x.gray(` ${s.copied.length} files written to ${i}/`));for(let n of s.copied)console.log(x.gray(` \u2022 ${n}`));if(!o.skipInstall&&Q(D(t,"package.json"))){let n=!1;try{Oo(D(t,"package.json")).resolve("@zibby/core/package.json"),n=!0}catch{}if(!n){let d=`@zibby/core@${JSON.parse(Eo(D(Bo,"../../package.json"),"utf-8")).dependencies?.["@zibby/core"]||"latest"}`,l=Ko(` Installing ${d} (needed by .zibby/graph.mjs)...`).start();await new Promise(w=>{To("npm",["install","--save-dev",d],{cwd:t,stdio:"pipe"}).on("close",h=>w(h??1))})===0?l.succeed(` Installed ${d}`):(l.warn(` Could not auto-install ${d}`),console.log(x.gray(` Run manually: npm install --save-dev ${d}`)))}}console.log(""),console.log(x.gray(" Re-running `zibby template add <name>` overwrites existing files \u2014")),console.log(x.gray(" use this to refresh after `npm update @zibby/core`.")),console.log("")}var Mo,Bo,No,Se=j(()=>{Mo=zo(import.meta.url),Bo=Ro(Mo),No=[/^__tests__$/,/^__mocks__$/,/^node_modules$/,/\.test\.[mc]?js$/,/\.spec\.[mc]?js$/,/^\.DS_Store$/,/^chat\.mjs$/]});var ze={};L(ze,{applyMemorySyncConfig:()=>Fo,validateMemorySyncConfig:()=>Re});function Re(e){if(!e||typeof e!="object")return{ok:!0,kind:"noop"};let o=e.remote;return Uo.includes(o)?{ok:!0,kind:"noop"}:typeof o!="string"?{ok:!1,error:`memorySync.remote must be null or a string, got ${typeof o}`}:o===Yo?{ok:!0,kind:"hosted"}:Ee.some(t=>o.startsWith(t))?{ok:!0,kind:"byo",remote:o}:{ok:!1,error:`memorySync.remote = ${JSON.stringify(o)} is not recognized. Use null, 'hosted', or a URL beginning with one of: ${Ee.join(" / ")}.`}}async function Fo({cwd:e,projectId:o,block:t,memoryApi:i,hostedSetup:s,getSessionToken:n,logger:p=console}){let d=Re(t);if(!d.ok)return p.warn?.(`[memory-sync] config invalid: ${d.error}`),{action:"error",reason:d.error};if(d.kind==="noop")return{action:"skipped",reason:"memorySync.remote not set"};if(d.kind==="byo")return i?.memoryRemoteAdd?i.memoryRemoteAdd(e,d.remote)?{action:"byo",remote:d.remote}:{action:"error",reason:"memoryRemoteAdd returned false (memory DB not initialized?)"}:{action:"error",reason:"@zibby/ui-memory not loaded"};if(d.kind==="hosted"){if(typeof n=="function"&&!n())return{action:"pending-login",reason:'memorySync.remote = "hosted" but the user is not logged in. Run `zibby login` then `zibby memory remote use --hosted`.'};if(typeof s!="function")return{action:"error",reason:"hostedSetup function not provided"};try{return await s({cwd:e,projectId:o}),{action:"hosted"}}catch(l){return{action:"error",reason:`hosted setup failed: ${l.message}`}}}return{action:"error",reason:`unhandled kind: ${d.kind}`}}var Uo,Yo,Ee,Te=j(()=>{Uo=[null,void 0,"","none","off",!1],Yo="hosted",Ee=["aws://","gs://","https://","http://","file://"]});var re={};L(re,{clearSession:()=>Ye,default:()=>qo,getMem0ProxyUrl:()=>He,getProjects:()=>Ve,getProxyUrl:()=>Fe,getSessionToken:()=>ne,getUserInfo:()=>Le,isLoggedIn:()=>Ue,loadConfig:()=>S,saveConfig:()=>O,saveMem0ProxyUrl:()=>Ge,saveProjects:()=>We,saveProxyUrl:()=>Ze,saveSessionToken:()=>je,saveUserInfo:()=>De});import{existsSync as Oe,mkdirSync as Zo,readFileSync as Ho,writeFileSync as Go}from"fs";import{homedir as Ke}from"os";import{join as ee}from"path";function Me(){return process.env.ZIBBY_CONFIG_DIR||ee(Ke(),".zibby")}function Be(){return ee(Me(),"config.json")}function Wo(){let e=Me();Oe(e)||Zo(e,{recursive:!0})}function S(){try{let e=Be();if(Oe(e)){let o=Ho(e,"utf-8");return JSON.parse(o)}}catch{}return{}}function O(e){Wo(),Go(Be(),JSON.stringify(e,null,2))}function ne(){return S().sessionToken||null}function je(e){let o=S();o.sessionToken=e,O(o)}function Le(){return S().user||null}function De(e){let o=S();o.user=e,O(o)}function Ue(){return ne()!==null}function Ye(){let e=S();delete e.sessionToken,delete e.user,delete e.mem0ProxyUrl,O(e)}function Fe(){return S().proxyUrl||null}function Ze(e){let o=S();o.proxyUrl=e,O(o)}function He(){return S().mem0ProxyUrl||null}function Ge(e){let o=S();o.mem0ProxyUrl=e,O(o)}function Ve(){return S().projects||[]}function We(e){let o=S();o.projects=e,O(o)}var Ne,Vo,qo,se=j(()=>{Ne=ee(Ke(),".zibby"),Vo=ee(Ne,"config.json");qo={loadConfig:S,saveConfig:O,getSessionToken:ne,saveSessionToken:je,getUserInfo:Le,saveUserInfo:De,isLoggedIn:Ue,clearSession:Ye,getProxyUrl:Fe,saveProxyUrl:Ze,getMem0ProxyUrl:He,saveMem0ProxyUrl:Ge,getProjects:Ve,saveProjects:We,CONFIG_DIR:Ne,CONFIG_FILE:Vo}});var qe={};L(qe,{ENVIRONMENTS:()=>C,getAccountApiUrl:()=>Xo,getApiUrl:()=>Jo,getCurrentEnvironment:()=>Qo,getFrontendUrl:()=>et});function Jo(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";C[o]?e=C[o].apiUrl:e=C.prod.apiUrl}try{let o=new URL(e);return o.protocol!=="http:"&&o.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${o.protocol} (only http/https allowed)`),C.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),C.prod.apiUrl}}function Xo(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let e=process.env.ZIBBY_ENV||"prod";return(C[e]||C.prod).accountApiUrl}function Qo(){let e=process.env.ZIBBY_ENV||"prod";return C[e]||C.prod}function et(){let e;if(process.env.ZIBBY_FRONTEND_URL)e=process.env.ZIBBY_FRONTEND_URL;else{let o=process.env.ZIBBY_ENV||"prod";C[o]?e=C[o].frontendUrl:e=C.prod.frontendUrl}try{let o=new URL(e);if(o.protocol!=="http:"&&o.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${o.protocol} (only http/https allowed)`),C.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let i=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],s=o.hostname;if(!i.some(p=>s===p||s.endsWith(`.${p}`))&&!s.includes("localhost")&&s!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${s}`),"https://studio.zibby.dev"}return e}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${e}`),C.local.frontendUrl}}var C,Je=j(()=>{C={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"}}});var ue={};L(ue,{__testing:()=>lt,buildDoltEnv:()=>at,clearConfig:()=>it,getActiveCredentials:()=>ro,isHosted:()=>rt,readConfig:()=>ce,refreshCredentials:()=>no,writeConfig:()=>st});import{readFileSync as Xe,writeFileSync as ae,existsSync as le,mkdirSync as Qe,chmodSync as ot}from"fs";import{join as ie}from"path";function H(e){let o=ie(e,".zibby");return{dir:o,config:ie(o,tt),creds:ie(o,nt)}}function ce(e){let{config:o}=H(e);if(!le(o))return null;try{let t=JSON.parse(Xe(o,"utf-8"));return t.mode!=="hosted"?null:t}catch{return null}}function rt(e){return!!ce(e)}function st(e,o){let{dir:t,config:i}=H(e);Qe(t,{recursive:!0}),ae(i,JSON.stringify({mode:"hosted",projectId:o.projectId,bucket:o.bucket,prefix:o.prefix,doltUrl:o.doltUrl,configuredAt:new Date().toISOString()},null,2),"utf-8")}function it(e){let{config:o,creds:t}=H(e);for(let i of[o,t])if(le(i))try{ae(i,"")}catch{}}function de(e){let{creds:o}=H(e);if(!le(o))return null;try{let t=JSON.parse(Xe(o,"utf-8"));return!t?.accessKeyId||!t?.secretAccessKey||!t?.sessionToken?null:t}catch{return null}}function oo(e,o){let{dir:t,creds:i}=H(e);Qe(t,{recursive:!0}),ae(i,JSON.stringify(o,null,2),"utf-8");try{ot(i,384)}catch{}}function to(e){return e?.expiration?new Date(e.expiration).getTime()-Date.now()<eo:!0}async function no({cwd:e,projectId:o,apiUrl:t,sessionToken:i,fetch:s=globalThis.fetch}){if(!o)throw new Error("refreshCredentials: projectId required");if(!t)throw new Error("refreshCredentials: apiUrl required");if(!i)throw new Error("refreshCredentials: sessionToken required (run `zibby login`)");let n=`${String(t).replace(/\/+$/,"")}/memory/sync-credentials`,p=await s(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({projectId:o})});if(!p.ok){let l=await p.text().catch(()=>"");throw new Error(`memory-sync credentials request failed (${p.status}): ${l||"no body"}`)}let d=await p.json();if(!d?.accessKeyId||!d?.secretAccessKey||!d?.sessionToken)throw new Error("memory-sync credentials response missing required fields");return oo(e,{accessKeyId:d.accessKeyId,secretAccessKey:d.secretAccessKey,sessionToken:d.sessionToken,expiration:d.expiration||null,refreshedAt:new Date().toISOString()}),de(e)}async function ro({cwd:e,apiUrl:o,sessionToken:t,fetch:i}){let s=ce(e);if(!s)return null;let n=de(e);return(!n||to(n))&&(n=await no({cwd:e,projectId:s.projectId,apiUrl:o,sessionToken:t,fetch:i})),n}async function at({cwd:e,apiUrl:o,sessionToken:t,fetch:i}){let s=await ro({cwd:e,apiUrl:o,sessionToken:t,fetch:i});return s?{AWS_ACCESS_KEY_ID:s.accessKeyId,AWS_SECRET_ACCESS_KEY:s.secretAccessKey,AWS_SESSION_TOKEN:s.sessionToken,AWS_REGION:process.env.AWS_REGION||"ap-southeast-2"}:null}var tt,nt,eo,lt,pe=j(()=>{tt="memory-sync.json",nt="memory-sync-creds.json",eo=120*1e3;lt={paths:H,readCreds:de,writeCreds:oo,isExpiringSoon:to,REFRESH_HEADROOM_MS:eo}});var so={};L(so,{memoryCompactCommand:()=>pt,memoryCostCommand:()=>mt,memoryInitCommand:()=>vt,memoryPullCommand:()=>ht,memoryPushCommand:()=>wt,memoryRemoteAddCommand:()=>gt,memoryRemoteInfoCommand:()=>yt,memoryRemoteRemoveCommand:()=>ft,memoryRemoteUseHostedCommand:()=>bt,memoryResetCommand:()=>ut,memoryStatsCommand:()=>dt});import r from"chalk";async function R(){try{return await import("@zibby/ui-memory")}catch{return console.log(r.yellow(`
|
|
9
|
+
`)),process.exit(1)}console.log(""),console.log(x.green(` \u2713 Added template ${x.bold(s.template.name)}`)),console.log(x.gray(` ${s.copied.length} files written to ${i}/`));for(let n of s.copied)console.log(x.gray(` \u2022 ${n}`));if(!o.skipInstall&&Q(D(t,"package.json"))){let n=!1;try{Oo(D(t,"package.json")).resolve("@zibby/core/package.json"),n=!0}catch{}if(!n){let d=`@zibby/core@${JSON.parse(Eo(D(Bo,"../../package.json"),"utf-8")).dependencies?.["@zibby/core"]||"latest"}`,l=Ko(` Installing ${d} (needed by .zibby/graph.mjs)...`).start();await new Promise(w=>{To("npm",["install","--save-dev",d],{cwd:t,stdio:"pipe"}).on("close",h=>w(h??1))})===0?l.succeed(` Installed ${d}`):(l.warn(` Could not auto-install ${d}`),console.log(x.gray(` Run manually: npm install --save-dev ${d}`)))}}console.log(""),console.log(x.gray(" Re-running `zibby template add <name>` overwrites existing files \u2014")),console.log(x.gray(" use this to refresh after `npm update @zibby/core`.")),console.log("")}var Mo,Bo,No,Se=j(()=>{Mo=zo(import.meta.url),Bo=Ro(Mo),No=[/^__tests__$/,/^__mocks__$/,/^node_modules$/,/\.test\.[mc]?js$/,/\.spec\.[mc]?js$/,/^\.DS_Store$/,/^chat\.mjs$/]});var ze={};L(ze,{applyMemorySyncConfig:()=>Fo,validateMemorySyncConfig:()=>Re});function Re(e){if(!e||typeof e!="object")return{ok:!0,kind:"noop"};let o=e.remote;return Uo.includes(o)?{ok:!0,kind:"noop"}:typeof o!="string"?{ok:!1,error:`memorySync.remote must be null or a string, got ${typeof o}`}:o===Yo?{ok:!0,kind:"hosted"}:Ee.some(t=>o.startsWith(t))?{ok:!0,kind:"byo",remote:o}:{ok:!1,error:`memorySync.remote = ${JSON.stringify(o)} is not recognized. Use null, 'hosted', or a URL beginning with one of: ${Ee.join(" / ")}.`}}async function Fo({cwd:e,projectId:o,block:t,memoryApi:i,hostedSetup:s,getSessionToken:n,logger:p=console}){let d=Re(t);if(!d.ok)return p.warn?.(`[memory-sync] config invalid: ${d.error}`),{action:"error",reason:d.error};if(d.kind==="noop")return{action:"skipped",reason:"memorySync.remote not set"};if(d.kind==="byo")return i?.memoryRemoteAdd?i.memoryRemoteAdd(e,d.remote)?{action:"byo",remote:d.remote}:{action:"error",reason:"memoryRemoteAdd returned false (memory DB not initialized?)"}:{action:"error",reason:"@zibby/ui-memory not loaded"};if(d.kind==="hosted"){if(typeof n=="function"&&!n())return{action:"pending-login",reason:'memorySync.remote = "hosted" but the user is not logged in. Run `zibby login` then `zibby memory remote use --hosted`.'};if(typeof s!="function")return{action:"error",reason:"hostedSetup function not provided"};try{return await s({cwd:e,projectId:o}),{action:"hosted"}}catch(l){return{action:"error",reason:`hosted setup failed: ${l.message}`}}}return{action:"error",reason:`unhandled kind: ${d.kind}`}}var Uo,Yo,Ee,Te=j(()=>{Uo=[null,void 0,"","none","off",!1],Yo="hosted",Ee=["aws://","gs://","https://","http://","file://"]});var re={};L(re,{clearSession:()=>Ye,default:()=>qo,getMem0ProxyUrl:()=>He,getProjects:()=>Ve,getProxyUrl:()=>Fe,getSessionToken:()=>ne,getUserInfo:()=>Le,isLoggedIn:()=>Ue,loadConfig:()=>S,saveConfig:()=>O,saveMem0ProxyUrl:()=>Ge,saveProjects:()=>We,saveProxyUrl:()=>Ze,saveSessionToken:()=>je,saveUserInfo:()=>De});import{existsSync as Oe,mkdirSync as Zo,readFileSync as Ho,writeFileSync as Go}from"fs";import{homedir as Ke}from"os";import{join as ee}from"path";function Me(){return process.env.ZIBBY_CONFIG_DIR||ee(Ke(),".zibby")}function Be(){return ee(Me(),"config.json")}function Wo(){let e=Me();Oe(e)||Zo(e,{recursive:!0})}function S(){try{let e=Be();if(Oe(e)){let o=Ho(e,"utf-8");return JSON.parse(o)}}catch{}return{}}function O(e){Wo(),Go(Be(),JSON.stringify(e,null,2))}function ne(){return S().sessionToken||null}function je(e){let o=S();o.sessionToken=e,O(o)}function Le(){return S().user||null}function De(e){let o=S();o.user=e,O(o)}function Ue(){return ne()!==null}function Ye(){let e=S();delete e.sessionToken,delete e.user,delete e.mem0ProxyUrl,O(e)}function Fe(){return S().proxyUrl||null}function Ze(e){let o=S();o.proxyUrl=e,O(o)}function He(){return S().mem0ProxyUrl||null}function Ge(e){let o=S();o.mem0ProxyUrl=e,O(o)}function Ve(){return S().projects||[]}function We(e){let o=S();o.projects=e,O(o)}var Ne,Vo,qo,se=j(()=>{Ne=ee(Ke(),".zibby"),Vo=ee(Ne,"config.json");qo={loadConfig:S,saveConfig:O,getSessionToken:ne,saveSessionToken:je,getUserInfo:Le,saveUserInfo:De,isLoggedIn:Ue,clearSession:Ye,getProxyUrl:Fe,saveProxyUrl:Ze,getMem0ProxyUrl:He,saveMem0ProxyUrl:Ge,getProjects:Ve,saveProjects:We,CONFIG_DIR:Ne,CONFIG_FILE:Vo}});var qe={};L(qe,{ENVIRONMENTS:()=>C,getAccountApiUrl:()=>Xo,getApiUrl:()=>Jo,getCurrentEnvironment:()=>Qo,getFrontendUrl:()=>et});function Jo(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";C[o]?e=C[o].apiUrl:e=C.prod.apiUrl}try{let o=new URL(e);return o.protocol!=="http:"&&o.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${o.protocol} (only http/https allowed)`),C.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),C.prod.apiUrl}}function Xo(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let e=process.env.ZIBBY_ENV||"prod";return(C[e]||C.prod).accountApiUrl}function Qo(){let e=process.env.ZIBBY_ENV||"prod";return C[e]||C.prod}function et(){let e;if(process.env.ZIBBY_FRONTEND_URL)e=process.env.ZIBBY_FRONTEND_URL;else{let o=process.env.ZIBBY_ENV||"prod";C[o]?e=C[o].frontendUrl:e=C.prod.frontendUrl}try{let o=new URL(e);if(o.protocol!=="http:"&&o.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${o.protocol} (only http/https allowed)`),C.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let i=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],s=o.hostname;if(!i.some(p=>s===p||s.endsWith(`.${p}`))&&!s.includes("localhost")&&s!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${s}`),"https://studio.zibby.dev"}return e}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${e}`),C.local.frontendUrl}}var C,Je=j(()=>{C={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}}});var ue={};L(ue,{__testing:()=>lt,buildDoltEnv:()=>at,clearConfig:()=>it,getActiveCredentials:()=>ro,isHosted:()=>rt,readConfig:()=>ce,refreshCredentials:()=>no,writeConfig:()=>st});import{readFileSync as Xe,writeFileSync as ae,existsSync as le,mkdirSync as Qe,chmodSync as ot}from"fs";import{join as ie}from"path";function H(e){let o=ie(e,".zibby");return{dir:o,config:ie(o,tt),creds:ie(o,nt)}}function ce(e){let{config:o}=H(e);if(!le(o))return null;try{let t=JSON.parse(Xe(o,"utf-8"));return t.mode!=="hosted"?null:t}catch{return null}}function rt(e){return!!ce(e)}function st(e,o){let{dir:t,config:i}=H(e);Qe(t,{recursive:!0}),ae(i,JSON.stringify({mode:"hosted",projectId:o.projectId,bucket:o.bucket,prefix:o.prefix,doltUrl:o.doltUrl,configuredAt:new Date().toISOString()},null,2),"utf-8")}function it(e){let{config:o,creds:t}=H(e);for(let i of[o,t])if(le(i))try{ae(i,"")}catch{}}function de(e){let{creds:o}=H(e);if(!le(o))return null;try{let t=JSON.parse(Xe(o,"utf-8"));return!t?.accessKeyId||!t?.secretAccessKey||!t?.sessionToken?null:t}catch{return null}}function oo(e,o){let{dir:t,creds:i}=H(e);Qe(t,{recursive:!0}),ae(i,JSON.stringify(o,null,2),"utf-8");try{ot(i,384)}catch{}}function to(e){return e?.expiration?new Date(e.expiration).getTime()-Date.now()<eo:!0}async function no({cwd:e,projectId:o,apiUrl:t,sessionToken:i,fetch:s=globalThis.fetch}){if(!o)throw new Error("refreshCredentials: projectId required");if(!t)throw new Error("refreshCredentials: apiUrl required");if(!i)throw new Error("refreshCredentials: sessionToken required (run `zibby login`)");let n=`${String(t).replace(/\/+$/,"")}/memory/sync-credentials`,p=await s(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({projectId:o})});if(!p.ok){let l=await p.text().catch(()=>"");throw new Error(`memory-sync credentials request failed (${p.status}): ${l||"no body"}`)}let d=await p.json();if(!d?.accessKeyId||!d?.secretAccessKey||!d?.sessionToken)throw new Error("memory-sync credentials response missing required fields");return oo(e,{accessKeyId:d.accessKeyId,secretAccessKey:d.secretAccessKey,sessionToken:d.sessionToken,expiration:d.expiration||null,refreshedAt:new Date().toISOString()}),de(e)}async function ro({cwd:e,apiUrl:o,sessionToken:t,fetch:i}){let s=ce(e);if(!s)return null;let n=de(e);return(!n||to(n))&&(n=await no({cwd:e,projectId:s.projectId,apiUrl:o,sessionToken:t,fetch:i})),n}async function at({cwd:e,apiUrl:o,sessionToken:t,fetch:i}){let s=await ro({cwd:e,apiUrl:o,sessionToken:t,fetch:i});return s?{AWS_ACCESS_KEY_ID:s.accessKeyId,AWS_SECRET_ACCESS_KEY:s.secretAccessKey,AWS_SESSION_TOKEN:s.sessionToken,AWS_REGION:process.env.AWS_REGION||"ap-southeast-2"}:null}var tt,nt,eo,lt,pe=j(()=>{tt="memory-sync.json",nt="memory-sync-creds.json",eo=120*1e3;lt={paths:H,readCreds:de,writeCreds:oo,isExpiringSoon:to,REFRESH_HEADROOM_MS:eo}});var so={};L(so,{memoryCompactCommand:()=>pt,memoryCostCommand:()=>mt,memoryInitCommand:()=>vt,memoryPullCommand:()=>ht,memoryPushCommand:()=>wt,memoryRemoteAddCommand:()=>gt,memoryRemoteInfoCommand:()=>yt,memoryRemoteRemoveCommand:()=>ft,memoryRemoteUseHostedCommand:()=>bt,memoryResetCommand:()=>ut,memoryStatsCommand:()=>dt});import r from"chalk";async function R(){try{return await import("@zibby/ui-memory")}catch{return console.log(r.yellow(`
|
|
10
10
|
@zibby/ui-memory is not installed.
|
|
11
11
|
`)),console.log(r.white(ct)),null}}async function dt(){let e=await R();if(!e)return;let o=process.cwd(),t=e.getStats(o);if(!t.available){console.log(r.red(`
|
|
12
12
|
Dolt is not installed.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import s from"chalk";import C from"ora";var r={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://
|
|
1
|
+
import s from"chalk";import C from"ora";var r={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function u(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let n=process.env.ZIBBY_ENV||"prod";r[n]?o=r[n].apiUrl:o=r.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)`),r.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),r.prod.apiUrl}}import{existsSync as g,mkdirSync as A,readFileSync as E,writeFileSync as $}from"fs";import{homedir as U}from"os";import{join as i}from"path";function m(){return process.env.ZIBBY_CONFIG_DIR||i(U(),".zibby")}function I(){return i(m(),"config.json")}var L=i(U(),".zibby"),Z=i(L,"config.json");function T(){let o=m();g(o)||A(o,{recursive:!0})}function f(){try{let o=I();if(g(o)){let n=E(o,"utf-8");return JSON.parse(n)}}catch{}return{}}function k(o){T(),$(I(),JSON.stringify(o,null,2))}function h(){return f().sessionToken||null}function v(){return f().user||null}function y(o){let n=f();n.projects=o,k(n)}async function G(){let o=C("Fetching projects...").start();try{let n=h(),c=v();n||(o.fail("Not logged in"),console.log(s.yellow(`
|
|
2
2
|
Please log in first:`)),console.log(s.gray(` zibby login
|
|
3
3
|
`)),process.exit(1)),c&&(console.log(s.gray(`Logged in as: ${c.email}`)),c.account_id&&console.log(s.gray(`Account ID: ${c.account_id}
|
|
4
4
|
`)));let _=u(),l=await fetch(`${_}/projects`,{headers:{Authorization:`Bearer ${n}`}});if(!l.ok){let e=await l.json().catch(()=>({}));throw new Error(e.error||"Failed to fetch projects")}let t=(await l.json()).projects||[],b=t.map(e=>({name:e.name,projectId:e.projectId,apiToken:e.apiToken}));if(y(b),o.stop(),t.length===0){console.log(`
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import p from"node:fs";import c from"node:path";import $ from"node:os";import r from"chalk";import{existsSync as x,mkdirSync as z,readFileSync as I,writeFileSync as L}from"fs";import{homedir as b}from"os";import{join as d}from"path";function P(){return process.env.ZIBBY_CONFIG_DIR||d(b(),".zibby")}function A(){return d(P(),"config.json")}var B=d(b(),".zibby"),Z=d(B,"config.json");function N(){try{let o=A();if(x(o)){let e=I(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function h(){return N().sessionToken||null}var u={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function v(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";u[e]?o=u[e].apiUrl:o=u.prod.apiUrl}try{let e=new URL(o);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),u.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),u.prod.apiUrl}}var _=v,g=["claude-code","claude-desktop","cursor","codex","gemini"],f={"claude-code":"Claude Code","claude-desktop":"Claude Desktop",cursor:"Cursor",codex:"Codex CLI",gemini:"Gemini CLI"};function C(o){let e=$.homedir();switch(o){case"claude-code":return c.join(e,".claude","settings.json");case"cursor":return c.join(e,".cursor","mcp.json");case"codex":return c.join(e,".codex","config.toml");case"gemini":return c.join(e,".gemini","settings.json");case"claude-desktop":return process.platform==="darwin"?c.join(e,"Library","Application Support","Claude","claude_desktop_config.json"):process.platform==="win32"?c.join(process.env.APPDATA||e,"Claude","claude_desktop_config.json"):c.join(e,".config","Claude","claude_desktop_config.json");default:return null}}async function w(o,e){let t=_(),s=await fetch(`${t}/api/user/tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({name:e})});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Could not mint PAT (HTTP ${s.status}): ${i.slice(0,200)}`)}let n=await s.json();if(!n?.token)throw new Error("PAT response missing token field");return n.token}function k(o){try{let e=p.readFileSync(o,"utf8");return e.trim()?JSON.parse(e):{}}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Could not parse existing config ${o}: ${e.message}`)}}function U(o,e){p.mkdirSync(c.dirname(o),{recursive:!0});let t=`${o}.zibby-mcp-${Date.now()}.tmp`;p.writeFileSync(t,e,{mode:384}),p.renameSync(t,o)}function S({existing:o,apiUrl:e,pat:t,agent:s}){let n={...o};n.mcpServers={...o.mcpServers||{}};let i=s==="gemini"?"httpUrl":"url";return n.mcpServers.zibby={[i]:`${e}/mcp`,headers:{Authorization:`Bearer ${t}`}},n}function R({existing:o,apiUrl:e,patEnvName:t}){let s=["","[mcp_servers.zibby]",`url = "${e}/mcp"`,`bearer_token_env_var = "${t}"`,""].join(`
|
|
2
|
+
`);if(!o.trim())return s.trimStart();let n=/(^|\n)\[mcp_servers\.zibby\][\s\S]*?(?=\n\[[^\]]+\]|\n*$)/;return n.test(o)?o.replace(n,`
|
|
3
|
+
${s.trim()}
|
|
4
|
+
`):o.replace(/\s*$/,"")+`
|
|
5
|
+
`+s}async function T({agent:o,sessionToken:e,apiUrl:t,force:s}){let n=C(o);if(!n)return console.log(r.yellow(` skip ${f[o]} \u2014 not supported on this platform`)),{skipped:!0};let i=`MCP \u2013 ${f[o]}`;console.log(r.gray(` \u2192 ${f[o]}`)),console.log(r.gray(` config: ${n}`));let l=await w(e,i);if(console.log(r.gray(` minted PAT: ${l.slice(0,18)}...`)),o==="codex"){let a=p.existsSync(n)?p.readFileSync(n,"utf8"):"",y=R({existing:a,apiUrl:t,patEnvName:"ZIBBY_PAT"});if(!s&&a===y)return console.log(r.gray(" no change needed")),{unchanged:!0};U(n,y),console.log(r.green(" \u2713 wrote")+r.gray(" "+c.basename(n))),console.log(r.yellow(" add to your shell rc:")),console.log(r.cyan(` export ZIBBY_PAT=${l}`))}else{let a=k(n),m=S({existing:a,apiUrl:t,pat:l,agent:o});U(n,JSON.stringify(m,null,2)+`
|
|
6
|
+
`),console.log(r.green(" \u2713 wrote")+r.gray(" "+c.basename(n)))}return{installed:!0,configFile:n}}async function W(o={}){let e=h();e||(console.error(r.red("Not logged in. Run `zibby login` first.")),process.exit(1));let t;o.all?t=[...g]:o.agent?(g.includes(o.agent)||(console.error(r.red(`Unknown agent: ${o.agent}`)),console.error(r.gray(`Known: ${g.join(", ")}`)),process.exit(1)),t=[o.agent]):(console.error(r.red("Pass --agent <name> or --all.")),console.error(""),console.error(r.gray("Examples:")),console.error(" zibby mcp install --agent claude-code"),console.error(" zibby mcp install --agent cursor"),console.error(" zibby mcp install --agent codex"),console.error(" zibby mcp install --agent gemini"),console.error(" zibby mcp install --all"),process.exit(1));let s=_();console.log(r.bold(`Installing Zibby Remote MCP into ${t.length} agent${t.length===1?"":"s"}\u2026`)),console.log(r.gray(`API: ${s}/mcp`)),console.log("");let n=[],i=0;for(let l of t){try{(await T({agent:l,sessionToken:e,apiUrl:s,force:o.force})).installed&&n.push(l)}catch(a){console.error(r.red(` \u2717 ${f[l]} failed: ${a.message}`)),i++}console.log("")}n.length&&(console.log(r.bold.green(`\u2713 Installed for ${n.length} agent${n.length===1?"":"s"}.`)),console.log(""),console.log(r.bold("Next step:")+" restart the agent so it picks up the new MCP server."),console.log(""),console.log(r.gray("Revoke / list your MCP tokens anytime at https://zibby.dev/settings/tokens"))),i&&process.exit(1)}export{W as mcpInstallCommand};
|
package/dist/commands/memory.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var lo=Object.defineProperty;var _=(e,n)=>()=>(e&&(n=e(e=0)),n);var I=(e,n)=>{for(var t in n)lo(e,t,{get:n[t],enumerable:!0})};var P={};I(P,{ENVIRONMENTS:()=>a,getAccountApiUrl:()=>ao,getApiUrl:()=>io,getCurrentEnvironment:()=>uo,getFrontendUrl:()=>go});function io(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let n=process.env.ZIBBY_ENV||"prod";a[n]?e=a[n].apiUrl:e=a.prod.apiUrl}try{let n=new URL(e);return n.protocol!=="http:"&&n.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${n.protocol} (only http/https allowed)`),a.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),a.prod.apiUrl}}function ao(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let e=process.env.ZIBBY_ENV||"prod";return(a[e]||a.prod).accountApiUrl}function uo(){let e=process.env.ZIBBY_ENV||"prod";return a[e]||a.prod}function go(){let e;if(process.env.ZIBBY_FRONTEND_URL)e=process.env.ZIBBY_FRONTEND_URL;else{let n=process.env.ZIBBY_ENV||"prod";a[n]?e=a[n].frontendUrl:e=a.prod.frontendUrl}try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${n.protocol} (only http/https allowed)`),a.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let c=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],s=n.hostname;if(!c.some(l=>s===l||s.endsWith(`.${l}`))&&!s.includes("localhost")&&s!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${s}`),"https://studio.zibby.dev"}return e}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${e}`),a.local.frontendUrl}}var a,E=_(()=>{a={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://
|
|
1
|
+
var lo=Object.defineProperty;var _=(e,n)=>()=>(e&&(n=e(e=0)),n);var I=(e,n)=>{for(var t in n)lo(e,t,{get:n[t],enumerable:!0})};var P={};I(P,{ENVIRONMENTS:()=>a,getAccountApiUrl:()=>ao,getApiUrl:()=>io,getCurrentEnvironment:()=>uo,getFrontendUrl:()=>go});function io(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let n=process.env.ZIBBY_ENV||"prod";a[n]?e=a[n].apiUrl:e=a.prod.apiUrl}try{let n=new URL(e);return n.protocol!=="http:"&&n.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${n.protocol} (only http/https allowed)`),a.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),a.prod.apiUrl}}function ao(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let e=process.env.ZIBBY_ENV||"prod";return(a[e]||a.prod).accountApiUrl}function uo(){let e=process.env.ZIBBY_ENV||"prod";return a[e]||a.prod}function go(){let e;if(process.env.ZIBBY_FRONTEND_URL)e=process.env.ZIBBY_FRONTEND_URL;else{let n=process.env.ZIBBY_ENV||"prod";a[n]?e=a[n].frontendUrl:e=a.prod.frontendUrl}try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${n.protocol} (only http/https allowed)`),a.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let c=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],s=n.hostname;if(!c.some(l=>s===l||s.endsWith(`.${l}`))&&!s.includes("localhost")&&s!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${s}`),"https://studio.zibby.dev"}return e}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${e}`),a.local.frontendUrl}}var a,E=_(()=>{a={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}}});var J={};I(J,{clearSession:()=>Y,default:()=>bo,getMem0ProxyUrl:()=>W,getProjects:()=>G,getProxyUrl:()=>Z,getSessionToken:()=>S,getUserInfo:()=>j,isLoggedIn:()=>F,loadConfig:()=>d,saveConfig:()=>f,saveMem0ProxyUrl:()=>V,saveProjects:()=>H,saveProxyUrl:()=>K,saveSessionToken:()=>O,saveUserInfo:()=>M});import{existsSync as N,mkdirSync as mo,readFileSync as yo,writeFileSync as po}from"fs";import{homedir as T}from"os";import{join as x}from"path";function D(){return process.env.ZIBBY_CONFIG_DIR||x(T(),".zibby")}function B(){return x(D(),"config.json")}function ho(){let e=D();N(e)||mo(e,{recursive:!0})}function d(){try{let e=B();if(N(e)){let n=yo(e,"utf-8");return JSON.parse(n)}}catch{}return{}}function f(e){ho(),po(B(),JSON.stringify(e,null,2))}function S(){return d().sessionToken||null}function O(e){let n=d();n.sessionToken=e,f(n)}function j(){return d().user||null}function M(e){let n=d();n.user=e,f(n)}function F(){return S()!==null}function Y(){let e=d();delete e.sessionToken,delete e.user,delete e.mem0ProxyUrl,f(e)}function Z(){return d().proxyUrl||null}function K(e){let n=d();n.proxyUrl=e,f(n)}function W(){return d().mem0ProxyUrl||null}function V(e){let n=d();n.mem0ProxyUrl=e,f(n)}function G(){return d().projects||[]}function H(e){let n=d();n.projects=e,f(n)}var L,fo,bo,q=_(()=>{L=x(T(),".zibby"),fo=x(L,"config.json");bo={loadConfig:d,saveConfig:f,getSessionToken:S,saveSessionToken:O,getUserInfo:j,saveUserInfo:M,isLoggedIn:F,clearSession:Y,getProxyUrl:Z,saveProxyUrl:K,getMem0ProxyUrl:W,saveMem0ProxyUrl:V,getProjects:G,saveProjects:H,CONFIG_DIR:L,CONFIG_FILE:fo}});var A={};I(A,{__testing:()=>Uo,buildDoltEnv:()=>vo,clearConfig:()=>So,getActiveCredentials:()=>ro,isHosted:()=>_o,readConfig:()=>C,refreshCredentials:()=>to,writeConfig:()=>Io});import{readFileSync as Q,writeFileSync as U,existsSync as R,mkdirSync as X,chmodSync as wo}from"fs";import{join as v}from"path";function b(e){let n=v(e,".zibby");return{dir:n,config:v(n,$o),creds:v(n,xo)}}function C(e){let{config:n}=b(e);if(!R(n))return null;try{let t=JSON.parse(Q(n,"utf-8"));return t.mode!=="hosted"?null:t}catch{return null}}function _o(e){return!!C(e)}function Io(e,n){let{dir:t,config:c}=b(e);X(t,{recursive:!0}),U(c,JSON.stringify({mode:"hosted",projectId:n.projectId,bucket:n.bucket,prefix:n.prefix,doltUrl:n.doltUrl,configuredAt:new Date().toISOString()},null,2),"utf-8")}function So(e){let{config:n,creds:t}=b(e);for(let c of[n,t])if(R(c))try{U(c,"")}catch{}}function z(e){let{creds:n}=b(e);if(!R(n))return null;try{let t=JSON.parse(Q(n,"utf-8"));return!t?.accessKeyId||!t?.secretAccessKey||!t?.sessionToken?null:t}catch{return null}}function eo(e,n){let{dir:t,creds:c}=b(e);X(t,{recursive:!0}),U(c,JSON.stringify(n,null,2),"utf-8");try{wo(c,384)}catch{}}function no(e){return e?.expiration?new Date(e.expiration).getTime()-Date.now()<oo:!0}async function to({cwd:e,projectId:n,apiUrl:t,sessionToken:c,fetch:s=globalThis.fetch}){if(!n)throw new Error("refreshCredentials: projectId required");if(!t)throw new Error("refreshCredentials: apiUrl required");if(!c)throw new Error("refreshCredentials: sessionToken required (run `zibby login`)");let r=`${String(t).replace(/\/+$/,"")}/memory/sync-credentials`,l=await s(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`},body:JSON.stringify({projectId:n})});if(!l.ok){let y=await l.text().catch(()=>"");throw new Error(`memory-sync credentials request failed (${l.status}): ${y||"no body"}`)}let i=await l.json();if(!i?.accessKeyId||!i?.secretAccessKey||!i?.sessionToken)throw new Error("memory-sync credentials response missing required fields");return eo(e,{accessKeyId:i.accessKeyId,secretAccessKey:i.secretAccessKey,sessionToken:i.sessionToken,expiration:i.expiration||null,refreshedAt:new Date().toISOString()}),z(e)}async function ro({cwd:e,apiUrl:n,sessionToken:t,fetch:c}){let s=C(e);if(!s)return null;let r=z(e);return(!r||no(r))&&(r=await to({cwd:e,projectId:s.projectId,apiUrl:n,sessionToken:t,fetch:c})),r}async function vo({cwd:e,apiUrl:n,sessionToken:t,fetch:c}){let s=await ro({cwd:e,apiUrl:n,sessionToken:t,fetch:c});return s?{AWS_ACCESS_KEY_ID:s.accessKeyId,AWS_SECRET_ACCESS_KEY:s.secretAccessKey,AWS_SESSION_TOKEN:s.sessionToken,AWS_REGION:process.env.AWS_REGION||"ap-southeast-2"}:null}var $o,xo,oo,Uo,k=_(()=>{$o="memory-sync.json",xo="memory-sync-creds.json",oo=120*1e3;Uo={paths:b,readCreds:z,writeCreds:eo,isExpiringSoon:no,REFRESH_HEADROOM_MS:oo}});import o from"chalk";var Ro=`
|
|
2
2
|
Install @zibby/ui-memory and Dolt to enable test memory:
|
|
3
3
|
|
|
4
4
|
npm install @zibby/ui-memory # add the package
|
package/dist/commands/project.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import a from"dotenv";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://
|
|
1
|
+
import a from"dotenv";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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function c(){let r;if(process.env.ZIBBY_API_URL)r=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";s[e]?r=s[e].apiUrl:r=s.prod.apiUrl}try{let e=new URL(r);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),s.prod.apiUrl):r}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${r}`),s.prod.apiUrl}}a.config();function d(r){let e=r.apiKey||process.env.ZIBBY_API_KEY;return e||(console.log(`
|
|
2
2
|
Error: API key is required`),console.log(` Set ZIBBY_API_KEY environment variable or use --api-key flag
|
|
3
3
|
`),process.exit(1)),{apiKey:e}}async function v(r={}){let{apiKey:e}=d(r),p=c();try{let t=await fetch(`${p}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}});if(!t.ok){let n=await t.json().catch(()=>({}));console.log(`
|
|
4
4
|
Error: ${n.message||t.statusText}
|
package/dist/commands/run.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
var De=Object.defineProperty;var je=(t,o)=>()=>(t&&(o=t(t=0)),o);var Ye=(t,o)=>{for(var s in o)De(t,s,{get:o[s],enumerable:!0})};var xe={};Ye(xe,{_resetLoaderCacheForTests:()=>lo,loadCredentialsIntoEnv:()=>co});import Pe from"node:fs";import to from"node:path";import no from"node:os";async function Ee(){if(!(process.env.__ZIBBY_CLAUDE_PLAN||process.platform!=="darwin"||!(process.env.CLAUDE_CODE_OAUTH_TOKEN||process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL||process.env.ANTHROPIC_AUTH_TOKEN)))try{let{execSync:o}=await import("node:child_process"),s=o('security find-generic-password -s "Claude Code-credentials" -w',{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(s){let i=JSON.parse(s)?.claudeAiOauth?.subscriptionType;i&&(process.env.__ZIBBY_CLAUDE_PLAN=i)}}catch{}}function io(t){try{if(!Pe.existsSync(t))return{};let o=Pe.readFileSync(t,"utf-8"),s=JSON.parse(o);return s&&s.agentKeys&&typeof s.agentKeys=="object"?s.agentKeys:{}}catch{return{}}}async function co(t={}){let{verbose:o=!1,force:s=!1,configPath:l}=t;if(q&&!s)return G;if(!!(process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL||process.env.ANTHROPIC_API_KEY_POOL||process.env.CLAUDE_CODE_OAUTH_TOKEN||process.env.ANTHROPIC_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN))return await Ee(),q=!0,G={oauthCount:0,apiCount:0,source:"cloud-env"},o&&console.log("[credentials-loader] env vars already set \u2014 skipping local discovery"),G;let a=l||to.join(no.homedir(),".zibby","config.json"),n=io(a),y="none",d=0,m=0;for(let h of so)n[h]&&!process.env[h]&&(process.env[h]=String(n[h]).trim(),y="config.json",h.endsWith("_POOL")?d+=String(n[h]).split(",").filter(D=>D.trim()).length:d+=1);for(let h of ro)n[h]&&!process.env[h]&&(process.env[h]=String(n[h]).trim(),y="config.json",h.endsWith("_POOL")?m+=String(n[h]).split(",").filter(D=>D.trim()).length:m+=1);return await Ee(),q=!0,G={oauthCount:d,apiCount:m,source:y},o&&d+m>0&&console.log(`[credentials-loader] loaded ${d} OAuth + ${m} API from ${y} (~/.zibby/config.json)`),G}function lo(){q=!1,G=null}var q,G,so,ro,be=je(()=>{q=!1,G=null,so=["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN_POOL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_AUTH_TOKEN_POOL"],ro=["ANTHROPIC_API_KEY","ANTHROPIC_API_KEY_POOL"]});import{runTest as ao,logger as U,DEFAULT_OUTPUT_BASE as uo,SESSIONS_DIR as po}from"@zibby/core";import{zibbyScratchSpecsDir as ae}from"@zibby/core/constants/zibby-scratch.js";import{createCliRunIndexPipelineProgressAppender as fo,postCliInterruptedRunIndex as Oe}from"@zibby/workflow-templates/run-index-post-cli.js";import{createWriteStream as Ke,mkdirSync as Fe}from"fs";import{join as pe,isAbsolute as ze}from"path";var Ge="studio-cli.log";function He(t,o){if(!t||typeof t!="string")return null;let s=t.trim();return s?ze(s)?s:pe(o,s):null}function Ze(t){if(!t)return()=>{};Fe(t,{recursive:!0});let o=pe(t,Ge),s=Ke(o,{flags:"a"}),l=process.stdout.write.bind(process.stdout),i=process.stderr.write.bind(process.stderr),a=n=>function(d,m,h){typeof m=="function"&&(h=m,m=void 0);try{Buffer.isBuffer(d)?s.write(d):s.write(String(d),m||"utf8")}catch{}return n(d,m,h)};return process.stdout.write=a(l),process.stderr.write=a(i),()=>{process.stdout.write=l,process.stderr.write=i;try{s.end()}catch{}}}function oe(t,o,s){let l=null;function i(a){if(!l&&a?.sessionPath){let n=He(a.sessionPath,o);n&&(l=Ze(n))}typeof t=="function"&&t(a)}return i.dispose=()=>{typeof l=="function"&&(l(),l=null)},i}import{existsSync as fe,mkdirSync as Me,readFileSync as Ve,readdirSync as Lo,unlinkSync as We,writeFileSync as ge}from"fs";import{join as he}from"path";import{execSync as Yo}from"child_process";import{DEFAULT_OUTPUT_BASE as Je}from"@zibby/core";function ye(t){return t?.paths?.output||Je}function te(t,o,s){return he(t,o,`.zibby-chat-run-pids-${s}.json`)}function me(t,o,s){let l=te(t,o,s);if(!fe(l))return[];try{let i=JSON.parse(Ve(l,"utf8"));return(Array.isArray(i?.pids)?i.pids:[]).map(n=>Number(n)).filter(n=>Number.isFinite(n)&&n>0)}catch{return[]}}function Ie(t,o,s,l={}){let i=Number(o),a=Number(s);if(!Number.isFinite(i)||i<=0||!Number.isFinite(a)||a<=0)return;let n=ye(l),y=he(t,n);Me(y,{recursive:!0});let d=me(t,n,i);d.includes(a)||d.push(a),ge(te(t,n,i),`${JSON.stringify({v:1,pids:d})}
|
|
2
2
|
`,"utf8")}function _e(t,o,s,l={}){let i=Number(o),a=Number(s);if(!Number.isFinite(i)||i<=0||!Number.isFinite(a)||a<=0)return;let n=ye(l),y=te(t,n,i);if(!fe(y))return;let d=me(t,n,i).filter(m=>m!==a);if(d.length===0)try{We(y)}catch{}else ge(y,`${JSON.stringify({v:1,pids:d})}
|
|
3
|
-
`,"utf8")}import{readFileSync as O,existsSync as w,statSync as Te,mkdirSync as Ue,writeFileSync as Se,appendFileSync as go,rmSync as $e}from"fs";import{resolve as B,join as $,dirname as ho,isAbsolute as Ne}from"path";import{fileURLToPath as yo}from"url";import{glob as X}from"glob";import e from"chalk";import Be from"ora";import mo from"dotenv";import Io from"open";var b={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://
|
|
3
|
+
`,"utf8")}import{readFileSync as O,existsSync as w,statSync as Te,mkdirSync as Ue,writeFileSync as Se,appendFileSync as go,rmSync as $e}from"fs";import{resolve as B,join as $,dirname as ho,isAbsolute as Ne}from"path";import{fileURLToPath as yo}from"url";import{glob as X}from"glob";import e from"chalk";import Be from"ora";import mo from"dotenv";import Io from"open";var b={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function W(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";b[o]?t=b[o].apiUrl:t=b.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)`),b.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),b.prod.apiUrl}}function we(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let t=process.env.ZIBBY_ENV||"prod";return(b[t]||b.prod).accountApiUrl}function ne(){let t=process.env.ZIBBY_ENV||"prod";return b[t]||b.prod}function se(){let t;if(process.env.ZIBBY_FRONTEND_URL)t=process.env.ZIBBY_FRONTEND_URL;else{let o=process.env.ZIBBY_ENV||"prod";b[o]?t=b[o].frontendUrl:t=b.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)`),b.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let l=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],i=o.hostname;if(!l.some(n=>i===n||i.endsWith(`.${n}`))&&!i.includes("localhost")&&i!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${i}`),"https://studio.zibby.dev"}return t}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${t}`),b.local.frontendUrl}}import{existsSync as qe,mkdirSync as Ho,readFileSync as Xe,writeFileSync as Zo}from"fs";import{homedir as ve}from"os";import{join as J}from"path";function Qe(){return process.env.ZIBBY_CONFIG_DIR||J(ve(),".zibby")}function eo(){return J(Qe(),"config.json")}var oo=J(ve(),".zibby"),Wo=J(oo,"config.json");function Ae(){try{let t=eo();if(qe(t)){let o=Xe(t,"utf-8");return JSON.parse(o)}}catch{}return{}}function re(){return Ae().sessionToken||null}function ie(){return Ae().user||null}var _o=yo(import.meta.url),wo=ho(_o),vo=JSON.parse(O($(wo,"../../package.json"),"utf-8"));function Ao(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 Ce(t,o){if(t==null)return null;let s=String(t).trim();return s?Ne(s)?s:B(o,s):null}function Po(t,o){try{if(!t||!w(t))return;let s=$(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)}
|
package/dist/commands/studio.js
CHANGED
|
@@ -5,7 +5,7 @@ var fe=Object.defineProperty;var me=(a,r)=>()=>(a&&(r=a(a=0)),r);var ge=(a,r)=>{
|
|
|
5
5
|
\u{1F4E6} Downloading Zibby Studio...`));try{let p=await fetch(a);if(!p.ok)throw new Error(`Download failed: ${p.status} ${p.statusText}`);let S=parseInt(p.headers.get("content-length")||"0",10),w=$.join(U.tmpdir(),r),h=0,_=Se(w);for await(let E of p.body)if(h+=E.length,_.write(E),S>0){let F=(h/S*100).toFixed(1),k=(h/1024/1024).toFixed(1),Y=(S/1024/1024).toFixed(1);process.stdout.write(`\r \u{1F4E5} ${F}% (${k}MB / ${Y}MB)`)}if(await new Promise((E,F)=>{_.on("finish",E),_.on("error",F),_.end()}),console.log(""),tt(O)&&Ie(O,{recursive:!0,force:!0}),be(O,{recursive:!0}),console.log(C.cyan(" \u{1F4C2} Installing...")),w.endsWith(".zip"))if(U.platform()==="darwin"||U.platform()==="linux"){if(Ut("unzip",["-oq",w,"-d",O]),U.platform()==="darwin")try{Ut("xattr",["-cr",O])}catch{}}else{let E=(await import("adm-zip")).default;new E(w).extractAllTo(O,!0)}else if(w.endsWith(".AppImage")){let{copyFileSync:E,chmodSync:F}=await import("fs"),k=$.join(O,r);E(w,k),F(k,493)}try{we(w)}catch{}return console.log(C.green(` \u2705 Zibby Studio installed!
|
|
6
6
|
`)),!0}catch(p){throw console.log(C.red(`
|
|
7
7
|
\u274C Installation failed: ${p.message}
|
|
8
|
-
`)),p}}function et(){let a=ot();return!!(a&&tt(a))}function ot(){if(U.platform()==="darwin")return $.join(O,"Zibby Studio.app");if(U.platform()==="win32")return $.join(O,"Zibby Studio.exe");if(U.platform()==="linux"){if(!tt(O))return null;let a=ye(O).find(r=>r.endsWith(".AppImage"));return a?$.join(O,a):null}return null}function Ae(){let a=$.join(O,"version.txt");return tt(a)?he(a,"utf-8").trim():"unknown"}var Pe,O,nt=me(()=>{Pe=process.env.ZIBBY_STUDIO_CDN||"https://dl.zibby.app",O=$.join(U.homedir(),".zibby","studio")});nt();import Gt from"express";import{createServer as ke}from"http";import{WebSocketServer as Ee}from"ws";import{spawn as ht,execSync as rt}from"child_process";import{readFileSync as x,existsSync as f,readdirSync as W,statSync as Z,createReadStream as Ue,createWriteStream as Be,mkdirSync as Wt,openSync as Le,readSync as Ce,closeSync as $e,writeFileSync as st,unlinkSync as Fe}from"fs";import{join as u,resolve as B,dirname as yt,basename as ze}from"path";import{homedir as De}from"os";import{inspect as Ze}from"util";import{fileURLToPath as Ye,pathToFileURL as Mt}from"url";import Ge from"dotenv";nt();import{spawn as Dt,execFileSync as $t}from"child_process";import mt from"os";import Zt from"path";import{existsSync as Ne,mkdirSync as Te,writeFileSync as Re}from"fs";var Ft=Zt.join(mt.homedir(),".zibby","studio-launch.json");function Oe(a){let r={};a.projectRoot&&(r.projectRoot=a.projectRoot),a.port&&(r.port=a.port),r.launchedAt=Date.now();let p=Zt.dirname(Ft);Te(p,{recursive:!0}),Re(Ft,JSON.stringify(r,null,2))}function xe(a){if(mt.platform()==="darwin"){try{$t("xattr",["-cr",a])}catch{}try{$t("spctl",["--add","--label","ZibbyStudio",a])}catch{}}}function zt(a,r){return new Promise(p=>{let S=Dt("open",["-a",a,"--env",`ZIBBY_STUDIO_PROJECT_ROOT=${r.projectRoot}`],{stdio:["ignore","pipe","pipe"]}),w="";S.stderr?.on("data",h=>{w+=h.toString()}),S.on("close",h=>p({code:h,stderr:w})),S.on("error",h=>p({code:1,stderr:h.message}))})}async function Yt(a={}){let r=ot();if(!r)throw new Error("Studio not installed");if(!Ne(r))throw new Error(`Studio app not found at ${r}`);Oe(a);let p=a.projectRoot||process.cwd();if(mt.platform()==="darwin"){let S=await zt(r,{projectRoot:p});if(S.code!==0&&S.stderr.includes("Launch failed")&&(xe(r),S=await zt(r,{projectRoot:p})),S.code!==0){let w=S.stderr.trim();w&&console.error(`[Studio Desktop] ${w}`),console.error(`Zibby Studio exited with code ${S.code}`)}}else{let S=Dt(r,[],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,ZIBBY_STUDIO_PROJECT_ROOT:p}});S.unref(),S.stderr?.on("data",w=>{let h=w.toString().trim();h&&console.error(`[Studio Desktop] ${h}`)}),S.on("error",w=>{console.error(`Failed to open Zibby Studio: ${w.message}`)})}}import{mergeSessionRunState as K,listRunningSessionStatesFromSessionsRoot as We}from"@zibby/core/utils/run-state-session.js";import{liveRunsFromSessionStateRows as Me}from"@zibby/core/utils/session-state-live-runs.js";import{findLatestLiveFrameFileSync as Jt,readLatestLiveFramePayloadSync as Kt}from"@zibby/core/utils/live-frame-discovery.js";var J={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://
|
|
8
|
+
`)),p}}function et(){let a=ot();return!!(a&&tt(a))}function ot(){if(U.platform()==="darwin")return $.join(O,"Zibby Studio.app");if(U.platform()==="win32")return $.join(O,"Zibby Studio.exe");if(U.platform()==="linux"){if(!tt(O))return null;let a=ye(O).find(r=>r.endsWith(".AppImage"));return a?$.join(O,a):null}return null}function Ae(){let a=$.join(O,"version.txt");return tt(a)?he(a,"utf-8").trim():"unknown"}var Pe,O,nt=me(()=>{Pe=process.env.ZIBBY_STUDIO_CDN||"https://dl.zibby.app",O=$.join(U.homedir(),".zibby","studio")});nt();import Gt from"express";import{createServer as ke}from"http";import{WebSocketServer as Ee}from"ws";import{spawn as ht,execSync as rt}from"child_process";import{readFileSync as x,existsSync as f,readdirSync as W,statSync as Z,createReadStream as Ue,createWriteStream as Be,mkdirSync as Wt,openSync as Le,readSync as Ce,closeSync as $e,writeFileSync as st,unlinkSync as Fe}from"fs";import{join as u,resolve as B,dirname as yt,basename as ze}from"path";import{homedir as De}from"os";import{inspect as Ze}from"util";import{fileURLToPath as Ye,pathToFileURL as Mt}from"url";import Ge from"dotenv";nt();import{spawn as Dt,execFileSync as $t}from"child_process";import mt from"os";import Zt from"path";import{existsSync as Ne,mkdirSync as Te,writeFileSync as Re}from"fs";var Ft=Zt.join(mt.homedir(),".zibby","studio-launch.json");function Oe(a){let r={};a.projectRoot&&(r.projectRoot=a.projectRoot),a.port&&(r.port=a.port),r.launchedAt=Date.now();let p=Zt.dirname(Ft);Te(p,{recursive:!0}),Re(Ft,JSON.stringify(r,null,2))}function xe(a){if(mt.platform()==="darwin"){try{$t("xattr",["-cr",a])}catch{}try{$t("spctl",["--add","--label","ZibbyStudio",a])}catch{}}}function zt(a,r){return new Promise(p=>{let S=Dt("open",["-a",a,"--env",`ZIBBY_STUDIO_PROJECT_ROOT=${r.projectRoot}`],{stdio:["ignore","pipe","pipe"]}),w="";S.stderr?.on("data",h=>{w+=h.toString()}),S.on("close",h=>p({code:h,stderr:w})),S.on("error",h=>p({code:1,stderr:h.message}))})}async function Yt(a={}){let r=ot();if(!r)throw new Error("Studio not installed");if(!Ne(r))throw new Error(`Studio app not found at ${r}`);Oe(a);let p=a.projectRoot||process.cwd();if(mt.platform()==="darwin"){let S=await zt(r,{projectRoot:p});if(S.code!==0&&S.stderr.includes("Launch failed")&&(xe(r),S=await zt(r,{projectRoot:p})),S.code!==0){let w=S.stderr.trim();w&&console.error(`[Studio Desktop] ${w}`),console.error(`Zibby Studio exited with code ${S.code}`)}}else{let S=Dt(r,[],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,ZIBBY_STUDIO_PROJECT_ROOT:p}});S.unref(),S.stderr?.on("data",w=>{let h=w.toString().trim();h&&console.error(`[Studio Desktop] ${h}`)}),S.on("error",w=>{console.error(`Failed to open Zibby Studio: ${w.message}`)})}}import{mergeSessionRunState as K,listRunningSessionStatesFromSessionsRoot as We}from"@zibby/core/utils/run-state-session.js";import{liveRunsFromSessionStateRows as Me}from"@zibby/core/utils/session-state-live-runs.js";import{findLatestLiveFrameFileSync as Jt,readLatestLiveFramePayloadSync as Kt}from"@zibby/core/utils/live-frame-discovery.js";var J={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function gt(){let a;if(process.env.ZIBBY_API_URL)a=process.env.ZIBBY_API_URL;else{let r=process.env.ZIBBY_ENV||"prod";J[r]?a=J[r].apiUrl:a=J.prod.apiUrl}try{let r=new URL(a);return r.protocol!=="http:"&&r.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${r.protocol} (only http/https allowed)`),J.prod.apiUrl):a}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${a}`),J.prod.apiUrl}}var Je=Ye(import.meta.url),Ke=yt(Je);function Ht(a){let r=u(a,"video.webm");if(f(r))return r;let p=u(a,"execute_live");if(!f(p))return null;try{let S=W(p).filter(h=>h.endsWith(".webm"));return S.length===0?null:S.map(h=>{let _=u(p,h);try{return{p:_,mtime:Z(_).mtimeMs}}catch{return{p:_,mtime:0}}}).sort((h,_)=>_.mtime-h.mtime)[0].p}catch{return null}}function Vt(a){if(process.platform==="win32")try{let r=rt("netstat -ano",{encoding:"utf8"}),p=new Set;for(let S of r.split(`
|
|
9
9
|
`)){if(!S.includes("LISTENING"))continue;let w=S.trim().split(/\s+/);if(!(w[1]||"").endsWith(`:${a}`))continue;let _=w[w.length-1];/^\d+$/.test(_)&&p.add(parseInt(_,10))}return[...p].filter(S=>S!==process.pid)}catch{return[]}try{let r=rt(`lsof -tiTCP:${a} -sTCP:LISTEN`,{encoding:"utf8"}).trim();return[...new Set(r.split(`
|
|
10
10
|
`).filter(Boolean))].map(p=>parseInt(p,10)).filter(p=>!Number.isNaN(p)&&p!==process.pid)}catch{return[]}}async function qt(a){let r=Vt(a);if(r.length!==0){console.log(`[Studio] Port ${a} in use \u2014 stopping previous Studio listener(s): ${r.join(", ")}`);for(let p of r)try{process.kill(p,"SIGTERM")}catch{}await new Promise(p=>setTimeout(p,450)),r=Vt(a);for(let p of r)try{process.kill(p,"SIGKILL")}catch{}await new Promise(p=>setTimeout(p,200))}}async function No(a={}){let r=Gt(),p=ke(r),S=new Ee({server:p}),w=a.port||3847,h=process.cwd(),_=De();process.env.DOTENV_CONFIG_QUIET="true";let E=process.env.NODE_ENV||"development";[B(h,".env.local"),B(h,`.env.${E}`),B(h,".env")].forEach(o=>{f(o)&&Ge.config({path:o,override:!1})});let k=new Map,Y=new Map,Qt=null,H=96e3,St="studio-cli.log",V="studio-run.json",Xt=".zibby-stop",it=512*1024;r.use(Gt.json()),r.get("/api/session-run-states",(o,t)=>{try{let e=L();try{let i=new URL(o.url,"http://zibby.studio").searchParams.get("sessionsRoot");if(i&&String(i).trim()){let l=B(decodeURIComponent(String(i).trim()));f(l)&&Z(l).isDirectory()&&(e=l)}}catch{}let s=We(e),{liveIdList:n,progressByKey:c}=Me(s);t.json({rows:s,liveIdList:n,progressByKey:c,sessionsRoot:e,unavailable:!1})}catch(e){t.status(500).json({error:e.message,rows:[],liveIdList:[],progressByKey:{},unavailable:!0})}}),r.get("/api/workflow/graph",async(o,t)=>{try{let e=null,s=u(h,".zibby","graph.mjs");if(f(s))try{let n=await import(Mt(s).href),c=n.BrowserTestAutomationAgent||n.default;if(c&&typeof c=="function"){let i=new c().buildGraph();i&&typeof i.serialize=="function"&&(e=i.serialize())}}catch{}if(!e)try{let{createRequire:n}=await import("module"),c=n(import.meta.url),d=u(yt(c.resolve("@zibby/core/package.json")),"templates","browser-test-automation","run_test.json");f(d)&&(e=JSON.parse(x(d,"utf-8")))}catch{}t.json({graph:e})}catch{t.json({graph:null})}}),r.use((o,t,e)=>(t.header("Access-Control-Allow-Origin","*"),t.header("Access-Control-Allow-Methods","GET, POST, PUT, DELETE"),t.header("Access-Control-Allow-Headers","Content-Type"),e()));let ct=u(Ke,"../../../../studio"),bt=f(u(ct,"package.json"));function te(){let o=u(ct,"node_modules",".bin",process.platform==="win32"?"electron.cmd":"electron"),t=f(o),n=ht(t?o:"npx",t?["."]:["electron","."],{cwd:ct,detached:!0,stdio:"ignore",shell:!1,env:{...process.env,ZIBBY_STUDIO_PROJECT_ROOT:h,ZIBBY_STUDIO_API_BASE:`http://localhost:${w}/api`}});n.unref(),Qt=n}async function ee(){if(bt){te();return}if(a.update||!et()){if(a.update&&et()){console.log(`
|
|
11
11
|
Updating Zibby Studio...
|
package/dist/commands/upload.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{readFileSync as m,existsSync as l,statSync as b}from"fs";import{join as p,basename as j}from"path";import{glob as z}from"glob";import e from"chalk";import F from"ora";import k from"dotenv";var r={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://
|
|
1
|
+
import{readFileSync as m,existsSync as l,statSync as b}from"fs";import{join as p,basename as j}from"path";import{glob as z}from"glob";import e from"chalk";import F from"ora";import k from"dotenv";var r={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function A(){let n;if(process.env.ZIBBY_API_URL)n=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";r[o]?n=r[o].apiUrl:n=r.prod.apiUrl}try{let o=new URL(n);return o.protocol!=="http:"&&o.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${o.protocol} (only http/https allowed)`),r.prod.apiUrl):n}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${n}`),r.prod.apiUrl}}function R(){let n=process.env.ZIBBY_ENV||"prod";return r[n]||r.prod}function E(){let n;if(process.env.ZIBBY_FRONTEND_URL)n=process.env.ZIBBY_FRONTEND_URL;else{let o=process.env.ZIBBY_ENV||"prod";r[o]?n=r[o].frontendUrl:n=r.prod.frontendUrl}try{let o=new URL(n);if(o.protocol!=="http:"&&o.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${o.protocol} (only http/https allowed)`),r.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let s=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],i=o.hostname;if(!s.some(u=>i===u||i.endsWith(`.${u}`))&&!i.includes("localhost")&&i!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${i}`),"https://studio.zibby.dev"}return n}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${n}`),r.local.frontendUrl}}import{existsSync as O,mkdirSync as q,readFileSync as D,writeFileSync as J}from"fs";import{homedir as $}from"os";import{join as y}from"path";function Y(){return process.env.ZIBBY_CONFIG_DIR||y($(),".zibby")}function S(){return y(Y(),"config.json")}var Z=y($(),".zibby"),H=y(Z,"config.json");function T(){try{let n=S();if(O(n)){let o=D(n,"utf-8");return JSON.parse(o)}}catch{}return{}}function w(){return T().sessionToken||null}function C(){return T().user||null}k.config();function V(n,o){let d=o?.paths?.specs||"test-specs",s=o?.paths?.generated||"tests";return n.replace(d,s).replace(/\.txt$/,".spec.js")}async function lo(n,o){let d=R();console.log(e.bold.cyan(`
|
|
2
2
|
\u{1F4E4} Zibby Cloud Upload
|
|
3
3
|
`)),console.log(e.gray("\u2501".repeat(50))),console.log(e.white(`Environment: ${e.cyan(d.name)}
|
|
4
4
|
`));let s=process.cwd(),i=o.project||process.env.ZIBBY_API_KEY;i||(console.log(e.red(`\u274C Error: Project API key required
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{readFileSync as Y,writeFileSync as U,existsSync as k,mkdirSync as x}from"fs";import{resolve as S,join as w}from"path";import o from"chalk";import I from"ora";import F from"dotenv";import L from"inquirer";var v={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://
|
|
1
|
+
import{readFileSync as Y,writeFileSync as U,existsSync as k,mkdirSync as x}from"fs";import{resolve as S,join as w}from"path";import o from"chalk";import I from"ora";import F from"dotenv";import L from"inquirer";var v={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function j(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";v[e]?t=v[e].apiUrl:t=v.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)`),v.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),v.prod.apiUrl}}function b(){let t=process.env.ZIBBY_ENV||"prod";return v[t]||v.prod}import{existsSync as z}from"fs";import{join as R}from"path";import{pathToFileURL as N}from"url";async function P(t){let e=R(t,".zibby.config.mjs");if(!z(e))throw new Error(".zibby.config.mjs not found");try{let n=await import(N(e).href);return n.default||n}catch(n){throw new Error(`Failed to load .zibby.config.mjs: ${n.message}`,{cause:n})}}import{validateGraphConfig as Z,generateWorkflowCode as O,generateNodeConfigsJson as K}from"@zibby/agent-workflow";import"@zibby/workflow-templates/register-nodes.js";F.config();async function J(t){let e=j(),n=I("Fetching projects...").start();try{let l=await fetch(`${e}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});l.ok||(n.fail("Failed to fetch projects"),process.exit(1));let r=await l.json();Array.isArray(r)||(r.projects&&Array.isArray(r.projects)?r=r.projects:r.data&&Array.isArray(r.data)?r=r.data:(n.fail("Unexpected response format"),process.exit(1))),(!r||r.length===0)&&(n.fail("No projects found"),process.exit(1)),n.stop();let p=r.map(a=>({name:`${a.name||"Unnamed"} (${a.id||"no-id"})`,value:a.id})),{projectId:c}=await L.prompt([{type:"list",name:"projectId",message:"Select a project:",choices:p}]);return c}catch(l){n.fail(`Error: ${l.message}`),process.exit(1)}}function B(t){let e=t.apiKey||process.env.ZIBBY_API_KEY;e||(console.log(o.red(`
|
|
2
2
|
ZIBBY_API_KEY not set`)),console.log(o.gray(` Add to .env: ZIBBY_API_KEY=zby_xxx
|
|
3
3
|
`)),process.exit(1));let n=t.project||process.env.ZIBBY_PROJECT_ID;return n||(console.log(o.red(`
|
|
4
4
|
--project or ZIBBY_PROJECT_ID is required`)),console.log(o.gray(` Example: zibby workflow download --project <id> --type analysis
|
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
import g from"ora";import h from"inquirer";import{readFileSync as I,existsSync as y}from"fs";import{join as E}from"path";import{homedir as P}from"os";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://
|
|
1
|
+
import g from"ora";import h from"inquirer";import{readFileSync as I,existsSync as y}from"fs";import{join as E}from"path";import{homedir as P}from"os";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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function b(){let s;if(process.env.ZIBBY_API_URL)s=process.env.ZIBBY_API_URL;else{let t=process.env.ZIBBY_ENV||"prod";p[t]?s=p[t].apiUrl:s=p.prod.apiUrl}try{let t=new URL(s);return t.protocol!=="http:"&&t.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${t.protocol} (only http/https allowed)`),p.prod.apiUrl):s}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${s}`),p.prod.apiUrl}}function m(){let s=E(P(),".zibby","config.json");if(y(s))try{let n=JSON.parse(I(s,"utf-8"));if(n.sessionToken)return n.sessionToken}catch{}let t=process.env.ZIBBY_API_KEY;if(t)return t;console.log(`
|
|
2
2
|
Not authenticated`),console.log(" Run: zibby login"),console.log(` OR set ZIBBY_API_KEY env var
|
|
3
3
|
`),process.exit(1)}async function L(s,t){let n=m(),e=b(),o={"Content-Type":"application/json",Authorization:`Bearer ${n}`};switch(s){case"enable":return v(e,o);case"status":return $(e,o);case"disable":return w(e,o);case"use":case"unuse":return U(e,o,s,t);default:console.log(`
|
|
4
4
|
Error: Unknown action "${s}"`),console.log(` Valid actions: enable | status | disable | use | unuse
|
|
5
5
|
`),process.exit(1)}}async function v(s,t){console.log(`
|
|
6
6
|
Dedicated Egress IP \u2014 Enable
|
|
7
|
-
`);let n=g("Checking account...").start(),e;try{let
|
|
8
|
-
`),process.exit(1)}e=await
|
|
7
|
+
`);let n=g("Checking account...").start(),e;try{let i=await fetch(`${s}/addons/dedicated-egress/status`,{method:"GET",headers:t});if(!i.ok){let a=await i.json().catch(()=>({}));n.fail("Check failed"),console.log(` Error: ${a.message||i.statusText}
|
|
8
|
+
`),process.exit(1)}e=await i.json()}catch(i){n.fail("Check failed"),console.log(` Error: ${i.message}
|
|
9
9
|
`),process.exit(1)}if(n.stop(),e.enabled&&!e.cancelAtPeriodEnd){console.log(" Already active."),e.elasticIp&&console.log(` Your static IP: ${e.elasticIp}`),console.log("");return}e.hasProSub||(console.log(" Dedicated egress requires an active Pro subscription."),console.log(` Upgrade at: https://zibby.dev/billing
|
|
10
|
-
`),process.exit(1));let o=e.pricing?.priceUSD??50,
|
|
11
|
-
`);let{confirm:d}=await h.prompt([{type:"confirm",name:"confirm",message:l?`Re-enable dedicated egress at $${o}/${
|
|
10
|
+
`),process.exit(1));let o=e.pricing?.priceUSD??50,c=e.pricing?.billingPeriod??"month",r=e.pricing?.description||"Static outbound IP for allowlisting on corporate firewalls.",l=e.enabled&&e.cancelAtPeriodEnd;console.log(` ${r}`),console.log(` Cost: $${o} per ${c} (prorated from today, billed via Stripe)
|
|
11
|
+
`);let{confirm:d}=await h.prompt([{type:"confirm",name:"confirm",message:l?`Re-enable dedicated egress at $${o}/${c}?`:`Enable dedicated egress at $${o}/${c}?`,default:!1}]);if(!d){console.log(`
|
|
12
12
|
Cancelled.
|
|
13
|
-
`);return}let u=g("Requesting dedicated egress IP for your account...").start();try{let
|
|
13
|
+
`);return}let u=g("Requesting dedicated egress IP for your account...").start();try{let i=await fetch(`${s}/addons/dedicated-egress/enable`,{method:"POST",headers:t});if(!i.ok){let f=await i.json().catch(()=>({}));u.fail("Enable failed"),f.code==="PAYMENT_METHOD_REQUIRED"?(console.log(`
|
|
14
14
|
No payment method on file.`),console.log(` Add a card first at: https://zibby.dev/billing
|
|
15
|
-
`)):console.log(` Error: ${f.error||f.message||
|
|
16
|
-
`),process.exit(1)}let a=await
|
|
15
|
+
`)):console.log(` Error: ${f.error||f.message||i.statusText}
|
|
16
|
+
`),process.exit(1)}let a=await i.json();u.succeed(l?"Re-enabled":"Provisioning started"),console.log(""),l&&a.elasticIp?console.log(` Your static IP is back online: ${a.elasticIp}
|
|
17
17
|
`):(console.log(` This takes 2-3 minutes.
|
|
18
18
|
`),a.elasticIp&&(console.log(" Once ready, allowlist this IP on your GitLab / GitHub:"),console.log(` ${a.elasticIp}
|
|
19
19
|
`))),console.log(" Then opt each project in:"),console.log(` zibby deploy --dedicated-ip use --project <project-id>
|
|
20
20
|
`),console.log(" Check status:"),console.log(` zibby deploy --dedicated-ip status
|
|
21
|
-
`)}catch(
|
|
21
|
+
`)}catch(i){u.fail("Enable failed"),console.log(` Error: ${i.message}
|
|
22
22
|
`),process.exit(1)}}async function $(s,t){let n=g("Fetching dedicated egress status...").start();try{let e=await fetch(`${s}/addons/dedicated-egress/status`,{method:"GET",headers:t});if(!e.ok){let r=await e.json().catch(()=>({}));n.fail("Status check failed"),console.log(` Error: ${r.message||e.statusText}
|
|
23
23
|
`),process.exit(1)}let o=await e.json();if(n.stop(),console.log(""),!o.enabled){console.log(` Dedicated egress IP: not enabled
|
|
24
24
|
`),console.log(" Enable it with:"),console.log(` zibby deploy --dedicated-ip enable
|
|
25
25
|
`);return}if(o.status==="provisioning"){console.log(` Dedicated egress IP: provisioning (2-3 min)
|
|
26
26
|
`),o.elasticIp&&console.log(` Your static IP (pending): ${o.elasticIp}`),console.log(""),console.log(" Check again in a moment:"),console.log(` zibby deploy --dedicated-ip status
|
|
27
|
-
`);return}let
|
|
28
|
-
`),console.log(` Your static IP: ${o.elasticIp}`),console.log(` Subnet: ${o.subnetId}`),console.log(` Provisioned: ${
|
|
27
|
+
`);return}let c=o.provisionedAt?new Date(o.provisionedAt).toLocaleDateString():"unknown";if(console.log(` Dedicated egress IP: active
|
|
28
|
+
`),console.log(` Your static IP: ${o.elasticIp}`),console.log(` Subnet: ${o.subnetId}`),console.log(` Provisioned: ${c}`),o.projects?.length){console.log(`
|
|
29
29
|
Projects using dedicated IP:`);for(let r of o.projects){let l=r.usesDedicatedEgress?"\u2713":"\u2717",d=r.usesDedicatedEgress?"":" [not opted in]";console.log(` ${l} ${r.name||r.projectId}${d}`)}}console.log(""),console.log(" Add this IP to your GitLab allowlist:"),console.log(" GitLab \u2192 Settings \u2192 Network \u2192 Outbound requests \u2192 Allow requests to:"),console.log(` ${o.elasticIp}
|
|
30
30
|
`)}catch(e){n.fail("Status check failed"),console.log(` Error: ${e.message}
|
|
31
31
|
`),process.exit(1)}}async function w(s,t){console.log(`
|
|
@@ -35,10 +35,10 @@ import g from"ora";import h from"inquirer";import{readFileSync as I,existsSync a
|
|
|
35
35
|
`)}catch(e){n.fail("Disable failed"),console.log(` Error: ${e.message}
|
|
36
36
|
`),process.exit(1)}}async function U(s,t,n,e){e||(e=process.env.ZIBBY_PROJECT_ID),e||(console.log(`
|
|
37
37
|
Error: --project <id> is required for "zibby deploy --dedicated-ip ${n}"`),console.log(` Or set ZIBBY_PROJECT_ID env var
|
|
38
|
-
`),process.exit(1));let o=n==="use",
|
|
38
|
+
`),process.exit(1));let o=n==="use",c=g(o?`Opting project ${e} into dedicated egress...`:`Opting project ${e} out of dedicated egress...`).start();try{let r=await fetch(`${s}/projects/${e}/addons/dedicated-egress/use`,{method:o?"POST":"DELETE",headers:t});if(!r.ok){let d=await r.json().catch(()=>({}));c.fail("Failed"),r.status===402?(console.log(`
|
|
39
39
|
Dedicated egress IP is not enabled for your account.`),console.log(" Enable it first:"),console.log(` zibby deploy --dedicated-ip enable
|
|
40
40
|
`)):console.log(` Error: ${d.message||r.statusText}
|
|
41
|
-
`),process.exit(1)}let l=await r.json();o?(
|
|
42
|
-
`))):(
|
|
43
|
-
`))}catch(r){
|
|
41
|
+
`),process.exit(1)}let l=await r.json();o?(c.succeed(`Project will now route through ${l.elasticIp||"dedicated IP"}`),console.log(""),l.elasticIp&&(console.log(` Static IP for this project: ${l.elasticIp}`),console.log(""),console.log(" Make sure this IP is allowlisted on your GitLab / GitHub:"),console.log(` ${l.elasticIp}
|
|
42
|
+
`))):(c.succeed("Project will now use dynamic public IP"),console.log(""),console.log(` This project's Fargate tasks will use a random IP going forward.
|
|
43
|
+
`))}catch(r){c.fail("Failed"),console.log(` Error: ${r.message}
|
|
44
44
|
`),process.exit(1)}}export{L as dedicatedEgressCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import e from"chalk";import h from"ora";import{confirm as y,select as U}from"@inquirer/prompts";import{readFileSync as I,existsSync as A}from"fs";import{homedir as $}from"os";import{join as _}from"path";var d={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://
|
|
1
|
+
import e from"chalk";import h from"ora";import{confirm as y,select as U}from"@inquirer/prompts";import{readFileSync as I,existsSync as A}from"fs";import{homedir as $}from"os";import{join as _}from"path";var d={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function u(){let r;if(process.env.ZIBBY_API_URL)r=process.env.ZIBBY_API_URL;else{let s=process.env.ZIBBY_ENV||"prod";d[s]?r=d[s].apiUrl:r=d.prod.apiUrl}try{let s=new URL(r);return s.protocol!=="http:"&&s.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${s.protocol} (only http/https allowed)`),d.prod.apiUrl):r}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${r}`),d.prod.apiUrl}}function B(){let r=_($(),".zibby","config.json");A(r)||(console.log(e.red(`
|
|
2
2
|
Not authenticated`)),console.log(e.gray(` Run: zibby login
|
|
3
3
|
`)),process.exit(1));let s;try{s=JSON.parse(I(r,"utf-8"))}catch{console.log(e.red(`
|
|
4
4
|
Config file corrupt`)),console.log(e.gray(` Run: zibby login
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var $o=Object.defineProperty;var O=(e,o)=>()=>(e&&(o=e(e=0)),o);var Ue=(e,o)=>{for(var t in o)$o(e,t,{get:o[t],enumerable:!0})};function U(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";G[o]?e=G[o].apiUrl:e=G.prod.apiUrl}try{let o=new URL(e);return o.protocol!=="http:"&&o.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${o.protocol} (only http/https allowed)`),G.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),G.prod.apiUrl}}var G,W=O(()=>{G={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://
|
|
1
|
+
var $o=Object.defineProperty;var O=(e,o)=>()=>(e&&(o=e(e=0)),o);var Ue=(e,o)=>{for(var t in o)$o(e,t,{get:o[t],enumerable:!0})};function U(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";G[o]?e=G[o].apiUrl:e=G.prod.apiUrl}try{let o=new URL(e);return o.protocol!=="http:"&&o.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${o.protocol} (only http/https allowed)`),G.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),G.prod.apiUrl}}var G,W=O(()=>{G={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}}});import{existsSync as Be,mkdirSync as No,readFileSync as Bo,writeFileSync as Ko}from"fs";import{homedir as Ke}from"os";import{join as Z}from"path";function De(){return process.env.ZIBBY_CONFIG_DIR||Z(Ke(),".zibby")}function Re(){return Z(De(),"config.json")}function Ro(){let e=De();Be(e)||No(e,{recursive:!0})}function R(){try{let e=Re();if(Be(e)){let o=Bo(e,"utf-8");return JSON.parse(o)}}catch{}return{}}function M(e){Ro(),Ko(Re(),JSON.stringify(e,null,2))}function ze(){return R().sessionToken||null}function Ye(e){let o=R();o.sessionToken=e,M(o)}function Fe(){return R().user||null}function Ge(e){let o=R();o.user=e,M(o)}function Me(e){let o=R();o.proxyUrl=e,M(o)}function He(e){let o=R();o.mem0ProxyUrl=e,M(o)}function Ve(e){let o=R();o.projects=e,M(o)}var Do,Ft,Je=O(()=>{Do=Z(Ke(),".zibby"),Ft=Z(Do,"config.json")});import{existsSync as Ht,mkdirSync as Vt,readFileSync as Jt,writeFileSync as Wt,unlinkSync as Zt}from"fs";import{resolve as Qt}from"path";import{homedir as en}from"os";var We=O(()=>{});import h from"chalk";import fe from"ora";import{spawn as zo}from"child_process";function Yo(e){let o=process.platform;try{let t,n;return o==="darwin"?(t="open",n=[e]):o==="win32"?(t="cmd",n=["/c","start","",e]):(t="xdg-open",n=[e]),zo(t,n,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function Fo(){let e=ze(),o=Fe();return e&&o?{loggedIn:!0,user:o,token:e}:{loggedIn:!1}}async function qe(){try{console.log(h.cyan(`
|
|
2
2
|
\u{1F510} Initiating login...
|
|
3
3
|
`));let e=Fo();if(e.loggedIn){console.log(h.green("\u2705 Already logged in!")),console.log(h.gray(`User: ${e.user.email}`)),console.log(h.gray(`Name: ${e.user.name}
|
|
4
4
|
`));let{createInterface:o}=await import("readline"),t=o({input:process.stdin,output:process.stdout});return new Promise((n,r)=>{let i=()=>{t.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},s=()=>{console.log(h.yellow(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var uo=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});import{existsSync as ro,readFileSync as Po,writeFileSync as L,mkdirSync as B,mkdtempSync as Ao,renameSync as _o,rmSync as _}from"fs";import{join as w,dirname as co,resolve as T}from"path";import{tmpdir as Bo}from"os";import a from"chalk";import so from"ora";import io from"inquirer";import{existsSync as Uo,readFileSync as So}from"fs";import{join as Io}from"path";import E from"chalk";import{confirm as xo}from"@inquirer/prompts";import t from"chalk";import C from"ora";import{spawn as mo}from"child_process";var I={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://
|
|
1
|
+
var uo=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});import{existsSync as ro,readFileSync as Po,writeFileSync as L,mkdirSync as B,mkdtempSync as Ao,renameSync as _o,rmSync as _}from"fs";import{join as w,dirname as co,resolve as T}from"path";import{tmpdir as Bo}from"os";import a from"chalk";import so from"ora";import io from"inquirer";import{existsSync as Uo,readFileSync as So}from"fs";import{join as Io}from"path";import E from"chalk";import{confirm as xo}from"@inquirer/prompts";import t from"chalk";import C from"ora";import{spawn as mo}from"child_process";var I={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function x(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";I[e]?o=I[e].apiUrl:o=I.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)`),I.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),I.prod.apiUrl}}import{existsSync as Y,mkdirSync as fo,readFileSync as po,writeFileSync as go}from"fs";import{homedir as Z}from"os";import{join as A}from"path";function J(){return process.env.ZIBBY_CONFIG_DIR||A(Z(),".zibby")}function G(){return A(J(),"config.json")}var yo=A(Z(),".zibby"),Fo=A(yo,"config.json");function ho(){let o=J();Y(o)||fo(o,{recursive:!0})}function k(){try{let o=G();if(Y(o)){let e=po(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function j(o){ho(),go(G(),JSON.stringify(o,null,2))}function K(){return k().sessionToken||null}function W(o){let e=k();e.sessionToken=o,j(e)}function M(){return k().user||null}function V(o){let e=k();e.user=o,j(e)}function H(o){let e=k();e.proxyUrl=o,j(e)}function q(o){let e=k();e.mem0ProxyUrl=o,j(e)}function X(o){let e=k();e.projects=o,j(e)}import{existsSync as Jo,mkdirSync as Go,readFileSync as Ko,writeFileSync as Wo,unlinkSync as Mo}from"fs";import{resolve as Ho}from"path";import{homedir as Xo}from"os";function wo(o){let e=process.platform;try{let n,r;return e==="darwin"?(n="open",r=[o]):e==="win32"?(n="cmd",r=["/c","start","",o]):(n="xdg-open",r=[o]),mo(n,r,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function vo(){let o=K(),e=M();return o&&e?{loggedIn:!0,user:e,token:o}:{loggedIn:!1}}async function oo(){try{console.log(t.cyan(`
|
|
2
2
|
\u{1F510} Initiating login...
|
|
3
3
|
`));let o=vo();if(o.loggedIn){console.log(t.green("\u2705 Already logged in!")),console.log(t.gray(`User: ${o.user.email}`)),console.log(t.gray(`Name: ${o.user.name}
|
|
4
4
|
`));let{createInterface:e}=await import("readline"),n=e({input:process.stdin,output:process.stdout});return new Promise((r,l)=>{let s=()=>{n.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},u=()=>{console.log(t.yellow(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import a from"chalk";import x from"ora";import{existsSync as ao,readFileSync as uo}from"fs";import{join as po}from"path";import A from"chalk";import{confirm as fo}from"@inquirer/prompts";import c from"chalk";import T from"ora";import{spawn as ro}from"child_process";var m={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://
|
|
1
|
+
import a from"chalk";import x from"ora";import{existsSync as ao,readFileSync as uo}from"fs";import{join as po}from"path";import A from"chalk";import{confirm as fo}from"@inquirer/prompts";import c from"chalk";import T from"ora";import{spawn as ro}from"child_process";var m={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function v(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";m[e]?o=m[e].apiUrl:o=m.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)`),m.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),m.prod.apiUrl}}import{existsSync as z,mkdirSync as Q,readFileSync as oo,writeFileSync as eo}from"fs";import{homedir as L}from"os";import{join as U}from"path";function O(){return process.env.ZIBBY_CONFIG_DIR||U(L(),".zibby")}function R(){return U(O(),"config.json")}var no=U(L(),".zibby"),ko=U(no,"config.json");function to(){let o=O();z(o)||Q(o,{recursive:!0})}function g(){try{let o=R();if(z(o)){let e=oo(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function w(o){to(),eo(R(),JSON.stringify(o,null,2))}function Y(){return g().sessionToken||null}function D(o){let e=g();e.sessionToken=o,w(e)}function F(){return g().user||null}function K(o){let e=g();e.user=o,w(e)}function Z(o){let e=g();e.proxyUrl=o,w(e)}function V(o){let e=g();e.mem0ProxyUrl=o,w(e)}function J(o){let e=g();e.projects=o,w(e)}import{existsSync as bo,mkdirSync as Io,readFileSync as To,writeFileSync as So,unlinkSync as Ao}from"fs";import{resolve as Eo}from"path";import{homedir as _o}from"os";function so(o){let e=process.platform;try{let n,t;return e==="darwin"?(n="open",t=[o]):e==="win32"?(n="cmd",t=["/c","start","",o]):(n="xdg-open",t=[o]),ro(n,t,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function io(){let o=Y(),e=F();return o&&e?{loggedIn:!0,user:e,token:o}:{loggedIn:!1}}async function M(){try{console.log(c.cyan(`
|
|
2
2
|
\u{1F510} Initiating login...
|
|
3
3
|
`));let o=io();if(o.loggedIn){console.log(c.green("\u2705 Already logged in!")),console.log(c.gray(`User: ${o.user.email}`)),console.log(c.gray(`Name: ${o.user.name}
|
|
4
4
|
`));let{createInterface:e}=await import("readline"),n=e({input:process.stdin,output:process.stdout});return new Promise((t,r)=>{let s=()=>{n.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},i=()=>{console.log(c.yellow(`
|
|
@@ -7,7 +7,7 @@ var et=Object.defineProperty;var K=(o,e)=>()=>(o&&(e=o(o=0)),e);var U=(o,e)=>{fo
|
|
|
7
7
|
`)),console.log(A.gray(" Run `zibby init` first to bootstrap the project.\n")),process.exit(1));let n;try{n=await Ve(t,o,{enableMemory:e.enableMemory!==!1})}catch(r){console.log(A.red(`
|
|
8
8
|
${r.message}
|
|
9
9
|
`)),console.log(A.gray(` See available templates: zibby template list
|
|
10
|
-
`)),process.exit(1)}console.log(""),console.log(A.green(` \u2713 Added template ${A.bold(n.template.name)}`)),console.log(A.gray(` ${n.copied.length} files written to ${s}/`));for(let r of n.copied)console.log(A.gray(` \u2022 ${r}`));if(!e.skipInstall&&ue(G(t,"package.json"))){let r=!1;try{yt(G(t,"package.json")).resolve("@zibby/core/package.json"),r=!0}catch{}if(!r){let l=`@zibby/core@${JSON.parse(pt(G(bt,"../../package.json"),"utf-8")).dependencies?.["@zibby/core"]||"latest"}`,i=ht(` Installing ${l} (needed by .zibby/graph.mjs)...`).start();await new Promise(w=>{ft("npm",["install","--save-dev",l],{cwd:t,stdio:"pipe"}).on("close",y=>w(y??1))})===0?i.succeed(` Installed ${l}`):(i.warn(` Could not auto-install ${l}`),console.log(A.gray(` Run manually: npm install --save-dev ${l}`)))}}console.log(""),console.log(A.gray(" Re-running `zibby template add <name>` overwrites existing files \u2014")),console.log(A.gray(" use this to refresh after `npm update @zibby/core`.")),console.log("")}var wt,bt,kt,he=K(()=>{wt=mt(import.meta.url),bt=gt(wt),kt=[/^__tests__$/,/^__mocks__$/,/^node_modules$/,/\.test\.[mc]?js$/,/\.spec\.[mc]?js$/,/^\.DS_Store$/,/^chat\.mjs$/]});var Xe={};U(Xe,{applyMemorySyncConfig:()=>St,validateMemorySyncConfig:()=>qe});function qe(o){if(!o||typeof o!="object")return{ok:!0,kind:"noop"};let e=o.remote;return Ct.includes(e)?{ok:!0,kind:"noop"}:typeof e!="string"?{ok:!1,error:`memorySync.remote must be null or a string, got ${typeof e}`}:e===At?{ok:!0,kind:"hosted"}:Je.some(t=>e.startsWith(t))?{ok:!0,kind:"byo",remote:e}:{ok:!1,error:`memorySync.remote = ${JSON.stringify(e)} is not recognized. Use null, 'hosted', or a URL beginning with one of: ${Je.join(" / ")}.`}}async function St({cwd:o,projectId:e,block:t,memoryApi:s,hostedSetup:n,getSessionToken:r,logger:u=console}){let l=qe(t);if(!l.ok)return u.warn?.(`[memory-sync] config invalid: ${l.error}`),{action:"error",reason:l.error};if(l.kind==="noop")return{action:"skipped",reason:"memorySync.remote not set"};if(l.kind==="byo")return s?.memoryRemoteAdd?s.memoryRemoteAdd(o,l.remote)?{action:"byo",remote:l.remote}:{action:"error",reason:"memoryRemoteAdd returned false (memory DB not initialized?)"}:{action:"error",reason:"@zibby/ui-memory not loaded"};if(l.kind==="hosted"){if(typeof r=="function"&&!r())return{action:"pending-login",reason:'memorySync.remote = "hosted" but the user is not logged in. Run `zibby login` then `zibby memory remote use --hosted`.'};if(typeof n!="function")return{action:"error",reason:"hostedSetup function not provided"};try{return await n({cwd:o,projectId:e}),{action:"hosted"}}catch(i){return{action:"error",reason:`hosted setup failed: ${i.message}`}}}return{action:"error",reason:`unhandled kind: ${l.kind}`}}var Ct,At,Je,Qe=K(()=>{Ct=[null,void 0,"","none","off",!1],At="hosted",Je=["aws://","gs://","https://","http://","file://"]});var be={};U(be,{clearSession:()=>co,default:()=>jt,getMem0ProxyUrl:()=>go,getProjects:()=>fo,getProxyUrl:()=>uo,getSessionToken:()=>we,getUserInfo:()=>io,isLoggedIn:()=>lo,loadConfig:()=>R,saveConfig:()=>Y,saveMem0ProxyUrl:()=>mo,saveProjects:()=>yo,saveProxyUrl:()=>po,saveSessionToken:()=>so,saveUserInfo:()=>ao});import{existsSync as eo,mkdirSync as It,readFileSync as _t,writeFileSync as Pt}from"fs";import{homedir as oo}from"os";import{join as de}from"path";function to(){return process.env.ZIBBY_CONFIG_DIR||de(oo(),".zibby")}function no(){return de(to(),"config.json")}function zt(){let o=to();eo(o)||It(o,{recursive:!0})}function R(){try{let o=no();if(eo(o)){let e=_t(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function Y(o){zt(),Pt(no(),JSON.stringify(o,null,2))}function we(){return R().sessionToken||null}function so(o){let e=R();e.sessionToken=o,Y(e)}function io(){return R().user||null}function ao(o){let e=R();e.user=o,Y(e)}function lo(){return we()!==null}function co(){let o=R();delete o.sessionToken,delete o.user,delete o.mem0ProxyUrl,Y(o)}function uo(){return R().proxyUrl||null}function po(o){let e=R();e.proxyUrl=o,Y(e)}function go(){return R().mem0ProxyUrl||null}function mo(o){let e=R();e.mem0ProxyUrl=o,Y(e)}function fo(){return R().projects||[]}function yo(o){let e=R();e.projects=o,Y(e)}var ro,Et,jt,ke=K(()=>{ro=de(oo(),".zibby"),Et=de(ro,"config.json");jt={loadConfig:R,saveConfig:Y,getSessionToken:we,saveSessionToken:so,getUserInfo:io,saveUserInfo:ao,isLoggedIn:lo,clearSession:co,getProxyUrl:uo,saveProxyUrl:po,getMem0ProxyUrl:go,saveMem0ProxyUrl:mo,getProjects:fo,saveProjects:yo,CONFIG_DIR:ro,CONFIG_FILE:Et}});var ho={};U(ho,{ENVIRONMENTS:()=>j,getAccountApiUrl:()=>Rt,getApiUrl:()=>Ot,getCurrentEnvironment:()=>Tt,getFrontendUrl:()=>Nt});function Ot(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";j[e]?o=j[e].apiUrl:o=j.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)`),j.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),j.prod.apiUrl}}function Rt(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let o=process.env.ZIBBY_ENV||"prod";return(j[o]||j.prod).accountApiUrl}function Tt(){let o=process.env.ZIBBY_ENV||"prod";return j[o]||j.prod}function Nt(){let o;if(process.env.ZIBBY_FRONTEND_URL)o=process.env.ZIBBY_FRONTEND_URL;else{let e=process.env.ZIBBY_ENV||"prod";j[e]?o=j[e].frontendUrl:o=j.prod.frontendUrl}try{let e=new URL(o);if(e.protocol!=="http:"&&e.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${e.protocol} (only http/https allowed)`),j.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let s=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],n=e.hostname;if(!s.some(u=>n===u||n.endsWith(`.${u}`))&&!n.includes("localhost")&&n!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${n}`),"https://studio.zibby.dev"}return o}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${o}`),j.local.frontendUrl}}var j,wo=K(()=>{j={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"}}});var Se={};U(Se,{__testing:()=>Ft,buildDoltEnv:()=>Yt,clearConfig:()=>Ut,getActiveCredentials:()=>Ao,isHosted:()=>Lt,readConfig:()=>Ce,refreshCredentials:()=>Co,writeConfig:()=>Dt});import{readFileSync as bo,writeFileSync as xe,existsSync as $e,mkdirSync as ko,chmodSync as Bt}from"fs";import{join as ve}from"path";function oe(o){let e=ve(o,".zibby");return{dir:e,config:ve(e,Mt),creds:ve(e,Kt)}}function Ce(o){let{config:e}=oe(o);if(!$e(e))return null;try{let t=JSON.parse(bo(e,"utf-8"));return t.mode!=="hosted"?null:t}catch{return null}}function Lt(o){return!!Ce(o)}function Dt(o,e){let{dir:t,config:s}=oe(o);ko(t,{recursive:!0}),xe(s,JSON.stringify({mode:"hosted",projectId:e.projectId,bucket:e.bucket,prefix:e.prefix,doltUrl:e.doltUrl,configuredAt:new Date().toISOString()},null,2),"utf-8")}function Ut(o){let{config:e,creds:t}=oe(o);for(let s of[e,t])if($e(s))try{xe(s,"")}catch{}}function Ae(o){let{creds:e}=oe(o);if(!$e(e))return null;try{let t=JSON.parse(bo(e,"utf-8"));return!t?.accessKeyId||!t?.secretAccessKey||!t?.sessionToken?null:t}catch{return null}}function xo(o,e){let{dir:t,creds:s}=oe(o);ko(t,{recursive:!0}),xe(s,JSON.stringify(e,null,2),"utf-8");try{Bt(s,384)}catch{}}function $o(o){return o?.expiration?new Date(o.expiration).getTime()-Date.now()<vo:!0}async function Co({cwd:o,projectId:e,apiUrl:t,sessionToken:s,fetch:n=globalThis.fetch}){if(!e)throw new Error("refreshCredentials: projectId required");if(!t)throw new Error("refreshCredentials: apiUrl required");if(!s)throw new Error("refreshCredentials: sessionToken required (run `zibby login`)");let r=`${String(t).replace(/\/+$/,"")}/memory/sync-credentials`,u=await n(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({projectId:e})});if(!u.ok){let i=await u.text().catch(()=>"");throw new Error(`memory-sync credentials request failed (${u.status}): ${i||"no body"}`)}let l=await u.json();if(!l?.accessKeyId||!l?.secretAccessKey||!l?.sessionToken)throw new Error("memory-sync credentials response missing required fields");return xo(o,{accessKeyId:l.accessKeyId,secretAccessKey:l.secretAccessKey,sessionToken:l.sessionToken,expiration:l.expiration||null,refreshedAt:new Date().toISOString()}),Ae(o)}async function Ao({cwd:o,apiUrl:e,sessionToken:t,fetch:s}){let n=Ce(o);if(!n)return null;let r=Ae(o);return(!r||$o(r))&&(r=await Co({cwd:o,projectId:n.projectId,apiUrl:e,sessionToken:t,fetch:s})),r}async function Yt({cwd:o,apiUrl:e,sessionToken:t,fetch:s}){let n=await Ao({cwd:o,apiUrl:e,sessionToken:t,fetch:s});return n?{AWS_ACCESS_KEY_ID:n.accessKeyId,AWS_SECRET_ACCESS_KEY:n.secretAccessKey,AWS_SESSION_TOKEN:n.sessionToken,AWS_REGION:process.env.AWS_REGION||"ap-southeast-2"}:null}var Mt,Kt,vo,Ft,Ie=K(()=>{Mt="memory-sync.json",Kt="memory-sync-creds.json",vo=120*1e3;Ft={paths:oe,readCreds:Ae,writeCreds:xo,isExpiringSoon:$o,REFRESH_HEADROOM_MS:vo}});var So={};U(So,{memoryCompactCommand:()=>Gt,memoryCostCommand:()=>Vt,memoryInitCommand:()=>tn,memoryPullCommand:()=>Qt,memoryPushCommand:()=>on,memoryRemoteAddCommand:()=>Jt,memoryRemoteInfoCommand:()=>qt,memoryRemoteRemoveCommand:()=>Xt,memoryRemoteUseHostedCommand:()=>en,memoryResetCommand:()=>Zt,memoryStatsCommand:()=>Wt});import a from"chalk";async function T(){try{return await import("@zibby/ui-memory")}catch{return console.log(a.yellow(`
|
|
10
|
+
`)),process.exit(1)}console.log(""),console.log(A.green(` \u2713 Added template ${A.bold(n.template.name)}`)),console.log(A.gray(` ${n.copied.length} files written to ${s}/`));for(let r of n.copied)console.log(A.gray(` \u2022 ${r}`));if(!e.skipInstall&&ue(G(t,"package.json"))){let r=!1;try{yt(G(t,"package.json")).resolve("@zibby/core/package.json"),r=!0}catch{}if(!r){let l=`@zibby/core@${JSON.parse(pt(G(bt,"../../package.json"),"utf-8")).dependencies?.["@zibby/core"]||"latest"}`,i=ht(` Installing ${l} (needed by .zibby/graph.mjs)...`).start();await new Promise(w=>{ft("npm",["install","--save-dev",l],{cwd:t,stdio:"pipe"}).on("close",y=>w(y??1))})===0?i.succeed(` Installed ${l}`):(i.warn(` Could not auto-install ${l}`),console.log(A.gray(` Run manually: npm install --save-dev ${l}`)))}}console.log(""),console.log(A.gray(" Re-running `zibby template add <name>` overwrites existing files \u2014")),console.log(A.gray(" use this to refresh after `npm update @zibby/core`.")),console.log("")}var wt,bt,kt,he=K(()=>{wt=mt(import.meta.url),bt=gt(wt),kt=[/^__tests__$/,/^__mocks__$/,/^node_modules$/,/\.test\.[mc]?js$/,/\.spec\.[mc]?js$/,/^\.DS_Store$/,/^chat\.mjs$/]});var Xe={};U(Xe,{applyMemorySyncConfig:()=>St,validateMemorySyncConfig:()=>qe});function qe(o){if(!o||typeof o!="object")return{ok:!0,kind:"noop"};let e=o.remote;return Ct.includes(e)?{ok:!0,kind:"noop"}:typeof e!="string"?{ok:!1,error:`memorySync.remote must be null or a string, got ${typeof e}`}:e===At?{ok:!0,kind:"hosted"}:Je.some(t=>e.startsWith(t))?{ok:!0,kind:"byo",remote:e}:{ok:!1,error:`memorySync.remote = ${JSON.stringify(e)} is not recognized. Use null, 'hosted', or a URL beginning with one of: ${Je.join(" / ")}.`}}async function St({cwd:o,projectId:e,block:t,memoryApi:s,hostedSetup:n,getSessionToken:r,logger:u=console}){let l=qe(t);if(!l.ok)return u.warn?.(`[memory-sync] config invalid: ${l.error}`),{action:"error",reason:l.error};if(l.kind==="noop")return{action:"skipped",reason:"memorySync.remote not set"};if(l.kind==="byo")return s?.memoryRemoteAdd?s.memoryRemoteAdd(o,l.remote)?{action:"byo",remote:l.remote}:{action:"error",reason:"memoryRemoteAdd returned false (memory DB not initialized?)"}:{action:"error",reason:"@zibby/ui-memory not loaded"};if(l.kind==="hosted"){if(typeof r=="function"&&!r())return{action:"pending-login",reason:'memorySync.remote = "hosted" but the user is not logged in. Run `zibby login` then `zibby memory remote use --hosted`.'};if(typeof n!="function")return{action:"error",reason:"hostedSetup function not provided"};try{return await n({cwd:o,projectId:e}),{action:"hosted"}}catch(i){return{action:"error",reason:`hosted setup failed: ${i.message}`}}}return{action:"error",reason:`unhandled kind: ${l.kind}`}}var Ct,At,Je,Qe=K(()=>{Ct=[null,void 0,"","none","off",!1],At="hosted",Je=["aws://","gs://","https://","http://","file://"]});var be={};U(be,{clearSession:()=>co,default:()=>jt,getMem0ProxyUrl:()=>go,getProjects:()=>fo,getProxyUrl:()=>uo,getSessionToken:()=>we,getUserInfo:()=>io,isLoggedIn:()=>lo,loadConfig:()=>R,saveConfig:()=>Y,saveMem0ProxyUrl:()=>mo,saveProjects:()=>yo,saveProxyUrl:()=>po,saveSessionToken:()=>so,saveUserInfo:()=>ao});import{existsSync as eo,mkdirSync as It,readFileSync as _t,writeFileSync as Pt}from"fs";import{homedir as oo}from"os";import{join as de}from"path";function to(){return process.env.ZIBBY_CONFIG_DIR||de(oo(),".zibby")}function no(){return de(to(),"config.json")}function zt(){let o=to();eo(o)||It(o,{recursive:!0})}function R(){try{let o=no();if(eo(o)){let e=_t(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function Y(o){zt(),Pt(no(),JSON.stringify(o,null,2))}function we(){return R().sessionToken||null}function so(o){let e=R();e.sessionToken=o,Y(e)}function io(){return R().user||null}function ao(o){let e=R();e.user=o,Y(e)}function lo(){return we()!==null}function co(){let o=R();delete o.sessionToken,delete o.user,delete o.mem0ProxyUrl,Y(o)}function uo(){return R().proxyUrl||null}function po(o){let e=R();e.proxyUrl=o,Y(e)}function go(){return R().mem0ProxyUrl||null}function mo(o){let e=R();e.mem0ProxyUrl=o,Y(e)}function fo(){return R().projects||[]}function yo(o){let e=R();e.projects=o,Y(e)}var ro,Et,jt,ke=K(()=>{ro=de(oo(),".zibby"),Et=de(ro,"config.json");jt={loadConfig:R,saveConfig:Y,getSessionToken:we,saveSessionToken:so,getUserInfo:io,saveUserInfo:ao,isLoggedIn:lo,clearSession:co,getProxyUrl:uo,saveProxyUrl:po,getMem0ProxyUrl:go,saveMem0ProxyUrl:mo,getProjects:fo,saveProjects:yo,CONFIG_DIR:ro,CONFIG_FILE:Et}});var ho={};U(ho,{ENVIRONMENTS:()=>j,getAccountApiUrl:()=>Rt,getApiUrl:()=>Ot,getCurrentEnvironment:()=>Tt,getFrontendUrl:()=>Nt});function Ot(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";j[e]?o=j[e].apiUrl:o=j.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)`),j.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),j.prod.apiUrl}}function Rt(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let o=process.env.ZIBBY_ENV||"prod";return(j[o]||j.prod).accountApiUrl}function Tt(){let o=process.env.ZIBBY_ENV||"prod";return j[o]||j.prod}function Nt(){let o;if(process.env.ZIBBY_FRONTEND_URL)o=process.env.ZIBBY_FRONTEND_URL;else{let e=process.env.ZIBBY_ENV||"prod";j[e]?o=j[e].frontendUrl:o=j.prod.frontendUrl}try{let e=new URL(o);if(e.protocol!=="http:"&&e.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${e.protocol} (only http/https allowed)`),j.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let s=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],n=e.hostname;if(!s.some(u=>n===u||n.endsWith(`.${u}`))&&!n.includes("localhost")&&n!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${n}`),"https://studio.zibby.dev"}return o}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${o}`),j.local.frontendUrl}}var j,wo=K(()=>{j={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}}});var Se={};U(Se,{__testing:()=>Ft,buildDoltEnv:()=>Yt,clearConfig:()=>Ut,getActiveCredentials:()=>Ao,isHosted:()=>Lt,readConfig:()=>Ce,refreshCredentials:()=>Co,writeConfig:()=>Dt});import{readFileSync as bo,writeFileSync as xe,existsSync as $e,mkdirSync as ko,chmodSync as Bt}from"fs";import{join as ve}from"path";function oe(o){let e=ve(o,".zibby");return{dir:e,config:ve(e,Mt),creds:ve(e,Kt)}}function Ce(o){let{config:e}=oe(o);if(!$e(e))return null;try{let t=JSON.parse(bo(e,"utf-8"));return t.mode!=="hosted"?null:t}catch{return null}}function Lt(o){return!!Ce(o)}function Dt(o,e){let{dir:t,config:s}=oe(o);ko(t,{recursive:!0}),xe(s,JSON.stringify({mode:"hosted",projectId:e.projectId,bucket:e.bucket,prefix:e.prefix,doltUrl:e.doltUrl,configuredAt:new Date().toISOString()},null,2),"utf-8")}function Ut(o){let{config:e,creds:t}=oe(o);for(let s of[e,t])if($e(s))try{xe(s,"")}catch{}}function Ae(o){let{creds:e}=oe(o);if(!$e(e))return null;try{let t=JSON.parse(bo(e,"utf-8"));return!t?.accessKeyId||!t?.secretAccessKey||!t?.sessionToken?null:t}catch{return null}}function xo(o,e){let{dir:t,creds:s}=oe(o);ko(t,{recursive:!0}),xe(s,JSON.stringify(e,null,2),"utf-8");try{Bt(s,384)}catch{}}function $o(o){return o?.expiration?new Date(o.expiration).getTime()-Date.now()<vo:!0}async function Co({cwd:o,projectId:e,apiUrl:t,sessionToken:s,fetch:n=globalThis.fetch}){if(!e)throw new Error("refreshCredentials: projectId required");if(!t)throw new Error("refreshCredentials: apiUrl required");if(!s)throw new Error("refreshCredentials: sessionToken required (run `zibby login`)");let r=`${String(t).replace(/\/+$/,"")}/memory/sync-credentials`,u=await n(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({projectId:e})});if(!u.ok){let i=await u.text().catch(()=>"");throw new Error(`memory-sync credentials request failed (${u.status}): ${i||"no body"}`)}let l=await u.json();if(!l?.accessKeyId||!l?.secretAccessKey||!l?.sessionToken)throw new Error("memory-sync credentials response missing required fields");return xo(o,{accessKeyId:l.accessKeyId,secretAccessKey:l.secretAccessKey,sessionToken:l.sessionToken,expiration:l.expiration||null,refreshedAt:new Date().toISOString()}),Ae(o)}async function Ao({cwd:o,apiUrl:e,sessionToken:t,fetch:s}){let n=Ce(o);if(!n)return null;let r=Ae(o);return(!r||$o(r))&&(r=await Co({cwd:o,projectId:n.projectId,apiUrl:e,sessionToken:t,fetch:s})),r}async function Yt({cwd:o,apiUrl:e,sessionToken:t,fetch:s}){let n=await Ao({cwd:o,apiUrl:e,sessionToken:t,fetch:s});return n?{AWS_ACCESS_KEY_ID:n.accessKeyId,AWS_SECRET_ACCESS_KEY:n.secretAccessKey,AWS_SESSION_TOKEN:n.sessionToken,AWS_REGION:process.env.AWS_REGION||"ap-southeast-2"}:null}var Mt,Kt,vo,Ft,Ie=K(()=>{Mt="memory-sync.json",Kt="memory-sync-creds.json",vo=120*1e3;Ft={paths:oe,readCreds:Ae,writeCreds:xo,isExpiringSoon:$o,REFRESH_HEADROOM_MS:vo}});var So={};U(So,{memoryCompactCommand:()=>Gt,memoryCostCommand:()=>Vt,memoryInitCommand:()=>tn,memoryPullCommand:()=>Qt,memoryPushCommand:()=>on,memoryRemoteAddCommand:()=>Jt,memoryRemoteInfoCommand:()=>qt,memoryRemoteRemoveCommand:()=>Xt,memoryRemoteUseHostedCommand:()=>en,memoryResetCommand:()=>Zt,memoryStatsCommand:()=>Wt});import a from"chalk";async function T(){try{return await import("@zibby/ui-memory")}catch{return console.log(a.yellow(`
|
|
11
11
|
@zibby/ui-memory is not installed.
|
|
12
12
|
`)),console.log(a.white(Ht)),null}}async function Wt(){let o=await T();if(!o)return;let e=process.cwd(),t=o.getStats(e);if(!t.available){console.log(a.red(`
|
|
13
13
|
Dolt is not installed.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{readdir as wo,stat as ho}from"fs/promises";import{existsSync as P}from"fs";import{join as S}from"path";import r from"chalk";import ko from"dotenv";import{existsSync as Q}from"fs";import{join as oo}from"path";import{pathToFileURL as eo}from"url";async function C(o){let e=oo(o,".zibby.config.mjs");if(!Q(e))throw new Error(".zibby.config.mjs not found");try{let t=await import(eo(e).href);return t.default||t}catch(t){throw new Error(`Failed to load .zibby.config.mjs: ${t.message}`,{cause:t})}}var j={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://
|
|
1
|
+
import{readdir as wo,stat as ho}from"fs/promises";import{existsSync as P}from"fs";import{join as S}from"path";import r from"chalk";import ko from"dotenv";import{existsSync as Q}from"fs";import{join as oo}from"path";import{pathToFileURL as eo}from"url";async function C(o){let e=oo(o,".zibby.config.mjs");if(!Q(e))throw new Error(".zibby.config.mjs not found");try{let t=await import(eo(e).href);return t.default||t}catch(t){throw new Error(`Failed to load .zibby.config.mjs: ${t.message}`,{cause:t})}}var j={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function I(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";j[e]?o=j[e].apiUrl:o=j.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)`),j.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),j.prod.apiUrl}}import{existsSync as fo,readFileSync as go}from"fs";import{join as yo}from"path";import E from"chalk";import{confirm as mo}from"@inquirer/prompts";import s from"chalk";import _ from"ora";import{spawn as lo}from"child_process";import{existsSync as B,mkdirSync as no,readFileSync as to,writeFileSync as ro}from"fs";import{homedir as R}from"os";import{join as A}from"path";function L(){return process.env.ZIBBY_CONFIG_DIR||A(R(),".zibby")}function D(){return A(L(),"config.json")}var so=A(R(),".zibby"),Ao=A(so,"config.json");function io(){let o=L();B(o)||no(o,{recursive:!0})}function b(){try{let o=D();if(B(o)){let e=to(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function U(o){io(),ro(D(),JSON.stringify(o,null,2))}function O(){return b().sessionToken||null}function Y(o){let e=b();e.sessionToken=o,U(e)}function F(){return b().user||null}function Z(o){let e=b();e.user=o,U(e)}function K(o){let e=b();e.proxyUrl=o,U(e)}function M(o){let e=b();e.mem0ProxyUrl=o,U(e)}function J(o){let e=b();e.projects=o,U(e)}import{existsSync as zo,mkdirSync as Eo,readFileSync as No,writeFileSync as Co,unlinkSync as Bo}from"fs";import{resolve as Lo}from"path";import{homedir as Oo}from"os";function co(o){let e=process.platform;try{let t,l;return e==="darwin"?(t="open",l=[o]):e==="win32"?(t="cmd",l=["/c","start","",o]):(t="xdg-open",l=[o]),lo(t,l,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function ao(){let o=O(),e=F();return o&&e?{loggedIn:!0,user:e,token:o}:{loggedIn:!1}}async function V(){try{console.log(s.cyan(`
|
|
2
2
|
\u{1F510} Initiating login...
|
|
3
3
|
`));let o=ao();if(o.loggedIn){console.log(s.green("\u2705 Already logged in!")),console.log(s.gray(`User: ${o.user.email}`)),console.log(s.gray(`Name: ${o.user.name}
|
|
4
4
|
`));let{createInterface:e}=await import("readline"),t=e({input:process.stdin,output:process.stdout});return new Promise((l,u)=>{let i=()=>{t.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},c=()=>{console.log(s.yellow(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var $=Object.create;var R=Object.defineProperty;var Z=Object.getOwnPropertyDescriptor;var P=Object.getOwnPropertyNames;var W=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var F=(u,f)=>()=>(f||u((f={exports:{}}).exports,f),f.exports);var j=(u,f,y,w)=>{if(f&&typeof f=="object"||typeof f=="function")for(let g of P(f))!z.call(u,g)&&g!==y&&R(u,g,{get:()=>f[g],enumerable:!(w=Z(f,g))||w.enumerable});return u};var V=(u,f,y)=>(y=u!=null?$(W(u)):{},j(f||!u||!u.__esModule?R(y,"default",{value:u,enumerable:!0}):y,u));var B=F((M,D)=>{(function(f,y){typeof M=="object"&&typeof D=="object"?D.exports=y():typeof define=="function"&&define.amd?define("cronstrue",[],y):typeof M=="object"?M.cronstrue=y():f.cronstrue=y()})(globalThis,()=>(()=>{"use strict";var u={949(g,d,m){Object.defineProperty(d,"__esModule",{value:!0}),d.CronParser=void 0;var r=m(515),b=(function(){function v(t,e,o){e===void 0&&(e=!0),o===void 0&&(o=!1),this.expression=t,this.dayOfWeekStartIndexZero=e,this.monthStartIndexZero=o}return v.prototype.parse=function(){var t,e,o=(t=this.expression)!==null&&t!==void 0?t:"";if(o==="@reboot")return e=["@reboot","","","","","",""],e;if(o.startsWith("@")){var n=this.parseSpecial(this.expression);e=this.extractParts(n)}else e=this.extractParts(this.expression);return this.normalize(e),this.validate(e),e},v.prototype.parseSpecial=function(t){var e={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@midnight":"0 0 * * *","@hourly":"0 * * * *","@reboot":"@reboot"},o=e[t];if(!o)throw new Error("Unknown special expression.");return o},v.prototype.extractParts=function(t){if(!this.expression)throw new Error("cron expression is empty");for(var e=t.trim().split(/[ ]+/),o=0;o<e.length;o++)if(e[o].includes(",")){var n=e[o].split(",").map(function(a){return a.trim()}).filter(function(a){return a!==""}).map(function(a){return isNaN(Number(a))?a:Number(a)}).filter(function(a){return a!==null&&a!==""});n.length===0&&n.push("*"),n.sort(function(a,s){return a!==null&&s!==null?a-s:0}),e[o]=n.map(function(a){return a!==null?a.toString():""}).join(",")}if(e.length<5)throw new Error("Expression has only ".concat(e.length," part").concat(e.length==1?"":"s",". At least 5 parts are required."));if(e.length==5)e.unshift(""),e.push("");else if(e.length==6){var i=/\d{4}$/.test(e[5])||e[4]=="?"||e[2]=="?";i?e.unshift(""):e.push("")}else if(e.length>7)throw new Error("Expression has ".concat(e.length," parts; too many!"));return e},v.prototype.normalize=function(t){var e=this;if(t[3]=t[3].replace("?","*"),t[5]=t[5].replace("?","*"),t[2]=t[2].replace("?","*"),t[0].indexOf("0/")==0&&(t[0]=t[0].replace("0/","*/")),t[1].indexOf("0/")==0&&(t[1]=t[1].replace("0/","*/")),t[2].indexOf("0/")==0&&(t[2]=t[2].replace("0/","*/")),t[3].indexOf("1/")==0&&(t[3]=t[3].replace("1/","*/")),t[4].indexOf("1/")==0&&(t[4]=t[4].replace("1/","*/")),t[6].indexOf("1/")==0&&(t[6]=t[6].replace("1/","*/")),t[5]=t[5].replace(/(^\d)|([^#/\s]\d)/g,function(l){var O=l.replace(/\D/,""),h=O;return e.dayOfWeekStartIndexZero?O=="7"&&(h="0"):h=(parseInt(O)-1).toString(),l.replace(O,h)}),t[5]=="L"&&(t[5]="6"),t[3]=="?"&&(t[3]="*"),t[3].indexOf("W")>-1&&(t[3].indexOf(",")>-1||t[3].indexOf("-")>-1))throw new Error("The 'W' character can be specified only when the day-of-month is a single day, not a range or list of days.");var o={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};for(var n in o)t[5]=t[5].replace(new RegExp(n,"gi"),o[n].toString());t[4]=t[4].replace(/(^\d{1,2})|([^#/\s]\d{1,2})/g,function(l){var O=l.replace(/\D/,""),h=O;return e.monthStartIndexZero&&(h=(parseInt(O)+1).toString()),l.replace(O,h)});var i={JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12};for(var a in i)t[4]=t[4].replace(new RegExp(a,"gi"),i[a].toString());t[0]=="0"&&(t[0]=""),!/\*|\-|\,|\//.test(t[2])&&(/\*|\//.test(t[1])||/\*|\//.test(t[0]))&&(t[2]+="-".concat(t[2]));for(var s=0;s<t.length;s++)if(t[s].indexOf(",")!=-1&&(t[s]=t[s].split(",").filter(function(l){return l!==""}).join(",")||"*"),t[s]=="*/1"&&(t[s]="*"),t[s].indexOf("/")>-1&&!/^\*|\-|\,/.test(t[s])){var c=null;switch(s){case 4:c="12";break;case 5:c="6";break;case 6:c="9999";break;default:c=null;break}if(c!==null){var p=t[s].split("/");t[s]="".concat(p[0],"-").concat(c,"/").concat(p[1])}}},v.prototype.validate=function(t){var e="0-9,\\-*/";this.validateOnlyExpectedCharactersFound(t[0],e),this.validateOnlyExpectedCharactersFound(t[1],e),this.validateOnlyExpectedCharactersFound(t[2],e),this.validateOnlyExpectedCharactersFound(t[3],"0-9,\\-*/LW"),this.validateOnlyExpectedCharactersFound(t[4],e),this.validateOnlyExpectedCharactersFound(t[5],"0-9,\\-*/L#"),this.validateOnlyExpectedCharactersFound(t[6],e),this.validateAnyRanges(t)},v.prototype.validateAnyRanges=function(t){r.default.secondRange(t[0]),r.default.minuteRange(t[1]),r.default.hourRange(t[2]),r.default.dayOfMonthRange(t[3]),r.default.monthRange(t[4],this.monthStartIndexZero),r.default.dayOfWeekRange(t[5],this.dayOfWeekStartIndexZero)},v.prototype.validateOnlyExpectedCharactersFound=function(t,e){var o=t.match(new RegExp("[^".concat(e,"]+"),"gi"));if(o&&o.length)throw new Error("Expression contains invalid values: '".concat(o.toString(),"'"))},v})();d.CronParser=b},333(g,d,m){Object.defineProperty(d,"__esModule",{value:!0}),d.ExpressionDescriptor=void 0;var r=m(823),b=m(949),v=(function(){function t(e,o){if(this.expression=e,this.options=o,this.expressionParts=new Array(5),!this.options.locale&&t.defaultLocale&&(this.options.locale=t.defaultLocale),!t.locales[this.options.locale]){var n=Object.keys(t.locales)[0];console.warn("Locale '".concat(this.options.locale,"' could not be found; falling back to '").concat(n,"'.")),this.options.locale=n}this.i18n=t.locales[this.options.locale],o.use24HourTimeFormat===void 0&&(o.use24HourTimeFormat=this.i18n.use24HourTimeFormatByDefault())}return t.toString=function(e,o){var n=o===void 0?{}:o,i=n.throwExceptionOnParseError,a=i===void 0?!0:i,s=n.verbose,c=s===void 0?!1:s,p=n.dayOfWeekStartIndexZero,l=p===void 0?!0:p,O=n.monthStartIndexZero,h=O===void 0?!1:O,S=n.use24HourTimeFormat,_=n.trimHoursLeadingZero,U=_===void 0?!1:_,X=n.locale,E=X===void 0?null:X,x=n.logicalAndDayFields,A=x===void 0?!1:x,k={throwExceptionOnParseError:a,verbose:c,dayOfWeekStartIndexZero:l,monthStartIndexZero:h,use24HourTimeFormat:S,trimHoursLeadingZero:U,locale:E,logicalAndDayFields:A};k.tzOffset&&console.warn("'tzOffset' option has been deprecated and is no longer supported.");var Y=new t(e,k);return Y.getFullDescription()},t.initialize=function(e,o){o===void 0&&(o="en"),t.specialCharacters=["/","-",",","*"],t.defaultLocale=o,e.load(t.locales)},t.prototype.getFullDescription=function(){var e,o,n="";try{var i=new b.CronParser(this.expression,this.options.dayOfWeekStartIndexZero,this.options.monthStartIndexZero);if(this.expressionParts=i.parse(),this.expressionParts[0]==="@reboot")return((o=(e=this.i18n).atReboot)===null||o===void 0?void 0:o.call(e))||"Run once, at startup";var a=this.getTimeOfDayDescription(),s=this.getDayOfMonthDescription(),c=this.getMonthDescription(),p=this.getDayOfWeekDescription(),l=this.getYearDescription();n+=a+s+p+c+l,n=this.transformVerbosity(n,!!this.options.verbose),n=n.charAt(0).toLocaleUpperCase()+n.substr(1)}catch(O){if(!this.options.throwExceptionOnParseError)n=this.i18n.anErrorOccuredWhenGeneratingTheExpressionD();else throw"".concat(O)}return n},t.prototype.getTimeOfDayDescription=function(){var e=this.expressionParts[0],o=this.expressionParts[1],n=this.expressionParts[2],i="";if(!r.StringUtilities.containsAny(o,t.specialCharacters)&&!r.StringUtilities.containsAny(n,t.specialCharacters)&&!r.StringUtilities.containsAny(e,t.specialCharacters))i+=this.i18n.atSpace()+this.formatTime(n,o,e);else if(!e&&o.indexOf("-")>-1&&!(o.indexOf(",")>-1)&&!(o.indexOf("/")>-1)&&!r.StringUtilities.containsAny(n,t.specialCharacters)){var a=o.split("-");i+=r.StringUtilities.format(this.i18n.everyMinuteBetweenX0AndX1(),this.formatTime(n,a[0],""),this.formatTime(n,a[1],""))}else if(!e&&n.indexOf(",")>-1&&n.indexOf("-")==-1&&n.indexOf("/")==-1&&!r.StringUtilities.containsAny(o,t.specialCharacters)){var s=n.split(",");i+=this.i18n.at();for(var c=0;c<s.length;c++)i+=" ",i+=this.formatTime(s[c],o,""),c<s.length-2&&(i+=","),c==s.length-2&&(i+=this.i18n.spaceAnd())}else{var p=this.getSecondsDescription(),l=this.getMinutesDescription(),O=this.getHoursDescription();if(i+=p,i&&l&&(i+=", "),i+=l,l===O)return i;i&&O&&(i+=", "),i+=O}return i},t.prototype.getSecondsDescription=function(){var e=this,o=this.getSegmentDescription(this.expressionParts[0],this.i18n.everySecond(),function(n){return n},function(n){return r.StringUtilities.format(e.i18n.everyX0Seconds(n),n)},function(n){return e.i18n.secondsX0ThroughX1PastTheMinute()},function(n){return n=="0"?"":parseInt(n)<20?e.i18n.atX0SecondsPastTheMinute(n):e.i18n.atX0SecondsPastTheMinuteGt20()||e.i18n.atX0SecondsPastTheMinute(n)});return o},t.prototype.getMinutesDescription=function(){var e=this,o=this.expressionParts[0],n=this.expressionParts[2],i=this.getSegmentDescription(this.expressionParts[1],this.i18n.everyMinute(),function(a){return a},function(a){return r.StringUtilities.format(e.i18n.everyX0Minutes(a),a)},function(a){return e.i18n.minutesX0ThroughX1PastTheHour()},function(a){var s,c;try{return a=="0"&&n.indexOf("/")==-1&&o==""?e.i18n.everyHour():a=="0"?((c=(s=e.i18n).onTheHour)===null||c===void 0?void 0:c.call(s))||e.i18n.atX0MinutesPastTheHour(a):parseInt(a)<20?e.i18n.atX0MinutesPastTheHour(a):e.i18n.atX0MinutesPastTheHourGt20()||e.i18n.atX0MinutesPastTheHour(a)}catch{return e.i18n.atX0MinutesPastTheHour(a)}});return i},t.prototype.getHoursDescription=function(){var e=this,o=this.expressionParts[2],n=0,i=[];o.split("/")[0].split(",").forEach(function(c){var p=c.split("-");p.length===2&&i.push({value:p[1],index:n+1}),n+=p.length});var a=0,s=this.getSegmentDescription(o,this.i18n.everyHour(),function(c){var p=i.find(function(O){return O.value===c&&O.index===a}),l=p&&e.expressionParts[1]!=="0";return a++,l?e.formatTime(c,"59",""):e.formatTime(c,"0","")},function(c){return r.StringUtilities.format(e.i18n.everyX0Hours(c),c)},function(c){return e.i18n.betweenX0AndX1()},function(c){return e.i18n.atX0()});return s},t.prototype.getDayOfWeekDescription=function(){var e=this,o=this.i18n.daysOfTheWeek(),n=null;return this.expressionParts[5]=="*"?n="":n=this.getSegmentDescription(this.expressionParts[5],this.i18n.commaEveryDay(),function(i,a){var s=i;i.indexOf("#")>-1?s=i.substring(0,i.indexOf("#")):i.indexOf("L")>-1&&(s=s.replace("L",""));var c=parseInt(s),p=e.i18n.daysOfTheWeekInCase?e.i18n.daysOfTheWeekInCase(a)[c]:o[c];if(i.indexOf("#")>-1){var l=null,O=i.substring(i.indexOf("#")+1),h=i.substring(0,i.indexOf("#"));switch(O){case"1":l=e.i18n.first(h);break;case"2":l=e.i18n.second(h);break;case"3":l=e.i18n.third(h);break;case"4":l=e.i18n.fourth(h);break;case"5":l=e.i18n.fifth(h);break}p=l+" "+p}return p},function(i){return parseInt(i)==1?"":r.StringUtilities.format(e.i18n.commaEveryX0DaysOfTheWeek(i),i)},function(i){var a=i.substring(0,i.indexOf("-")),s=e.expressionParts[3]!="*";return s?e.i18n.commaAndX0ThroughX1(a):e.i18n.commaX0ThroughX1(a)},function(i){var a=null;if(i.indexOf("#")>-1){var s=i.substring(i.indexOf("#")+1),c=i.substring(0,i.indexOf("#"));a=e.i18n.commaOnThe(s,c).trim()+e.i18n.spaceX0OfTheMonth()}else if(i.indexOf("L")>-1)a=e.i18n.commaOnTheLastX0OfTheMonth(i.replace("L",""));else{var p=e.expressionParts[3]!="*";p?e.options.logicalAndDayFields?a=e.i18n.commaOnlyOnX0(i):a=e.i18n.commaAndOnX0():a=e.i18n.commaOnlyOnX0(i)}return a}),n},t.prototype.getMonthDescription=function(){var e=this,o=this.i18n.monthsOfTheYear(),n=this.getSegmentDescription(this.expressionParts[4],"",function(i,a){return a&&e.i18n.monthsOfTheYearInCase?e.i18n.monthsOfTheYearInCase(a)[parseInt(i)-1]:o[parseInt(i)-1]},function(i){return parseInt(i)==1?"":r.StringUtilities.format(e.i18n.commaEveryX0Months(i),i)},function(i){return e.i18n.commaMonthX0ThroughMonthX1()||e.i18n.commaX0ThroughX1()},function(i){return e.i18n.commaOnlyInMonthX0?e.i18n.commaOnlyInMonthX0():e.i18n.commaOnlyInX0()});return n},t.prototype.getDayOfMonthDescription=function(){var e=this,o=null,n=this.expressionParts[3];switch(n){case"L":o=this.i18n.commaOnTheLastDayOfTheMonth();break;case"WL":case"LW":o=this.i18n.commaOnTheLastWeekdayOfTheMonth();break;default:var i=n.match(/(\d{1,2}W)|(W\d{1,2})/);if(i){var a=parseInt(i[0].replace("W","")),s=a==1?this.i18n.firstWeekday():r.StringUtilities.format(this.i18n.weekdayNearestDayX0(),a.toString());o=r.StringUtilities.format(this.i18n.commaOnTheX0OfTheMonth(),s);break}else{var c=n.match(/L-(\d{1,2})/);if(c){var p=c[1];o=r.StringUtilities.format(this.i18n.commaDaysBeforeTheLastDayOfTheMonth(p),p);break}else{if(n=="*"&&this.expressionParts[5]!="*")return"";o=this.getSegmentDescription(n,this.i18n.commaEveryDay(),function(l){return l=="L"?e.i18n.lastDay():e.i18n.dayX0?r.StringUtilities.format(e.i18n.dayX0(),l):l},function(l){return l=="1"?e.i18n.commaEveryDay():e.i18n.commaEveryX0Days(l)},function(l){return e.i18n.commaBetweenDayX0AndX1OfTheMonth(l)},function(l){return e.i18n.commaOnDayX0OfTheMonth(l)})}break}}return o},t.prototype.getYearDescription=function(){var e=this,o=this.getSegmentDescription(this.expressionParts[6],"",function(n){return/^\d+$/.test(n)?new Date(parseInt(n),1).getFullYear().toString():n},function(n){return r.StringUtilities.format(e.i18n.commaEveryX0Years(n),n)},function(n){return e.i18n.commaYearX0ThroughYearX1()||e.i18n.commaX0ThroughX1()},function(n){return e.i18n.commaOnlyInYearX0?e.i18n.commaOnlyInYearX0():e.i18n.commaOnlyInX0()});return o},t.prototype.getSegmentDescription=function(e,o,n,i,a,s){var c=null,p=e.indexOf("/")>-1,l=e.indexOf("-")>-1,O=e.indexOf(",")>-1;if(!e)c="";else if(e==="*")c=o;else if(!p&&!l&&!O)c=r.StringUtilities.format(s(e),n(e));else if(O){for(var h=e.split(","),S="",_=0;_<h.length;_++)if(_>0&&h.length>2&&(S+=",",_<h.length-1&&(S+=" ")),_>0&&h.length>1&&(_==h.length-1||h.length==2)&&(S+="".concat(this.i18n.spaceAnd()," ")),h[_].indexOf("/")>-1||h[_].indexOf("-")>-1){var U=h[_].indexOf("-")>-1&&h[_].indexOf("/")==-1,X=this.getSegmentDescription(h[_],o,n,i,U?this.i18n.commaX0ThroughX1:a,s);U&&(X=X.replace(", ","")),S+=X}else if(!p)S+=n(h[_]);else{var E=this.getSegmentDescription(h[_],o,n,i,a,s);E&&E.startsWith(", ")&&(E=E.substring(2)),S+=E}p?c=S:c=r.StringUtilities.format(s(e),S)}else if(p){var h=e.split("/");if(c=r.StringUtilities.format(i(h[1]),h[1]),h[0].indexOf("-")>-1){var x=this.generateRangeSegmentDescription(h[0],a,n);x.indexOf(", ")!=0&&(c+=", "),c+=x}else if(h[0].indexOf("*")==-1){var A=r.StringUtilities.format(s(h[0]),n(h[0]));A=A.replace(", ",""),c+=r.StringUtilities.format(this.i18n.commaStartingX0(),A)}}else l&&(c=this.generateRangeSegmentDescription(e,a,n));return c},t.prototype.generateRangeSegmentDescription=function(e,o,n){var i="",a=e.split("-"),s=n(a[0],1),c=n(a[1],2),p=o(e);return i+=r.StringUtilities.format(p,s,c),i},t.prototype.formatTime=function(e,o,n){var i=0,a=0,s=parseInt(e)+i,c=parseInt(o)+a;c>=60?(c-=60,s+=1):c<0&&(c+=60,s-=1),s>=24?s=s-24:s<0&&(s=24+s);var p="",l=!1;this.options.use24HourTimeFormat||(l=!!(this.i18n.setPeriodBeforeTime&&this.i18n.setPeriodBeforeTime()),p=l?"".concat(this.getPeriod(s)," "):" ".concat(this.getPeriod(s)),s>12&&(s-=12),s===0&&(s=12));var O="";n&&(O=":".concat(("00"+n).substring(n.length)));var h=s.toString(),S=("00"+h).substring(h.length),_=c.toString(),U=("00"+_).substring(_.length),X=this.options.trimHoursLeadingZero?h:S;return"".concat(l?p:"").concat(X,":").concat(U).concat(O).concat(l?"":p)},t.prototype.transformVerbosity=function(e,o){if(!o&&(e=e.replace(new RegExp(", ".concat(this.i18n.everyMinute()),"g"),""),e=e.replace(new RegExp(", ".concat(this.i18n.everyHour()),"g"),""),e=e.replace(new RegExp(this.i18n.commaEveryDay(),"g"),""),e=e.replace(/\, ?$/,""),this.i18n.conciseVerbosityReplacements))for(var n=0,i=Object.entries(this.i18n.conciseVerbosityReplacements());n<i.length;n++){var a=i[n],s=a[0],c=a[1];e=e.replace(new RegExp(s,"g"),c)}return e},t.prototype.getPeriod=function(e){return e>=12?this.i18n.pm&&this.i18n.pm()||"PM":this.i18n.am&&this.i18n.am()||"AM"},t.locales={},t})();d.ExpressionDescriptor=v},747(g,d,m){Object.defineProperty(d,"__esModule",{value:!0}),d.enLocaleLoader=void 0;var r=m(486),b=(function(){function v(){}return v.prototype.load=function(t){t.en=new r.en},v})();d.enLocaleLoader=b},486(g,d){Object.defineProperty(d,"__esModule",{value:!0}),d.en=void 0;var m=(function(){function r(){}return r.prototype.atX0SecondsPastTheMinuteGt20=function(){return null},r.prototype.atX0MinutesPastTheHourGt20=function(){return null},r.prototype.commaMonthX0ThroughMonthX1=function(){return null},r.prototype.commaYearX0ThroughYearX1=function(){return null},r.prototype.use24HourTimeFormatByDefault=function(){return!1},r.prototype.anErrorOccuredWhenGeneratingTheExpressionD=function(){return"An error occurred when generating the expression description. Check the cron expression syntax."},r.prototype.everyMinute=function(){return"every minute"},r.prototype.everyHour=function(){return"every hour"},r.prototype.atSpace=function(){return"At "},r.prototype.everyMinuteBetweenX0AndX1=function(){return"Every minute between %s and %s"},r.prototype.at=function(){return"At"},r.prototype.spaceAnd=function(){return" and"},r.prototype.everySecond=function(){return"every second"},r.prototype.everyX0Seconds=function(){return"every %s seconds"},r.prototype.secondsX0ThroughX1PastTheMinute=function(){return"seconds %s through %s past the minute"},r.prototype.atX0SecondsPastTheMinute=function(){return"at %s seconds past the minute"},r.prototype.everyX0Minutes=function(){return"every %s minutes"},r.prototype.minutesX0ThroughX1PastTheHour=function(){return"minutes %s through %s past the hour"},r.prototype.atX0MinutesPastTheHour=function(){return"at %s minutes past the hour"},r.prototype.everyX0Hours=function(){return"every %s hours"},r.prototype.betweenX0AndX1=function(){return"between %s and %s"},r.prototype.atX0=function(){return"at %s"},r.prototype.commaEveryDay=function(){return", every day"},r.prototype.commaEveryX0DaysOfTheWeek=function(){return", every %s days of the week"},r.prototype.commaX0ThroughX1=function(){return", %s through %s"},r.prototype.commaAndX0ThroughX1=function(){return", %s through %s"},r.prototype.first=function(){return"first"},r.prototype.second=function(){return"second"},r.prototype.third=function(){return"third"},r.prototype.fourth=function(){return"fourth"},r.prototype.fifth=function(){return"fifth"},r.prototype.commaOnThe=function(){return", on the "},r.prototype.spaceX0OfTheMonth=function(){return" %s of the month"},r.prototype.lastDay=function(){return"the last day"},r.prototype.commaOnTheLastX0OfTheMonth=function(){return", on the last %s of the month"},r.prototype.commaOnlyOnX0=function(){return", only on %s"},r.prototype.commaAndOnX0=function(){return", and on %s"},r.prototype.commaEveryX0Months=function(){return", every %s months"},r.prototype.commaOnlyInX0=function(){return", only in %s"},r.prototype.commaOnTheLastDayOfTheMonth=function(){return", on the last day of the month"},r.prototype.commaOnTheLastWeekdayOfTheMonth=function(){return", on the last weekday of the month"},r.prototype.commaDaysBeforeTheLastDayOfTheMonth=function(){return", %s days before the last day of the month"},r.prototype.firstWeekday=function(){return"first weekday"},r.prototype.weekdayNearestDayX0=function(){return"weekday nearest day %s"},r.prototype.commaOnTheX0OfTheMonth=function(){return", on the %s of the month"},r.prototype.commaEveryX0Days=function(){return", every %s days in a month"},r.prototype.commaBetweenDayX0AndX1OfTheMonth=function(){return", between day %s and %s of the month"},r.prototype.commaOnDayX0OfTheMonth=function(){return", on day %s of the month"},r.prototype.commaEveryHour=function(){return", every hour"},r.prototype.commaEveryX0Years=function(){return", every %s years"},r.prototype.commaStartingX0=function(){return", starting %s"},r.prototype.daysOfTheWeek=function(){return["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},r.prototype.monthsOfTheYear=function(){return["January","February","March","April","May","June","July","August","September","October","November","December"]},r.prototype.atReboot=function(){return"Run once, at startup"},r.prototype.onTheHour=function(){return"on the hour"},r})();d.en=m},515(g,d){Object.defineProperty(d,"__esModule",{value:!0});function m(b,v){if(!b)throw new Error(v)}var r=(function(){function b(){}return b.secondRange=function(v){for(var t=v.split(","),e=0;e<t.length;e++)if(!isNaN(parseInt(t[e],10))){var o=parseInt(t[e],10);m(o>=0&&o<=59,"seconds part must be >= 0 and <= 59")}},b.minuteRange=function(v){for(var t=v.split(","),e=0;e<t.length;e++)if(!isNaN(parseInt(t[e],10))){var o=parseInt(t[e],10);m(o>=0&&o<=59,"minutes part must be >= 0 and <= 59")}},b.hourRange=function(v){for(var t=v.split(","),e=0;e<t.length;e++)if(!isNaN(parseInt(t[e],10))){var o=parseInt(t[e],10);m(o>=0&&o<=23,"hours part must be >= 0 and <= 23")}},b.dayOfMonthRange=function(v){for(var t=v.split(","),e=0;e<t.length;e++)if(!isNaN(parseInt(t[e],10))){var o=parseInt(t[e],10);m(o>=1&&o<=31,"DOM part must be >= 1 and <= 31")}},b.monthRange=function(v,t){for(var e=v.split(","),o=0;o<e.length;o++)if(!isNaN(parseInt(e[o],10))){var n=parseInt(e[o],10);m(n>=1&&n<=12,t?"month part must be >= 0 and <= 11":"month part must be >= 1 and <= 12")}},b.dayOfWeekRange=function(v,t){for(var e=v.split(","),o=0;o<e.length;o++)if(!isNaN(parseInt(e[o],10))){var n=parseInt(e[o],10);m(n>=0&&n<=6,t?"DOW part must be >= 0 and <= 6":"DOW part must be >= 1 and <= 7")}},b})();d.default=r},823(g,d){Object.defineProperty(d,"__esModule",{value:!0}),d.StringUtilities=void 0;var m=(function(){function r(){}return r.format=function(b){for(var v=[],t=1;t<arguments.length;t++)v[t-1]=arguments[t];return b.replace(/%s/g,function(e){for(var o=[],n=1;n<arguments.length;n++)o[n-1]=arguments[n];return v.shift()})},r.containsAny=function(b,v){return v.some(function(t){return b.indexOf(t)>-1})},r})();d.StringUtilities=m}},f={};function y(g){var d=f[g];if(d!==void 0)return d.exports;var m=f[g]={exports:{}};return u[g](m,m.exports,y),m.exports}var w={};return(()=>{var g=w;Object.defineProperty(g,"__esModule",{value:!0}),g.toString=void 0;var d=y(333),m=y(747);d.ExpressionDescriptor.initialize(new m.enLocaleLoader),g.default=d.ExpressionDescriptor;var r=d.ExpressionDescriptor.toString;g.toString=r})(),w})())});var H=V(B(),1);import T from"chalk";import{readFileSync as J,existsSync as G}from"fs";import{homedir as K}from"os";import{join as q}from"path";var I={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 N(){let u;if(process.env.ZIBBY_API_URL)u=process.env.ZIBBY_API_URL;else{let f=process.env.ZIBBY_ENV||"prod";I[f]?u=I[f].apiUrl:u=I.prod.apiUrl}try{let f=new URL(u);return f.protocol!=="http:"&&f.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${f.protocol} (only http/https allowed)`),I.prod.apiUrl):u}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${u}`),I.prod.apiUrl}}function Q(u){if(!u)return null;try{return H.default.toString(u,{use24HourTimeFormat:!1,verbose:!1})}catch{return null}}function ee(u){if(u)return u;let f=q(K(),".zibby","config.json");if(G(f))try{let y=JSON.parse(J(f,"utf-8"));if(y.sessionToken)return y.sessionToken}catch{}if(process.env.ZIBBY_API_KEY)return process.env.ZIBBY_API_KEY;console.error(T.red(`
|
|
1
|
+
var $=Object.create;var R=Object.defineProperty;var Z=Object.getOwnPropertyDescriptor;var P=Object.getOwnPropertyNames;var W=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var F=(u,f)=>()=>(f||u((f={exports:{}}).exports,f),f.exports);var j=(u,f,y,w)=>{if(f&&typeof f=="object"||typeof f=="function")for(let g of P(f))!z.call(u,g)&&g!==y&&R(u,g,{get:()=>f[g],enumerable:!(w=Z(f,g))||w.enumerable});return u};var V=(u,f,y)=>(y=u!=null?$(W(u)):{},j(f||!u||!u.__esModule?R(y,"default",{value:u,enumerable:!0}):y,u));var B=F((M,D)=>{(function(f,y){typeof M=="object"&&typeof D=="object"?D.exports=y():typeof define=="function"&&define.amd?define("cronstrue",[],y):typeof M=="object"?M.cronstrue=y():f.cronstrue=y()})(globalThis,()=>(()=>{"use strict";var u={949(g,d,m){Object.defineProperty(d,"__esModule",{value:!0}),d.CronParser=void 0;var r=m(515),b=(function(){function v(t,e,o){e===void 0&&(e=!0),o===void 0&&(o=!1),this.expression=t,this.dayOfWeekStartIndexZero=e,this.monthStartIndexZero=o}return v.prototype.parse=function(){var t,e,o=(t=this.expression)!==null&&t!==void 0?t:"";if(o==="@reboot")return e=["@reboot","","","","","",""],e;if(o.startsWith("@")){var n=this.parseSpecial(this.expression);e=this.extractParts(n)}else e=this.extractParts(this.expression);return this.normalize(e),this.validate(e),e},v.prototype.parseSpecial=function(t){var e={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@midnight":"0 0 * * *","@hourly":"0 * * * *","@reboot":"@reboot"},o=e[t];if(!o)throw new Error("Unknown special expression.");return o},v.prototype.extractParts=function(t){if(!this.expression)throw new Error("cron expression is empty");for(var e=t.trim().split(/[ ]+/),o=0;o<e.length;o++)if(e[o].includes(",")){var n=e[o].split(",").map(function(a){return a.trim()}).filter(function(a){return a!==""}).map(function(a){return isNaN(Number(a))?a:Number(a)}).filter(function(a){return a!==null&&a!==""});n.length===0&&n.push("*"),n.sort(function(a,s){return a!==null&&s!==null?a-s:0}),e[o]=n.map(function(a){return a!==null?a.toString():""}).join(",")}if(e.length<5)throw new Error("Expression has only ".concat(e.length," part").concat(e.length==1?"":"s",". At least 5 parts are required."));if(e.length==5)e.unshift(""),e.push("");else if(e.length==6){var i=/\d{4}$/.test(e[5])||e[4]=="?"||e[2]=="?";i?e.unshift(""):e.push("")}else if(e.length>7)throw new Error("Expression has ".concat(e.length," parts; too many!"));return e},v.prototype.normalize=function(t){var e=this;if(t[3]=t[3].replace("?","*"),t[5]=t[5].replace("?","*"),t[2]=t[2].replace("?","*"),t[0].indexOf("0/")==0&&(t[0]=t[0].replace("0/","*/")),t[1].indexOf("0/")==0&&(t[1]=t[1].replace("0/","*/")),t[2].indexOf("0/")==0&&(t[2]=t[2].replace("0/","*/")),t[3].indexOf("1/")==0&&(t[3]=t[3].replace("1/","*/")),t[4].indexOf("1/")==0&&(t[4]=t[4].replace("1/","*/")),t[6].indexOf("1/")==0&&(t[6]=t[6].replace("1/","*/")),t[5]=t[5].replace(/(^\d)|([^#/\s]\d)/g,function(l){var O=l.replace(/\D/,""),h=O;return e.dayOfWeekStartIndexZero?O=="7"&&(h="0"):h=(parseInt(O)-1).toString(),l.replace(O,h)}),t[5]=="L"&&(t[5]="6"),t[3]=="?"&&(t[3]="*"),t[3].indexOf("W")>-1&&(t[3].indexOf(",")>-1||t[3].indexOf("-")>-1))throw new Error("The 'W' character can be specified only when the day-of-month is a single day, not a range or list of days.");var o={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};for(var n in o)t[5]=t[5].replace(new RegExp(n,"gi"),o[n].toString());t[4]=t[4].replace(/(^\d{1,2})|([^#/\s]\d{1,2})/g,function(l){var O=l.replace(/\D/,""),h=O;return e.monthStartIndexZero&&(h=(parseInt(O)+1).toString()),l.replace(O,h)});var i={JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12};for(var a in i)t[4]=t[4].replace(new RegExp(a,"gi"),i[a].toString());t[0]=="0"&&(t[0]=""),!/\*|\-|\,|\//.test(t[2])&&(/\*|\//.test(t[1])||/\*|\//.test(t[0]))&&(t[2]+="-".concat(t[2]));for(var s=0;s<t.length;s++)if(t[s].indexOf(",")!=-1&&(t[s]=t[s].split(",").filter(function(l){return l!==""}).join(",")||"*"),t[s]=="*/1"&&(t[s]="*"),t[s].indexOf("/")>-1&&!/^\*|\-|\,/.test(t[s])){var c=null;switch(s){case 4:c="12";break;case 5:c="6";break;case 6:c="9999";break;default:c=null;break}if(c!==null){var p=t[s].split("/");t[s]="".concat(p[0],"-").concat(c,"/").concat(p[1])}}},v.prototype.validate=function(t){var e="0-9,\\-*/";this.validateOnlyExpectedCharactersFound(t[0],e),this.validateOnlyExpectedCharactersFound(t[1],e),this.validateOnlyExpectedCharactersFound(t[2],e),this.validateOnlyExpectedCharactersFound(t[3],"0-9,\\-*/LW"),this.validateOnlyExpectedCharactersFound(t[4],e),this.validateOnlyExpectedCharactersFound(t[5],"0-9,\\-*/L#"),this.validateOnlyExpectedCharactersFound(t[6],e),this.validateAnyRanges(t)},v.prototype.validateAnyRanges=function(t){r.default.secondRange(t[0]),r.default.minuteRange(t[1]),r.default.hourRange(t[2]),r.default.dayOfMonthRange(t[3]),r.default.monthRange(t[4],this.monthStartIndexZero),r.default.dayOfWeekRange(t[5],this.dayOfWeekStartIndexZero)},v.prototype.validateOnlyExpectedCharactersFound=function(t,e){var o=t.match(new RegExp("[^".concat(e,"]+"),"gi"));if(o&&o.length)throw new Error("Expression contains invalid values: '".concat(o.toString(),"'"))},v})();d.CronParser=b},333(g,d,m){Object.defineProperty(d,"__esModule",{value:!0}),d.ExpressionDescriptor=void 0;var r=m(823),b=m(949),v=(function(){function t(e,o){if(this.expression=e,this.options=o,this.expressionParts=new Array(5),!this.options.locale&&t.defaultLocale&&(this.options.locale=t.defaultLocale),!t.locales[this.options.locale]){var n=Object.keys(t.locales)[0];console.warn("Locale '".concat(this.options.locale,"' could not be found; falling back to '").concat(n,"'.")),this.options.locale=n}this.i18n=t.locales[this.options.locale],o.use24HourTimeFormat===void 0&&(o.use24HourTimeFormat=this.i18n.use24HourTimeFormatByDefault())}return t.toString=function(e,o){var n=o===void 0?{}:o,i=n.throwExceptionOnParseError,a=i===void 0?!0:i,s=n.verbose,c=s===void 0?!1:s,p=n.dayOfWeekStartIndexZero,l=p===void 0?!0:p,O=n.monthStartIndexZero,h=O===void 0?!1:O,S=n.use24HourTimeFormat,_=n.trimHoursLeadingZero,U=_===void 0?!1:_,X=n.locale,E=X===void 0?null:X,x=n.logicalAndDayFields,A=x===void 0?!1:x,k={throwExceptionOnParseError:a,verbose:c,dayOfWeekStartIndexZero:l,monthStartIndexZero:h,use24HourTimeFormat:S,trimHoursLeadingZero:U,locale:E,logicalAndDayFields:A};k.tzOffset&&console.warn("'tzOffset' option has been deprecated and is no longer supported.");var Y=new t(e,k);return Y.getFullDescription()},t.initialize=function(e,o){o===void 0&&(o="en"),t.specialCharacters=["/","-",",","*"],t.defaultLocale=o,e.load(t.locales)},t.prototype.getFullDescription=function(){var e,o,n="";try{var i=new b.CronParser(this.expression,this.options.dayOfWeekStartIndexZero,this.options.monthStartIndexZero);if(this.expressionParts=i.parse(),this.expressionParts[0]==="@reboot")return((o=(e=this.i18n).atReboot)===null||o===void 0?void 0:o.call(e))||"Run once, at startup";var a=this.getTimeOfDayDescription(),s=this.getDayOfMonthDescription(),c=this.getMonthDescription(),p=this.getDayOfWeekDescription(),l=this.getYearDescription();n+=a+s+p+c+l,n=this.transformVerbosity(n,!!this.options.verbose),n=n.charAt(0).toLocaleUpperCase()+n.substr(1)}catch(O){if(!this.options.throwExceptionOnParseError)n=this.i18n.anErrorOccuredWhenGeneratingTheExpressionD();else throw"".concat(O)}return n},t.prototype.getTimeOfDayDescription=function(){var e=this.expressionParts[0],o=this.expressionParts[1],n=this.expressionParts[2],i="";if(!r.StringUtilities.containsAny(o,t.specialCharacters)&&!r.StringUtilities.containsAny(n,t.specialCharacters)&&!r.StringUtilities.containsAny(e,t.specialCharacters))i+=this.i18n.atSpace()+this.formatTime(n,o,e);else if(!e&&o.indexOf("-")>-1&&!(o.indexOf(",")>-1)&&!(o.indexOf("/")>-1)&&!r.StringUtilities.containsAny(n,t.specialCharacters)){var a=o.split("-");i+=r.StringUtilities.format(this.i18n.everyMinuteBetweenX0AndX1(),this.formatTime(n,a[0],""),this.formatTime(n,a[1],""))}else if(!e&&n.indexOf(",")>-1&&n.indexOf("-")==-1&&n.indexOf("/")==-1&&!r.StringUtilities.containsAny(o,t.specialCharacters)){var s=n.split(",");i+=this.i18n.at();for(var c=0;c<s.length;c++)i+=" ",i+=this.formatTime(s[c],o,""),c<s.length-2&&(i+=","),c==s.length-2&&(i+=this.i18n.spaceAnd())}else{var p=this.getSecondsDescription(),l=this.getMinutesDescription(),O=this.getHoursDescription();if(i+=p,i&&l&&(i+=", "),i+=l,l===O)return i;i&&O&&(i+=", "),i+=O}return i},t.prototype.getSecondsDescription=function(){var e=this,o=this.getSegmentDescription(this.expressionParts[0],this.i18n.everySecond(),function(n){return n},function(n){return r.StringUtilities.format(e.i18n.everyX0Seconds(n),n)},function(n){return e.i18n.secondsX0ThroughX1PastTheMinute()},function(n){return n=="0"?"":parseInt(n)<20?e.i18n.atX0SecondsPastTheMinute(n):e.i18n.atX0SecondsPastTheMinuteGt20()||e.i18n.atX0SecondsPastTheMinute(n)});return o},t.prototype.getMinutesDescription=function(){var e=this,o=this.expressionParts[0],n=this.expressionParts[2],i=this.getSegmentDescription(this.expressionParts[1],this.i18n.everyMinute(),function(a){return a},function(a){return r.StringUtilities.format(e.i18n.everyX0Minutes(a),a)},function(a){return e.i18n.minutesX0ThroughX1PastTheHour()},function(a){var s,c;try{return a=="0"&&n.indexOf("/")==-1&&o==""?e.i18n.everyHour():a=="0"?((c=(s=e.i18n).onTheHour)===null||c===void 0?void 0:c.call(s))||e.i18n.atX0MinutesPastTheHour(a):parseInt(a)<20?e.i18n.atX0MinutesPastTheHour(a):e.i18n.atX0MinutesPastTheHourGt20()||e.i18n.atX0MinutesPastTheHour(a)}catch{return e.i18n.atX0MinutesPastTheHour(a)}});return i},t.prototype.getHoursDescription=function(){var e=this,o=this.expressionParts[2],n=0,i=[];o.split("/")[0].split(",").forEach(function(c){var p=c.split("-");p.length===2&&i.push({value:p[1],index:n+1}),n+=p.length});var a=0,s=this.getSegmentDescription(o,this.i18n.everyHour(),function(c){var p=i.find(function(O){return O.value===c&&O.index===a}),l=p&&e.expressionParts[1]!=="0";return a++,l?e.formatTime(c,"59",""):e.formatTime(c,"0","")},function(c){return r.StringUtilities.format(e.i18n.everyX0Hours(c),c)},function(c){return e.i18n.betweenX0AndX1()},function(c){return e.i18n.atX0()});return s},t.prototype.getDayOfWeekDescription=function(){var e=this,o=this.i18n.daysOfTheWeek(),n=null;return this.expressionParts[5]=="*"?n="":n=this.getSegmentDescription(this.expressionParts[5],this.i18n.commaEveryDay(),function(i,a){var s=i;i.indexOf("#")>-1?s=i.substring(0,i.indexOf("#")):i.indexOf("L")>-1&&(s=s.replace("L",""));var c=parseInt(s),p=e.i18n.daysOfTheWeekInCase?e.i18n.daysOfTheWeekInCase(a)[c]:o[c];if(i.indexOf("#")>-1){var l=null,O=i.substring(i.indexOf("#")+1),h=i.substring(0,i.indexOf("#"));switch(O){case"1":l=e.i18n.first(h);break;case"2":l=e.i18n.second(h);break;case"3":l=e.i18n.third(h);break;case"4":l=e.i18n.fourth(h);break;case"5":l=e.i18n.fifth(h);break}p=l+" "+p}return p},function(i){return parseInt(i)==1?"":r.StringUtilities.format(e.i18n.commaEveryX0DaysOfTheWeek(i),i)},function(i){var a=i.substring(0,i.indexOf("-")),s=e.expressionParts[3]!="*";return s?e.i18n.commaAndX0ThroughX1(a):e.i18n.commaX0ThroughX1(a)},function(i){var a=null;if(i.indexOf("#")>-1){var s=i.substring(i.indexOf("#")+1),c=i.substring(0,i.indexOf("#"));a=e.i18n.commaOnThe(s,c).trim()+e.i18n.spaceX0OfTheMonth()}else if(i.indexOf("L")>-1)a=e.i18n.commaOnTheLastX0OfTheMonth(i.replace("L",""));else{var p=e.expressionParts[3]!="*";p?e.options.logicalAndDayFields?a=e.i18n.commaOnlyOnX0(i):a=e.i18n.commaAndOnX0():a=e.i18n.commaOnlyOnX0(i)}return a}),n},t.prototype.getMonthDescription=function(){var e=this,o=this.i18n.monthsOfTheYear(),n=this.getSegmentDescription(this.expressionParts[4],"",function(i,a){return a&&e.i18n.monthsOfTheYearInCase?e.i18n.monthsOfTheYearInCase(a)[parseInt(i)-1]:o[parseInt(i)-1]},function(i){return parseInt(i)==1?"":r.StringUtilities.format(e.i18n.commaEveryX0Months(i),i)},function(i){return e.i18n.commaMonthX0ThroughMonthX1()||e.i18n.commaX0ThroughX1()},function(i){return e.i18n.commaOnlyInMonthX0?e.i18n.commaOnlyInMonthX0():e.i18n.commaOnlyInX0()});return n},t.prototype.getDayOfMonthDescription=function(){var e=this,o=null,n=this.expressionParts[3];switch(n){case"L":o=this.i18n.commaOnTheLastDayOfTheMonth();break;case"WL":case"LW":o=this.i18n.commaOnTheLastWeekdayOfTheMonth();break;default:var i=n.match(/(\d{1,2}W)|(W\d{1,2})/);if(i){var a=parseInt(i[0].replace("W","")),s=a==1?this.i18n.firstWeekday():r.StringUtilities.format(this.i18n.weekdayNearestDayX0(),a.toString());o=r.StringUtilities.format(this.i18n.commaOnTheX0OfTheMonth(),s);break}else{var c=n.match(/L-(\d{1,2})/);if(c){var p=c[1];o=r.StringUtilities.format(this.i18n.commaDaysBeforeTheLastDayOfTheMonth(p),p);break}else{if(n=="*"&&this.expressionParts[5]!="*")return"";o=this.getSegmentDescription(n,this.i18n.commaEveryDay(),function(l){return l=="L"?e.i18n.lastDay():e.i18n.dayX0?r.StringUtilities.format(e.i18n.dayX0(),l):l},function(l){return l=="1"?e.i18n.commaEveryDay():e.i18n.commaEveryX0Days(l)},function(l){return e.i18n.commaBetweenDayX0AndX1OfTheMonth(l)},function(l){return e.i18n.commaOnDayX0OfTheMonth(l)})}break}}return o},t.prototype.getYearDescription=function(){var e=this,o=this.getSegmentDescription(this.expressionParts[6],"",function(n){return/^\d+$/.test(n)?new Date(parseInt(n),1).getFullYear().toString():n},function(n){return r.StringUtilities.format(e.i18n.commaEveryX0Years(n),n)},function(n){return e.i18n.commaYearX0ThroughYearX1()||e.i18n.commaX0ThroughX1()},function(n){return e.i18n.commaOnlyInYearX0?e.i18n.commaOnlyInYearX0():e.i18n.commaOnlyInX0()});return o},t.prototype.getSegmentDescription=function(e,o,n,i,a,s){var c=null,p=e.indexOf("/")>-1,l=e.indexOf("-")>-1,O=e.indexOf(",")>-1;if(!e)c="";else if(e==="*")c=o;else if(!p&&!l&&!O)c=r.StringUtilities.format(s(e),n(e));else if(O){for(var h=e.split(","),S="",_=0;_<h.length;_++)if(_>0&&h.length>2&&(S+=",",_<h.length-1&&(S+=" ")),_>0&&h.length>1&&(_==h.length-1||h.length==2)&&(S+="".concat(this.i18n.spaceAnd()," ")),h[_].indexOf("/")>-1||h[_].indexOf("-")>-1){var U=h[_].indexOf("-")>-1&&h[_].indexOf("/")==-1,X=this.getSegmentDescription(h[_],o,n,i,U?this.i18n.commaX0ThroughX1:a,s);U&&(X=X.replace(", ","")),S+=X}else if(!p)S+=n(h[_]);else{var E=this.getSegmentDescription(h[_],o,n,i,a,s);E&&E.startsWith(", ")&&(E=E.substring(2)),S+=E}p?c=S:c=r.StringUtilities.format(s(e),S)}else if(p){var h=e.split("/");if(c=r.StringUtilities.format(i(h[1]),h[1]),h[0].indexOf("-")>-1){var x=this.generateRangeSegmentDescription(h[0],a,n);x.indexOf(", ")!=0&&(c+=", "),c+=x}else if(h[0].indexOf("*")==-1){var A=r.StringUtilities.format(s(h[0]),n(h[0]));A=A.replace(", ",""),c+=r.StringUtilities.format(this.i18n.commaStartingX0(),A)}}else l&&(c=this.generateRangeSegmentDescription(e,a,n));return c},t.prototype.generateRangeSegmentDescription=function(e,o,n){var i="",a=e.split("-"),s=n(a[0],1),c=n(a[1],2),p=o(e);return i+=r.StringUtilities.format(p,s,c),i},t.prototype.formatTime=function(e,o,n){var i=0,a=0,s=parseInt(e)+i,c=parseInt(o)+a;c>=60?(c-=60,s+=1):c<0&&(c+=60,s-=1),s>=24?s=s-24:s<0&&(s=24+s);var p="",l=!1;this.options.use24HourTimeFormat||(l=!!(this.i18n.setPeriodBeforeTime&&this.i18n.setPeriodBeforeTime()),p=l?"".concat(this.getPeriod(s)," "):" ".concat(this.getPeriod(s)),s>12&&(s-=12),s===0&&(s=12));var O="";n&&(O=":".concat(("00"+n).substring(n.length)));var h=s.toString(),S=("00"+h).substring(h.length),_=c.toString(),U=("00"+_).substring(_.length),X=this.options.trimHoursLeadingZero?h:S;return"".concat(l?p:"").concat(X,":").concat(U).concat(O).concat(l?"":p)},t.prototype.transformVerbosity=function(e,o){if(!o&&(e=e.replace(new RegExp(", ".concat(this.i18n.everyMinute()),"g"),""),e=e.replace(new RegExp(", ".concat(this.i18n.everyHour()),"g"),""),e=e.replace(new RegExp(this.i18n.commaEveryDay(),"g"),""),e=e.replace(/\, ?$/,""),this.i18n.conciseVerbosityReplacements))for(var n=0,i=Object.entries(this.i18n.conciseVerbosityReplacements());n<i.length;n++){var a=i[n],s=a[0],c=a[1];e=e.replace(new RegExp(s,"g"),c)}return e},t.prototype.getPeriod=function(e){return e>=12?this.i18n.pm&&this.i18n.pm()||"PM":this.i18n.am&&this.i18n.am()||"AM"},t.locales={},t})();d.ExpressionDescriptor=v},747(g,d,m){Object.defineProperty(d,"__esModule",{value:!0}),d.enLocaleLoader=void 0;var r=m(486),b=(function(){function v(){}return v.prototype.load=function(t){t.en=new r.en},v})();d.enLocaleLoader=b},486(g,d){Object.defineProperty(d,"__esModule",{value:!0}),d.en=void 0;var m=(function(){function r(){}return r.prototype.atX0SecondsPastTheMinuteGt20=function(){return null},r.prototype.atX0MinutesPastTheHourGt20=function(){return null},r.prototype.commaMonthX0ThroughMonthX1=function(){return null},r.prototype.commaYearX0ThroughYearX1=function(){return null},r.prototype.use24HourTimeFormatByDefault=function(){return!1},r.prototype.anErrorOccuredWhenGeneratingTheExpressionD=function(){return"An error occurred when generating the expression description. Check the cron expression syntax."},r.prototype.everyMinute=function(){return"every minute"},r.prototype.everyHour=function(){return"every hour"},r.prototype.atSpace=function(){return"At "},r.prototype.everyMinuteBetweenX0AndX1=function(){return"Every minute between %s and %s"},r.prototype.at=function(){return"At"},r.prototype.spaceAnd=function(){return" and"},r.prototype.everySecond=function(){return"every second"},r.prototype.everyX0Seconds=function(){return"every %s seconds"},r.prototype.secondsX0ThroughX1PastTheMinute=function(){return"seconds %s through %s past the minute"},r.prototype.atX0SecondsPastTheMinute=function(){return"at %s seconds past the minute"},r.prototype.everyX0Minutes=function(){return"every %s minutes"},r.prototype.minutesX0ThroughX1PastTheHour=function(){return"minutes %s through %s past the hour"},r.prototype.atX0MinutesPastTheHour=function(){return"at %s minutes past the hour"},r.prototype.everyX0Hours=function(){return"every %s hours"},r.prototype.betweenX0AndX1=function(){return"between %s and %s"},r.prototype.atX0=function(){return"at %s"},r.prototype.commaEveryDay=function(){return", every day"},r.prototype.commaEveryX0DaysOfTheWeek=function(){return", every %s days of the week"},r.prototype.commaX0ThroughX1=function(){return", %s through %s"},r.prototype.commaAndX0ThroughX1=function(){return", %s through %s"},r.prototype.first=function(){return"first"},r.prototype.second=function(){return"second"},r.prototype.third=function(){return"third"},r.prototype.fourth=function(){return"fourth"},r.prototype.fifth=function(){return"fifth"},r.prototype.commaOnThe=function(){return", on the "},r.prototype.spaceX0OfTheMonth=function(){return" %s of the month"},r.prototype.lastDay=function(){return"the last day"},r.prototype.commaOnTheLastX0OfTheMonth=function(){return", on the last %s of the month"},r.prototype.commaOnlyOnX0=function(){return", only on %s"},r.prototype.commaAndOnX0=function(){return", and on %s"},r.prototype.commaEveryX0Months=function(){return", every %s months"},r.prototype.commaOnlyInX0=function(){return", only in %s"},r.prototype.commaOnTheLastDayOfTheMonth=function(){return", on the last day of the month"},r.prototype.commaOnTheLastWeekdayOfTheMonth=function(){return", on the last weekday of the month"},r.prototype.commaDaysBeforeTheLastDayOfTheMonth=function(){return", %s days before the last day of the month"},r.prototype.firstWeekday=function(){return"first weekday"},r.prototype.weekdayNearestDayX0=function(){return"weekday nearest day %s"},r.prototype.commaOnTheX0OfTheMonth=function(){return", on the %s of the month"},r.prototype.commaEveryX0Days=function(){return", every %s days in a month"},r.prototype.commaBetweenDayX0AndX1OfTheMonth=function(){return", between day %s and %s of the month"},r.prototype.commaOnDayX0OfTheMonth=function(){return", on day %s of the month"},r.prototype.commaEveryHour=function(){return", every hour"},r.prototype.commaEveryX0Years=function(){return", every %s years"},r.prototype.commaStartingX0=function(){return", starting %s"},r.prototype.daysOfTheWeek=function(){return["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},r.prototype.monthsOfTheYear=function(){return["January","February","March","April","May","June","July","August","September","October","November","December"]},r.prototype.atReboot=function(){return"Run once, at startup"},r.prototype.onTheHour=function(){return"on the hour"},r})();d.en=m},515(g,d){Object.defineProperty(d,"__esModule",{value:!0});function m(b,v){if(!b)throw new Error(v)}var r=(function(){function b(){}return b.secondRange=function(v){for(var t=v.split(","),e=0;e<t.length;e++)if(!isNaN(parseInt(t[e],10))){var o=parseInt(t[e],10);m(o>=0&&o<=59,"seconds part must be >= 0 and <= 59")}},b.minuteRange=function(v){for(var t=v.split(","),e=0;e<t.length;e++)if(!isNaN(parseInt(t[e],10))){var o=parseInt(t[e],10);m(o>=0&&o<=59,"minutes part must be >= 0 and <= 59")}},b.hourRange=function(v){for(var t=v.split(","),e=0;e<t.length;e++)if(!isNaN(parseInt(t[e],10))){var o=parseInt(t[e],10);m(o>=0&&o<=23,"hours part must be >= 0 and <= 23")}},b.dayOfMonthRange=function(v){for(var t=v.split(","),e=0;e<t.length;e++)if(!isNaN(parseInt(t[e],10))){var o=parseInt(t[e],10);m(o>=1&&o<=31,"DOM part must be >= 1 and <= 31")}},b.monthRange=function(v,t){for(var e=v.split(","),o=0;o<e.length;o++)if(!isNaN(parseInt(e[o],10))){var n=parseInt(e[o],10);m(n>=1&&n<=12,t?"month part must be >= 0 and <= 11":"month part must be >= 1 and <= 12")}},b.dayOfWeekRange=function(v,t){for(var e=v.split(","),o=0;o<e.length;o++)if(!isNaN(parseInt(e[o],10))){var n=parseInt(e[o],10);m(n>=0&&n<=6,t?"DOW part must be >= 0 and <= 6":"DOW part must be >= 1 and <= 7")}},b})();d.default=r},823(g,d){Object.defineProperty(d,"__esModule",{value:!0}),d.StringUtilities=void 0;var m=(function(){function r(){}return r.format=function(b){for(var v=[],t=1;t<arguments.length;t++)v[t-1]=arguments[t];return b.replace(/%s/g,function(e){for(var o=[],n=1;n<arguments.length;n++)o[n-1]=arguments[n];return v.shift()})},r.containsAny=function(b,v){return v.some(function(t){return b.indexOf(t)>-1})},r})();d.StringUtilities=m}},f={};function y(g){var d=f[g];if(d!==void 0)return d.exports;var m=f[g]={exports:{}};return u[g](m,m.exports,y),m.exports}var w={};return(()=>{var g=w;Object.defineProperty(g,"__esModule",{value:!0}),g.toString=void 0;var d=y(333),m=y(747);d.ExpressionDescriptor.initialize(new m.enLocaleLoader),g.default=d.ExpressionDescriptor;var r=d.ExpressionDescriptor.toString;g.toString=r})(),w})())});var H=V(B(),1);import T from"chalk";import{readFileSync as J,existsSync as G}from"fs";import{homedir as K}from"os";import{join as q}from"path";var I={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function N(){let u;if(process.env.ZIBBY_API_URL)u=process.env.ZIBBY_API_URL;else{let f=process.env.ZIBBY_ENV||"prod";I[f]?u=I[f].apiUrl:u=I.prod.apiUrl}try{let f=new URL(u);return f.protocol!=="http:"&&f.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${f.protocol} (only http/https allowed)`),I.prod.apiUrl):u}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${u}`),I.prod.apiUrl}}function Q(u){if(!u)return null;try{return H.default.toString(u,{use24HourTimeFormat:!1,verbose:!1})}catch{return null}}function ee(u){if(u)return u;let f=q(K(),".zibby","config.json");if(G(f))try{let y=JSON.parse(J(f,"utf-8"));if(y.sessionToken)return y.sessionToken}catch{}if(process.env.ZIBBY_API_KEY)return process.env.ZIBBY_API_KEY;console.error(T.red(`
|
|
2
2
|
Not authenticated`)),console.error(T.gray(" Run: zibby login")),console.error(T.gray(` OR set ZIBBY_API_KEY env var
|
|
3
3
|
`)),process.exit(1)}function te(u=[]){let f={};for(let y of u){let w=y.indexOf("=");if(w<=0)throw new Error(`-p expects key=value, got: ${y}`);f[y.slice(0,w)]=y.slice(w+1)}return f}async function L(u,f,y,w){let g=await fetch(f,{method:u,headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`},...w!==void 0?{body:JSON.stringify(w)}:{}}),d=await g.text(),m=null;try{m=d?JSON.parse(d):null}catch{}if(!g.ok){let r=m?.error||d||`HTTP ${g.status}`;throw new Error(`API ${u} ${g.status}: ${r}`)}return m}function C(u){if(!u)return T.gray(" (no schedule)");let f=Q(u.cron),y=[` ${T.bold("Cron:")} ${T.cyan(u.cron)}${f?T.gray(` (${f})`):""}`,` ${T.bold("Timezone:")} ${u.timezone||"UTC"}`];return u.input&&Object.keys(u.input).length&&y.push(` ${T.bold("Input:")} ${JSON.stringify(u.input)}`),u.createdAt&&y.push(` ${T.bold("Created:")} ${new Date(u.createdAt).toLocaleString()}`),u.updatedAt&&u.updatedAt!==u.createdAt&&y.push(` ${T.bold("Updated:")} ${new Date(u.updatedAt).toLocaleString()}`),y.join(`
|
|
4
4
|
`)}async function ue(u,f,y,w={}){u||(console.error(T.red("Workflow UUID required.")),console.error(T.gray("Usage: zibby workflow schedule <uuid> [get|set <cron>|clear]")),process.exit(1));let g=ee(w.apiKey),d=N(),m=`${String(d).replace(/\/+$/,"")}/workflows/${encodeURIComponent(u)}/schedule`,r=(f||"get").toLowerCase();try{if(r==="get"){let b=await L("GET",m,g);console.log(T.bold(`
|
|
@@ -39,7 +39,7 @@ var K=Object.defineProperty;var q=(o,e)=>()=>(o&&(e=o(o=0)),e);var H=(o,e)=>{for
|
|
|
39
39
|
Too many consecutive errors (${g}). Stopping.
|
|
40
40
|
`)),process.exit(1)),n||process.exit(1),await new Promise(k=>setTimeout(k,3e3))}}async function me(o,e){let{token:t,projectId:n}=fe(e),s=e.follow===!0,l=e.lines?parseInt(e.lines,10):1e5;if(e.all){let r=e.workflow;return r||(console.log(i.red(`
|
|
41
41
|
--workflow is required with --all`)),console.log(i.gray(` Example: zibby workflow logs --workflow ticket-triage --all --project <id>
|
|
42
|
-
`)),process.exit(1)),ge({token:t,projectId:n,workflow:r,follow:s,limit:l})}let a=await pe(o,e,t,n);return s?de({token:t,jobId:a,follow:s,projectId:n}):Z({token:t,projectId:n,jobId:a,follow:!1,limit:l})}var A,ae,T,W=q(()=>{A="https://logs.workflows.zibby.app",ae="https://logs-stream.zibby.app/",T=null});import C from"ora";import{select as V}from"@inquirer/prompts";import{readFileSync as ye,existsSync as we}from"fs";import{homedir as he}from"os";import{join as Ie}from"path";var U={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://
|
|
42
|
+
`)),process.exit(1)),ge({token:t,projectId:n,workflow:r,follow:s,limit:l})}let a=await pe(o,e,t,n);return s?de({token:t,jobId:a,follow:s,projectId:n}):Z({token:t,projectId:n,jobId:a,follow:!1,limit:l})}var A,ae,T,W=q(()=>{A="https://logs.workflows.zibby.app",ae="https://logs-stream.zibby.app/",T=null});import C from"ora";import{select as V}from"@inquirer/prompts";import{readFileSync as ye,existsSync as we}from"fs";import{homedir as he}from"os";import{join as Ie}from"path";var U={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function j(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";U[e]?o=U[e].apiUrl:o=U.prod.apiUrl}try{let e=new URL(o);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),U.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),U.prod.apiUrl}}var X=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function L(o){return o?X.test(o)?{ok:!0}:{ok:!1,error:`'${o}' is not a UUID. Cloud workflows are identified by UUID only. Run \`zibby workflow list\` to find yours, or run \`zibby workflow trigger\` with no argument for interactive selection.`}:{ok:!0}}import{existsSync as Q,readFileSync as ee}from"fs";import{resolve as oe}from"path";function O(o){return o==="true"?!0:o==="false"?!1:o==="null"?null:o!==""&&!isNaN(Number(o))?Number(o):o}function z(o){let e={};for(let t of o||[]){let n=t.indexOf("=");if(n===-1){console.warn(` Warning: ignored param "${t}" \u2014 expected key=value format`);continue}let s=t.slice(0,n).trim(),l=O(t.slice(n+1)),a=s.split("."),r=e;for(let c=0;c<a.length-1;c++)(typeof r[a[c]]!="object"||r[a[c]]===null)&&(r[a[c]]={}),r=r[a[c]];r[a[a.length-1]]=l}return e}function te(o){let e=oe(o);Q(e)||(console.log(`
|
|
43
43
|
Error: --input-file not found: ${o}
|
|
44
44
|
`),process.exit(1));try{return JSON.parse(ee(e,"utf-8"))}catch(t){console.log(`
|
|
45
45
|
Error: --input-file is not valid JSON: ${t.message}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var n={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://
|
|
1
|
+
var n={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://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function l(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let r=process.env.ZIBBY_ENV||"prod";n[r]?o=n[r].apiUrl:o=n.prod.apiUrl}try{let r=new URL(o);return r.protocol!=="http:"&&r.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${r.protocol} (only http/https allowed)`),n.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),n.prod.apiUrl}}function i(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let o=process.env.ZIBBY_ENV||"prod";return(n[o]||n.prod).accountApiUrl}function d(){let o=process.env.ZIBBY_ENV||"prod";return n[o]||n.prod}function a(){let o;if(process.env.ZIBBY_FRONTEND_URL)o=process.env.ZIBBY_FRONTEND_URL;else{let r=process.env.ZIBBY_ENV||"prod";n[r]?o=n[r].frontendUrl:o=n.prod.frontendUrl}try{let r=new URL(o);if(r.protocol!=="http:"&&r.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${r.protocol} (only http/https allowed)`),n.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let s=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],t=r.hostname;if(!s.some(e=>t===e||t.endsWith(`.${e}`))&&!t.includes("localhost")&&t!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${t}`),"https://studio.zibby.dev"}return o}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${o}`),n.local.frontendUrl}}export{n as ENVIRONMENTS,i as getAccountApiUrl,l as getApiUrl,d as getCurrentEnvironment,a as getFrontendUrl};
|
package/dist/package.json
CHANGED