@zibby/cli 0.5.2 → 0.5.5
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
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
|
-
`),z(process.cwd());const
|
|
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 k}from"commander";import{initCommand as b}from"../commands/init.js";import{runCommand as v}from"../commands/run.js";import{videoCommand as I}from"../commands/video.js";import{uploadCommand as C}from"../commands/upload.js";import{ciSetupCommand as P}from"../commands/ci-setup.js";import{setupPlaywrightMcpCommand as A,setupCiCommand as S,testWithVideoCommand as x}from"../commands/setup-scripts.js";import{readFileSync as B}from"fs";import{fileURLToPath as j}from"url";import{dirname as _,join as E}from"path";import{bootstrapAgentEnv as z}from"../utils/agent-credentials.js";const D=j(import.meta.url),Y=_(D),f=JSON.parse(B(E(Y,"../package.json"),"utf-8"));function s(e,o){return o.push(e),o}function y(e){if(e===void 0||e===!0||e==="")return 1;const o=parseInt(e,10);if(!Number.isFinite(o)||o<1||o>5)throw new Error(`--warm must be an integer 1-5 (got "${e}"). Omit the flag to disable warm pool.`);return o}const w=`zibby v${f.version}`,i=process.argv.slice(2),Z=i.includes("-h")||i.includes("--help"),R=i.includes("-v")||i.includes("-V")||i.includes("--version");R&&(console.log(w),process.exit(0));const g=i[0],O=i[1],L=["logs","uninstall"],M=g==="workflow"&&O==="list";!L.includes(g)&&!M&&console.log(`${w}
|
|
3
|
+
`),z(process.cwd());const U=i[0]==="chat",T=["--verbose","--agent","--stream","-s"],F=i.length>0&&i.every(e=>T.includes(e)||i[i.indexOf(e)-1]==="--agent"),K=i.length===0||U||F;if(K&&!Z){const e={},o=i.indexOf("--agent");o!==-1&&i[o+1]&&(e.agent=i[o+1]),i.includes("--verbose")&&(e.verbose=!0),(i.includes("--stream")||i.includes("-s"))&&(e.stream=!0);const{chatCommand:t}=await import("../commands/chat.js");await t(e),process.exit(0)}const n=new k;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(f.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(k),n.command("test").description("Run a test specification").argument("[spec-path]","Path to test spec file or inline test description in quotes").option("--sources <ids>","Comma-separated test case IDs to fetch from cloud").option("--execution <id>","Execution ID containing the test cases (required with --sources)").option("--agent <type>","Agent to use (claude, cursor, codex, gemini) - overrides config").option("--workflow <name>","Workflow to use (e.g., QuickSmokeWorkflow, quick-smoke)").option("--headless","Run browser in headless mode").option("--node <name>","Run only a specific node (e.g., execute_live, generate_script)").option("--session <id>",'Use existing session (e.g., 1768974629717 or "last") - requires --node').option("--session-path <dir>","Use this session folder (absolute or relative to cwd); Studio pins artifacts here").option("--project <id>","Project ID (optional, auto-detected from ZIBBY_API_KEY)").option("--collection <id-or-name>","Collection ID or name (creates new if name doesn't exist)").option("--folder <path>","Folder path within collection (optional, requires --collection)").option("--sync","Force upload to cloud (overrides cloudSync: false)").option("--no-sync","Skip upload to cloud (overrides cloudSync: true)").option("--config <path>","Path to config file",".zibby.config.mjs").option("--auto-approve","Auto-approve MCP tools (for CI/CD)").option("-o, --open","Open test results in browser after completion").option("--verbose","Show info level logs").option("--debug","Show debug level logs (most verbose)").option("-m, --mem","Enable test memory (Dolt-backed knowledge from previous runs)").action((e,o)=>(o.debug?process.env.ZIBBY_DEBUG="true":o.verbose&&(process.env.ZIBBY_VERBOSE="true"),b(e,o))),n.command("implement").description("Implement a Jira ticket using AI agent (runs in ECS container)").action(async(...e)=>{const{implementCommand:o}=await import("../commands/implement.js");return o(...e)}),n.command("analyze").description("Analyze a Jira ticket against the codebase (runs in ECS container)").option("--workflow <path>","Path to a local workflow JSON file (e.g., .zibby/workflow-analysis.json)").action(async(...e)=>{const{analyzeCommand:o}=await import("../commands/analyze-graph.js");return o(...e)}),n.command("video").description("Organize test videos next to test files").action(v),n.command("upload <spec-path>").description("Upload existing test artifacts to Zibby Cloud").option("--project <id>","Project ID (REQUIRED - use flag or ZIBBY_PROJECT_ID env)").option("--collection <id-or-name>","Collection ID or name (creates new if name doesn't exist)").option("--folder <path>","Folder path within collection (optional)").option("--agent <type>","Agent used (for metadata)").action(C),n.command("login").description("Log in to Zibby (opens browser for authentication)").action(async()=>{const{loginCli:e}=await import("../auth/cli-login.js");await e(),process.exit(0)}),n.command("logout").description("Log out from Zibby (clears saved session)").action(async()=>{const{logoutCli:e}=await import("../auth/cli-login.js");e(),process.exit(0)}),n.command("status").description("Show current authentication status and token details").option("--json","Output in JSON format (for scripts)").action(async e=>{const{showLoginStatus:o}=await import("../auth/cli-login.js");await o(e),process.exit(0)}),n.command("list").description("List your projects and API tokens").action(async()=>{const{listProjectsCommand:e}=await import("../commands/list-projects.js");await e()}),n.command("ci-setup").description("Setup Cursor Agent for CI/CD (patch and configure)").option("--get-keys","Get MCP approval keys").option("--save","Save approval keys to project").action(I),n.command("setup-playwright").description("Setup official Playwright MCP (from cursor-agent-package)").option("--headed","Configure MCP in headed mode (visible browser)").option("--viewport-width <width>","Viewport width (default: 1280)","1280").option("--viewport-height <height>","Viewport height (default: 720)","720").action(e=>{const o={width:parseInt(e.viewportWidth,10)||1280,height:parseInt(e.viewportHeight,10)||720};return P({...e,viewport:o})}),n.command("setup-ci-full").description("Complete CI/CD setup from scratch").action(S),n.command("test-video").description("Run Playwright tests with video recording").argument("[test-file]","Test file to run (default: tests/)").option("--headed","Run in headed mode (visible browser)").action(A),n.command("generate").description("Generate test specs from a ticket + codebase (local analysis using real AI agent)").option("-t, --ticket <key>","Jira ticket key (fetches automatically)").option("-i, --input <file>","Input file with ticket description/requirements").option("-d, --description <text>","Inline ticket description").option("--repo <path>","Path to the codebase (default: current directory)").option("--agent <type>","Agent to use (codex, claude, cursor, gemini)").option("--model <model>","Model override").option("-o, --output <dir>","Output directory for spec files (default: test-specs)").action(async e=>{const{generateCommand:o}=await import("../commands/generate.js");return o(e)}),n.command("studio").description("Launch Zibby Studio desktop (installs from CDN if needed). Uses this folder as the Zibby project.").option("-p, --port <port>","Port for the Studio API bridge (default: 3847)").option("--no-open","Start the API only; do not launch desktop app").option("--update","Force re-download of the latest Studio binary").action(async e=>{const{studioCommand:o}=await import("../commands/studio.js");return o(e)});const m=n.command("creds").description("Manage credentials Zibby has stored for your workspace (KMS-encrypted)");m.command("list").description("List credentials stored for your workspace (masked)").action(async()=>{const{listCmd:e}=await import("../commands/creds.js");await e(),process.exit(0)}),m.command("sync").description("Re-read ~/.zibby/credentials.env and upload any new tokens").action(async()=>{const{syncCmd:e}=await import("../commands/creds.js");await e(),process.exit(0)}),m.command("remove <type> <index>").description("Remove a stored credential. e.g. zibby creds remove oauth 0").action(async(e,o)=>{const{removeCmd:t}=await import("../commands/creds.js");await t(e,o),process.exit(0)});const T=n.command("g").description("Generate scaffolds");T.command("workflow [name]").description("Scaffold a new custom workflow in .zibby/workflows/<name>/ (auto-generates name if omitted)").option("-t, --template <name>","Scaffold from a template (see `zibby template list`). Future: also accepts npm package / git URL identifiers.").option("--skip-install","Skip running `npm install` in the new workflow folder").option("--skip-init-check","Skip the first-run init prompt that fires when ~/.zibby/config.json is missing (CI/scripted setups)").option("--agent-helpers [list]",'Install agent helpers (Claude Code / Cursor slash commands). List = comma-separated, e.g. "claude" or "claude,cursor". Bare flag defaults to claude.').option("--no-agent-helpers","Skip agent helpers even if .zibby.config.mjs says install").option("--agent <agent>","(legacy) Set up agent helpers: claude | cursor | codex | all | none. Prefer --agent-helpers.").option("--force-agents","Overwrite user-edited agent helper files (use with --agent-helpers)").action(async(e,o)=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(e,o)}),n.command("start <workflow-name>").description("Start a local dev server for a custom workflow").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(e,o)=>{const{startWorkflowCommand:t}=await import("../commands/workflows/start.js");return t(e,o)}),n.command("run <workflow-name>").description("Run a workflow locally \u2014 one-shot (alias of `zibby workflow run`)").option("-p, --param <key=value>","Input param (repeatable)",s,[]).option("--input <json>","Input as JSON string").option("--input-file <path>","Input as JSON file").action(async(e,o)=>{const{runLocalWorkflowCommand:t}=await import("../commands/workflows/run-local.js");return t(e,o)}),n.command("deploy [workflow-name]").description("Deploy a custom workflow to Zibby Cloud (interactive selection if workflow-name not provided)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--dedicated-ip <action>","Manage dedicated egress IP addon: enable | status | disable | use | unuse").option("--env <path>","Path to a .env file to sync into per-workflow env vars after deploy (repeatable)",s,[]).option("--verbose","Show raw CodeBuild logs during the bundle build").option("--no-creds-check","Skip the project secrets sanity check (CI/CD when the secret is provisioned out-of-band)").option("--force","Deploy even if the source checksum matches the last deployed version (bypasses the unchanged check)").option("--warm [count]","Enable warm-pool execution for this workflow (default 1, max 5). Skips ~60s Fargate cold-start by routing triggers to a per-account pool of always-on tasks. Pricing applies (paid feature).",f).option("--ai-agent <agent>","Per-workflow AI agent override (claude | cursor | codex | gemini). Falls back to the project default when omitted.").action(async(e,o)=>{if(o.dedicatedIp){const{dedicatedEgressCommand:r}=await import("../commands/workflows/dedicated-egress.js");return r(o.dedicatedIp,o.project)}o.aiAgent&&!["claude","cursor","codex","gemini"].includes(o.aiAgent)&&(console.error(chalk.red(`Invalid --ai-agent: ${o.aiAgent}. Must be one of: claude, cursor, codex, gemini.`)),process.exit(1));const{deployWorkflowCommand:t}=await import("../commands/workflows/deploy.js");return t(e,o)}),n.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (interactive selection if not provided). Get UUIDs from `zibby workflow list`.").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").option("-t, --follow","Stream logs in real-time after triggering (no need to run `logs -t` separately)").action(async(e,o)=>{const{triggerWorkflowCommand:t}=await import("../commands/workflows/trigger.js");return t(e,o)}),n.command("logs [jobId]").description("Fetch and display logs from a workflow execution (use -t to stream in real-time)").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (fetches the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --follow","Stream logs in real-time (like Heroku logs -t)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(e,o)=>{const{logsCommand:t}=await import("../commands/workflows/logs.js");return t(e,o)}),n.command("run-workflow").description("Run a deployed workflow from S3 sources (used by ECS containers)").action(async()=>{const{runWorkflowCommand:e}=await import("../commands/workflows/run.js");return e()});const g=n.command("template").description("Manage workflow templates in this project");g.command("list").description("List available workflow templates").action(async()=>{const{templateListCommand:e}=await import("../commands/template.js");return e()}),g.command("add",{hidden:!0}).argument("<name>","Template name (see `zibby template list`)").description("(deprecated \u2014 `zibby test` auto-installs the template) Copy a template into .zibby/, overwriting existing files").option("--skip-memory","Strip SKILLS.MEMORY from copied execute-live.mjs (browser-test only)").action(async(e,o)=>{const{templateAddCommand:t}=await import("../commands/template.js");return t(e,{enableMemory:!o.skipMemory})});const c=n.command("memory").description("Test memory database \u2014 version-controlled knowledge from runs");c.command("stats").description("Show memory database statistics").action(async()=>{const{memoryStatsCommand:e}=await import("../commands/memory.js");return e()}),c.command("init").description("Initialize the memory database (Dolt)").action(async()=>{const{memoryInitCommand:e}=await import("../commands/memory.js");return e()}),c.command("compact").description("Prune old data and run Dolt GC to reclaim storage").option("--max-runs <n>","Keep last N runs per spec (default: 50)",parseInt).option("--max-age <days>","Remove data older than N days (default: 90)",parseInt).action(async e=>{const{memoryCompactCommand:o}=await import("../commands/memory.js");return o(e)}),c.command("reset").description("Wipe the memory database").option("-f, --force","Confirm reset").action(async e=>{const{memoryResetCommand:o}=await import("../commands/memory.js");return o(e)}),c.command("cost").description("Show real LLM token usage from past runs (input/output/cache)").action(async()=>{const{memoryCostCommand:e}=await import("../commands/memory.js");return e()});const p=c.command("remote").description("Configure a remote so the team shares cross-spec memory");p.command("add").argument("<url>","Remote URL: aws://, gs://, https://, file:///").option("--name <name>","Remote name (default: origin)","origin").description("Point the local memory DB at a shared remote (S3/GCS/DoltHub/filesystem)").action(async(e,o)=>{const{memoryRemoteAddCommand:t}=await import("../commands/memory.js");return t(e,o)}),p.command("use").description("Switch to a managed remote backend. Currently: --hosted (Zibby-managed S3, signed-in users only).").option("--hosted","Use Zibby-managed S3 (allocates a tenant-scoped prefix per-project)").option("--project-id <id>","Override the projectId from .zibby.config.mjs").action(async e=>{e.hosted||(console.log("Pass --hosted. (Other backends will be added later.)"),process.exit(1));const{memoryRemoteUseHostedCommand:o}=await import("../commands/memory.js");return o(e)}),p.command("info").description("Show the configured memory remote (if any)").action(async()=>{const{memoryRemoteInfoCommand:e}=await import("../commands/memory.js");return e()}),p.command("remove").argument("[name]","Remote name (default: origin)").description("Remove a configured memory remote (memory becomes local-only)").action(async e=>{const{memoryRemoteRemoveCommand:o}=await import("../commands/memory.js");return o(e)}),c.command("pull").description("Pull latest team memory from the configured remote").action(async()=>{const{memoryPullCommand:e}=await import("../commands/memory.js");return e()}),c.command("push").description("Push local memory to the configured remote (auto-runs after passing tests)").action(async()=>{const{memoryPushCommand:e}=await import("../commands/memory.js");return e()});const F=n.command("agents").description("Manage Claude/Cursor/Codex helper files for working with Zibby workflows");F.command("add [agent]").description("Add agent helpers (claude | cursor | codex | all). Prompts if no agent given.").option("--force","Overwrite user-edited helper files").action(async(e,o)=>{const{runAgentHelpers:t,addAgent:r}=await import("../commands/workflows/agent-helpers.js");if(e){const l=["claude","cursor","codex","all","none"];l.includes(e)||(console.error(`Unknown agent "${e}". Valid: ${l.join(", ")}`),process.exit(1)),e==="none"?await t({forcedAgents:["none"],force:o.force===!0}):e==="all"?await t({forcedAgents:["claude","cursor","codex"],force:o.force===!0}):await r(e,{force:o.force===!0})}else await t({forcedAgents:void 0,force:o.force===!0,forcePrompt:!0})});const a=n.command("workflow").description("Manage workflow graphs \u2014 new, start, deploy, trigger, logs, list, download, delete");a.command("new [name]").description("Scaffold a new custom workflow (alias of `zibby g workflow`)").option("-t, --template <name>","Scaffold from a template (see `zibby template list`). Future: also accepts npm package / git URL identifiers.").option("--skip-install","Skip running `npm install` in the new workflow folder").option("--skip-init-check","Skip the first-run init prompt that fires when ~/.zibby/config.json is missing (CI/scripted setups)").option("--agent-helpers [list]",'Install agent helpers (Claude Code / Cursor slash commands). List = comma-separated, e.g. "claude" or "claude,cursor". Bare flag defaults to claude.').option("--no-agent-helpers","Skip agent helpers even if .zibby.config.mjs says install").option("--agent <agent>","(legacy) Set up agent helpers: claude | cursor | codex | all | none. Prefer --agent-helpers.").option("--force-agents","Overwrite user-edited agent helper files (use with --agent-helpers)").action(async(e,o)=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(e,o)}),a.command("run <workflow-name>").description("Run a workflow locally \u2014 one-shot, same input flags as `workflow trigger`").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON file \u2014 lowest precedence").action(async(e,o)=>{const{runLocalWorkflowCommand:t}=await import("../commands/workflows/run-local.js");return t(e,o)}),a.command("start <workflow-name>").description("Start a long-lived local dev server (Studio integration). Prefer `workflow run` for one-shots.").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(e,o)=>{const{startWorkflowCommand:t}=await import("../commands/workflows/start.js");return t(e,o)}),a.command("deploy [workflow-name]").description("Deploy a workflow to Zibby Cloud (alias of `zibby deploy`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--env <path>","Path to a .env file to sync into per-workflow env vars after deploy (repeatable)",s,[]).option("--verbose","Show raw CodeBuild logs during the bundle build").option("--no-creds-check","Skip the project secrets sanity check (CI/CD when the secret is provisioned out-of-band)").option("--force","Deploy even if the source checksum matches the last deployed version (bypasses the unchanged check)").option("--warm [count]","Enable warm-pool execution for this workflow (default 1, max 5). Skips ~60s Fargate cold-start by routing triggers to a per-account pool of always-on tasks. Pricing applies (paid feature).",f).action(async(e,o)=>{const{deployWorkflowCommand:t}=await import("../commands/workflows/deploy.js");return t(e,o)}),a.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (alias of `zibby trigger`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").option("-t, --follow","Stream logs in real-time after triggering (no need to run `logs -t` separately)").action(async(e,o)=>{const{triggerWorkflowCommand:t}=await import("../commands/workflows/trigger.js");return t(e,o)}),a.command("logs [jobId]").description("Tail logs from a workflow execution (alias of `zibby logs`)").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (fetches the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --follow","Stream logs in real-time (like Heroku logs -t)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(e,o)=>{const{logsCommand:t}=await import("../commands/workflows/logs.js");return t(e,o)}),a.command("download <uuid>").description("Download a deployed workflow back to local (edit it, then re-deploy with `zibby workflow deploy`)").option("--dest <path>","Destination directory (default: ./workflows/<name> when run inside a .zibby project)").option("--force","Overwrite without prompting; bypass uuid-mismatch guard").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{downloadWorkflowCommand:t}=await import("../commands/workflows/download.js");return t(e,o)}),a.command("list").description("List all workflows (local + remote if credentials available)").option("--local-only","Show only local workflows").option("--remote-only","Show only remote workflows (requires --project)").option("--project <id>","Project ID (optional, uses ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async e=>{if(e.remoteOnly){const{workflowListCommand:t}=await import("../commands/workflow.js");return t(e)}if(e.localOnly){const{listLocalWorkflowsCommand:t}=await import("../commands/workflows/list.js");return t(e)}const{listAllWorkflowsCommand:o}=await import("../commands/workflows/list.js");return o(e)}),a.command("validate <name>").description("Static-check a local workflow (.zibby/workflows/<name>/). Catches schema/topology/skill errors in ~30ms before you run anything.").option("--verbose","Print stack traces on graph.mjs import errors").action(async(e,o)=>{const{validateCommand:t}=await import("../commands/workflows/validate.js");return t(e,o)}),a.command("schedule <uuid> [action] [cron]").description(`Manage a workflow's cron schedule. Actions: get (default) | set <cron> | clear. Cron is Unix 5-field, e.g. "0 9 * * 1-5".`).option("--tz <iana>","IANA timezone for the schedule (default: UTC)").option("-p, --param <key=value>","Fixed input param for every scheduled run (repeatable)",s,[]).option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o,t,r)=>{const{scheduleCommand:l}=await import("../commands/workflows/schedule.js");return l(e,o,t,r)}),a.command("delete <uuid>").description("Delete a deployed workflow by UUID").action(async e=>{const{deleteWorkflowCommand:o}=await import("../commands/workflows/delete.js");return o(e,{})});const d=a.command("env").description("Manage per-workflow encrypted env vars (set ANTHROPIC_API_KEY, DATABASE_URL, etc. per workflow)");d.command("list <uuid>").description("List env var key names for a workflow (values never returned)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{listEnvCommand:t}=await import("../commands/workflows/env.js");return t(e,o)}),d.command("set <uuid> <kv>").description("Set or update one env var: zibby workflow env set <uuid> KEY=value").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o,t)=>{const{setEnvCommand:r}=await import("../commands/workflows/env.js");return r(e,o,t)}),d.command("unset <uuid> <key>").description("Remove one env var from a workflow").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o,t)=>{const{unsetEnvCommand:r}=await import("../commands/workflows/env.js");return r(e,o,t)}),d.command("push <uuid>").description("Bulk-replace env from one or more .env files (later files override). Removes any keys not in the new map.").option("--file <path>","Path to a .env file (repeatable, e.g. --file .env --file .env.prod)",s,[]).option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{pushEnvCommand:t}=await import("../commands/workflows/env.js");return t(e,o)});const K=n.command("project").description("Manage Zibby projects");K.command("list").description("List all projects").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async e=>{const{projectListCommand:o}=await import("../commands/project.js");return o(e)});const N=n.command("run-queue").description("Parallel capacity \u2014 on-disk wait queue (see parallel.waitWhenAtCapacity in .zibby.config.mjs)");N.command("list").description("List CLI processes waiting for a run slot").option("--config <path>","Path to config file",".zibby.config.mjs").action(async e=>{const{runCapacityQueueListCommand:o}=await import("../commands/run-capacity-queue-cli.js");await o(e),process.exit(0)});const G=n.command("mcp").description("Manage the Zibby Remote MCP integration in your AI agent");G.command("install").description("Auto-configure Zibby MCP into your AI agent (Claude Code/Desktop, Cursor, Codex, Gemini)").option("--agent <name>","claude-code | claude-desktop | cursor | codex | gemini").option("--all","Install for every supported agent on this machine").option("--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)}),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(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(x),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 W=n.command("g").description("Generate scaffolds");W.command("workflow [name]").description("Scaffold a new custom workflow in .zibby/workflows/<name>/ (auto-generates name if omitted)").option("-t, --template <name>","Scaffold from a template (see `zibby template list`). Future: also accepts npm package / git URL identifiers.").option("--skip-install","Skip running `npm install` in the new workflow folder").option("--skip-init-check","Skip the first-run init prompt that fires when ~/.zibby/config.json is missing (CI/scripted setups)").option("--agent-helpers [list]",'Install agent helpers (Claude Code / Cursor slash commands). List = comma-separated, e.g. "claude" or "claude,cursor". Bare flag defaults to claude.').option("--no-agent-helpers","Skip agent helpers even if .zibby.config.mjs says install").option("--agent <agent>","(legacy) Set up agent helpers: claude | cursor | codex | all | none. Prefer --agent-helpers.").option("--force-agents","Overwrite user-edited agent helper files (use with --agent-helpers)").action(async(e,o)=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(e,o)}),n.command("start <workflow-name>").description("Start a local dev server for a custom workflow").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(e,o)=>{const{startWorkflowCommand:t}=await import("../commands/workflows/start.js");return t(e,o)}),n.command("run <workflow-name>").description("Run a workflow locally \u2014 one-shot (alias of `zibby workflow run`)").option("-p, --param <key=value>","Input param (repeatable)",s,[]).option("--input <json>","Input as JSON string").option("--input-file <path>","Input as JSON file").action(async(e,o)=>{const{runLocalWorkflowCommand:t}=await import("../commands/workflows/run-local.js");return t(e,o)}),n.command("deploy [workflow-name]").description("Deploy a custom workflow to Zibby Cloud (interactive selection if workflow-name not provided)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--dedicated-ip <action>","Manage dedicated egress IP addon: enable | status | disable | use | unuse").option("--env <path>","Path to a .env file to sync into per-workflow env vars after deploy (repeatable)",s,[]).option("--verbose","Show raw CodeBuild logs during the bundle build").option("--no-creds-check","Skip the project secrets sanity check (CI/CD when the secret is provisioned out-of-band)").option("--force","Deploy even if the source checksum matches the last deployed version (bypasses the unchanged check)").option("--warm [count]","Enable warm-pool execution for this workflow (default 1, max 5). Skips ~60s Fargate cold-start by routing triggers to a per-account pool of always-on tasks. Pricing applies (paid feature).",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)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").option("-t, --follow","Stream logs in real-time after triggering (no need to run `logs -t` separately)").action(async(e,o)=>{const{triggerWorkflowCommand:t}=await import("../commands/workflows/trigger.js");return t(e,o)}),n.command("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 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 J=n.command("agents").description("Manage Claude/Cursor/Codex helper files for working with Zibby workflows");J.command("add [agent]").description("Add agent helpers (claude | cursor | codex | all). Prompts if no agent given.").option("--force","Overwrite user-edited helper files").action(async(e,o)=>{const{runAgentHelpers:t,addAgent:r}=await import("../commands/workflows/agent-helpers.js");if(e){const l=["claude","cursor","codex","all","none"];l.includes(e)||(console.error(`Unknown agent "${e}". Valid: ${l.join(", ")}`),process.exit(1)),e==="none"?await t({forcedAgents:["none"],force:o.force===!0}):e==="all"?await t({forcedAgents:["claude","cursor","codex"],force:o.force===!0}):await r(e,{force:o.force===!0})}else await t({forcedAgents:void 0,force:o.force===!0,forcePrompt:!0})});const a=n.command("workflow").description("Manage workflow graphs \u2014 new, start, deploy, trigger, logs, list, download, delete");a.command("new [name]").description("Scaffold a new custom workflow (alias of `zibby g workflow`)").option("-t, --template <name>","Scaffold from a template (see `zibby template list`). Future: also accepts npm package / git URL identifiers.").option("--skip-install","Skip running `npm install` in the new workflow folder").option("--skip-init-check","Skip the first-run init prompt that fires when ~/.zibby/config.json is missing (CI/scripted setups)").option("--agent-helpers [list]",'Install agent helpers (Claude Code / Cursor slash commands). List = comma-separated, e.g. "claude" or "claude,cursor". Bare flag defaults to claude.').option("--no-agent-helpers","Skip agent helpers even if .zibby.config.mjs says install").option("--agent <agent>","(legacy) Set up agent helpers: claude | cursor | codex | all | none. Prefer --agent-helpers.").option("--force-agents","Overwrite user-edited agent helper files (use with --agent-helpers)").action(async(e,o)=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(e,o)}),a.command("run <workflow-name>").description("Run a workflow locally \u2014 one-shot, same input flags as `workflow trigger`").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON file \u2014 lowest precedence").action(async(e,o)=>{const{runLocalWorkflowCommand:t}=await import("../commands/workflows/run-local.js");return t(e,o)}),a.command("start <workflow-name>").description("Start a long-lived local dev server (Studio integration). Prefer `workflow run` for one-shots.").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(e,o)=>{const{startWorkflowCommand:t}=await import("../commands/workflows/start.js");return t(e,o)}),a.command("deploy [workflow-name]").description("Deploy a workflow to Zibby Cloud (alias of `zibby deploy`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--env <path>","Path to a .env file to sync into per-workflow env vars after deploy (repeatable)",s,[]).option("--verbose","Show raw CodeBuild logs during the bundle build").option("--no-creds-check","Skip the project secrets sanity check (CI/CD when the secret is provisioned out-of-band)").option("--force","Deploy even if the source checksum matches the last deployed version (bypasses the unchanged check)").option("--warm [count]","Enable warm-pool execution for this workflow (default 1, max 5). Skips ~60s Fargate cold-start by routing triggers to a per-account pool of always-on tasks. Pricing applies (paid feature).",y).action(async(e,o)=>{const{deployWorkflowCommand:t}=await import("../commands/workflows/deploy.js");return t(e,o)}),a.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (alias of `zibby trigger`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").option("-t, --follow","Stream logs in real-time after triggering (no need to run `logs -t` separately)").action(async(e,o)=>{const{triggerWorkflowCommand:t}=await import("../commands/workflows/trigger.js");return t(e,o)}),a.command("logs [jobId]").description("Tail logs from a workflow execution (alias of `zibby logs`)").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (fetches the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --follow","Stream logs in real-time (like Heroku logs -t)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(e,o)=>{const{logsCommand:t}=await import("../commands/workflows/logs.js");return t(e,o)}),a.command("download <uuid>").description("Download a deployed workflow back to local (edit it, then re-deploy with `zibby workflow deploy`)").option("--dest <path>","Destination directory (default: ./workflows/<name> when run inside a .zibby project)").option("--force","Overwrite without prompting; bypass uuid-mismatch guard").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{downloadWorkflowCommand:t}=await import("../commands/workflows/download.js");return t(e,o)}),a.command("list").description("List all workflows (local + remote if credentials available)").option("--local-only","Show only local workflows").option("--remote-only","Show only remote workflows (requires --project)").option("--project <id>","Project ID (optional, uses ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async e=>{if(e.remoteOnly){const{workflowListCommand:t}=await import("../commands/workflow.js");return t(e)}if(e.localOnly){const{listLocalWorkflowsCommand:t}=await import("../commands/workflows/list.js");return t(e)}const{listAllWorkflowsCommand:o}=await import("../commands/workflows/list.js");return o(e)}),a.command("validate <name>").description("Static-check a local workflow (.zibby/workflows/<name>/). Catches schema/topology/skill errors in ~30ms before you run anything.").option("--verbose","Print stack traces on graph.mjs import errors").action(async(e,o)=>{const{validateCommand:t}=await import("../commands/workflows/validate.js");return t(e,o)}),a.command("schedule <uuid> [action] [cron]").description(`Manage a workflow's cron schedule. Actions: get (default) | set <cron> | clear. Cron is Unix 5-field, e.g. "0 9 * * 1-5".`).option("--tz <iana>","IANA timezone for the schedule (default: UTC)").option("-p, --param <key=value>","Fixed input param for every scheduled run (repeatable)",s,[]).option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o,t,r)=>{const{scheduleCommand:l}=await import("../commands/workflows/schedule.js");return l(e,o,t,r)}),a.command("delete <uuid>").description("Delete a deployed workflow by UUID").action(async e=>{const{deleteWorkflowCommand:o}=await import("../commands/workflows/delete.js");return o(e,{})});const u=a.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)",s,[]).option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{pushEnvCommand:t}=await import("../commands/workflows/env.js");return t(e,o)});const N=n.command("project").description("Manage Zibby projects");N.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 G=n.command("run-queue").description("Parallel capacity \u2014 on-disk wait queue (see parallel.waitWhenAtCapacity in .zibby.config.mjs)");G.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 H=n.command("mcp").description("Manage the Zibby Remote MCP integration in your AI agent");H.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 p=n.command("app").description("Manage Zibby Managed Apps \u2014 templates, deploy, list, status, destroy");p.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)}),p.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)}),p.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("--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)}),p.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)}),p.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)}),p.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)}),p.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)}),p.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();
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import c from"chalk";import h from"ora";import C from"inquirer";import ge from"dotenv";import{existsSync as ce,readFileSync as le}from"fs";import{join as pe}from"path";import k from"chalk";import{confirm as ue}from"@inquirer/prompts";import u from"chalk";import T from"ora";import{spawn as ne}from"child_process";var b={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function x(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";b[o]?e=b[o].apiUrl:e=b.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)`),b.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),b.prod.apiUrl}}import{existsSync as N,mkdirSync as Q,readFileSync as X,writeFileSync as ee}from"fs";import{homedir as _}from"os";import{join as I}from"path";function O(){return process.env.ZIBBY_CONFIG_DIR||I(_(),".zibby")}function z(){return I(O(),"config.json")}var oe=I(_(),".zibby"),we=I(oe,"config.json");function te(){let e=O();N(e)||Q(e,{recursive:!0})}function m(){try{let e=z();if(N(e)){let o=X(e,"utf-8");return JSON.parse(o)}}catch{}return{}}function A(e){te(),ee(z(),JSON.stringify(e,null,2))}function B(){return m().sessionToken||null}function L(e){let o=m();o.sessionToken=e,A(o)}function D(){return m().user||null}function M(e){let o=m();o.user=e,A(o)}function F(e){let o=m();o.proxyUrl=e,A(o)}function Y(e){let o=m();o.mem0ProxyUrl=e,A(o)}function Z(e){let o=m();o.projects=e,A(o)}import{existsSync as be,mkdirSync as xe,readFileSync as Ae,writeFileSync as Ie,unlinkSync as Ue}from"fs";import{resolve as Te}from"path";import{homedir as ke}from"os";function re(e){let o=process.platform;try{let r,i;return o==="darwin"?(r="open",i=[e]):o==="win32"?(r="cmd",i=["/c","start","",e]):(r="xdg-open",i=[e]),ne(r,i,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function se(){let e=B(),o=D();return e&&o?{loggedIn:!0,user:o,token:e}:{loggedIn:!1}}async function J(){try{console.log(u.cyan(`
|
|
2
|
+
\u{1F510} Initiating login...
|
|
3
|
+
`));let e=se();if(e.loggedIn){console.log(u.green("\u2705 Already logged in!")),console.log(u.gray(`User: ${e.user.email}`)),console.log(u.gray(`Name: ${e.user.name}
|
|
4
|
+
`));let{createInterface:o}=await import("readline"),r=o({input:process.stdin,output:process.stdout});return new Promise((i,t)=>{let a=()=>{r.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},s=()=>{console.log(u.yellow(`
|
|
5
|
+
|
|
6
|
+
\u26A0\uFE0F Login cancelled
|
|
7
|
+
`)),a(),process.exit(0)};process.on("SIGINT",s),r.question(u.yellow("Continue with this session? (Y/n): "),async l=>{process.removeListener("SIGINT",s),a();try{if(l.toLowerCase()==="n"||l.toLowerCase()==="no"){console.log(u.gray(`Starting new login...
|
|
8
|
+
`));let n=await V();i(n)}else console.log(u.green(`Using existing session.
|
|
9
|
+
`)),i({success:!0,...e})}catch(n){t(n)}})})}return await V()}catch(e){return console.error(u.red(`
|
|
10
|
+
\u274C Login failed:`,e.message)),{success:!1,error:e.message}}}async function ie(e){let o=x();try{let r=await fetch(`${o}/projects`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok){let t=((await r.json()).projects||[]).map(a=>({name:a.name,projectId:a.projectId,apiToken:a.apiToken}));return Z(t),t}}catch(r){console.log(u.gray(`\u26A0\uFE0F Could not fetch projects: ${r.message}`))}return[]}async function V(){let e=x(),o=T("Requesting login code...").start(),r=await fetch(`${e}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!r.ok){o.fail("Failed to request login code");let $=await r.json();throw new Error($.error||"Failed to initiate login")}let{deviceCode:i,userCode:t,verificationUrl:a,expiresIn:s,interval:l}=await r.json();o.succeed("Login code generated"),console.log(""),console.log(u.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(u.cyan("\u2551")+u.white.bold(" Complete login in your browser ")+u.cyan("\u2551")),console.log(u.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(u.white("Opening browser to login page...")),console.log(u.gray(`Code expires in ${Math.floor(s/60)} minutes`)),console.log(""),await re(a)||(console.log(u.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(u.white("Please open this URL manually: ")+u.blue(a)),console.log(""));let p=T("Waiting for authorization...").start(),g=(l||3)*1e3,d=Math.floor(s/(l||3)),v=0,E=!1,P=()=>{E=!0,p.stop(),console.log(u.yellow(`
|
|
11
|
+
|
|
12
|
+
\u26A0\uFE0F Login cancelled
|
|
13
|
+
`)),process.exit(0)};process.on("SIGINT",P);try{for(;v<d&&!E;){await ae(g),v++;let $=await fetch(`${e}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:i})});if($.status===202)continue;if(!$.ok){p.fail("Authorization failed");let S=await $.json();throw new Error(S.error||"Authorization failed")}let f=await $.json();if(f.status==="authorized"){p.succeed(u.white("Authorization successful!")),L(f.token),M(f.user),f.proxyUrl&&F(f.proxyUrl),f.mem0ProxyUrl&&Y(f.mem0ProxyUrl),console.log(""),console.log(u.gray(`User: ${f.user.email}`));let S=T("Fetching projects...").start(),R=await ie(f.token);return S.succeed(`Fetched ${R.length} project${R.length!==1?"s":""}`),console.log(u.gray(`Session saved to: ~/.zibby/config.json
|
|
14
|
+
`)),{success:!0,loggedIn:!0,user:f.user,token:f.token}}if(f.status==="denied")throw p.fail("Authorization denied"),new Error("User denied authorization")}throw p.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",P)}}function ae(e){return new Promise(o=>setTimeout(o,e))}function G(){try{let e=process.env.HOME||process.env.USERPROFILE;if(!e)return null;let o=pe(e,".zibby","config.json");return ce(o)&&JSON.parse(le(o,"utf-8")).sessionToken||null}catch{return null}}function j(){console.log(`
|
|
15
|
+
Not authenticated.`),console.log(` Run ${k.cyan("zibby login")} or set ${k.cyan("ZIBBY_API_KEY")} in your environment.
|
|
16
|
+
`)}async function K(e={}){let o=e.apiKey||process.env.ZIBBY_API_KEY||null,r=G();if(r||o)return{sessionToken:r,apiKey:o};if(!process.stdin.isTTY){if(e.optional)return{sessionToken:null,apiKey:null};j(),process.exit(1)}console.log(k.yellow(`
|
|
17
|
+
Not logged in.`));let i;try{i=await ue({message:"Open browser to log in now?",default:!0})}catch{i=!1}if(!i){if(e.optional)return{sessionToken:null,apiKey:null};j(),process.exit(1)}if(await J(),r=G(),!r){if(e.optional)return{sessionToken:null,apiKey:null};j(),process.exit(1)}return{sessionToken:r,apiKey:null}}ge.config();async function w(e){let{sessionToken:o,apiKey:r}=await K({apiKey:e?.apiKey}),i=o||r;return i||(console.error(c.red("Not authenticated. Run `zibby login` or set ZIBBY_API_KEY.")),process.exit(1)),{"Content-Type":"application/json",Authorization:`Bearer ${i}`}}async function y(e,o,{quiet:r=!1}={}){let t=`${x()}${e}`,a=await fetch(t,o),s=await a.text(),l=null;try{l=s?JSON.parse(s):null}catch{l={raw:s}}if(!a.ok){let n=l?.error||l?.message||`HTTP ${a.status}`;r||(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 ${n}`)),l?.detail&&console.error(c.gray(` ${l.detail}`))));let p=new Error(n);throw p.status=a.status,p.body=l,p.code=l?.code||null,p}return l}function q(e){return" "+e.map(o=>"\u2500".repeat(o)).join(" ")}function U(e,o){return" "+e.map((r,i)=>String(r??"").padEnd(o[i])).join(" ")}async function Qe(e={}){let o=h("Loading app catalog\u2026").start();try{let r=await y("/apps/catalog",{method:"GET"});o.stop();let i=Array.isArray(r?.items)?r.items:[];if(i.length===0)return console.log(`
|
|
18
|
+
No apps available in the catalog.
|
|
19
|
+
`),[];if(e.quiet)return i;let t=i.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)})),a=[Math.max(7,...t.map(s=>s.appType.length)),Math.max(7,...t.map(s=>s.version.length)),Math.max(4,...t.map(s=>s.tier.length)),Math.max(13,...t.map(s=>s.arch.length)),Math.max(7,...t.map(s=>s.tagline.length))];console.log(`
|
|
20
|
+
App Catalog (${i.length})
|
|
21
|
+
`),console.log(U(["AppType","Version","Tier","Architectures","Tagline"],a)),console.log(q(a));for(let s of t)console.log(U([s.appType,s.version,s.tier,s.arch,s.tagline],a));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(""),i}catch(r){o.fail("Failed to load catalog"),r.status&&console.error(` HTTP ${r.status}`),process.exit(1)}}async function Xe(e={}){let o=await w(e),r=h("Fetching deployed apps\u2026").start();try{let i=e.project?`?projectId=${encodeURIComponent(e.project)}`:"",t=await y(`/apps${i}`,{method:"GET",headers:o});r.stop();let a=Array.isArray(t?.apps)?t.apps:[];if(e.quiet)return a;if(a.length===0)return console.log(`
|
|
22
|
+
No apps deployed.`),console.log(` Deploy one with: zibby app deploy <appType> --project <projectId>
|
|
23
|
+
`),[];let s=a.map(n=>({instance:(n.instanceId||"").slice(0,12),name:String(n.name||n.appType||"\u2014").slice(0,22),app:`${n.appType}${n.appVersion?` v${n.appVersion}`:""}`,arch:String(n.architecture||"\u2014"),status:String(n.status||"unknown"),project:String(n.projectId||"\u2014").slice(0,36)})),l=[Math.max(8,...s.map(n=>n.instance.length)),Math.max(4,...s.map(n=>n.name.length)),Math.max(3,...s.map(n=>n.app.length)),Math.max(4,...s.map(n=>n.arch.length)),Math.max(6,...s.map(n=>n.status.length)),Math.max(7,...s.map(n=>n.project.length))];console.log(`
|
|
24
|
+
Deployed Apps (${a.length})
|
|
25
|
+
`),console.log(U(["Instance","Name","App","Arch","Status","Project"],l)),console.log(q(l));for(let n of s)console.log(U([n.instance,n.name,n.app,n.arch,n.status,n.project],l));return console.log(""),a}catch{r.fail("Failed to list apps"),process.exit(1)}}async function de(e){let o=h("Fetching projects\u2026").start(),r=await y("/projects",{method:"GET",headers:e});o.stop();let i=Array.isArray(r)?r:r?.projects||r?.data||[];i.length||(console.error(c.red("No projects found. Create one in the dashboard first.")),process.exit(1));let{projectId:t}=await C.prompt([{type:"list",name:"projectId",message:"Which project should this app deploy into?",choices:i.map(a=>({name:`${a.name||"Unnamed"} (${a.projectId||a.id})`,value:a.projectId||a.id}))}]);return t}async function eo(e,o={}){let r=o.goal;e&&r&&(console.error(c.red("Pass either appType (catalog id) OR --goal (free-form description), not both.")),process.exit(1)),!e&&!r&&(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 i=await w(o),t=o.project;t||(t=await de(i));let a=r?{goal:r,projectId:t}:{appType:e,projectId:t};o.name&&(a.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)),a.provider=o.provider),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)),a.architecture=o.arch);let s=[];o.provider&&s.push(o.provider),o.arch&&s.push(o.arch);let l=e||(r.length>60?`${r.slice(0,60).trim()}\u2026`:r),n=h(`Deploying ${l}${s.length?` (${s.join(", ")})`:""}\u2026`).start();try{let p=await y("/apps/deploy",{method:"POST",headers:i,body:JSON.stringify(a)});n.succeed(`Deployed ${l}`);let g=p?.instanceId,d=p?.url||(p?.subdomain?`https://${p.subdomain}`:null);return console.log(),g&&console.log(` instanceId: ${g}`),d&&console.log(` public URL: ${d}`),p?.architecture&&console.log(` architecture: ${p.architecture}`),g&&(console.log(),console.log(` Watch status: zibby app status ${g}`)),console.log(),p}catch(p){n.fail(`Deploy failed: ${p.message}`),process.exit(1)}}async function oo(e,o={}){e||(console.error(c.red("Missing <instanceId>.")),process.exit(1));let r=await w(o),i=h(`Fetching ${e}\u2026`).start();try{let t=await y(`/apps/${encodeURIComponent(e)}`,{method:"GET",headers:r});if(i.stop(),o.quiet)return t;let a=t.url||(t.subdomain?`https://${t.subdomain}`:null);if(console.log(),console.log(` ${t.name||t.appType||e}`),console.log(),console.log(` status ${t.status||"unknown"}`),typeof t.runningCount=="number"&&console.log(` running ${t.runningCount} / ${t.desiredCount??1}`),console.log(` app ${t.appType}${t.appVersion?` v${t.appVersion}`:""}`),t.resources?.cpu&&t.resources?.memory){let s=(t.resources.cpu/1024).toFixed(2),l=(t.resources.memory/1024).toFixed(2);console.log(` resources ${s} vCPU \xB7 ${l} GB RAM`)}if(t.architecture&&console.log(` arch ${t.architecture}`),t.projectId&&console.log(` project ${t.projectId}`),a&&console.log(` public URL ${a}`),t.createdAt&&console.log(` created ${t.createdAt}`),Array.isArray(t.containers)&&t.containers.length>1){console.log(),console.log(" services");let s=t.containers.map(n=>[n.name||"?",n.lastStatus||"\u2014",n.healthStatus||"\u2014",n.exitCode!==null&&n.exitCode!==void 0?String(n.exitCode):"\u2014"]),l=[Math.max(7,...s.map(n=>n[0].length)),Math.max(6,...s.map(n=>n[1].length)),Math.max(6,...s.map(n=>n[2].length))];console.log(` ${"NAME".padEnd(l[0])} ${"STATUS".padEnd(l[1])} ${"HEALTH".padEnd(l[2])} EXIT`);for(let n of s)console.log(` ${n[0].padEnd(l[0])} ${n[1].padEnd(l[1])} ${n[2].padEnd(l[2])} ${n[3]}`)}return console.log(),t}catch(t){i.fail(`Could not fetch ${e}`),t.status===404&&console.error(c.gray(" Instance not found \u2014 it may have been destroyed.")),process.exit(1)}}async function to(e,o={}){e||(console.error(c.red("Missing <instanceId>.")),process.exit(1));let r=await w(o);if(!o.yes){let{confirm:t}=await C.prompt([{type:"confirm",name:"confirm",message:`Destroy app ${e}? The running task will be stopped.`,default:!1}]);if(!t){console.log(c.gray("Aborted."));return}}let i=h(`Destroying ${e}\u2026`).start();try{await y(`/apps/${encodeURIComponent(e)}`,{method:"DELETE",headers:r,body:JSON.stringify({confirm:!0})}),i.succeed(`Destroyed ${e}`)}catch(t){i.fail(`Destroy failed: ${t.message}`),process.exit(1)}}async function no(e,o={}){e||(console.error(c.red("Missing <instanceId>.")),process.exit(1));let r=await w(o);if(!o.yes){let{confirm:a}=await C.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(!a){console.log(c.gray("Aborted."));return}}let i=o.version?`?version=${encodeURIComponent(o.version)}`:"",t=h(`Upgrading ${e}\u2026`).start();try{let a=await y(`/apps/${encodeURIComponent(e)}/upgrade${i}`,{method:"POST",headers:r});t.succeed(`Upgrade rolling out for ${e}`),console.log(),console.log(` taskDefinitionArn: ${a?.taskDefinitionArn||"\u2014"}`),a?.imageOverride&&console.log(` image: ${a.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(a){t.fail(`Upgrade failed: ${a.message}`),process.exit(1)}}async function ro(e,o={}){e||(console.error(c.red("Missing <instanceId>.")),process.exit(1));let r=await w(o),i=h(`Rotating Claude credential on ${e}\u2026`).start();try{let t=await y(`/apps/${encodeURIComponent(e)}/credentials`,{method:"POST",headers:r,body:"{}"});i.succeed(`Credential update rolling out for ${e}`),console.log(),console.log(` mode ${t?.mode||"\u2014"}`),console.log(` taskDefinitionArn ${t?.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(t){i.fail(`Credential update failed: ${t.message}`),process.exit(1)}}var H=3e3;function W(e,o={}){if(o.verbose)return e;let r=e.indexOf(" ");if(r<0)return e;let i=e.slice(0,r),t=e.slice(r+2),a=i.length>=19?i.slice(11,19):i;try{let s=JSON.parse(t),l=(s.level||"INFO").padEnd(4),n=s.msg||s.message||"",p=Object.entries(s).filter(([d])=>!["time","level","msg","message"].includes(d)).filter(([,d])=>d!==""&&d!==null&&d!==void 0).map(([d,v])=>`${d}=${typeof v=="string"?v:JSON.stringify(v)}`).join(" "),g=l.startsWith("ERR")||l.startsWith("FAIL")?c.red:l.startsWith("WARN")?c.yellow:c.gray;return`${c.dim(a)} ${g(l)} ${n}${p?" "+c.dim(p):""}`}catch{return`${c.dim(a)} ${t}`}}async function so(e,o={}){e||(console.error(c.red("Missing <instanceId>.")),process.exit(1));let r=await w(o),i=Math.min(Math.max(Number(o.lines)||200,1),5e3),t=o.service?`&container=${encodeURIComponent(String(o.service))}`:"",a=async()=>await y(`/apps/${encodeURIComponent(e)}/logs?lines=${i}${t}`,{method:"GET",headers:r});if(!o.follow){try{let n=await a(),p=Array.isArray(n?.lines)?n.lines:[];if(o.json)for(let g of p)console.log(g);else{p.length===0&&console.log(c.gray(" (no log events in window)"));for(let g of p)console.log(W(g,o))}}catch(n){console.error(c.red(`\xD7 ${n.message}`)),process.exit(1)}return}let s=new Set;console.log(c.gray(`Tailing logs for ${e} \u2014 Ctrl+C to stop
|
|
26
|
+
`));let l=!1;for(process.on("SIGINT",()=>{l=!0,console.log(c.gray(`
|
|
27
|
+
Stopped.`)),process.exit(0)});!l;){try{let n=await a(),p=Array.isArray(n?.lines)?n.lines:[];for(let g of p)s.has(g)||(s.add(g),console.log(o.json?g:W(g,o)));if(s.size>i*2){let g=Array.from(s).slice(-i);s.clear(),g.forEach(d=>s.add(d))}}catch(n){console.error(c.red(` \xD7 ${n.message} \u2014 retrying in ${H/1e3}s`))}await new Promise(n=>setTimeout(n,H))}}export{eo as appDeployCommand,to as appDestroyCommand,Xe as appListCommand,so as appLogsCommand,oo as appStatusCommand,Qe as appTemplatesCommand,ro as appUpdateCredentialCommand,no as appUpgradeCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var P=Object.defineProperty;var h=(s,n)=>()=>(s&&(n=s(s=0)),n);var b=(s,n)=>{for(var t in n)P(s,t,{get:n[t],enumerable:!0})};var _={};b(_,{DEFAULT_CONFIG_PATH:()=>w,discoverCredentials:()=>z,maskToken:()=>R,parseConfigJson:()=>$,readCredentialsConfig:()=>x});import T from"node:fs/promises";import U from"node:path";import j from"node:os";function $(s){if(!s)return[];let n;try{n=JSON.parse(s)}catch{return[]}let t=n?.agentKeys;if(!t||typeof t!="object")return[];let r=[],i=new Set;for(let[e,c]of Object.entries(m)){let a=t[e];if(!a||typeof a!="string")continue;let d=e.endsWith("_POOL")?a.split(",").map(l=>l.trim()).filter(Boolean):[a.trim()];for(let l of d)l.length<8||i.has(l)||(i.add(l),r.push({type:c,token:l,source_var:e}))}return r}async function x(s=w){let n;try{n=await T.readFile(s,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return $(n)}async function z({filepath:s,env:n=process.env}={}){let t=await x(s),r=new Set(t.map(e=>e.token)),i=[];for(let[e,c]of Object.entries(m)){let a=n[e];if(!a)continue;let d=e.endsWith("_POOL")?a.split(",").map(l=>l.trim()).filter(Boolean):[a];for(let l of d)l.length<8||r.has(l)||(r.add(l),i.push({type:c,token:l,source_var:e,source:"process.env"}))}return{config:t.map(e=>({...e,source:"config.json"})),env:i,all:[...t.map(e=>({...e,source:"config.json"})),...i]}}function R(s){return!s||typeof s!="string"||s.length<=4?"***":`***${s.slice(-4)}`}var w,m,C=h(()=>{w=U.join(j.homedir(),".zibby","config.json"),m={CLAUDE_CODE_OAUTH_TOKEN:"oauth",CLAUDE_CODE_OAUTH_TOKEN_POOL:"oauth",ANTHROPIC_AUTH_TOKEN:"oauth",ANTHROPIC_API_KEY:"api",ANTHROPIC_API_KEY_POOL:"api"}});var A={};b(A,{addCredential:()=>S,deleteCredential:()=>D,listCredentials:()=>N,syncFromLocal:()=>L});function g(s,n=""){return`${String(s).replace(/\/+$/,"")}/agents/credentials${n}`}function y(){let s=new Error("Session expired \u2014 run zibby login");return s.code="AUTH_EXPIRED",s}async function N({apiUrl:s,sessionToken:n}){if(!n)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let t=await fetch(g(s),{headers:{Authorization:`Bearer ${n}`}});if(t.status===401)throw y();if(t.status===404)return{credentials:[],by_type:{oauth:[],api:[]},total:0};if(!t.ok){let r=new Error(`List credentials failed (${t.status})`);throw r.status=t.status,r}return t.json()}async function S({apiUrl:s,sessionToken:n,type:t,token:r,source:i="~/.zibby/config.json"}){if(!n)throw new Error("No session token \u2014 run zibby login first");let e=await fetch(g(s),{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({type:t,token:r,source:i})});if(e.status===401)throw y();if(!e.ok){let c=`Add credential failed (${e.status})`;try{let d=await e.json();d?.error&&(c=`${c}: ${d.error}`)}catch{}let a=new Error(c);throw a.status=e.status,a}return e.json()}async function D({apiUrl:s,sessionToken:n,type:t,index:r}){if(!n)throw new Error("No session token \u2014 run zibby login first");let i=await fetch(g(s,`/${encodeURIComponent(t)}/${encodeURIComponent(r)}`),{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(i.status===401)throw y();if(!i.ok){let e=new Error(`Delete credential failed (${i.status})`);throw e.status=i.status,e}return i.json()}async function L({apiUrl:s,sessionToken:n,credentials:t}){let r=0,i=0,e=[];for(let c of t)try{let a=await S({apiUrl:s,sessionToken:n,type:c.type,token:c.token,source:c.source_var||c.source||"local"});a.deduped?i+=1:a.added&&(r+=1)}catch(a){e.push({masked:c.token?`***${c.token.slice(-4)}`:"***",error:a.message})}return{added:r,deduped:i,errors:e}}var E=h(()=>{});import{select as v,confirm as p,Separator as I}from"@inquirer/prompts";import o from"chalk";var u=[{id:"zibby",name:"Zibby Chat",short:"default",description:"Built-in chat using Anthropic SDK directly \xB7 BYOK \xB7 included with workspace",pricePerMonth:0,deployment:"instant"},{id:"claude-code",name:"Claude Code",short:"add-on",description:"Anthropic's Claude Code CLI deployed in your private sandbox",pricePerMonth:20,deployment:"fargate-warm"}];async function X({apiUrl:s,sessionToken:n,currentAgentId:t="zibby"}={}){let r;try{r=await K({apiUrl:s,sessionToken:n})}catch(e){if(/login/i.test(e.message))throw e;console.warn(o.gray(` (could not fetch sessions: ${e.message})`)),r=[]}let i=[];if(r.length>0){for(let e of r){let a=u.find(k=>k.id===e.agent_type)?.name||e.agent_type,d=Z(e.last_active),l=typeof e.message_count=="number"&&e.message_count>0?o.gray(` \xB7 ${e.message_count} msg`):"",O=e.label?o.gray(` \xB7 "${e.label}"`):"";i.push({name:`${o.cyan("\u2726")} ${a} ${o.gray(`(${d})`)}${O}${l}`,value:{action:"resume",agentType:e.agent_type,sessionId:e.session_id,session:e},description:o.gray(` Resume your ${a} session`)})}i.push(new I)}for(let e of u)e.id!=="zibby"&&i.push({name:`${o.dim("+")} New ${e.name} session${e.pricePerMonth>0?o.yellow(` (+$${e.pricePerMonth}/mo)`):""}`,value:{action:"create",agentType:e.id},description:o.gray(` ${e.description}`)});i.push(new I),i.push({name:`${o.green("\u2190")} Back to Zibby Chat (default)${t==="zibby"?o.dim(" [current]"):""}`,value:{action:"switch",agentType:"zibby"},description:o.gray(" Built-in chat using Anthropic SDK directly")});try{return await v({message:"Select chat agent:",choices:i})}catch(e){if(e?.name==="ExitPromptError")return{action:"cancel"};throw e}}async function Q(s="zibby"){let n=await v({message:"Select chat agent for this workspace:",default:s,choices:u.map(t=>{let r=t.pricePerMonth===0?o.green(" (included)"):o.yellow(` (+$${t.pricePerMonth}/mo)`),i=t.id===s?o.dim(" [current]"):"";return{name:`${t.name}${r}${i}`,value:t.id,description:o.gray(` ${t.description}`)}})});return u.find(t=>t.id===n)}async function V({workspaceId:s,sessionToken:n,apiUrl:t}){let r=await M({addon:"claude-code",workspaceId:s,sessionToken:n,apiUrl:t});if(r.configured&&r.sandboxState==="ready")return console.log(""),console.log(o.green(" \u2713 Claude Code is already deployed for your team.")),console.log(o.gray(` Sandbox: ${r.sandboxId} \xB7 state: ${r.sandboxState}`)),console.log(""),{ready:!0,sandboxId:r.sandboxId};if(r.configured&&r.sandboxState!=="ready")return console.log(""),console.log(o.cyan(` \u2699 Claude Code sandbox is ${r.sandboxState}...`)),console.log(o.gray(" You can keep using Zibby Chat \u2014 we'll switch when it's ready.")),console.log(""),{ready:!1,provisioning:!0,sandboxId:r.sandboxId};if(console.log(""),console.log(o.yellow(" Claude Code add-on is not enabled for your workspace.")),console.log(""),console.log(o.white(" About this add-on:")),console.log(o.gray(" \u2022 Anthropic's official Claude Code CLI runs in YOUR isolated sandbox")),console.log(o.gray(" \u2022 YOU provide your own Anthropic credentials (in ~/.zibby/config.json)")),console.log(o.gray(" \u2022 Zibby NEVER accesses Anthropic on your behalf \u2014 your tokens, your API calls")),console.log(o.gray(" \u2022 Zibby stores credentials KMS-encrypted, decrypts only inside YOUR sandbox")),console.log(o.gray(" \u2022 You're responsible for ToS compliance with the credentials you provide:")),console.log(o.gray(" https://www.anthropic.com/legal/commercial-terms")),console.log(""),console.log(o.cyan(" Pricing:")),console.log(o.white(" $20 / month per workspace ")+o.gray("\xB7 Zibby infrastructure fee, billed via Stripe")),console.log(o.gray(" Your Anthropic usage bills directly to your Anthropic account")),console.log(""),!await p({message:"Do you agree to Anthropic's Commercial Terms of Service?",default:!1}))return console.log(o.gray(" Cancelled. Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0};if(!await p({message:"Enable Claude Code add-on at $20/month?",default:!1}))return console.log(o.gray(" Cancelled. Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0};console.log(""),console.log(o.cyan(" Enabling Claude Code add-on..."));let c;try{c=await Y({addon:"claude-code",workspaceId:s,sessionToken:n,apiUrl:t,accept:{tos:!0,billing:!0}})}catch(a){if(a?.code==="BILLING_REQUIRED"){console.log("");let d=a.upgradeUrl?.startsWith("http")?a.upgradeUrl:"https://zibby.dev/billing";return a.needsSubscription?(console.log(o.yellow(" \u26A0 You need an active Pro subscription to enable Claude Code.")),console.log(o.gray(` Upgrade here: ${d}`))):a.needsPaymentMethod?(console.log(o.yellow(" \u26A0 Your card was declined or no payment method is on file.")),console.log(o.gray(` Update billing: ${d}`))):(console.log(o.yellow(` \u26A0 ${a.message}`)),console.log(o.gray(` Manage billing: ${d}`))),console.log(""),console.log(o.gray(" Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0,billingRequired:!0}}throw a}return console.log(""),console.log(o.green(" \u2713 Stripe subscription created")),console.log(o.gray(` sub_id: ${c.subscriptionId}`)),console.log(o.green(" \u2713 Lambda invoked: zibby-prod-provision-sandbox")),console.log(o.gray(` request: ${c.requestId}`)),console.log(o.cyan(" \u2699 Fargate task launching: zibby/agent-runtime:claude-code-v1")),console.log(o.gray(` sandbox_id: ${c.sandboxId}`)),console.log(""),await B({apiUrl:t,sessionToken:n}),console.log(""),console.log(o.gray(" Sandbox provisioning in the background. Zibby Chat (default) is active until ready.")),console.log(""),{ready:!1,provisioning:!0,sandboxId:c.sandboxId,deploymentId:c.requestId}}async function B({apiUrl:s,sessionToken:n}){let t;try{let{discoverCredentials:e}=await Promise.resolve().then(()=>(C(),_));t=await e()}catch(e){console.log(o.gray(` (could not scan local credentials: ${e.message})`));return}let r=t.all.length;if(r===0){console.log(o.yellow(" \u26A0 No Anthropic credentials found locally.")),console.log(""),console.log(o.white(" Two ways to authenticate Claude Code in your sandbox:")),console.log(""),console.log(o.bold(" Option A \u2014 provide your own (recommended):")),console.log(o.gray(" 1. Run: zibby init")),console.log(o.gray(" Pick Claude \u2192 Subscription (OAuth) or API key")),console.log(o.gray(" 2. Run: zibby creds sync (uploads to your workspace)")),console.log(o.gray(" 3. Re-run /agents in chat")),console.log(""),console.log(o.bold(" Option B \u2014 in-sandbox login (legacy):")),console.log(o.gray(" Skip this step. When sandbox is ready and you start")),console.log(o.gray(" Claude Code, it will prompt you to open a URL in your")),console.log(o.gray(" laptop browser to authenticate.")),console.log("");return}console.log(o.green(` \u2713 Found ${r} Anthropic ${r===1?"credential":"credentials"} in your local environment:`));for(let e of t.all){let c=e.source==="config.json"?`~/.zibby/config.json (${e.source_var})`:`process.env.${e.source_var}`;console.log(o.gray(` ${e.type} ***${e.token.slice(-4)} ${c}`))}if(console.log(""),console.log(o.white(" By proceeding you confirm:")),console.log(o.gray(" \u2022 These are YOUR credentials to use")),console.log(o.gray(" \u2022 You comply with Anthropic's ToS for the tier of these tokens")),console.log(o.gray(" \u2022 Zibby will store encrypted (AWS KMS) and inject into YOUR sandbox only")),console.log(""),!await p({message:"Upload these credentials to your Zibby workspace?",default:!0})){console.log(o.gray(" Skipped credential upload. Sandbox will fall back to in-sandbox login."));return}console.log(""),console.log(o.cyan(" Uploading (KMS-encrypted)..."));try{let{syncFromLocal:e}=await Promise.resolve().then(()=>(E(),A)),c=await e({apiUrl:s,sessionToken:n,credentials:t.all});console.log(o.green(` \u2713 ${c.added} new, ${c.deduped} already stored`)),c.errors.length>0&&console.log(o.yellow(` ${c.errors.length} failed \u2014 retry with 'zibby creds sync'`))}catch(e){console.log(o.red(` \u2717 Upload failed: ${e.message}`)),console.log(o.gray(" Sandbox will fall back to in-sandbox login when ready."))}}async function M({addon:s,sessionToken:n,apiUrl:t}){let r=process.env.ZIBBY_CLAUDE_CODE_STUB_STATUS;if(r==="ready")return{configured:!0,sandboxState:"ready",sandboxId:"sb_stub_acme_001"};if(r==="provisioning")return{configured:!0,sandboxState:"provisioning",sandboxId:"sb_stub_acme_001"};if(!t||!n)return{configured:!1,sandboxState:null,sandboxId:null};let i=`${String(t).replace(/\/+$/,"")}/agents/addons/${encodeURIComponent(s)}`,e;try{e=await fetch(i,{headers:{Authorization:`Bearer ${n}`}})}catch{return{configured:!1,sandboxState:null,sandboxId:null}}if(e.status===401){let a=new Error("Session expired \u2014 run zibby login");throw a.code="AUTH_EXPIRED",a}if(e.status===404)return{configured:!1,sandboxState:null,sandboxId:null};if(!e.ok)return{configured:!1,sandboxState:null,sandboxId:null};let c=await e.json();return{configured:!!c.configured,sandboxState:c.sandbox_state||null,sandboxId:c.sandbox_id||null,subscriptionId:c.subscription_id||null,enabledAt:c.enabled_at||null}}async function Y({addon:s,workspaceId:n,sessionToken:t,apiUrl:r}){if(!r||!t)return await new Promise(a=>setTimeout(a,500)),{subscriptionId:`sub_${Math.random().toString(36).slice(2,10)}`,sandboxId:`sb_${Math.random().toString(36).slice(2,10)}`,requestId:`req_offline_${Date.now().toString(36)}`};let i=`${String(r).replace(/\/+$/,"")}/agents/addons/${encodeURIComponent(s)}/enable`,e=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({workspace_id:n||null})});if(e.status===401){let a=new Error("Session expired \u2014 run zibby login");throw a.code="AUTH_EXPIRED",a}if(e.status===402){let a;try{a=await e.json()}catch{a={}}let d;try{d=typeof a.error=="string"?JSON.parse(a.error):a.error||a}catch{d={message:a.error||"Payment required"}}let l=new Error(d.message||"Payment required");throw l.code="BILLING_REQUIRED",l.status=402,l.needsSubscription=!!d.needs_subscription,l.needsPaymentMethod=!!d.needs_payment_method,l.upgradeUrl=d.upgrade_url||"/billing",l}if(!e.ok){let a=new Error(`Enable addon failed (${e.status})`);throw a.status=e.status,a}let c=await e.json();return{subscriptionId:c.subscription_id||null,sandboxId:c.sandbox_id||null,stripeSubscriptionItemId:c.stripe_subscription_item_id||null,requestId:c.request_id||`req_${Date.now().toString(36)}`}}function f(s,n){let t=String(s).replace(/\/+$/,"");return n?`${t}/agents/sessions/${encodeURIComponent(n)}`:`${t}/agents/sessions`}async function K({apiUrl:s,sessionToken:n}){if(!n)return[];let t=await fetch(f(s),{headers:{Authorization:`Bearer ${n}`}});if(t.status===401)throw new Error("Not authenticated. Run `zibby login` again.");if(t.status===404)return[];if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`Failed to list agent sessions (${t.status}): ${i.slice(0,200)}`)}let r=await t.json();return Array.isArray(r.sessions)?r.sessions:[]}async function ee({apiUrl:s,sessionToken:n,agentType:t,fields:r={}}){if(!n)throw new Error("Not authenticated");let i=await fetch(f(s,t),{method:"PUT",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok){let c=await i.text().catch(()=>"");throw new Error(`Failed to save agent session (${i.status}): ${c.slice(0,200)}`)}return(await i.json()).session}async function oe({apiUrl:s,sessionToken:n,agentType:t}){if(!n)throw new Error("Not authenticated");let r=await fetch(f(s,t),{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!r.ok){let e=await r.text().catch(()=>"");throw new Error(`Failed to delete agent session (${r.status}): ${e.slice(0,200)}`)}return(await r.json()).deleted===!0}function Z(s){if(!s)return"never";let n=new Date(s).getTime();if(Number.isNaN(n))return"unknown";let t=Math.max(0,(Date.now()-n)/1e3);if(t<60)return"just now";let r=t/60;if(r<60)return`${Math.round(r)}m ago`;let i=r/60;if(i<24)return`${Math.round(i)}h ago`;let e=i/24;if(e<30)return`${Math.round(e)}d ago`;let c=e/30;return`${Math.round(c)}mo ago`}export{u as AGENTS,oe as deleteAgentSession,K as fetchMyAgentSessions,Z as formatRelativeTime,V as handleClaudeCodeAddon,Q as pickAgent,X as pickAgentWithSessions,ee as upsertAgentSession};
|
|
1
|
+
var P=Object.defineProperty;var h=(s,n)=>()=>(s&&(n=s(s=0)),n);var w=(s,n)=>{for(var t in n)P(s,t,{get:n[t],enumerable:!0})};var C={};w(C,{DEFAULT_CONFIG_PATH:()=>m,discoverCredentials:()=>z,maskToken:()=>R,parseConfigJson:()=>x,readCredentialsConfig:()=>_});import T from"node:fs/promises";import U from"node:path";import j from"node:os";function x(s){if(!s)return[];let n;try{n=JSON.parse(s)}catch{return[]}let t=n?.agentKeys;if(!t||typeof t!="object")return[];let r=[],i=new Set;for(let[e,c]of Object.entries($)){let a=t[e];if(!a||typeof a!="string")continue;let d=e.endsWith("_POOL")?a.split(",").map(l=>l.trim()).filter(Boolean):[a.trim()];for(let l of d)l.length<8||i.has(l)||(i.add(l),r.push({type:c,token:l,source_var:e}))}return r}async function _(s=m){let n;try{n=await T.readFile(s,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return x(n)}async function z({filepath:s,env:n=process.env}={}){let t=await _(s),r=new Set(t.map(e=>e.token)),i=[];for(let[e,c]of Object.entries($)){let a=n[e];if(!a)continue;let d=e.endsWith("_POOL")?a.split(",").map(l=>l.trim()).filter(Boolean):[a];for(let l of d)l.length<8||r.has(l)||(r.add(l),i.push({type:c,token:l,source_var:e,source:"process.env"}))}return{config:t.map(e=>({...e,source:"config.json"})),env:i,all:[...t.map(e=>({...e,source:"config.json"})),...i]}}function R(s){return!s||typeof s!="string"||s.length<=4?"***":`***${s.slice(-4)}`}var m,$,S=h(()=>{m=U.join(j.homedir(),".zibby","config.json"),$={CLAUDE_CODE_OAUTH_TOKEN:"oauth",CLAUDE_CODE_OAUTH_TOKEN_POOL:"oauth",ANTHROPIC_AUTH_TOKEN:"oauth",ANTHROPIC_API_KEY:"api",ANTHROPIC_API_KEY_POOL:"api"}});var E={};w(E,{addCredential:()=>A,deleteCredential:()=>D,listCredentials:()=>N,syncFromLocal:()=>L});function y(s,n=""){return`${String(s).replace(/\/+$/,"")}/agents/credentials${n}`}function p(){let s=new Error("Session expired \u2014 run zibby login");return s.code="AUTH_EXPIRED",s}async function N({apiUrl:s,sessionToken:n}){if(!n)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let t=await fetch(y(s),{headers:{Authorization:`Bearer ${n}`}});if(t.status===401)throw p();if(t.status===404)return{credentials:[],by_type:{oauth:[],api:[]},total:0};if(!t.ok){let r=new Error(`List credentials failed (${t.status})`);throw r.status=t.status,r}return t.json()}async function A({apiUrl:s,sessionToken:n,type:t,token:r,provider:i,source:e="~/.zibby/config.json"}){if(!n)throw new Error("No session token \u2014 run zibby login first");let c={type:t,token:r,source:e};i&&(c.provider=i);let a=await fetch(y(s),{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(c)});if(a.status===401)throw p();if(!a.ok){let d=`Add credential failed (${a.status})`;try{let u=await a.json();u?.error&&(d=`${d}: ${u.error}`)}catch{}let l=new Error(d);throw l.status=a.status,l}return a.json()}async function D({apiUrl:s,sessionToken:n,type:t,index:r}){if(!n)throw new Error("No session token \u2014 run zibby login first");let i=await fetch(y(s,`/${encodeURIComponent(t)}/${encodeURIComponent(r)}`),{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(i.status===401)throw p();if(!i.ok){let e=new Error(`Delete credential failed (${i.status})`);throw e.status=i.status,e}return i.json()}async function L({apiUrl:s,sessionToken:n,credentials:t}){let r=0,i=0,e=[];for(let c of t)try{let a=await A({apiUrl:s,sessionToken:n,type:c.type,token:c.token,source:c.source_var||c.source||"local"});a.deduped?i+=1:a.added&&(r+=1)}catch(a){e.push({masked:c.token?`***${c.token.slice(-4)}`:"***",error:a.message})}return{added:r,deduped:i,errors:e}}var I=h(()=>{});import{select as O,confirm as f,Separator as v}from"@inquirer/prompts";import o from"chalk";var g=[{id:"zibby",name:"Zibby Chat",short:"default",description:"Built-in chat using Anthropic SDK directly \xB7 BYOK \xB7 included with workspace",pricePerMonth:0,deployment:"instant"},{id:"claude-code",name:"Claude Code",short:"add-on",description:"Anthropic's Claude Code CLI deployed in your private sandbox",pricePerMonth:20,deployment:"fargate-warm"}];async function X({apiUrl:s,sessionToken:n,currentAgentId:t="zibby"}={}){let r;try{r=await K({apiUrl:s,sessionToken:n})}catch(e){if(/login/i.test(e.message))throw e;console.warn(o.gray(` (could not fetch sessions: ${e.message})`)),r=[]}let i=[];if(r.length>0){for(let e of r){let a=g.find(k=>k.id===e.agent_type)?.name||e.agent_type,d=Z(e.last_active),l=typeof e.message_count=="number"&&e.message_count>0?o.gray(` \xB7 ${e.message_count} msg`):"",u=e.label?o.gray(` \xB7 "${e.label}"`):"";i.push({name:`${o.cyan("\u2726")} ${a} ${o.gray(`(${d})`)}${u}${l}`,value:{action:"resume",agentType:e.agent_type,sessionId:e.session_id,session:e},description:o.gray(` Resume your ${a} session`)})}i.push(new v)}for(let e of g)e.id!=="zibby"&&i.push({name:`${o.dim("+")} New ${e.name} session${e.pricePerMonth>0?o.yellow(` (+$${e.pricePerMonth}/mo)`):""}`,value:{action:"create",agentType:e.id},description:o.gray(` ${e.description}`)});i.push(new v),i.push({name:`${o.green("\u2190")} Back to Zibby Chat (default)${t==="zibby"?o.dim(" [current]"):""}`,value:{action:"switch",agentType:"zibby"},description:o.gray(" Built-in chat using Anthropic SDK directly")});try{return await O({message:"Select chat agent:",choices:i})}catch(e){if(e?.name==="ExitPromptError")return{action:"cancel"};throw e}}async function Q(s="zibby"){let n=await O({message:"Select chat agent for this workspace:",default:s,choices:g.map(t=>{let r=t.pricePerMonth===0?o.green(" (included)"):o.yellow(` (+$${t.pricePerMonth}/mo)`),i=t.id===s?o.dim(" [current]"):"";return{name:`${t.name}${r}${i}`,value:t.id,description:o.gray(` ${t.description}`)}})});return g.find(t=>t.id===n)}async function V({workspaceId:s,sessionToken:n,apiUrl:t}){let r=await M({addon:"claude-code",workspaceId:s,sessionToken:n,apiUrl:t});if(r.configured&&r.sandboxState==="ready")return console.log(""),console.log(o.green(" \u2713 Claude Code is already deployed for your team.")),console.log(o.gray(` Sandbox: ${r.sandboxId} \xB7 state: ${r.sandboxState}`)),console.log(""),{ready:!0,sandboxId:r.sandboxId};if(r.configured&&r.sandboxState!=="ready")return console.log(""),console.log(o.cyan(` \u2699 Claude Code sandbox is ${r.sandboxState}...`)),console.log(o.gray(" You can keep using Zibby Chat \u2014 we'll switch when it's ready.")),console.log(""),{ready:!1,provisioning:!0,sandboxId:r.sandboxId};if(console.log(""),console.log(o.yellow(" Claude Code add-on is not enabled for your workspace.")),console.log(""),console.log(o.white(" About this add-on:")),console.log(o.gray(" \u2022 Anthropic's official Claude Code CLI runs in YOUR isolated sandbox")),console.log(o.gray(" \u2022 YOU provide your own Anthropic credentials (in ~/.zibby/config.json)")),console.log(o.gray(" \u2022 Zibby NEVER accesses Anthropic on your behalf \u2014 your tokens, your API calls")),console.log(o.gray(" \u2022 Zibby stores credentials KMS-encrypted, decrypts only inside YOUR sandbox")),console.log(o.gray(" \u2022 You're responsible for ToS compliance with the credentials you provide:")),console.log(o.gray(" https://www.anthropic.com/legal/commercial-terms")),console.log(""),console.log(o.cyan(" Pricing:")),console.log(o.white(" $20 / month per workspace ")+o.gray("\xB7 Zibby infrastructure fee, billed via Stripe")),console.log(o.gray(" Your Anthropic usage bills directly to your Anthropic account")),console.log(""),!await f({message:"Do you agree to Anthropic's Commercial Terms of Service?",default:!1}))return console.log(o.gray(" Cancelled. Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0};if(!await f({message:"Enable Claude Code add-on at $20/month?",default:!1}))return console.log(o.gray(" Cancelled. Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0};console.log(""),console.log(o.cyan(" Enabling Claude Code add-on..."));let c;try{c=await Y({addon:"claude-code",workspaceId:s,sessionToken:n,apiUrl:t,accept:{tos:!0,billing:!0}})}catch(a){if(a?.code==="BILLING_REQUIRED"){console.log("");let d=a.upgradeUrl?.startsWith("http")?a.upgradeUrl:"https://zibby.dev/billing";return a.needsSubscription?(console.log(o.yellow(" \u26A0 You need an active Pro subscription to enable Claude Code.")),console.log(o.gray(` Upgrade here: ${d}`))):a.needsPaymentMethod?(console.log(o.yellow(" \u26A0 Your card was declined or no payment method is on file.")),console.log(o.gray(` Update billing: ${d}`))):(console.log(o.yellow(` \u26A0 ${a.message}`)),console.log(o.gray(` Manage billing: ${d}`))),console.log(""),console.log(o.gray(" Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0,billingRequired:!0}}throw a}return console.log(""),console.log(o.green(" \u2713 Stripe subscription created")),console.log(o.gray(` sub_id: ${c.subscriptionId}`)),console.log(o.green(" \u2713 Lambda invoked: zibby-prod-provision-sandbox")),console.log(o.gray(` request: ${c.requestId}`)),console.log(o.cyan(" \u2699 Fargate task launching: zibby/agent-runtime:claude-code-v1")),console.log(o.gray(` sandbox_id: ${c.sandboxId}`)),console.log(""),await B({apiUrl:t,sessionToken:n}),console.log(""),console.log(o.gray(" Sandbox provisioning in the background. Zibby Chat (default) is active until ready.")),console.log(""),{ready:!1,provisioning:!0,sandboxId:c.sandboxId,deploymentId:c.requestId}}async function B({apiUrl:s,sessionToken:n}){let t;try{let{discoverCredentials:e}=await Promise.resolve().then(()=>(S(),C));t=await e()}catch(e){console.log(o.gray(` (could not scan local credentials: ${e.message})`));return}let r=t.all.length;if(r===0){console.log(o.yellow(" \u26A0 No Anthropic credentials found locally.")),console.log(""),console.log(o.white(" Two ways to authenticate Claude Code in your sandbox:")),console.log(""),console.log(o.bold(" Option A \u2014 provide your own (recommended):")),console.log(o.gray(" 1. Run: zibby init")),console.log(o.gray(" Pick Claude \u2192 Subscription (OAuth) or API key")),console.log(o.gray(" 2. Run: zibby creds sync (uploads to your workspace)")),console.log(o.gray(" 3. Re-run /agents in chat")),console.log(""),console.log(o.bold(" Option B \u2014 in-sandbox login (legacy):")),console.log(o.gray(" Skip this step. When sandbox is ready and you start")),console.log(o.gray(" Claude Code, it will prompt you to open a URL in your")),console.log(o.gray(" laptop browser to authenticate.")),console.log("");return}console.log(o.green(` \u2713 Found ${r} Anthropic ${r===1?"credential":"credentials"} in your local environment:`));for(let e of t.all){let c=e.source==="config.json"?`~/.zibby/config.json (${e.source_var})`:`process.env.${e.source_var}`;console.log(o.gray(` ${e.type} ***${e.token.slice(-4)} ${c}`))}if(console.log(""),console.log(o.white(" By proceeding you confirm:")),console.log(o.gray(" \u2022 These are YOUR credentials to use")),console.log(o.gray(" \u2022 You comply with Anthropic's ToS for the tier of these tokens")),console.log(o.gray(" \u2022 Zibby will store encrypted (AWS KMS) and inject into YOUR sandbox only")),console.log(""),!await f({message:"Upload these credentials to your Zibby workspace?",default:!0})){console.log(o.gray(" Skipped credential upload. Sandbox will fall back to in-sandbox login."));return}console.log(""),console.log(o.cyan(" Uploading (KMS-encrypted)..."));try{let{syncFromLocal:e}=await Promise.resolve().then(()=>(I(),E)),c=await e({apiUrl:s,sessionToken:n,credentials:t.all});console.log(o.green(` \u2713 ${c.added} new, ${c.deduped} already stored`)),c.errors.length>0&&console.log(o.yellow(` ${c.errors.length} failed \u2014 retry with 'zibby creds sync'`))}catch(e){console.log(o.red(` \u2717 Upload failed: ${e.message}`)),console.log(o.gray(" Sandbox will fall back to in-sandbox login when ready."))}}async function M({addon:s,sessionToken:n,apiUrl:t}){let r=process.env.ZIBBY_CLAUDE_CODE_STUB_STATUS;if(r==="ready")return{configured:!0,sandboxState:"ready",sandboxId:"sb_stub_acme_001"};if(r==="provisioning")return{configured:!0,sandboxState:"provisioning",sandboxId:"sb_stub_acme_001"};if(!t||!n)return{configured:!1,sandboxState:null,sandboxId:null};let i=`${String(t).replace(/\/+$/,"")}/agents/addons/${encodeURIComponent(s)}`,e;try{e=await fetch(i,{headers:{Authorization:`Bearer ${n}`}})}catch{return{configured:!1,sandboxState:null,sandboxId:null}}if(e.status===401){let a=new Error("Session expired \u2014 run zibby login");throw a.code="AUTH_EXPIRED",a}if(e.status===404)return{configured:!1,sandboxState:null,sandboxId:null};if(!e.ok)return{configured:!1,sandboxState:null,sandboxId:null};let c=await e.json();return{configured:!!c.configured,sandboxState:c.sandbox_state||null,sandboxId:c.sandbox_id||null,subscriptionId:c.subscription_id||null,enabledAt:c.enabled_at||null}}async function Y({addon:s,workspaceId:n,sessionToken:t,apiUrl:r}){if(!r||!t)return await new Promise(a=>setTimeout(a,500)),{subscriptionId:`sub_${Math.random().toString(36).slice(2,10)}`,sandboxId:`sb_${Math.random().toString(36).slice(2,10)}`,requestId:`req_offline_${Date.now().toString(36)}`};let i=`${String(r).replace(/\/+$/,"")}/agents/addons/${encodeURIComponent(s)}/enable`,e=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({workspace_id:n||null})});if(e.status===401){let a=new Error("Session expired \u2014 run zibby login");throw a.code="AUTH_EXPIRED",a}if(e.status===402){let a;try{a=await e.json()}catch{a={}}let d;try{d=typeof a.error=="string"?JSON.parse(a.error):a.error||a}catch{d={message:a.error||"Payment required"}}let l=new Error(d.message||"Payment required");throw l.code="BILLING_REQUIRED",l.status=402,l.needsSubscription=!!d.needs_subscription,l.needsPaymentMethod=!!d.needs_payment_method,l.upgradeUrl=d.upgrade_url||"/billing",l}if(!e.ok){let a=new Error(`Enable addon failed (${e.status})`);throw a.status=e.status,a}let c=await e.json();return{subscriptionId:c.subscription_id||null,sandboxId:c.sandbox_id||null,stripeSubscriptionItemId:c.stripe_subscription_item_id||null,requestId:c.request_id||`req_${Date.now().toString(36)}`}}function b(s,n){let t=String(s).replace(/\/+$/,"");return n?`${t}/agents/sessions/${encodeURIComponent(n)}`:`${t}/agents/sessions`}async function K({apiUrl:s,sessionToken:n}){if(!n)return[];let t=await fetch(b(s),{headers:{Authorization:`Bearer ${n}`}});if(t.status===401)throw new Error("Not authenticated. Run `zibby login` again.");if(t.status===404)return[];if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`Failed to list agent sessions (${t.status}): ${i.slice(0,200)}`)}let r=await t.json();return Array.isArray(r.sessions)?r.sessions:[]}async function ee({apiUrl:s,sessionToken:n,agentType:t,fields:r={}}){if(!n)throw new Error("Not authenticated");let i=await fetch(b(s,t),{method:"PUT",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok){let c=await i.text().catch(()=>"");throw new Error(`Failed to save agent session (${i.status}): ${c.slice(0,200)}`)}return(await i.json()).session}async function oe({apiUrl:s,sessionToken:n,agentType:t}){if(!n)throw new Error("Not authenticated");let r=await fetch(b(s,t),{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!r.ok){let e=await r.text().catch(()=>"");throw new Error(`Failed to delete agent session (${r.status}): ${e.slice(0,200)}`)}return(await r.json()).deleted===!0}function Z(s){if(!s)return"never";let n=new Date(s).getTime();if(Number.isNaN(n))return"unknown";let t=Math.max(0,(Date.now()-n)/1e3);if(t<60)return"just now";let r=t/60;if(r<60)return`${Math.round(r)}m ago`;let i=r/60;if(i<24)return`${Math.round(i)}h ago`;let e=i/24;if(e<30)return`${Math.round(e)}d ago`;let c=e/30;return`${Math.round(c)}mo ago`}export{g as AGENTS,oe as deleteAgentSession,K as fetchMyAgentSessions,Z as formatRelativeTime,V as handleClaudeCodeAddon,Q as pickAgent,X as pickAgentWithSessions,ee as upsertAgentSession};
|
package/dist/commands/chat.js
CHANGED
|
@@ -1,77 +1,77 @@
|
|
|
1
|
-
var Go=Object.defineProperty;var $e=(t,e)=>()=>(t&&(e=t(t=0)),e);var ve=(t,e)=>{for(var o in e)Go(t,o,{get:e[o],enumerable:!0})};var so={};ve(so,{_resetLoaderCacheForTests:()=>mn,loadCredentialsIntoEnv:()=>gn});import oo from"node:fs";import ln from"node:path";import un from"node:os";async function no(){if(!(process.env.__ZIBBY_CLAUDE_PLAN||process.platform!=="darwin"||!(process.env.CLAUDE_CODE_OAUTH_TOKEN||process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL||process.env.ANTHROPIC_AUTH_TOKEN)))try{let{execSync:e}=await import("node:child_process"),o=e('security find-generic-password -s "Claude Code-credentials" -w',{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(o){let r=JSON.parse(o)?.claudeAiOauth?.subscriptionType;r&&(process.env.__ZIBBY_CLAUDE_PLAN=r)}}catch{}}function fn(t){try{if(!oo.existsSync(t))return{};let e=oo.readFileSync(t,"utf-8"),o=JSON.parse(e);return o&&o.agentKeys&&typeof o.agentKeys=="object"?o.agentKeys:{}}catch{return{}}}async function gn(t={}){let{verbose:e=!1,force:o=!1,configPath:n}=t;if(
|
|
1
|
+
var Go=Object.defineProperty;var $e=(t,e)=>()=>(t&&(e=t(t=0)),e);var ve=(t,e)=>{for(var o in e)Go(t,o,{get:e[o],enumerable:!0})};var so={};ve(so,{_resetLoaderCacheForTests:()=>mn,loadCredentialsIntoEnv:()=>gn});import oo from"node:fs";import ln from"node:path";import un from"node:os";async function no(){if(!(process.env.__ZIBBY_CLAUDE_PLAN||process.platform!=="darwin"||!(process.env.CLAUDE_CODE_OAUTH_TOKEN||process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL||process.env.ANTHROPIC_AUTH_TOKEN)))try{let{execSync:e}=await import("node:child_process"),o=e('security find-generic-password -s "Claude Code-credentials" -w',{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(o){let r=JSON.parse(o)?.claudeAiOauth?.subscriptionType;r&&(process.env.__ZIBBY_CLAUDE_PLAN=r)}}catch{}}function fn(t){try{if(!oo.existsSync(t))return{};let e=oo.readFileSync(t,"utf-8"),o=JSON.parse(e);return o&&o.agentKeys&&typeof o.agentKeys=="object"?o.agentKeys:{}}catch{return{}}}async function gn(t={}){let{verbose:e=!1,force:o=!1,configPath:n}=t;if(Ke&&!o)return Ae;if(!!(process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL||process.env.ANTHROPIC_API_KEY_POOL||process.env.CLAUDE_CODE_OAUTH_TOKEN||process.env.ANTHROPIC_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN))return await no(),Ke=!0,Ae={oauthCount:0,apiCount:0,source:"cloud-env"},e&&console.log("[credentials-loader] env vars already set \u2014 skipping local discovery"),Ae;let s=n||ln.join(un.homedir(),".zibby","config.json"),a=fn(s),c="none",l=0,p=0;for(let _ of dn)a[_]&&!process.env[_]&&(process.env[_]=String(a[_]).trim(),c="config.json",_.endsWith("_POOL")?l+=String(a[_]).split(",").filter(z=>z.trim()).length:l+=1);for(let _ of pn)a[_]&&!process.env[_]&&(process.env[_]=String(a[_]).trim(),c="config.json",_.endsWith("_POOL")?p+=String(a[_]).split(",").filter(z=>z.trim()).length:p+=1);return await no(),Ke=!0,Ae={oauthCount:l,apiCount:p,source:c},e&&l+p>0&&console.log(`[credentials-loader] loaded ${l} OAuth + ${p} API from ${c} (~/.zibby/config.json)`),Ae}function mn(){Ke=!1,Ae=null}var Ke,Ae,dn,pn,ro=$e(()=>{Ke=!1,Ae=null,dn=["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN_POOL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_AUTH_TOKEN_POOL"],pn=["ANTHROPIC_API_KEY","ANTHROPIC_API_KEY_POOL"]});var pt={};ve(pt,{cleanupStalePidFiles:()=>kn,killAllChatOrchestratedRuns:()=>vn,killPidTreeBestEffort:()=>lo,registerChatOrchestratedRun:()=>_n,unregisterChatOrchestratedRun:()=>Sn});import{existsSync as lt,mkdirSync as hn,readFileSync as yn,readdirSync as bn,unlinkSync as ut,writeFileSync as ao}from"fs";import{join as Ze}from"path";import{execSync as co}from"child_process";import{DEFAULT_OUTPUT_BASE as wn}from"@zibby/core";function We(t){return t?.paths?.output||wn}function Je(t,e,o){return Ze(t,e,`.zibby-chat-run-pids-${o}.json`)}function dt(t,e,o){let n=Je(t,e,o);if(!lt(n))return[];try{let r=JSON.parse(yn(n,"utf8"));return(Array.isArray(r?.pids)?r.pids:[]).map(a=>Number(a)).filter(a=>Number.isFinite(a)&&a>0)}catch{return[]}}function _n(t,e,o,n={}){let r=Number(e),s=Number(o);if(!Number.isFinite(r)||r<=0||!Number.isFinite(s)||s<=0)return;let a=We(n),c=Ze(t,a);hn(c,{recursive:!0});let l=dt(t,a,r);l.includes(s)||l.push(s),ao(Je(t,a,r),`${JSON.stringify({v:1,pids:l})}
|
|
2
2
|
`,"utf8")}function Sn(t,e,o,n={}){let r=Number(e),s=Number(o);if(!Number.isFinite(r)||r<=0||!Number.isFinite(s)||s<=0)return;let a=We(n),c=Je(t,a,r);if(!lt(c))return;let l=dt(t,a,r).filter(p=>p!==s);if(l.length===0)try{ut(c)}catch{}else ao(c,`${JSON.stringify({v:1,pids:l})}
|
|
3
|
-
`,"utf8")}function xn(t){let e=Number(t);if(!Number.isFinite(e)||e<=0)return[];try{let o=co(`pgrep -P ${e}`,{encoding:"utf8",stdio:["ignore","pipe","ignore"],maxBuffer:524288}).trim();return o?o.split(/\n/).map(n=>parseInt(n.trim(),10)).filter(n=>Number.isFinite(n)&&n>0):[]}catch{return[]}}function io(t,e){let o=Number(t);if(!Number.isFinite(o)||o<=0)return;let n=new Set;function r(s){if(!n.has(s)){n.add(s);for(let a of xn(s))r(a);try{process.kill(s,e)}catch{}}}r(o)}function $n(t){let e=Number(t);if(!(!Number.isFinite(e)||e<=0))try{co(`taskkill /PID ${e} /T /F`,{stdio:"ignore",windowsHide:!0})}catch{}}function lo(t){let e=Number(t);if(!Number.isFinite(e)||e<=0)return;if(process.platform==="win32"){$n(e);return}io(e,"SIGTERM");let o=setTimeout(()=>{io(e,"SIGKILL")},800);typeof o.unref=="function"&&o.unref()}function vn(t,e,o={}){let n=Number(e);if(!Number.isFinite(n)||n<=0)return;let r=We(o),s=Je(t,r,n),a=dt(t,r,n);for(let c of a)c!==process.pid&&lo(c);try{lt(s)&&ut(s)}catch{}}function An(t){try{return process.kill(t,0),!0}catch{return!1}}function kn(t,e={}){let o=We(e),n=Ke(t,o),r;try{r=bn(n)}catch{return}for(let s of r){let a=Cn.exec(s);if(!a)continue;let c=Number(a[1]);if(!(!Number.isFinite(c)||c<=0)&&!An(c))try{ut(Ke(n,s))}catch{}}}var Cn,ft=$e(()=>{Cn=/^\.zibby-chat-run-pids-(\d+)\.json$/});var mo={};ve(mo,{DEFAULT_CONFIG_PATH:()=>uo,discoverCredentials:()=>En,maskToken:()=>On,parseConfigJson:()=>fo,readCredentialsConfig:()=>go});import In from"node:fs/promises";import Tn from"node:path";import Pn from"node:os";function fo(t){if(!t)return[];let e;try{e=JSON.parse(t)}catch{return[]}let o=e?.agentKeys;if(!o||typeof o!="object")return[];let n=[],r=new Set;for(let[s,a]of Object.entries(po)){let c=o[s];if(!c||typeof c!="string")continue;let l=s.endsWith("_POOL")?c.split(",").map(p=>p.trim()).filter(Boolean):[c.trim()];for(let p of l)p.length<8||r.has(p)||(r.add(p),n.push({type:a,token:p,source_var:s}))}return n}async function go(t=uo){let e;try{e=await In.readFile(t,"utf8")}catch(o){if(o.code==="ENOENT")return[];throw o}return fo(e)}async function En({filepath:t,env:e=process.env}={}){let o=await go(t),n=new Set(o.map(s=>s.token)),r=[];for(let[s,a]of Object.entries(po)){let c=e[s];if(!c)continue;let l=s.endsWith("_POOL")?c.split(",").map(p=>p.trim()).filter(Boolean):[c];for(let p of l)p.length<8||n.has(p)||(n.add(p),r.push({type:a,token:p,source_var:s,source:"process.env"}))}return{config:o.map(s=>({...s,source:"config.json"})),env:r,all:[...o.map(s=>({...s,source:"config.json"})),...r]}}function On(t){return!t||typeof t!="string"||t.length<=4?"***":`***${t.slice(-4)}`}var uo,po,ho=$e(()=>{uo=Tn.join(Pn.homedir(),".zibby","config.json"),po={CLAUDE_CODE_OAUTH_TOKEN:"oauth",CLAUDE_CODE_OAUTH_TOKEN_POOL:"oauth",ANTHROPIC_AUTH_TOKEN:"oauth",ANTHROPIC_API_KEY:"api",ANTHROPIC_API_KEY_POOL:"api"}});var bo={};ve(bo,{addCredential:()=>yo,deleteCredential:()=>Un,listCredentials:()=>Nn,syncFromLocal:()=>Ln});function gt(t,e=""){return`${String(t).replace(/\/+$/,"")}/agents/credentials${e}`}function mt(){let t=new Error("Session expired \u2014 run zibby login");return t.code="AUTH_EXPIRED",t}async function Nn({apiUrl:t,sessionToken:e}){if(!e)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let o=await fetch(gt(t),{headers:{Authorization:`Bearer ${e}`}});if(o.status===401)throw mt();if(o.status===404)return{credentials:[],by_type:{oauth:[],api:[]},total:0};if(!o.ok){let n=new Error(`List credentials failed (${o.status})`);throw n.status=o.status,n}return o.json()}async function yo({apiUrl:t,sessionToken:e,type:o,token:n,source:r="~/.zibby/config.json"}){if(!e)throw new Error("No session token \u2014 run zibby login first");let s=await fetch(gt(t),{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({type:o,token:n,source:r})});if(s.status===401)throw mt();if(!s.ok){let a=`Add credential failed (${s.status})`;try{let l=await s.json();l?.error&&(a=`${a}: ${l.error}`)}catch{}let c=new Error(a);throw c.status=s.status,c}return s.json()}async function Un({apiUrl:t,sessionToken:e,type:o,index:n}){if(!e)throw new Error("No session token \u2014 run zibby login first");let r=await fetch(gt(t,`/${encodeURIComponent(o)}/${encodeURIComponent(n)}`),{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(r.status===401)throw mt();if(!r.ok){let s=new Error(`Delete credential failed (${r.status})`);throw s.status=r.status,s}return r.json()}async function Ln({apiUrl:t,sessionToken:e,credentials:o}){let n=0,r=0,s=[];for(let a of o)try{let c=await yo({apiUrl:t,sessionToken:e,type:a.type,token:a.token,source:a.source_var||a.source||"local"});c.deduped?r+=1:c.added&&(n+=1)}catch(c){s.push({masked:a.token?`***${a.token.slice(-4)}`:"***",error:c.message})}return{added:n,deduped:r,errors:s}}var wo=$e(()=>{});var vo={};ve(vo,{AGENTS:()=>Le,deleteAgentSession:()=>Yn,fetchMyAgentSessions:()=>xo,formatRelativeTime:()=>$o,handleClaudeCodeAddon:()=>Dn,pickAgent:()=>Bn,pickAgentWithSessions:()=>Rn,upsertAgentSession:()=>Fn});import{select as So,confirm as ht,Separator as _o}from"@inquirer/prompts";import u from"chalk";async function Rn({apiUrl:t,sessionToken:e,currentAgentId:o="zibby"}={}){let n;try{n=await xo({apiUrl:t,sessionToken:e})}catch(s){if(/login/i.test(s.message))throw s;console.warn(u.gray(` (could not fetch sessions: ${s.message})`)),n=[]}let r=[];if(n.length>0){for(let s of n){let c=Le.find(z=>z.id===s.agent_type)?.name||s.agent_type,l=$o(s.last_active),p=typeof s.message_count=="number"&&s.message_count>0?u.gray(` \xB7 ${s.message_count} msg`):"",$=s.label?u.gray(` \xB7 "${s.label}"`):"";r.push({name:`${u.cyan("\u2726")} ${c} ${u.gray(`(${l})`)}${$}${p}`,value:{action:"resume",agentType:s.agent_type,sessionId:s.session_id,session:s},description:u.gray(` Resume your ${c} session`)})}r.push(new _o)}for(let s of Le)s.id!=="zibby"&&r.push({name:`${u.dim("+")} New ${s.name} session${s.pricePerMonth>0?u.yellow(` (+$${s.pricePerMonth}/mo)`):""}`,value:{action:"create",agentType:s.id},description:u.gray(` ${s.description}`)});r.push(new _o),r.push({name:`${u.green("\u2190")} Back to Zibby Chat (default)${o==="zibby"?u.dim(" [current]"):""}`,value:{action:"switch",agentType:"zibby"},description:u.gray(" Built-in chat using Anthropic SDK directly")});try{return await So({message:"Select chat agent:",choices:r})}catch(s){if(s?.name==="ExitPromptError")return{action:"cancel"};throw s}}async function Bn(t="zibby"){let e=await So({message:"Select chat agent for this workspace:",default:t,choices:Le.map(o=>{let n=o.pricePerMonth===0?u.green(" (included)"):u.yellow(` (+$${o.pricePerMonth}/mo)`),r=o.id===t?u.dim(" [current]"):"";return{name:`${o.name}${n}${r}`,value:o.id,description:u.gray(` ${o.description}`)}})});return Le.find(o=>o.id===e)}async function Dn({workspaceId:t,sessionToken:e,apiUrl:o}){let n=await jn({addon:"claude-code",workspaceId:t,sessionToken:e,apiUrl:o});if(n.configured&&n.sandboxState==="ready")return console.log(""),console.log(u.green(" \u2713 Claude Code is already deployed for your team.")),console.log(u.gray(` Sandbox: ${n.sandboxId} \xB7 state: ${n.sandboxState}`)),console.log(""),{ready:!0,sandboxId:n.sandboxId};if(n.configured&&n.sandboxState!=="ready")return console.log(""),console.log(u.cyan(` \u2699 Claude Code sandbox is ${n.sandboxState}...`)),console.log(u.gray(" You can keep using Zibby Chat \u2014 we'll switch when it's ready.")),console.log(""),{ready:!1,provisioning:!0,sandboxId:n.sandboxId};if(console.log(""),console.log(u.yellow(" Claude Code add-on is not enabled for your workspace.")),console.log(""),console.log(u.white(" About this add-on:")),console.log(u.gray(" \u2022 Anthropic's official Claude Code CLI runs in YOUR isolated sandbox")),console.log(u.gray(" \u2022 YOU provide your own Anthropic credentials (in ~/.zibby/config.json)")),console.log(u.gray(" \u2022 Zibby NEVER accesses Anthropic on your behalf \u2014 your tokens, your API calls")),console.log(u.gray(" \u2022 Zibby stores credentials KMS-encrypted, decrypts only inside YOUR sandbox")),console.log(u.gray(" \u2022 You're responsible for ToS compliance with the credentials you provide:")),console.log(u.gray(" https://www.anthropic.com/legal/commercial-terms")),console.log(""),console.log(u.cyan(" Pricing:")),console.log(u.white(" $20 / month per workspace ")+u.gray("\xB7 Zibby infrastructure fee, billed via Stripe")),console.log(u.gray(" Your Anthropic usage bills directly to your Anthropic account")),console.log(""),!await ht({message:"Do you agree to Anthropic's Commercial Terms of Service?",default:!1}))return console.log(u.gray(" Cancelled. Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0};if(!await ht({message:"Enable Claude Code add-on at $20/month?",default:!1}))return console.log(u.gray(" Cancelled. Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0};console.log(""),console.log(u.cyan(" Enabling Claude Code add-on..."));let a;try{a=await zn({addon:"claude-code",workspaceId:t,sessionToken:e,apiUrl:o,accept:{tos:!0,billing:!0}})}catch(c){if(c?.code==="BILLING_REQUIRED"){console.log("");let l=c.upgradeUrl?.startsWith("http")?c.upgradeUrl:"https://zibby.dev/billing";return c.needsSubscription?(console.log(u.yellow(" \u26A0 You need an active Pro subscription to enable Claude Code.")),console.log(u.gray(` Upgrade here: ${l}`))):c.needsPaymentMethod?(console.log(u.yellow(" \u26A0 Your card was declined or no payment method is on file.")),console.log(u.gray(` Update billing: ${l}`))):(console.log(u.yellow(` \u26A0 ${c.message}`)),console.log(u.gray(` Manage billing: ${l}`))),console.log(""),console.log(u.gray(" Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0,billingRequired:!0}}throw c}return console.log(""),console.log(u.green(" \u2713 Stripe subscription created")),console.log(u.gray(` sub_id: ${a.subscriptionId}`)),console.log(u.green(" \u2713 Lambda invoked: zibby-prod-provision-sandbox")),console.log(u.gray(` request: ${a.requestId}`)),console.log(u.cyan(" \u2699 Fargate task launching: zibby/agent-runtime:claude-code-v1")),console.log(u.gray(` sandbox_id: ${a.sandboxId}`)),console.log(""),await Mn({apiUrl:o,sessionToken:e}),console.log(""),console.log(u.gray(" Sandbox provisioning in the background. Zibby Chat (default) is active until ready.")),console.log(""),{ready:!1,provisioning:!0,sandboxId:a.sandboxId,deploymentId:a.requestId}}async function Mn({apiUrl:t,sessionToken:e}){let o;try{let{discoverCredentials:s}=await Promise.resolve().then(()=>(ho(),mo));o=await s()}catch(s){console.log(u.gray(` (could not scan local credentials: ${s.message})`));return}let n=o.all.length;if(n===0){console.log(u.yellow(" \u26A0 No Anthropic credentials found locally.")),console.log(""),console.log(u.white(" Two ways to authenticate Claude Code in your sandbox:")),console.log(""),console.log(u.bold(" Option A \u2014 provide your own (recommended):")),console.log(u.gray(" 1. Run: zibby init")),console.log(u.gray(" Pick Claude \u2192 Subscription (OAuth) or API key")),console.log(u.gray(" 2. Run: zibby creds sync (uploads to your workspace)")),console.log(u.gray(" 3. Re-run /agents in chat")),console.log(""),console.log(u.bold(" Option B \u2014 in-sandbox login (legacy):")),console.log(u.gray(" Skip this step. When sandbox is ready and you start")),console.log(u.gray(" Claude Code, it will prompt you to open a URL in your")),console.log(u.gray(" laptop browser to authenticate.")),console.log("");return}console.log(u.green(` \u2713 Found ${n} Anthropic ${n===1?"credential":"credentials"} in your local environment:`));for(let s of o.all){let a=s.source==="config.json"?`~/.zibby/config.json (${s.source_var})`:`process.env.${s.source_var}`;console.log(u.gray(` ${s.type} ***${s.token.slice(-4)} ${a}`))}if(console.log(""),console.log(u.white(" By proceeding you confirm:")),console.log(u.gray(" \u2022 These are YOUR credentials to use")),console.log(u.gray(" \u2022 You comply with Anthropic's ToS for the tier of these tokens")),console.log(u.gray(" \u2022 Zibby will store encrypted (AWS KMS) and inject into YOUR sandbox only")),console.log(""),!await ht({message:"Upload these credentials to your Zibby workspace?",default:!0})){console.log(u.gray(" Skipped credential upload. Sandbox will fall back to in-sandbox login."));return}console.log(""),console.log(u.cyan(" Uploading (KMS-encrypted)..."));try{let{syncFromLocal:s}=await Promise.resolve().then(()=>(wo(),bo)),a=await s({apiUrl:t,sessionToken:e,credentials:o.all});console.log(u.green(` \u2713 ${a.added} new, ${a.deduped} already stored`)),a.errors.length>0&&console.log(u.yellow(` ${a.errors.length} failed \u2014 retry with 'zibby creds sync'`))}catch(s){console.log(u.red(` \u2717 Upload failed: ${s.message}`)),console.log(u.gray(" Sandbox will fall back to in-sandbox login when ready."))}}async function jn({addon:t,sessionToken:e,apiUrl:o}){let n=process.env.ZIBBY_CLAUDE_CODE_STUB_STATUS;if(n==="ready")return{configured:!0,sandboxState:"ready",sandboxId:"sb_stub_acme_001"};if(n==="provisioning")return{configured:!0,sandboxState:"provisioning",sandboxId:"sb_stub_acme_001"};if(!o||!e)return{configured:!1,sandboxState:null,sandboxId:null};let r=`${String(o).replace(/\/+$/,"")}/agents/addons/${encodeURIComponent(t)}`,s;try{s=await fetch(r,{headers:{Authorization:`Bearer ${e}`}})}catch{return{configured:!1,sandboxState:null,sandboxId:null}}if(s.status===401){let c=new Error("Session expired \u2014 run zibby login");throw c.code="AUTH_EXPIRED",c}if(s.status===404)return{configured:!1,sandboxState:null,sandboxId:null};if(!s.ok)return{configured:!1,sandboxState:null,sandboxId:null};let a=await s.json();return{configured:!!a.configured,sandboxState:a.sandbox_state||null,sandboxId:a.sandbox_id||null,subscriptionId:a.subscription_id||null,enabledAt:a.enabled_at||null}}async function zn({addon:t,workspaceId:e,sessionToken:o,apiUrl:n}){if(!n||!o)return await new Promise(c=>setTimeout(c,500)),{subscriptionId:`sub_${Math.random().toString(36).slice(2,10)}`,sandboxId:`sb_${Math.random().toString(36).slice(2,10)}`,requestId:`req_offline_${Date.now().toString(36)}`};let r=`${String(n).replace(/\/+$/,"")}/agents/addons/${encodeURIComponent(t)}/enable`,s=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({workspace_id:e||null})});if(s.status===401){let c=new Error("Session expired \u2014 run zibby login");throw c.code="AUTH_EXPIRED",c}if(s.status===402){let c;try{c=await s.json()}catch{c={}}let l;try{l=typeof c.error=="string"?JSON.parse(c.error):c.error||c}catch{l={message:c.error||"Payment required"}}let p=new Error(l.message||"Payment required");throw p.code="BILLING_REQUIRED",p.status=402,p.needsSubscription=!!l.needs_subscription,p.needsPaymentMethod=!!l.needs_payment_method,p.upgradeUrl=l.upgrade_url||"/billing",p}if(!s.ok){let c=new Error(`Enable addon failed (${s.status})`);throw c.status=s.status,c}let a=await s.json();return{subscriptionId:a.subscription_id||null,sandboxId:a.sandbox_id||null,stripeSubscriptionItemId:a.stripe_subscription_item_id||null,requestId:a.request_id||`req_${Date.now().toString(36)}`}}function yt(t,e){let o=String(t).replace(/\/+$/,"");return e?`${o}/agents/sessions/${encodeURIComponent(e)}`:`${o}/agents/sessions`}async function xo({apiUrl:t,sessionToken:e}){if(!e)return[];let o=await fetch(yt(t),{headers:{Authorization:`Bearer ${e}`}});if(o.status===401)throw new Error("Not authenticated. Run `zibby login` again.");if(o.status===404)return[];if(!o.ok){let r=await o.text().catch(()=>"");throw new Error(`Failed to list agent sessions (${o.status}): ${r.slice(0,200)}`)}let n=await o.json();return Array.isArray(n.sessions)?n.sessions:[]}async function Fn({apiUrl:t,sessionToken:e,agentType:o,fields:n={}}){if(!e)throw new Error("Not authenticated");let r=await fetch(yt(t,o),{method:"PUT",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let a=await r.text().catch(()=>"");throw new Error(`Failed to save agent session (${r.status}): ${a.slice(0,200)}`)}return(await r.json()).session}async function Yn({apiUrl:t,sessionToken:e,agentType:o}){if(!e)throw new Error("Not authenticated");let n=await fetch(yt(t,o),{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Failed to delete agent session (${n.status}): ${s.slice(0,200)}`)}return(await n.json()).deleted===!0}function $o(t){if(!t)return"never";let e=new Date(t).getTime();if(Number.isNaN(e))return"unknown";let o=Math.max(0,(Date.now()-e)/1e3);if(o<60)return"just now";let n=o/60;if(n<60)return`${Math.round(n)}m ago`;let r=n/60;if(r<24)return`${Math.round(r)}h ago`;let s=r/24;if(s<30)return`${Math.round(s)}d ago`;let a=s/30;return`${Math.round(a)}mo ago`}var Le,Ao=$e(()=>{Le=[{id:"zibby",name:"Zibby Chat",short:"default",description:"Built-in chat using Anthropic SDK directly \xB7 BYOK \xB7 included with workspace",pricePerMonth:0,deployment:"instant"},{id:"claude-code",name:"Claude Code",short:"add-on",description:"Anthropic's Claude Code CLI deployed in your private sandbox",pricePerMonth:20,deployment:"fargate-warm"}]});var bt={};ve(bt,{attachToSession:()=>To,spawnAgentSession:()=>Io,spawnAndAttach:()=>Zn});import Co from"ws";import ko from"chalk";function Hn({sandboxEndpoint:t,sessionId:e,useTls:o=!1}){return`${o?"wss":"ws"}://${t}/stream/${encodeURIComponent(e)}`}async function Io({sandboxEndpoint:t,sessionToken:e,agentType:o="claude-code",args:n=[],cwd:r="/workspace",useTls:s=!1}){let c=`${s?"https":"http"}://${t}/spawn`,l=await fetch(c,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({agent_type:o,args:n,cwd:r})});if(!l.ok){let $=await l.text().catch(()=>"");throw new Error(`spawn failed (${l.status}): ${$}`)}return await l.json()}async function To({sandboxEndpoint:t,sessionId:e,sessionToken:o,useTls:n=!1,showBanner:r=!0}){let s=Hn({sandboxEndpoint:t,sessionId:e,useTls:n}),a=new Co(s,{headers:{Authorization:`Bearer ${o}`}});return new Promise((c,l)=>{let p=!1,$=!1,z=null,Y=null,W=A=>{if(!p){p=!0;try{process.stdin.isTTY&&process.stdin.setRawMode&&process.stdin.setRawMode($)}catch{}z&&process.stdin.off("data",z),Y&&process.stdout.off("resize",Y);try{process.stdin.pause()}catch{}try{a.close()}catch{}c(A)}};a.on("open",()=>{r&&(process.stdout.write(ko.green(`
|
|
3
|
+
`,"utf8")}function xn(t){let e=Number(t);if(!Number.isFinite(e)||e<=0)return[];try{let o=co(`pgrep -P ${e}`,{encoding:"utf8",stdio:["ignore","pipe","ignore"],maxBuffer:524288}).trim();return o?o.split(/\n/).map(n=>parseInt(n.trim(),10)).filter(n=>Number.isFinite(n)&&n>0):[]}catch{return[]}}function io(t,e){let o=Number(t);if(!Number.isFinite(o)||o<=0)return;let n=new Set;function r(s){if(!n.has(s)){n.add(s);for(let a of xn(s))r(a);try{process.kill(s,e)}catch{}}}r(o)}function $n(t){let e=Number(t);if(!(!Number.isFinite(e)||e<=0))try{co(`taskkill /PID ${e} /T /F`,{stdio:"ignore",windowsHide:!0})}catch{}}function lo(t){let e=Number(t);if(!Number.isFinite(e)||e<=0)return;if(process.platform==="win32"){$n(e);return}io(e,"SIGTERM");let o=setTimeout(()=>{io(e,"SIGKILL")},800);typeof o.unref=="function"&&o.unref()}function vn(t,e,o={}){let n=Number(e);if(!Number.isFinite(n)||n<=0)return;let r=We(o),s=Je(t,r,n),a=dt(t,r,n);for(let c of a)c!==process.pid&&lo(c);try{lt(s)&&ut(s)}catch{}}function An(t){try{return process.kill(t,0),!0}catch{return!1}}function kn(t,e={}){let o=We(e),n=Ze(t,o),r;try{r=bn(n)}catch{return}for(let s of r){let a=Cn.exec(s);if(!a)continue;let c=Number(a[1]);if(!(!Number.isFinite(c)||c<=0)&&!An(c))try{ut(Ze(n,s))}catch{}}}var Cn,ft=$e(()=>{Cn=/^\.zibby-chat-run-pids-(\d+)\.json$/});var mo={};ve(mo,{DEFAULT_CONFIG_PATH:()=>uo,discoverCredentials:()=>En,maskToken:()=>On,parseConfigJson:()=>fo,readCredentialsConfig:()=>go});import In from"node:fs/promises";import Tn from"node:path";import Pn from"node:os";function fo(t){if(!t)return[];let e;try{e=JSON.parse(t)}catch{return[]}let o=e?.agentKeys;if(!o||typeof o!="object")return[];let n=[],r=new Set;for(let[s,a]of Object.entries(po)){let c=o[s];if(!c||typeof c!="string")continue;let l=s.endsWith("_POOL")?c.split(",").map(p=>p.trim()).filter(Boolean):[c.trim()];for(let p of l)p.length<8||r.has(p)||(r.add(p),n.push({type:a,token:p,source_var:s}))}return n}async function go(t=uo){let e;try{e=await In.readFile(t,"utf8")}catch(o){if(o.code==="ENOENT")return[];throw o}return fo(e)}async function En({filepath:t,env:e=process.env}={}){let o=await go(t),n=new Set(o.map(s=>s.token)),r=[];for(let[s,a]of Object.entries(po)){let c=e[s];if(!c)continue;let l=s.endsWith("_POOL")?c.split(",").map(p=>p.trim()).filter(Boolean):[c];for(let p of l)p.length<8||n.has(p)||(n.add(p),r.push({type:a,token:p,source_var:s,source:"process.env"}))}return{config:o.map(s=>({...s,source:"config.json"})),env:r,all:[...o.map(s=>({...s,source:"config.json"})),...r]}}function On(t){return!t||typeof t!="string"||t.length<=4?"***":`***${t.slice(-4)}`}var uo,po,ho=$e(()=>{uo=Tn.join(Pn.homedir(),".zibby","config.json"),po={CLAUDE_CODE_OAUTH_TOKEN:"oauth",CLAUDE_CODE_OAUTH_TOKEN_POOL:"oauth",ANTHROPIC_AUTH_TOKEN:"oauth",ANTHROPIC_API_KEY:"api",ANTHROPIC_API_KEY_POOL:"api"}});var bo={};ve(bo,{addCredential:()=>yo,deleteCredential:()=>Un,listCredentials:()=>Nn,syncFromLocal:()=>Ln});function gt(t,e=""){return`${String(t).replace(/\/+$/,"")}/agents/credentials${e}`}function mt(){let t=new Error("Session expired \u2014 run zibby login");return t.code="AUTH_EXPIRED",t}async function Nn({apiUrl:t,sessionToken:e}){if(!e)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let o=await fetch(gt(t),{headers:{Authorization:`Bearer ${e}`}});if(o.status===401)throw mt();if(o.status===404)return{credentials:[],by_type:{oauth:[],api:[]},total:0};if(!o.ok){let n=new Error(`List credentials failed (${o.status})`);throw n.status=o.status,n}return o.json()}async function yo({apiUrl:t,sessionToken:e,type:o,token:n,provider:r,source:s="~/.zibby/config.json"}){if(!e)throw new Error("No session token \u2014 run zibby login first");let a={type:o,token:n,source:s};r&&(a.provider=r);let c=await fetch(gt(t),{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(a)});if(c.status===401)throw mt();if(!c.ok){let l=`Add credential failed (${c.status})`;try{let _=await c.json();_?.error&&(l=`${l}: ${_.error}`)}catch{}let p=new Error(l);throw p.status=c.status,p}return c.json()}async function Un({apiUrl:t,sessionToken:e,type:o,index:n}){if(!e)throw new Error("No session token \u2014 run zibby login first");let r=await fetch(gt(t,`/${encodeURIComponent(o)}/${encodeURIComponent(n)}`),{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(r.status===401)throw mt();if(!r.ok){let s=new Error(`Delete credential failed (${r.status})`);throw s.status=r.status,s}return r.json()}async function Ln({apiUrl:t,sessionToken:e,credentials:o}){let n=0,r=0,s=[];for(let a of o)try{let c=await yo({apiUrl:t,sessionToken:e,type:a.type,token:a.token,source:a.source_var||a.source||"local"});c.deduped?r+=1:c.added&&(n+=1)}catch(c){s.push({masked:a.token?`***${a.token.slice(-4)}`:"***",error:c.message})}return{added:n,deduped:r,errors:s}}var wo=$e(()=>{});var vo={};ve(vo,{AGENTS:()=>Le,deleteAgentSession:()=>Yn,fetchMyAgentSessions:()=>xo,formatRelativeTime:()=>$o,handleClaudeCodeAddon:()=>Dn,pickAgent:()=>Bn,pickAgentWithSessions:()=>Rn,upsertAgentSession:()=>Fn});import{select as So,confirm as ht,Separator as _o}from"@inquirer/prompts";import u from"chalk";async function Rn({apiUrl:t,sessionToken:e,currentAgentId:o="zibby"}={}){let n;try{n=await xo({apiUrl:t,sessionToken:e})}catch(s){if(/login/i.test(s.message))throw s;console.warn(u.gray(` (could not fetch sessions: ${s.message})`)),n=[]}let r=[];if(n.length>0){for(let s of n){let c=Le.find(z=>z.id===s.agent_type)?.name||s.agent_type,l=$o(s.last_active),p=typeof s.message_count=="number"&&s.message_count>0?u.gray(` \xB7 ${s.message_count} msg`):"",_=s.label?u.gray(` \xB7 "${s.label}"`):"";r.push({name:`${u.cyan("\u2726")} ${c} ${u.gray(`(${l})`)}${_}${p}`,value:{action:"resume",agentType:s.agent_type,sessionId:s.session_id,session:s},description:u.gray(` Resume your ${c} session`)})}r.push(new _o)}for(let s of Le)s.id!=="zibby"&&r.push({name:`${u.dim("+")} New ${s.name} session${s.pricePerMonth>0?u.yellow(` (+$${s.pricePerMonth}/mo)`):""}`,value:{action:"create",agentType:s.id},description:u.gray(` ${s.description}`)});r.push(new _o),r.push({name:`${u.green("\u2190")} Back to Zibby Chat (default)${o==="zibby"?u.dim(" [current]"):""}`,value:{action:"switch",agentType:"zibby"},description:u.gray(" Built-in chat using Anthropic SDK directly")});try{return await So({message:"Select chat agent:",choices:r})}catch(s){if(s?.name==="ExitPromptError")return{action:"cancel"};throw s}}async function Bn(t="zibby"){let e=await So({message:"Select chat agent for this workspace:",default:t,choices:Le.map(o=>{let n=o.pricePerMonth===0?u.green(" (included)"):u.yellow(` (+$${o.pricePerMonth}/mo)`),r=o.id===t?u.dim(" [current]"):"";return{name:`${o.name}${n}${r}`,value:o.id,description:u.gray(` ${o.description}`)}})});return Le.find(o=>o.id===e)}async function Dn({workspaceId:t,sessionToken:e,apiUrl:o}){let n=await jn({addon:"claude-code",workspaceId:t,sessionToken:e,apiUrl:o});if(n.configured&&n.sandboxState==="ready")return console.log(""),console.log(u.green(" \u2713 Claude Code is already deployed for your team.")),console.log(u.gray(` Sandbox: ${n.sandboxId} \xB7 state: ${n.sandboxState}`)),console.log(""),{ready:!0,sandboxId:n.sandboxId};if(n.configured&&n.sandboxState!=="ready")return console.log(""),console.log(u.cyan(` \u2699 Claude Code sandbox is ${n.sandboxState}...`)),console.log(u.gray(" You can keep using Zibby Chat \u2014 we'll switch when it's ready.")),console.log(""),{ready:!1,provisioning:!0,sandboxId:n.sandboxId};if(console.log(""),console.log(u.yellow(" Claude Code add-on is not enabled for your workspace.")),console.log(""),console.log(u.white(" About this add-on:")),console.log(u.gray(" \u2022 Anthropic's official Claude Code CLI runs in YOUR isolated sandbox")),console.log(u.gray(" \u2022 YOU provide your own Anthropic credentials (in ~/.zibby/config.json)")),console.log(u.gray(" \u2022 Zibby NEVER accesses Anthropic on your behalf \u2014 your tokens, your API calls")),console.log(u.gray(" \u2022 Zibby stores credentials KMS-encrypted, decrypts only inside YOUR sandbox")),console.log(u.gray(" \u2022 You're responsible for ToS compliance with the credentials you provide:")),console.log(u.gray(" https://www.anthropic.com/legal/commercial-terms")),console.log(""),console.log(u.cyan(" Pricing:")),console.log(u.white(" $20 / month per workspace ")+u.gray("\xB7 Zibby infrastructure fee, billed via Stripe")),console.log(u.gray(" Your Anthropic usage bills directly to your Anthropic account")),console.log(""),!await ht({message:"Do you agree to Anthropic's Commercial Terms of Service?",default:!1}))return console.log(u.gray(" Cancelled. Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0};if(!await ht({message:"Enable Claude Code add-on at $20/month?",default:!1}))return console.log(u.gray(" Cancelled. Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0};console.log(""),console.log(u.cyan(" Enabling Claude Code add-on..."));let a;try{a=await zn({addon:"claude-code",workspaceId:t,sessionToken:e,apiUrl:o,accept:{tos:!0,billing:!0}})}catch(c){if(c?.code==="BILLING_REQUIRED"){console.log("");let l=c.upgradeUrl?.startsWith("http")?c.upgradeUrl:"https://zibby.dev/billing";return c.needsSubscription?(console.log(u.yellow(" \u26A0 You need an active Pro subscription to enable Claude Code.")),console.log(u.gray(` Upgrade here: ${l}`))):c.needsPaymentMethod?(console.log(u.yellow(" \u26A0 Your card was declined or no payment method is on file.")),console.log(u.gray(` Update billing: ${l}`))):(console.log(u.yellow(` \u26A0 ${c.message}`)),console.log(u.gray(` Manage billing: ${l}`))),console.log(""),console.log(u.gray(" Continuing with Zibby Chat (default).")),console.log(""),{ready:!1,cancelled:!0,billingRequired:!0}}throw c}return console.log(""),console.log(u.green(" \u2713 Stripe subscription created")),console.log(u.gray(` sub_id: ${a.subscriptionId}`)),console.log(u.green(" \u2713 Lambda invoked: zibby-prod-provision-sandbox")),console.log(u.gray(` request: ${a.requestId}`)),console.log(u.cyan(" \u2699 Fargate task launching: zibby/agent-runtime:claude-code-v1")),console.log(u.gray(` sandbox_id: ${a.sandboxId}`)),console.log(""),await Mn({apiUrl:o,sessionToken:e}),console.log(""),console.log(u.gray(" Sandbox provisioning in the background. Zibby Chat (default) is active until ready.")),console.log(""),{ready:!1,provisioning:!0,sandboxId:a.sandboxId,deploymentId:a.requestId}}async function Mn({apiUrl:t,sessionToken:e}){let o;try{let{discoverCredentials:s}=await Promise.resolve().then(()=>(ho(),mo));o=await s()}catch(s){console.log(u.gray(` (could not scan local credentials: ${s.message})`));return}let n=o.all.length;if(n===0){console.log(u.yellow(" \u26A0 No Anthropic credentials found locally.")),console.log(""),console.log(u.white(" Two ways to authenticate Claude Code in your sandbox:")),console.log(""),console.log(u.bold(" Option A \u2014 provide your own (recommended):")),console.log(u.gray(" 1. Run: zibby init")),console.log(u.gray(" Pick Claude \u2192 Subscription (OAuth) or API key")),console.log(u.gray(" 2. Run: zibby creds sync (uploads to your workspace)")),console.log(u.gray(" 3. Re-run /agents in chat")),console.log(""),console.log(u.bold(" Option B \u2014 in-sandbox login (legacy):")),console.log(u.gray(" Skip this step. When sandbox is ready and you start")),console.log(u.gray(" Claude Code, it will prompt you to open a URL in your")),console.log(u.gray(" laptop browser to authenticate.")),console.log("");return}console.log(u.green(` \u2713 Found ${n} Anthropic ${n===1?"credential":"credentials"} in your local environment:`));for(let s of o.all){let a=s.source==="config.json"?`~/.zibby/config.json (${s.source_var})`:`process.env.${s.source_var}`;console.log(u.gray(` ${s.type} ***${s.token.slice(-4)} ${a}`))}if(console.log(""),console.log(u.white(" By proceeding you confirm:")),console.log(u.gray(" \u2022 These are YOUR credentials to use")),console.log(u.gray(" \u2022 You comply with Anthropic's ToS for the tier of these tokens")),console.log(u.gray(" \u2022 Zibby will store encrypted (AWS KMS) and inject into YOUR sandbox only")),console.log(""),!await ht({message:"Upload these credentials to your Zibby workspace?",default:!0})){console.log(u.gray(" Skipped credential upload. Sandbox will fall back to in-sandbox login."));return}console.log(""),console.log(u.cyan(" Uploading (KMS-encrypted)..."));try{let{syncFromLocal:s}=await Promise.resolve().then(()=>(wo(),bo)),a=await s({apiUrl:t,sessionToken:e,credentials:o.all});console.log(u.green(` \u2713 ${a.added} new, ${a.deduped} already stored`)),a.errors.length>0&&console.log(u.yellow(` ${a.errors.length} failed \u2014 retry with 'zibby creds sync'`))}catch(s){console.log(u.red(` \u2717 Upload failed: ${s.message}`)),console.log(u.gray(" Sandbox will fall back to in-sandbox login when ready."))}}async function jn({addon:t,sessionToken:e,apiUrl:o}){let n=process.env.ZIBBY_CLAUDE_CODE_STUB_STATUS;if(n==="ready")return{configured:!0,sandboxState:"ready",sandboxId:"sb_stub_acme_001"};if(n==="provisioning")return{configured:!0,sandboxState:"provisioning",sandboxId:"sb_stub_acme_001"};if(!o||!e)return{configured:!1,sandboxState:null,sandboxId:null};let r=`${String(o).replace(/\/+$/,"")}/agents/addons/${encodeURIComponent(t)}`,s;try{s=await fetch(r,{headers:{Authorization:`Bearer ${e}`}})}catch{return{configured:!1,sandboxState:null,sandboxId:null}}if(s.status===401){let c=new Error("Session expired \u2014 run zibby login");throw c.code="AUTH_EXPIRED",c}if(s.status===404)return{configured:!1,sandboxState:null,sandboxId:null};if(!s.ok)return{configured:!1,sandboxState:null,sandboxId:null};let a=await s.json();return{configured:!!a.configured,sandboxState:a.sandbox_state||null,sandboxId:a.sandbox_id||null,subscriptionId:a.subscription_id||null,enabledAt:a.enabled_at||null}}async function zn({addon:t,workspaceId:e,sessionToken:o,apiUrl:n}){if(!n||!o)return await new Promise(c=>setTimeout(c,500)),{subscriptionId:`sub_${Math.random().toString(36).slice(2,10)}`,sandboxId:`sb_${Math.random().toString(36).slice(2,10)}`,requestId:`req_offline_${Date.now().toString(36)}`};let r=`${String(n).replace(/\/+$/,"")}/agents/addons/${encodeURIComponent(t)}/enable`,s=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({workspace_id:e||null})});if(s.status===401){let c=new Error("Session expired \u2014 run zibby login");throw c.code="AUTH_EXPIRED",c}if(s.status===402){let c;try{c=await s.json()}catch{c={}}let l;try{l=typeof c.error=="string"?JSON.parse(c.error):c.error||c}catch{l={message:c.error||"Payment required"}}let p=new Error(l.message||"Payment required");throw p.code="BILLING_REQUIRED",p.status=402,p.needsSubscription=!!l.needs_subscription,p.needsPaymentMethod=!!l.needs_payment_method,p.upgradeUrl=l.upgrade_url||"/billing",p}if(!s.ok){let c=new Error(`Enable addon failed (${s.status})`);throw c.status=s.status,c}let a=await s.json();return{subscriptionId:a.subscription_id||null,sandboxId:a.sandbox_id||null,stripeSubscriptionItemId:a.stripe_subscription_item_id||null,requestId:a.request_id||`req_${Date.now().toString(36)}`}}function yt(t,e){let o=String(t).replace(/\/+$/,"");return e?`${o}/agents/sessions/${encodeURIComponent(e)}`:`${o}/agents/sessions`}async function xo({apiUrl:t,sessionToken:e}){if(!e)return[];let o=await fetch(yt(t),{headers:{Authorization:`Bearer ${e}`}});if(o.status===401)throw new Error("Not authenticated. Run `zibby login` again.");if(o.status===404)return[];if(!o.ok){let r=await o.text().catch(()=>"");throw new Error(`Failed to list agent sessions (${o.status}): ${r.slice(0,200)}`)}let n=await o.json();return Array.isArray(n.sessions)?n.sessions:[]}async function Fn({apiUrl:t,sessionToken:e,agentType:o,fields:n={}}){if(!e)throw new Error("Not authenticated");let r=await fetch(yt(t,o),{method:"PUT",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let a=await r.text().catch(()=>"");throw new Error(`Failed to save agent session (${r.status}): ${a.slice(0,200)}`)}return(await r.json()).session}async function Yn({apiUrl:t,sessionToken:e,agentType:o}){if(!e)throw new Error("Not authenticated");let n=await fetch(yt(t,o),{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Failed to delete agent session (${n.status}): ${s.slice(0,200)}`)}return(await n.json()).deleted===!0}function $o(t){if(!t)return"never";let e=new Date(t).getTime();if(Number.isNaN(e))return"unknown";let o=Math.max(0,(Date.now()-e)/1e3);if(o<60)return"just now";let n=o/60;if(n<60)return`${Math.round(n)}m ago`;let r=n/60;if(r<24)return`${Math.round(r)}h ago`;let s=r/24;if(s<30)return`${Math.round(s)}d ago`;let a=s/30;return`${Math.round(a)}mo ago`}var Le,Ao=$e(()=>{Le=[{id:"zibby",name:"Zibby Chat",short:"default",description:"Built-in chat using Anthropic SDK directly \xB7 BYOK \xB7 included with workspace",pricePerMonth:0,deployment:"instant"},{id:"claude-code",name:"Claude Code",short:"add-on",description:"Anthropic's Claude Code CLI deployed in your private sandbox",pricePerMonth:20,deployment:"fargate-warm"}]});var bt={};ve(bt,{attachToSession:()=>To,spawnAgentSession:()=>Io,spawnAndAttach:()=>Kn});import Co from"ws";import ko from"chalk";function Hn({sandboxEndpoint:t,sessionId:e,useTls:o=!1}){return`${o?"wss":"ws"}://${t}/stream/${encodeURIComponent(e)}`}async function Io({sandboxEndpoint:t,sessionToken:e,agentType:o="claude-code",args:n=[],cwd:r="/workspace",useTls:s=!1}){let c=`${s?"https":"http"}://${t}/spawn`,l=await fetch(c,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({agent_type:o,args:n,cwd:r})});if(!l.ok){let _=await l.text().catch(()=>"");throw new Error(`spawn failed (${l.status}): ${_}`)}return await l.json()}async function To({sandboxEndpoint:t,sessionId:e,sessionToken:o,useTls:n=!1,showBanner:r=!0}){let s=Hn({sandboxEndpoint:t,sessionId:e,useTls:n}),a=new Co(s,{headers:{Authorization:`Bearer ${o}`}});return new Promise((c,l)=>{let p=!1,_=!1,z=null,Y=null,W=A=>{if(!p){p=!0;try{process.stdin.isTTY&&process.stdin.setRawMode&&process.stdin.setRawMode(_)}catch{}z&&process.stdin.off("data",z),Y&&process.stdout.off("resize",Y);try{process.stdin.pause()}catch{}try{a.close()}catch{}c(A)}};a.on("open",()=>{r&&(process.stdout.write(ko.green(`
|
|
4
4
|
\u2713 Connected to cloud sandbox session ${e}
|
|
5
5
|
`)),process.stdout.write(ko.gray(` Press Ctrl+\\ to detach (session keeps running).
|
|
6
6
|
|
|
7
|
-
`)));let A=()=>{let R=process.stdout.columns||80,B=process.stdout.rows||24;try{a.send(JSON.stringify({type:"resize",cols:R,rows:B}))}catch{}};A(),Y=()=>A(),process.stdout.on("resize",Y),process.stdin.isTTY&&process.stdin.setRawMode&&(
|
|
7
|
+
`)));let A=()=>{let R=process.stdout.columns||80,B=process.stdout.rows||24;try{a.send(JSON.stringify({type:"resize",cols:R,rows:B}))}catch{}};A(),Y=()=>A(),process.stdout.on("resize",Y),process.stdin.isTTY&&process.stdin.setRawMode&&(_=!!process.stdin.isRaw,process.stdin.setRawMode(!0)),process.stdin.resume();try{process.stdin.setEncoding("utf8")}catch{}z=R=>{let B=R.toString("utf8");if(B.includes("")){W({reason:"detach"});return}try{a.send(B)}catch{}},process.stdin.on("data",z)}),a.on("message",A=>{let R=A.toString("utf8");if(R.startsWith("{")&&R.endsWith("}"))try{let B=JSON.parse(R);if(B&&B.type==="exit"){W({reason:"remote-exit",exitCode:B.exitCode,signal:B.signal});return}}catch{}try{process.stdout.write(R)}catch{}}),a.on("close",()=>{W({reason:"remote-close"})}),a.on("error",A=>{p||W({reason:"ws-error",message:A?.message||String(A)})}),setTimeout(()=>{if(a.readyState===Co.CONNECTING){try{a.terminate()}catch{}p||(p=!0,l(new Error("WS connect timed out after 30s")))}},3e4).unref()})}async function Kn({sandboxEndpoint:t,sessionToken:e,agentType:o,args:n,cwd:r,useTls:s}){let a=await Io({sandboxEndpoint:t,sessionToken:e,agentType:o,args:n,cwd:r,useTls:s});return{...await To({sandboxEndpoint:t,sessionId:a.session_id,sessionToken:e,useTls:s}),sessionId:a.session_id}}var wt=$e(()=>{});import{invokeAgent as Zn,getAgentStrategy as Wn}from"@zibby/core";import{getSkill as Re}from"@zibby/skills";import{existsSync as Ce,readFileSync as Ro,readdirSync as Jn}from"fs";import{resolve as me,join as St,dirname as Gn,basename as qn}from"path";import{createInterface as Vn,moveCursor as j,cursorTo as Z,clearLine as Q,emitKeypressEvents as Xn}from"readline";import{fileURLToPath as Qn}from"url";import{homedir as es}from"os";import i from"chalk";import{highlight as Po}from"cli-highlight";import ts from"dotenv";import{existsSync as Lt,mkdirSync as qo,readFileSync as Vo,writeFileSync as Xo}from"fs";import{homedir as Rt}from"os";import{join as Fe}from"path";function Bt(){return process.env.ZIBBY_CONFIG_DIR||Fe(Rt(),".zibby")}function Dt(){return Fe(Bt(),"config.json")}var Qo=Fe(Rt(),".zibby"),Ms=Fe(Qo,"config.json");function en(){let t=Bt();Lt(t)||qo(t,{recursive:!0})}function se(){try{let t=Dt();if(Lt(t)){let e=Vo(t,"utf-8");return JSON.parse(e)}}catch{}return{}}function Pe(t){en(),Xo(Dt(),JSON.stringify(t,null,2))}function Ye(){return se().sessionToken||null}function Mt(t){let e=se();e.sessionToken=t,Pe(e)}function jt(){return se().user||null}function zt(t){let e=se();e.user=t,Pe(e)}function Ft(){let t=se();delete t.sessionToken,delete t.user,delete t.mem0ProxyUrl,Pe(t)}function Yt(){return se().proxyUrl||null}function Ht(t){let e=se();e.proxyUrl=t,Pe(e)}function Kt(){return se().mem0ProxyUrl||null}function Zt(t){let e=se();e.mem0ProxyUrl=t,Pe(e)}function Wt(){return se().projects||[]}var Ee={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function le(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";Ee[e]?t=Ee[e].apiUrl:t=Ee.prod.apiUrl}try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),Ee.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),Ee.prod.apiUrl}}import{existsSync as at,mkdirSync as tn,readFileSync as Jt,writeFileSync as Gt,unlinkSync as Ys}from"fs";import{resolve as Oe}from"path";import{homedir as Zs}from"os";var on=30;function qt(t){let e=Oe(t,".zibby","output");return at(e)||tn(e,{recursive:!0}),e}function Vt(t){let e=Oe(t,".zibby","output","chat-history.json");if(!at(e))return[];try{let o=JSON.parse(Jt(e,"utf-8"));return Array.isArray(o)?o:[]}catch{return[]}}function Ne(t,e){let o=qt(t),n=Oe(o,"chat-history.json");try{Gt(n,JSON.stringify((e||[]).slice(-on*2),null,2),"utf-8")}catch{}}function Xt(t){let e=Oe(t,".zibby","output","active-skills.json");if(!at(e))return null;try{let o=JSON.parse(Jt(e,"utf-8"));return Array.isArray(o)?o:null}catch{return null}}function Ue(t,e){let o=qt(t),n=Oe(o,"active-skills.json");try{Gt(n,JSON.stringify(Array.isArray(e)?e:[]),"utf-8")}catch{}}var ct={cli_reliable_v1:{title:"General intelligence reliability contract",operatingRules:["Evidence-first reasoning: ground conclusions in observed outputs or tool evidence, not guesses.","No false completion: never claim success for a state-changing action until verification confirms it.","Execution integrity: do not claim any external action unless the matching tool call actually happened.","Bounded recovery: for transient failures, retry with adjusted parameters up to 2 times, then escalate with blocker + next step.",'Binary-answer discipline: for yes/no questions, verify the exact asked condition before answering; do not answer "yes" from a broader or approximate match.'],executionSafety:["Prefer low-blast-radius, reversible actions first.","Before irreversible or high-impact actions, confirm explicit user intent unless already authorized.","If verification cannot be run, state that limitation explicitly."],investigationLoop:["For unclear failures, follow this loop: detect -> gather evidence -> form hypothesis -> test hypothesis -> conclude.","If evidence is insufficient, explicitly collect more before proposing a root cause.","Prefer smallest validating action first before broad or costly retries."],responseQuality:["State assumptions explicitly when certainty is low.","Differentiate facts, hypotheses, and next actions.","Keep reports concise but decision-useful.","If related-but-not-identical matches exist, report them separately as context, not as the direct yes/no answer."],incidentTemplate:["ONLY when diagnosing failures or errors (never for successful actions), structure your response as: Root cause, Evidence, Attempted fixes, Current status, Next action."],skillRunbooks:{}}},eo=2e3,Qt=12e3;function He(t=[]){if(!Array.isArray(t))return[];let e=new Set,o=[];for(let n of t){let r=String(n||"").replace(/\s+/g," ").trim();r&&(e.has(r)||(e.add(r),o.push(r)))}return o}function nn(t,e=eo){let o=String(t||"");return o.length<=e?o:`${o.slice(0,Math.max(0,e-14)).trimEnd()}
|
|
8
8
|
|
|
9
9
|
[truncated]`}function ge(t,e=[],o=eo){let n=He(e);if(n.length===0)return"";let r=[`## ${t}`,...n.map(s=>`- ${s}`)].join(`
|
|
10
10
|
`);return nn(r,o)}function sn(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function rn(t,e){let o={...t,...e},n=["operatingRules","rules","executionSafety","investigationLoop","responseQuality","incidentTemplate"];for(let r of n)Array.isArray(e?.[r])?o[r]=[...He(t?.[r]||[]),...He(e[r])]:Array.isArray(t?.[r])&&(o[r]=[...He(t[r])]);return o.skillRunbooks={...t?.skillRunbooks||{},...e?.skillRunbooks||{}},o}function an(t={},e={}){let o=Array.isArray(t?.reliabilityAppendSections)?t.reliabilityAppendSections:[],n=Array.isArray(e?.reliabilityAppendSections)?e.reliabilityAppendSections:[];return[...o,...n].map(r=>{if(typeof r=="string")return{title:"Additional reliability guidance",lines:[r]};if(!r||typeof r!="object")return null;let s=String(r.title||"Additional reliability guidance").trim(),a=Array.isArray(r.lines)?r.lines:[];return{title:s,lines:a}}).filter(Boolean)}function cn(t={},e={}){let o=String(e.reliabilityProfile||process.env.ZIBBY_RELIABILITY_PROFILE||t.reliabilityProfile||"cli_reliable_v1").trim(),n=t?.reliabilityProfiles?.[o];if(typeof n=="string"&&n.trim())return{name:o,text:n.trim()};if(n&&typeof n.instruction=="string"&&n.instruction.trim())return{name:o,text:n.instruction.trim()};let r=ct[o]||ct.cli_reliable_v1,s=sn(n),a=s?rn(r,s):r;return{name:o,defaults:a}}function to({activeSkills:t=[],chatConfig:e={},options:o={}}={}){let n=cn(e,o);if(n.text)return n.text;let r=n.defaults||ct.cli_reliable_v1,s=[ge(r.title||"Reliability contract",r.operatingRules||r.rules||[]),ge("Execution safety",r.executionSafety||[]),ge("Investigation loop",r.investigationLoop||[]),ge("Response quality",r.responseQuality||[]),ge("Failure reporting format",r.incidentTemplate||[])],a=r.skillRunbooks||{};for(let p of t)a[p]&&s.push(ge(`Runbook: ${p}`,a[p]));let c=an(e,o);for(let p of c)s.push(ge(p.title,p.lines));let l=s.filter(Boolean).join(`
|
|
11
11
|
|
|
12
12
|
`).trim();return l.length<=Qt?l:`${l.slice(0,Math.max(0,Qt-14)).trimEnd()}
|
|
13
13
|
|
|
14
|
-
[truncated]`}var os=Qn(import.meta.url),ns=Gn(os),ss=JSON.parse(Ro(St(ns,"../../package.json"),"utf-8")),Bo=30,rs=54,is=18e3,Do=12e3,Eo=42e3;function as(t){return new Promise(e=>setTimeout(e,t))}var Ge=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],$t=[{cmd:"/help",desc:"Show this help"},{cmd:"/agents",desc:"Choose chat agent (Zibby default or Claude Code add-on)"},{cmd:"/skills",desc:"List active & available skills"},{cmd:"/history",desc:"Show conversation history (--all or -n 50)"},{cmd:"/clear",desc:"Clear conversation history"},{cmd:"/memory",desc:"View stored memories, tasks, sessions"},{cmd:"/exit",desc:"Exit the chat"},{cmd:"/quit",desc:"Exit the chat"}];function Oo(){let t=0,e="thinking...",o=setInterval(()=>{let r=i.cyan(Ge[t%Ge.length]),s=t%3,a=s===0?i.white(".")+i.gray(".")+i.dim("."):s===1?i.dim(".")+i.white(".")+i.gray("."):i.gray(".")+i.dim(".")+i.white("."),c=e.replace(/\.+$/,""),l=` ${r} ${i.gray(c)}${a}`;process.stdout.write(`\r
|
|
14
|
+
[truncated]`}var os=Qn(import.meta.url),ns=Gn(os),ss=JSON.parse(Ro(St(ns,"../../package.json"),"utf-8")),Bo=30,rs=54,is=18e3,Do=12e3,Eo=42e3;function as(t){return new Promise(e=>setTimeout(e,t))}var Ge=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],$t=[{cmd:"/help",desc:"Show this help"},{cmd:"/agents",desc:"Choose chat agent (Zibby default or Claude Code add-on)"},{cmd:"/skills",desc:"List active & available skills"},{cmd:"/history",desc:"Show conversation history (--all or -n 50)"},{cmd:"/clear",desc:"Clear conversation history"},{cmd:"/memory",desc:"View stored memories, tasks, sessions"},{cmd:"/exit",desc:"Exit the chat"},{cmd:"/quit",desc:"Exit the chat"}];function Oo(){let t=0,e="thinking...",o=setInterval(()=>{let r=i.cyan(Ge[t%Ge.length]),s=t%3,a=s===0?i.white(".")+i.gray(".")+i.dim("."):s===1?i.dim(".")+i.white(".")+i.gray("."):i.gray(".")+i.dim(".")+i.white("."),c=e.replace(/\.+$/,""),l=` ${r} ${i.gray(c)}${a}`;process.stdout.write(`\r\x1B[2K${l}`),t++},300),n=()=>{clearInterval(o),process.stdout.write("\r\x1B[2K")};return n.setLabel=r=>{e=r},n}function $r(t){let e=t?.agent;return e?e.provider?e.provider:e.gemini?"gemini":e.codex?"codex":e.claude?"claude":e.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}function cs(t){return t.slice(-Bo).map(e=>`${e.role==="human"?"H":"AI"}: ${e.content}`).join(`
|
|
15
15
|
`)}function vr(t,e,o){let n=t;return e.length>0&&(n+=`
|
|
16
16
|
|
|
17
17
|
${cs(e)}`),n+=`
|
|
18
18
|
H: ${o}
|
|
19
|
-
AI:`,n}function ls(t){let e=t.filter(o=>!process.env[o]);return{ok:e.length===0,missing:e}}function us(t){let e=me(t,".zibby.config.mjs");if(!Ce(e))return{};try{return import(e).then(o=>o.default||{})}catch{return{}}}async function ds(t){let e=me(t,".zibby","chat.mjs");if(Ce(e)){let r=await import(e);if(r.CHAT_CONFIG||r.default)return r.CHAT_CONFIG||r.default}let o=me(es(),".zibby","chat.mjs");if(o!==e&&Ce(o)){let r=await import(o);if(r.CHAT_CONFIG||r.default)return r.CHAT_CONFIG||r.default}let n=await import("@zibby/workflow-templates/browser-test-automation/chat.mjs");return n.CHAT_CONFIG||n.default||{}}function No(t){try{let e=me(t,".zibby","commands");return Ce(e)?Jn(e).filter(o=>o.toLowerCase().endsWith(".md")).sort((o,n)=>o.localeCompare(n)):[]}catch{return[]}}function ps(t,e){let o=String(e||"").trim();if(!o.startsWith("/"))return o;let[n,...r]=o.split(/\s+/),s=r.join(" ").trim(),a=n.slice(1);if(!a)return o;let c=a.toLowerCase().endsWith(".md")?[a]:[a,`${a}.md`],l=me(t,".zibby","commands"),p=c.find(
|
|
19
|
+
AI:`,n}function ls(t){let e=t.filter(o=>!process.env[o]);return{ok:e.length===0,missing:e}}function us(t){let e=me(t,".zibby.config.mjs");if(!Ce(e))return{};try{return import(e).then(o=>o.default||{})}catch{return{}}}async function ds(t){let e=me(t,".zibby","chat.mjs");if(Ce(e)){let r=await import(e);if(r.CHAT_CONFIG||r.default)return r.CHAT_CONFIG||r.default}let o=me(es(),".zibby","chat.mjs");if(o!==e&&Ce(o)){let r=await import(o);if(r.CHAT_CONFIG||r.default)return r.CHAT_CONFIG||r.default}let n=await import("@zibby/workflow-templates/browser-test-automation/chat.mjs");return n.CHAT_CONFIG||n.default||{}}function No(t){try{let e=me(t,".zibby","commands");return Ce(e)?Jn(e).filter(o=>o.toLowerCase().endsWith(".md")).sort((o,n)=>o.localeCompare(n)):[]}catch{return[]}}function ps(t,e){let o=String(e||"").trim();if(!o.startsWith("/"))return o;let[n,...r]=o.split(/\s+/),s=r.join(" ").trim(),a=n.slice(1);if(!a)return o;let c=a.toLowerCase().endsWith(".md")?[a]:[a,`${a}.md`],l=me(t,".zibby","commands"),p=c.find(_=>Ce(St(l,_)));if(!p)return o;try{let _=Ro(St(l,p),"utf-8").trim();return s?`${_}
|
|
20
20
|
|
|
21
|
-
${s}
|
|
21
|
+
${s}`:_}catch{return o}}function fs(t){let e=t.slice(-Bo),o=[],n=0;for(let r=e.length-1;r>=0;r--){let s=e[r],a=String(s?.content||""),c=s?.role==="human"?"user":"assistant",l=a.length;if(o.length>=6&&n+l>is)break;o.push({role:c,content:a}),n+=l}return o.reverse()}function Be(t,e){let o=String(t||"");return o.length<=e?o:`${o.slice(0,Math.max(0,e-24))}
|
|
22
22
|
|
|
23
23
|
[truncated for proxy size]`}function xt(t){return t.reduce((e,o)=>e+String(o?.content||"").length+64,0)}function gs(t){let e=[...t];if(e.length===0||(e[0]?.role==="system"&&(e[0]={...e[0],content:Be(e[0].content,Do)}),xt(e)<=Eo))return e;let o=e[0],n=e[e.length-1],r=e.slice(1,-1).slice(-4).map(s=>({...s,content:Be(s.content,2500)}));return e=[o,...r,n],xt(e)<=Eo||(e=[{...o,content:Be(o?.content,6e3)},{...n,content:Be(n?.content,8e3)}]),e}function ms(t){let e=[];for(let o of t){let n=Re(o),r=String(n?.description||"").trim();if(!r){e.push(`- ${o}`);continue}e.push(`- ${o}: ${qe(r,80)}`)}return e.length===0?"":`## Active skills (call get_skill_context before first use)
|
|
24
24
|
${e.join(`
|
|
25
25
|
`)}`}var Uo={cli_plain:["## Response format for this channel","- Output plain terminal text with optional fenced code blocks.","- Use fenced code blocks (```language) when showing code or config. Always include the language tag.","- Outside of code blocks, do NOT use Markdown syntax (no **bold**, __underline__, headings, inline backticks, or markdown tables).","- Keep responses concise and readable in a terminal.","- Write in natural, conversational English. Avoid dumping raw JSON, run IDs, or technical jargon.",'- When reporting test results: summarize in plain language (e.g. "Both tests finished \u2014 the checkbox test passed but the login test failed because..."). Include ticket keys but skip internal run IDs unless the user asks.',"- When something fails, explain the root cause simply and suggest a fix."].join(`
|
|
26
26
|
`)};function hs(t={},e={}){let o=String(e.outputProfile||process.env.ZIBBY_OUTPUT_PROFILE||t.outputProfile||"cli_plain").trim(),n=t?.outputProfiles?.[o];return typeof n=="string"&&n.trim()?n.trim():n&&typeof n.instruction=="string"&&n.instruction.trim()?n.instruction.trim():Uo[o]||Uo.cli_plain}function qe(t,e){let o=String(t??"");return o.length<=e?o:e<=1?o.slice(0,e):`${o.slice(0,e-1)}\u2026`}function ys(){return!1}function bs(t){let e=/^```(\w*)\n([\s\S]*?)^```$/gm;return t.replace(e,(o,n,r)=>{let s=r.replace(/\n$/,"");try{let a=n?Po(s,{language:n,ignoreIllegals:!0}):Po(s,{ignoreIllegals:!0}),c=i.gray("\u2500".repeat(Math.min(process.stdout.columns-6||54,72))),l=n?i.dim(` ${n}`):"";return`${c}${l}
|
|
27
27
|
${a}
|
|
28
|
-
${c}`}catch{return s}})}function _t(){let t=Number(process.stdout?.columns)||0,e=t>8?Math.max(30,t-4):rs;return` ${"\u2500".repeat(e)}`}function Lo(t=[]){let e=$t.map(n=>({cmd:n.cmd,source:"builtin",name:n.cmd.slice(1),desc:n.desc})),o=t.map(n=>({cmd:`/${n}`,source:"template",name:n,desc:"Command template"}));return[...e,...o]}function ws(t,e){let o=String(t||""),n=Number.isFinite(e)?e:o.length;return!(!o.startsWith("/")||n!==o.length||o.includes(" "))}function _s({userName:t,cwd:e,projectName:o,restoredCount:n,skillsLine:r}){let s=Number(process.stdout?.columns)||0,a=Math.max(40,Math.min(s-8,100)),c=Math.max(20,Math.floor((a-3)*.55)),l=a-c-3,p=t||"there"
|
|
29
|
-
`);j(process.stdout,0,-(1+I.length)),process.stdout.write("\x1B7"),j(process.stdout,0,2);for(let b=0;b<I.length;b++){
|
|
28
|
+
${c}`}catch{return s}})}function _t(){let t=Number(process.stdout?.columns)||0,e=t>8?Math.max(30,t-4):rs;return` ${"\u2500".repeat(e)}`}function Lo(t=[]){let e=$t.map(n=>({cmd:n.cmd,source:"builtin",name:n.cmd.slice(1),desc:n.desc})),o=t.map(n=>({cmd:`/${n}`,source:"template",name:n,desc:"Command template"}));return[...e,...o]}function ws(t,e){let o=String(t||""),n=Number.isFinite(e)?e:o.length;return!(!o.startsWith("/")||n!==o.length||o.includes(" "))}function _s({userName:t,cwd:e,projectName:o,restoredCount:n,skillsLine:r}){let s=Number(process.stdout?.columns)||0,a=Math.max(40,Math.min(s-8,100)),c=Math.max(20,Math.floor((a-3)*.55)),l=a-c-3,p=t||"there",_=o||"No project linked",z=qn(e||process.cwd()),Y=[`Restored ${n} messages from previous session.`,"",r],W=["Workspace details","",`v${ss.version} | Hi, ${p}`,`Company: ${_}`,`Directory: ~/${z}`,`Path: ${e}`,"","Use /help for commands"],A=Math.max(Y.length,W.length),R=(()=>{if(Y.length>=A)return Y;let H=Math.floor((A-Y.length)/2),ue=A-Y.length-H;return[...Array(H).fill(""),...Y,...Array(ue).fill("")]})(),B="\u2500",he=` \u250C${B.repeat(c+2)}\u252C${B.repeat(l+2)}\u2510`,L=` \u2514${B.repeat(c+2)}\u2534${B.repeat(l+2)}\u2518`;console.log(i.gray(he));for(let H=0;H<A;H++){let ue=qe(R[H]||"",c),ye=qe(W[H]||"",l),be=" ".repeat(Math.max(0,c-ue.length)),S=" ".repeat(Math.max(0,l-ye.length)),k=` \u2502 ${ue}${be} \u2502 ${ye}${S} \u2502`;console.log(i.gray(k))}console.log(i.gray(L)),console.log("")}function Ss(){process.stdout?.isTTY&&(j(process.stdout,0,-2),Z(process.stdout,4))}function xs(t){let e=!!(process.stdout?.isTTY&&process.stdin?.isTTY),o=!1,n=!1,r=!1,s=null,a=0,c=0,l=0;function p(){return i.gray(_t())}function _(){s&&(clearInterval(s),s=null)}function z(S){!e||!o||!n||!r||(process.stdout.write("\x1B7"),j(process.stdout,0,-2),Z(process.stdout,0),Q(process.stdout,0),process.stdout.write(` ${S}`),process.stdout.write("\x1B8"))}function Y(){if(!(!e||!o)&&c!==0){process.stdout.write("\x1B7"),j(process.stdout,0,2);for(let S=0;S<c;S++)Z(process.stdout,0),Q(process.stdout,0),S<c-1&&j(process.stdout,0,1);process.stdout.write("\x1B8"),c=0,n&&W()}}function W(){!e||!o||!n||(process.stdout.write("\x1B7"),j(process.stdout,0,1),Z(process.stdout,0),Q(process.stdout,0),process.stdout.write(p()),process.stdout.write("\x1B8"))}function A(S,k){if(!e||!o||!n)return;Y();let I=S.slice(0,6);if(I.length!==0){j(process.stdout,0,1);for(let b=0;b<I.length;b++)process.stdout.write(`
|
|
29
|
+
`);j(process.stdout,0,-(1+I.length)),process.stdout.write("\x1B7"),j(process.stdout,0,2);for(let b=0;b<I.length;b++){Z(process.stdout,0),Q(process.stdout,0);let ee=b===k?i.cyan("\u203A"):" ",te=b===k?i.white(I[b]):i.gray(I[b]);process.stdout.write(` ${ee} /${te}`),b<I.length-1&&j(process.stdout,0,1)}process.stdout.write("\x1B8"),c=I.length,W()}}function R(){if(!e||!o||!n)return;Y();let S=process.stdout.columns||80,k=l>0?Math.ceil(l/S):1;Z(process.stdout,0),j(process.stdout,0,-k),r&&j(process.stdout,0,-2),process.stdout.write("\x1B[J"),n=!1}function B(S={}){let k=S.preserveInput===!0;if(!e){t.prompt();return}k||(t.line="",t.cursor=0),l=_t().length;let I=p();process.stdout.write(`${I}
|
|
30
30
|
`),t.prompt(),process.stdout.write(`
|
|
31
31
|
${I}
|
|
32
|
-
`),Ss(),n=!0}function he(){if(!e||!o||!n)return;let
|
|
33
|
-
`);for(;k.length>0&&k[k.length-1]==="";)k.pop();for(let I of k)console.log(I?` ${I}`:"");r=!1}function ue(
|
|
32
|
+
`),Ss(),n=!0}function he(){if(!e||!o||!n)return;let S=process.stdout.columns||80,k=l>0?Math.ceil(l/S):1,I=p();process.stdout.write("\x1B7"),j(process.stdout,0,-k);for(let b=0;b<k;b++)Z(process.stdout,0),Q(process.stdout,0),b<k-1&&j(process.stdout,0,1);Z(process.stdout,0),process.stdout.write(I),j(process.stdout,0,2),Z(process.stdout,0),Q(process.stdout,0),process.stdout.write(I);for(let b=1;b<k;b++)j(process.stdout,0,1),Z(process.stdout,0),Q(process.stdout,0);process.stdout.write("\x1B8"),l=_t().length}function L(){if(!e||!o||!n)return;let S=(()=>{if(typeof t.getCursorPos!="function")return 0;try{return Math.max(0,Number(t.getCursorPos()?.rows||0))}catch{return 0}})();process.stdout.write("\x1B7"),j(process.stdout,0,-(S+1)),Z(process.stdout,0),Q(process.stdout,0),process.stdout.write(p()),j(process.stdout,0,S+2),Z(process.stdout,0),Q(process.stdout,0),process.stdout.write(p()),process.stdout.write("\x1B8")}function H(S){_(),R(),console.log();let k=String(S??"").replace(/\r/g,"").split(`
|
|
33
|
+
`);for(;k.length>0&&k[k.length-1]==="";)k.pop();for(let I of k)console.log(I?` ${I}`:"");r=!1}function ue(S){let k=String(S??"").replace(/\r/g,"").split(`
|
|
34
34
|
`);k.length===0&&k.push("");let I=[];for(let b of k)I.push(i.bgGray.white(` ${b||" "} `));return I.join(`
|
|
35
|
-
`)}function ye(){
|
|
36
|
-
`);for(;I.length>0&&I[I.length-1]==="";)I.pop();for(let b of I)console.log(b?` ${b}`:"");console.log(),r=!1}return{enabled:e,mount(){if(!o){if(!e){t.prompt(),o=!0;return}o=!0,B()}},refreshPrompt(
|
|
35
|
+
`)}function ye(){_();let S=()=>i.gray(`${Ge[a%Ge.length]} thinking`);if(!e){console.log(` ${S()}`),r=!0;return}Y(),R(),console.log(),console.log(` ${S()}`),B({preserveInput:!0}),r=!0,a+=1,s=setInterval(()=>{r&&(z(S()),a+=1)},120)}function be(S){_();let k=String(S??"").replace(/\r/g,"").replace(/⎿/g,"");if(!r){H(k);return}R(),console.log();let I=k.split(`
|
|
36
|
+
`);for(;I.length>0&&I[I.length-1]==="";)I.pop();for(let b of I)console.log(b?` ${b}`:"");console.log(),r=!1}return{enabled:e,mount(){if(!o){if(!e){t.prompt(),o=!0;return}o=!0,B()}},refreshPrompt(S={}){if(e&&o){n&&R(),B(S);return}t.prompt()},pushSystem(S){H(S)},pushUser(S){H(ue(S))},pushAssistant(S){be(S)},showAssistantLoading:ye,dismissTransientLoading(){_(),r&&e&&o&&n&&(process.stdout.write("\x1B7"),j(process.stdout,0,-2),Z(process.stdout,0),Q(process.stdout,0),j(process.stdout,0,-1),Z(process.stdout,0),Q(process.stdout,0),process.stdout.write("\x1B8")),r=!1},touchInputFrame:L,handleResize:he,showCommandDropdown:A,clearCommandDropdown:Y}}function $s(){console.log(""),console.log(i.cyan(" Available commands:"));for(let t of $t)console.log(i.white(` ${t.cmd.padEnd(10)} `)+i.gray(t.desc));console.log(""),console.log(i.cyan(" Chat options:")),console.log(i.white(" --stream, -s ")+i.gray("Enable typewriter effect (default: instant)")),console.log(""),console.log(i.gray(" To install/uninstall skills, just ask naturally:")),console.log(i.gray(' "connect to Jira" \u2022 "add GitHub" \u2022 "remove Slack"')),console.log("")}var vs=ls;async function Ar(t={}){let e=process.cwd();t.verbose&&(process.env.ZIBBY_VERBOSE="true");let o=t.stream||!1;[me(e,".env.local"),me(e,".env")].forEach(b=>{Ce(b)&&ts.config({path:b,override:!1})});try{let{loadCredentialsIntoEnv:b}=await Promise.resolve().then(()=>(ro(),so));await b({verbose:!!process.env.ZIBBY_DEBUG})}catch{}try{await import("@zibby/skills")}catch{}function r(){let b=Ye();if(!b)return!1;try{let ee=JSON.parse(atob(b.split(".")[1]));return ee.exp&&ee.exp*1e3>Date.now()}catch{return!1}}if(!r()){Ft();let b=le(),{spawn:ee}=await import("child_process"),te=await fetch(`${b}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});te.ok||(console.log(i.red("\n Could not start login. Try `zibby login`.\n")),process.exit(1));let{deviceCode:C,verificationUrl:d,expiresIn:K,interval:re}=await te.json(),J=process.platform;ee(J==="darwin"?"open":J==="win32"?"cmd":"xdg-open",J==="win32"?["/c","start","",d]:[d],{detached:!0,stdio:"ignore"}).unref(),console.log(i.cyan(`
|
|
37
37
|
Opening browser to authorize Zibby CLI...`)),console.log(i.gray(` ${d}
|
|
38
|
-
`));let pe=Oo();pe.setLabel("waiting for authorization");let we=(re||3)*1e3,_e=Math.floor(
|
|
38
|
+
`));let pe=Oo();pe.setLabel("waiting for authorization");let we=(re||3)*1e3,_e=Math.floor(K/(re||3)),ie=!1;for(let de=0;de<_e;de++){await as(we);try{let ae=await fetch(`${b}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:C})});if(ae.status===202)continue;if(!ae.ok)break;let q=await ae.json();if(q.status==="authorized"){Mt(q.token),zt(q.user),q.proxyUrl&&Ht(q.proxyUrl),q.mem0ProxyUrl&&Zt(q.mem0ProxyUrl),ie=!0;break}if(q.status==="denied")break}catch{break}}pe(),ie||(console.log(i.red("\n Login failed or timed out. Run `zibby login` to try again.\n")),process.exit(1))}let s=await us(e),a=await ds(e),c=t.agent||"assistant",l=Ye();l&&!process.env.ZIBBY_USER_TOKEN&&(process.env.ZIBBY_USER_TOKEN=l);let p=Kt()||Yt();p&&!process.env.ZIBBY_MEM0_OPENAI_BASE_URL&&(process.env.ZIBBY_MEM0_OPENAI_BASE_URL=p),process.env.AGENT_TYPE=c,process.env.ZIBBY_CHAT_OWNER_PID=String(process.pid);try{let{cleanupStalePidFiles:b}=await Promise.resolve().then(()=>(ft(),pt));b(e,s)}catch{}let _;try{_=Wn({state:{agentType:c}})}catch(b){console.log(i.red(`
|
|
39
39
|
${b.message}
|
|
40
|
-
`)),process.exit(1)}let z=jt(),W=Wt()?.[0]?.name,A=Vt(e),R="zibby",B=a.skills||[],he=Xt(e),L=he?[...new Set([...B,...he])]:[...B],H={data:null,timestamp:0},ue=300*1e3,ye={jira:"jira",github:"github",slack:"slack",sentry:"sentry"};try{let b=Ye();if(b){let ee=le(),te=await fetch(`${ee}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${b}`}});if(te.ok){let C=await te.json();for(let[d,
|
|
40
|
+
`)),process.exit(1)}let z=jt(),W=Wt()?.[0]?.name,A=Vt(e),R="zibby",B=a.skills||[],he=Xt(e),L=he?[...new Set([...B,...he])]:[...B],H={data:null,timestamp:0},ue=300*1e3,ye={jira:"jira",github:"github",slack:"slack",sentry:"sentry"};try{let b=Ye();if(b){let ee=le(),te=await fetch(`${ee}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${b}`}});if(te.ok){let C=await te.json();for(let[d,K]of Object.entries(ye)){let re=C[d]?.connected,J=L.indexOf(K),Ve=Re(K);re&&J===-1&&Ve?L.push(K):!re&&J!==-1&&L.splice(J,1)}Ue(e,L)}}}catch{}let be=L.filter(b=>b!=="skill-installer"&&b!=="core-tools"),S=be.length>0?`Skills: ${be.join(", ")}`:"Skills: (none)";_s({userName:z?.name?.split(" ")[0],cwd:e,projectName:W,restoredCount:A.length,skillsLine:S});let k=No(e),I=Lo(k);return new Promise(b=>{let ee=process.env.ZIBBY_CHAT_TAB_COMPLETION==="1",te={input:process.stdin,output:process.stdout,prompt:i.green(" > "),terminal:!0};ee&&(te.completer=x=>{let g=String(x||"");if(!g.startsWith("/"))return[[],g];let v=I.map(U=>U.cmd),P=v.filter(U=>U.startsWith(g));return[P.length>0?P:v,g]});let C=Vn(te),d=xs(C),K=null,re=!1,J=[],Ve=0,Mo=1200,pe=!1,we=!1,_e=!1,ie=!1,de="",ae=0,q=typeof C._ttyWrite=="function"?C._ttyWrite.bind(C):null;q&&(C._ttyWrite=(...x)=>{if(!(ie||Date.now()<ae))return q(...x)});function jo(){_e||!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004h"),_e=!0)}function vt(){_e&&(!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004l"),_e=!1))}function zo(x){let g="\x1B[200~",v="\x1B[201~";if(!ie&&!x.includes(g))return!1;let P=x,U=!1;for(;P.length>0;){if(!ie){let N=P.indexOf(g);if(N===-1)break;U=!0,It(),ie=!0,de="",P=P.slice(N+g.length);continue}let V=P.indexOf(v);if(V===-1){U=!0,de+=P;break}U=!0,de+=P.slice(0,V);let ce=String(de||"").replace(/\r\n/g,`
|
|
41
41
|
`).replace(/\r/g,`
|
|
42
42
|
`);if(ce.length>0){let N=ce.split(`
|
|
43
|
-
`);for(let oe of N)nt(oe)}Me(),de="",ie=!1,P=P.slice(V+v.length)}return U}function At(){if(!pe){pe=!0;try{Ne(e,A),Ue(e,L)}catch{}try{vt()}catch{}try{C.close()}catch{}process.exit(0)}}async function Xe(){if(!pe){pe=!0,typeof
|
|
43
|
+
`);for(let oe of N)nt(oe)}Me(),de="",ie=!1,P=P.slice(V+v.length)}return U}function At(){if(!pe){pe=!0;try{Ne(e,A),Ue(e,L)}catch{}try{vt()}catch{}try{C.close()}catch{}process.exit(0)}}async function Xe(){if(!pe){pe=!0,typeof _?.cleanup=="function"&&await _.cleanup().catch(()=>{});try{let{killAllChatOrchestratedRuns:x}=await Promise.resolve().then(()=>(ft(),pt)),{postCliInterruptedRunIndex:g}=await import("@zibby/workflow-templates/run-index-post-cli.js");x(e,process.pid,s),g({cwd:e,config:s})}catch{}Ne(e,A),Ue(e,L),d.pushSystem(i.gray("Session saved. Goodbye!")),vt(),C.close(),process.exit(0)}}if(d.mount(),jo(),process.stdout?.isTTY){let x;process.stdout.on("resize",()=>{clearTimeout(x),x=setTimeout(()=>{d.handleResize()},80)})}let Qe=0,De=x=>{if(typeof x=="string"?x==="\x1B":x&&typeof x.length=="number"?x.length===1&&x[0]===27:!1){K&&K.abort(),At();return}let v=typeof x=="string"?x:x&&typeof x.length=="number"?Buffer.from(x).toString("utf8"):"";if(!v)return;if(zo(v)){Qe=Date.now()+1200,ae=Date.now()+1200,ot();return}let P=(v.includes(`
|
|
44
44
|
`)||v.includes("\r"))&&v!=="\r"&&v!==`
|
|
45
45
|
`&&v!==`\r
|
|
46
|
-
`,U=v.includes("\x1B[200~")||v.includes("\x1B[201~"),V=v.length>=16&&/\s/.test(v)&&!v.startsWith("\x1B");(P||U||V)&&(Qe=Date.now()+1200,ae=Date.now()+1200,It(),ot())},F={query:"",matches:[],selected:0},G={prefix:"",matches:[],nextIndex:0},O={active:!1,prefix:"",lines:[],timer:null},et=[],Ct=0,tt="",Fo=new Set($t.map(
|
|
47
|
-
`);et.push({placeholder:g,text:v});let P=String(O.prefix||"").trimEnd(),U=P?`${P} ${g}`:g;Se(U,{preserveFrame:!0}),xe(C.line)}O.active=!1,O.prefix="",O.lines=[],ae=0}function ot(){O.timer&&clearTimeout(O.timer),O.timer=setTimeout(()=>{Me()},180)}function It(){O.active||(O.active=!0,O.prefix=String(tt||C.line||""),O.lines=[],Se(O.prefix,{preserveFrame:!0}))}function nt(
|
|
46
|
+
`,U=v.includes("\x1B[200~")||v.includes("\x1B[201~"),V=v.length>=16&&/\s/.test(v)&&!v.startsWith("\x1B");(P||U||V)&&(Qe=Date.now()+1200,ae=Date.now()+1200,It(),ot())},F={query:"",matches:[],selected:0},G={prefix:"",matches:[],nextIndex:0},O={active:!1,prefix:"",lines:[],timer:null},et=[],Ct=0,tt="",Fo=new Set($t.map(x=>x.cmd));function Se(x,{preserveFrame:g=!1}={}){let v=String(x||"");C.line=v,C.cursor=v.length,tt=v,typeof C._refreshLine=="function"?C._refreshLine():C.prompt(),g&&d.touchInputFrame()}function kt(){G.prefix="",G.matches=[],G.nextIndex=0}function Me(){if(O.timer&&(clearTimeout(O.timer),O.timer=null),O.active&&O.lines.length>0){Ct+=1;let x=O.lines.length,g=`[Pasted text #${Ct} +${x} lines]`,v=O.lines.join(`
|
|
47
|
+
`);et.push({placeholder:g,text:v});let P=String(O.prefix||"").trimEnd(),U=P?`${P} ${g}`:g;Se(U,{preserveFrame:!0}),xe(C.line)}O.active=!1,O.prefix="",O.lines=[],ae=0}function ot(){O.timer&&clearTimeout(O.timer),O.timer=setTimeout(()=>{Me()},180)}function It(){O.active||(O.active=!0,O.prefix=String(tt||C.line||""),O.lines=[],Se(O.prefix,{preserveFrame:!0}))}function nt(x){return O.active?(O.lines.push(String(x||"")),Se(O.prefix,{preserveFrame:!0}),ot(),!0):!1}function Yo(x){let g=String(x||"");for(let v of et)g=g.split(v.placeholder).join(v.text);return g}function xe(x){let g=String(x||"");if(!g.startsWith("/")||g.includes(" ")||g.length===0){F.query="",F.matches=[],F.selected=0,d.clearCommandDropdown();return}k=No(e),I=Lo(k);let v=g.slice(1).toLowerCase(),P=k.filter(U=>U.toLowerCase().startsWith(v));F.query=v,F.matches=P,F.selected=Math.min(F.selected,Math.max(0,P.length-1)),d.showCommandDropdown(P,F.selected)}let st=(x,g)=>{if(g?.name==="escape"||g?.sequence==="\x1B"){K&&K.abort(),At();return}if((g?.name==="return"||g?.name==="enter")&&(we=!0),(g?.name==="backspace"||g?.name==="delete")&&d.touchInputFrame(),g?.name==="tab"&&!g?.shift){let U=String(C.line||""),V=Number(C.cursor||U.length);if(!ws(U,V)){kt(),xe(C.line);return}let ce=U.slice(1).toLowerCase();if(G.prefix!==ce&&(G.prefix=ce,G.matches=I.map(oe=>oe.cmd).filter(oe=>oe.toLowerCase().startsWith(`/${ce}`)),G.nextIndex=0),G.matches.length===0)return;let N=G.nextIndex%G.matches.length;G.nextIndex+=1,Se(G.matches[N]),xe(C.line);return}let v=String(C.line||""),P=v.startsWith("/")&&!v.includes(" ")&&F.matches.length>0;if(g?.name==="up"||g?.name==="down"){if(!P){xe(C.line);return}let U=g.name==="up"?-1:1,V=F.matches.length;F.selected=(F.selected+U+V)%V;let ce=F.matches[F.selected];Se(`/${ce}`,{preserveFrame:!0}),d.showCommandDropdown(F.matches,F.selected);return}g?.name!=="tab"&&kt(),setTimeout(()=>{xe(C.line),O.active||(tt=String(C.line||""))},50)};process.stdin?.on&&(Xn(process.stdin,C),process.stdin.on("keypress",st)),d.enabled&&process.stdin?.on&&(typeof process.stdin.prependListener=="function"?process.stdin.prependListener("data",De):process.stdin.on("data",De)),C.on("line",async x=>{try{let g=String(x||""),v=we;if(we=!1,!v&&(O.active||ie||Date.now()<Qe||Date.now()<ae)){if(O.active&&g.length>0){nt(g);return}O.active&&(Me(),d.refreshPrompt());return}if(O.active&&(Me(),g=String(C.line||g||"")),nt(g))return;let P=g.trim(),U=F.matches[F.selected];if(P.startsWith("/")&&!P.includes(" ")&&F.matches.length>0&&!Fo.has(P)&&P!==`/${U}`){d.clearCommandDropdown(),d.refreshPrompt(),Se(`/${U}`),xe(`/${U}`);return}d.clearCommandDropdown();let N=String(g||"").replace(/[\u0000-\u001F\u007F-\u009F]/g,"").trim();if(!N){d.enabled&&process.stdout?.isTTY&&(j(process.stdout,0,-1),Z(process.stdout,4));return}if(re&&N!=="/exit"&&N!=="/quit"){K&&K.abort(),J.push(N),d.pushSystem(i.gray("Processing your message...")),d.refreshPrompt({preserveInput:!0});return}let oe=1e4;if(N.length>oe){d.pushSystem(i.red(`\u26A0 Input too long (${N.length} chars). Maximum: ${oe} characters.`)),d.pushSystem(i.gray("Tip: If you need to share logs, use a file instead:")),d.pushSystem(i.gray(" 1. Save to file: pbpaste > debug.log")),d.pushSystem(i.gray(' 2. Ask: "analyze debug.log in current directory"')),d.refreshPrompt();return}if(N==="/exit"||N==="/quit"){Xe();return}if(N==="/help"){$s(),d.refreshPrompt();return}if(N==="/agents"){try{let{pickAgentWithSessions:m,handleClaudeCodeAddon:T,upsertAgentSession:$,AGENTS:E}=await Promise.resolve().then(()=>(Ao(),vo));console.log("");let y=await m({apiUrl:le(),sessionToken:l,currentAgentId:R});if(y.action==="cancel"){console.log(i.gray(" Cancelled.")),console.log(""),d.refreshPrompt();return}if(y.action==="switch"&&y.agentType==="zibby"){R==="zibby"?console.log(i.gray(" Already using Zibby Chat.")):(R="zibby",console.log(i.green(" \u2713 Switched to Zibby Chat (default)"))),console.log(""),d.refreshPrompt();return}if(y.action==="resume"){let w=E.find(h=>h.id===y.agentType),f=y.session?.sandbox_endpoint||process.env.ZIBBY_SANDBOX_ENDPOINT||null;if(!f||!y.sessionId){console.log(i.yellow(` Cannot resume \u2014 sandbox endpoint or session_id missing for ${w?.name||y.agentType}.`)),console.log(i.gray(" (Sandbox manager Lambda must record sandbox_endpoint in /agents/sessions when provisioning ready.)")),console.log(""),d.refreshPrompt();return}try{let{attachToSession:h}=await Promise.resolve().then(()=>(wt(),bt)),D=/^https/.test(le()),M=await h({sandboxEndpoint:f,sessionId:y.sessionId,sessionToken:l,useTls:D});M.reason==="detach"?console.log(i.gray(`
|
|
48
48
|
Detached from ${w?.name}. Session continues running in the cloud.`)):M.reason==="remote-exit"?console.log(i.gray(`
|
|
49
49
|
${w?.name} session exited (code ${M.exitCode??"?"}).`)):M.reason==="ws-error"&&console.log(i.red(`
|
|
50
|
-
Connection error: ${M.message}`))}catch(h){console.log(i.red(` Attach failed: ${h.message}`))}console.log(""),d.refreshPrompt();return}if(y.action==="create"){let w=E.find(f=>f.id===y.agentType);if(y.agentType==="claude-code"){let f=await T({workspaceId:z?.account_id||"workspace-default",sessionToken:l,apiUrl:le()});if(!f.cancelled){if(f.ready||f.provisioning){try{await
|
|
50
|
+
Connection error: ${M.message}`))}catch(h){console.log(i.red(` Attach failed: ${h.message}`))}console.log(""),d.refreshPrompt();return}if(y.action==="create"){let w=E.find(f=>f.id===y.agentType);if(y.agentType==="claude-code"){let f=await T({workspaceId:z?.account_id||"workspace-default",sessionToken:l,apiUrl:le()});if(!f.cancelled){if(f.ready||f.provisioning){try{await $({apiUrl:le(),sessionToken:l,agentType:"claude-code",fields:{sandbox_id:f.sandboxId,workspace_id:z?.account_id}})}catch(D){console.warn(i.gray(` (could not save session metadata: ${D.message})`))}let h=f.sandboxEndpoint||process.env.ZIBBY_SANDBOX_ENDPOINT||null;if(f.ready&&h)try{let{spawnAndAttach:D}=await Promise.resolve().then(()=>(wt(),bt)),M=/^https/.test(le()),X=await D({sandboxEndpoint:h,sessionToken:l,agentType:"claude-code",useTls:M});X.reason==="detach"?console.log(i.gray(`
|
|
51
51
|
Detached from ${w.name}. Session continues in the cloud.`)):X.reason==="remote-exit"?console.log(i.gray(`
|
|
52
52
|
${w.name} session exited (code ${X.exitCode??"?"}).`)):X.reason==="ws-error"&&console.log(i.red(`
|
|
53
|
-
Connection error: ${X.message}`))}catch(D){console.log(i.red(` Spawn/attach failed: ${D.message}`))}else R="claude-code",console.log(i.green(f.ready?` \u2713 Active agent: ${w.name}`:` Provisioning ${w.name} \u2014 re-run /agents in ~30s when ready`));console.log("")}}}else{try{await
|
|
54
|
-
Active skills:`))
|
|
53
|
+
Connection error: ${X.message}`))}catch(D){console.log(i.red(` Spawn/attach failed: ${D.message}`))}else R="claude-code",console.log(i.green(f.ready?` \u2713 Active agent: ${w.name}`:` Provisioning ${w.name} \u2014 re-run /agents in ~30s when ready`));console.log("")}}}else{try{await $({apiUrl:le(),sessionToken:l,agentType:y.agentType,fields:{workspace_id:z?.account_id}})}catch(f){console.warn(i.gray(` (could not save session metadata: ${f.message})`))}R=y.agentType,console.log(i.green(` \u2713 New ${w?.name||y.agentType} session`)),console.log(i.gray(" (Live agent connect \u2014 wiring up in next slice.)")),console.log("")}d.refreshPrompt();return}}catch(m){m?.name==="ExitPromptError"?(console.log(i.gray(" Cancelled.")),console.log("")):/zibby login/i.test(m?.message||"")?(console.log(i.yellow(" Session expired \u2014 please run `zibby login` again.")),console.log("")):(console.log(i.red(` Agent selection failed: ${m.message}`)),console.log(""))}d.refreshPrompt();return}if(N==="/skills"){let T=Re("skill-installer")?.catalog||{},$=L.filter(y=>y!=="skill-installer");console.log(i.cyan(`
|
|
54
|
+
Active skills:`)),$.length===0&&console.log(i.gray(" (none)"));for(let y of $){let w=T[y]||{};console.log(i.green(` \u2713 ${y}`)+i.gray(w.description?` \u2014 ${w.description}`:""))}let E=Object.keys(T).filter(y=>!L.includes(y));if(E.length>0){console.log(i.cyan(`
|
|
55
55
|
Available:`));for(let y of E){let w=T[y],f=w.envKeys?.length>0?vs(w.envKeys).ok?i.green(" \u2713 configured"):i.yellow(` \u26A0 needs: ${w.envKeys.join(", ")}`):"";console.log(i.white(` - ${y}`)+i.gray(` \u2014 ${w.description}`)+f)}}console.log(i.gray(`
|
|
56
56
|
Just ask to install: "connect to Jira", "add GitHub", etc.
|
|
57
57
|
`)),d.refreshPrompt();return}if(N.startsWith("/history")){if(A.length===0)console.log(i.gray(`
|
|
58
58
|
No conversation history.
|
|
59
|
-
`));else{let m=N.split(/\s+/).slice(1),T=m.includes("--all")
|
|
59
|
+
`));else{let m=N.split(/\s+/).slice(1),T=m.includes("--all"),$=m.indexOf("-n"),E=$>=0&&m[$+1]?parseInt(m[$+1],10):NaN,y=T?A.length:isNaN(E)?10:E,w=A.slice(-y);console.log(i.gray(`
|
|
60
60
|
Showing ${w.length} of ${A.length} messages${T?" (all)":""}:
|
|
61
61
|
`));for(let f of w){let h=f.role==="human"?i.green(" You"):i.cyan(" Zibby"),D=T||E>10?500:100,M=f.content.length>D?`${f.content.substring(0,D)}...`:f.content;console.log(`${h}: ${i.white(M)}`)}console.log("")}d.refreshPrompt();return}if(N==="/clear"){A.length=0,Ne(e,A),console.log(i.gray(`
|
|
62
62
|
History cleared.
|
|
63
63
|
`)),d.refreshPrompt();return}if(N.startsWith("/memory")){let m=L.includes("chat-memory")?Re("chat-memory"):null;if(!m?.handleToolCall){console.log(i.yellow(`
|
|
64
64
|
Chat memory not active. Install with: "add chat memory"
|
|
65
|
-
`)),d.refreshPrompt();return}let T=N.split(/\s+/).slice(1)
|
|
65
|
+
`)),d.refreshPrompt();return}let T=N.split(/\s+/).slice(1),$=T[0]||"brief",E={options:{workspace:e}};try{if($==="facts"||$==="all"){let y=parseInt(T[1],10)||30,w=await m.handleToolCall("memory_recall",{limit:y},E),f=JSON.parse(w);if(console.log(i.cyan(`
|
|
66
66
|
Stored memories (${f.total}):
|
|
67
67
|
`)),f.total===0)console.log(i.gray(` (empty \u2014 memories are saved as the agent learns things)
|
|
68
|
-
`));else{for(let h of f.memories){let D=i.yellow(`[${h.category}]`),M=Number(h.relevance)<1?i.gray(` (${(Number(h.relevance)*100).toFixed(0)}%)`):"",X=h.ticket_key?i.magenta(` ${h.ticket_key}`):"",Te=h.source?i.gray(` via ${h.source}`):"";console.log(` ${D}${X} ${i.white(h.content)}${M}${Te}`)}console.log("")}}else if(
|
|
68
|
+
`));else{for(let h of f.memories){let D=i.yellow(`[${h.category}]`),M=Number(h.relevance)<1?i.gray(` (${(Number(h.relevance)*100).toFixed(0)}%)`):"",X=h.ticket_key?i.magenta(` ${h.ticket_key}`):"",Te=h.source?i.gray(` via ${h.source}`):"";console.log(` ${D}${X} ${i.white(h.content)}${M}${Te}`)}console.log("")}}else if($==="tasks"){let y=parseInt(T[1],10)||20,w=await m.handleToolCall("task_history",{limit:y},E),f=JSON.parse(w);if(console.log(i.cyan(`
|
|
69
69
|
Task history (${f.total}):
|
|
70
70
|
`)),f.total===0)console.log(i.gray(` (no tasks logged yet)
|
|
71
|
-
`));else{for(let h of f.tasks){let D=h.status==="passed"?i.green("\u2713"):h.status==="failed"?i.red("\u2717"):i.yellow("\u25CB"),M=h.ticket_key?i.magenta(` ${h.ticket_key}`):"",X=i.gray(`[${h.type}]`),Te=h.result_summary?i.gray(` \u2014 ${h.result_summary.slice(0,80)}`):"";console.log(` ${D} ${X}${M} ${i.white(h.title)}${Te}`)}console.log("")}}else if(
|
|
71
|
+
`));else{for(let h of f.tasks){let D=h.status==="passed"?i.green("\u2713"):h.status==="failed"?i.red("\u2717"):i.yellow("\u25CB"),M=h.ticket_key?i.magenta(` ${h.ticket_key}`):"",X=i.gray(`[${h.type}]`),Te=h.result_summary?i.gray(` \u2014 ${h.result_summary.slice(0,80)}`):"";console.log(` ${D} ${X}${M} ${i.white(h.title)}${Te}`)}console.log("")}}else if($==="sessions"){let y=await m.handleToolCall("memory_brief",{},E),w=JSON.parse(y);if(console.log(i.cyan(`
|
|
72
72
|
Recent sessions (${w.recentSessions?.length||0}):
|
|
73
73
|
`)),!w.recentSessions?.length)console.log(i.gray(` (no sessions saved yet)
|
|
74
|
-
`));else{for(let f of w.recentSessions){let h=f.tickets?i.magenta(` [${f.tickets}]`):"",D=f.tasks_run>0?i.gray(` \u2014 ${f.tasks_run} tasks (${f.tasks_passed} passed, ${f.tasks_failed} failed)`):"",M=f.created_at?i.gray(` ${f.created_at.split("T")[0]}`):"";if(console.log(` ${i.white(f.summary)}${h}${D}${M}`),f.key_facts)for(let X of f.key_facts.split(";").map(Te=>Te.trim()).filter(Boolean))console.log(i.gray(` \u2192 ${X}`))}console.log("")}}else if(
|
|
74
|
+
`));else{for(let f of w.recentSessions){let h=f.tickets?i.magenta(` [${f.tickets}]`):"",D=f.tasks_run>0?i.gray(` \u2014 ${f.tasks_run} tasks (${f.tasks_passed} passed, ${f.tasks_failed} failed)`):"",M=f.created_at?i.gray(` ${f.created_at.split("T")[0]}`):"";if(console.log(` ${i.white(f.summary)}${h}${D}${M}`),f.key_facts)for(let X of f.key_facts.split(";").map(Te=>Te.trim()).filter(Boolean))console.log(i.gray(` \u2192 ${X}`))}console.log("")}}else if($==="search"){let y=T.slice(1).join(" ");if(!y)console.log(i.yellow(`
|
|
75
75
|
Usage: /memory search <keyword>
|
|
76
76
|
`));else{let w=await m.handleToolCall("memory_recall",{query:y,limit:20},E),f=JSON.parse(w);console.log(i.cyan(`
|
|
77
77
|
Search "${y}" \u2014 ${f.total} results:
|
|
@@ -80,7 +80,7 @@ ${I}
|
|
|
80
80
|
`)),console.log(i.white(` Facts stored: ${f>0?i.cyan(f):i.gray("0")}`)),console.log(i.white(` Sessions saved: ${h>0?i.cyan(h):i.gray("0")}`)),D&&console.log(i.white(` Task history: ${i.gray(D)}`)),console.log(i.gray(`
|
|
81
81
|
Subcommands:`)),console.log(i.gray(" /memory facts [n] \u2014 List all stored memories")),console.log(i.gray(" /memory tasks [n] \u2014 List task history")),console.log(i.gray(" /memory sessions \u2014 List session summaries")),console.log(i.gray(" /memory search <keyword> \u2014 Search memories")),console.log("")}}catch(y){console.log(i.red(`
|
|
82
82
|
Memory error: ${y.message}
|
|
83
|
-
`))}d.refreshPrompt();return}d.enabled&&process.stdout?.isTTY&&(j(process.stdout,0,-1),
|
|
83
|
+
`))}d.refreshPrompt();return}d.enabled&&process.stdout?.isTTY&&(j(process.stdout,0,-1),Z(process.stdout,0)),d.pushUser(N),d.refreshPrompt(),d.showAssistantLoading();let Tt=Yo(N),je=ps(e,Tt);if(et.length=0,!String(je||"").trim()){d.dismissTransientLoading(),d.refreshPrompt();return}if(je.length>oe){d.pushAssistant(i.red(`Input too long after command expansion (${je.length} chars).`)),d.pushSystem(i.gray(`Try shortening the command template or user text. Limit: ${oe} chars.`)),d.refreshPrompt();return}re=!0;let ne=a.systemPrompt||"You are Zibby, a helpful AI assistant.",Pt=hs(a,t);Pt&&(ne+=`
|
|
84
84
|
|
|
85
85
|
${Pt}`);let Et=to({activeSkills:L,chatConfig:a,options:t});Et&&(ne+=`
|
|
86
86
|
|
|
@@ -103,8 +103,8 @@ Use provided tools when external data/actions are required. Do not claim actions
|
|
|
103
103
|
- Conversation flow: ask about purpose \u2192 input data \u2192 processing steps \u2192 output format \u2192 conditional logic.
|
|
104
104
|
- Then call design_workflow to create a spec, review with user, then build_workflow to generate code.
|
|
105
105
|
- After building: remind user about \`zibby workflow run <name>\` (run locally), \`zibby workflow deploy <name>\` (deploy), \`zibby workflow logs <uuid>\` (logs).
|
|
106
|
-
- Use list_workflows to show existing workflows, add_node to extend them, deploy_workflow to ship.`),L.includes("chat-memory"))try{let m=Re("chat-memory");if(typeof m?.buildPromptContext=="function"){let T=Date.now()
|
|
106
|
+
- Use list_workflows to show existing workflows, add_node to extend them, deploy_workflow to ship.`),L.includes("chat-memory"))try{let m=Re("chat-memory");if(typeof m?.buildPromptContext=="function"){let T=Date.now(),$;H.data&&T-H.timestamp<ue?($=H.data,process.env.ZIBBY_VERBOSE==="true"&&d.pushSystem(i.gray("Using cached memory context"))):($=await m.buildPromptContext({options:{workspace:e}},{}),H={data:$,timestamp:T},process.env.ZIBBY_VERBOSE==="true"&&d.pushSystem(i.gray("Refreshed memory context cache")));let E=String($?.backend||"dolt");process.env.ZIBBY_VERBOSE==="true"&&(d.pushSystem(i.gray(`memory backend: ${E}`)),d.pushSystem(i.gray(`memory retrieval output: ${qe(JSON.stringify($?.debugPreview||{}),1400)}`)),$?.error&&d.pushSystem(i.yellow(`memory backend warning: ${$.error}`))),$?.promptContext&&(ne+=`
|
|
107
107
|
|
|
108
|
-
${
|
|
109
|
-
${
|
|
110
|
-
[Active test runs: ${w.runs.map(h=>`${h.runId}: ${h.ticketKey||h.spec} (${h.status})`).join(", ")}. Use run_status("all") to check progress.]`)}catch{}let
|
|
108
|
+
${$.promptContext}`)}}catch(m){process.env.ZIBBY_VERBOSE==="true"&&d.pushSystem(i.yellow(`memory backend warning: ${String(m?.message||m)}`))}ne=Be(ne,Do);let Ko=fs(A),rt=gs([{role:"system",content:ne},...Ko,{role:"user",content:je}]),Nt=xt(rt),Zo=Buffer.byteLength(JSON.stringify(rt),"utf8");process.env.ZIBBY_VERBOSE==="true"&&d.pushSystem(i.gray(`payload estimate: ${Nt} chars, ${Zo} bytes (~${Math.round(Nt/4)} tokens)`)),A.push({role:"human",content:Tt});let ke=d.enabled?(()=>{let m=()=>{};return m.setLabel=()=>{},m})():Oo(),fe=!0,ze=[],Ut="",Ie="",Cs=50,ks=500,Is=3,Ts=60,Ps=500,Es=15,Os=25,Ns=4,Us=new Set([".","!","?",",",";",":"]),Wo=m=>{fe&&(ke(),fe=!1),Ie+=m},Jo=(m,T)=>{if(!m){fe&&ke.setLabel("thinking...");return}ze.push(m);let $=70,E=m;if(T&&typeof T=="object"){let w=Object.values(T).map(h=>typeof h=="string"?h:JSON.stringify(h)).join(", "),f=`${m}(${w})`;f.length<=$?E=f:E=`${m}(${w.slice(0,$-m.length-4)}...)`}E!==Ut&&(Ut=E,d.pushSystem(i.gray(`\u23BF ${E}`)),d.refreshPrompt({preserveInput:!0}),fe&&d.showAssistantLoading()),fe&&ke.setLabel(E)},it=new AbortController;K=it;try{let m=await Zn("",{state:{agentType:c,config:s,cwd:e,workspace:e}},{model:s?.agent?.assistant?.model||a.model||"auto",workspace:e,skills:L,activeSkills:L,config:s,timeout:a.timeout||3e5,messages:rt,skipPromptFragments:!0,stream:!0,onToken:Wo,onToolCall:Jo,signal:it.signal});fe&&ke();let T=typeof m=="string"?m:m?.structured?JSON.stringify(m.structured,null,2):m?.raw||String(m),$=Ie&&Ie.trim().length>0?Ie.trim():T.trim(),E=ys($,ze)?$:bs($);d.pushAssistant(E);let y=ze.length>0?`[tools used: ${ze.join(", ")}]
|
|
109
|
+
${$}`:$;A.push({role:"ai",content:y}),Ne(e,A),Ue(e,L)}catch(m){if(fe&&ke(),d.dismissTransientLoading(),it.signal.aborted){J.length===0&&d.pushAssistant(i.gray("[cancelled]"));let T="";try{let{testRunnerSkill:E}=await import("../../skills/index.js"),y=await E.handleToolCall("run_status",{runId:"all"},{options:{workspace:e}}),w=JSON.parse(y);w.runs?.length>0&&(T=`
|
|
110
|
+
[Active test runs: ${w.runs.map(h=>`${h.runId}: ${h.ticketKey||h.spec} (${h.status})`).join(", ")}. Use run_status("all") to check progress.]`)}catch{}let $=Ie.trim();$?A.push({role:"ai",content:$+T}):A.push({role:"ai",content:`[interrupted \u2014 new message]${T}`})}else{let T=String(m?.message||m||"Unknown error");/413|payload too large|request payload too large/i.test(T)?(d.pushAssistant(i.yellow("Request became too large for the proxy (413).")),d.pushSystem(i.gray("Try: /clear, then retry your command; or shorten command/context."))):d.pushAssistant(i.red(`Error: ${T}`)),A.push({role:"ai",content:`[Error: ${m.message}]`})}}finally{K=null,re=!1}if(d.refreshPrompt(),J.length>0){let m=J.shift();we=!0,setImmediate(()=>C.emit("line",m))}}catch(g){d.pushSystem(i.red(`Input handling error: ${g?.message||String(g)}`)),d.refreshPrompt()}}),C.on("SIGINT",()=>{if(K){K.abort();return}Xe()}),C.on("close",Xe);let Ho=()=>{process.stdin?.off?(process.stdin.off("data",De),process.stdin.off("keypress",st)):process.stdin?.removeListener&&(process.stdin.removeListener("data",De),process.stdin.removeListener("keypress",st))};C.on("close",Ho)})}export{vr as _buildPrompt,ls as _checkEnvKeys,cs as _formatHistory,$r as _inferAgentType,Ar as chatCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function d(e,r=""){return`${String(e).replace(/\/+$/,"")}/agents/credentials${r}`}function u(){let e=new Error("Session expired \u2014 run zibby login");return e.code="AUTH_EXPIRED",e}async function y({apiUrl:e,sessionToken:r}){if(!r)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let t=await fetch(d(e),{headers:{Authorization:`Bearer ${r}`}});if(t.status===401)throw u();if(t.status===404)return{credentials:[],by_type:{oauth:[],api:[]},total:0};if(!t.ok){let s=new Error(`List credentials failed (${t.status})`);throw s.status=t.status,s}return t.json()}async function h({apiUrl:e,sessionToken:r,type:t,token:s,provider:o,source:i="~/.zibby/config.json"}){if(!r)throw new Error("No session token \u2014 run zibby login first");let a={type:t,token:s,source:i};o&&(a.provider=o);let n=await fetch(d(e),{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(a)});if(n.status===401)throw u();if(!n.ok){let c=`Add credential failed (${n.status})`;try{let f=await n.json();f?.error&&(c=`${c}: ${f.error}`)}catch{}let l=new Error(c);throw l.status=n.status,l}return n.json()}async function p({apiUrl:e,sessionToken:r,type:t,index:s}){if(!r)throw new Error("No session token \u2014 run zibby login first");let o=await fetch(d(e,`/${encodeURIComponent(t)}/${encodeURIComponent(s)}`),{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(o.status===401)throw u();if(!o.ok){let i=new Error(`Delete credential failed (${o.status})`);throw i.status=o.status,i}return o.json()}async function w({apiUrl:e,sessionToken:r,credentials:t}){let s=0,o=0,i=[];for(let a of t)try{let n=await h({apiUrl:e,sessionToken:r,type:a.type,token:a.token,source:a.source_var||a.source||"local"});n.deduped?o+=1:n.added&&(s+=1)}catch(n){i.push({masked:a.token?`***${a.token.slice(-4)}`:"***",error:n.message})}return{added:s,deduped:o,errors:i}}export{h as addCredential,p as deleteCredential,y as listCredentials,w as syncFromLocal};
|
package/dist/commands/creds.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import o from"chalk";function b(e,n=""){return`${String(e).replace(/\/+$/,"")}/agents/credentials${n}`}function h(){let e=new Error("Session expired \u2014 run zibby login");return e.code="AUTH_EXPIRED",e}async function _({apiUrl:e,sessionToken:n}){if(!n)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let t=await fetch(b(e),{headers:{Authorization:`Bearer ${n}`}});if(t.status===401)throw h();if(t.status===404)return{credentials:[],by_type:{oauth:[],api:[]},total:0};if(!t.ok){let c=new Error(`List credentials failed (${t.status})`);throw c.status=t.status,c}return t.json()}async function m({apiUrl:e,sessionToken:n,type:t,token:c,provider:s,source:r="~/.zibby/config.json"}){if(!n)throw new Error("No session token \u2014 run zibby login first");let l={type:t,token:c,source:r};s&&(l.provider=s);let i=await fetch(b(e),{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(l)});if(i.status===401)throw h();if(!i.ok){let d=`Add credential failed (${i.status})`;try{let U=await i.json();U?.error&&(d=`${d}: ${U.error}`)}catch{}let a=new Error(d);throw a.status=i.status,a}return i.json()}async function k({apiUrl:e,sessionToken:n,type:t,index:c}){if(!n)throw new Error("No session token \u2014 run zibby login first");let s=await fetch(b(e,`/${encodeURIComponent(t)}/${encodeURIComponent(c)}`),{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(s.status===401)throw h();if(!s.ok){let r=new Error(`Delete credential failed (${s.status})`);throw r.status=s.status,r}return s.json()}async function w({apiUrl:e,sessionToken:n,credentials:t}){let c=0,s=0,r=[];for(let l of t)try{let i=await m({apiUrl:e,sessionToken:n,type:l.type,token:l.token,source:l.source_var||l.source||"local"});i.deduped?s+=1:i.added&&(c+=1)}catch(i){r.push({masked:l.token?`***${l.token.slice(-4)}`:"***",error:i.message})}return{added:c,deduped:s,errors:r}}import C from"node:fs/promises";import O from"node:path";import A from"node:os";var g=O.join(A.homedir(),".zibby","config.json"),v={CLAUDE_CODE_OAUTH_TOKEN:"oauth",CLAUDE_CODE_OAUTH_TOKEN_POOL:"oauth",ANTHROPIC_AUTH_TOKEN:"oauth",ANTHROPIC_API_KEY:"api",ANTHROPIC_API_KEY_POOL:"api"};function N(e){if(!e)return[];let n;try{n=JSON.parse(e)}catch{return[]}let t=n?.agentKeys;if(!t||typeof t!="object")return[];let c=[],s=new Set;for(let[r,l]of Object.entries(v)){let i=t[r];if(!i||typeof i!="string")continue;let d=r.endsWith("_POOL")?i.split(",").map(a=>a.trim()).filter(Boolean):[i.trim()];for(let a of d)a.length<8||s.has(a)||(s.add(a),c.push({type:l,token:a,source_var:r}))}return c}async function P(e=g){let n;try{n=await C.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return N(n)}async function x({filepath:e,env:n=process.env}={}){let t=await P(e),c=new Set(t.map(r=>r.token)),s=[];for(let[r,l]of Object.entries(v)){let i=n[r];if(!i)continue;let d=r.endsWith("_POOL")?i.split(",").map(a=>a.trim()).filter(Boolean):[i];for(let a of d)a.length<8||c.has(a)||(c.add(a),s.push({type:l,token:a,source_var:r,source:"process.env"}))}return{config:t.map(r=>({...r,source:"config.json"})),env:s,all:[...t.map(r=>({...r,source:"config.json"})),...s]}}var p={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function u(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let n=process.env.ZIBBY_ENV||"prod";p[n]?e=p[n].apiUrl:e=p.prod.apiUrl}try{let n=new URL(e);return n.protocol!=="http:"&&n.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${n.protocol} (only http/https allowed)`),p.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),p.prod.apiUrl}}import{existsSync as E,mkdirSync as J,readFileSync as z,writeFileSync as W}from"fs";import{homedir as I}from"os";import{join as f}from"path";function R(){return process.env.ZIBBY_CONFIG_DIR||f(I(),".zibby")}function T(){return f(R(),"config.json")}var B=f(I(),".zibby"),Q=f(B,"config.json");function L(){try{let e=T();if(E(e)){let n=z(e,"utf-8");return JSON.parse(n)}}catch{}return{}}function $(){return L().sessionToken||null}function y(){let e=$();return e||(console.log(o.red("Not logged in. Run `zibby login` first.")),process.exit(1)),e}async function S(){let e=y(),n=u();console.log(""),console.log(o.cyan(" Stored credentials in your Zibby workspace")),console.log(o.gray(` Source file: ${g}`)),console.log("");let t;try{t=await _({apiUrl:n,sessionToken:e})}catch(s){console.log(o.red(` Failed: ${s.message}`)),process.exit(1)}let{by_type:c}=t;for(let s of["oauth","api"]){let r=c[s]||[];if(console.log(o.bold(` ${s} pool (${r.length} ${r.length===1?"token":"tokens"}):`)),r.length===0)console.log(o.gray(" (none)"));else for(let l of r){let i=l.uploaded_at?new Date(l.uploaded_at).toISOString().slice(0,10):"?",d=l.uploaded_by||"?";console.log(` [${l.index}] ${o.cyan(l.masked)} ${o.gray(`uploaded ${i} by ${d} source: ${l.source||"unknown"}`)}`)}console.log("")}t.total===0&&(console.log(o.gray(" No credentials yet. Run `zibby init` to set them up \u2014 Claude has")),console.log(o.gray(" both OAuth subscription and API key options. Then re-run sync.")),console.log("")),console.log(o.gray(" Same file, same credentials, used by every zibby command:")),console.log(o.gray(" zibby test (test automation)")),console.log(o.gray(" zibby chat (interactive chat + cloud Claude Code sandbox)")),console.log(o.gray(" zibby workflow run (local execution)")),console.log(o.gray(" zibby workflow start (local dev server)")),console.log("")}async function D(){let e=y(),n=u();console.log(""),console.log(o.cyan(" Scanning your local credentials...")),console.log(o.gray(` ${g}`));let t=await x(),c=t.all.length;if(c===0){console.log(""),console.log(o.yellow(" No credentials found in ~/.zibby/config.json.")),console.log(""),console.log(o.white(" Run `zibby init` first to choose API key or OAuth subscription.")),console.log(o.gray(" Or export tokens in your shell \u2014 Zibby reads process.env too.")),console.log("");return}console.log(o.green(` \u2713 Found ${c} ${c===1?"credential":"credentials"}:`));for(let r of t.all)console.log(o.gray(` ${r.type} ***${r.token.slice(-4)} source: ${r.source_var} (${r.source})`));console.log(""),console.log(o.cyan(" Uploading to Zibby (KMS-encrypted)..."));let s=await w({apiUrl:n,sessionToken:e,credentials:t.all});if(console.log(""),console.log(o.green(` \u2713 ${s.added} new, ${s.deduped} already present`)),s.errors.length>0){console.log(o.red(` \u2717 ${s.errors.length} failed:`));for(let r of s.errors)console.log(o.red(` ${r.masked}: ${r.error}`))}console.log("")}async function F(e,n){let t=y(),c=u();(!e||!n)&&(console.log(o.red("Usage: zibby creds remove <type> <index>")),console.log(o.gray(" e.g. zibby creds remove oauth 0")),process.exit(1)),console.log(""),console.log(o.cyan(` Removing ${e} credential at index ${n}...`));try{await k({apiUrl:c,sessionToken:t,type:e,index:n})}catch(s){console.log(o.red(` Failed: ${s.message}`)),process.exit(1)}console.log(o.green(" \u2713 Removed.")),console.log(""),console.log(o.gray(" Note: this only deletes Zibby's encrypted copy. To revoke")),console.log(o.gray(" the actual token, do that on the upstream provider where")),console.log(o.gray(" it was issued.")),console.log("")}async function j(e,n,t={}){e!=="claude"&&e!=="openai"&&(console.log(o.red(`Unknown provider: ${e}`)),console.log(o.gray(" zibby creds set claude <token>")),console.log(o.gray(" zibby creds set openai sk-...")),process.exit(1)),(!n||typeof n!="string"||n.length<8)&&(console.log(o.red("Missing or too-short <token>.")),e==="claude"?(console.log(o.gray(" Mint one with: claude setup-token")),console.log(o.gray(" Or paste an API key: sk-ant-api03-..."))):console.log(o.gray(" Mint one at: https://platform.openai.com/api-keys")),process.exit(1));let c;e==="openai"?c="api":(c=t?.type||null,c||(/^sk-ant-oat/i.test(n)||/^oat_/i.test(n)?c="oauth":/^sk-ant-api/i.test(n)&&(c="api")),c||(console.log(o.red("Could not detect token kind from format.")),console.log(o.gray(" Re-run with --type oauth (long-lived `claude setup-token` token)")),console.log(o.gray(" or --type api (`sk-ant-api\u2026` raw API key)")),process.exit(1)));let s=y(),r=u(),l=e==="openai"?"OpenAI":"Claude";console.log(""),console.log(o.cyan(` Uploading ${l} ${c} token to your workspace (KMS-encrypted)...`));try{let i=await m({apiUrl:r,sessionToken:s,type:c,provider:e,token:n,source:"cli:zibby creds set"});i.deduped?console.log(o.green(" \u2713 Token already present \u2014 kept existing entry.")):console.log(o.green(` \u2713 Stored. Suffix: ${i.credential?.masked||"***"}`)),console.log(""),console.log(o.gray(" Deploys + new sandbox runs will use it on next start.")),console.log(o.gray(" Already-running apps: rotate with zibby app update-credential <id>")),console.log("")}catch(i){console.log(o.red(` Failed: ${i.message}`)),process.exit(1)}}async function co(e,...n){switch(e){case"list":return S();case"sync":return D();case"set":return j(n[0],n[1],n[2]);case"remove":return F(n[0],n[1]);default:console.log(o.red(`Unknown subcommand: ${e}`)),console.log(o.gray(" zibby creds list")),console.log(o.gray(" zibby creds sync")),console.log(o.gray(" zibby creds set claude <token>")),console.log(o.gray(" zibby creds set openai <token>")),console.log(o.gray(" zibby creds remove <type> <index>")),process.exit(1)}}export{co as credsCmd,S as listCmd,F as removeCmd,j as setCmd,D as syncCmd};
|
package/dist/package.json
CHANGED