@zibby/cli 0.5.9 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/zibby.js +3 -3
- package/dist/commands/app-run.js +19 -0
- package/dist/commands/app-solo.js +19 -0
- package/dist/commands/app.js +22 -20
- package/dist/commands/mcp.js +3 -3
- package/dist/commands/workflows/webhook.js +28 -0
- package/dist/config/soloTiers.js +1 -0
- package/dist/config/warmPool.js +1 -0
- package/dist/lib/api-client.js +17 -0
- package/dist/lib/find-app-link.js +2 -0
- package/dist/lib/framework-commands.js +1 -0
- package/dist/package.json +2 -2
- package/package.json +2 -2
package/dist/bin/zibby.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
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
|
|
3
|
-
`),
|
|
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 C}from"commander";import{initCommand as P}from"../commands/init.js";import{runCommand as A}from"../commands/run.js";import{videoCommand as S}from"../commands/video.js";import{uploadCommand as _}from"../commands/upload.js";import{ciSetupCommand as B}from"../commands/ci-setup.js";import{setupPlaywrightMcpCommand as E,setupCiCommand as x,testWithVideoCommand as Y}from"../commands/setup-scripts.js";import{readFileSync as j}from"fs";import{fileURLToPath as O}from"url";import{dirname as R,join as z}from"path";import{bootstrapAgentEnv as Z}from"../utils/agent-credentials.js";import{WARM_POOL_QUANTITY_OPTIONS as w,WARM_POOL_MAX_QUANTITY as h}from"../config/warmPool.js";const D=O(import.meta.url),T=R(D),g=JSON.parse(j(z(T,"../package.json"),"utf-8"));function p(e,o){return o.push(e),o}function k(e){if(e===void 0||e===!0||e==="")return 1;const o=parseInt(e,10);if(!Number.isFinite(o)||!w.includes(o))throw new Error(`--warm must be one of [${w.join(", ")}] (got "${e}"). Omit the flag to disable warm pool.`);return o}const b=`zibby v${g.version}`,a=process.argv.slice(2),U=a.includes("-h")||a.includes("--help"),L=a.includes("-v")||a.includes("-V")||a.includes("--version");L&&(console.log(b),process.exit(0));const v=a[0],M=a[1],K=["logs","uninstall"],N=v==="workflow"&&M==="list";!K.includes(v)&&!N&&console.log(`${b}
|
|
3
|
+
`),Z(process.cwd());const F=a[0]==="chat",W=["--verbose","--agent","--stream","-s"],J=a.length>0&&a.every(e=>W.includes(e)||a[a.indexOf(e)-1]==="--agent"),H=a.length===0||F||J;if(H&&!U){const e={},o=a.indexOf("--agent");o!==-1&&a[o+1]&&(e.agent=a[o+1]),a.includes("--verbose")&&(e.verbose=!0),(a.includes("--stream")||a.includes("-s"))&&(e.stream=!0);const{chatCommand:t}=await import("../commands/chat.js");await t(e),process.exit(0)}const n=new C;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(g.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>/
|
|
6
6
|
workflow run <name> Run a workflow locally (one-shot, mirrors trigger flags)
|
|
@@ -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(b),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"),v(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(I),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(P),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 A({...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(B),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 d=n.command("creds").description("Manage credentials Zibby has stored for your workspace (KMS-encrypted)");d.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)}),d.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)}),d.command("set <provider> <token>").description("Paste-token shortcut. e.g. zibby creds set claude sk-ant-oat01-... (auto-detects oauth vs api)").option("--type <kind>","Force credential kind: oauth | api (skips auto-detect)").action(async(e,o,t)=>{const{setCmd:r}=await import("../commands/creds.js");await r(e,o,t),process.exit(0)}),d.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)",c,[]).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)",c,[]).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).",y).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)",c,[]).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("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 h=n.command("template").description("Manage workflow templates in this project");h.command("list").description("List available workflow templates").action(async()=>{const{templateListCommand:e}=await import("../commands/template.js");return e()}),h.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 p=n.command("memory").description("Test memory database \u2014 version-controlled knowledge from runs");p.command("stats").description("Show memory database statistics").action(async()=>{const{memoryStatsCommand:e}=await import("../commands/memory.js");return e()}),p.command("init").description("Initialize the memory database (Dolt)").action(async()=>{const{memoryInitCommand:e}=await import("../commands/memory.js");return e()}),p.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)}),p.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)}),p.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 m=p.command("remote").description("Configure a remote so the team shares cross-spec memory");m.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)}),m.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)}),m.command("info").description("Show the configured memory remote (if any)").action(async()=>{const{memoryRemoteInfoCommand:e}=await import("../commands/memory.js");return e()}),m.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)}),p.command("pull").description("Pull latest team memory from the configured remote").action(async()=>{const{memoryPullCommand:e}=await import("../commands/memory.js");return e()}),p.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 W=n.command("agents").description("Manage Claude/Cursor/Codex helper files for working with Zibby workflows");W.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 i=n.command("workflow").description("Manage workflow graphs \u2014 new, start, deploy, trigger, logs, list, download, delete");i.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)}),i.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)",c,[]).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)}),i.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)}),i.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)",c,[]).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).",y).action(async(e,o)=>{const{deployWorkflowCommand:t}=await import("../commands/workflows/deploy.js");return t(e,o)}),i.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)",c,[]).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)}),i.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)}),i.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)}),i.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)}),i.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)}),i.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)",c,[]).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)}),i.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 u=i.command("env").description("Manage per-workflow encrypted env vars (set ANTHROPIC_API_KEY, DATABASE_URL, etc. per workflow)");u.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)}),u.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)}),u.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)}),u.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)",c,[]).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 J=n.command("project").description("Manage Zibby projects");J.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 H=n.command("run-queue").description("Parallel capacity \u2014 on-disk wait queue (see parallel.waitWhenAtCapacity in .zibby.config.mjs)");H.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 q=n.command("mcp").description("Manage the Zibby Remote MCP integration in your AI agent");q.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("--token <pat>","Use this PAT (zby_pat_\u2026) instead of minting one via session. Also reads ZIBBY_PAT env var.").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)});const s=n.command("app").description("Manage Zibby Managed Apps \u2014 templates, deploy, list, status, destroy");s.command("templates").description("List the app catalog (n8n, grafana, gas-town, \u2026)").action(async e=>{const{appTemplatesCommand:o}=await import("../commands/app.js");return o(e)}),s.command("list").description("List deployed app instances (use --project to scope to one project)").option("--project <id>","Project ID \u2014 defaults to all instances under your account").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async e=>{const{appListCommand:o}=await import("../commands/app.js");return o(e)}),s.command("deploy [appType]").description('Deploy an app \u2014 either from the catalog (e.g. `zibby app deploy grafana --project <id>`) or a free-form install described by --goal (e.g. `zibby app deploy --goal "Install n8n at /n8n on port 5678, persist data in /data" --project <id>`). Pass exactly one of <appType> OR --goal. Catalog deploys are curated by Zibby; goal-based deploys are user-directed installs where you (not Zibby) choose what gets installed and accept the license terms of whatever you install.').option("--project <id>","Project ID (interactive prompt if not provided)").option("--goal <text>",'Free-form natural-language description of what to install (mutually exclusive with <appType>). The agent-ops bootstrap follows the description \u2014 e.g. "install n8n on port 5678 with sqlite persistence". You are responsible for the license terms of any software you install via this path.').option("--name <name>","Instance display name (defaults to appType, or first line of --goal)").option("--provider <name>",'Agent provider \u2014 "claude" (default) or "codex"').option("--arch <name>",`CPU architecture \u2014 "x86_64" or "arm64" (default = catalog's first listed arch; arm64 is ~20% greener at the same price)`).option("--model <name>","Claude model identifier to use for the agent-ops bootstrap (e.g. claude-sonnet-4-6, claude-opus-4-5, claude-haiku-4-5-20251001). Overrides the daemon's baked default. Use a stronger model (Opus) for complex installs; a cheaper one (Haiku) for trivial ones.").option("--anthropic-token <token>","SENSITIVE: Per-deploy Claude credential override. Replaces the workspace-stored token for THIS deploy only \u2014 never persisted. Must start with sk-ant-oat01- (OAuth subscription) or sk-ant-api03- (Anthropic API key). Env equivalent: ZIBBY_ANTHROPIC_TOKEN.").option("--max-turns <n>","Cap on Claude subprocess --max-turns (cfg.Agent.MaxToolCallsPerTask). Default 25; bump for heavy goal-mode installs (n8n, OpenHands) that exhaust the default before finishing. Range 1..200. Example: --max-turns 60.").option("--timeout-min <n>","Bootstrap-task wall-clock cap in minutes. Default 30; bump when npm install / docker pull / native compile dominates wall time (n8n ~500MB install often takes 25-40min). Range 1..120. Example: --timeout-min 45.").option("--auth-type <kind>",'Optional auth sidecar \u2014 "basic" (username + password), "token" (bearer header), or "none" (default, no auth). Adds a tiny Caddy container in front of the public URL that gates requests. Use this on apps with weak / no built-in auth (Grafana ships admin/admin; n8n ships with nothing).').option("--auth-user <name>","Username for --auth-type basic. Required for basic auth. Printable ASCII, no spaces (1-64 chars).").option("--auth-password <pass>","SENSITIVE: Password for --auth-type basic. 8-256 chars; bcrypt-hashed server-side, plaintext never persisted. Env equivalent: ZIBBY_APP_AUTH_PASSWORD.").option("--auth-token <tok>","Optional explicit bearer token for --auth-type token. 16-128 chars, base64url alphabet only ([A-Za-z0-9_-]). Omit to let the backend auto-generate a 32-byte token (returned ONCE in the deploy response \u2014 save it). Env equivalent: ZIBBY_APP_AUTH_TOKEN.").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{appDeployCommand:t}=await import("../commands/app.js");return t(e,o)}),s.command("status <instanceId>").description("Show one instance: status, resources, public URL").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{appStatusCommand:t}=await import("../commands/app.js");return t(e,o)}),s.command("destroy <instanceId>").description("Stop + remove an app instance (interactive confirm unless --yes)").option("-y, --yes","Skip the confirmation prompt").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{appDestroyCommand:t}=await import("../commands/app.js");return t(e,o)}),s.command("upgrade <instanceId>").description("Roll the agent-ops container image without destroying the instance (EFS data preserved)").option("--version <tag>","Pin to a specific agent-ops version (e.g. 0.1.16). Defaults to whatever AppsFleet base task def says.").option("-y, --yes","Skip the confirmation prompt").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{appUpgradeCommand:t}=await import("../commands/app.js");return t(e,o)}),s.command("update-credential <instanceId>").description("Rotate the per-instance Claude credential to whatever's currently in your workspace-credentials. EFS preserved; task restarts ~30s.").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{appUpdateCredentialCommand:t}=await import("../commands/app.js");return t(e,o)}),s.command("set-auth <instanceId>").description("Enable, rotate, or disable the optional Caddy auth sidecar on a running instance. Use --auth-type basic / token / none, or --off to disable. PATCH semantics: omitted flags preserve current state, so e.g. `zibby app set-auth <id> --auth-password new` rotates JUST the password on a basic-auth instance.").option("--auth-type <kind>",'"basic" | "token" | "none". Omit to keep current type (e.g. just rotate the password).').option("--auth-user <name>","Username for basic auth. Required when switching TO basic; preserved on subsequent rotations.").option("--auth-password <pass>","SENSITIVE: Password for basic auth. 8-256 chars; bcrypt-hashed server-side. Env equivalent: ZIBBY_APP_AUTH_PASSWORD.").option("--auth-token <tok>","Optional bearer token for token auth. Omit to let the backend regenerate a fresh 32-byte token (returned ONCE \u2014 save it). Env equivalent: ZIBBY_APP_AUTH_TOKEN.").option("--off","Disable the auth sidecar entirely (alias for --auth-type none). Caddy container removed; public URL exposes the app port directly again.").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{appSetAuthCommand:t}=await import("../commands/app.js");return t(e,o)}),s.command("logs <instanceId>").description("Show recent logs from an app instance (use -t to tail; polls every 3s)").option("-t, --follow","Tail mode \u2014 poll every 3s and print new lines as they arrive (Ctrl+C to stop)").option("--lines <n>","Max lines per fetch (default 200, max 5000)").option("--service <name>","For multi-container apps: limit logs to one service (e.g. `db`, `web`, `agent-ops`). Defaults to interleaved across all containers.").option("--json","Print raw JSON lines (one per line) instead of parsed summary").option("--verbose","Print the full line including JSON body (default: parsed `<time> <msg>` summary)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{appLogsCommand:t}=await import("../commands/app.js");return t(e,o)}),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(P),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"),A(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(S),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(_),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(B),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 E({...e,viewport:o})}),n.command("setup-ci-full").description("Complete CI/CD setup from scratch").action(x),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(Y),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 d=n.command("creds").description("Manage credentials Zibby has stored for your workspace (KMS-encrypted)");d.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)}),d.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)}),d.command("set <provider> <token>").description("Paste-token shortcut. e.g. zibby creds set claude sk-ant-oat01-... (auto-detects oauth vs api)").option("--type <kind>","Force credential kind: oauth | api (skips auto-detect)").action(async(e,o,t)=>{const{setCmd:s}=await import("../commands/creds.js");await s(e,o,t),process.exit(0)}),d.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 q=n.command("g").description("Generate scaffolds");q.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)",p,[]).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)",p,[]).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 ${h}). Skips ~60s Fargate cold-start by routing triggers to a per-account pool of always-on tasks. Pricing applies (paid feature).`,k).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:s}=await import("../commands/workflows/dedicated-egress.js");return s(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)",p,[]).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("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 I=n.command("template").description("Manage workflow templates in this project");I.command("list").description("List available workflow templates").action(async()=>{const{templateListCommand:e}=await import("../commands/template.js");return e()}),I.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 m=c.command("remote").description("Configure a remote so the team shares cross-spec memory");m.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)}),m.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)}),m.command("info").description("Show the configured memory remote (if any)").action(async()=>{const{memoryRemoteInfoCommand:e}=await import("../commands/memory.js");return e()}),m.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 G=n.command("agents").description("Manage Claude/Cursor/Codex helper files for working with Zibby workflows");G.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:s}=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 s(e,{force:o.force===!0})}else await t({forcedAgents:void 0,force:o.force===!0,forcePrompt:!0})});const r=n.command("workflow").description("Manage workflow graphs \u2014 new, start, deploy, trigger, logs, list, download, delete");r.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)}),r.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)",p,[]).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)}),r.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)}),r.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)",p,[]).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 ${h}). Skips ~60s Fargate cold-start by routing triggers to a per-account pool of always-on tasks. Pricing applies (paid feature).`,k).action(async(e,o)=>{const{deployWorkflowCommand:t}=await import("../commands/workflows/deploy.js");return t(e,o)}),r.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)",p,[]).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)}),r.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)}),r.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)}),r.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)}),r.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)}),r.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)",p,[]).option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o,t,s)=>{const{scheduleCommand:l}=await import("../commands/workflows/schedule.js");return l(e,o,t,s)});const u=r.command("webhook").description("Configure a workflow's inbound webhook + auth (enable/disable, basic/ip/token, show)");u.command("enable <uuid>").description("Enable the workflow's inbound webhook (HTTP trigger)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{webhookCommand:t}=await import("../commands/workflows/webhook.js");return t("enable",e,void 0,o)}),u.command("disable <uuid>").description("Disable the workflow's inbound webhook (HTTP trigger)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{webhookCommand:t}=await import("../commands/workflows/webhook.js");return t("disable",e,void 0,o)}),u.command("show <uuid>").description("Show current webhook config (which auth methods are on, masked token, IP list, URL)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{webhookCommand:t}=await import("../commands/workflows/webhook.js");return t("show",e,void 0,o)});const y=u.command("auth").description("Configure webhook auth methods: basic | ip | token");y.command("basic <uuid>").description("Enable HTTP Basic auth (or --disable to turn it off). Password optional on update.").option("--username <u>","Basic auth username").option("--password <p>","Basic auth password (plaintext; backend hashes it; omit to keep existing)").option("--disable","Turn Basic auth off").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{webhookCommand:t}=await import("../commands/workflows/webhook.js");return t("auth","basic",e,o)}),y.command("ip <uuid>").description("Set the IP allowlist (or --disable to turn it off)").option("--allow <cidr,...>","Comma-separated IPs/CIDRs, e.g. 1.2.3.4,10.0.0.0/8").option("--disable","Turn the IP allowlist off").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{webhookCommand:t}=await import("../commands/workflows/webhook.js");return t("auth","ip",e,o)}),y.command("token <uuid>").description("Generate a bearer token (--generate) \u2014 printed ONCE \u2014 or --disable to turn it off").option("--generate","Mint a new token; printed once in plaintext").option("--disable","Turn token auth off").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{webhookCommand:t}=await import("../commands/workflows/webhook.js");return t("auth","token",e,o)}),r.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 f=r.command("env").description("Manage per-workflow encrypted env vars (set ANTHROPIC_API_KEY, DATABASE_URL, etc. per workflow)");f.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)}),f.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:s}=await import("../commands/workflows/env.js");return s(e,o,t)}),f.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:s}=await import("../commands/workflows/env.js");return s(e,o,t)}),f.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)",p,[]).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 V=n.command("project").description("Manage Zibby projects");V.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.command("run-queue").description("Parallel capacity \u2014 on-disk wait queue (see parallel.waitWhenAtCapacity in .zibby.config.mjs)");$.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 Q=n.command("mcp").description("Manage the Zibby Remote MCP integration in your AI agent");Q.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("--token <pat>","Use this PAT (zby_pat_\u2026) instead of minting one via session. Also reads ZIBBY_PAT env var.").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)});const i=n.command("app").description("Manage Zibby Managed Apps \u2014 templates, deploy, list, status, destroy");i.command("templates").description("List the app catalog (n8n, grafana, gas-town, \u2026)").action(async e=>{const{appTemplatesCommand:o}=await import("../commands/app.js");return o(e)}),i.command("list").description("List deployed app instances (use --project to scope to one project)").option("--project <id>","Project ID \u2014 defaults to all instances under your account").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async e=>{const{appListCommand:o}=await import("../commands/app.js");return o(e)}),i.command("deploy [appType]").description('Deploy an app \u2014 either from the catalog (e.g. `zibby app deploy grafana --project <id>`) or a free-form install described by --goal (e.g. `zibby app deploy --goal "Install n8n at /n8n on port 5678, persist data in /data" --project <id>`). Pass exactly one of <appType> OR --goal. Catalog deploys are curated by Zibby; goal-based deploys are user-directed installs where you (not Zibby) choose what gets installed and accept the license terms of whatever you install.').option("--mode <name>",'Deploy mode \u2014 "cloud" (default, shared Fargate) or "solo" (dedicated t4g.* EC2 per app, cheaper + isolated). Solo deploys take --repo / --tier / --secret instead of <appType>; see `zibby app deploy --mode solo --help` for the solo flags.').option("--slug <name>","[solo] App slug \u2014 used to form the public hostname <slug>.solo.zibby.app. lowercase [a-z0-9-], 1-40 chars.").option("--repo <ownerRepo>",'[solo] GitHub source repo in "owner/name" form. Mutually exclusive with --tarball.').option("--ref <ref>","[solo] Git ref (branch, tag, sha) to clone. Defaults to the repo's default branch.").option("--tarball <s3Url>","[solo] s3:// URL of a tarball source. Mutually exclusive with --repo.").option("--framework <name>",'[solo] Framework hint \u2014 auto (default), rails, node, python, static, other. "auto" lets agent-ops detect from the source tree.').option("--tier <id>","[solo] Instance tier id: micro | small | medium | large. Run `zibby app deploy --mode solo` without --tier to see the live pricing table.").option("--region <id>","[solo] AWS region for the VM: ap-southeast-2 (Sydney, default) | us-east-1 | us-west-2 | eu-west-1 | ap-northeast-1 | auto (latency-probe + pick nearest). The Zibby control plane stays in Sydney; only your app's EC2 + storage move. Pricing is the same in every region. Omit the flag in interactive mode to pick from a list sorted by measured latency.").option("--secret <kv...>","[solo] Repeatable. Each is KEY=VALUEREF where VALUEREF points at your workspace-credentials (uploaded via `zibby creds set`). Plaintext is NOT accepted here. Example: --secret STRIPE_KEY=workspace:stripe-prod.").option("--db-persistence <kind>","[solo] Database persistence: sqlite-litestream | postgres-walg | none (default).").option("--files-persistence <kind>","[solo] Files persistence: activestorage-s3 | rclone-bisync | none (default).").option("--no-tail","[solo] Skip the post-fire status tail. Default tails until phase=running/failed (max 15 min). --yes implies --no-tail.").option("-y, --yes","Non-interactive mode \u2014 exit 1 on any missing inputs instead of prompting. Implies --no-tail.").option("--project <id>","Project ID (interactive prompt if not provided)").option("--goal <text>",'Free-form natural-language description of what to install (mutually exclusive with <appType>). The agent-ops bootstrap follows the description \u2014 e.g. "install n8n on port 5678 with sqlite persistence". You are responsible for the license terms of any software you install via this path.').option("--name <name>","Instance display name (defaults to appType, or first line of --goal)").option("--provider <name>",'Agent provider \u2014 "claude" (default) or "codex"').option("--arch <name>",`CPU architecture \u2014 "x86_64" or "arm64" (default = catalog's first listed arch; arm64 is ~20% greener at the same price)`).option("--model <name>","Claude model identifier to use for the agent-ops bootstrap (e.g. claude-sonnet-4-6, claude-opus-4-5, claude-haiku-4-5-20251001). Overrides the daemon's baked default. Use a stronger model (Opus) for complex installs; a cheaper one (Haiku) for trivial ones.").option("--anthropic-token <token>","SENSITIVE: Per-deploy Claude credential override. Replaces the workspace-stored token for THIS deploy only \u2014 never persisted. Must start with sk-ant-oat01- (OAuth subscription) or sk-ant-api03- (Anthropic API key). Env equivalent: ZIBBY_ANTHROPIC_TOKEN.").option("--max-turns <n>","Cap on Claude subprocess --max-turns (cfg.Agent.MaxToolCallsPerTask). Default 25; bump for heavy goal-mode installs (n8n, OpenHands) that exhaust the default before finishing. Range 1..200. Example: --max-turns 60.").option("--timeout-min <n>","Bootstrap-task wall-clock cap in minutes. Default 30; bump when npm install / docker pull / native compile dominates wall time (n8n ~500MB install often takes 25-40min). Range 1..120. Example: --timeout-min 45.").option("--auth-type <kind>",'Optional auth sidecar \u2014 "basic" (username + password), "token" (bearer header), or "none" (default, no auth). Adds a tiny Caddy container in front of the public URL that gates requests. Use this on apps with weak / no built-in auth (Grafana ships admin/admin; n8n ships with nothing).').option("--auth-user <name>","Username for --auth-type basic. Required for basic auth. Printable ASCII, no spaces (1-64 chars).").option("--auth-password <pass>","SENSITIVE: Password for --auth-type basic. 8-256 chars; bcrypt-hashed server-side, plaintext never persisted. Env equivalent: ZIBBY_APP_AUTH_PASSWORD.").option("--auth-token <tok>","Optional explicit bearer token for --auth-type token. 16-128 chars, base64url alphabet only ([A-Za-z0-9_-]). Omit to let the backend auto-generate a 32-byte token (returned ONCE in the deploy response \u2014 save it). Env equivalent: ZIBBY_APP_AUTH_TOKEN.").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{appDeployCommand:t}=await import("../commands/app.js");return t(e,o)}),i.command("status <instanceId>").description("Show one instance: status, resources, public URL").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{appStatusCommand:t}=await import("../commands/app.js");return t(e,o)}),i.command("destroy <instanceId>").description("Stop + remove an app instance (interactive confirm unless --yes)").option("-y, --yes","Skip the confirmation prompt").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{appDestroyCommand:t}=await import("../commands/app.js");return t(e,o)}),i.command("upgrade <instanceId>").description("Roll the agent-ops container image without destroying the instance (EFS data preserved)").option("--version <tag>","Pin to a specific agent-ops version (e.g. 0.1.16). Defaults to whatever AppsFleet base task def says.").option("-y, --yes","Skip the confirmation prompt").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{appUpgradeCommand:t}=await import("../commands/app.js");return t(e,o)}),i.command("update-credential <instanceId>").description("Rotate the per-instance Claude credential to whatever's currently in your workspace-credentials. EFS preserved; task restarts ~30s.").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{appUpdateCredentialCommand:t}=await import("../commands/app.js");return t(e,o)}),i.command("set-auth <instanceId>").description("Enable, rotate, or disable the optional Caddy auth sidecar on a running instance. Use --auth-type basic / token / none, or --off to disable. PATCH semantics: omitted flags preserve current state, so e.g. `zibby app set-auth <id> --auth-password new` rotates JUST the password on a basic-auth instance.").option("--auth-type <kind>",'"basic" | "token" | "none". Omit to keep current type (e.g. just rotate the password).').option("--auth-user <name>","Username for basic auth. Required when switching TO basic; preserved on subsequent rotations.").option("--auth-password <pass>","SENSITIVE: Password for basic auth. 8-256 chars; bcrypt-hashed server-side. Env equivalent: ZIBBY_APP_AUTH_PASSWORD.").option("--auth-token <tok>","Optional bearer token for token auth. Omit to let the backend regenerate a fresh 32-byte token (returned ONCE \u2014 save it). Env equivalent: ZIBBY_APP_AUTH_TOKEN.").option("--off","Disable the auth sidecar entirely (alias for --auth-type none). Caddy container removed; public URL exposes the app port directly again.").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{appSetAuthCommand:t}=await import("../commands/app.js");return t(e,o)}),i.command("logs <instanceId>").description("Show recent logs from an app instance (use -t to tail; polls every 3s)").option("-t, --follow","Tail mode \u2014 poll every 3s and print new lines as they arrive (Ctrl+C to stop)").option("--lines <n>","Max lines per fetch (default 200, max 5000)").option("--service <name>","For multi-container apps: limit logs to one service (e.g. `db`, `web`, `agent-ops`). Defaults to interleaved across all containers.").option("--json","Print raw JSON lines (one per line) instead of parsed summary").option("--verbose","Print the full line including JSON body (default: parsed `<time> <msg>` summary)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{appLogsCommand:t}=await import("../commands/app.js");return t(e,o)}),i.command("run [cmd...]").description("Run a one-off command on a linked solo app (e.g. `zibby app run rails db:migrate`). Attaches your TTY via SSM \u2014 no AWS creds needed.").option("--app <slug>","App slug (defaults to the nearest .zibby/app.json)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{appRunCommand:t}=await import("../commands/app-run.js");return t(e,o)}),i.command("console").description("Open the framework REPL on a linked solo app (rails console, python manage.py shell, node, iex -S mix)").option("--app <slug>","App slug (defaults to the nearest .zibby/app.json)").option("--framework <name>","Override the framework from the link file (rails | django | python | node | elixir)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async e=>{const{appConsoleCommand:o}=await import("../commands/app-run.js");return o(e)}),i.command("migrate").description("Run database migrations on a linked solo app (rails db:migrate / python manage.py migrate)").option("--app <slug>","App slug (defaults to the nearest .zibby/app.json)").option("--framework <name>","Override the framework from the link file").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async e=>{const{appMigrateCommand:o}=await import("../commands/app-run.js");return o(e)}),i.command("rollback [steps]").description("Roll back the last database migration(s) on a linked solo app (rails db:rollback STEP=<n>, default 1)").option("--app <slug>","App slug (defaults to the nearest .zibby/app.json)").option("--framework <name>","Override the framework from the link file").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{appRollbackCommand:t}=await import("../commands/app-run.js");return t(e,o)}),i.command("link <slug>").description("Link the current directory to a solo app \u2014 writes .zibby/app.json (commit it so your team can `zibby app run` without --app)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{appLinkCommand:t}=await import("../commands/app-run.js");return t(e,o)}),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();
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import{spawn as So,spawnSync as vo}from"node:child_process";import a from"chalk";import no from"ora";import ko from"chalk";import{existsSync as yo,readFileSync as ho}from"fs";import{join as wo}from"path";import A from"chalk";import{confirm as bo}from"@inquirer/prompts";import i from"chalk";import T from"ora";import{spawn as uo}from"child_process";var w={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";w[e]?o=w[e].apiUrl:o=w.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)`),w.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),w.prod.apiUrl}}import{existsSync as L,mkdirSync as so,readFileSync as io,writeFileSync as ao}from"fs";import{homedir as B}from"os";import{join as I}from"path";function R(){return process.env.ZIBBY_CONFIG_DIR||I(B(),".zibby")}function O(){return I(R(),"config.json")}var co=I(B(),".zibby"),Co=I(co,"config.json");function lo(){let o=R();L(o)||so(o,{recursive:!0})}function g(){try{let o=O();if(L(o)){let e=io(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function b(o){lo(),ao(O(),JSON.stringify(o,null,2))}function E(){return g().sessionToken||null}function F(o){let e=g();e.sessionToken=o,b(e)}function Y(){return g().user||null}function D(o){let e=g();e.user=o,b(e)}function Z(o){let e=g();e.proxyUrl=o,b(e)}function J(o){let e=g();e.mem0ProxyUrl=o,b(e)}function K(o){let e=g();e.projects=o,b(e)}import{existsSync as Bo,mkdirSync as Ro,readFileSync as Oo,writeFileSync as Eo,unlinkSync as Fo}from"fs";import{resolve as Do}from"path";import{homedir as Jo}from"os";function po(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]),uo(n,t,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function go(){let o=E(),e=Y();return o&&e?{loggedIn:!0,user:e,token:o}:{loggedIn:!1}}async function V(){try{console.log(i.cyan(`
|
|
2
|
+
\u{1F510} Initiating login...
|
|
3
|
+
`));let o=go();if(o.loggedIn){console.log(i.green("\u2705 Already logged in!")),console.log(i.gray(`User: ${o.user.email}`)),console.log(i.gray(`Name: ${o.user.name}
|
|
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)},l=()=>{console.log(i.yellow(`
|
|
5
|
+
|
|
6
|
+
\u26A0\uFE0F Login cancelled
|
|
7
|
+
`)),s(),process.exit(0)};process.on("SIGINT",l),n.question(i.yellow("Continue with this session? (Y/n): "),async c=>{process.removeListener("SIGINT",l),s();try{if(c.toLowerCase()==="n"||c.toLowerCase()==="no"){console.log(i.gray(`Starting new login...
|
|
8
|
+
`));let p=await M();t(p)}else console.log(i.green(`Using existing session.
|
|
9
|
+
`)),t({success:!0,...o})}catch(p){r(p)}})})}return await M()}catch(o){return console.error(i.red(`
|
|
10
|
+
\u274C Login failed:`,o.message)),{success:!1,error:o.message}}}async function fo(o){let e=h();try{let n=await fetch(`${e}/projects`,{headers:{Authorization:`Bearer ${o}`}});if(n.ok){let r=((await n.json()).projects||[]).map(s=>({name:s.name,projectId:s.projectId,apiToken:s.apiToken}));return K(r),r}}catch(n){console.log(i.gray(`\u26A0\uFE0F Could not fetch projects: ${n.message}`))}return[]}async function M(){let o=h(),e=T("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 y=await n.json();throw new Error(y.error||"Failed to initiate login")}let{deviceCode:t,userCode:r,verificationUrl:s,expiresIn:l,interval:c}=await n.json();e.succeed("Login code generated"),console.log(""),console.log(i.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(i.cyan("\u2551")+i.white.bold(" Complete login in your browser ")+i.cyan("\u2551")),console.log(i.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(i.white("Opening browser to login page...")),console.log(i.gray(`Code expires in ${Math.floor(l/60)} minutes`)),console.log(""),await po(s)||(console.log(i.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(i.white("Please open this URL manually: ")+i.blue(s)),console.log(""));let d=T("Waiting for authorization...").start(),k=(c||3)*1e3,x=Math.floor(l/(c||3)),m=0,_=!1,C=()=>{_=!0,d.stop(),console.log(i.yellow(`
|
|
11
|
+
|
|
12
|
+
\u26A0\uFE0F Login cancelled
|
|
13
|
+
`)),process.exit(0)};process.on("SIGINT",C);try{for(;m<x&&!_;){await mo(k),m++;let y=await fetch(`${o}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:t})});if(y.status===202)continue;if(!y.ok){d.fail("Authorization failed");let U=await y.json();throw new Error(U.error||"Authorization failed")}let u=await y.json();if(u.status==="authorized"){d.succeed(i.white("Authorization successful!")),F(u.token),D(u.user),u.proxyUrl&&Z(u.proxyUrl),u.mem0ProxyUrl&&J(u.mem0ProxyUrl),console.log(""),console.log(i.gray(`User: ${u.user.email}`));let U=T("Fetching projects...").start(),z=await fo(u.token);return U.succeed(`Fetched ${z.length} project${z.length!==1?"s":""}`),console.log(i.gray(`Session saved to: ~/.zibby/config.json
|
|
14
|
+
`)),{success:!0,loggedIn:!0,user:u.user,token:u.token}}if(u.status==="denied")throw d.fail("Authorization denied"),new Error("User denied authorization")}throw d.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",C)}}function mo(o){return new Promise(e=>setTimeout(e,o))}function H(){try{let o=process.env.HOME||process.env.USERPROFILE;if(!o)return null;let e=wo(o,".zibby","config.json");return yo(e)&&JSON.parse(ho(e,"utf-8")).sessionToken||null}catch{return null}}function j(){console.log(`
|
|
15
|
+
Not authenticated.`),console.log(` Run ${A.cyan("zibby login")} or set ${A.cyan("ZIBBY_API_KEY")} in your environment.
|
|
16
|
+
`)}async function G(o={}){let e=o.apiKey||process.env.ZIBBY_API_KEY||null,n=H();if(n||e)return{sessionToken:n,apiKey:e};if(!process.stdin.isTTY){if(o.optional)return{sessionToken:null,apiKey:null};j(),process.exit(1)}console.log(A.yellow(`
|
|
17
|
+
Not logged in.`));let t;try{t=await bo({message:"Open browser to log in now?",default:!0})}catch{t=!1}if(!t){if(o.optional)return{sessionToken:null,apiKey:null};j(),process.exit(1)}if(await V(),n=H(),!n){if(o.optional)return{sessionToken:null,apiKey:null};j(),process.exit(1)}return{sessionToken:n,apiKey:null}}function W(o){if(!o)return null;try{return JSON.parse(o)}catch{return{raw:o}}}async function P(o){let{sessionToken:e,apiKey:n}=await G({apiKey:o?.apiKey}),t=e||n;return t||(console.error(ko.red("Not authenticated. Run `zibby login` or set ZIBBY_API_KEY.")),process.exit(1)),{"Content-Type":"application/json",Authorization:`Bearer ${t}`}}async function q(o,e,n){let t=h(),r=await fetch(`${t}${o}`,{method:"POST",headers:n,body:JSON.stringify(e)}),s=await r.text();return{status:r.status,body:W(s)}}async function X(o,e){let n=h(),t=await fetch(`${n}${o}`,{method:"GET",headers:e}),r=await t.text();return{status:t.status,body:W(r)}}import S from"node:fs";import f from"node:path";var xo=f.join(".zibby","app.json");function Io(o){return!!o&&typeof o=="object"&&typeof o.appSlug=="string"&&o.appSlug.length>0&&o.deployMode==="solo"}function Q(o=process.cwd()){let e=f.resolve(o);for(let n=0;n<256;n+=1){let t=f.join(e,xo);if(S.existsSync(t))try{let s=JSON.parse(S.readFileSync(t,"utf8"));if(Io(s))return{path:t,config:s}}catch{}let r=f.dirname(e);if(r===e)break;e=r}return null}function oo(o,e={}){let n=f.join(f.resolve(o),".zibby");S.mkdirSync(n,{recursive:!0});let t=f.join(n,"app.json"),r={appSlug:e.appSlug,deployMode:"solo",region:e.region||"",instanceId:e.instanceId||"",domain:e.domain||"",framework:e.framework||""};return S.writeFileSync(t,`${JSON.stringify(r,null,2)}
|
|
18
|
+
`,"utf8"),{path:t,config:r}}var $='Use `zibby app run "<your command>"` instead.';function eo(o){let e=String(o||"").toLowerCase();return{framework:e,console(){switch(e){case"rails":return{command:"bin/rails console"};case"django":case"python":return{command:"python manage.py shell"};case"node":return{command:"node"};case"elixir":return{command:"iex -S mix"};default:return{error:`No known REPL for framework "${o||"unknown"}". ${$}`}}},migrate(){switch(e){case"rails":return{command:"bin/rails db:migrate"};case"django":return{command:"python manage.py migrate"};default:return{error:`No known migrate command for framework "${o||"unknown"}". ${$}`}}},rollback(n){let t=Number.parseInt(n,10),r=Number.isFinite(t)&&t>0?t:1;switch(e){case"rails":return{command:`bin/rails db:rollback STEP=${r}`};case"django":return{error:'Django rollback needs an explicit migration target (e.g. `python manage.py migrate <app> <name>`). Use `zibby app run "python manage.py migrate <app> <target>"`.'};default:return{error:`No known rollback command for framework "${o||"unknown"}". ${$}`}}}}}var to="No app linked. Run `zibby app link <slug>` in your project, or pass --app <slug>.";function ro(o={},e=process.cwd()){if(o.app)return{slug:String(o.app),link:null};let n=Q(e);return n?{slug:n.config.appSlug,link:n}:{slug:null,link:null}}function Uo(o,e){return o.framework?String(o.framework):e?.config?.framework||""}function To(o=vo){let e=process.platform==="win32"?"where":"which";return o(e,["session-manager-plugin"],{stdio:"ignore"}).status===0}function jo(o=process.platform){let e="https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html",n=["",a.red("session-manager-plugin is not installed (required for `zibby app run`)."),""];return o==="darwin"?(n.push("Install it on macOS:"),n.push(a.cyan(" brew install --cask session-manager-plugin"))):o==="win32"?(n.push("Install it on Windows \u2014 download and run the installer:"),n.push(a.cyan(" https://s3.amazonaws.com/session-manager-downloads/plugin/latest/windows/SessionManagerPluginSetup.exe"))):(n.push("Install it on Linux (Debian/Ubuntu):"),n.push(a.cyan(' curl "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/ubuntu_64bit/session-manager-plugin.deb" -o "/tmp/session-manager-plugin.deb"')),n.push(a.cyan(" sudo dpkg -i /tmp/session-manager-plugin.deb")),n.push("Or on RHEL/Fedora:"),n.push(a.cyan(' sudo dnf install -y "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/linux_64bit/session-manager-plugin.rpm"'))),n.push(""),n.push(a.dim(`Docs: ${e}`)),n.push(""),n.join(`
|
|
19
|
+
`)}function Ao(o,e,n=So){let t=JSON.stringify({SessionId:o.sessionId,StreamUrl:o.streamUrl,TokenValue:o.tokenValue});return new Promise((r,s)=>{let l=n("session-manager-plugin",[t,e,"StartSession"],{stdio:"inherit"});l.on("error",s),l.on("exit",(c,p)=>{if(p){r(1);return}r(c??0)})})}async function v(o,e){let{slug:n}=ro(e);if(!n){console.error(a.red(to)),process.exit(1);return}if(!To()){console.error(jo()),process.exit(1);return}let t=await P(e),r=no(`Starting remote session on ${n}\u2026`).start(),s=await q(`/apps/solo/${encodeURIComponent(n)}/run`,{command:o,interactive:!0},t);if(s.status>=400){r.fail("Could not start remote session");let m=s.body?.error||s.body?.message||`HTTP ${s.status}`;console.error(a.red(m)),process.exit(1);return}let{sessionId:l,streamUrl:c,tokenValue:p,region:d,instanceId:k}=s.body||{};if(!l||!c||!p||!d){r.fail("Backend did not return a usable session"),console.error(a.red("Expected { sessionId, streamUrl, tokenValue, region } from /run.")),process.exit(1);return}r.succeed(`Connected to ${n}${k?` (${k})`:""}`),console.log(a.dim(`$ ${o}`));let x;try{x=await Ao({sessionId:l,streamUrl:c,tokenValue:p},d)}catch(m){console.error(a.red(`Failed to launch session-manager-plugin: ${m.message}`)),process.exit(1);return}process.exit(x)}function N(o,e,n){let{slug:t,link:r}=ro(e);if(!t)return console.error(a.red(to)),process.exit(1),null;let s=Uo(e,r),l=eo(s),c=o==="rollback"?l.rollback(n):l[o]();return c.error?(console.error(a.red(c.error)),process.exit(1),null):c.command}async function xe(o=[],e={}){let n=(Array.isArray(o)?o:[o]).join(" ").trim();if(!n){console.error(a.red("Nothing to run. Example: `zibby app run rails db:migrate`")),process.exit(1);return}await v(n,e)}async function Ie(o={}){let e=N("console",o);e&&await v(e,o)}async function Se(o={}){let e=N("migrate",o);e&&await v(e,o)}async function ve(o,e={}){let n=N("rollback",e,o);n&&await v(n,e)}async function Ue(o,e={}){if(!o){console.error(a.red("Usage: zibby app link <slug>")),process.exit(1);return}let n=await P(e),t=no(`Fetching status for ${o}\u2026`).start(),r=await X(`/apps/solo/${encodeURIComponent(o)}/status`,n);if(r.status>=400){t.fail("Could not fetch app status");let c=r.body?.error||r.body?.message||`HTTP ${r.status}`;console.error(a.red(c)),process.exit(1);return}t.succeed(`Found ${o}`);let s=r.body||{},{path:l}=oo(process.cwd(),{appSlug:o,deployMode:"solo",region:s.region||"",instanceId:s.instanceId||"",domain:s.domain||"",framework:s.framework||"auto"});console.log(""),console.log(a.green(`Linked ${process.cwd()} \u2192 ${o}.`)),console.log(a.dim(` ${l}`)),console.log("Committed-friendly: add .zibby/app.json to git."),console.log("")}export{Ie as appConsoleCommand,Ue as appLinkCommand,Se as appMigrateCommand,ve as appRollbackCommand,xe as appRunCommand,To as hasSessionManagerPlugin,jo as pluginInstallInstructions,ro as resolveApp,Ao as spawnSessionPlugin};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import ve from"node:net";import Ie from"node:path";import d from"chalk";import $ from"ora";import k from"inquirer";var se=[{id:"micro",instanceType:"t4g.nano",vCpu:2,ramGB:.5,priceUSD:6},{id:"small",instanceType:"t4g.micro",vCpu:2,ramGB:1,priceUSD:10},{id:"medium",instanceType:"t4g.small",vCpu:2,ramGB:2,priceUSD:18},{id:"large",instanceType:"t4g.medium",vCpu:2,ramGB:4,priceUSD:32}],O=se.map(e=>e.id);var v=[{id:"ap-southeast-2",name:"Sydney",default:!0},{id:"us-east-1",name:"N. Virginia"},{id:"us-west-2",name:"Oregon"},{id:"eu-west-1",name:"Ireland"},{id:"ap-northeast-1",name:"Tokyo"}],_=v.map(e=>e.id),R=(v.find(e=>e.default)||v[0]).id;import Se from"chalk";import{existsSync as ye,readFileSync as he}from"fs";import{join as be}from"path";import C from"chalk";import{confirm as we}from"@inquirer/prompts";import p from"chalk";import j from"ora";import{spawn as ue}from"child_process";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 I(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";U[o]?e=U[o].apiUrl:e=U.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)`),U.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),U.prod.apiUrl}}import{existsSync as E,mkdirSync as ie,readFileSync as ce,writeFileSync as ae}from"fs";import{homedir as B}from"os";import{join as A}from"path";function z(){return process.env.ZIBBY_CONFIG_DIR||A(B(),".zibby")}function D(){return A(z(),"config.json")}var le=A(B(),".zibby"),Ee=A(le,"config.json");function pe(){let e=z();E(e)||ie(e,{recursive:!0})}function S(){try{let e=D();if(E(e)){let o=ce(e,"utf-8");return JSON.parse(o)}}catch{}return{}}function x(e){pe(),ae(D(),JSON.stringify(e,null,2))}function F(){return S().sessionToken||null}function Y(e){let o=S();o.sessionToken=e,x(o)}function J(){return S().user||null}function M(e){let o=S();o.user=e,x(o)}function Z(e){let o=S();o.proxyUrl=e,x(o)}function G(e){let o=S();o.mem0ProxyUrl=e,x(o)}function K(e){let o=S();o.projects=e,x(o)}import{existsSync as De,mkdirSync as Fe,readFileSync as Ye,writeFileSync as Je,unlinkSync as Me}from"fs";import{resolve as Ge}from"path";import{homedir as Ve}from"os";function fe(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]),ue(t,n,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function de(){let e=F(),o=J();return e&&o?{loggedIn:!0,user:o,token:e}:{loggedIn:!1}}async function H(){try{console.log(p.cyan(`
|
|
2
|
+
\u{1F510} Initiating login...
|
|
3
|
+
`));let e=de();if(e.loggedIn){console.log(p.green("\u2705 Already logged in!")),console.log(p.gray(`User: ${e.user.email}`)),console.log(p.gray(`Name: ${e.user.name}
|
|
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(p.yellow(`
|
|
5
|
+
|
|
6
|
+
\u26A0\uFE0F Login cancelled
|
|
7
|
+
`)),i(),process.exit(0)};process.on("SIGINT",s),t.question(p.yellow("Continue with this session? (Y/n): "),async c=>{process.removeListener("SIGINT",s),i();try{if(c.toLowerCase()==="n"||c.toLowerCase()==="no"){console.log(p.gray(`Starting new login...
|
|
8
|
+
`));let l=await V();n(l)}else console.log(p.green(`Using existing session.
|
|
9
|
+
`)),n({success:!0,...e})}catch(l){r(l)}})})}return await V()}catch(e){return console.error(p.red(`
|
|
10
|
+
\u274C Login failed:`,e.message)),{success:!1,error:e.message}}}async function ge(e){let o=I();try{let t=await fetch(`${o}/projects`,{headers:{Authorization:`Bearer ${e}`}});if(t.ok){let r=((await t.json()).projects||[]).map(i=>({name:i.name,projectId:i.projectId,apiToken:i.apiToken}));return K(r),r}}catch(t){console.log(p.gray(`\u26A0\uFE0F Could not fetch projects: ${t.message}`))}return[]}async function V(){let e=I(),o=j("Requesting login code...").start(),t=await fetch(`${e}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){o.fail("Failed to request login code");let y=await t.json();throw new Error(y.error||"Failed to initiate login")}let{deviceCode:n,userCode:r,verificationUrl:i,expiresIn:s,interval:c}=await t.json();o.succeed("Login code generated"),console.log(""),console.log(p.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(p.cyan("\u2551")+p.white.bold(" Complete login in your browser ")+p.cyan("\u2551")),console.log(p.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(p.white("Opening browser to login page...")),console.log(p.gray(`Code expires in ${Math.floor(s/60)} minutes`)),console.log(""),await fe(i)||(console.log(p.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(p.white("Please open this URL manually: ")+p.blue(i)),console.log(""));let a=j("Waiting for authorization...").start(),m=(c||3)*1e3,g=Math.floor(s/(c||3)),b=0,f=!1,w=()=>{f=!0,a.stop(),console.log(p.yellow(`
|
|
11
|
+
|
|
12
|
+
\u26A0\uFE0F Login cancelled
|
|
13
|
+
`)),process.exit(0)};process.on("SIGINT",w);try{for(;b<g&&!f;){await me(m),b++;let y=await fetch(`${e}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:n})});if(y.status===202)continue;if(!y.ok){a.fail("Authorization failed");let h=await y.json();throw new Error(h.error||"Authorization failed")}let u=await y.json();if(u.status==="authorized"){a.succeed(p.white("Authorization successful!")),Y(u.token),M(u.user),u.proxyUrl&&Z(u.proxyUrl),u.mem0ProxyUrl&&G(u.mem0ProxyUrl),console.log(""),console.log(p.gray(`User: ${u.user.email}`));let h=j("Fetching projects...").start(),T=await ge(u.token);return h.succeed(`Fetched ${T.length} project${T.length!==1?"s":""}`),console.log(p.gray(`Session saved to: ~/.zibby/config.json
|
|
14
|
+
`)),{success:!0,loggedIn:!0,user:u.user,token:u.token}}if(u.status==="denied")throw a.fail("Authorization denied"),new Error("User denied authorization")}throw a.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",w)}}function me(e){return new Promise(o=>setTimeout(o,e))}function W(){try{let e=process.env.HOME||process.env.USERPROFILE;if(!e)return null;let o=be(e,".zibby","config.json");return ye(o)&&JSON.parse(he(o,"utf-8")).sessionToken||null}catch{return null}}function N(){console.log(`
|
|
15
|
+
Not authenticated.`),console.log(` Run ${C.cyan("zibby login")} or set ${C.cyan("ZIBBY_API_KEY")} in your environment.
|
|
16
|
+
`)}async function q(e={}){let o=e.apiKey||process.env.ZIBBY_API_KEY||null,t=W();if(t||o)return{sessionToken:t,apiKey:o};if(!process.stdin.isTTY){if(e.optional)return{sessionToken:null,apiKey:null};N(),process.exit(1)}console.log(C.yellow(`
|
|
17
|
+
Not logged in.`));let n;try{n=await we({message:"Open browser to log in now?",default:!0})}catch{n=!1}if(!n){if(e.optional)return{sessionToken:null,apiKey:null};N(),process.exit(1)}if(await H(),t=W(),!t){if(e.optional)return{sessionToken:null,apiKey:null};N(),process.exit(1)}return{sessionToken:t,apiKey:null}}function X(e){if(!e)return null;try{return JSON.parse(e)}catch{return{raw:e}}}async function Q(e){let{sessionToken:o,apiKey:t}=await q({apiKey:e?.apiKey}),n=o||t;return n||(console.error(Se.red("Not authenticated. Run `zibby login` or set ZIBBY_API_KEY.")),process.exit(1)),{"Content-Type":"application/json",Authorization:`Bearer ${n}`}}async function L(e,o,t){let n=I(),r=await fetch(`${n}${e}`,{method:"POST",headers:t,body:JSON.stringify(o)}),i=await r.text();return{status:r.status,body:X(i)}}async function ee(e,o){let t=I(),n=await fetch(`${t}${e}`,{method:"GET",headers:o}),r=await n.text();return{status:n.status,body:X(r)}}import oe from"node:fs";import P from"node:path";var bo=P.join(".zibby","app.json");function te(e,o={}){let t=P.join(P.resolve(e),".zibby");oe.mkdirSync(t,{recursive:!0});let n=P.join(t,"app.json"),r={appSlug:o.appSlug,deployMode:"solo",region:o.region||"",instanceId:o.instanceId||"",domain:o.domain||"",framework:o.framework||""};return oe.writeFileSync(n,`${JSON.stringify(r,null,2)}
|
|
18
|
+
`,"utf8"),{path:n,config:r}}function ke(e={},o={}){let t={};return e.slug?t.appSlug=String(e.slug):o.appSlug&&(t.appSlug=o.appSlug),e.repo?(t.source={type:"github",repo:String(e.repo)},e.ref&&(t.source.ref=String(e.ref))):e.tarball&&(t.source={type:"tarball",s3Url:String(e.tarball)}),e.framework&&(t.framework=String(e.framework)),e.tier&&(t.tier=String(e.tier)),e.region&&(t.region=String(e.region)),e.dbPersistence&&(t.persistence={...t.persistence||{},db:String(e.dbPersistence)}),e.filesPersistence&&(t.persistence={...t.persistence||{},files:String(e.filesPersistence)}),Array.isArray(e.secret)&&e.secret.length&&(t.secrets=e.secret.map(n=>{let r=n.indexOf("=");if(r<0)return{key:n};let i=n.slice(0,r),s=n.slice(r+1);return{key:i,valueRef:s}})),t}async function Ue(e,{rounds:o=4,timeoutMs:t=800}={}){let n=`ec2.${e}.amazonaws.com`,r=null;for(let i=0;i<o;i+=1){let s=await xe(n,443,t);s!=null&&(r==null||s<r)&&(r=s)}return r}function xe(e,o,t){return new Promise(n=>{let r=process.hrtime.bigint(),i=ve.connect({host:e,port:o}),s=!1,c=l=>{s||(s=!0,i.destroy(),n(l))};i.setTimeout(t),i.once("connect",()=>{let l=Number(process.hrtime.bigint()-r);c(l/1e6)}),i.once("timeout",()=>c(null)),i.once("error",()=>c(null))})}async function Te(e,{probe:o=Ue,defaultRegion:t}={}){let n=t||(e.find(c=>c.default)||e[0])?.id,r=await Promise.all(e.map(async c=>({id:c.id,rtt:await o(c.id)}))),i=new Map(r.map(c=>[c.id,c.rtt])),s=r.filter(c=>c.rtt!=null).sort((c,l)=>c.rtt-l.rtt);return{best:s.length?s[0].id:n,rtts:i}}function ne(e){return e==null?"\u2014":`${Math.round(e)}ms`}function Ae(e,o,t){let n=JSON.parse(JSON.stringify(e||{}));return o==="source"||o==="source.type"?(n.source={type:t},n):o==="source.repo"?(n.source={...n.source||{},type:"github",repo:t},n):o==="source.s3Url"?(n.source={...n.source||{},type:"tarball",s3Url:t},n):(n[o]=t,n)}function Pe(e=[],o=[]){let t=["Cannot proceed in --yes mode \u2014 the spec is incomplete:"];for(let n of e)t.push(` - ${n.field}: ${n.prompt}`);for(let n of o){let r=Array.isArray(n.options)?n.options.join(", "):"(see plan response)";t.push(` - ${n.field} (ambiguous): ${n.prompt} options=${r}`)}return t.push(""),t.push("Pass the missing flags (e.g. --repo, --tier) and re-run, or drop --yes to be prompted."),t.join(`
|
|
19
|
+
`)}async function $e(e,o,t){let{postPlan:n,prompt:r,yes:i}=t,s=e;for(let c=0;c<12;c+=1){let l=await n(s);if(l.status===402)return{complete:!1,exitCode:1,msg:l.body?.error||"Insufficient credits."};if(l.status>=400)return{complete:!1,exitCode:1,msg:l.body?.error||`Plan failed: HTTP ${l.status}`};let a=l.body||{};if(a.ok)return{complete:!0,spec:a.spec,costEstimate:a.costEstimate,summary:a.summary};if(a.spec&&(s=a.spec),a.insufficientCredits)return{complete:!1,exitCode:1,msg:`Insufficient credits \u2014 need ${a.insufficientCredits.neededMilliCents} mc, have ${a.insufficientCredits.balanceMilliCents} mc. ${a.insufficientCredits.hint||""}`};if(i)return{complete:!1,exitCode:1,msg:Pe(a.missingInputs,a.ambiguities)};let m=a.missingInputs&&a.missingInputs[0]||a.ambiguities&&a.ambiguities[0];if(!m)return{complete:!1,exitCode:1,msg:"Server reported ok:false but no missingInputs/ambiguities \u2014 likely a backend bug."};let g=await r(m);if(g==null||g==="")return{complete:!1,exitCode:1,msg:`Aborted at ${m.field}.`};s=Ae(s,m.field,g)}return{complete:!1,exitCode:1,msg:"Plan loop exceeded 12 iterations \u2014 bailing to avoid infinite prompt."}}async function Oe(e){let o=Array.isArray(e.options)&&e.options.length>0;if(e.field==="tier"&&o){let{value:n}=await k.prompt([{type:"list",name:"value",message:e.prompt,default:e.suggested||void 0,choices:e.options.map(r=>({name:r.label||r.id,value:r.id}))}]);return n}if(e.field==="source"||e.field==="source.type"){let{value:n}=await k.prompt([{type:"list",name:"value",message:e.prompt,choices:[{name:"GitHub repository (owner/name)",value:"github"},{name:"S3 tarball",value:"tarball"}]}]);return n}if(o){let{value:n}=await k.prompt([{type:"list",name:"value",message:e.prompt,choices:e.options.map(r=>typeof r=="string"?{name:r,value:r}:{name:r.label||r.id,value:r.id||r.value})}]);return n}let{value:t}=await k.prompt([{type:"input",name:"value",message:e.prompt}]);return String(t).trim()}async function $o(e={}){let o=ke(e,{});o.tier&&!O.includes(o.tier)&&(console.error(d.red(`Unknown --tier: ${o.tier}. Pick one of: ${O.join(", ")}`)),process.exit(1));let t=o.region==="auto";if(t&&(o.region=void 0),o.region&&!_.includes(o.region)&&(console.error(d.red(`Unknown --region: ${o.region}. Pick one of: ${_.join(", ")} (or "auto")`)),process.exit(1)),!o.region)if(e.yes&&!t)o.region=R;else{let f=$("Finding the nearest AWS region\u2026").start(),{best:w,rtts:y}=await Te(v,{defaultRegion:R});if(f.stop(),t)o.region=w,console.log(d.dim(`Auto-selected nearest region: ${w} (${ne(y.get(w))})`));else{let{value:u}=await k.prompt([{type:"list",name:"value",message:"Which AWS region should the VM run in? (control plane stays in Sydney; pricing is the same everywhere)",default:w,choices:v.map(h=>{let T=ne(y.get(h.id)),re=h.id===w?d.green(" \u2190 nearest"):"";return{name:`${h.name} (${h.id}) \xB7 ${T}${re}`,value:h.id}})}]);o.region=u}}let n=await Q(e),r=f=>L("/apps/solo/plan",f,n),i=$("Planning solo deploy\u2026").start(),s=await $e(o,e,{postPlan:r,prompt:Oe,yes:!!e.yes});if(i.stop(),!s.complete){console.error(d.red(s.msg)),process.exit(s.exitCode);return}if(console.log(""),console.log(s.summary||"(no summary)"),console.log(""),s.costEstimate?.monthlyUSD!=null&&console.log(d.gray(` Monthly cost (instance only): $${s.costEstimate.monthlyUSD} USD \u2014 ${s.costEstimate.detail}`)),console.log(""),!e.yes){let{proceed:f}=await k.prompt([{type:"confirm",name:"proceed",message:"Fire this deploy?",default:!0}]);if(!f){console.log(d.gray("Aborted."));return}}let c=$("Provisioning EC2 instance\u2026").start(),l=await L("/apps/solo/fire",s.spec,n);if(l.status===402){c.fail("Insufficient credits"),console.error(d.red(l.body?.error||"Insufficient credits.")),process.exit(1);return}if(l.status>=400){c.fail("Fire failed"),console.error(d.red(l.body?.error||`HTTP ${l.status}`)),Array.isArray(l.body?.missingInputs)&&console.error(" Server reports the spec is no longer complete \u2014 re-run without --yes to prompt."),process.exit(1);return}c.succeed("Instance launched");let{instanceId:a,deploymentId:m,domain:g}=l.body||{};console.log(""),a&&console.log(` instanceId: ${a}`),m&&console.log(` deploymentId: ${m}`),g&&console.log(` URL (once up): https://${g}`),console.log("");let b=s.spec||{};try{let{path:f}=te(process.cwd(),{appSlug:b.appSlug,deployMode:"solo",region:b.region,instanceId:a||"",domain:g||b.domain||"",framework:b.framework||"auto"});console.log(d.green(` Wrote ${Ie.relative(process.cwd(),f)||f} \u2014 commit it so your team can \`zibby app run\` without --app.`)),console.log("")}catch(f){console.log(d.yellow(` Could not write .zibby/app.json (${f.message}). Run \`zibby app link ${b.appSlug}\` later.`)),console.log("")}console.log(d.gray(` Watch: zibby app status ${s.spec.appSlug}`)),console.log(""),!e.yes&&!e.noTail&&await _e(s.spec.appSlug,n)}async function _e(e,o){let t=new Set(["running","failed","unknown"]),n=$("Waiting for bootstrap\u2026").start(),r=Date.now()+900*1e3;for(;Date.now()<r;){let i=await ee(`/apps/solo/${encodeURIComponent(e)}/status`,o),s=i.body?.phase||"unknown";if(n.text=`Phase: ${s}${i.body?.detail?` \u2014 ${i.body.detail}`:""}`,t.has(s)){s==="running"?n.succeed("Running."):s==="failed"?n.fail(`Failed: ${i.body?.detail||"unknown error"}`):n.stop();return}await new Promise(c=>setTimeout(c,5e3))}n.fail("Timed out waiting for bootstrap \u2014 run `zibby app status` to check.")}export{$o as appDeploySoloCommand,Q as authHeaders,ke as buildPartialSpec,Te as detectNearestRegion,Pe as formatMissingForNonInteractive,ee as getJson,Ae as mergeAnswer,$e as planAndPromptLoop,L as postJson,Ue as probeRegionRtt};
|
package/dist/commands/app.js
CHANGED
|
@@ -1,27 +1,29 @@
|
|
|
1
|
-
|
|
1
|
+
var Ee=Object.defineProperty;var S=(e,o)=>()=>(e&&(o=e(e=0)),o);var Oe=(e,o)=>{for(var t in o)Ee(e,t,{get:o[t],enumerable:!0})};function v(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";P[o]?e=P[o].apiUrl:e=P.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)`),P.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),P.prod.apiUrl}}var P,O=S(()=>{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"}}});import{existsSync as V,mkdirSync as je,readFileSync as _e,writeFileSync as Re}from"fs";import{homedir as W}from"os";import{join as j}from"path";function q(){return process.env.ZIBBY_CONFIG_DIR||j(W(),".zibby")}function Q(){return j(q(),"config.json")}function Le(){let e=q();V(e)||je(e,{recursive:!0})}function T(){try{let e=Q();if(V(e)){let o=_e(e,"utf-8");return JSON.parse(o)}}catch{}return{}}function C(e){Le(),Re(Q(),JSON.stringify(e,null,2))}function X(){return T().sessionToken||null}function ee(e){let o=T();o.sessionToken=e,C(o)}function oe(){return T().user||null}function te(e){let o=T();o.user=e,C(o)}function re(e){let o=T();o.proxyUrl=e,C(o)}function ne(e){let o=T();o.mem0ProxyUrl=e,C(o)}function se(e){let o=T();o.projects=e,C(o)}var Ne,co,ie=S(()=>{Ne=j(W(),".zibby"),co=j(Ne,"config.json")});import{existsSync as uo,mkdirSync as go,readFileSync as fo,writeFileSync as mo,unlinkSync as yo}from"fs";import{resolve as bo}from"path";import{homedir as $o}from"os";var ae=S(()=>{});import g from"chalk";import z from"ora";import{spawn as Be}from"child_process";function ze(e){let o=process.platform;try{let t,r;return o==="darwin"?(t="open",r=[e]):o==="win32"?(t="cmd",r=["/c","start","",e]):(t="xdg-open",r=[e]),Be(t,r,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function De(){let e=X(),o=oe();return e&&o?{loggedIn:!0,user:o,token:e}:{loggedIn:!1}}async function le(){try{console.log(g.cyan(`
|
|
2
2
|
\u{1F510} Initiating login...
|
|
3
|
-
`));let
|
|
4
|
-
`));let{createInterface:
|
|
3
|
+
`));let e=De();if(e.loggedIn){console.log(g.green("\u2705 Already logged in!")),console.log(g.gray(`User: ${e.user.email}`)),console.log(g.gray(`Name: ${e.user.name}
|
|
4
|
+
`));let{createInterface:o}=await import("readline"),t=o({input:process.stdin,output:process.stdout});return new Promise((r,n)=>{let i=()=>{t.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},s=()=>{console.log(g.yellow(`
|
|
5
5
|
|
|
6
6
|
\u26A0\uFE0F Login cancelled
|
|
7
|
-
`)),
|
|
8
|
-
`));let
|
|
9
|
-
`)),
|
|
10
|
-
\u274C Login failed:`,
|
|
7
|
+
`)),i(),process.exit(0)};process.on("SIGINT",s),t.question(g.yellow("Continue with this session? (Y/n): "),async l=>{process.removeListener("SIGINT",s),i();try{if(l.toLowerCase()==="n"||l.toLowerCase()==="no"){console.log(g.gray(`Starting new login...
|
|
8
|
+
`));let a=await ce();r(a)}else console.log(g.green(`Using existing session.
|
|
9
|
+
`)),r({success:!0,...e})}catch(a){n(a)}})})}return await ce()}catch(e){return console.error(g.red(`
|
|
10
|
+
\u274C Login failed:`,e.message)),{success:!1,error:e.message}}}async function Me(e){let o=v();try{let t=await fetch(`${o}/projects`,{headers:{Authorization:`Bearer ${e}`}});if(t.ok){let n=((await t.json()).projects||[]).map(i=>({name:i.name,projectId:i.projectId,apiToken:i.apiToken}));return se(n),n}}catch(t){console.log(g.gray(`\u26A0\uFE0F Could not fetch projects: ${t.message}`))}return[]}async function ce(){let e=v(),o=z("Requesting login code...").start(),t=await fetch(`${e}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){o.fail("Failed to request login code");let w=await t.json();throw new Error(w.error||"Failed to initiate login")}let{deviceCode:r,userCode:n,verificationUrl:i,expiresIn:s,interval:l}=await t.json();o.succeed("Login code generated"),console.log(""),console.log(g.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(g.cyan("\u2551")+g.white.bold(" Complete login in your browser ")+g.cyan("\u2551")),console.log(g.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(g.white("Opening browser to login page...")),console.log(g.gray(`Code expires in ${Math.floor(s/60)} minutes`)),console.log(""),await ze(i)||(console.log(g.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(g.white("Please open this URL manually: ")+g.blue(i)),console.log(""));let u=z("Waiting for authorization...").start(),d=(l||3)*1e3,p=Math.floor(s/(l||3)),f=0,m=!1,k=()=>{m=!0,u.stop(),console.log(g.yellow(`
|
|
11
11
|
|
|
12
12
|
\u26A0\uFE0F Login cancelled
|
|
13
|
-
`)),process.exit(0)};process.on("SIGINT",
|
|
14
|
-
`)),{success:!0,loggedIn:!0,user:
|
|
15
|
-
Not authenticated.`),console.log(` Run ${
|
|
16
|
-
`)}async function
|
|
17
|
-
Not logged in.`));let
|
|
13
|
+
`)),process.exit(0)};process.on("SIGINT",k);try{for(;f<p&&!m;){await Fe(d),f++;let w=await fetch(`${e}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:r})});if(w.status===202)continue;if(!w.ok){u.fail("Authorization failed");let $=await w.json();throw new Error($.error||"Authorization failed")}let y=await w.json();if(y.status==="authorized"){u.succeed(g.white("Authorization successful!")),ee(y.token),te(y.user),y.proxyUrl&&re(y.proxyUrl),y.mem0ProxyUrl&&ne(y.mem0ProxyUrl),console.log(""),console.log(g.gray(`User: ${y.user.email}`));let $=z("Fetching projects...").start(),E=await Me(y.token);return $.succeed(`Fetched ${E.length} project${E.length!==1?"s":""}`),console.log(g.gray(`Session saved to: ~/.zibby/config.json
|
|
14
|
+
`)),{success:!0,loggedIn:!0,user:y.user,token:y.token}}if(y.status==="denied")throw u.fail("Authorization denied"),new Error("User denied authorization")}throw u.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",k)}}function Fe(e){return new Promise(o=>setTimeout(o,e))}var pe=S(()=>{O();ie();ae()});import{existsSync as Ye,readFileSync as Ze}from"fs";import{join as Je}from"path";import M from"chalk";import{confirm as Ge}from"@inquirer/prompts";function ue(){try{let e=process.env.HOME||process.env.USERPROFILE;if(!e)return null;let o=Je(e,".zibby","config.json");return Ye(o)&&JSON.parse(Ze(o,"utf-8")).sessionToken||null}catch{return null}}function D(){console.log(`
|
|
15
|
+
Not authenticated.`),console.log(` Run ${M.cyan("zibby login")} or set ${M.cyan("ZIBBY_API_KEY")} in your environment.
|
|
16
|
+
`)}async function _(e={}){let o=e.apiKey||process.env.ZIBBY_API_KEY||null,t=ue();if(t||o)return{sessionToken:t,apiKey:o};if(!process.stdin.isTTY){if(e.optional)return{sessionToken:null,apiKey:null};D(),process.exit(1)}console.log(M.yellow(`
|
|
17
|
+
Not logged in.`));let r;try{r=await Ge({message:"Open browser to log in now?",default:!0})}catch{r=!1}if(!r){if(e.optional)return{sessionToken:null,apiKey:null};D(),process.exit(1)}if(await le(),t=ue(),!t){if(e.optional)return{sessionToken:null,apiKey:null};D(),process.exit(1)}return{sessionToken:t,apiKey:null}}var F=S(()=>{pe()});var He,Y,I,Z,J,de=S(()=>{He=[{id:"micro",instanceType:"t4g.nano",vCpu:2,ramGB:.5,priceUSD:6},{id:"small",instanceType:"t4g.micro",vCpu:2,ramGB:1,priceUSD:10},{id:"medium",instanceType:"t4g.small",vCpu:2,ramGB:2,priceUSD:18},{id:"large",instanceType:"t4g.medium",vCpu:2,ramGB:4,priceUSD:32}],Y=He.map(e=>e.id),I=[{id:"ap-southeast-2",name:"Sydney",default:!0},{id:"us-east-1",name:"N. Virginia"},{id:"us-west-2",name:"Oregon"},{id:"eu-west-1",name:"Ireland"},{id:"ap-northeast-1",name:"Tokyo"}],Z=I.map(e=>e.id),J=(I.find(e=>e.default)||I[0]).id});import Ke from"chalk";function ge(e){if(!e)return null;try{return JSON.parse(e)}catch{return{raw:e}}}async function G(e){let{sessionToken:o,apiKey:t}=await _({apiKey:e?.apiKey}),r=o||t;return r||(console.error(Ke.red("Not authenticated. Run `zibby login` or set ZIBBY_API_KEY.")),process.exit(1)),{"Content-Type":"application/json",Authorization:`Bearer ${r}`}}async function R(e,o,t){let r=v(),n=await fetch(`${r}${e}`,{method:"POST",headers:t,body:JSON.stringify(o)}),i=await n.text();return{status:n.status,body:ge(i)}}async function H(e,o){let t=v(),r=await fetch(`${t}${e}`,{method:"GET",headers:o}),n=await r.text();return{status:r.status,body:ge(n)}}var fe=S(()=>{F();O()});import me from"node:fs";import N from"node:path";function ye(e,o={}){let t=N.join(N.resolve(e),".zibby");me.mkdirSync(t,{recursive:!0});let r=N.join(t,"app.json"),n={appSlug:o.appSlug,deployMode:"solo",region:o.region||"",instanceId:o.instanceId||"",domain:o.domain||"",framework:o.framework||""};return me.writeFileSync(r,`${JSON.stringify(n,null,2)}
|
|
18
|
+
`,"utf8"),{path:r,config:n}}var Zo,he=S(()=>{Zo=N.join(".zibby","app.json")});var Ae={};Oe(Ae,{appDeploySoloCommand:()=>Xe,authHeaders:()=>G,buildPartialSpec:()=>we,detectNearestRegion:()=>Se,formatMissingForNonInteractive:()=>ke,getJson:()=>H,mergeAnswer:()=>xe,planAndPromptLoop:()=>ve,postJson:()=>R,probeRegionRtt:()=>$e});import Ve from"node:net";import We from"node:path";import h from"chalk";import L from"ora";import U from"inquirer";function we(e={},o={}){let t={};return e.slug?t.appSlug=String(e.slug):o.appSlug&&(t.appSlug=o.appSlug),e.repo?(t.source={type:"github",repo:String(e.repo)},e.ref&&(t.source.ref=String(e.ref))):e.tarball&&(t.source={type:"tarball",s3Url:String(e.tarball)}),e.framework&&(t.framework=String(e.framework)),e.tier&&(t.tier=String(e.tier)),e.region&&(t.region=String(e.region)),e.dbPersistence&&(t.persistence={...t.persistence||{},db:String(e.dbPersistence)}),e.filesPersistence&&(t.persistence={...t.persistence||{},files:String(e.filesPersistence)}),Array.isArray(e.secret)&&e.secret.length&&(t.secrets=e.secret.map(r=>{let n=r.indexOf("=");if(n<0)return{key:r};let i=r.slice(0,n),s=r.slice(n+1);return{key:i,valueRef:s}})),t}async function $e(e,{rounds:o=4,timeoutMs:t=800}={}){let r=`ec2.${e}.amazonaws.com`,n=null;for(let i=0;i<o;i+=1){let s=await qe(r,443,t);s!=null&&(n==null||s<n)&&(n=s)}return n}function qe(e,o,t){return new Promise(r=>{let n=process.hrtime.bigint(),i=Ve.connect({host:e,port:o}),s=!1,l=a=>{s||(s=!0,i.destroy(),r(a))};i.setTimeout(t),i.once("connect",()=>{let a=Number(process.hrtime.bigint()-n);l(a/1e6)}),i.once("timeout",()=>l(null)),i.once("error",()=>l(null))})}async function Se(e,{probe:o=$e,defaultRegion:t}={}){let r=t||(e.find(l=>l.default)||e[0])?.id,n=await Promise.all(e.map(async l=>({id:l.id,rtt:await o(l.id)}))),i=new Map(n.map(l=>[l.id,l.rtt])),s=n.filter(l=>l.rtt!=null).sort((l,a)=>l.rtt-a.rtt);return{best:s.length?s[0].id:r,rtts:i}}function be(e){return e==null?"\u2014":`${Math.round(e)}ms`}function xe(e,o,t){let r=JSON.parse(JSON.stringify(e||{}));return o==="source"||o==="source.type"?(r.source={type:t},r):o==="source.repo"?(r.source={...r.source||{},type:"github",repo:t},r):o==="source.s3Url"?(r.source={...r.source||{},type:"tarball",s3Url:t},r):(r[o]=t,r)}function ke(e=[],o=[]){let t=["Cannot proceed in --yes mode \u2014 the spec is incomplete:"];for(let r of e)t.push(` - ${r.field}: ${r.prompt}`);for(let r of o){let n=Array.isArray(r.options)?r.options.join(", "):"(see plan response)";t.push(` - ${r.field} (ambiguous): ${r.prompt} options=${n}`)}return t.push(""),t.push("Pass the missing flags (e.g. --repo, --tier) and re-run, or drop --yes to be prompted."),t.join(`
|
|
19
|
+
`)}async function ve(e,o,t){let{postPlan:r,prompt:n,yes:i}=t,s=e;for(let l=0;l<12;l+=1){let a=await r(s);if(a.status===402)return{complete:!1,exitCode:1,msg:a.body?.error||"Insufficient credits."};if(a.status>=400)return{complete:!1,exitCode:1,msg:a.body?.error||`Plan failed: HTTP ${a.status}`};let u=a.body||{};if(u.ok)return{complete:!0,spec:u.spec,costEstimate:u.costEstimate,summary:u.summary};if(u.spec&&(s=u.spec),u.insufficientCredits)return{complete:!1,exitCode:1,msg:`Insufficient credits \u2014 need ${u.insufficientCredits.neededMilliCents} mc, have ${u.insufficientCredits.balanceMilliCents} mc. ${u.insufficientCredits.hint||""}`};if(i)return{complete:!1,exitCode:1,msg:ke(u.missingInputs,u.ambiguities)};let d=u.missingInputs&&u.missingInputs[0]||u.ambiguities&&u.ambiguities[0];if(!d)return{complete:!1,exitCode:1,msg:"Server reported ok:false but no missingInputs/ambiguities \u2014 likely a backend bug."};let p=await n(d);if(p==null||p==="")return{complete:!1,exitCode:1,msg:`Aborted at ${d.field}.`};s=xe(s,d.field,p)}return{complete:!1,exitCode:1,msg:"Plan loop exceeded 12 iterations \u2014 bailing to avoid infinite prompt."}}async function Qe(e){let o=Array.isArray(e.options)&&e.options.length>0;if(e.field==="tier"&&o){let{value:r}=await U.prompt([{type:"list",name:"value",message:e.prompt,default:e.suggested||void 0,choices:e.options.map(n=>({name:n.label||n.id,value:n.id}))}]);return r}if(e.field==="source"||e.field==="source.type"){let{value:r}=await U.prompt([{type:"list",name:"value",message:e.prompt,choices:[{name:"GitHub repository (owner/name)",value:"github"},{name:"S3 tarball",value:"tarball"}]}]);return r}if(o){let{value:r}=await U.prompt([{type:"list",name:"value",message:e.prompt,choices:e.options.map(n=>typeof n=="string"?{name:n,value:n}:{name:n.label||n.id,value:n.id||n.value})}]);return r}let{value:t}=await U.prompt([{type:"input",name:"value",message:e.prompt}]);return String(t).trim()}async function Xe(e={}){let o=we(e,{});o.tier&&!Y.includes(o.tier)&&(console.error(h.red(`Unknown --tier: ${o.tier}. Pick one of: ${Y.join(", ")}`)),process.exit(1));let t=o.region==="auto";if(t&&(o.region=void 0),o.region&&!Z.includes(o.region)&&(console.error(h.red(`Unknown --region: ${o.region}. Pick one of: ${Z.join(", ")} (or "auto")`)),process.exit(1)),!o.region)if(e.yes&&!t)o.region=J;else{let m=L("Finding the nearest AWS region\u2026").start(),{best:k,rtts:w}=await Se(I,{defaultRegion:J});if(m.stop(),t)o.region=k,console.log(h.dim(`Auto-selected nearest region: ${k} (${be(w.get(k))})`));else{let{value:y}=await U.prompt([{type:"list",name:"value",message:"Which AWS region should the VM run in? (control plane stays in Sydney; pricing is the same everywhere)",default:k,choices:I.map($=>{let E=be(w.get($.id)),Ce=$.id===k?h.green(" \u2190 nearest"):"";return{name:`${$.name} (${$.id}) \xB7 ${E}${Ce}`,value:$.id}})}]);o.region=y}}let r=await G(e),n=m=>R("/apps/solo/plan",m,r),i=L("Planning solo deploy\u2026").start(),s=await ve(o,e,{postPlan:n,prompt:Qe,yes:!!e.yes});if(i.stop(),!s.complete){console.error(h.red(s.msg)),process.exit(s.exitCode);return}if(console.log(""),console.log(s.summary||"(no summary)"),console.log(""),s.costEstimate?.monthlyUSD!=null&&console.log(h.gray(` Monthly cost (instance only): $${s.costEstimate.monthlyUSD} USD \u2014 ${s.costEstimate.detail}`)),console.log(""),!e.yes){let{proceed:m}=await U.prompt([{type:"confirm",name:"proceed",message:"Fire this deploy?",default:!0}]);if(!m){console.log(h.gray("Aborted."));return}}let l=L("Provisioning EC2 instance\u2026").start(),a=await R("/apps/solo/fire",s.spec,r);if(a.status===402){l.fail("Insufficient credits"),console.error(h.red(a.body?.error||"Insufficient credits.")),process.exit(1);return}if(a.status>=400){l.fail("Fire failed"),console.error(h.red(a.body?.error||`HTTP ${a.status}`)),Array.isArray(a.body?.missingInputs)&&console.error(" Server reports the spec is no longer complete \u2014 re-run without --yes to prompt."),process.exit(1);return}l.succeed("Instance launched");let{instanceId:u,deploymentId:d,domain:p}=a.body||{};console.log(""),u&&console.log(` instanceId: ${u}`),d&&console.log(` deploymentId: ${d}`),p&&console.log(` URL (once up): https://${p}`),console.log("");let f=s.spec||{};try{let{path:m}=ye(process.cwd(),{appSlug:f.appSlug,deployMode:"solo",region:f.region,instanceId:u||"",domain:p||f.domain||"",framework:f.framework||"auto"});console.log(h.green(` Wrote ${We.relative(process.cwd(),m)||m} \u2014 commit it so your team can \`zibby app run\` without --app.`)),console.log("")}catch(m){console.log(h.yellow(` Could not write .zibby/app.json (${m.message}). Run \`zibby app link ${f.appSlug}\` later.`)),console.log("")}console.log(h.gray(` Watch: zibby app status ${s.spec.appSlug}`)),console.log(""),!e.yes&&!e.noTail&&await eo(s.spec.appSlug,r)}async function eo(e,o){let t=new Set(["running","failed","unknown"]),r=L("Waiting for bootstrap\u2026").start(),n=Date.now()+900*1e3;for(;Date.now()<n;){let i=await H(`/apps/solo/${encodeURIComponent(e)}/status`,o),s=i.body?.phase||"unknown";if(r.text=`Phase: ${s}${i.body?.detail?` \u2014 ${i.body.detail}`:""}`,t.has(s)){s==="running"?r.succeed("Running."):s==="failed"?r.fail(`Failed: ${i.body?.detail||"unknown error"}`):r.stop();return}await new Promise(l=>setTimeout(l,5e3))}r.fail("Timed out waiting for bootstrap \u2014 run `zibby app status` to check.")}var Te=S(()=>{de();fe();he()});F();O();import c from"chalk";import x from"ora";import K from"inquirer";import oo from"dotenv";oo.config();async function A(e){let{sessionToken:o,apiKey:t}=await _({apiKey:e?.apiKey}),r=o||t;return r||(console.error(c.red("Not authenticated. Run `zibby login` or set ZIBBY_API_KEY.")),process.exit(1)),{"Content-Type":"application/json",Authorization:`Bearer ${r}`}}async function b(e,o,{quiet:t=!1}={}){let n=`${v()}${e}`,i=await fetch(n,o),s=await i.text(),l=null;try{l=s?JSON.parse(s):null}catch{l={raw:s}}if(!i.ok){let a=l?.error||l?.message||`HTTP ${i.status}`;t||(l?.code==="CLAUDE_CREDENTIAL_REQUIRED"?(console.error(c.red("\xD7 Connect your Claude Code subscription first.")),console.error(""),console.error(c.white(" Run:")),console.error(c.cyan(" claude setup-token # mints a long-lived OAuth token")),console.error(c.cyan(" zibby creds set claude <token>")),console.error(""),console.error(c.gray(" Or paste an Anthropic API key:")),console.error(c.cyan(" zibby creds set claude sk-ant-api03-...")),console.error("")):l?.code==="OPENAI_CREDENTIAL_REQUIRED"?(console.error(c.red("\xD7 Connect your OpenAI API key to deploy with Codex.")),console.error(""),console.error(c.white(" Run:")),console.error(c.cyan(" zibby creds set openai sk-...")),console.error(""),console.error(c.gray(" Mint one at: https://platform.openai.com/api-keys")),console.error(c.gray(" Or paste at: https://zibby.dev/integrations")),console.error("")):(console.error(c.red(`\xD7 ${a}`)),l?.detail&&console.error(c.gray(` ${l.detail}`))));let u=new Error(a);throw u.status=i.status,u.body=l,u.code=l?.code||null,u}return l}function Pe(e){return" "+e.map(o=>"\u2500".repeat(o)).join(" ")}function B(e,o){return" "+e.map((t,r)=>String(t??"").padEnd(o[r])).join(" ")}async function at(e={}){let o=x("Loading app catalog\u2026").start();try{let t=await b("/apps/catalog",{method:"GET"});o.stop();let r=Array.isArray(t?.items)?t.items:[];if(r.length===0)return console.log(`
|
|
18
20
|
No apps available in the catalog.
|
|
19
|
-
`),[];if(
|
|
20
|
-
App Catalog (${
|
|
21
|
-
`),console.log(
|
|
21
|
+
`),[];if(e.quiet)return r;let n=r.map(s=>({appType:String(s.appType||""),version:`v${s.appVersion||s.app?.version||"?"}`,tier:String(s.pricing?.tier||"standard"),arch:Array.isArray(s.architectures)&&s.architectures.length?s.architectures.join(","):"x86_64",tagline:(s.tagline||"").slice(0,40)})),i=[Math.max(7,...n.map(s=>s.appType.length)),Math.max(7,...n.map(s=>s.version.length)),Math.max(4,...n.map(s=>s.tier.length)),Math.max(13,...n.map(s=>s.arch.length)),Math.max(7,...n.map(s=>s.tagline.length))];console.log(`
|
|
22
|
+
App Catalog (${r.length})
|
|
23
|
+
`),console.log(B(["AppType","Version","Tier","Architectures","Tagline"],i)),console.log(Pe(i));for(let s of n)console.log(B([s.appType,s.version,s.tier,s.arch,s.tagline],i));return console.log(""),console.log(" Deploy with: zibby app deploy <appType> --project <projectId>"),console.log(" ARM64 (~20% greener, same price): zibby app deploy <appType> --project <id> --arch arm64"),console.log(""),r}catch(t){o.fail("Failed to load catalog"),t.status&&console.error(` HTTP ${t.status}`),process.exit(1)}}async function ct(e={}){let o=await A(e),t=x("Fetching deployed apps\u2026").start();try{let r=e.project?`?projectId=${encodeURIComponent(e.project)}`:"",n=await b(`/apps${r}`,{method:"GET",headers:o});t.stop();let i=Array.isArray(n?.apps)?n.apps:[];if(e.quiet)return i;if(i.length===0)return console.log(`
|
|
22
24
|
No apps deployed.`),console.log(` Deploy one with: zibby app deploy <appType> --project <projectId>
|
|
23
|
-
`),[];let
|
|
24
|
-
Deployed Apps (${
|
|
25
|
-
`),console.log(U(["Instance","Name","App","Arch","Status","Project"],p)),console.log(G(p));for(let r of a)console.log(U([r.instance,r.name,r.app,r.arch,r.status,r.project],p));return console.log(""),t}catch{i.fail("Failed to list apps"),process.exit(1)}}async function ge(o){let e=m("Fetching projects\u2026").start(),i=await y("/projects",{method:"GET",headers:o});e.stop();let c=Array.isArray(i)?i:i?.projects||i?.data||[];c.length||(console.error(s.red("No projects found. Create one in the dashboard first.")),process.exit(1));let{projectId:n}=await C.prompt([{type:"list",name:"projectId",message:"Which project should this app deploy into?",choices:c.map(t=>({name:`${t.name||"Unnamed"} (${t.projectId||t.id})`,value:t.projectId||t.id}))}]);return n}async function eo(o,e={}){let i=e.goal;o&&i&&(console.error(s.red("Pass either appType (catalog id) OR --goal (free-form description), not both.")),process.exit(1)),!o&&!i&&(console.error(s.red("Missing target.")),console.error(s.gray(" Pass appType to deploy from catalog (see `zibby app templates`)")),console.error(s.gray(' OR --goal "<description>" to describe a custom install.')),process.exit(1));let c=await w(e),n=e.project;n||(n=await ge(c));let t=i?{goal:i,projectId:n}:{appType:o,projectId:n};e.name&&(t.name=e.name),e.provider&&(e.provider!=="claude"&&e.provider!=="codex"&&(console.error(s.red(`Unknown --provider: ${e.provider}`)),console.error(s.gray(" Pick claude (Anthropic) or codex (OpenAI).")),process.exit(1)),t.provider=e.provider),e.model!==void 0&&((typeof e.model!="string"||!e.model.trim())&&(console.error(s.red("--model requires a non-empty model identifier (e.g. claude-sonnet-4-6).")),process.exit(1)),t.model=e.model.trim());let a=process.env.ZIBBY_ANTHROPIC_TOKEN,p=e.anthropicToken||a||null;if(p&&((typeof p!="string"||!/^sk-ant-(oat01|api03)-/.test(p))&&(console.error(s.red("--anthropic-token must start with sk-ant-oat01- (OAuth) or sk-ant-api03- (API key).")),process.exit(1)),t.anthropicToken=p),e.maxTurns!==void 0){let l=Number(e.maxTurns);(!Number.isInteger(l)||l<1||l>200)&&(console.error(s.red("--max-turns must be an integer between 1 and 200.")),process.exit(1)),t.maxTurns=l}if(e.timeoutMin!==void 0){let l=Number(e.timeoutMin);(!Number.isInteger(l)||l<1||l>120)&&(console.error(s.red("--timeout-min must be an integer between 1 and 120 (minutes).")),process.exit(1)),t.timeoutMin=l}if(e.arch&&(e.arch!=="x86_64"&&e.arch!=="arm64"&&(console.error(s.red(`Unknown --arch: ${e.arch}`)),console.error(s.gray(" Pick x86_64 (Intel/AMD) or arm64 (Graviton, ~20% greener at the same price).")),process.exit(1)),t.architecture=e.arch),e.authType){if(["basic","token","none"].includes(e.authType)||(console.error(s.red(`Unknown --auth-type: ${e.authType}`)),console.error(s.gray(" Pick basic (user + password), token (bearer header), or none.")),process.exit(1)),t.authType=e.authType,e.authType==="basic"){let l=e.authUser;(!l||typeof l!="string"||!/^[\x21-\x7e]{1,64}$/.test(l))&&(console.error(s.red("--auth-type basic requires --auth-user <name> (1-64 printable ASCII, no spaces).")),process.exit(1)),t.authUser=l;let f=e.authPassword||process.env.ZIBBY_APP_AUTH_PASSWORD||"";(!f||f.length<8||f.length>256)&&(console.error(s.red("--auth-type basic requires --auth-password (8-256 chars). Env equivalent: ZIBBY_APP_AUTH_PASSWORD.")),process.exit(1)),t.authPassword=f}else if(e.authType==="token"){let l=e.authToken||process.env.ZIBBY_APP_AUTH_TOKEN||null;l&&((l.length<16||l.length>128||!/^[A-Za-z0-9_-]+$/.test(l))&&(console.error(s.red("--auth-token must be 16-128 chars, base64url alphabet only ([A-Za-z0-9_-]).")),process.exit(1)),t.authToken=l)}}let r=[];e.provider&&r.push(e.provider),e.arch&&r.push(e.arch);let d=o||(i.length>60?`${i.slice(0,60).trim()}\u2026`:i),g=m(`Deploying ${d}${r.length?` (${r.join(", ")})`:""}\u2026`).start();try{let l=await y("/apps/deploy",{method:"POST",headers:c,body:JSON.stringify(t)});g.succeed(`Deployed ${d}`);let f=l?.instanceId,$=l?.url||(l?.subdomain?`https://${l.subdomain}`:null);return console.log(),f&&console.log(` instanceId: ${f}`),$&&console.log(` public URL: ${$}`),l?.architecture&&console.log(` architecture: ${l.architecture}`),l?.auth&&(l.auth.type==="basic"?console.log(` auth: basic (user: ${l.auth.user})`):l.auth.type==="token"&&(l.auth.token?(console.log(" auth: token (auto-generated)"),console.log(),console.log(s.yellow(" \u250C\u2500\u2500\u2500 SAVE THIS TOKEN \u2014 shown ONCE, never again \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510")),console.log(s.yellow(` \u2502 ${l.auth.token}`)),console.log(s.yellow(" \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")),console.log(),console.log(s.gray(` Use it in requests: curl -H 'Authorization: Bearer ${l.auth.token}' ${$}`))):console.log(` auth: token (ends \u2026${l.auth.tokenLast4||"????"})`))),f&&(console.log(),console.log(` Watch status: zibby app status ${f}`)),console.log(),l}catch(l){g.fail(`Deploy failed: ${l.message}`),process.exit(1)}}async function oo(o,e={}){o||(console.error(s.red("Missing <instanceId>.")),process.exit(1));let i=await w(e),c=m(`Fetching ${o}\u2026`).start();try{let n=await y(`/apps/${encodeURIComponent(o)}`,{method:"GET",headers:i});if(c.stop(),e.quiet)return n;let t=n.url||(n.subdomain?`https://${n.subdomain}`:null);if(console.log(),console.log(` ${n.name||n.appType||o}`),console.log(),console.log(` status ${n.status||"unknown"}`),typeof n.runningCount=="number"&&console.log(` running ${n.runningCount} / ${n.desiredCount??1}`),console.log(` app ${n.appType}${n.appVersion?` v${n.appVersion}`:""}`),n.resources?.cpu&&n.resources?.memory){let a=(n.resources.cpu/1024).toFixed(2),p=(n.resources.memory/1024).toFixed(2);console.log(` resources ${a} vCPU \xB7 ${p} GB RAM`)}if(n.architecture&&console.log(` arch ${n.architecture}`),n.projectId&&console.log(` project ${n.projectId}`),t&&console.log(` public URL ${t}`),n.createdAt&&console.log(` created ${n.createdAt}`),Array.isArray(n.containers)&&n.containers.length>1){console.log(),console.log(" services");let a=n.containers.map(r=>[r.name||"?",r.lastStatus||"\u2014",r.healthStatus||"\u2014",r.exitCode!==null&&r.exitCode!==void 0?String(r.exitCode):"\u2014"]),p=[Math.max(7,...a.map(r=>r[0].length)),Math.max(6,...a.map(r=>r[1].length)),Math.max(6,...a.map(r=>r[2].length))];console.log(` ${"NAME".padEnd(p[0])} ${"STATUS".padEnd(p[1])} ${"HEALTH".padEnd(p[2])} EXIT`);for(let r of a)console.log(` ${r[0].padEnd(p[0])} ${r[1].padEnd(p[1])} ${r[2].padEnd(p[2])} ${r[3]}`)}return console.log(),n}catch(n){c.fail(`Could not fetch ${o}`),n.status===404&&console.error(s.gray(" Instance not found \u2014 it may have been destroyed.")),process.exit(1)}}async function to(o,e={}){o||(console.error(s.red("Missing <instanceId>.")),process.exit(1));let i=await w(e);if(!e.yes){let{confirm:n}=await C.prompt([{type:"confirm",name:"confirm",message:`Destroy app ${o}? The running task will be stopped.`,default:!1}]);if(!n){console.log(s.gray("Aborted."));return}}let c=m(`Destroying ${o}\u2026`).start();try{await y(`/apps/${encodeURIComponent(o)}`,{method:"DELETE",headers:i,body:JSON.stringify({confirm:!0})}),c.succeed(`Destroyed ${o}`)}catch(n){c.fail(`Destroy failed: ${n.message}`),process.exit(1)}}async function no(o,e={}){o||(console.error(s.red("Missing <instanceId>.")),process.exit(1));let i=await w(e);if(!e.yes){let{confirm:t}=await C.prompt([{type:"confirm",name:"confirm",message:e.version?`Upgrade ${o} to ghcr.io/zibbyhq/agent-ops:${e.version}? EFS data is preserved.`:`Upgrade ${o} to the latest base image? EFS data is preserved.`,default:!0}]);if(!t){console.log(s.gray("Aborted."));return}}let c=e.version?`?version=${encodeURIComponent(e.version)}`:"",n=m(`Upgrading ${o}\u2026`).start();try{let t=await y(`/apps/${encodeURIComponent(o)}/upgrade${c}`,{method:"POST",headers:i});n.succeed(`Upgrade rolling out for ${o}`),console.log(),console.log(` taskDefinitionArn: ${t?.taskDefinitionArn||"\u2014"}`),t?.imageOverride&&console.log(` image: ${t.imageOverride}`),console.log(),console.log(s.gray(" ECS rolls the service: new task pulls image, then swaps over. EFS data preserved.")),console.log(s.gray(` Watch: zibby app status ${o}`)),console.log()}catch(t){n.fail(`Upgrade failed: ${t.message}`),process.exit(1)}}async function ro(o,e={}){o||(console.error(s.red("Missing <instanceId>.")),process.exit(1));let i=await w(e),c=m(`Rotating Claude credential on ${o}\u2026`).start();try{let n=await y(`/apps/${encodeURIComponent(o)}/credentials`,{method:"POST",headers:i,body:"{}"});c.succeed(`Credential update rolling out for ${o}`),console.log(),console.log(` mode ${n?.mode||"\u2014"}`),console.log(` taskDefinitionArn ${n?.taskDefinitionArn||"\u2014"}`),console.log(),console.log(s.gray(" ECS rolls the service: new task pulls the new env, swaps over once healthy.")),console.log(s.gray(` Watch: zibby app status ${o}`)),console.log()}catch(n){c.fail(`Credential update failed: ${n.message}`),process.exit(1)}}async function so(o,e={}){o||(console.error(s.red("Missing <instanceId>.")),process.exit(1));let i=await w(e),c={};if(e.off)c.authType="none";else{e.authType!==void 0&&(["basic","token","none"].includes(e.authType)||(console.error(s.red(`Unknown --auth-type: ${e.authType}`)),console.error(s.gray(" Pick basic, token, none \u2014 or pass --off.")),process.exit(1)),c.authType=e.authType),e.authUser!==void 0&&((typeof e.authUser!="string"||!/^[\x21-\x7e]{1,64}$/.test(e.authUser))&&(console.error(s.red("--auth-user must be 1-64 printable ASCII chars (no spaces).")),process.exit(1)),c.authUser=e.authUser);let t=e.authPassword||process.env.ZIBBY_APP_AUTH_PASSWORD||null;t&&((t.length<8||t.length>256)&&(console.error(s.red("--auth-password must be 8-256 chars.")),process.exit(1)),c.authPassword=t);let a=e.authToken||process.env.ZIBBY_APP_AUTH_TOKEN||null;a&&((a.length<16||a.length>128||!/^[A-Za-z0-9_-]+$/.test(a))&&(console.error(s.red("--auth-token must be 16-128 chars, base64url alphabet ([A-Za-z0-9_-]).")),process.exit(1)),c.authToken=a)}Object.keys(c).length===0&&(console.error(s.red("Nothing to do \u2014 pass at least one of --auth-type / --auth-user / --auth-password / --auth-token / --off.")),process.exit(1));let n=m(`Updating auth on ${o}\u2026`).start();try{let t=await y(`/apps/${encodeURIComponent(o)}/auth`,{method:"PATCH",headers:i,body:JSON.stringify(c)});n.succeed(`Auth update rolling out for ${o}`),console.log(),t?.auth&&(t.auth.type==="none"?console.log(" auth: disabled"):t.auth.type==="basic"?console.log(` auth: basic (user: ${t.auth.user})`):t.auth.type==="token"&&(t.auth.token?(console.log(` auth: token (auto-generated, ends \u2026${t.auth.tokenLast4})`),console.log(),console.log(s.yellow(" \u250C\u2500\u2500\u2500 SAVE THIS TOKEN \u2014 shown ONCE, never again \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510")),console.log(s.yellow(` \u2502 ${t.auth.token}`)),console.log(s.yellow(" \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"))):console.log(` auth: token (ends \u2026${t.auth.tokenLast4||"????"})`))),console.log(),console.log(s.gray(" ECS rolls the task; the new container picks up the Caddy sidecar on healthy.")),console.log(s.gray(` Watch: zibby app status ${o}`)),console.log()}catch(t){n.fail(`Auth update failed: ${t.message}`),process.exit(1)}}var W=3e3;function q(o,e={}){if(e.verbose)return o;let i=o.indexOf(" ");if(i<0)return o;let c=o.slice(0,i),n=o.slice(i+2),t=c.length>=19?c.slice(11,19):c;try{let a=JSON.parse(n),p=(a.level||"INFO").padEnd(4),r=a.msg||a.message||"",d=Object.entries(a).filter(([l])=>!["time","level","msg","message"].includes(l)).filter(([,l])=>l!==""&&l!==null&&l!==void 0).map(([l,f])=>`${l}=${typeof f=="string"?f:JSON.stringify(f)}`).join(" "),g=p.startsWith("ERR")||p.startsWith("FAIL")?s.red:p.startsWith("WARN")?s.yellow:s.gray;return`${s.dim(t)} ${g(p)} ${r}${d?" "+s.dim(d):""}`}catch{return`${s.dim(t)} ${n}`}}async function ao(o,e={}){o||(console.error(s.red("Missing <instanceId>.")),process.exit(1));let i=await w(e),c=Math.min(Math.max(Number(e.lines)||200,1),5e3),n=e.service?`&container=${encodeURIComponent(String(e.service))}`:"",t=async()=>await y(`/apps/${encodeURIComponent(o)}/logs?lines=${c}${n}`,{method:"GET",headers:i});if(!e.follow){try{let r=await t(),d=Array.isArray(r?.lines)?r.lines:[];if(e.json)for(let g of d)console.log(g);else{d.length===0&&console.log(s.gray(" (no log events in window)"));for(let g of d)console.log(q(g,e))}}catch(r){console.error(s.red(`\xD7 ${r.message}`)),process.exit(1)}return}let a=new Set;console.log(s.gray(`Tailing logs for ${o} \u2014 Ctrl+C to stop
|
|
26
|
-
`));let
|
|
27
|
-
Stopped.`)),process.exit(0)});!
|
|
25
|
+
`),[];let s=i.map(a=>({instance:(a.instanceId||"").slice(0,12),name:String(a.name||a.appType||"\u2014").slice(0,22),app:`${a.appType}${a.appVersion?` v${a.appVersion}`:""}`,arch:String(a.architecture||"\u2014"),status:String(a.status||"unknown"),project:String(a.projectId||"\u2014").slice(0,36)})),l=[Math.max(8,...s.map(a=>a.instance.length)),Math.max(4,...s.map(a=>a.name.length)),Math.max(3,...s.map(a=>a.app.length)),Math.max(4,...s.map(a=>a.arch.length)),Math.max(6,...s.map(a=>a.status.length)),Math.max(7,...s.map(a=>a.project.length))];console.log(`
|
|
26
|
+
Deployed Apps (${i.length})
|
|
27
|
+
`),console.log(B(["Instance","Name","App","Arch","Status","Project"],l)),console.log(Pe(l));for(let a of s)console.log(B([a.instance,a.name,a.app,a.arch,a.status,a.project],l));return console.log(""),i}catch{t.fail("Failed to list apps"),process.exit(1)}}async function to(e){let o=x("Fetching projects\u2026").start(),t=await b("/projects",{method:"GET",headers:e});o.stop();let r=Array.isArray(t)?t:t?.projects||t?.data||[];r.length||(console.error(c.red("No projects found. Create one in the dashboard first.")),process.exit(1));let{projectId:n}=await K.prompt([{type:"list",name:"projectId",message:"Which project should this app deploy into?",choices:r.map(i=>({name:`${i.name||"Unnamed"} (${i.projectId||i.id})`,value:i.projectId||i.id}))}]);return n}async function lt(e,o={}){if(o.mode==="solo"){e&&console.warn(c.yellow(` Note: appType "${e}" is ignored under --mode solo (solo deploys a repo/tarball, not the catalog).`));let{appDeploySoloCommand:p}=await Promise.resolve().then(()=>(Te(),Ae));return p(o)}o.mode&&o.mode!=="cloud"&&(console.error(c.red(`Unknown --mode: ${o.mode}. Pick cloud (default) or solo.`)),process.exit(1));let t=o.goal;e&&t&&(console.error(c.red("Pass either appType (catalog id) OR --goal (free-form description), not both.")),process.exit(1)),!e&&!t&&(console.error(c.red("Missing target.")),console.error(c.gray(" Pass appType to deploy from catalog (see `zibby app templates`)")),console.error(c.gray(' OR --goal "<description>" to describe a custom install.')),process.exit(1));let r=await A(o),n=o.project;n||(n=await to(r));let i=t?{goal:t,projectId:n}:{appType:e,projectId:n};o.name&&(i.name=o.name),o.provider&&(o.provider!=="claude"&&o.provider!=="codex"&&(console.error(c.red(`Unknown --provider: ${o.provider}`)),console.error(c.gray(" Pick claude (Anthropic) or codex (OpenAI).")),process.exit(1)),i.provider=o.provider),o.model!==void 0&&((typeof o.model!="string"||!o.model.trim())&&(console.error(c.red("--model requires a non-empty model identifier (e.g. claude-sonnet-4-6).")),process.exit(1)),i.model=o.model.trim());let s=process.env.ZIBBY_ANTHROPIC_TOKEN,l=o.anthropicToken||s||null;if(l&&((typeof l!="string"||!/^sk-ant-(oat01|api03)-/.test(l))&&(console.error(c.red("--anthropic-token must start with sk-ant-oat01- (OAuth) or sk-ant-api03- (API key).")),process.exit(1)),i.anthropicToken=l),o.maxTurns!==void 0){let p=Number(o.maxTurns);(!Number.isInteger(p)||p<1||p>200)&&(console.error(c.red("--max-turns must be an integer between 1 and 200.")),process.exit(1)),i.maxTurns=p}if(o.timeoutMin!==void 0){let p=Number(o.timeoutMin);(!Number.isInteger(p)||p<1||p>120)&&(console.error(c.red("--timeout-min must be an integer between 1 and 120 (minutes).")),process.exit(1)),i.timeoutMin=p}if(o.arch&&(o.arch!=="x86_64"&&o.arch!=="arm64"&&(console.error(c.red(`Unknown --arch: ${o.arch}`)),console.error(c.gray(" Pick x86_64 (Intel/AMD) or arm64 (Graviton, ~20% greener at the same price).")),process.exit(1)),i.architecture=o.arch),o.authType){if(["basic","token","none"].includes(o.authType)||(console.error(c.red(`Unknown --auth-type: ${o.authType}`)),console.error(c.gray(" Pick basic (user + password), token (bearer header), or none.")),process.exit(1)),i.authType=o.authType,o.authType==="basic"){let p=o.authUser;(!p||typeof p!="string"||!/^[\x21-\x7e]{1,64}$/.test(p))&&(console.error(c.red("--auth-type basic requires --auth-user <name> (1-64 printable ASCII, no spaces).")),process.exit(1)),i.authUser=p;let f=o.authPassword||process.env.ZIBBY_APP_AUTH_PASSWORD||"";(!f||f.length<8||f.length>256)&&(console.error(c.red("--auth-type basic requires --auth-password (8-256 chars). Env equivalent: ZIBBY_APP_AUTH_PASSWORD.")),process.exit(1)),i.authPassword=f}else if(o.authType==="token"){let p=o.authToken||process.env.ZIBBY_APP_AUTH_TOKEN||null;p&&((p.length<16||p.length>128||!/^[A-Za-z0-9_-]+$/.test(p))&&(console.error(c.red("--auth-token must be 16-128 chars, base64url alphabet only ([A-Za-z0-9_-]).")),process.exit(1)),i.authToken=p)}}let a=[];o.provider&&a.push(o.provider),o.arch&&a.push(o.arch);let u=e||(t.length>60?`${t.slice(0,60).trim()}\u2026`:t),d=x(`Deploying ${u}${a.length?` (${a.join(", ")})`:""}\u2026`).start();try{let p=await b("/apps/deploy",{method:"POST",headers:r,body:JSON.stringify(i)});d.succeed(`Deployed ${u}`);let f=p?.instanceId,m=p?.url||(p?.subdomain?`https://${p.subdomain}`:null);return console.log(),f&&console.log(` instanceId: ${f}`),m&&console.log(` public URL: ${m}`),p?.architecture&&console.log(` architecture: ${p.architecture}`),p?.auth&&(p.auth.type==="basic"?console.log(` auth: basic (user: ${p.auth.user})`):p.auth.type==="token"&&(p.auth.token?(console.log(" auth: token (auto-generated)"),console.log(),console.log(c.yellow(" \u250C\u2500\u2500\u2500 SAVE THIS TOKEN \u2014 shown ONCE, never again \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510")),console.log(c.yellow(` \u2502 ${p.auth.token}`)),console.log(c.yellow(" \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")),console.log(),console.log(c.gray(` Use it in requests: curl -H 'Authorization: Bearer ${p.auth.token}' ${m}`))):console.log(` auth: token (ends \u2026${p.auth.tokenLast4||"????"})`))),f&&(console.log(),console.log(` Watch status: zibby app status ${f}`)),console.log(),p}catch(p){d.fail(`Deploy failed: ${p.message}`),process.exit(1)}}async function pt(e,o={}){e||(console.error(c.red("Missing <instanceId>.")),process.exit(1));let t=await A(o),r=x(`Fetching ${e}\u2026`).start();try{let n=await b(`/apps/${encodeURIComponent(e)}`,{method:"GET",headers:t});if(r.stop(),o.quiet)return n;let i=n.url||(n.subdomain?`https://${n.subdomain}`:null);if(console.log(),console.log(` ${n.name||n.appType||e}`),console.log(),console.log(` status ${n.status||"unknown"}`),typeof n.runningCount=="number"&&console.log(` running ${n.runningCount} / ${n.desiredCount??1}`),console.log(` app ${n.appType}${n.appVersion?` v${n.appVersion}`:""}`),n.resources?.cpu&&n.resources?.memory){let s=(n.resources.cpu/1024).toFixed(2),l=(n.resources.memory/1024).toFixed(2);console.log(` resources ${s} vCPU \xB7 ${l} GB RAM`)}if(n.architecture&&console.log(` arch ${n.architecture}`),n.projectId&&console.log(` project ${n.projectId}`),i&&console.log(` public URL ${i}`),n.createdAt&&console.log(` created ${n.createdAt}`),Array.isArray(n.containers)&&n.containers.length>1){console.log(),console.log(" services");let s=n.containers.map(a=>[a.name||"?",a.lastStatus||"\u2014",a.healthStatus||"\u2014",a.exitCode!==null&&a.exitCode!==void 0?String(a.exitCode):"\u2014"]),l=[Math.max(7,...s.map(a=>a[0].length)),Math.max(6,...s.map(a=>a[1].length)),Math.max(6,...s.map(a=>a[2].length))];console.log(` ${"NAME".padEnd(l[0])} ${"STATUS".padEnd(l[1])} ${"HEALTH".padEnd(l[2])} EXIT`);for(let a of s)console.log(` ${a[0].padEnd(l[0])} ${a[1].padEnd(l[1])} ${a[2].padEnd(l[2])} ${a[3]}`)}return console.log(),n}catch(n){r.fail(`Could not fetch ${e}`),n.status===404&&console.error(c.gray(" Instance not found \u2014 it may have been destroyed.")),process.exit(1)}}async function ut(e,o={}){e||(console.error(c.red("Missing <instanceId>.")),process.exit(1));let t=await A(o);if(!o.yes){let{confirm:n}=await K.prompt([{type:"confirm",name:"confirm",message:`Destroy app ${e}? The running task will be stopped.`,default:!1}]);if(!n){console.log(c.gray("Aborted."));return}}let r=x(`Destroying ${e}\u2026`).start();try{await b(`/apps/${encodeURIComponent(e)}`,{method:"DELETE",headers:t,body:JSON.stringify({confirm:!0})}),r.succeed(`Destroyed ${e}`)}catch(n){r.fail(`Destroy failed: ${n.message}`),process.exit(1)}}async function dt(e,o={}){e||(console.error(c.red("Missing <instanceId>.")),process.exit(1));let t=await A(o);if(!o.yes){let{confirm:i}=await K.prompt([{type:"confirm",name:"confirm",message:o.version?`Upgrade ${e} to ghcr.io/zibbyhq/agent-ops:${o.version}? EFS data is preserved.`:`Upgrade ${e} to the latest base image? EFS data is preserved.`,default:!0}]);if(!i){console.log(c.gray("Aborted."));return}}let r=o.version?`?version=${encodeURIComponent(o.version)}`:"",n=x(`Upgrading ${e}\u2026`).start();try{let i=await b(`/apps/${encodeURIComponent(e)}/upgrade${r}`,{method:"POST",headers:t});n.succeed(`Upgrade rolling out for ${e}`),console.log(),console.log(` taskDefinitionArn: ${i?.taskDefinitionArn||"\u2014"}`),i?.imageOverride&&console.log(` image: ${i.imageOverride}`),console.log(),console.log(c.gray(" ECS rolls the service: new task pulls image, then swaps over. EFS data preserved.")),console.log(c.gray(` Watch: zibby app status ${e}`)),console.log()}catch(i){n.fail(`Upgrade failed: ${i.message}`),process.exit(1)}}async function gt(e,o={}){e||(console.error(c.red("Missing <instanceId>.")),process.exit(1));let t=await A(o),r=x(`Rotating Claude credential on ${e}\u2026`).start();try{let n=await b(`/apps/${encodeURIComponent(e)}/credentials`,{method:"POST",headers:t,body:"{}"});r.succeed(`Credential update rolling out for ${e}`),console.log(),console.log(` mode ${n?.mode||"\u2014"}`),console.log(` taskDefinitionArn ${n?.taskDefinitionArn||"\u2014"}`),console.log(),console.log(c.gray(" ECS rolls the service: new task pulls the new env, swaps over once healthy.")),console.log(c.gray(` Watch: zibby app status ${e}`)),console.log()}catch(n){r.fail(`Credential update failed: ${n.message}`),process.exit(1)}}async function ft(e,o={}){e||(console.error(c.red("Missing <instanceId>.")),process.exit(1));let t=await A(o),r={};if(o.off)r.authType="none";else{o.authType!==void 0&&(["basic","token","none"].includes(o.authType)||(console.error(c.red(`Unknown --auth-type: ${o.authType}`)),console.error(c.gray(" Pick basic, token, none \u2014 or pass --off.")),process.exit(1)),r.authType=o.authType),o.authUser!==void 0&&((typeof o.authUser!="string"||!/^[\x21-\x7e]{1,64}$/.test(o.authUser))&&(console.error(c.red("--auth-user must be 1-64 printable ASCII chars (no spaces).")),process.exit(1)),r.authUser=o.authUser);let i=o.authPassword||process.env.ZIBBY_APP_AUTH_PASSWORD||null;i&&((i.length<8||i.length>256)&&(console.error(c.red("--auth-password must be 8-256 chars.")),process.exit(1)),r.authPassword=i);let s=o.authToken||process.env.ZIBBY_APP_AUTH_TOKEN||null;s&&((s.length<16||s.length>128||!/^[A-Za-z0-9_-]+$/.test(s))&&(console.error(c.red("--auth-token must be 16-128 chars, base64url alphabet ([A-Za-z0-9_-]).")),process.exit(1)),r.authToken=s)}Object.keys(r).length===0&&(console.error(c.red("Nothing to do \u2014 pass at least one of --auth-type / --auth-user / --auth-password / --auth-token / --off.")),process.exit(1));let n=x(`Updating auth on ${e}\u2026`).start();try{let i=await b(`/apps/${encodeURIComponent(e)}/auth`,{method:"PATCH",headers:t,body:JSON.stringify(r)});n.succeed(`Auth update rolling out for ${e}`),console.log(),i?.auth&&(i.auth.type==="none"?console.log(" auth: disabled"):i.auth.type==="basic"?console.log(` auth: basic (user: ${i.auth.user})`):i.auth.type==="token"&&(i.auth.token?(console.log(` auth: token (auto-generated, ends \u2026${i.auth.tokenLast4})`),console.log(),console.log(c.yellow(" \u250C\u2500\u2500\u2500 SAVE THIS TOKEN \u2014 shown ONCE, never again \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510")),console.log(c.yellow(` \u2502 ${i.auth.token}`)),console.log(c.yellow(" \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"))):console.log(` auth: token (ends \u2026${i.auth.tokenLast4||"????"})`))),console.log(),console.log(c.gray(" ECS rolls the task; the new container picks up the Caddy sidecar on healthy.")),console.log(c.gray(` Watch: zibby app status ${e}`)),console.log()}catch(i){n.fail(`Auth update failed: ${i.message}`),process.exit(1)}}var Ie=3e3;function Ue(e,o={}){if(o.verbose)return e;let t=e.indexOf(" ");if(t<0)return e;let r=e.slice(0,t),n=e.slice(t+2),i=r.length>=19?r.slice(11,19):r;try{let s=JSON.parse(n),l=(s.level||"INFO").padEnd(4),a=s.msg||s.message||"",u=Object.entries(s).filter(([p])=>!["time","level","msg","message"].includes(p)).filter(([,p])=>p!==""&&p!==null&&p!==void 0).map(([p,f])=>`${p}=${typeof f=="string"?f:JSON.stringify(f)}`).join(" "),d=l.startsWith("ERR")||l.startsWith("FAIL")?c.red:l.startsWith("WARN")?c.yellow:c.gray;return`${c.dim(i)} ${d(l)} ${a}${u?" "+c.dim(u):""}`}catch{return`${c.dim(i)} ${n}`}}async function mt(e,o={}){e||(console.error(c.red("Missing <instanceId>.")),process.exit(1));let t=await A(o),r=Math.min(Math.max(Number(o.lines)||200,1),5e3),n=o.service?`&container=${encodeURIComponent(String(o.service))}`:"",i=async()=>await b(`/apps/${encodeURIComponent(e)}/logs?lines=${r}${n}`,{method:"GET",headers:t});if(!o.follow){try{let a=await i(),u=Array.isArray(a?.lines)?a.lines:[];if(o.json)for(let d of u)console.log(d);else{u.length===0&&console.log(c.gray(" (no log events in window)"));for(let d of u)console.log(Ue(d,o))}}catch(a){console.error(c.red(`\xD7 ${a.message}`)),process.exit(1)}return}let s=new Set;console.log(c.gray(`Tailing logs for ${e} \u2014 Ctrl+C to stop
|
|
28
|
+
`));let l=!1;for(process.on("SIGINT",()=>{l=!0,console.log(c.gray(`
|
|
29
|
+
Stopped.`)),process.exit(0)});!l;){try{let a=await i(),u=Array.isArray(a?.lines)?a.lines:[];for(let d of u)s.has(d)||(s.add(d),console.log(o.json?d:Ue(d,o)));if(s.size>r*2){let d=Array.from(s).slice(-r);s.clear(),d.forEach(p=>s.add(p))}}catch(a){console.error(c.red(` \xD7 ${a.message} \u2014 retrying in ${Ie/1e3}s`))}await new Promise(a=>setTimeout(a,Ie))}}export{lt as appDeployCommand,ut as appDestroyCommand,ct as appListCommand,mt as appLogsCommand,ft as appSetAuthCommand,pt as appStatusCommand,at as appTemplatesCommand,gt as appUpdateCredentialCommand,dt as appUpgradeCommand};
|
package/dist/commands/mcp.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import p from"node:fs";import l from"node:path";import $ from"node:os";import n from"chalk";import{existsSync as x,mkdirSync as
|
|
1
|
+
import p from"node:fs";import l from"node:path";import $ from"node:os";import n from"chalk";import{existsSync as x,mkdirSync as j,readFileSync as A,writeFileSync as O}from"fs";import{homedir as h}from"os";import{join as f}from"path";function P(){return process.env.ZIBBY_CONFIG_DIR||f(h(),".zibby")}function B(){return f(P(),"config.json")}var k=f(h(),".zibby"),F=f(k,"config.json");function N(){try{let o=B();if(x(o)){let e=A(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function _(){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 I=v,m=["claude-code","claude-desktop","cursor","codex","gemini"],C={claude:"claude-code","claude-desktop-app":"claude-desktop"},g={"claude-code":"Claude Code","claude-desktop":"Claude Desktop",cursor:"Cursor",codex:"Codex CLI",gemini:"Gemini CLI"};function w(o){let e=$.homedir();switch(o){case"claude-code":return l.join(e,".claude","settings.json");case"cursor":return l.join(e,".cursor","mcp.json");case"codex":return l.join(e,".codex","config.toml");case"gemini":return l.join(e,".gemini","settings.json");case"claude-desktop":return process.platform==="darwin"?l.join(e,"Library","Application Support","Claude","claude_desktop_config.json"):process.platform==="win32"?l.join(process.env.APPDATA||e,"Claude","claude_desktop_config.json"):l.join(e,".config","Claude","claude_desktop_config.json");default:return null}}async function T(o,e){let s=I(),r=await fetch(`${s}/api/user/tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({name:e})});if(!r.ok){let t=await r.text().catch(()=>"");throw new Error(`Could not mint PAT (HTTP ${r.status}): ${t.slice(0,200)}`)}let c=await r.json();if(!c?.token)throw new Error("PAT response missing token field");return c.token}function z(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(l.dirname(o),{recursive:!0});let s=`${o}.zibby-mcp-${Date.now()}.tmp`;p.writeFileSync(s,e,{mode:384}),p.renameSync(s,o)}function S({existing:o,apiUrl:e,pat:s,agent:r}){let c={...o};c.mcpServers={...o.mcpServers||{}};let t=r==="gemini"?"httpUrl":"url";return c.mcpServers.zibby={[t]:`${e}/mcp`,headers:{Authorization:`Bearer ${s}`}},c}function E({existing:o,apiUrl:e,patEnvName:s}){let r=["","[mcp_servers.zibby]",`url = "${e}/mcp"`,`bearer_token_env_var = "${s}"`,""].join(`
|
|
2
2
|
`);if(!o.trim())return r.trimStart();let c=/(^|\n)\[mcp_servers\.zibby\][\s\S]*?(?=\n\[[^\]]+\]|\n*$)/;return c.test(o)?o.replace(c,`
|
|
3
3
|
${r.trim()}
|
|
4
4
|
`):o.replace(/\s*$/,"")+`
|
|
5
|
-
`+r}async function R({agent:o,sessionToken:e,explicitPat:s,apiUrl:r,force:c}){let t=
|
|
6
|
-
`),console.log(n.green(" \u2713 wrote")+n.gray(" "+l.basename(t)))}return{installed:!0,configFile:t}}async function
|
|
5
|
+
`+r}async function R({agent:o,sessionToken:e,explicitPat:s,apiUrl:r,force:c}){let t=w(o);if(!t)return console.log(n.yellow(` skip ${g[o]} \u2014 not supported on this platform`)),{skipped:!0};let d=`MCP \u2013 ${g[o]}`;console.log(n.gray(` \u2192 ${g[o]}`)),console.log(n.gray(` config: ${t}`));let i;if(s?(i=s,console.log(n.gray(` using supplied PAT: ${i.slice(0,18)}...`))):(i=await T(e,d),console.log(n.gray(` minted PAT: ${i.slice(0,18)}...`))),o==="codex"){let a=p.existsSync(t)?p.readFileSync(t,"utf8"):"",b=E({existing:a,apiUrl:r,patEnvName:"ZIBBY_PAT"});if(!c&&a===b)return console.log(n.gray(" no change needed")),{unchanged:!0};U(t,b),console.log(n.green(" \u2713 wrote")+n.gray(" "+l.basename(t))),console.log(n.yellow(" add to your shell rc:")),console.log(n.cyan(` export ZIBBY_PAT=${i}`))}else{let a=z(t),y=S({existing:a,apiUrl:r,pat:i,agent:o});U(t,JSON.stringify(y,null,2)+`
|
|
6
|
+
`),console.log(n.green(" \u2713 wrote")+n.gray(" "+l.basename(t)))}return{installed:!0,configFile:t}}async function q(o={}){let e=o.token||process.env.ZIBBY_PAT||null,s=e?null:_();!e&&!s&&(console.error(n.red("No Zibby auth available.")),console.error(""),console.error(n.gray("Pick one:")),console.error(" zibby login # interactive OAuth, stores session"),console.error(" zibby mcp install --token zby_pat_\u2026 --all # one-shot, no login"),console.error(" ZIBBY_PAT=zby_pat_\u2026 zibby mcp install --all # CI / scripted"),process.exit(1)),e&&!/^zby_pat_/.test(e)&&(console.error(n.red("--token / ZIBBY_PAT must be a Personal Access Token (starts with zby_pat_).")),process.exit(1));let r;if(o.all)r=[...m];else if(o.agent){let i=C[o.agent]||o.agent;m.includes(i)||(console.error(n.red(`Unknown agent: ${o.agent}`)),console.error(n.gray(`Known: ${m.join(", ")}`)),process.exit(1)),r=[i]}else console.error(n.red("Pass --agent <name> or --all.")),console.error(""),console.error(n.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 c=I();console.log(n.bold(`Installing Zibby Remote MCP into ${r.length} agent${r.length===1?"":"s"}\u2026`)),console.log(n.gray(`API: ${c}/mcp`)),console.log("");let t=[],d=0;for(let i of r){try{(await R({agent:i,sessionToken:s,explicitPat:e,apiUrl:c,force:o.force})).installed&&t.push(i)}catch(a){console.error(n.red(` \u2717 ${g[i]} failed: ${a.message}`)),d++}console.log("")}t.length&&(console.log(n.bold.green(`\u2713 Installed for ${t.length} agent${t.length===1?"":"s"}.`)),console.log(""),console.log(n.bold("Next step:")+" restart the agent so it picks up the new MCP server."),console.log(""),console.log(n.gray("Revoke / list your MCP tokens anytime at https://zibby.dev/settings/tokens"))),d&&process.exit(1)}export{q as mcpInstallCommand};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import e from"chalk";import{readFileSync as y,existsSync as I}from"fs";import{homedir as B}from"os";import{join as v}from"path";var w={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 o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let r=process.env.ZIBBY_ENV||"prod";w[r]?o=w[r].apiUrl:o=w.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)`),w.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),w.prod.apiUrl}}var $=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function h(o){return o?$.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}}function m(o){if(o)return o;let r=v(B(),".zibby","config.json");if(I(r))try{let i=JSON.parse(y(r,"utf-8"));if(i.sessionToken)return i.sessionToken}catch{}if(process.env.ZIBBY_API_KEY)return process.env.ZIBBY_API_KEY;console.error(e.red(`
|
|
2
|
+
Not authenticated`)),console.error(e.gray(" Run: zibby login")),console.error(e.gray(` OR set ZIBBY_API_KEY env var
|
|
3
|
+
`)),process.exit(1)}async function k(o,r,i,s){let t=await fetch(r,{method:o,headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},...s!==void 0?{body:JSON.stringify(s)}:{}}),a=await t.text(),n=null;try{n=a?JSON.parse(a):null}catch{}if(!t.ok){let p=n?.error||n?.message||a||`HTTP ${t.status}`;throw new Error(`API ${o} ${t.status}: ${p}`)}return n}async function _(o,r){let i=b(),s=await fetch(`${i}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`}});if(!s.ok)throw new Error(`Failed to list projects (HTTP ${s.status})`);let t=await s.json(),a=t.projects||t||[];for(let n of a){let p=n.projectId||n.id;if(!p)continue;let l=await fetch(`${i}/projects/${p}/workflows`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`}});if(!l.ok)continue;let c=await l.json(),u=(Array.isArray(c)?c:c.workflows||[]).find(g=>g.uuid===o);if(u)return{projectId:p,workflowType:u.workflowType||u.name}}throw new Error(`Workflow with UUID "${o}" not found. Check: zibby workflow list`)}function A(o,r){return`${String(b()).replace(/\/+$/,"")}/projects/${encodeURIComponent(o)}/workflows/${encodeURIComponent(r)}`}function R(o){return`${String(b()).replace(/\/+$/,"")}/workflows/${encodeURIComponent(o)}`}async function f(o,r,i,{tokenJustGenerated:s=!1}={}){let t=await k("PATCH",o,r,{triggers:i});if(U(t),s){let a=t?.webhookToken;a?(console.log(""),console.log(e.yellow.bold(" \u26A0 Copy this token now \u2014 it will NOT be shown again:")),console.log(` ${e.cyan(a)}`)):console.log(e.gray(`
|
|
4
|
+
(backend did not return a plaintext token)`))}return console.log(""),t}function T(o){if(!o)return null;let r=String(b()),i="";return/-dev\b|\bdev\b|localhost|127\.0\.0\.1/.test(r)?i="-dev":/-staging\b|\bstaging\b/.test(r)&&(i="-staging"),`https://${o}.workflows${i}.zibby.app/trigger`}function U(o){if(!o)return;let r=o?.triggers?.api===!0,i=o?.triggers?.webhook||{},s=i.basic||{},t=i.ip||{},a=i.token||{},n=l=>l?e.green("on"):e.gray("off");console.log(""),console.log(` ${e.bold("Webhook:")} ${n(r)}`);let p=T(o?.subdomain);p&&console.log(` ${e.bold("URL:")} ${e.cyan(p)}`),console.log(` ${e.bold("Basic:")} ${n(s.enabled)}${s.username?e.gray(` (user: ${s.username})`):""}`),console.log(` ${e.bold("IP allow:")} ${n(t.enabled)}${Array.isArray(t.allowList)&&t.allowList.length?e.gray(` [${t.allowList.join(", ")}]`):""}`),console.log(` ${e.bold("Token:")} ${n(a.enabled)}${a.tokenMasked?e.gray(` (${a.tokenMasked})`):""}`)}function P(o){return o?String(o).split(",").map(r=>r.trim()).filter(Boolean):[]}async function Z(o,r,i,s={}){let t=(o||"").toLowerCase(),a=null,n=r;t==="auth"&&(a=(r||"").toLowerCase(),n=i);let p=h(n);p.ok||(console.error(e.red(`
|
|
5
|
+
Error: ${p.error}
|
|
6
|
+
`)),process.exit(1)),n||(console.error(e.red(`
|
|
7
|
+
Workflow UUID required.`)),console.error(e.gray(` Usage: zibby workflow webhook <enable|disable|auth|show> <uuid>
|
|
8
|
+
`)),process.exit(1));let l=m(s.apiKey);try{let c=R(n);if(t==="enable"||t==="disable"){let d=t==="enable";console.log(e.green(`
|
|
9
|
+
\u2714 Webhook ${d?"enabled":"disabled"} for ${n}`)),await f(c,l,{api:d});return}if(t==="show"||t==="get"){let{projectId:d,workflowType:u}=await _(n,l),g=await k("GET",A(d,u),l);console.log(e.bold(`
|
|
10
|
+
Webhook config for ${n}:`)),U(g),console.log("");return}if(t==="auth"){if(a==="basic"){if(s.disable){console.log(e.green(`
|
|
11
|
+
\u2714 Basic auth disabled for ${n}`)),await f(c,l,{webhook:{basic:{enabled:!1}}});return}s.username||(console.error(e.red(`
|
|
12
|
+
--username is required (or pass --disable)
|
|
13
|
+
`)),process.exit(1));let d={enabled:!0,username:s.username};s.password&&(d.password=s.password),console.log(e.green(`
|
|
14
|
+
\u2714 Basic auth enabled for ${n}`)),await f(c,l,{webhook:{basic:d}});return}if(a==="ip"){if(s.disable){console.log(e.green(`
|
|
15
|
+
\u2714 IP allowlist disabled for ${n}`)),await f(c,l,{webhook:{ip:{enabled:!1}}});return}let d=P(s.allow);d.length||(console.error(e.red(`
|
|
16
|
+
--allow <cidr,...> is required (or pass --disable)
|
|
17
|
+
`)),process.exit(1)),console.log(e.green(`
|
|
18
|
+
\u2714 IP allowlist set for ${n}`)),await f(c,l,{webhook:{ip:{enabled:!0,allowList:d}}});return}if(a==="token"){if(s.disable){console.log(e.green(`
|
|
19
|
+
\u2714 Token auth disabled for ${n}`)),await f(c,l,{webhook:{token:{enabled:!1}}});return}s.generate||(console.error(e.red(`
|
|
20
|
+
Pass --generate to mint a token (or --disable to turn it off)
|
|
21
|
+
`)),process.exit(1)),console.log(e.green(`
|
|
22
|
+
\u2714 Token generated for ${n}`)),await f(c,l,{webhook:{token:{enabled:!0,generate:!0}}},{tokenJustGenerated:!0});return}console.error(e.red(`
|
|
23
|
+
Unknown auth method: "${r}"`)),console.error(e.gray(` Valid methods: basic | ip | token
|
|
24
|
+
`)),process.exit(1)}console.error(e.red(`
|
|
25
|
+
Unknown action: "${o}"`)),console.error(e.gray(` Valid actions: enable | disable | auth <basic|ip|token> | show
|
|
26
|
+
`)),process.exit(1)}catch(c){console.error(e.red(`
|
|
27
|
+
\u2717 ${c.message}
|
|
28
|
+
`)),process.exit(1)}}export{Z as webhookCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var t=[{id:"micro",instanceType:"t4g.nano",vCpu:2,ramGB:.5,priceUSD:6},{id:"small",instanceType:"t4g.micro",vCpu:2,ramGB:1,priceUSD:10},{id:"medium",instanceType:"t4g.small",vCpu:2,ramGB:2,priceUSD:18},{id:"large",instanceType:"t4g.medium",vCpu:2,ramGB:4,priceUSD:32}],a=t.map(e=>e.id);function r(e){return t.find(i=>i.id===e)||null}var n=[{id:"ap-southeast-2",name:"Sydney",default:!0},{id:"us-east-1",name:"N. Virginia"},{id:"us-west-2",name:"Oregon"},{id:"eu-west-1",name:"Ireland"},{id:"ap-northeast-1",name:"Tokyo"}],o=n.map(e=>e.id),d=(n.find(e=>e.default)||n[0]).id;function p(e){return n.find(i=>i.id===e)||null}export{d as DEFAULT_SOLO_REGION,n as SOLO_REGIONS,o as SOLO_REGION_IDS,t as SOLO_TIERS,a as SOLO_TIER_IDS,p as getSoloRegion,r as getSoloTier};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var O=[1,2,3],_=Math.max(...O);export{_ as WARM_POOL_MAX_QUANTITY,O as WARM_POOL_QUANTITY_OPTIONS};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import ro from"chalk";import{existsSync as oo,readFileSync as eo}from"fs";import{join as no}from"path";import I from"chalk";import{confirm as to}from"@inquirer/prompts";import t from"chalk";import w from"ora";import{spawn as H}from"child_process";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 o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";d[e]?o=d[e].apiUrl:o=d.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)`),d.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),d.prod.apiUrl}}import{existsSync as T,mkdirSync as J,readFileSync as K,writeFileSync as V}from"fs";import{homedir as A}from"os";import{join as m}from"path";function P(){return process.env.ZIBBY_CONFIG_DIR||m(A(),".zibby")}function j(){return m(P(),"config.json")}var M=m(A(),".zibby"),ao=m(M,"config.json");function G(){let o=P();T(o)||J(o,{recursive:!0})}function l(){try{let o=j();if(T(o)){let e=K(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function y(o){G(),V(j(),JSON.stringify(o,null,2))}function _(){return l().sessionToken||null}function B(o){let e=l();e.sessionToken=o,y(e)}function N(){return l().user||null}function R(o){let e=l();e.user=o,y(e)}function z(o){let e=l();e.proxyUrl=o,y(e)}function C(o){let e=l();e.mem0ProxyUrl=o,y(e)}function L(o){let e=l();e.projects=o,y(e)}import{existsSync as fo,mkdirSync as go,readFileSync as yo,writeFileSync as ho,unlinkSync as mo}from"fs";import{resolve as wo}from"path";import{homedir as Io}from"os";function W(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]),H(n,r,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function q(){let o=_(),e=N();return o&&e?{loggedIn:!0,user:e,token:o}:{loggedIn:!1}}async function O(){try{console.log(t.cyan(`
|
|
2
|
+
\u{1F510} Initiating login...
|
|
3
|
+
`));let o=q();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
|
+
`));let{createInterface:e}=await import("readline"),n=e({input:process.stdin,output:process.stdout});return new Promise((r,c)=>{let i=()=>{n.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},p=()=>{console.log(t.yellow(`
|
|
5
|
+
|
|
6
|
+
\u26A0\uFE0F Login cancelled
|
|
7
|
+
`)),i(),process.exit(0)};process.on("SIGINT",p),n.question(t.yellow("Continue with this session? (Y/n): "),async f=>{process.removeListener("SIGINT",p),i();try{if(f.toLowerCase()==="n"||f.toLowerCase()==="no"){console.log(t.gray(`Starting new login...
|
|
8
|
+
`));let h=await $();r(h)}else console.log(t.green(`Using existing session.
|
|
9
|
+
`)),r({success:!0,...o})}catch(h){c(h)}})})}return await $()}catch(o){return console.error(t.red(`
|
|
10
|
+
\u274C Login failed:`,o.message)),{success:!1,error:o.message}}}async function X(o){let e=u();try{let n=await fetch(`${e}/projects`,{headers:{Authorization:`Bearer ${o}`}});if(n.ok){let c=((await n.json()).projects||[]).map(i=>({name:i.name,projectId:i.projectId,apiToken:i.apiToken}));return L(c),c}}catch(n){console.log(t.gray(`\u26A0\uFE0F Could not fetch projects: ${n.message}`))}return[]}async function $(){let o=u(),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 a=await n.json();throw new Error(a.error||"Failed to initiate login")}let{deviceCode:r,userCode:c,verificationUrl:i,expiresIn:p,interval:f}=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(p/60)} minutes`)),console.log(""),await W(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(),Z=(f||3)*1e3,F=Math.floor(p/(f||3)),b=0,x=!1,k=()=>{x=!0,g.stop(),console.log(t.yellow(`
|
|
11
|
+
|
|
12
|
+
\u26A0\uFE0F Login cancelled
|
|
13
|
+
`)),process.exit(0)};process.on("SIGINT",k);try{for(;b<F&&!x;){await Q(Z),b++;let a=await fetch(`${o}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:r})});if(a.status===202)continue;if(!a.ok){g.fail("Authorization failed");let v=await a.json();throw new Error(v.error||"Authorization failed")}let s=await a.json();if(s.status==="authorized"){g.succeed(t.white("Authorization successful!")),B(s.token),R(s.user),s.proxyUrl&&z(s.proxyUrl),s.mem0ProxyUrl&&C(s.mem0ProxyUrl),console.log(""),console.log(t.gray(`User: ${s.user.email}`));let v=w("Fetching projects...").start(),S=await X(s.token);return v.succeed(`Fetched ${S.length} project${S.length!==1?"s":""}`),console.log(t.gray(`Session saved to: ~/.zibby/config.json
|
|
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",k)}}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=no(o,".zibby","config.json");return oo(e)&&JSON.parse(eo(e,"utf-8")).sessionToken||null}catch{return null}}function U(){console.log(`
|
|
15
|
+
Not authenticated.`),console.log(` Run ${I.cyan("zibby login")} or set ${I.cyan("ZIBBY_API_KEY")} in your environment.
|
|
16
|
+
`)}async function Y(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};U(),process.exit(1)}console.log(I.yellow(`
|
|
17
|
+
Not logged in.`));let r;try{r=await to({message:"Open browser to log in now?",default:!0})}catch{r=!1}if(!r){if(o.optional)return{sessionToken:null,apiKey:null};U(),process.exit(1)}if(await O(),n=E(),!n){if(o.optional)return{sessionToken:null,apiKey:null};U(),process.exit(1)}return{sessionToken:n,apiKey:null}}function D(o){if(!o)return null;try{return JSON.parse(o)}catch{return{raw:o}}}async function Do(o){let{sessionToken:e,apiKey:n}=await Y({apiKey:o?.apiKey}),r=e||n;return r||(console.error(ro.red("Not authenticated. Run `zibby login` or set ZIBBY_API_KEY.")),process.exit(1)),{"Content-Type":"application/json",Authorization:`Bearer ${r}`}}async function Zo(o,e,n){let r=u(),c=await fetch(`${r}${o}`,{method:"POST",headers:n,body:JSON.stringify(e)}),i=await c.text();return{status:c.status,body:D(i)}}async function Fo(o,e){let n=u(),r=await fetch(`${n}${o}`,{method:"GET",headers:e}),c=await r.text();return{status:r.status,body:D(c)}}export{Do as authHeaders,Fo as getJson,Zo as postJson};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import p from"node:fs";import t from"node:path";var s=t.join(".zibby","app.json");function l(e){return!!e&&typeof e=="object"&&typeof e.appSlug=="string"&&e.appSlug.length>0&&e.deployMode==="solo"}function u(e=process.cwd()){let n=t.resolve(e);for(let o=0;o<256;o+=1){let r=t.join(n,s);if(p.existsSync(r))try{let a=JSON.parse(p.readFileSync(r,"utf8"));if(l(a))return{path:r,config:a}}catch{}let i=t.dirname(n);if(i===n)break;n=i}return null}function f(e,n={}){let o=t.join(t.resolve(e),".zibby");p.mkdirSync(o,{recursive:!0});let r=t.join(o,"app.json"),i={appSlug:n.appSlug,deployMode:"solo",region:n.region||"",instanceId:n.instanceId||"",domain:n.domain||"",framework:n.framework||""};return p.writeFileSync(r,`${JSON.stringify(i,null,2)}
|
|
2
|
+
`,"utf8"),{path:r,config:i}}export{s as APP_LINK_REL,u as findAppLink,l as isValidAppLink,f as writeAppLink};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e='Use `zibby app run "<your command>"` instead.';function m(n){let r=String(n||"").toLowerCase();return{framework:r,console(){switch(r){case"rails":return{command:"bin/rails console"};case"django":case"python":return{command:"python manage.py shell"};case"node":return{command:"node"};case"elixir":return{command:"iex -S mix"};default:return{error:`No known REPL for framework "${n||"unknown"}". ${e}`}}},migrate(){switch(r){case"rails":return{command:"bin/rails db:migrate"};case"django":return{command:"python manage.py migrate"};default:return{error:`No known migrate command for framework "${n||"unknown"}". ${e}`}}},rollback(o){let a=Number.parseInt(o,10),t=Number.isFinite(a)&&a>0?a:1;switch(r){case"rails":return{command:`bin/rails db:rollback STEP=${t}`};case"django":return{error:'Django rollback needs an explicit migration target (e.g. `python manage.py migrate <app> <name>`). Use `zibby app run "python manage.py migrate <app> <target>"`.'};default:return{error:`No known rollback command for framework "${n||"unknown"}". ${e}`}}}}}export{m as frameworkCommands};
|
package/dist/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zibby/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"description": "Zibby CLI - Test automation generator and runner",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
},
|
|
10
10
|
"scripts": {
|
|
11
11
|
"build": "node ../scripts/build.mjs --extra-dirs bin",
|
|
12
|
-
"test": "vitest run test/auth*.test.js test/two-layer-auth.test.js test/trigger-params.test.js test/trigger-helpers.test.js test/deploy-helpers.test.js test/deploy-bundles-user-config.test.js test/deploy-skip-unchanged.test.js test/deploy-warm-flag.test.js test/deploy-402-formatter.test.js test/run-loads-user-config.test.js test/env-helpers.test.js test/env-cli.test.js test/chat-agents.test.js test/chat-agents-api.test.js test/chat-agents-picker.test.js test/chat-sandbox-attach.test.js test/credentials-file.test.js test/credentials-api.test.js test/credentials-loader.test.js test/cli-namespace-consistency.test.js test/cli-workflow-subcommands.test.js test/template-resolver.test.js test/workflow-new-template.test.js test/runner-input-state-shape.test.js test/run-bundle-core-import.test.js test/start-respects-config.test.js test/sse-backoff.test.js test/sse-reconnect-loop.test.js test/run-helpers.test.js test/run-banner.test.js test/run-banner-e2e.test.js test/sse-parser.test.js test/cloud-creds-check.test.js test/managed-block.test.js",
|
|
12
|
+
"test": "vitest run test/auth*.test.js test/two-layer-auth.test.js test/trigger-params.test.js test/trigger-helpers.test.js test/deploy-helpers.test.js test/deploy-bundles-user-config.test.js test/deploy-skip-unchanged.test.js test/deploy-warm-flag.test.js test/deploy-402-formatter.test.js test/run-loads-user-config.test.js test/env-helpers.test.js test/env-cli.test.js test/chat-agents.test.js test/chat-agents-api.test.js test/chat-agents-picker.test.js test/chat-sandbox-attach.test.js test/credentials-file.test.js test/credentials-api.test.js test/credentials-loader.test.js test/cli-namespace-consistency.test.js test/cli-workflow-subcommands.test.js test/template-resolver.test.js test/workflow-new-template.test.js test/runner-input-state-shape.test.js test/run-bundle-core-import.test.js test/start-respects-config.test.js test/sse-backoff.test.js test/sse-reconnect-loop.test.js test/run-helpers.test.js test/run-banner.test.js test/run-banner-e2e.test.js test/sse-parser.test.js test/cloud-creds-check.test.js test/managed-block.test.js test/app-deploy-solo.test.js test/app-run-solo.test.js",
|
|
13
13
|
"test:unit": "vitest run src/",
|
|
14
14
|
"test:auth": "vitest run test/auth*.test.js test/two-layer-auth.test.js",
|
|
15
15
|
"lint": "eslint .",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zibby/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"description": "Zibby CLI - Test automation generator and runner",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
},
|
|
10
10
|
"scripts": {
|
|
11
11
|
"build": "node ../scripts/build.mjs --extra-dirs bin",
|
|
12
|
-
"test": "vitest run test/auth*.test.js test/two-layer-auth.test.js test/trigger-params.test.js test/trigger-helpers.test.js test/deploy-helpers.test.js test/deploy-bundles-user-config.test.js test/deploy-skip-unchanged.test.js test/deploy-warm-flag.test.js test/deploy-402-formatter.test.js test/run-loads-user-config.test.js test/env-helpers.test.js test/env-cli.test.js test/chat-agents.test.js test/chat-agents-api.test.js test/chat-agents-picker.test.js test/chat-sandbox-attach.test.js test/credentials-file.test.js test/credentials-api.test.js test/credentials-loader.test.js test/cli-namespace-consistency.test.js test/cli-workflow-subcommands.test.js test/template-resolver.test.js test/workflow-new-template.test.js test/runner-input-state-shape.test.js test/run-bundle-core-import.test.js test/start-respects-config.test.js test/sse-backoff.test.js test/sse-reconnect-loop.test.js test/run-helpers.test.js test/run-banner.test.js test/run-banner-e2e.test.js test/sse-parser.test.js test/cloud-creds-check.test.js test/managed-block.test.js",
|
|
12
|
+
"test": "vitest run test/auth*.test.js test/two-layer-auth.test.js test/trigger-params.test.js test/trigger-helpers.test.js test/deploy-helpers.test.js test/deploy-bundles-user-config.test.js test/deploy-skip-unchanged.test.js test/deploy-warm-flag.test.js test/deploy-402-formatter.test.js test/run-loads-user-config.test.js test/env-helpers.test.js test/env-cli.test.js test/chat-agents.test.js test/chat-agents-api.test.js test/chat-agents-picker.test.js test/chat-sandbox-attach.test.js test/credentials-file.test.js test/credentials-api.test.js test/credentials-loader.test.js test/cli-namespace-consistency.test.js test/cli-workflow-subcommands.test.js test/template-resolver.test.js test/workflow-new-template.test.js test/runner-input-state-shape.test.js test/run-bundle-core-import.test.js test/start-respects-config.test.js test/sse-backoff.test.js test/sse-reconnect-loop.test.js test/run-helpers.test.js test/run-banner.test.js test/run-banner-e2e.test.js test/sse-parser.test.js test/cloud-creds-check.test.js test/managed-block.test.js test/app-deploy-solo.test.js test/app-run-solo.test.js",
|
|
13
13
|
"test:unit": "vitest run src/",
|
|
14
14
|
"test:auth": "vitest run test/auth*.test.js test/two-layer-auth.test.js",
|
|
15
15
|
"lint": "eslint .",
|