@zibby/cli 0.5.1 → 0.5.3

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 h}from"commander";import{initCommand as k}from"../commands/init.js";import{runCommand as b}from"../commands/run.js";import{videoCommand as v}from"../commands/video.js";import{uploadCommand as C}from"../commands/upload.js";import{ciSetupCommand as I}from"../commands/ci-setup.js";import{setupPlaywrightMcpCommand as P,setupCiCommand as S,testWithVideoCommand as A}from"../commands/setup-scripts.js";import{readFileSync as x}from"fs";import{fileURLToPath as j}from"url";import{dirname as B,join as _}from"path";import{bootstrapAgentEnv as z}from"../utils/agent-credentials.js";const E=j(import.meta.url),D=B(E),u=JSON.parse(x(_(D,"../package.json"),"utf-8"));function s(e,o){return o.push(e),o}function f(e){if(e===void 0||e===!0||e==="")return 1;const o=parseInt(e,10);if(!Number.isFinite(o)||o<1||o>5)throw new Error(`--warm must be an integer 1-5 (got "${e}"). Omit the flag to disable warm pool.`);return o}const w=`zibby v${u.version}`,i=process.argv.slice(2),R=i.includes("-h")||i.includes("--help"),Z=i.includes("-v")||i.includes("-V")||i.includes("--version");Z&&(console.log(w),process.exit(0));const y=i[0],Y=i[1],O=["logs","uninstall"],L=y==="workflow"&&Y==="list";!O.includes(y)&&!L&&console.log(`${w}
3
- `),z(process.cwd());const M=i[0]==="chat",U=["--verbose","--agent","--stream","-s"],W=i.length>0&&i.every(e=>U.includes(e)||i[i.indexOf(e)-1]==="--agent"),J=i.length===0||M||W;if(J&&!R){const e={},o=i.indexOf("--agent");o!==-1&&i[o+1]&&(e.agent=i[o+1]),i.includes("--verbose")&&(e.verbose=!0),(i.includes("--stream")||i.includes("-s"))&&(e.stream=!0);const{chatCommand:t}=await import("../commands/chat.js");await t(e),process.exit(0)}const n=new h;n.name("zibby").description("Zibby \u2014 the cloud pipeline for Claude Code, Cursor, Codex, and Gemini. Compose them into structured workflows with schema-enforced handoff.").version(u.version,"-V, --version"),n.configureHelp({visibleCommands:()=>[]}),n.addHelpText("after",`
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("--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 a from"chalk";import h from"ora";import C from"inquirer";import ge from"dotenv";import{existsSync as ae,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 S from"ora";import{spawn as re}from"child_process";var $={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://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";$[o]?e=$[o].apiUrl:e=$.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)`),$.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),$.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 U}from"path";function O(){return process.env.ZIBBY_CONFIG_DIR||U(_(),".zibby")}function z(){return U(O(),"config.json")}var oe=U(_(),".zibby"),we=U(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 I(e){te(),ee(z(),JSON.stringify(e,null,2))}function B(){return m().sessionToken||null}function L(e){let o=m();o.sessionToken=e,I(o)}function D(){return m().user||null}function M(e){let o=m();o.user=e,I(o)}function F(e){let o=m();o.proxyUrl=e,I(o)}function Y(e){let o=m();o.mem0ProxyUrl=e,I(o)}function Z(e){let o=m();o.projects=e,I(o)}import{existsSync as $e,mkdirSync as xe,readFileSync as Ie,writeFileSync as Ue,unlinkSync as Ae}from"fs";import{resolve as Se}from"path";import{homedir as ke}from"os";function ne(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]),re(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 s=()=>{r.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},n=()=>{console.log(u.yellow(`
5
+
6
+ \u26A0\uFE0F Login cancelled
7
+ `)),s(),process.exit(0)};process.on("SIGINT",n),r.question(u.yellow("Continue with this session? (Y/n): "),async l=>{process.removeListener("SIGINT",n),s();try{if(l.toLowerCase()==="n"||l.toLowerCase()==="no"){console.log(u.gray(`Starting new login...
8
+ `));let c=await V();i(c)}else console.log(u.green(`Using existing session.
9
+ `)),i({success:!0,...e})}catch(c){t(c)}})})}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(s=>({name:s.name,projectId:s.projectId,apiToken:s.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=S("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 b=await r.json();throw new Error(b.error||"Failed to initiate login")}let{deviceCode:i,userCode:t,verificationUrl:s,expiresIn:n,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(n/60)} minutes`)),console.log(""),await ne(s)||(console.log(u.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(u.white("Please open this URL manually: ")+u.blue(s)),console.log(""));let p=S("Waiting for authorization...").start(),f=(l||3)*1e3,g=Math.floor(n/(l||3)),v=0,P=!1,R=()=>{P=!0,p.stop(),console.log(u.yellow(`
11
+
12
+ \u26A0\uFE0F Login cancelled
13
+ `)),process.exit(0)};process.on("SIGINT",R);try{for(;v<g&&!P;){await ce(f),v++;let b=await fetch(`${e}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:i})});if(b.status===202)continue;if(!b.ok){p.fail("Authorization failed");let T=await b.json();throw new Error(T.error||"Authorization failed")}let d=await b.json();if(d.status==="authorized"){p.succeed(u.white("Authorization successful!")),L(d.token),M(d.user),d.proxyUrl&&F(d.proxyUrl),d.mem0ProxyUrl&&Y(d.mem0ProxyUrl),console.log(""),console.log(u.gray(`User: ${d.user.email}`));let T=S("Fetching projects...").start(),E=await ie(d.token);return T.succeed(`Fetched ${E.length} project${E.length!==1?"s":""}`),console.log(u.gray(`Session saved to: ~/.zibby/config.json
14
+ `)),{success:!0,loggedIn:!0,user:d.user,token:d.token}}if(d.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",R)}}function ce(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 ae(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(a.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}`,s=await fetch(t,o),n=await s.text(),l=null;try{l=n?JSON.parse(n):null}catch{l={raw:n}}if(!s.ok){let c=l?.error||l?.message||`HTTP ${s.status}`;r||(l?.code==="CLAUDE_CREDENTIAL_REQUIRED"?(console.error(a.red("\xD7 Connect your Claude Code subscription first.")),console.error(""),console.error(a.white(" Run:")),console.error(a.cyan(" claude setup-token # mints a long-lived OAuth token")),console.error(a.cyan(" zibby creds set claude <token>")),console.error(""),console.error(a.gray(" Or paste an Anthropic API key:")),console.error(a.cyan(" zibby creds set claude sk-ant-api03-...")),console.error("")):l?.code==="OPENAI_CREDENTIAL_REQUIRED"?(console.error(a.red("\xD7 Connect your OpenAI API key to deploy with Codex.")),console.error(""),console.error(a.white(" Run:")),console.error(a.cyan(" zibby creds set openai sk-...")),console.error(""),console.error(a.gray(" Mint one at: https://platform.openai.com/api-keys")),console.error(a.gray(" Or paste at: https://zibby.dev/integrations")),console.error("")):(console.error(a.red(`\xD7 ${c}`)),l?.detail&&console.error(a.gray(` ${l.detail}`))));let p=new Error(c);throw p.status=s.status,p.body=l,p.code=l?.code||null,p}return l}function H(e){return" "+e.map(o=>"\u2500".repeat(o)).join(" ")}function A(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(n=>({appType:String(n.appType||""),version:`v${n.appVersion||n.app?.version||"?"}`,tier:String(n.pricing?.tier||"standard"),arch:Array.isArray(n.architectures)&&n.architectures.length?n.architectures.join(","):"x86_64",tagline:(n.tagline||"").slice(0,40)})),s=[Math.max(7,...t.map(n=>n.appType.length)),Math.max(7,...t.map(n=>n.version.length)),Math.max(4,...t.map(n=>n.tier.length)),Math.max(13,...t.map(n=>n.arch.length)),Math.max(7,...t.map(n=>n.tagline.length))];console.log(`
20
+ App Catalog (${i.length})
21
+ `),console.log(A(["AppType","Version","Tier","Architectures","Tagline"],s)),console.log(H(s));for(let n of t)console.log(A([n.appType,n.version,n.tier,n.arch,n.tagline],s));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 s=Array.isArray(t?.apps)?t.apps:[];if(e.quiet)return s;if(s.length===0)return console.log(`
22
+ No apps deployed.`),console.log(` Deploy one with: zibby app deploy <appType> --project <projectId>
23
+ `),[];let n=s.map(c=>({instance:(c.instanceId||"").slice(0,12),name:String(c.name||c.appType||"\u2014").slice(0,22),app:`${c.appType}${c.appVersion?` v${c.appVersion}`:""}`,arch:String(c.architecture||"\u2014"),status:String(c.status||"unknown"),project:String(c.projectId||"\u2014").slice(0,36)})),l=[Math.max(8,...n.map(c=>c.instance.length)),Math.max(4,...n.map(c=>c.name.length)),Math.max(3,...n.map(c=>c.app.length)),Math.max(4,...n.map(c=>c.arch.length)),Math.max(6,...n.map(c=>c.status.length)),Math.max(7,...n.map(c=>c.project.length))];console.log(`
24
+ Deployed Apps (${s.length})
25
+ `),console.log(A(["Instance","Name","App","Arch","Status","Project"],l)),console.log(H(l));for(let c of n)console.log(A([c.instance,c.name,c.app,c.arch,c.status,c.project],l));return console.log(""),s}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(a.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(s=>({name:`${s.name||"Unnamed"} (${s.projectId||s.id})`,value:s.projectId||s.id}))}]);return t}async function eo(e,o={}){let r=o.goal;e&&r&&(console.error(a.red("Pass either appType (catalog id) OR --goal (free-form description), not both.")),process.exit(1)),!e&&!r&&(console.error(a.red("Missing target.")),console.error(a.gray(" Pass appType to deploy from catalog (see `zibby app templates`)")),console.error(a.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 s=r?{goal:r,projectId:t}:{appType:e,projectId:t};o.name&&(s.name=o.name),o.provider&&(o.provider!=="claude"&&o.provider!=="codex"&&(console.error(a.red(`Unknown --provider: ${o.provider}`)),console.error(a.gray(" Pick claude (Anthropic) or codex (OpenAI).")),process.exit(1)),s.provider=o.provider),o.arch&&(o.arch!=="x86_64"&&o.arch!=="arm64"&&(console.error(a.red(`Unknown --arch: ${o.arch}`)),console.error(a.gray(" Pick x86_64 (Intel/AMD) or arm64 (Graviton, ~20% greener at the same price).")),process.exit(1)),s.architecture=o.arch);let n=[];o.provider&&n.push(o.provider),o.arch&&n.push(o.arch);let l=e||(r.length>60?`${r.slice(0,60).trim()}\u2026`:r),c=h(`Deploying ${l}${n.length?` (${n.join(", ")})`:""}\u2026`).start();try{let p=await y("/apps/deploy",{method:"POST",headers:i,body:JSON.stringify(s)});c.succeed(`Deployed ${l}`);let f=p?.instanceId,g=p?.url||(p?.subdomain?`https://${p.subdomain}`:null);return console.log(),f&&console.log(` instanceId: ${f}`),g&&console.log(` public URL: ${g}`),p?.architecture&&console.log(` architecture: ${p.architecture}`),f&&(console.log(),console.log(` Watch status: zibby app status ${f}`)),console.log(),p}catch(p){c.fail(`Deploy failed: ${p.message}`),process.exit(1)}}async function oo(e,o={}){e||(console.error(a.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 s=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 n=(t.resources.cpu/1024).toFixed(2),l=(t.resources.memory/1024).toFixed(2);console.log(` resources ${n} vCPU \xB7 ${l} GB RAM`)}return t.architecture&&console.log(` arch ${t.architecture}`),t.projectId&&console.log(` project ${t.projectId}`),s&&console.log(` public URL ${s}`),t.createdAt&&console.log(` created ${t.createdAt}`),console.log(),t}catch(t){i.fail(`Could not fetch ${e}`),t.status===404&&console.error(a.gray(" Instance not found \u2014 it may have been destroyed.")),process.exit(1)}}async function to(e,o={}){e||(console.error(a.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(a.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 ro(e,o={}){e||(console.error(a.red("Missing <instanceId>.")),process.exit(1));let r=await w(o);if(!o.yes){let{confirm:s}=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(!s){console.log(a.gray("Aborted."));return}}let i=o.version?`?version=${encodeURIComponent(o.version)}`:"",t=h(`Upgrading ${e}\u2026`).start();try{let s=await y(`/apps/${encodeURIComponent(e)}/upgrade${i}`,{method:"POST",headers:r});t.succeed(`Upgrade rolling out for ${e}`),console.log(),console.log(` taskDefinitionArn: ${s?.taskDefinitionArn||"\u2014"}`),s?.imageOverride&&console.log(` image: ${s.imageOverride}`),console.log(),console.log(a.gray(" ECS rolls the service: new task pulls image, then swaps over. EFS data preserved.")),console.log(a.gray(` Watch: zibby app status ${e}`)),console.log()}catch(s){t.fail(`Upgrade failed: ${s.message}`),process.exit(1)}}async function no(e,o={}){e||(console.error(a.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(a.gray(" ECS rolls the service: new task pulls the new env, swaps over once healthy.")),console.log(a.gray(` Watch: zibby app status ${e}`)),console.log()}catch(t){i.fail(`Credential update failed: ${t.message}`),process.exit(1)}}var W=3e3;function q(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),s=i.length>=19?i.slice(11,19):i;try{let n=JSON.parse(t),l=(n.level||"INFO").padEnd(4),c=n.msg||n.message||"",p=Object.entries(n).filter(([g])=>!["time","level","msg","message"].includes(g)).filter(([,g])=>g!==""&&g!==null&&g!==void 0).map(([g,v])=>`${g}=${typeof v=="string"?v:JSON.stringify(v)}`).join(" "),f=l.startsWith("ERR")||l.startsWith("FAIL")?a.red:l.startsWith("WARN")?a.yellow:a.gray;return`${a.dim(s)} ${f(l)} ${c}${p?" "+a.dim(p):""}`}catch{return`${a.dim(s)} ${t}`}}async function so(e,o={}){e||(console.error(a.red("Missing <instanceId>.")),process.exit(1));let r=await w(o),i=Math.min(Math.max(Number(o.lines)||200,1),5e3),t=async()=>await y(`/apps/${encodeURIComponent(e)}/logs?lines=${i}`,{method:"GET",headers:r});if(!o.follow){try{let l=await t(),c=Array.isArray(l?.lines)?l.lines:[];if(o.json)for(let p of c)console.log(p);else{c.length===0&&console.log(a.gray(" (no log events in window)"));for(let p of c)console.log(q(p,o))}}catch(l){console.error(a.red(`\xD7 ${l.message}`)),process.exit(1)}return}let s=new Set;console.log(a.gray(`Tailing logs for ${e} \u2014 Ctrl+C to stop
26
+ `));let n=!1;for(process.on("SIGINT",()=>{n=!0,console.log(a.gray(`
27
+ Stopped.`)),process.exit(0)});!n;){try{let l=await t(),c=Array.isArray(l?.lines)?l.lines:[];for(let p of c)s.has(p)||(s.add(p),console.log(o.json?p:q(p,o)));if(s.size>i*2){let p=Array.from(s).slice(-i);s.clear(),p.forEach(f=>s.add(f))}}catch(l){console.error(a.red(` \xD7 ${l.message} \u2014 retrying in ${W/1e3}s`))}await new Promise(l=>setTimeout(l,W))}}export{eo as appDeployCommand,to as appDestroyCommand,Xe as appListCommand,so as appLogsCommand,oo as appStatusCommand,Qe as appTemplatesCommand,no as appUpdateCredentialCommand,ro 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};
@@ -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(Ze&&!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(),Ze=!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(),Ze=!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(){Ze=!1,Ae=null}var Ze,Ae,dn,pn,ro=$e(()=>{Ze=!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 Ke}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 Ke(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=Ke(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})}
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&&($=!!process.stdin.isRaw,process.stdin.setRawMode(!0)),process.stdin.resume();try{process.stdin.setEncoding("utf8")}catch{}z=R=>{let B=R.toString("utf8");if(B.includes("")){W({reason:"detach"});return}try{a.send(B)}catch{}},process.stdin.on("data",z)}),a.on("message",A=>{let R=A.toString("utf8");if(R.startsWith("{")&&R.endsWith("}"))try{let B=JSON.parse(R);if(B&&B.type==="exit"){W({reason:"remote-exit",exitCode:B.exitCode,signal:B.signal});return}}catch{}try{process.stdout.write(R)}catch{}}),a.on("close",()=>{W({reason:"remote-close"})}),a.on("error",A=>{p||W({reason:"ws-error",message:A?.message||String(A)})}),setTimeout(()=>{if(a.readyState===Co.CONNECTING){try{a.terminate()}catch{}p||(p=!0,l(new Error("WS connect timed out after 30s")))}},3e4).unref()})}async function Zn({sandboxEndpoint:t,sessionToken:e,agentType:o,args:n,cwd:r,useTls:s}){let a=await Io({sandboxEndpoint:t,sessionToken:e,agentType:o,args:n,cwd:r,useTls:s});return{...await To({sandboxEndpoint:t,sessionId:a.session_id,sessionToken:e,useTls:s}),sessionId:a.session_id}}var wt=$e(()=>{});import{invokeAgent as Kn,getAgentStrategy as Wn}from"@zibby/core";import{getSkill as Re}from"@zibby/skills";import{existsSync as Ce,readFileSync as Ro,readdirSync as Jn}from"fs";import{resolve as me,join as St,dirname as Gn,basename as qn}from"path";import{createInterface as Vn,moveCursor as j,cursorTo as K,clearLine as Q,emitKeypressEvents as Xn}from"readline";import{fileURLToPath as Qn}from"url";import{homedir as es}from"os";import i from"chalk";import{highlight as Po}from"cli-highlight";import ts from"dotenv";import{existsSync as Lt,mkdirSync as qo,readFileSync as Vo,writeFileSync as Xo}from"fs";import{homedir as Rt}from"os";import{join as Fe}from"path";function Bt(){return process.env.ZIBBY_CONFIG_DIR||Fe(Rt(),".zibby")}function Dt(){return Fe(Bt(),"config.json")}var Qo=Fe(Rt(),".zibby"),Ms=Fe(Qo,"config.json");function en(){let t=Bt();Lt(t)||qo(t,{recursive:!0})}function se(){try{let t=Dt();if(Lt(t)){let e=Vo(t,"utf-8");return JSON.parse(e)}}catch{}return{}}function Pe(t){en(),Xo(Dt(),JSON.stringify(t,null,2))}function Ye(){return se().sessionToken||null}function Mt(t){let e=se();e.sessionToken=t,Pe(e)}function jt(){return se().user||null}function zt(t){let e=se();e.user=t,Pe(e)}function Ft(){let t=se();delete t.sessionToken,delete t.user,delete t.mem0ProxyUrl,Pe(t)}function Yt(){return se().proxyUrl||null}function Ht(t){let e=se();e.proxyUrl=t,Pe(e)}function Zt(){return se().mem0ProxyUrl||null}function Kt(t){let e=se();e.mem0ProxyUrl=t,Pe(e)}function Wt(){return se().projects||[]}var Ee={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function le(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";Ee[e]?t=Ee[e].apiUrl:t=Ee.prod.apiUrl}try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),Ee.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),Ee.prod.apiUrl}}import{existsSync as at,mkdirSync as tn,readFileSync as Jt,writeFileSync as Gt,unlinkSync as Ys}from"fs";import{resolve as Oe}from"path";import{homedir as Ks}from"os";var on=30;function qt(t){let e=Oe(t,".zibby","output");return at(e)||tn(e,{recursive:!0}),e}function Vt(t){let e=Oe(t,".zibby","output","chat-history.json");if(!at(e))return[];try{let o=JSON.parse(Jt(e,"utf-8"));return Array.isArray(o)?o:[]}catch{return[]}}function Ne(t,e){let o=qt(t),n=Oe(o,"chat-history.json");try{Gt(n,JSON.stringify((e||[]).slice(-on*2),null,2),"utf-8")}catch{}}function Xt(t){let e=Oe(t,".zibby","output","active-skills.json");if(!at(e))return null;try{let o=JSON.parse(Jt(e,"utf-8"));return Array.isArray(o)?o:null}catch{return null}}function Ue(t,e){let o=qt(t),n=Oe(o,"active-skills.json");try{Gt(n,JSON.stringify(Array.isArray(e)?e:[]),"utf-8")}catch{}}var ct={cli_reliable_v1:{title:"General intelligence reliability contract",operatingRules:["Evidence-first reasoning: ground conclusions in observed outputs or tool evidence, not guesses.","No false completion: never claim success for a state-changing action until verification confirms it.","Execution integrity: do not claim any external action unless the matching tool call actually happened.","Bounded recovery: for transient failures, retry with adjusted parameters up to 2 times, then escalate with blocker + next step.",'Binary-answer discipline: for yes/no questions, verify the exact asked condition before answering; do not answer "yes" from a broader or approximate match.'],executionSafety:["Prefer low-blast-radius, reversible actions first.","Before irreversible or high-impact actions, confirm explicit user intent unless already authorized.","If verification cannot be run, state that limitation explicitly."],investigationLoop:["For unclear failures, follow this loop: detect -> gather evidence -> form hypothesis -> test hypothesis -> conclude.","If evidence is insufficient, explicitly collect more before proposing a root cause.","Prefer smallest validating action first before broad or costly retries."],responseQuality:["State assumptions explicitly when certainty is low.","Differentiate facts, hypotheses, and next actions.","Keep reports concise but decision-useful.","If related-but-not-identical matches exist, report them separately as context, not as the direct yes/no answer."],incidentTemplate:["ONLY when diagnosing failures or errors (never for successful actions), structure your response as: Root cause, Evidence, Attempted fixes, Current status, Next action."],skillRunbooks:{}}},eo=2e3,Qt=12e3;function He(t=[]){if(!Array.isArray(t))return[];let e=new Set,o=[];for(let n of t){let r=String(n||"").replace(/\s+/g," ").trim();r&&(e.has(r)||(e.add(r),o.push(r)))}return o}function nn(t,e=eo){let o=String(t||"");return o.length<=e?o:`${o.slice(0,Math.max(0,e-14)).trimEnd()}
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${" ".repeat(80)}\r${l}`),t++},300),n=()=>{clearInterval(o),process.stdout.write(`\r${" ".repeat(80)}\r`)};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(`
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($=>Ce(St(l,$)));if(!p)return o;try{let $=Ro(St(l,p),"utf-8").trim();return s?`${$}
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}`:$}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))}
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",$=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)),_=" ".repeat(Math.max(0,l-ye.length)),k=` \u2502 ${ue}${be} \u2502 ${ye}${_} \u2502`;console.log(i.gray(k))}console.log(i.gray(L)),console.log("")}function Ss(){process.stdout?.isTTY&&(j(process.stdout,0,-2),K(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(_){!e||!o||!n||!r||(process.stdout.write("\x1B7"),j(process.stdout,0,-2),K(process.stdout,0),Q(process.stdout,0),process.stdout.write(` ${_}`),process.stdout.write("\x1B8"))}function Y(){if(!(!e||!o)&&c!==0){process.stdout.write("\x1B7"),j(process.stdout,0,2);for(let _=0;_<c;_++)K(process.stdout,0),Q(process.stdout,0),_<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),K(process.stdout,0),Q(process.stdout,0),process.stdout.write(p()),process.stdout.write("\x1B8"))}function A(_,k){if(!e||!o||!n)return;Y();let I=_.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++){K(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 _=process.stdout.columns||80,k=l>0?Math.ceil(l/_):1;K(process.stdout,0),j(process.stdout,0,-k),r&&j(process.stdout,0,-2),process.stdout.write("\x1B[J"),n=!1}function B(_={}){let k=_.preserveInput===!0;if(!e){t.prompt();return}k||(t.line="",t.cursor=0),l=_t().length;let I=p();process.stdout.write(`${I}
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 _=process.stdout.columns||80,k=l>0?Math.ceil(l/_):1,I=p();process.stdout.write("\x1B7"),j(process.stdout,0,-k);for(let b=0;b<k;b++)K(process.stdout,0),Q(process.stdout,0),b<k-1&&j(process.stdout,0,1);K(process.stdout,0),process.stdout.write(I),j(process.stdout,0,2),K(process.stdout,0),Q(process.stdout,0),process.stdout.write(I);for(let b=1;b<k;b++)j(process.stdout,0,1),K(process.stdout,0),Q(process.stdout,0);process.stdout.write("\x1B8"),l=_t().length}function L(){if(!e||!o||!n)return;let _=(()=>{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,-(_+1)),K(process.stdout,0),Q(process.stdout,0),process.stdout.write(p()),j(process.stdout,0,_+2),K(process.stdout,0),Q(process.stdout,0),process.stdout.write(p()),process.stdout.write("\x1B8")}function H(_){$(),R(),console.log();let k=String(_??"").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(_){let k=String(_??"").replace(/\r/g,"").split(`
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(){$();let _=()=>i.gray(`${Ge[a%Ge.length]} thinking`);if(!e){console.log(` ${_()}`),r=!0;return}Y(),R(),console.log(),console.log(` ${_()}`),B({preserveInput:!0}),r=!0,a+=1,s=setInterval(()=>{r&&(z(_()),a+=1)},120)}function be(_){$();let k=String(_??"").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(_={}){if(e&&o){n&&R(),B(_);return}t.prompt()},pushSystem(_){H(_)},pushUser(_){H(ue(_))},pushAssistant(_){be(_)},showAssistantLoading:ye,dismissTransientLoading(){$(),r&&e&&o&&n&&(process.stdout.write("\x1B7"),j(process.stdout,0,-2),K(process.stdout,0),Q(process.stdout,0),j(process.stdout,0,-1),K(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:Z,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(`
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(Z/(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&&Kt(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=Zt()||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(`
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,Z]of Object.entries(ye)){let re=C[d]?.connected,J=L.indexOf(Z),Ve=Re(Z);re&&J===-1&&Ve?L.push(Z):!re&&J!==-1&&L.splice(J,1)}Ue(e,L)}}}catch{}let be=L.filter(b=>b!=="skill-installer"&&b!=="core-tools"),_=be.length>0?`Skills: ${be.join(", ")}`:"Skills: (none)";_s({userName:z?.name?.split(" ")[0],cwd:e,projectName:W,restoredCount:A.length,skillsLine:_});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=S=>{let g=String(S||"");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),Z=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=(...S)=>{if(!(ie||Date.now()<ae))return q(...S)});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(S){let g="\x1B[200~",v="\x1B[201~";if(!ie&&!S.includes(g))return!1;let P=S,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,`
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 $?.cleanup=="function"&&await $.cleanup().catch(()=>{});try{let{killAllChatOrchestratedRuns:S}=await Promise.resolve().then(()=>(ft(),pt)),{postCliInterruptedRunIndex:g}=await import("@zibby/workflow-templates/run-index-post-cli.js");S(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 S;process.stdout.on("resize",()=>{clearTimeout(S),S=setTimeout(()=>{d.handleResize()},80)})}let Qe=0,De=S=>{if(typeof S=="string"?S==="\x1B":S&&typeof S.length=="number"?S.length===1&&S[0]===27:!1){Z&&Z.abort(),At();return}let v=typeof S=="string"?S:S&&typeof S.length=="number"?Buffer.from(S).toString("utf8"):"";if(!v)return;if(zo(v)){Qe=Date.now()+1200,ae=Date.now()+1200,ot();return}let P=(v.includes(`
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(S=>S.cmd));function Se(S,{preserveFrame:g=!1}={}){let v=String(S||"");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 S=O.lines.length,g=`[Pasted text #${Ct} +${S} 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(S){return O.active?(O.lines.push(String(S||"")),Se(O.prefix,{preserveFrame:!0}),ot(),!0):!1}function Yo(S){let g=String(S||"");for(let v of et)g=g.split(v.placeholder).join(v.text);return g}function xe(S){let g=String(S||"");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=(S,g)=>{if(g?.name==="escape"||g?.sequence==="\x1B"){Z&&Z.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 S=>{try{let g=String(S||""),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),K(process.stdout,4));return}if(re&&N!=="/exit"&&N!=="/quit"){Z&&Z.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:x,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(`
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 x({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(`
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 x({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||{},x=L.filter(y=>y!=="skill-installer");console.log(i.cyan(`
54
- Active skills:`)),x.length===0&&console.log(i.gray(" (none)"));for(let y of x){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(`
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"),x=m.indexOf("-n"),E=x>=0&&m[x+1]?parseInt(m[x+1],10):NaN,y=T?A.length:isNaN(E)?10:E,w=A.slice(-y);console.log(i.gray(`
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),x=T[0]||"brief",E={options:{workspace:e}};try{if(x==="facts"||x==="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(`
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(x==="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(`
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(x==="sessions"){let y=await m.handleToolCall("memory_brief",{},E),w=JSON.parse(y);if(console.log(i.cyan(`
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(x==="search"){let y=T.slice(1).join(" ");if(!y)console.log(i.yellow(`
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),K(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+=`
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(),x;H.data&&T-H.timestamp<ue?(x=H.data,process.env.ZIBBY_VERBOSE==="true"&&d.pushSystem(i.gray("Using cached memory context"))):(x=await m.buildPromptContext({options:{workspace:e}},{}),H={data:x,timestamp:T},process.env.ZIBBY_VERBOSE==="true"&&d.pushSystem(i.gray("Refreshed memory context cache")));let E=String(x?.backend||"dolt");process.env.ZIBBY_VERBOSE==="true"&&(d.pushSystem(i.gray(`memory backend: ${E}`)),d.pushSystem(i.gray(`memory retrieval output: ${qe(JSON.stringify(x?.debugPreview||{}),1400)}`)),x?.error&&d.pushSystem(i.yellow(`memory backend warning: ${x.error}`))),x?.promptContext&&(ne+=`
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
- ${x.promptContext}`)}}catch(m){process.env.ZIBBY_VERBOSE==="true"&&d.pushSystem(i.yellow(`memory backend warning: ${String(m?.message||m)}`))}ne=Be(ne,Do);let Zo=fs(A),rt=gs([{role:"system",content:ne},...Zo,{role:"user",content:je}]),Nt=xt(rt),Ko=Buffer.byteLength(JSON.stringify(rt),"utf8");process.env.ZIBBY_VERBOSE==="true"&&d.pushSystem(i.gray(`payload estimate: ${Nt} chars, ${Ko} 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 x=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<=x?E=f:E=`${m}(${w.slice(0,x-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;Z=it;try{let m=await Kn("",{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),x=Ie&&Ie.trim().length>0?Ie.trim():T.trim(),E=ys(x,ze)?x:bs(x);d.pushAssistant(E);let y=ze.length>0?`[tools used: ${ze.join(", ")}]
109
- ${x}`:x;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 x=Ie.trim();x?A.push({role:"ai",content:x+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{Z=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(Z){Z.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};
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 c(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 f({apiUrl:e,sessionToken:r}){if(!r)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let t=await fetch(c(e),{headers:{Authorization:`Bearer ${r}`}});if(t.status===401)throw u();if(t.status===404)return{credentials:[],by_type:{oauth:[],api:[]},total:0};if(!t.ok){let a=new Error(`List credentials failed (${t.status})`);throw a.status=t.status,a}return t.json()}async function l({apiUrl:e,sessionToken:r,type:t,token:a,source:n="~/.zibby/config.json"}){if(!r)throw new Error("No session token \u2014 run zibby login first");let o=await fetch(c(e),{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify({type:t,token:a,source:n})});if(o.status===401)throw u();if(!o.ok){let s=`Add credential failed (${o.status})`;try{let d=await o.json();d?.error&&(s=`${s}: ${d.error}`)}catch{}let i=new Error(s);throw i.status=o.status,i}return o.json()}async function h({apiUrl:e,sessionToken:r,type:t,index:a}){if(!r)throw new Error("No session token \u2014 run zibby login first");let n=await fetch(c(e,`/${encodeURIComponent(t)}/${encodeURIComponent(a)}`),{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(n.status===401)throw u();if(!n.ok){let o=new Error(`Delete credential failed (${n.status})`);throw o.status=n.status,o}return n.json()}async function y({apiUrl:e,sessionToken:r,credentials:t}){let a=0,n=0,o=[];for(let s of t)try{let i=await l({apiUrl:e,sessionToken:r,type:s.type,token:s.token,source:s.source_var||s.source||"local"});i.deduped?n+=1:i.added&&(a+=1)}catch(i){o.push({masked:s.token?`***${s.token.slice(-4)}`:"***",error:i.message})}return{added:a,deduped:n,errors:o}}export{l as addCredential,h as deleteCredential,f as listCredentials,y as syncFromLocal};
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};
@@ -1 +1 @@
1
- import t from"chalk";function y(o,e=""){return`${String(o).replace(/\/+$/,"")}/agents/credentials${e}`}function h(){let o=new Error("Session expired \u2014 run zibby login");return o.code="AUTH_EXPIRED",o}async function m({apiUrl:o,sessionToken:e}){if(!e)return{credentials:[],by_type:{oauth:[],api:[]},total:0};let r=await fetch(y(o),{headers:{Authorization:`Bearer ${e}`}});if(r.status===401)throw h();if(r.status===404)return{credentials:[],by_type:{oauth:[],api:[]},total:0};if(!r.ok){let c=new Error(`List credentials failed (${r.status})`);throw c.status=r.status,c}return r.json()}async function $({apiUrl:o,sessionToken:e,type:r,token:c,source:s="~/.zibby/config.json"}){if(!e)throw new Error("No session token \u2014 run zibby login first");let n=await fetch(y(o),{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({type:r,token:c,source:s})});if(n.status===401)throw h();if(!n.ok){let i=`Add credential failed (${n.status})`;try{let d=await n.json();d?.error&&(i=`${i}: ${d.error}`)}catch{}let l=new Error(i);throw l.status=n.status,l}return n.json()}async function _({apiUrl:o,sessionToken:e,type:r,index:c}){if(!e)throw new Error("No session token \u2014 run zibby login first");let s=await fetch(y(o,`/${encodeURIComponent(r)}/${encodeURIComponent(c)}`),{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(s.status===401)throw h();if(!s.ok){let n=new Error(`Delete credential failed (${s.status})`);throw n.status=s.status,n}return s.json()}async function U({apiUrl:o,sessionToken:e,credentials:r}){let c=0,s=0,n=[];for(let i of r)try{let l=await $({apiUrl:o,sessionToken:e,type:i.type,token:i.token,source:i.source_var||i.source||"local"});l.deduped?s+=1:l.added&&(c+=1)}catch(l){n.push({masked:i.token?`***${i.token.slice(-4)}`:"***",error:l.message})}return{added:c,deduped:s,errors:n}}import O from"node:fs/promises";import C from"node:path";import A from"node:os";var p=C.join(A.homedir(),".zibby","config.json"),v={CLAUDE_CODE_OAUTH_TOKEN:"oauth",CLAUDE_CODE_OAUTH_TOKEN_POOL:"oauth",ANTHROPIC_AUTH_TOKEN:"oauth",ANTHROPIC_API_KEY:"api",ANTHROPIC_API_KEY_POOL:"api"};function k(o){if(!o)return[];let e;try{e=JSON.parse(o)}catch{return[]}let r=e?.agentKeys;if(!r||typeof r!="object")return[];let c=[],s=new Set;for(let[n,i]of Object.entries(v)){let l=r[n];if(!l||typeof l!="string")continue;let d=n.endsWith("_POOL")?l.split(",").map(a=>a.trim()).filter(Boolean):[l.trim()];for(let a of d)a.length<8||s.has(a)||(s.add(a),c.push({type:i,token:a,source_var:n}))}return c}async function N(o=p){let e;try{e=await O.readFile(o,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}return k(e)}async function w({filepath:o,env:e=process.env}={}){let r=await N(o),c=new Set(r.map(n=>n.token)),s=[];for(let[n,i]of Object.entries(v)){let l=e[n];if(!l)continue;let d=n.endsWith("_POOL")?l.split(",").map(a=>a.trim()).filter(Boolean):[l];for(let a of d)a.length<8||c.has(a)||(c.add(a),s.push({type:i,token:a,source_var:n,source:"process.env"}))}return{config:r.map(n=>({...n,source:"config.json"})),env:s,all:[...r.map(n=>({...n,source:"config.json"})),...s]}}var u={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function f(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";u[e]?o=u[e].apiUrl:o=u.prod.apiUrl}try{let e=new URL(o);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),u.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),u.prod.apiUrl}}import{existsSync as E,mkdirSync as G,readFileSync as P,writeFileSync as J}from"fs";import{homedir as x}from"os";import{join as g}from"path";function R(){return process.env.ZIBBY_CONFIG_DIR||g(x(),".zibby")}function T(){return g(R(),"config.json")}var B=g(x(),".zibby"),X=g(B,"config.json");function z(){try{let o=T();if(E(o)){let e=P(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function I(){return z().sessionToken||null}function b(){let o=I();return o||(console.log(t.red("Not logged in. Run `zibby login` first.")),process.exit(1)),o}async function L(){let o=b(),e=f();console.log(""),console.log(t.cyan(" Stored credentials in your Zibby workspace")),console.log(t.gray(` Source file: ${p}`)),console.log("");let r;try{r=await m({apiUrl:e,sessionToken:o})}catch(s){console.log(t.red(` Failed: ${s.message}`)),process.exit(1)}let{by_type:c}=r;for(let s of["oauth","api"]){let n=c[s]||[];if(console.log(t.bold(` ${s} pool (${n.length} ${n.length===1?"token":"tokens"}):`)),n.length===0)console.log(t.gray(" (none)"));else for(let i of n){let l=i.uploaded_at?new Date(i.uploaded_at).toISOString().slice(0,10):"?",d=i.uploaded_by||"?";console.log(` [${i.index}] ${t.cyan(i.masked)} ${t.gray(`uploaded ${l} by ${d} source: ${i.source||"unknown"}`)}`)}console.log("")}r.total===0&&(console.log(t.gray(" No credentials yet. Run `zibby init` to set them up \u2014 Claude has")),console.log(t.gray(" both OAuth subscription and API key options. Then re-run sync.")),console.log("")),console.log(t.gray(" Same file, same credentials, used by every zibby command:")),console.log(t.gray(" zibby test (test automation)")),console.log(t.gray(" zibby chat (interactive chat + cloud Claude Code sandbox)")),console.log(t.gray(" zibby workflow run (local execution)")),console.log(t.gray(" zibby workflow start (local dev server)")),console.log("")}async function S(){let o=b(),e=f();console.log(""),console.log(t.cyan(" Scanning your local credentials...")),console.log(t.gray(` ${p}`));let r=await w(),c=r.all.length;if(c===0){console.log(""),console.log(t.yellow(" No credentials found in ~/.zibby/config.json.")),console.log(""),console.log(t.white(" Run `zibby init` first to choose API key or OAuth subscription.")),console.log(t.gray(" Or export tokens in your shell \u2014 Zibby reads process.env too.")),console.log("");return}console.log(t.green(` \u2713 Found ${c} ${c===1?"credential":"credentials"}:`));for(let n of r.all)console.log(t.gray(` ${n.type} ***${n.token.slice(-4)} source: ${n.source_var} (${n.source})`));console.log(""),console.log(t.cyan(" Uploading to Zibby (KMS-encrypted)..."));let s=await U({apiUrl:e,sessionToken:o,credentials:r.all});if(console.log(""),console.log(t.green(` \u2713 ${s.added} new, ${s.deduped} already present`)),s.errors.length>0){console.log(t.red(` \u2717 ${s.errors.length} failed:`));for(let n of s.errors)console.log(t.red(` ${n.masked}: ${n.error}`))}console.log("")}async function D(o,e){let r=b(),c=f();(!o||!e)&&(console.log(t.red("Usage: zibby creds remove <type> <index>")),console.log(t.gray(" e.g. zibby creds remove oauth 0")),process.exit(1)),console.log(""),console.log(t.cyan(` Removing ${o} credential at index ${e}...`));try{await _({apiUrl:c,sessionToken:r,type:o,index:e})}catch(s){console.log(t.red(` Failed: ${s.message}`)),process.exit(1)}console.log(t.green(" \u2713 Removed.")),console.log(""),console.log(t.gray(" Note: this only deletes Zibby's encrypted copy. To revoke")),console.log(t.gray(" the actual token, do that on the upstream provider where")),console.log(t.gray(" it was issued.")),console.log("")}async function ro(o,...e){switch(o){case"list":return L();case"sync":return S();case"remove":return D(e[0],e[1]);default:console.log(t.red(`Unknown subcommand: ${o}`)),console.log(t.gray(" zibby creds list")),console.log(t.gray(" zibby creds sync")),console.log(t.gray(" zibby creds remove <type> <index>")),process.exit(1)}}export{ro as credsCmd,L as listCmd,D as removeCmd,S as syncCmd};
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};
@@ -1,19 +1,28 @@
1
1
  #!/usr/bin/env node
2
- var _t=Object.defineProperty;var Ee=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var m=(e,t)=>()=>(e&&(t=e(e=0)),t);var $e=(e,t)=>{for(var r in t)_t(e,r,{get:t[r],enumerable:!0})};var ve,be=m(()=>{ve="ffffffff-ffff-ffff-ffff-ffffffffffff"});var De,ke=m(()=>{De="00000000-0000-0000-0000-000000000000"});var Le,Ce=m(()=>{Le=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});function bt(e){return typeof e=="string"&&Le.test(e)}var L,F=m(()=>{Ce();L=bt});function Dt(e){if(!L(e))throw TypeError("Invalid UUID");let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var v,G=m(()=>{F();v=Dt});function _(e,t=0){return(y[e[t+0]]+y[e[t+1]]+y[e[t+2]]+y[e[t+3]]+"-"+y[e[t+4]]+y[e[t+5]]+"-"+y[e[t+6]]+y[e[t+7]]+"-"+y[e[t+8]]+y[e[t+9]]+"-"+y[e[t+10]]+y[e[t+11]]+y[e[t+12]]+y[e[t+13]]+y[e[t+14]]+y[e[t+15]]).toLowerCase()}function kt(e,t=0){let r=_(e,t);if(!L(r))throw TypeError("Stringified UUID is invalid");return r}var y,Ne,b=m(()=>{F();y=[];for(let e=0;e<256;++e)y.push((e+256).toString(16).slice(1));Ne=kt});import{randomFillSync as Lt}from"crypto";function D(){return Y>q.length-16&&(Lt(q),Y=0),q.slice(Y,Y+=16)}var q,Y,V=m(()=>{q=new Uint8Array(256),Y=q.length});function Ct(e,t,r){let n,o=e?._v6??!1;if(e){let s=Object.keys(e);s.length===1&&s[0]==="_v6"&&(e=void 0)}if(e)n=je(e.random??e.rng?.()??D(),e.msecs,e.nsecs,e.clockseq,e.node,t,r);else{let s=Date.now(),i=D();Nt(z,s,i),n=je(i,z.msecs,z.nsecs,o?void 0:z.clockseq,o?void 0:z.node,t,r)}return t??_(n)}function Nt(e,t,r){return e.msecs??=-1/0,e.nsecs??=0,t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t<e.msecs&&(e.node=void 0),e.node||(e.node=r.slice(10,16),e.node[0]|=1,e.clockseq=(r[8]<<8|r[9])&16383),e.msecs=t,e}function je(e,t,r,n,o,s,i=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(!s)s=new Uint8Array(16),i=0;else if(i<0||i+16>s.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);t??=Date.now(),r??=0,n??=(e[8]<<8|e[9])&16383,o??=e.slice(10,16),t+=122192928e5;let f=((t&268435455)*1e4+r)%4294967296;s[i++]=f>>>24&255,s[i++]=f>>>16&255,s[i++]=f>>>8&255,s[i++]=f&255;let a=t/4294967296*1e4&268435455;s[i++]=a>>>8&255,s[i++]=a&255,s[i++]=a>>>24&15|16,s[i++]=a>>>16&255,s[i++]=n>>>8|128,s[i++]=n&255;for(let c=0;c<6;++c)s[i++]=o[c];return s}var z,Z,ce=m(()=>{V();b();z={};Z=Ct});function B(e){let t=typeof e=="string"?v(e):e,r=jt(t);return typeof e=="string"?_(r):r}function jt(e){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}var le=m(()=>{G();b()});import{createHash as Kt}from"crypto";function Ft(e){return Array.isArray(e)?e=Buffer.from(e):typeof e=="string"&&(e=Buffer.from(e,"utf8")),Kt("md5").update(e).digest()}var Ke,Fe=m(()=>{Ke=Ft});function Gt(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}function W(e,t,r,n,o,s){let i=typeof r=="string"?Gt(r):r,f=typeof n=="string"?v(n):n;if(typeof n=="string"&&(n=v(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+i.length);if(a.set(f),a.set(i,f.length),a=t(a),a[6]=a[6]&15|e,a[8]=a[8]&63|128,o){if(s=s||0,s<0||s+16>o.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let c=0;c<16;++c)o[s+c]=a[c];return o}return _(a)}var X,ee,fe=m(()=>{G();b();X="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ee="6ba7b811-9dad-11d1-80b4-00c04fd430c8"});function pe(e,t,r,n){return W(48,Ke,e,t,r,n)}var Ge,ze=m(()=>{Fe();fe();pe.DNS=X;pe.URL=ee;Ge=pe});import{randomUUID as zt}from"crypto";var de,Be=m(()=>{de={randomUUID:zt}});function Bt(e,t,r){if(de.randomUUID&&!t&&!e)return de.randomUUID();e=e||{};let n=e.random??e.rng?.()??D();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let o=0;o<16;++o)t[r+o]=n[o];return t}return _(n)}var We,He=m(()=>{Be();V();b();We=Bt});import{createHash as Wt}from"crypto";function Ht(e){return Array.isArray(e)?e=Buffer.from(e):typeof e=="string"&&(e=Buffer.from(e,"utf8")),Wt("sha1").update(e).digest()}var Je,Me=m(()=>{Je=Ht});function ue(e,t,r,n){return W(80,Je,e,t,r,n)}var Qe,Ye=m(()=>{Me();fe();ue.DNS=X;ue.URL=ee;Qe=ue});function Jt(e,t,r){e??={},r??=0;let n=Z({...e,_v6:!0},new Uint8Array(16));if(n=B(n),t){if(r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let o=0;o<16;o++)t[r+o]=n[o];return t}return _(n)}var qe,Ve=m(()=>{b();ce();le();qe=Jt});function ge(e){let t=typeof e=="string"?v(e):e,r=Mt(t);return typeof e=="string"?_(r):r}function Mt(e){return Uint8Array.of((e[3]&15)<<4|e[4]>>4&15,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|e[6]&15,e[7],(e[1]&15)<<4|(e[2]&240)>>4,(e[2]&15)<<4|(e[3]&240)>>4,16|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}var Ze=m(()=>{G();b()});function Qt(e,t,r){let n;if(e)n=Xe(e.random??e.rng?.()??D(),e.msecs,e.seq,t,r);else{let o=Date.now(),s=D();Yt(me,o,s),n=Xe(s,me.msecs,me.seq,t,r)}return t??_(n)}function Yt(e,t,r){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}function Xe(e,t,r,n,o=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),o=0;else if(o<0||o+16>n.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);return t??=Date.now(),r??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],n[o++]=t/1099511627776&255,n[o++]=t/4294967296&255,n[o++]=t/16777216&255,n[o++]=t/65536&255,n[o++]=t/256&255,n[o++]=t&255,n[o++]=112|r>>>28&15,n[o++]=r>>>20&255,n[o++]=128|r>>>14&63,n[o++]=r>>>6&255,n[o++]=r<<2&255|e[10]&3,n[o++]=e[11],n[o++]=e[12],n[o++]=e[13],n[o++]=e[14],n[o++]=e[15],n}var me,et,tt=m(()=>{V();b();me={};et=Qt});function qt(e){if(!L(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)}var rt,ot=m(()=>{F();rt=qt});var nt={};$e(nt,{MAX:()=>ve,NIL:()=>De,parse:()=>v,stringify:()=>Ne,v1:()=>Z,v1ToV6:()=>B,v3:()=>Ge,v4:()=>We,v5:()=>Qe,v6:()=>qe,v6ToV1:()=>ge,v7:()=>et,validate:()=>L,version:()=>rt});var it=m(()=>{be();ke();G();b();ce();le();ze();He();Ye();Ve();Ze();tt();F();ot()});var ft={};$e(ft,{uploadSessionArtifacts:()=>ar});import{readdirSync as at,statSync as he,createReadStream as Vt,existsSync as Zt}from"node:fs";import{join as ct,relative as Xt,sep as er,extname as tr}from"node:path";function ir(e){let t=tr(e).toLowerCase();return nr[t]||"application/octet-stream"}function lt(e){let t=[],r;try{r=at(e)}catch{return t}for(let n of r){if(rr.has(n)||n.startsWith(".")||or.has(n))continue;let o=ct(e,n),s;try{s=he(o)}catch{continue}s.isDirectory()?t.push(...lt(o)):s.isFile()&&t.push(o)}return t}async function sr({apiUrl:e,apiKey:t,executionId:r,nodeName:n,filename:o,absolutePath:s,sizeBytes:i,contentType:f}){let a;try{let c=await fetch(`${e}/${r}/artifacts/upload-url`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({nodeName:n,filename:o,contentType:f,sizeBytes:i})});if(!c.ok){let l=await c.text();return console.warn(`[artifacts] upload-url failed for ${n}/${o}: ${c.status} ${l.slice(0,200)}`),null}a=await c.json()}catch(c){return console.warn(`[artifacts] upload-url request errored for ${n}/${o}: ${c.message}`),null}try{let c=Vt(s),l=a.requiredHeaders?{...a.requiredHeaders,"Content-Length":String(i)}:{"Content-Type":f,"Content-Length":String(i)},u=await fetch(a.url,{method:"PUT",headers:l,body:c,duplex:"half"});if(!u.ok)return console.warn(`[artifacts] S3 PUT failed for ${n}/${o}: ${u.status}`),null}catch(c){return console.warn(`[artifacts] S3 PUT errored for ${n}/${o}: ${c.message}`),null}return{nodeName:n,filename:o,s3Key:a.s3Key,contentType:f,sizeBytes:i}}async function ar({sessionPath:e,executionId:t,apiUrl:r,apiKey:n}){let o={uploaded:[],skipped:[]};if(!e||!Zt(e))return o;if(!r||!n||!t)return console.warn("[artifacts] uploader missing required input \u2014 skipping"),o;let s;try{s=at(e)}catch(l){return console.warn(`[artifacts] could not read session folder ${e}: ${l.message}`),o}let i=[];for(let l of s){let u=ct(e,l),d;try{d=he(u)}catch{continue}if(!d.isDirectory()||l.startsWith(".")||l.startsWith("_"))continue;let k=lt(u);for(let x of k){let T=Xt(u,x).split(er).join("/"),U;try{U=he(x).size}catch{continue}if(U>st){o.skipped.push({nodeName:l,filename:T,reason:`size ${U} > ${st}`});continue}if(U===0){o.skipped.push({nodeName:l,filename:T,reason:"empty"});continue}i.push({apiUrl:r,apiKey:n,executionId:t,nodeName:l,filename:T,absolutePath:x,sizeBytes:U,contentType:ir(T)})}}if(i.length===0)return o;let f=4,a=i.slice(),c=Array.from({length:Math.min(f,a.length)},async()=>{for(;a.length;){let l=a.shift(),u=await sr(l);u?o.uploaded.push(u):o.skipped.push({nodeName:l.nodeName,filename:l.filename,reason:"upload failed"})}});if(await Promise.all(c),o.uploaded.length>0)try{let l=await fetch(`${r}/${t}/artifacts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({files:o.uploaded})});if(!l.ok){let u=await l.text();console.warn(`[artifacts] record failed: ${l.status} ${u.slice(0,200)}`)}}catch(l){console.warn(`[artifacts] record errored: ${l.message}`)}return o}var st,rr,or,nr,pt=m(()=>{st=500*1024*1024,rr=new Set([".DS_Store","Thumbs.db",".zibby-stop"]),or=new Set(["node_modules",".git","dist",".zibby","__tests__","__mocks__",".cache",".next",".turbo"]),nr={".webm":"video/webm",".mp4":"video/mp4",".mov":"video/quicktime",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".txt":"text/plain",".md":"text/markdown",".csv":"text/csv",".log":"text/plain",".json":"application/json",".yaml":"application/yaml",".yml":"application/yaml",".pdf":"application/pdf",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip"}});import{mkdirSync as ht,writeFileSync as cr,existsSync as C,readFileSync as dt}from"fs";import{join as A,dirname as lr,resolve as ut}from"path";import{pathToFileURL as ye}from"url";import{execSync as fr,spawn as gt}from"node:child_process";import{SQSClient as Et,SendMessageCommand as $t}from"@aws-sdk/client-sqs";var ne=null;function Rt(){return ne||(ne=new Et({region:process.env.AWS_REGION||"ap-southeast-2"})),ne}async function Re(e,t,r,n){let{EXECUTION_ID:o,SQS_AUTH_TOKEN:s,PROGRESS_API_URL:i,PROGRESS_QUEUE_URL:f,PROJECT_API_TOKEN:a}=n;if(!o)return;let c={executionId:o,...s&&{sqsAuthToken:s},step:{name:e,status:t,logs:r,timestamp:new Date().toISOString(),...t==="success"&&{completedAt:new Date().toISOString()}},status:t==="failed"?"failed":"running"};try{i?await ie(i,o,c,a):f&&await se(f,o,c)}catch(l){console.error(`\u26A0\uFE0F Failed to send progress: ${l.message}`)}}async function Ue(e,t,r){let{EXECUTION_ID:n,SQS_AUTH_TOKEN:o,PROGRESS_API_URL:s,PROGRESS_QUEUE_URL:i,PROJECT_API_TOKEN:f}=e;if(!n||!r)return;let a=JSON.stringify(r).length;console.log(`Sending artifact: ${t} (${(a/1024).toFixed(1)}KB)`);let c={executionId:n,...o&&{sqsAuthToken:o},artifacts:{[t]:r},timestamp:new Date().toISOString()},l=s?"HTTP":i?"SQS":"NONE",u=JSON.stringify(c).length;try{if(s)await ie(s,n,c,f);else if(i)await se(i,n,c);else{console.warn(`\u26A0\uFE0F No transport configured for artifact ${t} \u2014 neither PROGRESS_API_URL nor PROGRESS_QUEUE_URL set`);return}console.log(`Artifact ${t} sent via ${l} (payload=${(u/1024).toFixed(1)}KB, value=${(a/1024).toFixed(1)}KB)`)}catch(d){console.error(`Failed to send artifact ${t} via ${l}:`),console.error(` Payload size: ${(u/1024).toFixed(1)}KB, Value size: ${(a/1024).toFixed(1)}KB`),console.error(` Error: ${d.message}`),d.name&&console.error(` Error type: ${d.name}`),d.code&&console.error(` Error code: ${d.code}`),u>256*1024&&console.error(" \u26A0\uFE0F Message exceeds SQS 256KB limit! Consider splitting or compressing.")}}async function Oe(e,{status:t,error:r,finalState:n}){let{EXECUTION_ID:o,SQS_AUTH_TOKEN:s,PROGRESS_API_URL:i,PROGRESS_QUEUE_URL:f,PROJECT_API_TOKEN:a}=e;if(!o)return;let c={executionId:o,...s&&{sqsAuthToken:s},status:t,...r&&{error:r},...n&&typeof n=="object"&&Object.keys(n).length>0?{finalState:n}:{},timestamp:new Date().toISOString()},l=i?"HTTP":f?"SQS":"NONE",u=JSON.stringify(c).length;console.log(`Sending final status: ${t} via ${l} (${(u/1024).toFixed(1)}KB)`);try{if(i)await ie(i,o,c,a);else if(f){let d=["completed","failed","insufficient_context","blocked"].includes(t)?"execution_completed":"progress_update";await se(f,o,c,d)}else{console.warn("No transport configured for final status \u2014 neither PROGRESS_API_URL nor PROGRESS_QUEUE_URL set");return}console.log(`Final status ${t} sent via ${l}`)}catch(d){console.error(`Failed to send final status (${t}) via ${l}:`),console.error(` Payload: ${(u/1024).toFixed(1)}KB`),console.error(` Error: ${d.message}`),d.name&&console.error(` Error type: ${d.name}`),d.code&&console.error(` Error code: ${d.code}`)}}async function ie(e,t,r,n){let o=`${e}/${t}/progress`,s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);let i=await fetch(o,{method:"POST",headers:s,body:JSON.stringify(r)});if(!i.ok){let f=await i.text();throw new Error(`HTTP ${i.status}: ${f}`)}}async function se(e,t,r,n="progress_update"){let o=JSON.stringify(r),s=(o.length/1024).toFixed(1);o.length>256*1024&&console.error(`\u274C SQS message too large: ${s}KB (limit 256KB) for ${t} [${n}]`),await Rt().send(new $t({QueueUrl:e,MessageBody:o,MessageGroupId:t,MessageAttributes:{executionId:{DataType:"String",StringValue:t},messageType:{DataType:"String",StringValue:n}}}))}function Ut(e,t){try{let r=e?.sessionPath||e?.SESSION_PATH||process.env.ZIBBY_SESSION_PATH;if(!r||!t)return null;let n=Ee("fs"),s=Ee("path").join(r,t,"usage.json");if(!n.existsSync(s))return null;let i=n.readFileSync(s,"utf-8"),f=JSON.parse(i);return!f.input_tokens&&!f.output_tokens&&!f.inputTokens&&!f.outputTokens?null:f}catch{return null}}function Ie(e,t,r=null){return async function(o,s,i){let f=Date.now(),a=[],c="",l=console.log,u=process.stdout.write.bind(process.stdout),d=process.stderr.write.bind(process.stderr),k=!1;console.log=(...g)=>{let S=g.map(E=>typeof E=="string"?E:JSON.stringify(E)).join(" ");a.push(S),k=!0,l(...g),k=!1};let x="";process.stdout.write=(g,S,E)=>{if(!k){let N=typeof g=="string"?g:g.toString();x+=N;let h=x.split(`
3
- `);x=h.pop()||"";for(let J of h){let M=J.trim();M&&a.push(M)}}return u(g,S,E)},l(`[Middleware] Started capturing logs for ${o}`);let T=!1,U=setInterval(()=>{if(T)return;let g=a.join(`
4
- `);g!==c&&g.length>0&&(c=g,d(`\u{1F4E1} [Middleware] Sending live update for ${o}: ${g.length} chars, ${a.length} lines
5
- `),e(o,"in_progress",g,i).catch(S=>{d(`\u26A0\uFE0F [Middleware] Failed to send live update: ${S.message}
6
- `)}))},500);try{await e(o,"in_progress","",i);let g=await s(),S=((Date.now()-f)/1e3).toFixed(1);T=!0,clearInterval(U),await new Promise(h=>setImmediate(h)),console.log=l,process.stdout.write=u,x.trim()&&(a.push(x.trim()),x="");let E=a.join(`
7
- `);d(`\u{1F4E1} [Middleware] Sending final update for ${o}: ${E.length} chars, ${a.length} total lines captured
8
- `);let N=Ut(i,o);if(N)try{await t(i,`usage_${o}`,N)}catch(h){d(`\u26A0\uFE0F [Middleware] usage ship failed for ${o}: ${h.message}
9
- `)}if(g.success){if(await e(o,"success",E||`Completed in ${S}s`,i),r)try{let h=r(o,g);h&&h.key&&h.value&&await t(i,h.key,h.value)}catch(h){d(`\u26A0\uFE0F [Middleware] artifactExtractor for ${o} threw: ${h.message}
10
- `)}}else await e(o,"failed",`${E}
2
+ var Ct=Object.defineProperty;var Ce=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ne=(e,t)=>{for(var r in t)Ct(e,r,{get:t[r],enumerable:!0})};var He,Je=y(()=>{He="ffffffff-ffff-ffff-ffff-ffffffffffff"});var Me,Qe=y(()=>{Me="00000000-0000-0000-0000-000000000000"});var Ye,qe=y(()=>{Ye=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});function Vt(e){return typeof e=="string"&&Ye.test(e)}var F,J=y(()=>{qe();F=Vt});function Xt(e){if(!F(e))throw TypeError("Invalid UUID");let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var C,M=y(()=>{J();C=Xt});function U(e,t=0){return($[e[t+0]]+$[e[t+1]]+$[e[t+2]]+$[e[t+3]]+"-"+$[e[t+4]]+$[e[t+5]]+"-"+$[e[t+6]]+$[e[t+7]]+"-"+$[e[t+8]]+$[e[t+9]]+"-"+$[e[t+10]]+$[e[t+11]]+$[e[t+12]]+$[e[t+13]]+$[e[t+14]]+$[e[t+15]]).toLowerCase()}function Zt(e,t=0){let r=U(e,t);if(!F(r))throw TypeError("Stringified UUID is invalid");return r}var $,Ve,N=y(()=>{J();$=[];for(let e=0;e<256;++e)$.push((e+256).toString(16).slice(1));Ve=Zt});import{randomFillSync as er}from"crypto";function j(){return re>oe.length-16&&(er(oe),re=0),oe.slice(re,re+=16)}var oe,re,ne=y(()=>{oe=new Uint8Array(256),re=oe.length});function tr(e,t,r){let o,n=e?._v6??!1;if(e){let s=Object.keys(e);s.length===1&&s[0]==="_v6"&&(e=void 0)}if(e)o=Xe(e.random??e.rng?.()??j(),e.msecs,e.nsecs,e.clockseq,e.node,t,r);else{let s=Date.now(),i=j();rr(Q,s,i),o=Xe(i,Q.msecs,Q.nsecs,n?void 0:Q.clockseq,n?void 0:Q.node,t,r)}return t??U(o)}function rr(e,t,r){return e.msecs??=-1/0,e.nsecs??=0,t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t<e.msecs&&(e.node=void 0),e.node||(e.node=r.slice(10,16),e.node[0]|=1,e.clockseq=(r[8]<<8|r[9])&16383),e.msecs=t,e}function Xe(e,t,r,o,n,s,i=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(!s)s=new Uint8Array(16),i=0;else if(i<0||i+16>s.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);t??=Date.now(),r??=0,o??=(e[8]<<8|e[9])&16383,n??=e.slice(10,16),t+=122192928e5;let f=((t&268435455)*1e4+r)%4294967296;s[i++]=f>>>24&255,s[i++]=f>>>16&255,s[i++]=f>>>8&255,s[i++]=f&255;let a=t/4294967296*1e4&268435455;s[i++]=a>>>8&255,s[i++]=a&255,s[i++]=a>>>24&15|16,s[i++]=a>>>16&255,s[i++]=o>>>8|128,s[i++]=o&255;for(let l=0;l<6;++l)s[i++]=n[l];return s}var Q,se,he=y(()=>{ne();N();Q={};se=tr});function Y(e){let t=typeof e=="string"?C(e):e,r=or(t);return typeof e=="string"?U(r):r}function or(e){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}var we=y(()=>{M();N()});import{createHash as nr}from"crypto";function sr(e){return Array.isArray(e)?e=Buffer.from(e):typeof e=="string"&&(e=Buffer.from(e,"utf8")),nr("md5").update(e).digest()}var Ze,et=y(()=>{Ze=sr});function ir(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}function q(e,t,r,o,n,s){let i=typeof r=="string"?ir(r):r,f=typeof o=="string"?C(o):o;if(typeof o=="string"&&(o=C(o)),o?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+i.length);if(a.set(f),a.set(i,f.length),a=t(a),a[6]=a[6]&15|e,a[8]=a[8]&63|128,n){if(s=s||0,s<0||s+16>n.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let l=0;l<16;++l)n[s+l]=a[l];return n}return U(a)}var ie,ae,Se=y(()=>{M();N();ie="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ae="6ba7b811-9dad-11d1-80b4-00c04fd430c8"});function ye(e,t,r,o){return q(48,Ze,e,t,r,o)}var tt,rt=y(()=>{et();Se();ye.DNS=ie;ye.URL=ae;tt=ye});import{randomUUID as ar}from"crypto";var xe,ot=y(()=>{xe={randomUUID:ar}});function cr(e,t,r){if(xe.randomUUID&&!t&&!e)return xe.randomUUID();e=e||{};let o=e.random??e.rng?.()??j();if(o.length<16)throw new Error("Random bytes length must be >= 16");if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let n=0;n<16;++n)t[r+n]=o[n];return t}return U(o)}var nt,st=y(()=>{ot();ne();N();nt=cr});import{createHash as lr}from"crypto";function fr(e){return Array.isArray(e)?e=Buffer.from(e):typeof e=="string"&&(e=Buffer.from(e,"utf8")),lr("sha1").update(e).digest()}var it,at=y(()=>{it=fr});function _e(e,t,r,o){return q(80,it,e,t,r,o)}var ct,lt=y(()=>{at();Se();_e.DNS=ie;_e.URL=ae;ct=_e});function pr(e,t,r){e??={},r??=0;let o=se({...e,_v6:!0},new Uint8Array(16));if(o=Y(o),t){if(r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let n=0;n<16;n++)t[r+n]=o[n];return t}return U(o)}var ft,pt=y(()=>{N();he();we();ft=pr});function Ee(e){let t=typeof e=="string"?C(e):e,r=dr(t);return typeof e=="string"?U(r):r}function dr(e){return Uint8Array.of((e[3]&15)<<4|e[4]>>4&15,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|e[6]&15,e[7],(e[1]&15)<<4|(e[2]&240)>>4,(e[2]&15)<<4|(e[3]&240)>>4,16|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}var dt=y(()=>{M();N()});function ur(e,t,r){let o;if(e)o=ut(e.random??e.rng?.()??j(),e.msecs,e.seq,t,r);else{let n=Date.now(),s=j();gr($e,n,s),o=ut(s,$e.msecs,$e.seq,t,r)}return t??U(o)}function gr(e,t,r){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}function ut(e,t,r,o,n=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(!o)o=new Uint8Array(16),n=0;else if(n<0||n+16>o.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);return t??=Date.now(),r??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],o[n++]=t/1099511627776&255,o[n++]=t/4294967296&255,o[n++]=t/16777216&255,o[n++]=t/65536&255,o[n++]=t/256&255,o[n++]=t&255,o[n++]=112|r>>>28&15,o[n++]=r>>>20&255,o[n++]=128|r>>>14&63,o[n++]=r>>>6&255,o[n++]=r<<2&255|e[10]&3,o[n++]=e[11],o[n++]=e[12],o[n++]=e[13],o[n++]=e[14],o[n++]=e[15],o}var $e,gt,mt=y(()=>{ne();N();$e={};gt=ur});function mr(e){if(!F(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)}var ht,wt=y(()=>{J();ht=mr});var St={};Ne(St,{MAX:()=>He,NIL:()=>Me,parse:()=>C,stringify:()=>Ve,v1:()=>se,v1ToV6:()=>Y,v3:()=>tt,v4:()=>nt,v5:()=>ct,v6:()=>ft,v6ToV1:()=>Ee,v7:()=>gt,validate:()=>F,version:()=>ht});var yt=y(()=>{Je();Qe();M();N();he();we();rt();st();lt();pt();dt();mt();J();wt()});var Rt={};Ne(Rt,{uploadSessionArtifacts:()=>Or});import{readdirSync as _t,statSync as Re,createReadStream as hr,existsSync as wr}from"node:fs";import{join as Et,relative as Sr,sep as yr,extname as xr}from"node:path";function Rr(e){let t=xr(e).toLowerCase();return $r[t]||"application/octet-stream"}function $t(e){let t=[],r;try{r=_t(e)}catch{return t}for(let o of r){if(_r.has(o)||o.startsWith(".")||Er.has(o))continue;let n=Et(e,o),s;try{s=Re(n)}catch{continue}s.isDirectory()?t.push(...$t(n)):s.isFile()&&t.push(n)}return t}async function Ur({apiUrl:e,apiKey:t,executionId:r,nodeName:o,filename:n,absolutePath:s,sizeBytes:i,contentType:f}){let a;try{let l=await fetch(`${e}/${r}/artifacts/upload-url`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({nodeName:o,filename:n,contentType:f,sizeBytes:i})});if(!l.ok){let c=await l.text();return console.warn(`[artifacts] upload-url failed for ${o}/${n}: ${l.status} ${c.slice(0,200)}`),null}a=await l.json()}catch(l){return console.warn(`[artifacts] upload-url request errored for ${o}/${n}: ${l.message}`),null}try{let l=hr(s),c=a.requiredHeaders?{...a.requiredHeaders,"Content-Length":String(i)}:{"Content-Type":f,"Content-Length":String(i)},p=await fetch(a.url,{method:"PUT",headers:c,body:l,duplex:"half"});if(!p.ok)return console.warn(`[artifacts] S3 PUT failed for ${o}/${n}: ${p.status}`),null}catch(l){return console.warn(`[artifacts] S3 PUT errored for ${o}/${n}: ${l.message}`),null}return{nodeName:o,filename:n,s3Key:a.s3Key,contentType:f,sizeBytes:i}}async function Or({sessionPath:e,executionId:t,apiUrl:r,apiKey:o}){let n={uploaded:[],skipped:[]};if(!e||!wr(e))return n;if(!r||!o||!t)return console.warn("[artifacts] uploader missing required input \u2014 skipping"),n;let s;try{s=_t(e)}catch(c){return console.warn(`[artifacts] could not read session folder ${e}: ${c.message}`),n}let i=[];for(let c of s){let p=Et(e,c),d;try{d=Re(p)}catch{continue}if(!d.isDirectory()||c.startsWith(".")||c.startsWith("_"))continue;let R=$t(p);for(let S of R){let I=Sr(p,S).split(yr).join("/"),_;try{_=Re(S).size}catch{continue}if(_>xt){n.skipped.push({nodeName:c,filename:I,reason:`size ${_} > ${xt}`});continue}if(_===0){n.skipped.push({nodeName:c,filename:I,reason:"empty"});continue}i.push({apiUrl:r,apiKey:o,executionId:t,nodeName:c,filename:I,absolutePath:S,sizeBytes:_,contentType:Rr(I)})}}if(i.length===0)return n;let f=4,a=i.slice(),l=Array.from({length:Math.min(f,a.length)},async()=>{for(;a.length;){let c=a.shift(),p=await Ur(c);p?n.uploaded.push(p):n.skipped.push({nodeName:c.nodeName,filename:c.filename,reason:"upload failed"})}});if(await Promise.all(l),n.uploaded.length>0)try{let c=await fetch(`${r}/${t}/artifacts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({files:n.uploaded})});if(!c.ok){let p=await c.text();console.warn(`[artifacts] record failed: ${c.status} ${p.slice(0,200)}`)}}catch(c){console.warn(`[artifacts] record errored: ${c.message}`)}return n}var xt,_r,Er,$r,Ut=y(()=>{xt=500*1024*1024,_r=new Set([".DS_Store","Thumbs.db",".zibby-stop"]),Er=new Set(["node_modules",".git","dist",".zibby","__tests__","__mocks__",".cache",".next",".turbo"]),$r={".webm":"video/webm",".mp4":"video/mp4",".mov":"video/quicktime",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".txt":"text/plain",".md":"text/markdown",".csv":"text/csv",".log":"text/plain",".json":"application/json",".yaml":"application/yaml",".yml":"application/yaml",".pdf":"application/pdf",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip"}});import{mkdirSync as Pt,writeFileSync as Ir,existsSync as G,readFileSync as Ot}from"fs";import{join as D,dirname as Tr,resolve as It}from"path";import{pathToFileURL as Oe}from"url";import{spawn as Ie}from"node:child_process";import{SQSClient as Nt,SendMessageCommand as jt}from"@aws-sdk/client-sqs";var pe=null;function Kt(){return pe||(pe=new Nt({region:process.env.AWS_REGION||"ap-southeast-2"})),pe}async function de(e,t,r,o){let{EXECUTION_ID:n,SQS_AUTH_TOKEN:s,PROGRESS_API_URL:i,PROGRESS_QUEUE_URL:f,PROJECT_API_TOKEN:a}=o;if(!n)return;let l={executionId:n,...s&&{sqsAuthToken:s},step:{name:e,status:t,logs:r,timestamp:new Date().toISOString(),...t==="success"&&{completedAt:new Date().toISOString()}},status:t==="failed"?"failed":"running"};try{i?await ue(i,n,l,a):f&&await ge(f,n,l)}catch(c){console.error(`\u26A0\uFE0F Failed to send progress: ${c.message}`)}}async function je(e,t,r){let{EXECUTION_ID:o,SQS_AUTH_TOKEN:n,PROGRESS_API_URL:s,PROGRESS_QUEUE_URL:i,PROJECT_API_TOKEN:f}=e;if(!o||!r)return;let a=JSON.stringify(r).length;console.log(`Sending artifact: ${t} (${(a/1024).toFixed(1)}KB)`);let l={executionId:o,...n&&{sqsAuthToken:n},artifacts:{[t]:r},timestamp:new Date().toISOString()},c=s?"HTTP":i?"SQS":"NONE",p=JSON.stringify(l).length;try{if(s)await ue(s,o,l,f);else if(i)await ge(i,o,l);else{console.warn(`\u26A0\uFE0F No transport configured for artifact ${t} \u2014 neither PROGRESS_API_URL nor PROGRESS_QUEUE_URL set`);return}console.log(`Artifact ${t} sent via ${c} (payload=${(p/1024).toFixed(1)}KB, value=${(a/1024).toFixed(1)}KB)`)}catch(d){console.error(`Failed to send artifact ${t} via ${c}:`),console.error(` Payload size: ${(p/1024).toFixed(1)}KB, Value size: ${(a/1024).toFixed(1)}KB`),console.error(` Error: ${d.message}`),d.name&&console.error(` Error type: ${d.name}`),d.code&&console.error(` Error code: ${d.code}`),p>256*1024&&console.error(" \u26A0\uFE0F Message exceeds SQS 256KB limit! Consider splitting or compressing.")}}async function Ke(e,{status:t,error:r,finalState:o}){let{EXECUTION_ID:n,SQS_AUTH_TOKEN:s,PROGRESS_API_URL:i,PROGRESS_QUEUE_URL:f,PROJECT_API_TOKEN:a}=e;if(!n)return;let l={executionId:n,...s&&{sqsAuthToken:s},status:t,...r&&{error:r},...o&&typeof o=="object"&&Object.keys(o).length>0?{finalState:o}:{},timestamp:new Date().toISOString()},c=i?"HTTP":f?"SQS":"NONE",p=JSON.stringify(l).length;console.log(`Sending final status: ${t} via ${c} (${(p/1024).toFixed(1)}KB)`);try{if(i)await ue(i,n,l,a);else if(f){let d=["completed","failed","insufficient_context","blocked"].includes(t)?"execution_completed":"progress_update";await ge(f,n,l,d)}else{console.warn("No transport configured for final status \u2014 neither PROGRESS_API_URL nor PROGRESS_QUEUE_URL set");return}console.log(`Final status ${t} sent via ${c}`)}catch(d){console.error(`Failed to send final status (${t}) via ${c}:`),console.error(` Payload: ${(p/1024).toFixed(1)}KB`),console.error(` Error: ${d.message}`),d.name&&console.error(` Error type: ${d.name}`),d.code&&console.error(` Error code: ${d.code}`)}}async function ue(e,t,r,o){let n=`${e}/${t}/progress`,s={"Content-Type":"application/json"};o&&(s.Authorization=`Bearer ${o}`);let i=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(r)});if(!i.ok){let f=await i.text();throw new Error(`HTTP ${i.status}: ${f}`)}}async function ge(e,t,r,o="progress_update"){let n=JSON.stringify(r),s=(n.length/1024).toFixed(1);n.length>256*1024&&console.error(`\u274C SQS message too large: ${s}KB (limit 256KB) for ${t} [${o}]`),await Kt().send(new jt({QueueUrl:e,MessageBody:n,MessageGroupId:t,MessageAttributes:{executionId:{DataType:"String",StringValue:t},messageType:{DataType:"String",StringValue:o}}}))}function Ft(e,t){try{let r=e?.sessionPath||e?.SESSION_PATH||process.env.ZIBBY_SESSION_PATH;if(!r||!t)return null;let o=Ce("fs"),s=Ce("path").join(r,t,"usage.json");if(!o.existsSync(s))return null;let i=o.readFileSync(s,"utf-8"),f=JSON.parse(i);return!f.input_tokens&&!f.output_tokens&&!f.inputTokens&&!f.outputTokens?null:f}catch{return null}}function Fe(e,t,r=null){return async function(n,s,i){let f=Date.now(),a=[],l="",c=console.log,p=process.stdout.write.bind(process.stdout),d=process.stderr.write.bind(process.stderr),R=!1;console.log=(...w)=>{let u=w.map(h=>typeof h=="string"?h:JSON.stringify(h)).join(" ");a.push(u),R=!0,c(...w),R=!1};let S="";process.stdout.write=(w,u,h)=>{if(!R){let x=typeof w=="string"?w:w.toString();S+=x;let m=S.split(`
3
+ `);S=m.pop()||"";for(let O of m){let b=O.trim();b&&a.push(b)}}return p(w,u,h)},c(`[Middleware] Started capturing logs for ${n}`);let I=!1,_=setInterval(()=>{if(I)return;let w=a.join(`
4
+ `);w!==l&&w.length>0&&(l=w,d(`\u{1F4E1} [Middleware] Sending live update for ${n}: ${w.length} chars, ${a.length} lines
5
+ `),e(n,"in_progress",w,i).catch(u=>{d(`\u26A0\uFE0F [Middleware] Failed to send live update: ${u.message}
6
+ `)}))},500);try{await e(n,"in_progress","",i);let w=await s(),u=((Date.now()-f)/1e3).toFixed(1);I=!0,clearInterval(_),await new Promise(m=>setImmediate(m)),console.log=c,process.stdout.write=p,S.trim()&&(a.push(S.trim()),S="");let h=a.join(`
7
+ `);d(`\u{1F4E1} [Middleware] Sending final update for ${n}: ${h.length} chars, ${a.length} total lines captured
8
+ `);let x=Ft(i,n);if(x)try{await t(i,`usage_${n}`,x)}catch(m){d(`\u26A0\uFE0F [Middleware] usage ship failed for ${n}: ${m.message}
9
+ `)}if(w.success){if(await e(n,"success",h||`Completed in ${u}s`,i),r)try{let m=r(n,w);m&&m.key&&m.value&&await t(i,m.key,m.value)}catch(m){d(`\u26A0\uFE0F [Middleware] artifactExtractor for ${n} threw: ${m.message}
10
+ `)}}else await e(n,"failed",`${h}
11
11
 
12
- Error: ${g.error}`,i);return g}catch(g){T=!0,clearInterval(U),await new Promise(E=>setImmediate(E)),console.log=l,process.stdout.write=u;let S=`${a.join(`
12
+ Error: ${w.error}`,i);return w}catch(w){I=!0,clearInterval(_),await new Promise(h=>setImmediate(h)),console.log=c,process.stdout.write=p;let u=`${a.join(`
13
13
  `)}
14
14
 
15
- Error: ${g.message}`;throw await e(o,"failed",S,i),g}}}function Te({workflowType:e,jobId:t,projectId:r,agentType:n,model:o,egressIp:s,egressKind:i}){let f="\u2500".repeat(60),a=`${n||"default"} (model: ${o||"auto"})`,c=["",f,` Workflow: ${e}`,` Job: ${t||"local"}`,` Project: ${r||"none"}`,` Agent: ${a}`];if(s||i){let l=s||"unknown",u=i||"static";c.push(` Egress: ${l} (${u})`)}return c.push(f),c.join(`
16
- `)}import{existsSync as Ot,writeFileSync as It}from"fs";import{join as Ae}from"path";var ae={width:1280,height:720},Tt="on",At="tests",Pt="test-results/playwright";function vt(e={}){let t=e.viewport&&typeof e.viewport=="object"?{width:Number(e.viewport.width)||ae.width,height:Number(e.viewport.height)||ae.height}:ae,r=typeof e.video=="string"?e.video:Tt,n=e.paths?.generated||At,o=e.playwrightArtifacts!==!1,s=o?"on":"off",i=o?"only-on-failure":"off";return`// AUTO-GENERATED at workflow run start by @zibby/cli's
15
+ Error: ${w.message}`;throw await e(n,"failed",u,i),w}}}import{existsSync as Gt,readFileSync as zt}from"fs";var Bt="/tmp/zibby-entrypoint-setup.log",Wt=500;function B(e){return e.replace(/\r/g,"").trimEnd()}function Ge({reportProgressFn:e,state:t,entrypointLogPath:r=Bt}={}){if(!t||!t.EXECUTION_ID)return{finalize:async()=>{},getBuffer:()=>""};let o=[],n=0,s=!1;try{if(Gt(r)){let u=zt(r,"utf-8");for(let h of u.split(`
16
+ `)){let x=B(h);x&&o.push(x)}}}catch{}let i=console.log,f=console.warn,a=console.error,l=process.stdout.write.bind(process.stdout),c=process.stderr.write.bind(process.stderr),p=!1,d=u=>(...h)=>{let x=h.map(m=>typeof m=="string"?m:(()=>{try{return JSON.stringify(m)}catch{return String(m)}})()).join(" ");for(let m of x.split(`
17
+ `)){let O=B(m);O&&o.push(O)}p=!0;try{u(...h)}finally{p=!1}};console.log=d(i),console.warn=d(f),console.error=d(a);let R="",S="";process.stdout.write=(u,h,x)=>{if(!p){let m=typeof u=="string"?u:u.toString();R+=m;let O=R.split(`
18
+ `);R=O.pop()||"";for(let b of O){let K=B(b);K&&o.push(K)}}return l(u,h,x)},process.stderr.write=(u,h,x)=>{if(!p){let m=typeof u=="string"?u:u.toString();S+=m;let O=S.split(`
19
+ `);S=O.pop()||"";for(let b of O){let K=B(b);K&&o.push(K)}}return c(u,h,x)};let _=setInterval(()=>{if(s)return;let u=o.join(`
20
+ `);u.length!==n&&(n=u.length,e("setup","in_progress",u,t).catch(h=>{c(`[setup-progress] flush failed: ${h.message}
21
+ `)}))},Wt);return _.unref&&_.unref(),{finalize:async()=>{if(s)return;s=!0,clearInterval(_),console.log=i,console.warn=f,console.error=a,process.stdout.write=l,process.stderr.write=c,R.trim()&&(o.push(B(R)),R=""),S.trim()&&(o.push(B(S)),S="");let u=o.join(`
22
+ `);if(u.length>0)try{await e("setup","in_progress",u,t)}catch(h){c(`[setup-progress] final flush failed: ${h.message}
23
+ `)}},getBuffer:()=>o.join(`
24
+ `)}}function ze({workflowType:e,jobId:t,projectId:r,agentType:o,model:n,egressIp:s,egressKind:i}){let f="\u2500".repeat(60),a=`${o||"default"} (model: ${n||"auto"})`,l=["",f,` Workflow: ${e}`,` Job: ${t||"local"}`,` Project: ${r||"none"}`,` Agent: ${a}`];if(s||i){let c=s||"unknown",p=i||"static";l.push(` Egress: ${c} (${p})`)}return l.push(f),l.join(`
25
+ `)}import{existsSync as Ht,writeFileSync as Jt}from"fs";import{join as Be}from"path";var me={width:1280,height:720},Mt="on",Qt="tests",Yt="test-results/playwright";function qt(e={}){let t=e.viewport&&typeof e.viewport=="object"?{width:Number(e.viewport.width)||me.width,height:Number(e.viewport.height)||me.height}:me,r=typeof e.video=="string"?e.video:Mt,o=e.paths?.generated||Qt,n=e.playwrightArtifacts!==!1,s=n?"on":"off",i=n?"only-on-failure":"off";return`// AUTO-GENERATED at workflow run start by @zibby/cli's
17
26
  // playwright-config-materialize.js. Derived from the bundled
18
27
  // zibby.config.json (which @zibby/workflow-deploy serialized from your
19
28
  // project's .zibby.config.mjs). Do NOT edit by hand \u2014 re-run a workflow
@@ -23,8 +32,8 @@ Error: ${g.message}`;throw await e(o,"failed",S,i),g}}}function Te({workflowType
23
32
  import { defineConfig } from '@playwright/test';
24
33
 
25
34
  export default defineConfig({
26
- testDir: '${n.replace(/'/g,"\\'")}',
27
- outputDir: '${Pt}',
35
+ testDir: '${o.replace(/'/g,"\\'")}',
36
+ outputDir: '${Yt}',
28
37
  timeout: 60000,
29
38
  retries: 0,
30
39
  workers: 1,
@@ -39,7 +48,8 @@ export default defineConfig({
39
48
 
40
49
  reporter: [['list']],
41
50
  });
42
- `}function Pe(e,t){if(!e)return{written:!1,path:null,reason:"no workspaceDir"};for(let o of["js","mjs","ts"]){let s=Ae(e,`playwright.config.${o}`);if(Ot(s))return{written:!1,path:s,reason:`existing playwright.config.${o} in workspace`}}let r=Ae(e,"playwright.config.js"),n=vt(t||{});try{return It(r,n,"utf-8"),{written:!0,path:r,reason:"derived from zibby.config"}}catch(o){return{written:!1,path:null,reason:`write failed: ${o.message}`}}}import"@zibby/core";var H=process.env.WORKSPACE||"/workspace";async function pr(e,t){ht(t,{recursive:!0});let r=Date.now();console.log("[setup] Fetching bundle...");let n=setInterval(()=>{let s=((Date.now()-r)/1e3).toFixed(1);console.log(`[setup] still fetching (${s}s elapsed)`)},3e3);try{await new Promise((s,i)=>{let f=gt("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),a=gt("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(a.stdin);let c,l,u=()=>{if(c!==void 0&&l!==void 0){if(c!==0)return i(new Error(`curl exited ${c}`));if(l!==0)return i(new Error(`tar exited ${l}`));s()}};f.on("close",d=>{c=d,u()}),a.on("close",d=>{l=d,u()}),f.on("error",i),a.on("error",i)})}finally{clearInterval(n)}let o=((Date.now()-r)/1e3).toFixed(1);return console.log(`[setup] Bundle extracted (${o}s)`),t}async function mt(){let e=process.env.WORKFLOW_SOURCES_URL;if(!e)throw new Error("WORKFLOW_SOURCES_URL env var is required");let t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch sources: ${t.status} ${t.statusText}`);let r=await t.json();if(!r.sources||typeof r.sources!="object")throw new Error('Invalid sources payload \u2014 missing "sources" map');return r}function dr(e){let t=e?.agent;if(!t)return null;if(typeof t=="string")return t;if(typeof t=="object"){if(typeof t.provider=="string")return t.provider;for(let r of["claude","cursor","codex","gemini"])if(t[r])return r}return null}function ur(e,t){let r=ut(t),n=0;for(let[o,s]of Object.entries(e)){let i=ut(t,o);if(!i.startsWith(`${r}/`)&&i!==r){console.error(` \u26D4 Skipping unsafe path: ${o}`);continue}ht(lr(i),{recursive:!0}),cr(i,s,"utf-8"),n++}return n}async function gr(){let e=process.env.ZIBBY_EGRESS_PROXY_URL,t=process.env.ZIBBY_EGRESS_TOKEN;if(!(!e||!t))try{let r=await import("undici"),n=new r.ProxyAgent({uri:e,token:`Bearer ${t}`});r.setGlobalDispatcher(n)}catch(r){console.warn(`[setup] Failed to install egress proxy dispatcher: ${r.message}`)}}async function mr(){if(process.env.ZIBBY_EGRESS_IP)return{ip:process.env.ZIBBY_EGRESS_IP,kind:"static"};try{let e=new AbortController,t=setTimeout(()=>e.abort(),1500),r=await fetch("https://api.ipify.org?format=json",{signal:e.signal});return clearTimeout(t),r.ok?{ip:(await r.json())?.ip||null,kind:"dynamic"}:{ip:null,kind:"dynamic"}}catch{return{ip:null,kind:"dynamic"}}}async function hr(e,t){let r=A(e,"graph.mjs");if(!C(r))throw new Error(`graph.mjs not found at ${r}`);let n=await import(ye(r).href),o=t?.entryClass,s=o&&n[o]||n.default||Object.values(n).find(i=>typeof i=="function"&&i.prototype?.buildGraph);if(!s)throw new Error("No WorkflowAgent class found in graph.mjs");return s}async function Jo(){if(!process.env.NODE_PATH){process.env.NODE_PATH="/opt/zibby/packages";let p=await import("module");p.default._initPaths&&p.default._initPaths()}await gr();let{WORKFLOW_JOB_ID:e,WORKFLOW_TYPE:t,PROJECT_ID:r,AGENT_TYPE:n,MODEL:o}=process.env;t||(console.error("Missing WORKFLOW_TYPE env var"),process.exit(1));let s=process.env.WORKFLOW_BUNDLE_URL,i,f={},a,c;if(s){a=t,i=A(H,".zibby","workflows",a);try{await pr(s,i);try{let p=await mt();f=p.input||{},c=p.version}catch{}}catch(p){console.warn(`[setup] Bundle extract failed (${p.message}); falling back to source install`),i=null}}if(!i){let p=await mt(),{sources:w,input:$,workflowType:O,version:R}=p;f=$||{},a=O||t,c=R,console.log(`[setup] Workflow v${c||"?"} (${Object.keys(w).length} files)`),i=A(H,".zibby","workflows",a);let P=ur(w,i);console.log(`[setup] Wrote ${P} files`),console.log("[setup] Installing dependencies...");try{fr("npm install --silent --no-audit --no-fund",{cwd:i,stdio:"inherit"}),console.log("[setup] Dependencies installed")}catch(I){console.warn(`[setup] npm install failed: ${I.message}`)}}let l={},u=A(i,"workflow.json");C(u)&&(l=JSON.parse(dt(u,"utf-8")));let d={},k=A(i,"zibby.config.json");if(C(k))try{d=JSON.parse(dt(k,"utf-8")),console.log("[setup] Loaded user config from zibby.config.json")}catch(p){console.warn(`[setup] Failed to parse zibby.config.json: ${p.message} \u2014 falling back to defaults`)}let x=Pe(H,d);x.written?console.log(`[setup] Materialized playwright.config.js \u2192 ${x.path} (${x.reason})`):x.path&&console.log(`[setup] Using existing playwright config: ${x.path}`);let T=dr(d)||n,U=await mr();console.log(Te({workflowType:t,jobId:e,projectId:r,agentType:T,model:o,egressIp:U.ip,egressKind:U.kind}));let g=await hr(i,l);console.log(`[setup] Loaded ${g.name}`);let S=[],E=A(i,"node_modules","@zibby","agent-workflow"),N=A(i,"node_modules","@zibby","core","node_modules","@zibby","agent-workflow");C(E)&&S.push({kind:"hoisted",path:E}),C(N)&&S.push({kind:"nested",path:N});let h=process.env.ZIBBY_RUN_DIAG==="1";if(h){let{readdirSync:p}=await import("fs");console.log(` [diag] @zibby/agent-workflow copies in bundle: ${S.length}`);for(let w of S)console.log(` [diag] ${w.kind}: ${w.path}`);try{let w=A(i,"node_modules","@zibby");C(w)&&console.log(` [diag] node_modules/@zibby/ contents: [${p(w).join(", ")}]`)}catch{}}let J=A(i,"node_modules","@zibby","core","dist","index.js");if(C(J)&&S.length>0)try{let p=await import(ye(J).href),w=[p.AssistantStrategy,p.CursorAgentStrategy,p.ClaudeAgentStrategy,p.CodexAgentStrategy,p.GeminiAgentStrategy].filter(Boolean);for(let $ of S){let O=A($.path,"dist","index.js");if(!C(O))continue;let R=await import(ye(O).href),P=h?R.listStrategies():null;for(let I of w)try{R.registerStrategy(new I)}catch(St){console.warn(` register ${I.name} into ${$.kind} failed: ${St.message}`)}h&&console.log(` [diag] ${$.kind} registry: before=[${P.join(",")||"empty"}] after=[${R.listStrategies().join(",")||"empty"}]`)}console.log("[setup] Registered 5 agent strategies (assistant, cursor, claude, codex, gemini)")}catch(p){console.warn(`[setup] Failed to bridge strategies: ${p.message}`)}else console.warn("[setup] No @zibby/core or @zibby/agent-workflow in bundle \u2014 agent strategies may be unavailable");let M=Date.now(),xe=new g({workflow:a||t}),te=xe.buildGraph(),wt=Ie(Re,Ue);Array.isArray(te.middleware)?te.middleware.push(wt):console.warn("[run] graph.middleware not an array \u2014 per-node progress reporting disabled for this run");let K=process.env.WORKFLOW_UUID||null,Q=process.env.ZIBBY_CONVERSATION_ID||null,re=!1;if(K&&Q)try{let{v5:p}=await Promise.resolve().then(()=>(it(),nt)),w=p(`${K}:${Q}`,"6ba7b810-9dad-11d1-80b4-00c04fd430c8"),$=(process.env.PROGRESS_API_URL||process.env.ZIBBY_API_BASE||"").replace(/\/executions\/?$/,"").replace(/\/+$/,""),O=process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_SDK_DEBUG==="1"&&console.log(`[session-preflight] sessionId=${w} apiUrl=${$?"set":"unset"} apiKey=${O?"set":"unset"}`),$&&O){let R=`${$}/workflows/${encodeURIComponent(K)}/sessions/${encodeURIComponent(w)}`,P=await fetch(R,{method:"GET",headers:{Authorization:`Bearer ${O}`}});if(process.env.ZIBBY_SDK_DEBUG==="1"&&console.log(`[session-preflight] GET ${R} \u2192 HTTP ${P.status}`),P.ok){let I=await P.json().catch(()=>({}));re=Array.isArray(I?.entries)&&I.entries.length>0,process.env.ZIBBY_SDK_DEBUG==="1"&&console.log(`[session-preflight] hasPriorSession=${re} entries=${I?.entries?.length??"n/a"}`)}}}catch(p){process.env.ZIBBY_SDK_DEBUG==="1"&&console.log(`[session-preflight] threw: ${p.message}`)}let oe=null;try{process.env.REPOS&&(oe=JSON.parse(process.env.REPOS))}catch{}let yt={...f||{},cwd:H,runId:e||`run-${Date.now()}`,config:d,input:f||{},...K?{workflowUuid:K}:{},...Q?{conversationId:Q}:{},...re?{hasPriorSession:!0}:{},workspace:H,...oe?{repos:oe}:{},...process.env.GITHUB_TOKEN?{githubToken:process.env.GITHUB_TOKEN}:{},EXECUTION_ID:process.env.EXECUTION_ID||e||"",PROGRESS_API_URL:process.env.PROGRESS_API_URL||"",PROGRESS_QUEUE_URL:process.env.PROGRESS_QUEUE_URL||"",SQS_AUTH_TOKEN:process.env.SQS_AUTH_TOKEN||"",PROJECT_API_TOKEN:process.env.PROJECT_API_TOKEN||""};console.log("");let j;try{j=await te.run(xe,yt)}catch(p){console.error(`
43
- Workflow execution failed: ${p.message}`),console.error(p.stack),await we("failed",p.message),process.exit(1)}let Se=((Date.now()-M)/1e3).toFixed(1),xt=j?.success!==!1,_e=a||t;if(process.env.UPLOAD_ARTIFACTS!=="0"){let p=j?.state?.sessionPath,w=process.env.PROGRESS_API_URL||process.env.ZIBBY_API_BASE,$=process.env.PROJECT_API_TOKEN,O=process.env.WORKFLOW_JOB_ID;if(p&&w&&$&&O)try{let{uploadSessionArtifacts:R}=await Promise.resolve().then(()=>(pt(),ft)),{uploaded:P,skipped:I}=await R({sessionPath:p,executionId:O,apiUrl:w,apiKey:$});console.log(`[artifacts] uploaded ${P.length} file(s)${I.length?`, skipped ${I.length}`:""}`)}catch(R){console.warn(`[artifacts] uploader threw: ${R.message}`)}else console.log("[artifacts] skipping upload \u2014 sessionPath/apiUrl/apiKey/executionId missing")}xt?(console.log(`
44
- [done] ${_e} completed in ${Se}s`),await we("completed",null,j?.state)):(console.error(`
45
- [done] ${_e} failed after ${Se}s`),await we("failed",j?.error||"Workflow execution failed",j?.state),process.exit(1))}async function we(e,t=null,r=void 0){let n={EXECUTION_ID:process.env.WORKFLOW_JOB_ID,PROGRESS_API_URL:process.env.PROGRESS_API_URL,PROGRESS_QUEUE_URL:process.env.PROGRESS_QUEUE_URL,PROJECT_API_TOKEN:process.env.PROJECT_API_TOKEN,SQS_AUTH_TOKEN:process.env.SQS_AUTH_TOKEN};if(n.EXECUTION_ID)try{await Oe(n,{status:e,...t&&{error:t},...r?{finalState:r}:{}})}catch(o){console.error(`\u26A0\uFE0F Failed to report status: ${o.message}`)}}export{dr as resolveAgentFromConfig,Jo as runWorkflowCommand};
51
+ `}function We(e,t){if(!e)return{written:!1,path:null,reason:"no workspaceDir"};for(let n of["js","mjs","ts"]){let s=Be(e,`playwright.config.${n}`);if(Ht(s))return{written:!1,path:s,reason:`existing playwright.config.${n} in workspace`}}let r=Be(e,"playwright.config.js"),o=qt(t||{});try{return Jt(r,o,"utf-8"),{written:!0,path:r,reason:"derived from zibby.config"}}catch(n){return{written:!1,path:null,reason:`write failed: ${n.message}`}}}import"@zibby/core";var V=process.env.WORKSPACE||"/workspace";async function Pr(e,t){Pt(t,{recursive:!0});let r=Date.now();console.log("[setup] Fetching bundle...");let o=setInterval(()=>{let s=((Date.now()-r)/1e3).toFixed(1);console.log(`[setup] still fetching (${s}s elapsed)`)},3e3);try{await new Promise((s,i)=>{let f=Ie("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),a=Ie("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(a.stdin);let l,c,p=()=>{if(l!==void 0&&c!==void 0){if(l!==0)return i(new Error(`curl exited ${l}`));if(c!==0)return i(new Error(`tar exited ${c}`));s()}};f.on("close",d=>{l=d,p()}),a.on("close",d=>{c=d,p()}),f.on("error",i),a.on("error",i)})}finally{clearInterval(o)}let n=((Date.now()-r)/1e3).toFixed(1);return console.log(`[setup] Bundle extracted (${n}s)`),t}async function Tt(){let e=process.env.WORKFLOW_SOURCES_URL;if(!e)throw new Error("WORKFLOW_SOURCES_URL env var is required");let t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch sources: ${t.status} ${t.statusText}`);let r=await t.json();if(!r.sources||typeof r.sources!="object")throw new Error('Invalid sources payload \u2014 missing "sources" map');return r}function Ar(e){let t=e?.agent;if(!t)return null;if(typeof t=="string")return t;if(typeof t=="object"){if(typeof t.provider=="string")return t.provider;for(let r of["claude","cursor","codex","gemini"])if(t[r])return r}return null}function vr(e,t){let r=It(t),o=0;for(let[n,s]of Object.entries(e)){let i=It(t,n);if(!i.startsWith(`${r}/`)&&i!==r){console.error(` \u26D4 Skipping unsafe path: ${n}`);continue}Pt(Tr(i),{recursive:!0}),Ir(i,s,"utf-8"),o++}return o}async function br(){let e=process.env.ZIBBY_EGRESS_PROXY_URL,t=process.env.ZIBBY_EGRESS_TOKEN;if(!(!e||!t))try{let r=await import("undici"),o=new r.ProxyAgent({uri:e,token:`Bearer ${t}`});r.setGlobalDispatcher(o)}catch(r){console.warn(`[setup] Failed to install egress proxy dispatcher: ${r.message}`)}}async function Dr(){if(process.env.ZIBBY_EGRESS_IP)return{ip:process.env.ZIBBY_EGRESS_IP,kind:"static"};try{let e=new AbortController,t=setTimeout(()=>e.abort(),1500),r=await fetch("https://api.ipify.org?format=json",{signal:e.signal});return clearTimeout(t),r.ok?{ip:(await r.json())?.ip||null,kind:"dynamic"}:{ip:null,kind:"dynamic"}}catch{return{ip:null,kind:"dynamic"}}}async function Lr(e,t){let r=D(e,"graph.mjs");if(!G(r))throw new Error(`graph.mjs not found at ${r}`);let o=await import(Oe(r).href),n=t?.entryClass,s=n&&o[n]||o.default||Object.values(o).find(i=>typeof i=="function"&&i.prototype?.buildGraph);if(!s)throw new Error("No WorkflowAgent class found in graph.mjs");return s}async function gn(){if(!process.env.NODE_PATH){process.env.NODE_PATH="/opt/zibby/packages";let g=await import("module");g.default._initPaths&&g.default._initPaths()}let e={EXECUTION_ID:process.env.EXECUTION_ID||process.env.WORKFLOW_JOB_ID||"",PROGRESS_API_URL:process.env.PROGRESS_API_URL||"",PROGRESS_QUEUE_URL:process.env.PROGRESS_QUEUE_URL||"",SQS_AUTH_TOKEN:process.env.SQS_AUTH_TOKEN||"",PROJECT_API_TOKEN:process.env.PROJECT_API_TOKEN||""},t=Ge({reportProgressFn:de,state:e});await br();let{WORKFLOW_JOB_ID:r,WORKFLOW_TYPE:o,PROJECT_ID:n,AGENT_TYPE:s,MODEL:i}=process.env;o||(console.error("Missing WORKFLOW_TYPE env var"),process.exit(1));let f=process.env.WORKFLOW_BUNDLE_URL,a,l={},c,p;if(f){c=o,a=D(V,".zibby","workflows",c);try{await Pr(f,a);try{let g=await Tt();l=g.input||{},p=g.version}catch{}}catch(g){console.warn(`[setup] Bundle extract failed (${g.message}); falling back to source install`),a=null}}if(!a){let g=await Tt(),{sources:E,input:T,workflowType:A,version:P}=g;l=T||{},c=A||o,p=P,console.log(`[setup] Workflow v${p||"?"} (${Object.keys(E).length} files)`),a=D(V,".zibby","workflows",c);let L=vr(E,a);console.log(`[setup] Wrote ${L} files`),console.log("[setup] Installing dependencies...");let v=Date.now();try{await new Promise((Lt,ve)=>{let Z=Ie("npm",["install","--silent","--no-audit","--no-fund"],{cwd:a,stdio:["ignore","pipe","pipe"]}),be=(k,De)=>{let ee="";k.on("data",te=>{ee+=te.toString();let Le=ee.split(`
52
+ `);ee=Le.pop()||"";for(let kt of Le){let ke=kt.replace(/\r/g,"").trimEnd();ke&&De(ke)}}),k.on("end",()=>{let te=ee.replace(/\r/g,"").trimEnd();te&&De(te)})};be(Z.stdout,k=>console.log(`[npm] ${k}`)),be(Z.stderr,k=>console.warn(`[npm] ${k}`)),Z.on("error",ve),Z.on("close",k=>{k===0?Lt():ve(new Error(`npm install exited with code ${k}`))})});let H=((Date.now()-v)/1e3).toFixed(1);console.log(`[setup] Dependencies installed (${H}s)`)}catch(H){console.warn(`[setup] npm install failed: ${H.message}`)}}let d={},R=D(a,"workflow.json");G(R)&&(d=JSON.parse(Ot(R,"utf-8")));let S={},I=D(a,"zibby.config.json");if(G(I))try{S=JSON.parse(Ot(I,"utf-8")),console.log("[setup] Loaded user config from zibby.config.json")}catch(g){console.warn(`[setup] Failed to parse zibby.config.json: ${g.message} \u2014 falling back to defaults`)}let _=We(V,S);_.written?console.log(`[setup] Materialized playwright.config.js \u2192 ${_.path} (${_.reason})`):_.path&&console.log(`[setup] Using existing playwright config: ${_.path}`);let w=Ar(S)||s,u=await Dr();console.log(ze({workflowType:o,jobId:r,projectId:n,agentType:w,model:i,egressIp:u.ip,egressKind:u.kind}));let h=await Lr(a,d);console.log(`[setup] Loaded ${h.name}`);let x=[],m=D(a,"node_modules","@zibby","agent-workflow"),O=D(a,"node_modules","@zibby","core","node_modules","@zibby","agent-workflow");G(m)&&x.push({kind:"hoisted",path:m}),G(O)&&x.push({kind:"nested",path:O});let b=process.env.ZIBBY_RUN_DIAG==="1";if(b){let{readdirSync:g}=await import("fs");console.log(` [diag] @zibby/agent-workflow copies in bundle: ${x.length}`);for(let E of x)console.log(` [diag] ${E.kind}: ${E.path}`);try{let E=D(a,"node_modules","@zibby");G(E)&&console.log(` [diag] node_modules/@zibby/ contents: [${g(E).join(", ")}]`)}catch{}}let K=D(a,"node_modules","@zibby","core","dist","index.js");if(G(K)&&x.length>0)try{let g=await import(Oe(K).href),E=[g.AssistantStrategy,g.CursorAgentStrategy,g.ClaudeAgentStrategy,g.CodexAgentStrategy,g.GeminiAgentStrategy].filter(Boolean);for(let T of x){let A=D(T.path,"dist","index.js");if(!G(A))continue;let P=await import(Oe(A).href),L=b?P.listStrategies():null;for(let v of E)try{P.registerStrategy(new v)}catch(H){console.warn(` register ${v.name} into ${T.kind} failed: ${H.message}`)}b&&console.log(` [diag] ${T.kind} registry: before=[${L.join(",")||"empty"}] after=[${P.listStrategies().join(",")||"empty"}]`)}console.log("[setup] Registered 5 agent strategies (assistant, cursor, claude, codex, gemini)")}catch(g){console.warn(`[setup] Failed to bridge strategies: ${g.message}`)}else console.warn("[setup] No @zibby/core or @zibby/agent-workflow in bundle \u2014 agent strategies may be unavailable");let At=Date.now(),Te=new h({workflow:c||o}),ce=Te.buildGraph(),vt=Fe(de,je);Array.isArray(ce.middleware)?ce.middleware.push(vt):console.warn("[run] graph.middleware not an array \u2014 per-node progress reporting disabled for this run");let W=process.env.WORKFLOW_UUID||null,X=process.env.ZIBBY_CONVERSATION_ID||null,le=!1;if(W&&X)try{let{v5:g}=await Promise.resolve().then(()=>(yt(),St)),E=g(`${W}:${X}`,"6ba7b810-9dad-11d1-80b4-00c04fd430c8"),T=(process.env.PROGRESS_API_URL||process.env.ZIBBY_API_BASE||"").replace(/\/executions\/?$/,"").replace(/\/+$/,""),A=process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_SDK_DEBUG==="1"&&console.log(`[session-preflight] sessionId=${E} apiUrl=${T?"set":"unset"} apiKey=${A?"set":"unset"}`),T&&A){let P=`${T}/workflows/${encodeURIComponent(W)}/sessions/${encodeURIComponent(E)}`,L=await fetch(P,{method:"GET",headers:{Authorization:`Bearer ${A}`}});if(process.env.ZIBBY_SDK_DEBUG==="1"&&console.log(`[session-preflight] GET ${P} \u2192 HTTP ${L.status}`),L.ok){let v=await L.json().catch(()=>({}));le=Array.isArray(v?.entries)&&v.entries.length>0,process.env.ZIBBY_SDK_DEBUG==="1"&&console.log(`[session-preflight] hasPriorSession=${le} entries=${v?.entries?.length??"n/a"}`)}}}catch(g){process.env.ZIBBY_SDK_DEBUG==="1"&&console.log(`[session-preflight] threw: ${g.message}`)}let fe=null;try{process.env.REPOS&&(fe=JSON.parse(process.env.REPOS))}catch{}let bt={...l||{},cwd:V,runId:r||`run-${Date.now()}`,config:S,input:l||{},...W?{workflowUuid:W}:{},...X?{conversationId:X}:{},...le?{hasPriorSession:!0}:{},workspace:V,...fe?{repos:fe}:{},...process.env.GITHUB_TOKEN?{githubToken:process.env.GITHUB_TOKEN}:{},EXECUTION_ID:process.env.EXECUTION_ID||r||"",PROGRESS_API_URL:process.env.PROGRESS_API_URL||"",PROGRESS_QUEUE_URL:process.env.PROGRESS_QUEUE_URL||"",SQS_AUTH_TOKEN:process.env.SQS_AUTH_TOKEN||"",PROJECT_API_TOKEN:process.env.PROJECT_API_TOKEN||""};await t.finalize(),console.log("");let z;try{z=await ce.run(Te,bt)}catch(g){console.error(`
53
+ Workflow execution failed: ${g.message}`),console.error(g.stack),await Ue("failed",g.message),process.exit(1)}let Pe=((Date.now()-At)/1e3).toFixed(1),Dt=z?.success!==!1,Ae=c||o;if(process.env.UPLOAD_ARTIFACTS!=="0"){let g=z?.state?.sessionPath,E=process.env.PROGRESS_API_URL||process.env.ZIBBY_API_BASE,T=process.env.PROJECT_API_TOKEN,A=process.env.WORKFLOW_JOB_ID;if(g&&E&&T&&A)try{let{uploadSessionArtifacts:P}=await Promise.resolve().then(()=>(Ut(),Rt)),{uploaded:L,skipped:v}=await P({sessionPath:g,executionId:A,apiUrl:E,apiKey:T});console.log(`[artifacts] uploaded ${L.length} file(s)${v.length?`, skipped ${v.length}`:""}`)}catch(P){console.warn(`[artifacts] uploader threw: ${P.message}`)}else console.log("[artifacts] skipping upload \u2014 sessionPath/apiUrl/apiKey/executionId missing")}Dt?(console.log(`
54
+ [done] ${Ae} completed in ${Pe}s`),await Ue("completed",null,z?.state)):(console.error(`
55
+ [done] ${Ae} failed after ${Pe}s`),await Ue("failed",z?.error||"Workflow execution failed",z?.state),process.exit(1))}async function Ue(e,t=null,r=void 0){let o={EXECUTION_ID:process.env.WORKFLOW_JOB_ID,PROGRESS_API_URL:process.env.PROGRESS_API_URL,PROGRESS_QUEUE_URL:process.env.PROGRESS_QUEUE_URL,PROJECT_API_TOKEN:process.env.PROJECT_API_TOKEN,SQS_AUTH_TOKEN:process.env.SQS_AUTH_TOKEN};if(o.EXECUTION_ID)try{await Ke(o,{status:e,...t&&{error:t},...r?{finalState:r}:{}})}catch(n){console.error(`\u26A0\uFE0F Failed to report status: ${n.message}`)}}export{Ar as resolveAgentFromConfig,gn as runWorkflowCommand};
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/cli",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "description": "Zibby CLI - Test automation generator and runner",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,10 @@
1
+ import{existsSync as z,readFileSync as I}from"fs";var b="/tmp/zibby-entrypoint-setup.log",x=500;function c(p){return p.replace(/\r/g,"").trimEnd()}function v({reportProgressFn:p,state:u,entrypointLogPath:S=b}={}){if(!u||!u.EXECUTION_ID)return{finalize:async()=>{},getBuffer:()=>""};let o=[],h=0,d=!1;try{if(z(S)){let t=I(S,"utf-8");for(let r of t.split(`
2
+ `)){let s=c(r);s&&o.push(s)}}}catch{}let L=console.log,_=console.warn,j=console.error,E=process.stdout.write.bind(process.stdout),a=process.stderr.write.bind(process.stderr),g=!1,m=t=>(...r)=>{let s=r.map(n=>typeof n=="string"?n:(()=>{try{return JSON.stringify(n)}catch{return String(n)}})()).join(" ");for(let n of s.split(`
3
+ `)){let e=c(n);e&&o.push(e)}g=!0;try{t(...r)}finally{g=!1}};console.log=m(L),console.warn=m(_),console.error=m(j);let i="",l="";process.stdout.write=(t,r,s)=>{if(!g){let n=typeof t=="string"?t:t.toString();i+=n;let e=i.split(`
4
+ `);i=e.pop()||"";for(let w of e){let f=c(w);f&&o.push(f)}}return E(t,r,s)},process.stderr.write=(t,r,s)=>{if(!g){let n=typeof t=="string"?t:t.toString();l+=n;let e=l.split(`
5
+ `);l=e.pop()||"";for(let w of e){let f=c(w);f&&o.push(f)}}return a(t,r,s)};let y=setInterval(()=>{if(d)return;let t=o.join(`
6
+ `);t.length!==h&&(h=t.length,p("setup","in_progress",t,u).catch(r=>{a(`[setup-progress] flush failed: ${r.message}
7
+ `)}))},x);return y.unref&&y.unref(),{finalize:async()=>{if(d)return;d=!0,clearInterval(y),console.log=L,console.warn=_,console.error=j,process.stdout.write=E,process.stderr.write=a,i.trim()&&(o.push(c(i)),i=""),l.trim()&&(o.push(c(l)),l="");let t=o.join(`
8
+ `);if(t.length>0)try{await p("setup","in_progress",t,u)}catch(r){a(`[setup-progress] final flush failed: ${r.message}
9
+ `)}},getBuffer:()=>o.join(`
10
+ `)}}export{v as startSetupProgress};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/cli",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "description": "Zibby CLI - Test automation generator and runner",
5
5
  "type": "module",
6
6
  "bin": {