@zibby/cli 0.1.68 → 0.1.69

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,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- process.stdout.on("error",o=>{o.code}),process.stderr.on("error",o=>{o.code}),process.env.DOTENV_CONFIG_QUIET="true";import"@zibby/skills";import{Command as p}from"commander";import{initCommand as l}from"../commands/init.js";import{runCommand as m}from"../commands/run.js";import{videoCommand as u}from"../commands/video.js";import{uploadCommand as f}from"../commands/upload.js";import{ciSetupCommand as w}from"../commands/ci-setup.js";import{setupPlaywrightMcpCommand as y,setupCiCommand as g,testWithVideoCommand as h}from"../commands/setup-scripts.js";import{readFileSync as k}from"fs";import{fileURLToPath as b}from"url";import{dirname as v,join as C}from"path";import{bootstrapAgentEnv as I}from"../utils/agent-credentials.js";const P=b(import.meta.url),j=v(P),s=JSON.parse(k(C(j,"../package.json"),"utf-8")),c=`zibby v${s.version}`,i=process.argv.slice(2),S=i.includes("-h")||i.includes("--help"),_=i.includes("-v")||i.includes("-V")||i.includes("--version");_&&(console.log(c),process.exit(0));const d=i[0],x=i[1],A=["logs","uninstall"],D=d==="workflow"&&x==="list";!A.includes(d)&&!D&&console.log(`${c}
3
- `),I(process.cwd());const B=i[0]==="chat",E=["--verbose","--agent","--stream","-s"],Z=i.length>0&&i.every(o=>E.includes(o)||i[i.indexOf(o)-1]==="--agent"),O=i.length===0||B||Z;if(O&&!S){const o={},t=i.indexOf("--agent");t!==-1&&i[t+1]&&(o.agent=i[t+1]),i.includes("--verbose")&&(o.verbose=!0),(i.includes("--stream")||i.includes("-s"))&&(o.stream=!0);const{chatCommand:n}=await import("../commands/chat.js");await n(o),process.exit(0)}const e=new p;e.name("zibby").description("Zibby Test Automation - AI-powered test generation").version(s.version,"-V, --version"),e.command("init").description("Initialize a new Zibby test project (like rails new)").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("--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").action(l),e.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((o,t)=>(t.debug?process.env.ZIBBY_DEBUG="true":t.verbose&&(process.env.ZIBBY_VERBOSE="true"),m(o,t))),e.command("implement").description("Implement a Jira ticket using AI agent (runs in ECS container)").action(async(...o)=>{const{implementCommand:t}=await import("../commands/implement.js");return t(...o)}),e.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(...o)=>{const{analyzeCommand:t}=await import("../commands/analyze-graph.js");return t(...o)}),e.command("video").description("Organize test videos next to test files").action(u),e.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(f),e.command("login").description("Log in to Zibby (opens browser for authentication)").action(async()=>{const{loginCli:o}=await import("../auth/cli-login.js");await o(),process.exit(0)}),e.command("logout").description("Log out from Zibby (clears saved session)").action(async()=>{const{logoutCli:o}=await import("../auth/cli-login.js");o(),process.exit(0)}),e.command("status").description("Show current authentication status and token details").option("--json","Output in JSON format (for scripts)").action(async o=>{const{showLoginStatus:t}=await import("../auth/cli-login.js");await t(o),process.exit(0)}),e.command("list").description("List your projects and API tokens").action(async()=>{const{listProjectsCommand:o}=await import("../commands/list-projects.js");await o()}),e.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(w),e.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(o=>{const t={width:parseInt(o.viewportWidth,10)||1280,height:parseInt(o.viewportHeight,10)||720};return y({...o,viewport:t})}),e.command("setup-ci-full").description("Complete CI/CD setup from scratch").action(g),e.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(h),e.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 o=>{const{generateCommand:t}=await import("../commands/generate.js");return t(o)}),e.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 o=>{const{studioCommand:t}=await import("../commands/studio.js");return t(o)});const Y=e.command("g").description("Generate scaffolds");Y.command("workflow [name]").description("Scaffold a new custom workflow in .zibby/workflows/<name>/ (auto-generates name if omitted)").action(async o=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(o)}),e.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(o,t)=>{const{startWorkflowCommand:n}=await import("../commands/workflows/start.js");return n(o,t)}),e.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)").action(async(o,t)=>{const{deployWorkflowCommand:n}=await import("../commands/workflows/deploy.js");return n(o,t)}),e.command("trigger [workflow-name]").description("Trigger a deployed workflow to run in the cloud (interactive selection if 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("--input <json>",`Input data as JSON string (e.g., '{"key":"value"}')`).option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").action(async(o,t)=>{const{triggerWorkflowCommand:n}=await import("../commands/workflows/trigger.js");return n(o,t)}),e.command("logs [jobId]").description("Tail logs from a workflow job or all executions of a workflow").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (tails the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --tail-latest","Auto-tail newest execution (scrollable history)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--no-follow","Fetch logs once and exit (default: tail)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(o,t)=>{const{logsCommand:n}=await import("../commands/workflows/logs.js");return n(o,t)}),e.command("run-workflow").description("Run a deployed workflow from S3 sources (used by ECS containers)").action(async()=>{const{runWorkflowCommand:o}=await import("../commands/workflows/run.js");return o()});const a=e.command("memory").description("Test memory database \u2014 version-controlled knowledge from runs");a.command("stats").description("Show memory database statistics").action(async()=>{const{memoryStatsCommand:o}=await import("../commands/memory.js");return o()}),a.command("init").description("Initialize the memory database (Dolt)").action(async()=>{const{memoryInitCommand:o}=await import("../commands/memory.js");return o()}),a.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 o=>{const{memoryCompactCommand:t}=await import("../commands/memory.js");return t(o)}),a.command("reset").description("Wipe the memory database").option("-f, --force","Confirm reset").action(async o=>{const{memoryResetCommand:t}=await import("../commands/memory.js");return t(o)});const r=e.command("workflow").description("Manage workflow graphs (download, upload, list)");r.command("download").description("Download a workflow graph from Zibby Cloud to .zibby/").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--type <type>","Workflow type: analysis, implementation, run_test").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--output <dir>","Output directory (default: .zibby/)").option("--include-default","Download the built-in default graph if no custom one exists").action(async o=>{const{workflowDownloadCommand:t}=await import("../commands/workflow.js");return t(o)}),r.command("list").description("List all workflows (local + remote if credentials available)").option("--local-only","Show only local workflows").option("--remote-only","Show only remote workflows (requires --project)").option("--project <id>","Project ID (optional, uses ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async o=>{if(o.remoteOnly){const{workflowListCommand:n}=await import("../commands/workflow.js");return n(o)}if(o.localOnly){const{listLocalWorkflowsCommand:n}=await import("../commands/workflows/list.js");return n(o)}const{listAllWorkflowsCommand:t}=await import("../commands/workflows/list.js");return t(o)}),r.command("delete <uuid>").description("Delete a deployed workflow by UUID").action(async o=>{const{deleteWorkflowCommand:t}=await import("../commands/workflows/delete.js");return t(o,{})});const R=e.command("project").description("Manage Zibby projects");R.command("list").description("List all projects").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async o=>{const{projectListCommand:t}=await import("../commands/project.js");return t(o)});const z=e.command("run-queue").description("Parallel capacity \u2014 on-disk wait queue (see parallel.waitWhenAtCapacity in .zibby.config.mjs)");z.command("list").description("List CLI processes waiting for a run slot").option("--config <path>","Path to config file",".zibby.config.mjs").action(async o=>{const{runCapacityQueueListCommand:t}=await import("../commands/run-capacity-queue-cli.js");await t(o),process.exit(0)}),e.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 o=>{const{uninstallCommand:t}=await import("../commands/uninstall.js");await t(o),process.exit(0)}),e.parse();
2
+ process.stdout.on("error",o=>{o.code}),process.stderr.on("error",o=>{o.code}),process.env.DOTENV_CONFIG_QUIET="true";import"@zibby/skills";import{Command as p}from"commander";import{initCommand as l}from"../commands/init.js";import{runCommand as m}from"../commands/run.js";import{videoCommand as u}from"../commands/video.js";import{uploadCommand as f}from"../commands/upload.js";import{ciSetupCommand as w}from"../commands/ci-setup.js";import{setupPlaywrightMcpCommand as y,setupCiCommand as g,testWithVideoCommand as k}from"../commands/setup-scripts.js";import{readFileSync as h}from"fs";import{fileURLToPath as b}from"url";import{dirname as v,join as C}from"path";import{bootstrapAgentEnv as I}from"../utils/agent-credentials.js";const P=b(import.meta.url),S=v(P),s=JSON.parse(h(C(S,"../package.json"),"utf-8")),c=`zibby v${s.version}`,i=process.argv.slice(2),j=i.includes("-h")||i.includes("--help"),_=i.includes("-v")||i.includes("-V")||i.includes("--version");_&&(console.log(c),process.exit(0));const d=i[0],D=i[1],A=["logs","uninstall"],B=d==="workflow"&&D==="list";!A.includes(d)&&!B&&console.log(`${c}
3
+ `),I(process.cwd());const E=i[0]==="chat",x=["--verbose","--agent","--stream","-s"],Z=i.length>0&&i.every(o=>x.includes(o)||i[i.indexOf(o)-1]==="--agent"),O=i.length===0||E||Z;if(O&&!j){const o={},t=i.indexOf("--agent");t!==-1&&i[t+1]&&(o.agent=i[t+1]),i.includes("--verbose")&&(o.verbose=!0),(i.includes("--stream")||i.includes("-s"))&&(o.stream=!0);const{chatCommand:n}=await import("../commands/chat.js");await n(o),process.exit(0)}const e=new p;e.name("zibby").description("Zibby Test Automation - AI-powered test generation").version(s.version,"-V, --version"),e.command("init").description("Initialize a new Zibby test project (like rails new)").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("--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").action(l),e.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((o,t)=>(t.debug?process.env.ZIBBY_DEBUG="true":t.verbose&&(process.env.ZIBBY_VERBOSE="true"),m(o,t))),e.command("implement").description("Implement a Jira ticket using AI agent (runs in ECS container)").action(async(...o)=>{const{implementCommand:t}=await import("../commands/implement.js");return t(...o)}),e.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(...o)=>{const{analyzeCommand:t}=await import("../commands/analyze-graph.js");return t(...o)}),e.command("video").description("Organize test videos next to test files").action(u),e.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(f),e.command("login").description("Log in to Zibby (opens browser for authentication)").action(async()=>{const{loginCli:o}=await import("../auth/cli-login.js");await o(),process.exit(0)}),e.command("logout").description("Log out from Zibby (clears saved session)").action(async()=>{const{logoutCli:o}=await import("../auth/cli-login.js");o(),process.exit(0)}),e.command("status").description("Show current authentication status and token details").option("--json","Output in JSON format (for scripts)").action(async o=>{const{showLoginStatus:t}=await import("../auth/cli-login.js");await t(o),process.exit(0)}),e.command("list").description("List your projects and API tokens").action(async()=>{const{listProjectsCommand:o}=await import("../commands/list-projects.js");await o()}),e.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(w),e.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(o=>{const t={width:parseInt(o.viewportWidth,10)||1280,height:parseInt(o.viewportHeight,10)||720};return y({...o,viewport:t})}),e.command("setup-ci-full").description("Complete CI/CD setup from scratch").action(g),e.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(k),e.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 o=>{const{generateCommand:t}=await import("../commands/generate.js");return t(o)}),e.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 o=>{const{studioCommand:t}=await import("../commands/studio.js");return t(o)});const Y=e.command("g").description("Generate scaffolds");Y.command("workflow [name]").description("Scaffold a new custom workflow in .zibby/workflows/<name>/ (auto-generates name if omitted)").action(async o=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(o)}),e.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(o,t)=>{const{startWorkflowCommand:n}=await import("../commands/workflows/start.js");return n(o,t)}),e.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)").action(async(o,t)=>{const{deployWorkflowCommand:n}=await import("../commands/workflows/deploy.js");return n(o,t)}),e.command("trigger [workflow-name]").description("Trigger a deployed workflow to run in the cloud (interactive selection if 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("--input <json>",`Input data as JSON string (e.g., '{"key":"value"}')`).option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").action(async(o,t)=>{const{triggerWorkflowCommand:n}=await import("../commands/workflows/trigger.js");return n(o,t)}),e.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(o,t)=>{const{logsCommand:n}=await import("../commands/workflows/logs.js");return n(o,t)}),e.command("run-workflow").description("Run a deployed workflow from S3 sources (used by ECS containers)").action(async()=>{const{runWorkflowCommand:o}=await import("../commands/workflows/run.js");return o()});const a=e.command("memory").description("Test memory database \u2014 version-controlled knowledge from runs");a.command("stats").description("Show memory database statistics").action(async()=>{const{memoryStatsCommand:o}=await import("../commands/memory.js");return o()}),a.command("init").description("Initialize the memory database (Dolt)").action(async()=>{const{memoryInitCommand:o}=await import("../commands/memory.js");return o()}),a.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 o=>{const{memoryCompactCommand:t}=await import("../commands/memory.js");return t(o)}),a.command("reset").description("Wipe the memory database").option("-f, --force","Confirm reset").action(async o=>{const{memoryResetCommand:t}=await import("../commands/memory.js");return t(o)});const r=e.command("workflow").description("Manage workflow graphs (download, upload, list)");r.command("download").description("Download a workflow graph from Zibby Cloud to .zibby/").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--type <type>","Workflow type: analysis, implementation, run_test").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--output <dir>","Output directory (default: .zibby/)").option("--include-default","Download the built-in default graph if no custom one exists").action(async o=>{const{workflowDownloadCommand:t}=await import("../commands/workflow.js");return t(o)}),r.command("list").description("List all workflows (local + remote if credentials available)").option("--local-only","Show only local workflows").option("--remote-only","Show only remote workflows (requires --project)").option("--project <id>","Project ID (optional, uses ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async o=>{if(o.remoteOnly){const{workflowListCommand:n}=await import("../commands/workflow.js");return n(o)}if(o.localOnly){const{listLocalWorkflowsCommand:n}=await import("../commands/workflows/list.js");return n(o)}const{listAllWorkflowsCommand:t}=await import("../commands/workflows/list.js");return t(o)}),r.command("delete <uuid>").description("Delete a deployed workflow by UUID").action(async o=>{const{deleteWorkflowCommand:t}=await import("../commands/workflows/delete.js");return t(o,{})});const R=e.command("project").description("Manage Zibby projects");R.command("list").description("List all projects").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async o=>{const{projectListCommand:t}=await import("../commands/project.js");return t(o)});const z=e.command("run-queue").description("Parallel capacity \u2014 on-disk wait queue (see parallel.waitWhenAtCapacity in .zibby.config.mjs)");z.command("list").description("List CLI processes waiting for a run slot").option("--config <path>","Path to config file",".zibby.config.mjs").action(async o=>{const{runCapacityQueueListCommand:t}=await import("../commands/run-capacity-queue-cli.js");await t(o),process.exit(0)}),e.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 o=>{const{uninstallCommand:t}=await import("../commands/uninstall.js");await t(o),process.exit(0)}),e.parse();
@@ -1,46 +1,46 @@
1
- var dn=Object.defineProperty;var mn=(e,t)=>()=>(e&&(t=e(e=0)),t);var gn=(e,t)=>{for(var n in t)dn(e,n,{get:t[n],enumerable:!0})};var se={};gn(se,{cleanupStalePidFiles:()=>Mn,killAllChatOrchestratedRuns:()=>On,killPidTreeBestEffort:()=>We,registerChatOrchestratedRun:()=>Ln,unregisterChatOrchestratedRun:()=>Bn});import{existsSync as ee,mkdirSync as Tn,readFileSync as Pn,readdirSync as Cn,unlinkSync as ne,writeFileSync as ze}from"fs";import{join as Ft}from"path";import{execSync as He}from"child_process";import{DEFAULT_OUTPUT_BASE as Nn}from"@zibby/core";function Mt(e){return e?.paths?.output||Nn}function jt(e,t,n){return Ft(e,t,`.zibby-chat-run-pids-${n}.json`)}function oe(e,t,n){let s=jt(e,t,n);if(!ee(s))return[];try{let r=JSON.parse(Pn(s,"utf8"));return(Array.isArray(r?.pids)?r.pids:[]).map(l=>Number(l)).filter(l=>Number.isFinite(l)&&l>0)}catch{return[]}}function Ln(e,t,n,s={}){let r=Number(t),c=Number(n);if(!Number.isFinite(r)||r<=0||!Number.isFinite(c)||c<=0)return;let l=Mt(s),d=Ft(e,l);Tn(d,{recursive:!0});let y=oe(e,l,r);y.includes(c)||y.push(c),ze(jt(e,l,r),`${JSON.stringify({v:1,pids:y})}
2
- `,"utf8")}function Bn(e,t,n,s={}){let r=Number(t),c=Number(n);if(!Number.isFinite(r)||r<=0||!Number.isFinite(c)||c<=0)return;let l=Mt(s),d=jt(e,l,r);if(!ee(d))return;let y=oe(e,l,r).filter(L=>L!==c);if(y.length===0)try{ne(d)}catch{}else ze(d,`${JSON.stringify({v:1,pids:y})}
3
- `,"utf8")}function En(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)return[];try{let n=He(`pgrep -P ${t}`,{encoding:"utf8",stdio:["ignore","pipe","ignore"],maxBuffer:524288}).trim();return n?n.split(/\n/).map(s=>parseInt(s.trim(),10)).filter(s=>Number.isFinite(s)&&s>0):[]}catch{return[]}}function Ye(e,t){let n=Number(e);if(!Number.isFinite(n)||n<=0)return;let s=new Set;function r(c){if(!s.has(c)){s.add(c);for(let l of En(c))r(l);try{process.kill(c,t)}catch{}}}r(n)}function Rn(e){let t=Number(e);if(!(!Number.isFinite(t)||t<=0))try{He(`taskkill /PID ${t} /T /F`,{stdio:"ignore",windowsHide:!0})}catch{}}function We(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)return;if(process.platform==="win32"){Rn(t);return}Ye(t,"SIGTERM");let n=setTimeout(()=>{Ye(t,"SIGKILL")},800);typeof n.unref=="function"&&n.unref()}function On(e,t,n={}){let s=Number(t);if(!Number.isFinite(s)||s<=0)return;let r=Mt(n),c=jt(e,r,s),l=oe(e,r,s);for(let d of l)d!==process.pid&&We(d);try{ee(c)&&ne(c)}catch{}}function Un(e){try{return process.kill(e,0),!0}catch{return!1}}function Mn(e,t={}){let n=Mt(t),s=Ft(e,n),r;try{r=Cn(s)}catch{return}for(let c of r){let l=Fn.exec(c);if(!l)continue;let d=Number(l[1]);if(!(!Number.isFinite(d)||d<=0)&&!Un(d))try{ne(Ft(s,c))}catch{}}}var Fn,re=mn(()=>{Fn=/^\.zibby-chat-run-pids-(\d+)\.json$/});import{invokeAgent as jn,getAgentStrategy as Dn,getSkill as Pt}from"@zibby/core";import{existsSync as yt,readFileSync as Xe,readdirSync as Yn}from"fs";import{resolve as ft,join as ce,dirname as zn,basename as Hn}from"path";import{createInterface as Wn,moveCursor as E,cursorTo as U,clearLine as G,emitKeypressEvents as Zn}from"readline";import{fileURLToPath as Jn}from"url";import{homedir as Gn}from"os";import o from"chalk";import{highlight as Ze}from"cli-highlight";import Vn from"dotenv";import{existsSync as xe,mkdirSync as hn,readFileSync as yn,writeFileSync as bn}from"fs";import{homedir as ke}from"os";import{join as Rt}from"path";function _e(){return process.env.ZIBBY_CONFIG_DIR||Rt(ke(),".zibby")}function ve(){return Rt(_e(),"config.json")}var wn=Rt(ke(),".zibby"),Eo=Rt(wn,"config.json");function Sn(){let e=_e();xe(e)||hn(e,{recursive:!0})}function X(){try{let e=ve();if(xe(e)){let t=yn(e,"utf-8");return JSON.parse(t)}}catch{}return{}}function vt(e){Sn(),bn(ve(),JSON.stringify(e,null,2))}function Ot(){return X().sessionToken||null}function $e(e){let t=X();t.sessionToken=e,vt(t)}function Ie(){return X().user||null}function Ae(e){let t=X();t.user=e,vt(t)}function Te(){let e=X();delete e.sessionToken,delete e.user,delete e.mem0ProxyUrl,vt(e)}function Pe(){return X().proxyUrl||null}function Ce(e){let t=X();t.proxyUrl=e,vt(t)}function Ne(){return X().mem0ProxyUrl||null}function Le(e){let t=X();t.mem0ProxyUrl=e,vt(t)}function Be(){return X().projects||[]}var $t={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.app",description:"Production environment"}};function Xt(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let t=process.env.ZIBBY_ENV||"prod";$t[t]?e=$t[t].apiUrl:e=$t.prod.apiUrl}try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${t.protocol} (only http/https allowed)`),$t.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),$t.prod.apiUrl}}import{existsSync as Qt,mkdirSync as xn,readFileSync as Ee,writeFileSync as Re,unlinkSync as Fo}from"fs";import{resolve as It}from"path";import{homedir as Do}from"os";var kn=30;function Oe(e){let t=It(e,".zibby","output");return Qt(t)||xn(t,{recursive:!0}),t}function Ue(e){let t=It(e,".zibby","output","chat-history.json");if(!Qt(t))return[];try{let n=JSON.parse(Ee(t,"utf-8"));return Array.isArray(n)?n:[]}catch{return[]}}function At(e,t){let n=Oe(e),s=It(n,"chat-history.json");try{Re(s,JSON.stringify((t||[]).slice(-kn*2),null,2),"utf-8")}catch{}}function Fe(e){let t=It(e,".zibby","output","active-skills.json");if(!Qt(t))return null;try{let n=JSON.parse(Ee(t,"utf-8"));return Array.isArray(n)?n:null}catch{return null}}function Tt(e,t){let n=Oe(e),s=It(n,"active-skills.json");try{Re(s,JSON.stringify(Array.isArray(t)?t:[]),"utf-8")}catch{}}var te={cli_reliable_v1:{title:"General intelligence reliability contract",operatingRules:["Evidence-first reasoning: ground conclusions in observed outputs or tool evidence, not guesses.","No false completion: never claim success for a state-changing action until verification confirms it.","Execution integrity: do not claim any external action unless the matching tool call actually happened.","Bounded recovery: for transient failures, retry with adjusted parameters up to 2 times, then escalate with blocker + next step.",'Binary-answer discipline: for yes/no questions, verify the exact asked condition before answering; do not answer "yes" from a broader or approximate match.'],executionSafety:["Prefer low-blast-radius, reversible actions first.","Before irreversible or high-impact actions, confirm explicit user intent unless already authorized.","If verification cannot be run, state that limitation explicitly."],investigationLoop:["For unclear failures, follow this loop: detect -> gather evidence -> form hypothesis -> test hypothesis -> conclude.","If evidence is insufficient, explicitly collect more before proposing a root cause.","Prefer smallest validating action first before broad or costly retries."],responseQuality:["State assumptions explicitly when certainty is low.","Differentiate facts, hypotheses, and next actions.","Keep reports concise but decision-useful.","If related-but-not-identical matches exist, report them separately as context, not as the direct yes/no answer."],incidentTemplate:["ONLY when diagnosing failures or errors (never for successful actions), structure your response as: Root cause, Evidence, Attempted fixes, Current status, Next action."],skillRunbooks:{}}},je=2e3,Me=12e3;function Ut(e=[]){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let s of e){let r=String(s||"").replace(/\s+/g," ").trim();r&&(t.has(r)||(t.add(r),n.push(r)))}return n}function _n(e,t=je){let n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-14)).trimEnd()}
1
+ var dn=Object.defineProperty;var mn=(e,t)=>()=>(e&&(t=e(e=0)),t);var gn=(e,t)=>{for(var n in t)dn(e,n,{get:t[n],enumerable:!0})};var re={};gn(re,{cleanupStalePidFiles:()=>Mn,killAllChatOrchestratedRuns:()=>On,killPidTreeBestEffort:()=>Ze,registerChatOrchestratedRun:()=>Ln,unregisterChatOrchestratedRun:()=>Bn});import{existsSync as ne,mkdirSync as Tn,readFileSync as Pn,readdirSync as Cn,unlinkSync as oe,writeFileSync as He}from"fs";import{join as Ft}from"path";import{execSync as We}from"child_process";import{DEFAULT_OUTPUT_BASE as Nn}from"@zibby/core";function Mt(e){return e?.paths?.output||Nn}function jt(e,t,n){return Ft(e,t,`.zibby-chat-run-pids-${n}.json`)}function se(e,t,n){let s=jt(e,t,n);if(!ne(s))return[];try{let r=JSON.parse(Pn(s,"utf8"));return(Array.isArray(r?.pids)?r.pids:[]).map(l=>Number(l)).filter(l=>Number.isFinite(l)&&l>0)}catch{return[]}}function Ln(e,t,n,s={}){let r=Number(t),c=Number(n);if(!Number.isFinite(r)||r<=0||!Number.isFinite(c)||c<=0)return;let l=Mt(s),d=Ft(e,l);Tn(d,{recursive:!0});let y=se(e,l,r);y.includes(c)||y.push(c),He(jt(e,l,r),`${JSON.stringify({v:1,pids:y})}
2
+ `,"utf8")}function Bn(e,t,n,s={}){let r=Number(t),c=Number(n);if(!Number.isFinite(r)||r<=0||!Number.isFinite(c)||c<=0)return;let l=Mt(s),d=jt(e,l,r);if(!ne(d))return;let y=se(e,l,r).filter(L=>L!==c);if(y.length===0)try{oe(d)}catch{}else He(d,`${JSON.stringify({v:1,pids:y})}
3
+ `,"utf8")}function En(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)return[];try{let n=We(`pgrep -P ${t}`,{encoding:"utf8",stdio:["ignore","pipe","ignore"],maxBuffer:524288}).trim();return n?n.split(/\n/).map(s=>parseInt(s.trim(),10)).filter(s=>Number.isFinite(s)&&s>0):[]}catch{return[]}}function ze(e,t){let n=Number(e);if(!Number.isFinite(n)||n<=0)return;let s=new Set;function r(c){if(!s.has(c)){s.add(c);for(let l of En(c))r(l);try{process.kill(c,t)}catch{}}}r(n)}function Rn(e){let t=Number(e);if(!(!Number.isFinite(t)||t<=0))try{We(`taskkill /PID ${t} /T /F`,{stdio:"ignore",windowsHide:!0})}catch{}}function Ze(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)return;if(process.platform==="win32"){Rn(t);return}ze(t,"SIGTERM");let n=setTimeout(()=>{ze(t,"SIGKILL")},800);typeof n.unref=="function"&&n.unref()}function On(e,t,n={}){let s=Number(t);if(!Number.isFinite(s)||s<=0)return;let r=Mt(n),c=jt(e,r,s),l=se(e,r,s);for(let d of l)d!==process.pid&&Ze(d);try{ne(c)&&oe(c)}catch{}}function Un(e){try{return process.kill(e,0),!0}catch{return!1}}function Mn(e,t={}){let n=Mt(t),s=Ft(e,n),r;try{r=Cn(s)}catch{return}for(let c of r){let l=Fn.exec(c);if(!l)continue;let d=Number(l[1]);if(!(!Number.isFinite(d)||d<=0)&&!Un(d))try{oe(Ft(s,c))}catch{}}}var Fn,ie=mn(()=>{Fn=/^\.zibby-chat-run-pids-(\d+)\.json$/});import{invokeAgent as jn,getAgentStrategy as Dn}from"@zibby/core";import{getSkill as Pt}from"@zibby/skills";import{existsSync as yt,readFileSync as Qe,readdirSync as Yn}from"fs";import{resolve as ft,join as le,dirname as zn,basename as Hn}from"path";import{createInterface as Wn,moveCursor as E,cursorTo as U,clearLine as G,emitKeypressEvents as Zn}from"readline";import{fileURLToPath as Jn}from"url";import{homedir as Gn}from"os";import o from"chalk";import{highlight as Je}from"cli-highlight";import Vn from"dotenv";import{existsSync as ke,mkdirSync as hn,readFileSync as yn,writeFileSync as bn}from"fs";import{homedir as _e}from"os";import{join as Rt}from"path";function ve(){return process.env.ZIBBY_CONFIG_DIR||Rt(_e(),".zibby")}function $e(){return Rt(ve(),"config.json")}var wn=Rt(_e(),".zibby"),Eo=Rt(wn,"config.json");function Sn(){let e=ve();ke(e)||hn(e,{recursive:!0})}function X(){try{let e=$e();if(ke(e)){let t=yn(e,"utf-8");return JSON.parse(t)}}catch{}return{}}function vt(e){Sn(),bn($e(),JSON.stringify(e,null,2))}function Ot(){return X().sessionToken||null}function Ie(e){let t=X();t.sessionToken=e,vt(t)}function Ae(){return X().user||null}function Te(e){let t=X();t.user=e,vt(t)}function Pe(){let e=X();delete e.sessionToken,delete e.user,delete e.mem0ProxyUrl,vt(e)}function Ce(){return X().proxyUrl||null}function Ne(e){let t=X();t.proxyUrl=e,vt(t)}function Le(){return X().mem0ProxyUrl||null}function Be(e){let t=X();t.mem0ProxyUrl=e,vt(t)}function Ee(){return X().projects||[]}var $t={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.app",description:"Production environment"}};function Qt(){let e;if(process.env.ZIBBY_API_URL)e=process.env.ZIBBY_API_URL;else{let t=process.env.ZIBBY_ENV||"prod";$t[t]?e=$t[t].apiUrl:e=$t.prod.apiUrl}try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${t.protocol} (only http/https allowed)`),$t.prod.apiUrl):e}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${e}`),$t.prod.apiUrl}}import{existsSync as te,mkdirSync as xn,readFileSync as Re,writeFileSync as Oe,unlinkSync as Fo}from"fs";import{resolve as It}from"path";import{homedir as Do}from"os";var kn=30;function Ue(e){let t=It(e,".zibby","output");return te(t)||xn(t,{recursive:!0}),t}function Fe(e){let t=It(e,".zibby","output","chat-history.json");if(!te(t))return[];try{let n=JSON.parse(Re(t,"utf-8"));return Array.isArray(n)?n:[]}catch{return[]}}function At(e,t){let n=Ue(e),s=It(n,"chat-history.json");try{Oe(s,JSON.stringify((t||[]).slice(-kn*2),null,2),"utf-8")}catch{}}function Me(e){let t=It(e,".zibby","output","active-skills.json");if(!te(t))return null;try{let n=JSON.parse(Re(t,"utf-8"));return Array.isArray(n)?n:null}catch{return null}}function Tt(e,t){let n=Ue(e),s=It(n,"active-skills.json");try{Oe(s,JSON.stringify(Array.isArray(t)?t:[]),"utf-8")}catch{}}var ee={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:{}}},De=2e3,je=12e3;function Ut(e=[]){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let s of e){let r=String(s||"").replace(/\s+/g," ").trim();r&&(t.has(r)||(t.add(r),n.push(r)))}return n}function _n(e,t=De){let n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-14)).trimEnd()}
4
4
 
5
- [truncated]`}function pt(e,t=[],n=je){let s=Ut(t);if(s.length===0)return"";let r=[`## ${e}`,...s.map(c=>`- ${c}`)].join(`
6
- `);return _n(r,n)}function vn(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function $n(e,t){let n={...e,...t},s=["operatingRules","rules","executionSafety","investigationLoop","responseQuality","incidentTemplate"];for(let r of s)Array.isArray(t?.[r])?n[r]=[...Ut(e?.[r]||[]),...Ut(t[r])]:Array.isArray(e?.[r])&&(n[r]=[...Ut(e[r])]);return n.skillRunbooks={...e?.skillRunbooks||{},...t?.skillRunbooks||{}},n}function In(e={},t={}){let n=Array.isArray(e?.reliabilityAppendSections)?e.reliabilityAppendSections:[],s=Array.isArray(t?.reliabilityAppendSections)?t.reliabilityAppendSections:[];return[...n,...s].map(r=>{if(typeof r=="string")return{title:"Additional reliability guidance",lines:[r]};if(!r||typeof r!="object")return null;let c=String(r.title||"Additional reliability guidance").trim(),l=Array.isArray(r.lines)?r.lines:[];return{title:c,lines:l}}).filter(Boolean)}function An(e={},t={}){let n=String(t.reliabilityProfile||process.env.ZIBBY_RELIABILITY_PROFILE||e.reliabilityProfile||"cli_reliable_v1").trim(),s=e?.reliabilityProfiles?.[n];if(typeof s=="string"&&s.trim())return{name:n,text:s.trim()};if(s&&typeof s.instruction=="string"&&s.instruction.trim())return{name:n,text:s.instruction.trim()};let r=te[n]||te.cli_reliable_v1,c=vn(s),l=c?$n(r,c):r;return{name:n,defaults:l}}function De({activeSkills:e=[],chatConfig:t={},options:n={}}={}){let s=An(t,n);if(s.text)return s.text;let r=s.defaults||te.cli_reliable_v1,c=[pt(r.title||"Reliability contract",r.operatingRules||r.rules||[]),pt("Execution safety",r.executionSafety||[]),pt("Investigation loop",r.investigationLoop||[]),pt("Response quality",r.responseQuality||[]),pt("Failure reporting format",r.incidentTemplate||[])],l=r.skillRunbooks||{};for(let L of e)l[L]&&c.push(pt(`Runbook: ${L}`,l[L]));let d=In(t,n);for(let L of d)c.push(pt(L.title,L.lines));let y=c.filter(Boolean).join(`
5
+ [truncated]`}function pt(e,t=[],n=De){let s=Ut(t);if(s.length===0)return"";let r=[`## ${e}`,...s.map(c=>`- ${c}`)].join(`
6
+ `);return _n(r,n)}function vn(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function $n(e,t){let n={...e,...t},s=["operatingRules","rules","executionSafety","investigationLoop","responseQuality","incidentTemplate"];for(let r of s)Array.isArray(t?.[r])?n[r]=[...Ut(e?.[r]||[]),...Ut(t[r])]:Array.isArray(e?.[r])&&(n[r]=[...Ut(e[r])]);return n.skillRunbooks={...e?.skillRunbooks||{},...t?.skillRunbooks||{}},n}function In(e={},t={}){let n=Array.isArray(e?.reliabilityAppendSections)?e.reliabilityAppendSections:[],s=Array.isArray(t?.reliabilityAppendSections)?t.reliabilityAppendSections:[];return[...n,...s].map(r=>{if(typeof r=="string")return{title:"Additional reliability guidance",lines:[r]};if(!r||typeof r!="object")return null;let c=String(r.title||"Additional reliability guidance").trim(),l=Array.isArray(r.lines)?r.lines:[];return{title:c,lines:l}}).filter(Boolean)}function An(e={},t={}){let n=String(t.reliabilityProfile||process.env.ZIBBY_RELIABILITY_PROFILE||e.reliabilityProfile||"cli_reliable_v1").trim(),s=e?.reliabilityProfiles?.[n];if(typeof s=="string"&&s.trim())return{name:n,text:s.trim()};if(s&&typeof s.instruction=="string"&&s.instruction.trim())return{name:n,text:s.instruction.trim()};let r=ee[n]||ee.cli_reliable_v1,c=vn(s),l=c?$n(r,c):r;return{name:n,defaults:l}}function Ye({activeSkills:e=[],chatConfig:t={},options:n={}}={}){let s=An(t,n);if(s.text)return s.text;let r=s.defaults||ee.cli_reliable_v1,c=[pt(r.title||"Reliability contract",r.operatingRules||r.rules||[]),pt("Execution safety",r.executionSafety||[]),pt("Investigation loop",r.investigationLoop||[]),pt("Response quality",r.responseQuality||[]),pt("Failure reporting format",r.incidentTemplate||[])],l=r.skillRunbooks||{};for(let L of e)l[L]&&c.push(pt(`Runbook: ${L}`,l[L]));let d=In(t,n);for(let L of d)c.push(pt(L.title,L.lines));let y=c.filter(Boolean).join(`
7
7
 
8
- `).trim();return y.length<=Me?y:`${y.slice(0,Math.max(0,Me-14)).trimEnd()}
8
+ `).trim();return y.length<=je?y:`${y.slice(0,Math.max(0,je-14)).trimEnd()}
9
9
 
10
- [truncated]`}var qn=Jn(import.meta.url),Kn=zn(qn),Xn=JSON.parse(Xe(ce(Kn,"../../package.json"),"utf-8")),Qe=30,Qn=54,to=18e3,tn=12e3,Je=42e3;function eo(e){return new Promise(t=>setTimeout(t,e))}var Dt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],ae=[{cmd:"/help",desc:"Show this help"},{cmd:"/skills",desc:"List active & available skills"},{cmd:"/history",desc:"Show conversation history (--all or -n 50)"},{cmd:"/clear",desc:"Clear conversation history"},{cmd:"/memory",desc:"View stored memories, tasks, sessions"},{cmd:"/exit",desc:"Exit the chat"},{cmd:"/quit",desc:"Exit the chat"}];function Ge(){let e=0,t="thinking...",n=setInterval(()=>{let r=o.cyan(Dt[e%Dt.length]),c=e%3,l=c===0?o.white(".")+o.gray(".")+o.dim("."):c===1?o.dim(".")+o.white(".")+o.gray("."):o.gray(".")+o.dim(".")+o.white("."),d=t.replace(/\.+$/,""),y=` ${r} ${o.gray(d)}${l}`;process.stdout.write(`\r${" ".repeat(80)}\r${y}`),e++},300),s=()=>{clearInterval(n),process.stdout.write(`\r${" ".repeat(80)}\r`)};return s.setLabel=r=>{t=r},s}function cs(e){let t=e?.agent;return t?t.provider?t.provider:t.gemini?"gemini":t.codex?"codex":t.claude?"claude":t.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}function no(e){return e.slice(-Qe).map(t=>`${t.role==="human"?"H":"AI"}: ${t.content}`).join(`
11
- `)}function ls(e,t,n){let s=e;return t.length>0&&(s+=`
10
+ [truncated]`}var qn=Jn(import.meta.url),Kn=zn(qn),Xn=JSON.parse(Qe(le(Kn,"../../package.json"),"utf-8")),tn=30,Qn=54,to=18e3,en=12e3,Ge=42e3;function eo(e){return new Promise(t=>setTimeout(t,e))}var Dt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],ue=[{cmd:"/help",desc:"Show this help"},{cmd:"/skills",desc:"List active & available skills"},{cmd:"/history",desc:"Show conversation history (--all or -n 50)"},{cmd:"/clear",desc:"Clear conversation history"},{cmd:"/memory",desc:"View stored memories, tasks, sessions"},{cmd:"/exit",desc:"Exit the chat"},{cmd:"/quit",desc:"Exit the chat"}];function Ve(){let e=0,t="thinking...",n=setInterval(()=>{let r=o.cyan(Dt[e%Dt.length]),c=e%3,l=c===0?o.white(".")+o.gray(".")+o.dim("."):c===1?o.dim(".")+o.white(".")+o.gray("."):o.gray(".")+o.dim(".")+o.white("."),d=t.replace(/\.+$/,""),y=` ${r} ${o.gray(d)}${l}`;process.stdout.write(`\r${" ".repeat(80)}\r${y}`),e++},300),s=()=>{clearInterval(n),process.stdout.write(`\r${" ".repeat(80)}\r`)};return s.setLabel=r=>{t=r},s}function ls(e){let t=e?.agent;return t?t.provider?t.provider:t.gemini?"gemini":t.codex?"codex":t.claude?"claude":t.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}function no(e){return e.slice(-tn).map(t=>`${t.role==="human"?"H":"AI"}: ${t.content}`).join(`
11
+ `)}function as(e,t,n){let s=e;return t.length>0&&(s+=`
12
12
 
13
13
  ${no(t)}`),s+=`
14
14
  H: ${n}
15
- AI:`,s}function oo(e){let t=e.filter(n=>!process.env[n]);return{ok:t.length===0,missing:t}}function so(e){let t=ft(e,".zibby.config.mjs");if(!yt(t))return{};try{return import(t).then(n=>n.default||{})}catch{return{}}}async function ro(e){let t=ft(e,".zibby","chat.mjs");if(yt(t)){let r=await import(t);if(r.CHAT_CONFIG||r.default)return r.CHAT_CONFIG||r.default}let n=ft(Gn(),".zibby","chat.mjs");if(n!==t&&yt(n)){let r=await import(n);if(r.CHAT_CONFIG||r.default)return r.CHAT_CONFIG||r.default}let s=await import("@zibby/core/templates/browser-test-automation/chat.mjs");return s.CHAT_CONFIG||s.default||{}}function Ve(e){try{let t=ft(e,".zibby","commands");return yt(t)?Yn(t).filter(n=>n.toLowerCase().endsWith(".md")).sort((n,s)=>n.localeCompare(s)):[]}catch{return[]}}function io(e,t){let n=String(t||"").trim();if(!n.startsWith("/"))return n;let[s,...r]=n.split(/\s+/),c=r.join(" ").trim(),l=s.slice(1);if(!l)return n;let d=l.toLowerCase().endsWith(".md")?[l]:[l,`${l}.md`],y=ft(e,".zibby","commands"),L=d.find(F=>yt(ce(y,F)));if(!L)return n;try{let F=Xe(ce(y,L),"utf-8").trim();return c?`${F}
15
+ AI:`,s}function oo(e){let t=e.filter(n=>!process.env[n]);return{ok:t.length===0,missing:t}}function so(e){let t=ft(e,".zibby.config.mjs");if(!yt(t))return{};try{return import(t).then(n=>n.default||{})}catch{return{}}}async function ro(e){let t=ft(e,".zibby","chat.mjs");if(yt(t)){let r=await import(t);if(r.CHAT_CONFIG||r.default)return r.CHAT_CONFIG||r.default}let n=ft(Gn(),".zibby","chat.mjs");if(n!==t&&yt(n)){let r=await import(n);if(r.CHAT_CONFIG||r.default)return r.CHAT_CONFIG||r.default}let s=await import("@zibby/core/templates/browser-test-automation/chat.mjs");return s.CHAT_CONFIG||s.default||{}}function qe(e){try{let t=ft(e,".zibby","commands");return yt(t)?Yn(t).filter(n=>n.toLowerCase().endsWith(".md")).sort((n,s)=>n.localeCompare(s)):[]}catch{return[]}}function io(e,t){let n=String(t||"").trim();if(!n.startsWith("/"))return n;let[s,...r]=n.split(/\s+/),c=r.join(" ").trim(),l=s.slice(1);if(!l)return n;let d=l.toLowerCase().endsWith(".md")?[l]:[l,`${l}.md`],y=ft(e,".zibby","commands"),L=d.find(F=>yt(le(y,F)));if(!L)return n;try{let F=Qe(le(y,L),"utf-8").trim();return c?`${F}
16
16
 
17
- ${c}`:F}catch{return n}}function co(e){let t=e.slice(-Qe),n=[],s=0;for(let r=t.length-1;r>=0;r--){let c=t[r],l=String(c?.content||""),d=c?.role==="human"?"user":"assistant",y=l.length;if(n.length>=6&&s+y>to)break;n.push({role:d,content:l}),s+=y}return n.reverse()}function Ct(e,t){let n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-24))}
17
+ ${c}`:F}catch{return n}}function co(e){let t=e.slice(-tn),n=[],s=0;for(let r=t.length-1;r>=0;r--){let c=t[r],l=String(c?.content||""),d=c?.role==="human"?"user":"assistant",y=l.length;if(n.length>=6&&s+y>to)break;n.push({role:d,content:l}),s+=y}return n.reverse()}function Ct(e,t){let n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-24))}
18
18
 
19
- [truncated for proxy size]`}function le(e){return e.reduce((t,n)=>t+String(n?.content||"").length+64,0)}function lo(e){let t=[...e];if(t.length===0||(t[0]?.role==="system"&&(t[0]={...t[0],content:Ct(t[0].content,tn)}),le(t)<=Je))return t;let n=t[0],s=t[t.length-1],r=t.slice(1,-1).slice(-4).map(c=>({...c,content:Ct(c.content,2500)}));return t=[n,...r,s],le(t)<=Je||(t=[{...n,content:Ct(n?.content,6e3)},{...s,content:Ct(s?.content,8e3)}]),t}function ao(e){let t=[];for(let n of e){let s=Pt(n),r=String(s?.description||"").trim();if(!r){t.push(`- ${n}`);continue}t.push(`- ${n}: ${Yt(r,80)}`)}return t.length===0?"":`## Active skills (call get_skill_context before first use)
19
+ [truncated for proxy size]`}function ae(e){return e.reduce((t,n)=>t+String(n?.content||"").length+64,0)}function lo(e){let t=[...e];if(t.length===0||(t[0]?.role==="system"&&(t[0]={...t[0],content:Ct(t[0].content,en)}),ae(t)<=Ge))return t;let n=t[0],s=t[t.length-1],r=t.slice(1,-1).slice(-4).map(c=>({...c,content:Ct(c.content,2500)}));return t=[n,...r,s],ae(t)<=Ge||(t=[{...n,content:Ct(n?.content,6e3)},{...s,content:Ct(s?.content,8e3)}]),t}function ao(e){let t=[];for(let n of e){let s=Pt(n),r=String(s?.description||"").trim();if(!r){t.push(`- ${n}`);continue}t.push(`- ${n}: ${Yt(r,80)}`)}return t.length===0?"":`## Active skills (call get_skill_context before first use)
20
20
  ${t.join(`
21
- `)}`}var qe={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(`
22
- `)};function uo(e={},t={}){let n=String(t.outputProfile||process.env.ZIBBY_OUTPUT_PROFILE||e.outputProfile||"cli_plain").trim(),s=e?.outputProfiles?.[n];return typeof s=="string"&&s.trim()?s.trim():s&&typeof s.instruction=="string"&&s.instruction.trim()?s.instruction.trim():qe[n]||qe.cli_plain}function Yt(e,t){let n=String(e??"");return n.length<=t?n:t<=1?n.slice(0,t):`${n.slice(0,t-1)}\u2026`}function po(){return!1}function fo(e){let t=/^```(\w*)\n([\s\S]*?)^```$/gm;return e.replace(t,(n,s,r)=>{let c=r.replace(/\n$/,"");try{let l=s?Ze(c,{language:s,ignoreIllegals:!0}):Ze(c,{ignoreIllegals:!0}),d=o.gray("\u2500".repeat(Math.min(process.stdout.columns-6||54,72))),y=s?o.dim(` ${s}`):"";return`${d}${y}
21
+ `)}`}var Ke={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(`
22
+ `)};function uo(e={},t={}){let n=String(t.outputProfile||process.env.ZIBBY_OUTPUT_PROFILE||e.outputProfile||"cli_plain").trim(),s=e?.outputProfiles?.[n];return typeof s=="string"&&s.trim()?s.trim():s&&typeof s.instruction=="string"&&s.instruction.trim()?s.instruction.trim():Ke[n]||Ke.cli_plain}function Yt(e,t){let n=String(e??"");return n.length<=t?n:t<=1?n.slice(0,t):`${n.slice(0,t-1)}\u2026`}function po(){return!1}function fo(e){let t=/^```(\w*)\n([\s\S]*?)^```$/gm;return e.replace(t,(n,s,r)=>{let c=r.replace(/\n$/,"");try{let l=s?Je(c,{language:s,ignoreIllegals:!0}):Je(c,{ignoreIllegals:!0}),d=o.gray("\u2500".repeat(Math.min(process.stdout.columns-6||54,72))),y=s?o.dim(` ${s}`):"";return`${d}${y}
23
23
  ${l}
24
- ${d}`}catch{return c}})}function ie(){let e=Number(process.stdout?.columns)||0,t=e>8?Math.max(30,e-4):Qn;return` ${"\u2500".repeat(t)}`}function Ke(e=[]){let t=ae.map(s=>({cmd:s.cmd,source:"builtin",name:s.cmd.slice(1),desc:s.desc})),n=e.map(s=>({cmd:`/${s}`,source:"template",name:s,desc:"Command template"}));return[...t,...n]}function mo(e,t){let n=String(e||""),s=Number.isFinite(t)?t:n.length;return!(!n.startsWith("/")||s!==n.length||n.includes(" "))}function go({userName:e,cwd:t,projectName:n,restoredCount:s,skillsLine:r}){let c=Number(process.stdout?.columns)||0,l=Math.max(40,Math.min(c-8,100)),d=Math.max(20,Math.floor((l-3)*.55)),y=l-d-3,L=e||"there",F=n||"No project linked",bt=Hn(t||process.cwd()),Y=[`Restored ${s} messages from previous session.`,"",r],ct=["Workspace details","",`v${Xn.version} | Hi, ${L}`,`Company: ${F}`,`Directory: ~/${bt}`,`Path: ${t}`,"","Use /help for commands"],N=Math.max(Y.length,ct.length),Q=(()=>{if(Y.length>=N)return Y;let M=Math.floor((N-Y.length)/2),rt=N-Y.length-M;return[...Array(M).fill(""),...Y,...Array(rt).fill("")]})(),W="\u2500",B=` \u250C${W.repeat(d+2)}\u252C${W.repeat(y+2)}\u2510`,st=` \u2514${W.repeat(d+2)}\u2534${W.repeat(y+2)}\u2518`;console.log(o.gray(B));for(let M=0;M<N;M++){let rt=Yt(Q[M]||"",d),lt=Yt(ct[M]||"",y),wt=" ".repeat(Math.max(0,d-rt.length)),f=" ".repeat(Math.max(0,y-lt.length)),k=` \u2502 ${rt}${wt} \u2502 ${lt}${f} \u2502`;console.log(o.gray(k))}console.log(o.gray(st)),console.log("")}function ho(){process.stdout?.isTTY&&(E(process.stdout,0,-2),U(process.stdout,4))}function yo(e){let t=!!(process.stdout?.isTTY&&process.stdin?.isTTY),n=!1,s=!1,r=!1,c=null,l=0,d=0,y=0;function L(){return o.gray(ie())}function F(){c&&(clearInterval(c),c=null)}function bt(f){!t||!n||!s||!r||(process.stdout.write("\x1B7"),E(process.stdout,0,-2),U(process.stdout,0),G(process.stdout,0),process.stdout.write(` ${f}`),process.stdout.write("\x1B8"))}function Y(){if(!(!t||!n)&&d!==0){process.stdout.write("\x1B7"),E(process.stdout,0,2);for(let f=0;f<d;f++)U(process.stdout,0),G(process.stdout,0),f<d-1&&E(process.stdout,0,1);process.stdout.write("\x1B8"),d=0,s&&ct()}}function ct(){!t||!n||!s||(process.stdout.write("\x1B7"),E(process.stdout,0,1),U(process.stdout,0),G(process.stdout,0),process.stdout.write(L()),process.stdout.write("\x1B8"))}function N(f,k){if(!t||!n||!s)return;Y();let u=f.slice(0,6);if(u.length!==0){E(process.stdout,0,1);for(let x=0;x<u.length;x++)process.stdout.write(`
25
- `);E(process.stdout,0,-(1+u.length)),process.stdout.write("\x1B7"),E(process.stdout,0,2);for(let x=0;x<u.length;x++){U(process.stdout,0),G(process.stdout,0);let V=x===k?o.cyan("\u203A"):" ",b=x===k?o.white(u[x]):o.gray(u[x]);process.stdout.write(` ${V} /${b}`),x<u.length-1&&E(process.stdout,0,1)}process.stdout.write("\x1B8"),d=u.length,ct()}}function Q(){if(!t||!n||!s)return;Y();let f=process.stdout.columns||80,k=y>0?Math.ceil(y/f):1;U(process.stdout,0),E(process.stdout,0,-k),r&&E(process.stdout,0,-2),process.stdout.write("\x1B[J"),s=!1}function W(f={}){let k=f.preserveInput===!0;if(!t){e.prompt();return}k||(e.line="",e.cursor=0),y=ie().length;let u=L();process.stdout.write(`${u}
24
+ ${d}`}catch{return c}})}function ce(){let e=Number(process.stdout?.columns)||0,t=e>8?Math.max(30,e-4):Qn;return` ${"\u2500".repeat(t)}`}function Xe(e=[]){let t=ue.map(s=>({cmd:s.cmd,source:"builtin",name:s.cmd.slice(1),desc:s.desc})),n=e.map(s=>({cmd:`/${s}`,source:"template",name:s,desc:"Command template"}));return[...t,...n]}function mo(e,t){let n=String(e||""),s=Number.isFinite(t)?t:n.length;return!(!n.startsWith("/")||s!==n.length||n.includes(" "))}function go({userName:e,cwd:t,projectName:n,restoredCount:s,skillsLine:r}){let c=Number(process.stdout?.columns)||0,l=Math.max(40,Math.min(c-8,100)),d=Math.max(20,Math.floor((l-3)*.55)),y=l-d-3,L=e||"there",F=n||"No project linked",bt=Hn(t||process.cwd()),Y=[`Restored ${s} messages from previous session.`,"",r],ct=["Workspace details","",`v${Xn.version} | Hi, ${L}`,`Company: ${F}`,`Directory: ~/${bt}`,`Path: ${t}`,"","Use /help for commands"],N=Math.max(Y.length,ct.length),Q=(()=>{if(Y.length>=N)return Y;let M=Math.floor((N-Y.length)/2),rt=N-Y.length-M;return[...Array(M).fill(""),...Y,...Array(rt).fill("")]})(),W="\u2500",B=` \u250C${W.repeat(d+2)}\u252C${W.repeat(y+2)}\u2510`,st=` \u2514${W.repeat(d+2)}\u2534${W.repeat(y+2)}\u2518`;console.log(o.gray(B));for(let M=0;M<N;M++){let rt=Yt(Q[M]||"",d),lt=Yt(ct[M]||"",y),wt=" ".repeat(Math.max(0,d-rt.length)),f=" ".repeat(Math.max(0,y-lt.length)),k=` \u2502 ${rt}${wt} \u2502 ${lt}${f} \u2502`;console.log(o.gray(k))}console.log(o.gray(st)),console.log("")}function ho(){process.stdout?.isTTY&&(E(process.stdout,0,-2),U(process.stdout,4))}function yo(e){let t=!!(process.stdout?.isTTY&&process.stdin?.isTTY),n=!1,s=!1,r=!1,c=null,l=0,d=0,y=0;function L(){return o.gray(ce())}function F(){c&&(clearInterval(c),c=null)}function bt(f){!t||!n||!s||!r||(process.stdout.write("\x1B7"),E(process.stdout,0,-2),U(process.stdout,0),G(process.stdout,0),process.stdout.write(` ${f}`),process.stdout.write("\x1B8"))}function Y(){if(!(!t||!n)&&d!==0){process.stdout.write("\x1B7"),E(process.stdout,0,2);for(let f=0;f<d;f++)U(process.stdout,0),G(process.stdout,0),f<d-1&&E(process.stdout,0,1);process.stdout.write("\x1B8"),d=0,s&&ct()}}function ct(){!t||!n||!s||(process.stdout.write("\x1B7"),E(process.stdout,0,1),U(process.stdout,0),G(process.stdout,0),process.stdout.write(L()),process.stdout.write("\x1B8"))}function N(f,k){if(!t||!n||!s)return;Y();let u=f.slice(0,6);if(u.length!==0){E(process.stdout,0,1);for(let x=0;x<u.length;x++)process.stdout.write(`
25
+ `);E(process.stdout,0,-(1+u.length)),process.stdout.write("\x1B7"),E(process.stdout,0,2);for(let x=0;x<u.length;x++){U(process.stdout,0),G(process.stdout,0);let V=x===k?o.cyan("\u203A"):" ",b=x===k?o.white(u[x]):o.gray(u[x]);process.stdout.write(` ${V} /${b}`),x<u.length-1&&E(process.stdout,0,1)}process.stdout.write("\x1B8"),d=u.length,ct()}}function Q(){if(!t||!n||!s)return;Y();let f=process.stdout.columns||80,k=y>0?Math.ceil(y/f):1;U(process.stdout,0),E(process.stdout,0,-k),r&&E(process.stdout,0,-2),process.stdout.write("\x1B[J"),s=!1}function W(f={}){let k=f.preserveInput===!0;if(!t){e.prompt();return}k||(e.line="",e.cursor=0),y=ce().length;let u=L();process.stdout.write(`${u}
26
26
  `),e.prompt(),process.stdout.write(`
27
27
  ${u}
28
- `),ho(),s=!0}function B(){if(!t||!n||!s)return;let f=process.stdout.columns||80,k=y>0?Math.ceil(y/f):1,u=L();process.stdout.write("\x1B7"),E(process.stdout,0,-k);for(let x=0;x<k;x++)U(process.stdout,0),G(process.stdout,0),x<k-1&&E(process.stdout,0,1);U(process.stdout,0),process.stdout.write(u),E(process.stdout,0,2),U(process.stdout,0),G(process.stdout,0),process.stdout.write(u);for(let x=1;x<k;x++)E(process.stdout,0,1),U(process.stdout,0),G(process.stdout,0);process.stdout.write("\x1B8"),y=ie().length}function st(){if(!t||!n||!s)return;let f=(()=>{if(typeof e.getCursorPos!="function")return 0;try{return Math.max(0,Number(e.getCursorPos()?.rows||0))}catch{return 0}})();process.stdout.write("\x1B7"),E(process.stdout,0,-(f+1)),U(process.stdout,0),G(process.stdout,0),process.stdout.write(L()),E(process.stdout,0,f+2),U(process.stdout,0),G(process.stdout,0),process.stdout.write(L()),process.stdout.write("\x1B8")}function M(f){F(),Q(),console.log();let k=String(f??"").replace(/\r/g,"").split(`
28
+ `),ho(),s=!0}function B(){if(!t||!n||!s)return;let f=process.stdout.columns||80,k=y>0?Math.ceil(y/f):1,u=L();process.stdout.write("\x1B7"),E(process.stdout,0,-k);for(let x=0;x<k;x++)U(process.stdout,0),G(process.stdout,0),x<k-1&&E(process.stdout,0,1);U(process.stdout,0),process.stdout.write(u),E(process.stdout,0,2),U(process.stdout,0),G(process.stdout,0),process.stdout.write(u);for(let x=1;x<k;x++)E(process.stdout,0,1),U(process.stdout,0),G(process.stdout,0);process.stdout.write("\x1B8"),y=ce().length}function st(){if(!t||!n||!s)return;let f=(()=>{if(typeof e.getCursorPos!="function")return 0;try{return Math.max(0,Number(e.getCursorPos()?.rows||0))}catch{return 0}})();process.stdout.write("\x1B7"),E(process.stdout,0,-(f+1)),U(process.stdout,0),G(process.stdout,0),process.stdout.write(L()),E(process.stdout,0,f+2),U(process.stdout,0),G(process.stdout,0),process.stdout.write(L()),process.stdout.write("\x1B8")}function M(f){F(),Q(),console.log();let k=String(f??"").replace(/\r/g,"").split(`
29
29
  `);for(;k.length>0&&k[k.length-1]==="";)k.pop();for(let u of k)console.log(u?` ${u}`:"");r=!1}function rt(f){let k=String(f??"").replace(/\r/g,"").split(`
30
30
  `);k.length===0&&k.push("");let u=[];for(let x of k)u.push(o.bgGray.white(` ${x||" "} `));return u.join(`
31
31
  `)}function lt(){F();let f=()=>o.gray(`${Dt[l%Dt.length]} thinking`);if(!t){console.log(` ${f()}`),r=!0;return}Y(),Q(),console.log(),console.log(` ${f()}`),W({preserveInput:!0}),r=!0,l+=1,c=setInterval(()=>{r&&(bt(f()),l+=1)},120)}function wt(f){F();let k=String(f??"").replace(/\r/g,"").replace(/⎿/g,"");if(!r){M(k);return}Q(),console.log();let u=k.split(`
32
- `);for(;u.length>0&&u[u.length-1]==="";)u.pop();for(let x of u)console.log(x?` ${x}`:"");console.log(),r=!1}return{enabled:t,mount(){if(!n){if(!t){e.prompt(),n=!0;return}n=!0,W()}},refreshPrompt(f={}){if(t&&n){s&&Q(),W(f);return}e.prompt()},pushSystem(f){M(f)},pushUser(f){M(rt(f))},pushAssistant(f){wt(f)},showAssistantLoading:lt,dismissTransientLoading(){F(),r&&t&&n&&s&&(process.stdout.write("\x1B7"),E(process.stdout,0,-2),U(process.stdout,0),G(process.stdout,0),E(process.stdout,0,-1),U(process.stdout,0),G(process.stdout,0),process.stdout.write("\x1B8")),r=!1},touchInputFrame:st,handleResize:B,showCommandDropdown:N,clearCommandDropdown:Y}}function bo(){console.log(""),console.log(o.cyan(" Available commands:"));for(let e of ae)console.log(o.white(` ${e.cmd.padEnd(10)} `)+o.gray(e.desc));console.log(""),console.log(o.cyan(" Chat options:")),console.log(o.white(" --stream, -s ")+o.gray("Enable typewriter effect (default: instant)")),console.log(""),console.log(o.gray(" To install/uninstall skills, just ask naturally:")),console.log(o.gray(' "connect to Jira" \u2022 "add GitHub" \u2022 "remove Slack"')),console.log("")}var wo=oo;async function as(e={}){let t=process.cwd();e.verbose&&(process.env.ZIBBY_VERBOSE="true");let n=e.stream||!1;[ft(t,".env.local"),ft(t,".env")].forEach(u=>{yt(u)&&Vn.config({path:u,override:!1})});try{await import("@zibby/skills")}catch{}function r(){let u=Ot();if(!u)return!1;try{let x=JSON.parse(atob(u.split(".")[1]));return x.exp&&x.exp*1e3>Date.now()}catch{return!1}}if(!r()){Te();let u=Xt(),{spawn:x}=await import("child_process"),V=await fetch(`${u}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});V.ok||(console.log(o.red("\n Could not start login. Try `zibby login`.\n")),process.exit(1));let{deviceCode:b,verificationUrl:i,expiresIn:O,interval:tt}=await V.json(),z=process.platform;x(z==="darwin"?"open":z==="win32"?"cmd":"xdg-open",z==="win32"?["/c","start","",i]:[i],{detached:!0,stdio:"ignore"}).unref(),console.log(o.cyan(`
32
+ `);for(;u.length>0&&u[u.length-1]==="";)u.pop();for(let x of u)console.log(x?` ${x}`:"");console.log(),r=!1}return{enabled:t,mount(){if(!n){if(!t){e.prompt(),n=!0;return}n=!0,W()}},refreshPrompt(f={}){if(t&&n){s&&Q(),W(f);return}e.prompt()},pushSystem(f){M(f)},pushUser(f){M(rt(f))},pushAssistant(f){wt(f)},showAssistantLoading:lt,dismissTransientLoading(){F(),r&&t&&n&&s&&(process.stdout.write("\x1B7"),E(process.stdout,0,-2),U(process.stdout,0),G(process.stdout,0),E(process.stdout,0,-1),U(process.stdout,0),G(process.stdout,0),process.stdout.write("\x1B8")),r=!1},touchInputFrame:st,handleResize:B,showCommandDropdown:N,clearCommandDropdown:Y}}function bo(){console.log(""),console.log(o.cyan(" Available commands:"));for(let e of ue)console.log(o.white(` ${e.cmd.padEnd(10)} `)+o.gray(e.desc));console.log(""),console.log(o.cyan(" Chat options:")),console.log(o.white(" --stream, -s ")+o.gray("Enable typewriter effect (default: instant)")),console.log(""),console.log(o.gray(" To install/uninstall skills, just ask naturally:")),console.log(o.gray(' "connect to Jira" \u2022 "add GitHub" \u2022 "remove Slack"')),console.log("")}var wo=oo;async function us(e={}){let t=process.cwd();e.verbose&&(process.env.ZIBBY_VERBOSE="true");let n=e.stream||!1;[ft(t,".env.local"),ft(t,".env")].forEach(u=>{yt(u)&&Vn.config({path:u,override:!1})});try{await import("@zibby/skills")}catch{}function r(){let u=Ot();if(!u)return!1;try{let x=JSON.parse(atob(u.split(".")[1]));return x.exp&&x.exp*1e3>Date.now()}catch{return!1}}if(!r()){Pe();let u=Qt(),{spawn:x}=await import("child_process"),V=await fetch(`${u}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});V.ok||(console.log(o.red("\n Could not start login. Try `zibby login`.\n")),process.exit(1));let{deviceCode:b,verificationUrl:i,expiresIn:O,interval:tt}=await V.json(),z=process.platform;x(z==="darwin"?"open":z==="win32"?"cmd":"xdg-open",z==="win32"?["/c","start","",i]:[i],{detached:!0,stdio:"ignore"}).unref(),console.log(o.cyan(`
33
33
  Opening browser to authorize Zibby CLI...`)),console.log(o.gray(` ${i}
34
- `));let at=Ge();at.setLabel("waiting for authorization");let dt=(tt||3)*1e3,mt=Math.floor(O/(tt||3)),et=!1;for(let it=0;it<mt;it++){await eo(dt);try{let nt=await fetch(`${u}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:b})});if(nt.status===202)continue;if(!nt.ok)break;let Z=await nt.json();if(Z.status==="authorized"){$e(Z.token),Ae(Z.user),Z.proxyUrl&&Ce(Z.proxyUrl),Z.mem0ProxyUrl&&Le(Z.mem0ProxyUrl),et=!0;break}if(Z.status==="denied")break}catch{break}}at(),et||(console.log(o.red("\n Login failed or timed out. Run `zibby login` to try again.\n")),process.exit(1))}let c=await so(t),l=await ro(t),d=e.agent||"assistant",y=Ot();y&&!process.env.ZIBBY_USER_TOKEN&&(process.env.ZIBBY_USER_TOKEN=y);let L=Ne()||Pe();L&&!process.env.ZIBBY_MEM0_OPENAI_BASE_URL&&(process.env.ZIBBY_MEM0_OPENAI_BASE_URL=L),process.env.AGENT_TYPE=d,process.env.ZIBBY_CHAT_OWNER_PID=String(process.pid);try{let{cleanupStalePidFiles:u}=await Promise.resolve().then(()=>(re(),se));u(t,c)}catch{}let F;try{F=Dn({state:{agentType:d}})}catch(u){console.log(o.red(`
34
+ `));let at=Ve();at.setLabel("waiting for authorization");let dt=(tt||3)*1e3,mt=Math.floor(O/(tt||3)),et=!1;for(let it=0;it<mt;it++){await eo(dt);try{let nt=await fetch(`${u}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:b})});if(nt.status===202)continue;if(!nt.ok)break;let Z=await nt.json();if(Z.status==="authorized"){Ie(Z.token),Te(Z.user),Z.proxyUrl&&Ne(Z.proxyUrl),Z.mem0ProxyUrl&&Be(Z.mem0ProxyUrl),et=!0;break}if(Z.status==="denied")break}catch{break}}at(),et||(console.log(o.red("\n Login failed or timed out. Run `zibby login` to try again.\n")),process.exit(1))}let c=await so(t),l=await ro(t),d=e.agent||"assistant",y=Ot();y&&!process.env.ZIBBY_USER_TOKEN&&(process.env.ZIBBY_USER_TOKEN=y);let L=Le()||Ce();L&&!process.env.ZIBBY_MEM0_OPENAI_BASE_URL&&(process.env.ZIBBY_MEM0_OPENAI_BASE_URL=L),process.env.AGENT_TYPE=d,process.env.ZIBBY_CHAT_OWNER_PID=String(process.pid);try{let{cleanupStalePidFiles:u}=await Promise.resolve().then(()=>(ie(),re));u(t,c)}catch{}let F;try{F=Dn({state:{agentType:d}})}catch(u){console.log(o.red(`
35
35
  ${u.message}
36
- `)),process.exit(1)}let bt=Ie(),ct=Be()?.[0]?.name,N=Ue(t),Q=l.skills||[],W=Fe(t),B=W?[...new Set([...Q,...W])]:[...Q],st={data:null,timestamp:0},M=300*1e3,rt={jira:"jira",github:"github",slack:"slack",sentry:"sentry"};try{let u=Ot();if(u){let x=Xt(),V=await fetch(`${x}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${u}`}});if(V.ok){let b=await V.json();for(let[i,O]of Object.entries(rt)){let tt=b[i]?.connected,z=B.indexOf(O);tt&&z===-1&&Pt(O)?B.push(O):!tt&&z!==-1&&B.splice(z,1)}Tt(t,B)}}}catch{}let lt=B.filter(u=>u!=="skill-installer"&&u!=="core-tools"),wt=lt.length>0?`Skills: ${lt.join(", ")}`:"Skills: (none)";go({userName:bt?.name?.split(" ")[0],cwd:t,projectName:ct,restoredCount:N.length,skillsLine:wt});let f=Ve(t),k=Ke(f);return new Promise(u=>{let x=process.env.ZIBBY_CHAT_TAB_COMPLETION==="1",V={input:process.stdin,output:process.stdout,prompt:o.green(" > "),terminal:!0};x&&(V.completer=m=>{let a=String(m||"");if(!a.startsWith("/"))return[[],a];let w=k.map(P=>P.cmd),$=w.filter(P=>P.startsWith(a));return[$.length>0?$:w,a]});let b=Wn(V),i=yo(b),O=null,tt=!1,z=[],en=0,nn=1200,at=!1,dt=!1,mt=!1,et=!1,it="",nt=0,Z=typeof b._ttyWrite=="function"?b._ttyWrite.bind(b):null;Z&&(b._ttyWrite=(...m)=>{if(!(et||Date.now()<nt))return Z(...m)});function on(){mt||!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004h"),mt=!0)}function ue(){mt&&(!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004l"),mt=!1))}function sn(m){let a="\x1B[200~",w="\x1B[201~";if(!et&&!m.includes(a))return!1;let $=m,P=!1;for(;$.length>0;){if(!et){let C=$.indexOf(a);if(C===-1)break;P=!0,me(),et=!0,it="",$=$.slice(C+a.length);continue}let J=$.indexOf(w);if(J===-1){P=!0,it+=$;break}P=!0,it+=$.slice(0,J);let ot=String(it||"").replace(/\r\n/g,`
36
+ `)),process.exit(1)}let bt=Ae(),ct=Ee()?.[0]?.name,N=Fe(t),Q=l.skills||[],W=Me(t),B=W?[...new Set([...Q,...W])]:[...Q],st={data:null,timestamp:0},M=300*1e3,rt={jira:"jira",github:"github",slack:"slack",sentry:"sentry"};try{let u=Ot();if(u){let x=Qt(),V=await fetch(`${x}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${u}`}});if(V.ok){let b=await V.json();for(let[i,O]of Object.entries(rt)){let tt=b[i]?.connected,z=B.indexOf(O),zt=Pt(O);tt&&z===-1&&zt?B.push(O):!tt&&z!==-1&&B.splice(z,1)}Tt(t,B)}}}catch{}let lt=B.filter(u=>u!=="skill-installer"&&u!=="core-tools"),wt=lt.length>0?`Skills: ${lt.join(", ")}`:"Skills: (none)";go({userName:bt?.name?.split(" ")[0],cwd:t,projectName:ct,restoredCount:N.length,skillsLine:wt});let f=qe(t),k=Xe(f);return new Promise(u=>{let x=process.env.ZIBBY_CHAT_TAB_COMPLETION==="1",V={input:process.stdin,output:process.stdout,prompt:o.green(" > "),terminal:!0};x&&(V.completer=m=>{let a=String(m||"");if(!a.startsWith("/"))return[[],a];let w=k.map(P=>P.cmd),$=w.filter(P=>P.startsWith(a));return[$.length>0?$:w,a]});let b=Wn(V),i=yo(b),O=null,tt=!1,z=[],zt=0,nn=1200,at=!1,dt=!1,mt=!1,et=!1,it="",nt=0,Z=typeof b._ttyWrite=="function"?b._ttyWrite.bind(b):null;Z&&(b._ttyWrite=(...m)=>{if(!(et||Date.now()<nt))return Z(...m)});function on(){mt||!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004h"),mt=!0)}function pe(){mt&&(!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004l"),mt=!1))}function sn(m){let a="\x1B[200~",w="\x1B[201~";if(!et&&!m.includes(a))return!1;let $=m,P=!1;for(;$.length>0;){if(!et){let C=$.indexOf(a);if(C===-1)break;P=!0,ge(),et=!0,it="",$=$.slice(C+a.length);continue}let J=$.indexOf(w);if(J===-1){P=!0,it+=$;break}P=!0,it+=$.slice(0,J);let ot=String(it||"").replace(/\r\n/g,`
37
37
  `).replace(/\r/g,`
38
38
  `);if(ot.length>0){let C=ot.split(`
39
- `);for(let q of C)Gt(q)}Lt(),it="",et=!1,$=$.slice(J+w.length)}return P}function pe(){if(!at){at=!0;try{At(t,N),Tt(t,B)}catch{}try{ue()}catch{}try{b.close()}catch{}process.exit(0)}}async function zt(){if(!at){at=!0,typeof F?.cleanup=="function"&&await F.cleanup().catch(()=>{});try{let{killAllChatOrchestratedRuns:m}=await Promise.resolve().then(()=>(re(),se)),{postCliInterruptedRunIndex:a}=await import("@zibby/core/utils/run-index-post-cli.js");m(t,process.pid,c),a({cwd:t,config:c})}catch{}At(t,N),Tt(t,B),i.pushSystem(o.gray("Session saved. Goodbye!")),ue(),b.close(),process.exit(0)}}if(i.mount(),on(),process.stdout?.isTTY){let m;process.stdout.on("resize",()=>{clearTimeout(m),m=setTimeout(()=>{i.handleResize()},80)})}let Ht=0,Nt=m=>{if(typeof m=="string"?m==="\x1B":m&&typeof m.length=="number"?m.length===1&&m[0]===27:!1){O&&O.abort(),pe();return}let w=typeof m=="string"?m:m&&typeof m.length=="number"?Buffer.from(m).toString("utf8"):"";if(!w)return;if(sn(w)){Ht=Date.now()+1200,nt=Date.now()+1200,Jt();return}let $=(w.includes(`
39
+ `);for(let q of C)Vt(q)}Lt(),it="",et=!1,$=$.slice(J+w.length)}return P}function fe(){if(!at){at=!0;try{At(t,N),Tt(t,B)}catch{}try{pe()}catch{}try{b.close()}catch{}process.exit(0)}}async function Ht(){if(!at){at=!0,typeof F?.cleanup=="function"&&await F.cleanup().catch(()=>{});try{let{killAllChatOrchestratedRuns:m}=await Promise.resolve().then(()=>(ie(),re)),{postCliInterruptedRunIndex:a}=await import("@zibby/core/utils/run-index-post-cli.js");m(t,process.pid,c),a({cwd:t,config:c})}catch{}At(t,N),Tt(t,B),i.pushSystem(o.gray("Session saved. Goodbye!")),pe(),b.close(),process.exit(0)}}if(i.mount(),on(),process.stdout?.isTTY){let m;process.stdout.on("resize",()=>{clearTimeout(m),m=setTimeout(()=>{i.handleResize()},80)})}let Wt=0,Nt=m=>{if(typeof m=="string"?m==="\x1B":m&&typeof m.length=="number"?m.length===1&&m[0]===27:!1){O&&O.abort(),fe();return}let w=typeof m=="string"?m:m&&typeof m.length=="number"?Buffer.from(m).toString("utf8"):"";if(!w)return;if(sn(w)){Wt=Date.now()+1200,nt=Date.now()+1200,Gt();return}let $=(w.includes(`
40
40
  `)||w.includes("\r"))&&w!=="\r"&&w!==`
41
41
  `&&w!==`\r
42
- `,P=w.includes("\x1B[200~")||w.includes("\x1B[201~"),J=w.length>=16&&/\s/.test(w)&&!w.startsWith("\x1B");($||P||J)&&(Ht=Date.now()+1200,nt=Date.now()+1200,me(),Jt())},R={query:"",matches:[],selected:0},H={prefix:"",matches:[],nextIndex:0},A={active:!1,prefix:"",lines:[],timer:null},Wt=[],fe=0,Zt="",rn=new Set(ae.map(m=>m.cmd));function gt(m,{preserveFrame:a=!1}={}){let w=String(m||"");b.line=w,b.cursor=w.length,Zt=w,typeof b._refreshLine=="function"?b._refreshLine():b.prompt(),a&&i.touchInputFrame()}function de(){H.prefix="",H.matches=[],H.nextIndex=0}function Lt(){if(A.timer&&(clearTimeout(A.timer),A.timer=null),A.active&&A.lines.length>0){fe+=1;let m=A.lines.length,a=`[Pasted text #${fe} +${m} lines]`,w=A.lines.join(`
43
- `);Wt.push({placeholder:a,text:w});let $=String(A.prefix||"").trimEnd(),P=$?`${$} ${a}`:a;gt(P,{preserveFrame:!0}),ht(b.line)}A.active=!1,A.prefix="",A.lines=[],nt=0}function Jt(){A.timer&&clearTimeout(A.timer),A.timer=setTimeout(()=>{Lt()},180)}function me(){A.active||(A.active=!0,A.prefix=String(Zt||b.line||""),A.lines=[],gt(A.prefix,{preserveFrame:!0}))}function Gt(m){return A.active?(A.lines.push(String(m||"")),gt(A.prefix,{preserveFrame:!0}),Jt(),!0):!1}function cn(m){let a=String(m||"");for(let w of Wt)a=a.split(w.placeholder).join(w.text);return a}function ht(m){let a=String(m||"");if(!a.startsWith("/")||a.includes(" ")||a.length===0){R.query="",R.matches=[],R.selected=0,i.clearCommandDropdown();return}f=Ve(t),k=Ke(f);let w=a.slice(1).toLowerCase(),$=f.filter(P=>P.toLowerCase().startsWith(w));R.query=w,R.matches=$,R.selected=Math.min(R.selected,Math.max(0,$.length-1)),i.showCommandDropdown($,R.selected)}let Vt=(m,a)=>{if(a?.name==="escape"||a?.sequence==="\x1B"){O&&O.abort(),pe();return}if((a?.name==="return"||a?.name==="enter")&&(dt=!0),(a?.name==="backspace"||a?.name==="delete")&&i.touchInputFrame(),a?.name==="tab"&&!a?.shift){let P=String(b.line||""),J=Number(b.cursor||P.length);if(!mo(P,J)){de(),ht(b.line);return}let ot=P.slice(1).toLowerCase();if(H.prefix!==ot&&(H.prefix=ot,H.matches=k.map(q=>q.cmd).filter(q=>q.toLowerCase().startsWith(`/${ot}`)),H.nextIndex=0),H.matches.length===0)return;let C=H.nextIndex%H.matches.length;H.nextIndex+=1,gt(H.matches[C]),ht(b.line);return}let w=String(b.line||""),$=w.startsWith("/")&&!w.includes(" ")&&R.matches.length>0;if(a?.name==="up"||a?.name==="down"){if(!$){ht(b.line);return}let P=a.name==="up"?-1:1,J=R.matches.length;R.selected=(R.selected+P+J)%J;let ot=R.matches[R.selected];gt(`/${ot}`,{preserveFrame:!0}),i.showCommandDropdown(R.matches,R.selected);return}a?.name!=="tab"&&de(),setTimeout(()=>{ht(b.line),A.active||(Zt=String(b.line||""))},50)};process.stdin?.on&&(Zn(process.stdin,b),process.stdin.on("keypress",Vt)),i.enabled&&process.stdin?.on&&(typeof process.stdin.prependListener=="function"?process.stdin.prependListener("data",Nt):process.stdin.on("data",Nt)),b.on("line",async m=>{try{let a=String(m||""),w=dt;if(dt=!1,!w&&(A.active||et||Date.now()<Ht||Date.now()<nt)){if(A.active&&a.length>0){Gt(a);return}A.active&&(Lt(),i.refreshPrompt());return}if(A.active&&(Lt(),a=String(b.line||a||"")),Gt(a))return;let $=a.trim(),P=R.matches[R.selected];if($.startsWith("/")&&!$.includes(" ")&&R.matches.length>0&&!rn.has($)&&$!==`/${P}`){i.clearCommandDropdown(),i.refreshPrompt(),gt(`/${P}`),ht(`/${P}`);return}i.clearCommandDropdown();let C=String(a||"").replace(/[\u0000-\u001F\u007F-\u009F]/g,"").trim();if(!C){i.enabled&&process.stdout?.isTTY&&(E(process.stdout,0,-1),U(process.stdout,4));return}if(tt&&C!=="/exit"&&C!=="/quit"){O&&O.abort(),z.push(C),i.pushSystem(o.gray("Processing your message...")),i.refreshPrompt({preserveInput:!0});return}let q=1e4;if(C.length>q){i.pushSystem(o.red(`\u26A0 Input too long (${C.length} chars). Maximum: ${q} characters.`)),i.pushSystem(o.gray("Tip: If you need to share logs, use a file instead:")),i.pushSystem(o.gray(" 1. Save to file: pbpaste > debug.log")),i.pushSystem(o.gray(' 2. Ask: "analyze debug.log in current directory"')),i.refreshPrompt();return}if(C==="/exit"||C==="/quit"){zt();return}if(C==="/help"){bo(),i.refreshPrompt();return}if(C==="/skills"){let I=Pt("skill-installer")?.catalog||{},S=B.filter(_=>_!=="skill-installer");console.log(o.cyan(`
42
+ `,P=w.includes("\x1B[200~")||w.includes("\x1B[201~"),J=w.length>=16&&/\s/.test(w)&&!w.startsWith("\x1B");($||P||J)&&(Wt=Date.now()+1200,nt=Date.now()+1200,ge(),Gt())},R={query:"",matches:[],selected:0},H={prefix:"",matches:[],nextIndex:0},A={active:!1,prefix:"",lines:[],timer:null},Zt=[],de=0,Jt="",rn=new Set(ue.map(m=>m.cmd));function gt(m,{preserveFrame:a=!1}={}){let w=String(m||"");b.line=w,b.cursor=w.length,Jt=w,typeof b._refreshLine=="function"?b._refreshLine():b.prompt(),a&&i.touchInputFrame()}function me(){H.prefix="",H.matches=[],H.nextIndex=0}function Lt(){if(A.timer&&(clearTimeout(A.timer),A.timer=null),A.active&&A.lines.length>0){de+=1;let m=A.lines.length,a=`[Pasted text #${de} +${m} lines]`,w=A.lines.join(`
43
+ `);Zt.push({placeholder:a,text:w});let $=String(A.prefix||"").trimEnd(),P=$?`${$} ${a}`:a;gt(P,{preserveFrame:!0}),ht(b.line)}A.active=!1,A.prefix="",A.lines=[],nt=0}function Gt(){A.timer&&clearTimeout(A.timer),A.timer=setTimeout(()=>{Lt()},180)}function ge(){A.active||(A.active=!0,A.prefix=String(Jt||b.line||""),A.lines=[],gt(A.prefix,{preserveFrame:!0}))}function Vt(m){return A.active?(A.lines.push(String(m||"")),gt(A.prefix,{preserveFrame:!0}),Gt(),!0):!1}function cn(m){let a=String(m||"");for(let w of Zt)a=a.split(w.placeholder).join(w.text);return a}function ht(m){let a=String(m||"");if(!a.startsWith("/")||a.includes(" ")||a.length===0){R.query="",R.matches=[],R.selected=0,i.clearCommandDropdown();return}f=qe(t),k=Xe(f);let w=a.slice(1).toLowerCase(),$=f.filter(P=>P.toLowerCase().startsWith(w));R.query=w,R.matches=$,R.selected=Math.min(R.selected,Math.max(0,$.length-1)),i.showCommandDropdown($,R.selected)}let qt=(m,a)=>{if(a?.name==="escape"||a?.sequence==="\x1B"){O&&O.abort(),fe();return}if((a?.name==="return"||a?.name==="enter")&&(dt=!0),(a?.name==="backspace"||a?.name==="delete")&&i.touchInputFrame(),a?.name==="tab"&&!a?.shift){let P=String(b.line||""),J=Number(b.cursor||P.length);if(!mo(P,J)){me(),ht(b.line);return}let ot=P.slice(1).toLowerCase();if(H.prefix!==ot&&(H.prefix=ot,H.matches=k.map(q=>q.cmd).filter(q=>q.toLowerCase().startsWith(`/${ot}`)),H.nextIndex=0),H.matches.length===0)return;let C=H.nextIndex%H.matches.length;H.nextIndex+=1,gt(H.matches[C]),ht(b.line);return}let w=String(b.line||""),$=w.startsWith("/")&&!w.includes(" ")&&R.matches.length>0;if(a?.name==="up"||a?.name==="down"){if(!$){ht(b.line);return}let P=a.name==="up"?-1:1,J=R.matches.length;R.selected=(R.selected+P+J)%J;let ot=R.matches[R.selected];gt(`/${ot}`,{preserveFrame:!0}),i.showCommandDropdown(R.matches,R.selected);return}a?.name!=="tab"&&me(),setTimeout(()=>{ht(b.line),A.active||(Jt=String(b.line||""))},50)};process.stdin?.on&&(Zn(process.stdin,b),process.stdin.on("keypress",qt)),i.enabled&&process.stdin?.on&&(typeof process.stdin.prependListener=="function"?process.stdin.prependListener("data",Nt):process.stdin.on("data",Nt)),b.on("line",async m=>{try{let a=String(m||""),w=dt;if(dt=!1,!w&&(A.active||et||Date.now()<Wt||Date.now()<nt)){if(A.active&&a.length>0){Vt(a);return}A.active&&(Lt(),i.refreshPrompt());return}if(A.active&&(Lt(),a=String(b.line||a||"")),Vt(a))return;let $=a.trim(),P=R.matches[R.selected];if($.startsWith("/")&&!$.includes(" ")&&R.matches.length>0&&!rn.has($)&&$!==`/${P}`){i.clearCommandDropdown(),i.refreshPrompt(),gt(`/${P}`),ht(`/${P}`);return}i.clearCommandDropdown();let C=String(a||"").replace(/[\u0000-\u001F\u007F-\u009F]/g,"").trim();if(!C){i.enabled&&process.stdout?.isTTY&&(E(process.stdout,0,-1),U(process.stdout,4));return}if(tt&&C!=="/exit"&&C!=="/quit"){O&&O.abort(),z.push(C),i.pushSystem(o.gray("Processing your message...")),i.refreshPrompt({preserveInput:!0});return}let q=1e4;if(C.length>q){i.pushSystem(o.red(`\u26A0 Input too long (${C.length} chars). Maximum: ${q} characters.`)),i.pushSystem(o.gray("Tip: If you need to share logs, use a file instead:")),i.pushSystem(o.gray(" 1. Save to file: pbpaste > debug.log")),i.pushSystem(o.gray(' 2. Ask: "analyze debug.log in current directory"')),i.refreshPrompt();return}if(C==="/exit"||C==="/quit"){Ht();return}if(C==="/help"){bo(),i.refreshPrompt();return}if(C==="/skills"){let I=Pt("skill-installer")?.catalog||{},S=B.filter(_=>_!=="skill-installer");console.log(o.cyan(`
44
44
  Active skills:`)),S.length===0&&console.log(o.gray(" (none)"));for(let _ of S){let v=I[_]||{};console.log(o.green(` \u2713 ${_}`)+o.gray(v.description?` \u2014 ${v.description}`:""))}let T=Object.keys(I).filter(_=>!B.includes(_));if(T.length>0){console.log(o.cyan(`
45
45
  Available:`));for(let _ of T){let v=I[_],h=v.envKeys?.length>0?wo(v.envKeys).ok?o.green(" \u2713 configured"):o.yellow(` \u26A0 needs: ${v.envKeys.join(", ")}`):"";console.log(o.white(` - ${_}`)+o.gray(` \u2014 ${v.description}`)+h)}}console.log(o.gray(`
46
46
  Just ask to install: "connect to Jira", "add GitHub", etc.
@@ -70,13 +70,13 @@ ${u}
70
70
  `)),console.log(o.white(` Facts stored: ${h>0?o.cyan(h):o.gray("0")}`)),console.log(o.white(` Sessions saved: ${g>0?o.cyan(g):o.gray("0")}`)),j&&console.log(o.white(` Task history: ${o.gray(j)}`)),console.log(o.gray(`
71
71
  Subcommands:`)),console.log(o.gray(" /memory facts [n] \u2014 List all stored memories")),console.log(o.gray(" /memory tasks [n] \u2014 List task history")),console.log(o.gray(" /memory sessions \u2014 List session summaries")),console.log(o.gray(" /memory search <keyword> \u2014 Search memories")),console.log("")}}catch(_){console.log(o.red(`
72
72
  Memory error: ${_.message}
73
- `))}i.refreshPrompt();return}i.enabled&&process.stdout?.isTTY&&(E(process.stdout,0,-1),U(process.stdout,0)),i.pushUser(C),i.refreshPrompt(),i.showAssistantLoading();let ge=cn(C),Bt=io(t,ge);if(Wt.length=0,!String(Bt||"").trim()){i.dismissTransientLoading(),i.refreshPrompt();return}if(Bt.length>q){i.pushAssistant(o.red(`Input too long after command expansion (${Bt.length} chars).`)),i.pushSystem(o.gray(`Try shortening the command template or user text. Limit: ${q} chars.`)),i.refreshPrompt();return}tt=!0;let K=l.systemPrompt||"You are Zibby, a helpful AI assistant.",he=uo(l,e);he&&(K+=`
73
+ `))}i.refreshPrompt();return}i.enabled&&process.stdout?.isTTY&&(E(process.stdout,0,-1),U(process.stdout,0)),i.pushUser(C),i.refreshPrompt(),i.showAssistantLoading();let he=cn(C),Bt=io(t,he);if(Zt.length=0,!String(Bt||"").trim()){i.dismissTransientLoading(),i.refreshPrompt();return}if(Bt.length>q){i.pushAssistant(o.red(`Input too long after command expansion (${Bt.length} chars).`)),i.pushSystem(o.gray(`Try shortening the command template or user text. Limit: ${q} chars.`)),i.refreshPrompt();return}tt=!0;let K=l.systemPrompt||"You are Zibby, a helpful AI assistant.",ye=uo(l,e);ye&&(K+=`
74
74
 
75
- ${he}`);let ye=De({activeSkills:B,chatConfig:l,options:e});ye&&(K+=`
75
+ ${ye}`);let be=Ye({activeSkills:B,chatConfig:l,options:e});be&&(K+=`
76
76
 
77
- ${ye}`);let be=ao(B);if(be&&(K+=`
77
+ ${be}`);let we=ao(B);if(we&&(K+=`
78
78
 
79
- ${be}`),K+=`
79
+ ${we}`),K+=`
80
80
 
81
81
  Use provided tools when external data/actions are required. Do not claim actions without tool calls. Before using a skill's tools for the first time in a conversation, call get_skill_context(skillId) to load its full guidance.`,B.includes("chat-memory")&&(K+=`
82
82
 
@@ -95,6 +95,6 @@ Use provided tools when external data/actions are required. Do not claim actions
95
95
  - After building: remind user about \`zibby start <name>\` (test), \`zibby deploy <name>\` (deploy), \`zibby logs\` (logs).
96
96
  - Use list_workflows to show existing workflows, add_node to extend them, deploy_workflow to ship.`),B.includes("chat-memory"))try{let p=Pt("chat-memory");if(typeof p?.buildPromptContext=="function"){let I=Date.now(),S;st.data&&I-st.timestamp<M?(S=st.data,process.env.ZIBBY_VERBOSE==="true"&&i.pushSystem(o.gray("Using cached memory context"))):(S=await p.buildPromptContext({options:{workspace:t}},{}),st={data:S,timestamp:I},process.env.ZIBBY_VERBOSE==="true"&&i.pushSystem(o.gray("Refreshed memory context cache")));let T=String(S?.backend||"dolt");process.env.ZIBBY_VERBOSE==="true"&&(i.pushSystem(o.gray(`memory backend: ${T}`)),i.pushSystem(o.gray(`memory retrieval output: ${Yt(JSON.stringify(S?.debugPreview||{}),1400)}`)),S?.error&&i.pushSystem(o.yellow(`memory backend warning: ${S.error}`))),S?.promptContext&&(K+=`
97
97
 
98
- ${S.promptContext}`)}}catch(p){process.env.ZIBBY_VERBOSE==="true"&&i.pushSystem(o.yellow(`memory backend warning: ${String(p?.message||p)}`))}K=Ct(K,tn);let an=co(N),qt=lo([{role:"system",content:K},...an,{role:"user",content:Bt}]),we=le(qt),un=Buffer.byteLength(JSON.stringify(qt),"utf8");process.env.ZIBBY_VERBOSE==="true"&&i.pushSystem(o.gray(`payload estimate: ${we} chars, ${un} bytes (~${Math.round(we/4)} tokens)`)),N.push({role:"human",content:ge});let St=i.enabled?(()=>{let p=()=>{};return p.setLabel=()=>{},p})():Ge(),ut=!0,Et=[],Se="",xt="",xo=50,ko=500,_o=3,vo=60,$o=500,Io=15,Ao=25,To=4,Po=new Set([".","!","?",",",";",":"]),pn=p=>{ut&&(St(),ut=!1),xt+=p},fn=(p,I)=>{if(!p){ut&&St.setLabel("thinking...");return}Et.push(p);let S=70,T=p;if(I&&typeof I=="object"){let v=Object.values(I).map(g=>typeof g=="string"?g:JSON.stringify(g)).join(", "),h=`${p}(${v})`;h.length<=S?T=h:T=`${p}(${v.slice(0,S-p.length-4)}...)`}T!==Se&&(Se=T,i.pushSystem(o.gray(`\u23BF ${T}`)),i.refreshPrompt({preserveInput:!0}),ut&&i.showAssistantLoading()),ut&&St.setLabel(T)},Kt=new AbortController;O=Kt;try{let p=await jn("",{state:{agentType:d,config:c,cwd:t,workspace:t}},{model:c?.agent?.assistant?.model||l.model||"auto",workspace:t,skills:B,activeSkills:B,config:c,timeout:l.timeout||3e5,messages:qt,skipPromptFragments:!0,stream:!0,onToken:pn,onToolCall:fn,signal:Kt.signal});ut&&St();let I=typeof p=="string"?p:p?.structured?JSON.stringify(p.structured,null,2):p?.raw||String(p),S=xt&&xt.trim().length>0?xt.trim():I.trim(),T=po(S,Et)?S:fo(S);i.pushAssistant(T);let _=Et.length>0?`[tools used: ${Et.join(", ")}]
99
- ${S}`:S;N.push({role:"ai",content:_}),At(t,N),Tt(t,B)}catch(p){if(ut&&St(),i.dismissTransientLoading(),Kt.signal.aborted){z.length===0&&i.pushAssistant(o.gray("[cancelled]"));let I="";try{let{testRunnerSkill:T}=await import("../../skills/index.js"),_=await T.handleToolCall("run_status",{runId:"all"},{options:{workspace:t}}),v=JSON.parse(_);v.runs?.length>0&&(I=`
100
- [Active test runs: ${v.runs.map(g=>`${g.runId}: ${g.ticketKey||g.spec} (${g.status})`).join(", ")}. Use run_status("all") to check progress.]`)}catch{}let S=xt.trim();S?N.push({role:"ai",content:S+I}):N.push({role:"ai",content:`[interrupted \u2014 new message]${I}`})}else{let I=String(p?.message||p||"Unknown error");/413|payload too large|request payload too large/i.test(I)?(i.pushAssistant(o.yellow("Request became too large for the proxy (413).")),i.pushSystem(o.gray("Try: /clear, then retry your command; or shorten command/context."))):i.pushAssistant(o.red(`Error: ${I}`)),N.push({role:"ai",content:`[Error: ${p.message}]`})}}finally{O=null,tt=!1}if(i.refreshPrompt(),z.length>0){let p=z.shift();dt=!0,setImmediate(()=>b.emit("line",p))}}catch(a){i.pushSystem(o.red(`Input handling error: ${a?.message||String(a)}`)),i.refreshPrompt()}}),b.on("SIGINT",()=>{if(O){O.abort();return}zt()}),b.on("close",zt);let ln=()=>{process.stdin?.off?(process.stdin.off("data",Nt),process.stdin.off("keypress",Vt)):process.stdin?.removeListener&&(process.stdin.removeListener("data",Nt),process.stdin.removeListener("keypress",Vt))};b.on("close",ln)})}export{ls as _buildPrompt,oo as _checkEnvKeys,no as _formatHistory,cs as _inferAgentType,as as chatCommand};
98
+ ${S.promptContext}`)}}catch(p){process.env.ZIBBY_VERBOSE==="true"&&i.pushSystem(o.yellow(`memory backend warning: ${String(p?.message||p)}`))}K=Ct(K,en);let an=co(N),Kt=lo([{role:"system",content:K},...an,{role:"user",content:Bt}]),Se=ae(Kt),un=Buffer.byteLength(JSON.stringify(Kt),"utf8");process.env.ZIBBY_VERBOSE==="true"&&i.pushSystem(o.gray(`payload estimate: ${Se} chars, ${un} bytes (~${Math.round(Se/4)} tokens)`)),N.push({role:"human",content:he});let St=i.enabled?(()=>{let p=()=>{};return p.setLabel=()=>{},p})():Ve(),ut=!0,Et=[],xe="",xt="",xo=50,ko=500,_o=3,vo=60,$o=500,Io=15,Ao=25,To=4,Po=new Set([".","!","?",",",";",":"]),pn=p=>{ut&&(St(),ut=!1),xt+=p},fn=(p,I)=>{if(!p){ut&&St.setLabel("thinking...");return}Et.push(p);let S=70,T=p;if(I&&typeof I=="object"){let v=Object.values(I).map(g=>typeof g=="string"?g:JSON.stringify(g)).join(", "),h=`${p}(${v})`;h.length<=S?T=h:T=`${p}(${v.slice(0,S-p.length-4)}...)`}T!==xe&&(xe=T,i.pushSystem(o.gray(`\u23BF ${T}`)),i.refreshPrompt({preserveInput:!0}),ut&&i.showAssistantLoading()),ut&&St.setLabel(T)},Xt=new AbortController;O=Xt;try{let p=await jn("",{state:{agentType:d,config:c,cwd:t,workspace:t}},{model:c?.agent?.assistant?.model||l.model||"auto",workspace:t,skills:B,activeSkills:B,config:c,timeout:l.timeout||3e5,messages:Kt,skipPromptFragments:!0,stream:!0,onToken:pn,onToolCall:fn,signal:Xt.signal});ut&&St();let I=typeof p=="string"?p:p?.structured?JSON.stringify(p.structured,null,2):p?.raw||String(p),S=xt&&xt.trim().length>0?xt.trim():I.trim(),T=po(S,Et)?S:fo(S);i.pushAssistant(T);let _=Et.length>0?`[tools used: ${Et.join(", ")}]
99
+ ${S}`:S;N.push({role:"ai",content:_}),At(t,N),Tt(t,B)}catch(p){if(ut&&St(),i.dismissTransientLoading(),Xt.signal.aborted){z.length===0&&i.pushAssistant(o.gray("[cancelled]"));let I="";try{let{testRunnerSkill:T}=await import("../../skills/index.js"),_=await T.handleToolCall("run_status",{runId:"all"},{options:{workspace:t}}),v=JSON.parse(_);v.runs?.length>0&&(I=`
100
+ [Active test runs: ${v.runs.map(g=>`${g.runId}: ${g.ticketKey||g.spec} (${g.status})`).join(", ")}. Use run_status("all") to check progress.]`)}catch{}let S=xt.trim();S?N.push({role:"ai",content:S+I}):N.push({role:"ai",content:`[interrupted \u2014 new message]${I}`})}else{let I=String(p?.message||p||"Unknown error");/413|payload too large|request payload too large/i.test(I)?(i.pushAssistant(o.yellow("Request became too large for the proxy (413).")),i.pushSystem(o.gray("Try: /clear, then retry your command; or shorten command/context."))):i.pushAssistant(o.red(`Error: ${I}`)),N.push({role:"ai",content:`[Error: ${p.message}]`})}}finally{O=null,tt=!1}if(i.refreshPrompt(),z.length>0){let p=z.shift();dt=!0,setImmediate(()=>b.emit("line",p))}}catch(a){i.pushSystem(o.red(`Input handling error: ${a?.message||String(a)}`)),i.refreshPrompt()}}),b.on("SIGINT",()=>{if(O){O.abort();return}Ht()}),b.on("close",Ht);let ln=()=>{process.stdin?.off?(process.stdin.off("data",Nt),process.stdin.off("keypress",qt)):process.stdin?.removeListener&&(process.stdin.removeListener("data",Nt),process.stdin.removeListener("keypress",qt))};b.on("close",ln)})}export{as as _buildPrompt,oo as _checkEnvKeys,no as _formatHistory,ls as _inferAgentType,us as chatCommand};
@@ -46,7 +46,7 @@ Write 4-10 test cases covering:
46
46
  - Related features that might be affected
47
47
 
48
48
  IMPORTANT: Write steps in natural language. Don't use CSS selectors or technical identifiers.
49
- Example step: "Click the 'Submit' button" NOT "Click button[type=submit]"`}function S(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,60)}async function D(e={}){let c=process.cwd(),t=e.agent||process.env.AGENT_TYPE,i=$(c,e.output||"test-specs");t||(console.error(s.red("\u274C No agent specified. Use --agent <codex|claude|cursor|gemini> or set AGENT_TYPE env")),process.exit(1));let a="",d=e.ticket||"unknown";if(e.input){let r=$(c,e.input);w(r)||(console.error(s.red(`\u274C Input file not found: ${r}`)),process.exit(1)),a=R(r,"utf-8")}else if(e.description)a=e.description;else if(e.ticket)try{let{getSkill:r}=await import("@zibby/core/framework/skill-registry.js"),l=r("jira");if(l?.handleToolCall){console.log(s.cyan(`\u{1F4CB} Fetching ticket ${e.ticket} from Jira...`));let n=JSON.parse(await l.handleToolCall(T.GET_ISSUE,{issueKey:e.ticket}));n.error&&(console.error(s.red(`\u274C Jira error: ${n.error}`)),process.exit(1)),d=n.key||e.ticket,a=`Key: ${n.key}
49
+ Example step: "Click the 'Submit' button" NOT "Click button[type=submit]"`}function S(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,60)}async function D(e={}){let c=process.cwd(),t=e.agent||process.env.AGENT_TYPE,i=$(c,e.output||"test-specs");t||(console.error(s.red("\u274C No agent specified. Use --agent <codex|claude|cursor|gemini> or set AGENT_TYPE env")),process.exit(1));let a="",d=e.ticket||"unknown";if(e.input){let r=$(c,e.input);w(r)||(console.error(s.red(`\u274C Input file not found: ${r}`)),process.exit(1)),a=R(r,"utf-8")}else if(e.description)a=e.description;else if(e.ticket)try{let{getSkill:r}=await import("@zibby/skills"),l=r("jira");if(l?.handleToolCall){console.log(s.cyan(`\u{1F4CB} Fetching ticket ${e.ticket} from Jira...`));let n=JSON.parse(await l.handleToolCall(T.GET_ISSUE,{issueKey:e.ticket}));n.error&&(console.error(s.red(`\u274C Jira error: ${n.error}`)),process.exit(1)),d=n.key||e.ticket,a=`Key: ${n.key}
50
50
  Summary: ${n.summary}
51
51
  Type: ${n.type}
52
52
  Priority: ${n.priority}
@@ -1,50 +1,38 @@
1
- import e from"chalk";import{readFileSync as R,existsSync as N}from"fs";import{homedir as v}from"os";import{join as P}from"path";var E="https://logs.workflows.zibby.app",C="https://logs-stream.zibby.app/",S=null;async function A(o){return S||(process.env.ZIBBY_SSE_ENDPOINT?(S=process.env.ZIBBY_SSE_ENDPOINT,S):(S=C,S))}function z(o){let r=P(v(),".zibby","config.json");N(r)||(console.log(e.red(`
1
+ import e from"chalk";import{readFileSync as N,existsSync as R}from"fs";import{homedir as v}from"os";import{join as P}from"path";var E="https://logs.workflows.zibby.app",j="https://logs-stream.zibby.app/",h=null;async function C(i){return h||(process.env.ZIBBY_SSE_ENDPOINT?(h=process.env.ZIBBY_SSE_ENDPOINT,h):(h=j,h))}function A(i){let s=P(v(),".zibby","config.json");R(s)||(console.log(e.red(`
2
2
  Not authenticated`)),console.log(e.gray(` Run: zibby login
3
- `)),process.exit(1));let n;try{n=JSON.parse(R(r,"utf-8"))}catch{console.log(e.red(`
3
+ `)),process.exit(1));let n;try{n=JSON.parse(N(s,"utf-8"))}catch{console.log(e.red(`
4
4
  Config file corrupt`)),console.log(e.gray(` Run: zibby login
5
- `)),process.exit(1)}let i=n.sessionToken;i||(console.log(e.red(`
5
+ `)),process.exit(1)}let a=n.sessionToken;a||(console.log(e.red(`
6
6
  Not authenticated`)),console.log(e.gray(` Run: zibby login
7
- `)),process.exit(1));let f=o.project;return{token:i,projectId:f}}function x(o){return new Date(o).toISOString().replace("T"," ").replace("Z","")}function J(o){return o==="running"?e.yellow(o):o==="completed"?e.green(o):e.red(o||"unknown")}function k(o){return o?.length>16?o.slice(0,16):o}async function I(o,r){let n=await fetch(o,{headers:{Authorization:`Bearer ${r}`}});if(!n.ok){let i=await n.text();throw new Error(`API ${n.status}: ${i}`)}return n.json()}async function U(o,r,n,i){if(o)return o;i||(console.log(e.red(`
8
- Job ID or --project is required`)),console.log(e.gray(" Usage: zibby logs <uuid>")),console.log(e.gray(` zibby logs --workflow ticket-triage --project <id>
9
- `)),process.exit(1));let f=r.workflow;f||(console.log(e.red(`
10
- Job ID or --workflow is required`)),console.log(e.gray(" Usage: zibby logs <uuid>")),console.log(e.gray(" zibby logs --workflow ticket-triage --project <id>")),console.log(e.gray(` zibby logs --workflow ticket-triage --all --project <id>
11
- `)),process.exit(1));let p=new URLSearchParams({workflow:f,limit:"10"}),{jobs:g}=await I(`${E}/jobs/${i}?${p}`,n);(!g||g.length===0)&&(console.log(e.yellow(`
12
- No jobs found for workflow "${f}".`)),process.exit(0)),console.log(e.gray(`
13
- Recent runs for ${e.cyan(f)}:
14
- `));for(let u of g.slice(0,5))console.log(e.gray(` ${k(u.jobId)} ${J(u.status)} ${u.createdAt||""}`));let l=g[0];return console.log(e.gray(`
15
- Tailing latest: ${e.cyan(k(l.jobId))}
16
- `)),l.jobId}async function _({token:o,jobId:r,follow:n}){console.log(e.gray(` Streaming logs for job ${e.cyan(r)}...`)),console.log(n?e.gray(` Press Ctrl+C to stop.
17
- `):"");let i=await A(o);if(!i)return console.log(e.yellow(` SSE endpoint not configured, using CloudWatch polling...
18
- `)),j({token:o,projectId:null,jobId:r,follow:n,limit:1e3});let f=!1,p=null,g=()=>{f=!0,console.log(e.gray(`
7
+ `)),process.exit(1));let f=i.project;return{token:a,projectId:f}}function k(i){return new Date(i).toISOString().replace("T"," ").replace("Z","")}async function T(i,s){let n=await fetch(i,{headers:{Authorization:`Bearer ${s}`}});if(!n.ok){let a=await n.text();throw new Error(`API ${n.status}: ${a}`)}return n.json()}async function _(i,s,n,a){return i||(console.log(e.red(`
8
+ Workflow UUID is required`)),console.log(e.gray(" Usage: zibby logs <workflow-uuid>")),console.log(e.gray(` zibby logs <workflow-uuid> -t
9
+ `)),process.exit(1)),i}async function J({token:i,jobId:s,follow:n}){console.log(e.gray(` Streaming logs for workflow ${e.cyan(s)}...`)),console.log(n?e.gray(` Press Ctrl+C to stop.
10
+ `):"");let a=await C(i);if(!a)return console.log(e.yellow(` SSE endpoint not configured, using CloudWatch polling...
11
+ `)),I({token:i,projectId:null,jobId:s,follow:n,limit:1e3});let f=!1,u=null,c=()=>{f=!0,console.log(e.gray(`
19
12
  Stopped streaming.
20
- `)),process.exit(0)};process.on("SIGINT",g),process.on("SIGTERM",g);try{let l=new URL(i);l.searchParams.set("jobId",r),p&&l.searchParams.set("lastEventId",p);let u=await fetch(l.toString(),{headers:{Authorization:`Bearer ${o}`,Accept:"text/event-stream"}});if(!u.ok)throw new Error(`SSE connection failed: ${u.status} ${u.statusText}`);let y=u.body.getReader(),w=new TextDecoder,m="";for(;!f;){let{done:b,value:d}=await y.read();if(b)break;m+=w.decode(d,{stream:!0});let s=m.split(`
21
- `);m=s.pop()||"";for(let a of s)if(a.trim()){if(a.startsWith("id:"))p=a.slice(3).trim();else if(a.startsWith("event:")){let $=a.slice(6).trim();if($==="complete"){console.log(e.green(`
22
- Job completed.`)),n||process.exit(0);return}if($==="error"){console.log(e.red(`
23
- Job failed.`)),n||process.exit(1);return}}else if(a.startsWith("data:")){let $=a.slice(5).trim();if(!$)continue;try{let c=JSON.parse($),t=e.gray(x(c.timestamp));console.log(`${t} ${c.message.replace(/\n$/,"")}`)}catch{console.log($)}}}}}catch(l){return l.name==="AbortError"?void 0:(console.error(e.red(` SSE Error: ${l.message}`)),console.log(e.yellow(` Falling back to polling mode...
24
- `)),j({token:o,projectId:null,jobId:r,follow:n,limit:1e3}))}}async function L({token:o,projectId:r,workflowUuid:n,follow:i,limit:f}){console.log(e.gray(` Tailing all executions for workflow ${e.cyan(n)}...`)),console.log(e.gray(" Showing live logs from all runs (interleaved by timestamp).")),console.log(e.gray(` Press Ctrl+C to stop.
25
- `));let p=new Set,g=new Set,l=null,u=!1,y=0,w=5,m=()=>{u=!0,console.log(e.gray(`
13
+ `)),process.exit(0)};process.on("SIGINT",c),process.on("SIGTERM",c);try{let l=new URL(a);l.searchParams.set("jobId",s),u&&l.searchParams.set("lastEventId",u);let p=await fetch(l.toString(),{headers:{Authorization:`Bearer ${i}`,Accept:"text/event-stream"}});if(!p.ok)throw new Error(`SSE connection failed: ${p.status} ${p.statusText}`);let w=p.body.getReader(),b=new TextDecoder,d="";for(;!f;){let{done:$,value:m}=await w.read();if($)break;d+=b.decode(m,{stream:!0});let o=d.split(`
14
+ `);d=o.pop()||"";for(let r of o)if(r.trim()){if(r.startsWith("id:"))u=r.slice(3).trim();else if(r.startsWith("event:")){let y=r.slice(6).trim();if(y==="status"||y==="log")continue;if(y==="complete"){console.log(e.green(`
15
+ Job completed.`)),n||process.exit(0);return}if(y==="error"){let g=o[o.indexOf(r)+1];if(g&&g.startsWith("data:"))try{let t=JSON.parse(g.slice(5).trim());if(t.error==="No executions found for workflow"){console.log(e.yellow(`
16
+ No executions found for this workflow. Trigger the workflow first.
17
+ `)),process.exit(1);return}if(t.error==="Task not started yet"){console.log(e.yellow(`
18
+ Task not started yet. Try again in a few seconds.
19
+ `)),process.exit(1);return}}catch{}console.log(e.red(`
20
+ Job failed.`)),n||process.exit(1);return}}else if(r.startsWith("data:")){let y=r.slice(5).trim();if(!y)continue;try{let g=JSON.parse(y);if(g.timestamp&&g.message){let t=e.gray(k(g.timestamp));console.log(`${t} ${g.message.replace(/\n$/,"")}`)}}catch{}}}}}catch(l){return l.name==="AbortError"?void 0:(console.error(e.red(` SSE Error: ${l.message}`)),console.log(e.yellow(` Falling back to polling mode...
21
+ `)),I({token:i,projectId:null,jobId:s,follow:n,limit:1e3}))}}async function I({token:i,projectId:s,jobId:n,follow:a,limit:f}){let u=s?`${E}/logs/${s}/${n}`:`${E}/job/${n}`,c=null,l=0,p=new Set,w=!1,b=0,d=5,$=()=>{w=!0,console.log(e.gray(`
26
22
  Stopped tailing.
27
- `)),process.exit(0)};for(process.on("SIGINT",m),process.on("SIGTERM",m);!u;)try{let b=r?`${E}/logs/${r}/${n}`:`${E}/job/${n}`,d=new URLSearchParams({limit:String(f)}),s=await I(`${b}?${d}`,o);if(y=0,s.executions)for(let c of s.executions)g.has(c.jobId)||(g.size>0&&console.log(e.yellow(`
28
- \u26A1 New execution: ${k(c.jobId)}
29
- `)),g.add(c.jobId));let a=[];for(let c of s.lines||[]){let t=`${c.jobId}:${c.timestamp}:${c.message}`;p.has(t)||(p.add(t),a.push(c))}a.sort((c,t)=>c.timestamp-t.timestamp);for(let c of a){let t=c.jobId||c.executionId;t!==l&&(l!==null&&console.log(""),console.log(e.dim(` \u2500\u2500 Execution: ${k(t)} \u2500\u2500`)),l=t);let h=e.gray(x(c.timestamp));console.log(`${h} ${c.message.replace(/\n$/,"")}`)}if(!i)break;let $=a.length>0?500:2e3;await new Promise(c=>setTimeout(c,$))}catch(b){if(b.name==="AbortError")break;y++,console.error(e.red(` Error: ${b.message}`)),y>=w&&(console.error(e.red(`
30
- Too many consecutive errors (${w}). Stopping.
31
- `)),process.exit(1)),i||process.exit(1),await new Promise(d=>setTimeout(d,3e3))}}async function j({token:o,projectId:r,jobId:n,follow:i,limit:f}){let p=r?`${E}/logs/${r}/${n}`:`${E}/job/${n}`,g=null,l=0,u=new Set,y=!1,w=0,m=5,b=()=>{y=!0,console.log(e.gray(`
23
+ `)),process.exit(0)};for(process.on("SIGINT",$),process.on("SIGTERM",$),console.log(e.gray(` Fetching logs for workflow ${e.cyan(n)}...`)),console.log(a?e.gray(` Press Ctrl+C to stop.
24
+ `):"");!w;)try{let m=new URLSearchParams({limit:String(f)});c&&m.set("nextToken",c);let o=await T(`${u}?${m}`,i);b=0,o.message&&o.lines?.length===0&&l===0&&console.log(e.gray(` ${o.message}`)),o.status==="starting"&&o.lines?.length===0&&l===0&&console.log(e.gray(" Container starting..."));for(let t of o.lines||[]){let S=`${t.timestamp}:${t.message}`;if(p.has(S))continue;p.add(S);let x=e.gray(k(t.timestamp));console.log(`${x} ${t.message.replace(/\n$/,"")}`)}if(l=o.lines?.length>0?0:l+1,c=o.nextForwardToken||null,o.status==="completed"||o.status==="failed"){let t=o.status==="completed"?e.green:e.red;console.log(t(`
25
+ Job ${o.status}.`)),process.exit(o.status==="completed"?0:1)}if(!a){o.status&&console.log(e.gray(`
26
+ Status: ${o.status}`));break}let g=o.lines?.length>0?500:l>5?5e3:2e3;await new Promise(t=>setTimeout(t,g))}catch(m){if(m.name==="AbortError")break;b++,console.error(e.red(` Error: ${m.message}`)),b>=d&&(console.error(e.red(`
27
+ Too many consecutive errors (${d}). Stopping.
28
+ `)),process.exit(1)),a||process.exit(1),await new Promise(o=>setTimeout(o,3e3))}}async function O({token:i,projectId:s,workflow:n,follow:a,limit:f}){let u=`${E}/all/${s}`,c=null,l=0,p=new Set,w=null,b=!1,d=0,$=5,m=()=>{b=!0,console.log(e.gray(`
32
29
  Stopped tailing.
33
- `)),process.exit(0)};for(process.on("SIGINT",b),process.on("SIGTERM",b),console.log(e.gray(` Tailing logs for job ${e.cyan(n)}...`)),console.log(i?e.gray(` Press Ctrl+C to stop.
34
- `):"");!y;)try{let d=new URLSearchParams({limit:String(f)});g&&d.set("nextToken",g);let s=await I(`${p}?${d}`,o);w=0,s.message&&s.lines?.length===0&&l===0&&console.log(e.gray(` ${s.message}`)),s.status==="starting"&&s.lines?.length===0&&l===0&&console.log(e.gray(" Container starting..."));for(let t of s.lines||[]){let h=`${t.timestamp}:${t.message}`;if(u.has(h))continue;u.add(h);let T=e.gray(x(t.timestamp));console.log(`${T} ${t.message.replace(/\n$/,"")}`)}if(l=s.lines?.length>0?0:l+1,g=s.nextForwardToken||null,s.status==="completed"||s.status==="failed"){let t=s.status==="completed"?e.green:e.red;console.log(t(`
35
- Job ${s.status}.`)),process.exit(s.status==="completed"?0:1)}if(!i){s.status&&console.log(e.gray(`
36
- Status: ${s.status}`));break}let c=s.lines?.length>0?500:l>5?5e3:2e3;await new Promise(t=>setTimeout(t,c))}catch(d){if(d.name==="AbortError")break;w++,console.error(e.red(` Error: ${d.message}`)),w>=m&&(console.error(e.red(`
37
- Too many consecutive errors (${m}). Stopping.
38
- `)),process.exit(1)),i||process.exit(1),await new Promise(s=>setTimeout(s,3e3))}}async function O({token:o,projectId:r,workflow:n,follow:i,limit:f}){let p=`${E}/all/${r}`,g=null,l=0,u=new Set,y=null,w=!1,m=0,b=5,d=()=>{w=!0,console.log(e.gray(`
39
- Stopped tailing.
40
- `)),process.exit(0)};for(process.on("SIGINT",d),process.on("SIGTERM",d),console.log(e.gray(`
41
- Tailing all runs for ${e.cyan(n)}...`)),console.log(i?e.gray(` Press Ctrl+C to stop.
42
- `):"");!w;)try{let s=new URLSearchParams({workflow:n,limit:String(f)});g&&s.set("nextToken",g);let a=await I(`${p}?${s}`,o);m=0,a.message&&a.lines?.length===0&&l===0&&console.log(e.gray(` ${a.message}`));for(let t of a.lines||[]){let h=`${t.timestamp}:${t.jobId}:${t.message}`;if(u.has(h))continue;u.add(h),t.jobId!==y&&(y!==null&&console.log(""),console.log(e.dim(` \u2500\u2500 ${k(t.jobId)} \u2500\u2500`)),y=t.jobId);let T=e.gray(x(t.timestamp));console.log(`${T} ${t.message.replace(/\n$/,"")}`)}if(l=a.lines?.length>0?0:l+1,g=a.nextToken||null,!i){g&&console.log(e.gray(`
43
- ... more logs available. Run again or use --follow to stream.`)),a.jobCount&&console.log(e.gray(` ${a.jobCount} job(s) found.`));break}if(!a.hasRunning&&!g&&l>2){console.log(e.gray(`
44
- No running jobs. All caught up.`));break}let c=a.lines?.length>0?500:l>5?5e3:2e3;await new Promise(t=>setTimeout(t,c))}catch(s){if(s.name==="AbortError")break;m++,console.error(e.red(` Error: ${s.message}`)),m>=b&&(console.error(e.red(`
45
- Too many consecutive errors (${b}). Stopping.
46
- `)),process.exit(1)),i||process.exit(1),await new Promise(a=>setTimeout(a,3e3))}}async function W(o,r){let{token:n,projectId:i}=z(r),f=r.follow!==!1,p=r.lines?parseInt(r.lines,10):1e3;if(r.all){let l=r.workflow;return l||(console.log(e.red(`
30
+ `)),process.exit(0)};for(process.on("SIGINT",m),process.on("SIGTERM",m),console.log(e.gray(`
31
+ Tailing all runs for ${e.cyan(n)}...`)),console.log(a?e.gray(` Press Ctrl+C to stop.
32
+ `):"");!b;)try{let o=new URLSearchParams({workflow:n,limit:String(f)});c&&o.set("nextToken",c);let r=await T(`${u}?${o}`,i);d=0,r.message&&r.lines?.length===0&&l===0&&console.log(e.gray(` ${r.message}`));for(let t of r.lines||[]){let S=`${t.timestamp}:${t.jobId}:${t.message}`;if(p.has(S))continue;p.add(S),t.jobId!==w&&(w!==null&&console.log(""),console.log(e.dim(` \u2500\u2500 ${t.jobId} \u2500\u2500`)),w=t.jobId);let x=e.gray(k(t.timestamp));console.log(`${x} ${t.message.replace(/\n$/,"")}`)}if(l=r.lines?.length>0?0:l+1,c=r.nextToken||null,!a){c&&console.log(e.gray(`
33
+ ... more logs available. Run again or use --follow to stream.`)),r.jobCount&&console.log(e.gray(` ${r.jobCount} job(s) found.`));break}if(!r.hasRunning&&!c&&l>2){console.log(e.gray(`
34
+ No running jobs. All caught up.`));break}let g=r.lines?.length>0?500:l>5?5e3:2e3;await new Promise(t=>setTimeout(t,g))}catch(o){if(o.name==="AbortError")break;d++,console.error(e.red(` Error: ${o.message}`)),d>=$&&(console.error(e.red(`
35
+ Too many consecutive errors (${$}). Stopping.
36
+ `)),process.exit(1)),a||process.exit(1),await new Promise(r=>setTimeout(r,3e3))}}async function B(i,s){let{token:n,projectId:a}=A(s),f=s.follow===!0,u=s.lines?parseInt(s.lines,10):1e3;if(s.all){let l=s.workflow;return l||(console.log(e.red(`
47
37
  --workflow is required with --all`)),console.log(e.gray(` Example: zibby logs --workflow ticket-triage --all --project <id>
48
- `)),process.exit(1)),O({token:n,projectId:i,workflow:l,follow:f,limit:p})}if(r.tailLatest)return o||(console.log(e.red(`
49
- Workflow UUID is required with --tail-latest`)),console.log(e.gray(` Example: zibby logs <workflowUuid> -t
50
- `)),process.exit(1)),L({token:n,projectId:i,workflowUuid:o,follow:f,limit:p});let g=await U(o,r,n,i);return f?_({token:n,jobId:g,follow:f}):j({token:n,projectId:i,jobId:g,follow:f,limit:p})}export{W as logsCommand};
38
+ `)),process.exit(1)),O({token:n,projectId:a,workflow:l,follow:f,limit:u})}let c=await _(i,s,n,a);return f?J({token:n,jobId:c,follow:f}):I({token:n,projectId:a,jobId:c,follow:!1,limit:u})}export{B as logsCommand};
@@ -1,22 +1,22 @@
1
- import j from"ora";import{select as m}from"@inquirer/prompts";import{readFileSync as U,existsSync as v}from"fs";import{homedir as B}from"os";import{join as _}from"path";var $={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.app",description:"Production environment"}};function y(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";$[e]?o=$[e].apiUrl:o=$.prod.apiUrl}try{let e=new URL(o);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),$.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),$.prod.apiUrl}}function b(){let o=_(B(),".zibby","config.json");if(v(o))try{let s=JSON.parse(U(o,"utf-8"));if(s.sessionToken)return s.sessionToken}catch{}let e=process.env.ZIBBY_API_KEY;if(e)return e;console.log(`
1
+ import w from"ora";import{select as m}from"@inquirer/prompts";import{readFileSync as v,existsSync as B}from"fs";import{homedir as _}from"os";import{join as b}from"path";var $={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.app",description:"Production environment"}};function y(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";$[e]?o=$[e].apiUrl:o=$.prod.apiUrl}try{let e=new URL(o);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),$.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),$.prod.apiUrl}}function U(){let o=b(_(),".zibby","config.json");if(B(o))try{let r=JSON.parse(v(o,"utf-8"));if(r.sessionToken)return r.sessionToken}catch{}let e=process.env.ZIBBY_API_KEY;if(e)return e;console.log(`
2
2
  Not authenticated`),console.log(" Run: zibby login"),console.log(` OR set ZIBBY_API_KEY env var (for CI/CD)
3
- `),process.exit(1)}async function E(o){let e=y(),s=j("Fetching projects...").start();try{let p=await fetch(`${e}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}});p.ok||(s.fail("Failed to fetch projects"),process.exit(1));let t=await p.json();Array.isArray(t)||(t.projects?t=t.projects:t.data&&(t=t.data)),(!t||t.length===0)&&(s.fail("No projects found"),process.exit(1)),s.succeed(`Found ${t.length} project${t.length===1?"":"s"}`),console.log("");let n=t.map(r=>({name:`${r.name||"Unnamed"} (${r.projectId||r.id})`,value:r.projectId||r.id}));return await m({message:"Select a project:",choices:n})}catch(p){s.fail(`Error: ${p.message}`),process.exit(1)}}async function k(o,e){let s=y(),p=j("Fetching deployed workflows...").start();try{let t=["analysis","implementation","run_test"],n=[];for(let l of t){let d=await fetch(`${s}/projects/${o}/workflows/${l}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}});if(d.ok){let i=await d.json();i.graph&&n.push({name:l,version:i.version||0,isDefault:i.isDefault!==!1})}}n.length===0&&(p.fail("No deployed workflows found for this project"),process.exit(1)),p.succeed(`Found ${n.length} deployed workflow${n.length===1?"":"s"}`),console.log("");let r=n.map(l=>({name:`${l.name} (v${l.version})${l.isDefault?" [default]":""}`,value:l.name}));return await m({message:"Select a workflow to trigger:",choices:r})}catch(t){p.fail(`Error: ${t.message}`),process.exit(1)}}async function Y(o,e={}){let s=b(),t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(o),n=e.project||process.env.ZIBBY_PROJECT_ID,r=o;if(o&&t){let i=y();try{let a=await fetch(`${i}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}});if(a.ok){let f=(await a.json()).projects||[];for(let c of f){let u=await fetch(`${i}/projects/${c.projectId}/workflows`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}});if(u.ok){let I=(await u.json()).find(w=>w.uuid===o);if(I){n=c.projectId,r=I.workflowType||I.name,console.log(`
4
- \u2713 Found workflow "${r}" (UUID: ${o})
5
- `);break}}}(!r||r===o)&&(console.log(`
3
+ `),process.exit(1)}async function E(o){let e=y(),r=w("Fetching projects...").start();try{let p=await fetch(`${e}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}});p.ok||(r.fail("Failed to fetch projects"),process.exit(1));let n=await p.json();Array.isArray(n)||(n.projects?n=n.projects:n.data&&(n=n.data)),(!n||n.length===0)&&(r.fail("No projects found"),process.exit(1)),r.succeed(`Found ${n.length} project${n.length===1?"":"s"}`),console.log("");let t=n.map(s=>({name:`${s.name||"Unnamed"} (${s.projectId||s.id})`,value:s.projectId||s.id}));return await m({message:"Select a project:",choices:t})}catch(p){r.fail(`Error: ${p.message}`),process.exit(1)}}async function T(o,e){let r=y(),p=w("Fetching deployed workflows...").start();try{let n=["analysis","implementation","run_test"],t=[];for(let i of n){let d=await fetch(`${r}/projects/${o}/workflows/${i}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}});if(d.ok){let l=await d.json();l.graph&&t.push({name:i,version:l.version||0,isDefault:l.isDefault!==!1})}}t.length===0&&(p.fail("No deployed workflows found for this project"),process.exit(1)),p.succeed(`Found ${t.length} deployed workflow${t.length===1?"":"s"}`),console.log("");let s=t.map(i=>({name:`${i.name} (v${i.version})${i.isDefault?" [default]":""}`,value:i.name}));return await m({message:"Select a workflow to trigger:",choices:s})}catch(n){p.fail(`Error: ${n.message}`),process.exit(1)}}async function L(o,e={}){let r=U(),n=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(o),t=e.project||process.env.ZIBBY_PROJECT_ID,s=o;if(o&&n){let l=y();try{let a=await fetch(`${l}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`}});if(a.ok){let f=(await a.json()).projects||[];for(let c of f){let u=await fetch(`${l}/projects/${c.projectId}/workflows`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`}});if(u.ok){let j=(await u.json()).find(I=>I.uuid===o);if(j){t=c.projectId,s=j.workflowType||j.name,console.log(`
4
+ \u2713 Found workflow "${s}" (UUID: ${o})
5
+ `);break}}}(!s||s===o)&&(console.log(`
6
6
  Error: Workflow with UUID "${o}" not found`),console.log(` Check: zibby workflow list
7
7
  `),process.exit(1))}}catch(a){console.log(`
8
8
  Error looking up workflow UUID: ${a.message}
9
- `),process.exit(1)}}else if(o&&!n){let i=y();try{let a=await fetch(`${i}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}});if(a.ok){let f=(await a.json()).projects||[],c=[];for(let u of f){let h=await fetch(`${i}/projects/${u.projectId}/workflows`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}});h.ok&&(await h.json()).some(w=>w.workflowType===o)&&c.push(u)}if(c.length===1)n=c[0].projectId,console.log(`
10
- \u2713 Found workflow "${o}" in project: ${c[0].name||n}
9
+ `),process.exit(1)}}else if(o&&!t){let l=y();try{let a=await fetch(`${l}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`}});if(a.ok){let f=(await a.json()).projects||[],c=[];for(let u of f){let h=await fetch(`${l}/projects/${u.projectId}/workflows`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`}});h.ok&&(await h.json()).some(I=>I.workflowType===o)&&c.push(u)}if(c.length===1)t=c[0].projectId,console.log(`
10
+ \u2713 Found workflow "${o}" in project: ${c[0].name||t}
11
11
  `);else if(c.length>1){console.log(`
12
12
  Workflow "${o}" is deployed to multiple projects:
13
- `);let u=c.map(h=>({name:`${h.name||"Unnamed"} (${h.projectId})`,value:h.projectId}));n=await m({message:"Select a project:",choices:u})}else console.log(`
13
+ `);let u=c.map(h=>({name:`${h.name||"Unnamed"} (${h.projectId})`,value:h.projectId}));t=await m({message:"Select a project:",choices:u})}else console.log(`
14
14
  Error: Workflow "${o}" not found in any of your projects`),console.log(` Deploy it first with: zibby deploy ${o}
15
- `),process.exit(1)}}catch{}}n||(console.log(""),n=await E(s)),r||(console.log(""),r=await k(n,s));let l={};if(e.input)try{l=JSON.parse(e.input)}catch(i){console.log(`
16
- Error: Invalid JSON in --input`),console.log(` ${i.message}
15
+ `),process.exit(1)}}catch{}}t||(console.log(""),t=await E(r)),s||(console.log(""),s=await T(t,r));let i={};if(e.input)try{i=JSON.parse(e.input)}catch(l){console.log(`
16
+ Error: Invalid JSON in --input`),console.log(` ${l.message}
17
17
  `),process.exit(1)}console.log(`
18
18
  Triggering Workflow
19
- `),console.log(" ".padEnd(60,"-")),console.log(` Workflow: ${r}`),console.log(` Project: ${n}`),Object.keys(l).length>0&&console.log(` Input: ${JSON.stringify(l).substring(0,50)}...`),e.idempotencyKey&&console.log(` Idempotency: ${e.idempotencyKey}`),console.log(" ".padEnd(60,"-")),console.log("");let d=j("Triggering workflow execution...").start();try{let i=y(),a={input:l};e.idempotencyKey&&(a.idempotencyKey=e.idempotencyKey);let g=await fetch(`${i}/projects/${n}/workflows/${r}/trigger`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(a)});if(!g.ok){let c=await g.json().catch(()=>({}));g.status===429&&(d.fail("Quota exceeded"),console.log(`
19
+ `),console.log(" ".padEnd(60,"-")),console.log(` Workflow: ${s}`),console.log(` Project: ${t}`),Object.keys(i).length>0&&console.log(` Input: ${JSON.stringify(i).substring(0,50)}...`),e.idempotencyKey&&console.log(` Idempotency: ${e.idempotencyKey}`),console.log(" ".padEnd(60,"-")),console.log("");let d=w("Triggering workflow execution...").start();try{let l=y(),a={input:i};e.idempotencyKey&&(a.idempotencyKey=e.idempotencyKey);let g=await fetch(`${l}/projects/${t}/workflows/${s}/trigger`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(a)});if(!g.ok){let c=await g.json().catch(()=>({}));g.status===429&&(d.fail("Quota exceeded"),console.log(`
20
20
  Your workflow execution quota has been exceeded`),c.quotaInfo&&(console.log(` Used: ${c.quotaInfo.used}/${c.quotaInfo.limit} executions`),console.log(` Plan: ${c.quotaInfo.planId}`),c.quotaInfo.periodEnd&&console.log(` Resets: ${new Date(c.quotaInfo.periodEnd).toLocaleDateString()}`)),console.log(""),process.exit(1)),d.fail("Trigger failed"),console.log(` Error: ${c.message||g.statusText}
21
- `),process.exit(1)}let f=await g.json();d.succeed("Workflow triggered successfully"),console.log(""),console.log(" Job Details:"),console.log(` Job ID: ${f.jobId}`),console.log(` Status: ${f.status}`),console.log(` Version: ${f.version}`),console.log(` Triggered: ${new Date(f.triggeredAt).toLocaleString()}`),console.log(""),console.log(" Monitor execution:"),console.log(` zibby logs ${f.jobId}`),console.log(` zibby logs --workflow ${r}`),console.log("")}catch(i){d.fail("Trigger failed"),console.log(` Error: ${i.message}
22
- `),process.exit(1)}}export{Y as triggerWorkflowCommand};
21
+ `),process.exit(1)}let f=await g.json();d.succeed("Workflow triggered successfully"),console.log(""),console.log(" Job Details:"),console.log(` Job ID: ${f.jobId}`),console.log(` Status: ${f.status}`),console.log(` Version: ${f.version}`),console.log(` Triggered: ${new Date(f.triggeredAt).toLocaleString()}`),console.log(""),console.log(" Monitor execution:"),o&&n?(console.log(` zibby logs ${o}`),console.log(` zibby logs ${o} -t`)):(console.log(` zibby logs --workflow ${s} --project ${t}`),console.log(` zibby logs --workflow ${s} --project ${t} -t`)),console.log("")}catch(l){d.fail("Trigger failed"),console.log(` Error: ${l.message}
22
+ `),process.exit(1)}}export{L as triggerWorkflowCommand};
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/cli",
3
- "version": "0.1.68",
3
+ "version": "0.1.69",
4
4
  "description": "Zibby CLI - Test automation generator and runner",
5
5
  "type": "module",
6
6
  "bin": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/cli",
3
- "version": "0.1.68",
3
+ "version": "0.1.69",
4
4
  "description": "Zibby CLI - Test automation generator and runner",
5
5
  "type": "module",
6
6
  "bin": {