@zibby/cli 0.1.83 → 0.1.87

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 m}from"commander";import{initCommand as u}from"../commands/init.js";import{runCommand as f}from"../commands/run.js";import{videoCommand as w}from"../commands/video.js";import{uploadCommand as y}from"../commands/upload.js";import{ciSetupCommand as g}from"../commands/ci-setup.js";import{setupPlaywrightMcpCommand as k,setupCiCommand as b,testWithVideoCommand as h}from"../commands/setup-scripts.js";import{readFileSync as I}from"fs";import{fileURLToPath as v}from"url";import{dirname as C,join as P}from"path";import{bootstrapAgentEnv as _}from"../utils/agent-credentials.js";const S=v(import.meta.url),j=C(S),s=JSON.parse(I(P(j,"../package.json"),"utf-8"));function c(o,e){return e.push(o),e}const p=`zibby v${s.version}`,n=process.argv.slice(2),B=n.includes("-h")||n.includes("--help"),D=n.includes("-v")||n.includes("-V")||n.includes("--version");D&&(console.log(p),process.exit(0));const l=n[0],A=n[1],E=["logs","uninstall"],x=l==="workflow"&&A==="list";!E.includes(l)&&!x&&console.log(`${p}
3
- `),_(process.cwd());const Z=n[0]==="chat",Y=["--verbose","--agent","--stream","-s"],O=n.length>0&&n.every(o=>Y.includes(o)||n[n.indexOf(o)-1]==="--agent"),z=n.length===0||Z||O;if(z&&!B){const o={},e=n.indexOf("--agent");e!==-1&&n[e+1]&&(o.agent=n[e+1]),n.includes("--verbose")&&(o.verbose=!0),(n.includes("--stream")||n.includes("-s"))&&(o.stream=!0);const{chatCommand:i}=await import("../commands/chat.js");await i(o),process.exit(0)}const t=new m;t.name("zibby").description("Zibby Test Automation - AI-powered test generation").version(s.version,"-V, --version"),t.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(u),t.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,e)=>(e.debug?process.env.ZIBBY_DEBUG="true":e.verbose&&(process.env.ZIBBY_VERBOSE="true"),f(o,e))),t.command("implement").description("Implement a Jira ticket using AI agent (runs in ECS container)").action(async(...o)=>{const{implementCommand:e}=await import("../commands/implement.js");return e(...o)}),t.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:e}=await import("../commands/analyze-graph.js");return e(...o)}),t.command("video").description("Organize test videos next to test files").action(w),t.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(y),t.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)}),t.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)}),t.command("status").description("Show current authentication status and token details").option("--json","Output in JSON format (for scripts)").action(async o=>{const{showLoginStatus:e}=await import("../auth/cli-login.js");await e(o),process.exit(0)}),t.command("list").description("List your projects and API tokens").action(async()=>{const{listProjectsCommand:o}=await import("../commands/list-projects.js");await o()}),t.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(g),t.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 e={width:parseInt(o.viewportWidth,10)||1280,height:parseInt(o.viewportHeight,10)||720};return k({...o,viewport:e})}),t.command("setup-ci-full").description("Complete CI/CD setup from scratch").action(b),t.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),t.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:e}=await import("../commands/generate.js");return e(o)}),t.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:e}=await import("../commands/studio.js");return e(o)});const R=t.command("g").description("Generate scaffolds");R.command("workflow [name]").description("Scaffold a new custom workflow in .zibby/workflows/<name>/ (auto-generates name if omitted)").option("--skip-install","Skip running `npm install` in the new workflow folder").action(async(o,e)=>{const{generateWorkflowCommand:i}=await import("../commands/workflows/generate.js");return i(o,e)}),t.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,e)=>{const{startWorkflowCommand:i}=await import("../commands/workflows/start.js");return i(o,e)}),t.command("deploy [workflow-name]").description("Deploy a custom workflow to Zibby Cloud (interactive selection if workflow-name not provided)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--dedicated-ip <action>","Manage dedicated egress IP addon: enable | status | disable | use | unuse").action(async(o,e)=>{if(e.dedicatedIp){const{dedicatedEgressCommand:d}=await import("../commands/workflows/dedicated-egress.js");return d(e.dedicatedIp,e.project)}const{deployWorkflowCommand:i}=await import("../commands/workflows/deploy.js");return i(o,e)}),t.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (interactive selection if not provided). Get UUIDs from `zibby workflow list`.").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",c,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").action(async(o,e)=>{const{triggerWorkflowCommand:i}=await import("../commands/workflows/trigger.js");return i(o,e)}),t.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,e)=>{const{logsCommand:i}=await import("../commands/workflows/logs.js");return i(o,e)}),t.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=t.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:e}=await import("../commands/memory.js");return e(o)}),a.command("reset").description("Wipe the memory database").option("-f, --force","Confirm reset").action(async o=>{const{memoryResetCommand:e}=await import("../commands/memory.js");return e(o)});const r=t.command("workflow").description("Manage workflow graphs \u2014 new, start, deploy, trigger, logs, list, download, delete");r.command("new [name]").description("Scaffold a new custom workflow (alias of `zibby g workflow`)").option("--skip-install","Skip running `npm install` in the new workflow folder").action(async(o,e)=>{const{generateWorkflowCommand:i}=await import("../commands/workflows/generate.js");return i(o,e)}),r.command("start <workflow-name>").description("Start a local dev server for a workflow (alias of `zibby start`)").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(o,e)=>{const{startWorkflowCommand:i}=await import("../commands/workflows/start.js");return i(o,e)}),r.command("deploy [workflow-name]").description("Deploy a workflow to Zibby Cloud (alias of `zibby deploy`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(o,e)=>{const{deployWorkflowCommand:i}=await import("../commands/workflows/deploy.js");return i(o,e)}),r.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (alias of `zibby trigger`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",c,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").action(async(o,e)=>{const{triggerWorkflowCommand:i}=await import("../commands/workflows/trigger.js");return i(o,e)}),r.command("logs [jobId]").description("Tail logs from a workflow execution (alias of `zibby logs`)").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (fetches the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --follow","Stream logs in real-time (like Heroku logs -t)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(o,e)=>{const{logsCommand:i}=await import("../commands/workflows/logs.js");return i(o,e)}),r.command("download [uuid]").description("Download a workflow from Zibby Cloud to .zibby/workflows/<name>/. Pass a UUID (from `zibby workflow list`) for custom workflows, or use --type for built-ins.").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--type <type>","Built-in workflow type: analysis, implementation, run_test (alternative to positional <uuid>)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--output <dir>","Output directory base (default: .zibby/workflows)").option("--include-default","Download the built-in default graph if no custom one exists").action(async(o,e)=>{const{workflowDownloadCommand:i}=await import("../commands/workflow.js");return i({...e,uuid: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:i}=await import("../commands/workflow.js");return i(o)}if(o.localOnly){const{listLocalWorkflowsCommand:i}=await import("../commands/workflows/list.js");return i(o)}const{listAllWorkflowsCommand:e}=await import("../commands/workflows/list.js");return e(o)}),r.command("delete <uuid>").description("Delete a deployed workflow by UUID").action(async o=>{const{deleteWorkflowCommand:e}=await import("../commands/workflows/delete.js");return e(o,{})});const W=t.command("project").description("Manage Zibby projects");W.command("list").description("List all projects").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async o=>{const{projectListCommand:e}=await import("../commands/project.js");return e(o)});const J=t.command("run-queue").description("Parallel capacity \u2014 on-disk wait queue (see parallel.waitWhenAtCapacity in .zibby.config.mjs)");J.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:e}=await import("../commands/run-capacity-queue-cli.js");await e(o),process.exit(0)}),t.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:e}=await import("../commands/uninstall.js");await e(o),process.exit(0)}),t.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 m}from"commander";import{initCommand as u}from"../commands/init.js";import{runCommand as w}from"../commands/run.js";import{videoCommand as f}from"../commands/video.js";import{uploadCommand as y}from"../commands/upload.js";import{ciSetupCommand as g}from"../commands/ci-setup.js";import{setupPlaywrightMcpCommand as k,setupCiCommand as b,testWithVideoCommand as h}from"../commands/setup-scripts.js";import{readFileSync as I}from"fs";import{fileURLToPath as v}from"url";import{dirname as C,join as P}from"path";import{bootstrapAgentEnv as S}from"../utils/agent-credentials.js";const _=v(import.meta.url),B=C(_),s=JSON.parse(I(P(B,"../package.json"),"utf-8"));function c(o,e){return e.push(o),e}const p=`zibby v${s.version}`,n=process.argv.slice(2),j=n.includes("-h")||n.includes("--help"),D=n.includes("-v")||n.includes("-V")||n.includes("--version");D&&(console.log(p),process.exit(0));const l=n[0],A=n[1],E=["logs","uninstall"],x=l==="workflow"&&A==="list";!E.includes(l)&&!x&&console.log(`${p}
3
+ `),S(process.cwd());const Z=n[0]==="chat",Y=["--verbose","--agent","--stream","-s"],O=n.length>0&&n.every(o=>Y.includes(o)||n[n.indexOf(o)-1]==="--agent"),z=n.length===0||Z||O;if(z&&!j){const o={},e=n.indexOf("--agent");e!==-1&&n[e+1]&&(o.agent=n[e+1]),n.includes("--verbose")&&(o.verbose=!0),(n.includes("--stream")||n.includes("-s"))&&(o.stream=!0);const{chatCommand:i}=await import("../commands/chat.js");await i(o),process.exit(0)}const t=new m;t.name("zibby").description("Zibby Test Automation - AI-powered test generation").version(s.version,"-V, --version"),t.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(u),t.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,e)=>(e.debug?process.env.ZIBBY_DEBUG="true":e.verbose&&(process.env.ZIBBY_VERBOSE="true"),w(o,e))),t.command("implement").description("Implement a Jira ticket using AI agent (runs in ECS container)").action(async(...o)=>{const{implementCommand:e}=await import("../commands/implement.js");return e(...o)}),t.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:e}=await import("../commands/analyze-graph.js");return e(...o)}),t.command("video").description("Organize test videos next to test files").action(f),t.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(y),t.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)}),t.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)}),t.command("status").description("Show current authentication status and token details").option("--json","Output in JSON format (for scripts)").action(async o=>{const{showLoginStatus:e}=await import("../auth/cli-login.js");await e(o),process.exit(0)}),t.command("list").description("List your projects and API tokens").action(async()=>{const{listProjectsCommand:o}=await import("../commands/list-projects.js");await o()}),t.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(g),t.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 e={width:parseInt(o.viewportWidth,10)||1280,height:parseInt(o.viewportHeight,10)||720};return k({...o,viewport:e})}),t.command("setup-ci-full").description("Complete CI/CD setup from scratch").action(b),t.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),t.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:e}=await import("../commands/generate.js");return e(o)}),t.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:e}=await import("../commands/studio.js");return e(o)});const R=t.command("g").description("Generate scaffolds");R.command("workflow [name]").description("Scaffold a new custom workflow in .zibby/workflows/<name>/ (auto-generates name if omitted)").option("--skip-install","Skip running `npm install` in the new workflow folder").action(async(o,e)=>{const{generateWorkflowCommand:i}=await import("../commands/workflows/generate.js");return i(o,e)}),t.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,e)=>{const{startWorkflowCommand:i}=await import("../commands/workflows/start.js");return i(o,e)}),t.command("deploy [workflow-name]").description("Deploy a custom workflow to Zibby Cloud (interactive selection if workflow-name not provided)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--dedicated-ip <action>","Manage dedicated egress IP addon: enable | status | disable | use | unuse").option("--verbose","Show raw CodeBuild logs during the bundle build").action(async(o,e)=>{if(e.dedicatedIp){const{dedicatedEgressCommand:d}=await import("../commands/workflows/dedicated-egress.js");return d(e.dedicatedIp,e.project)}const{deployWorkflowCommand:i}=await import("../commands/workflows/deploy.js");return i(o,e)}),t.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (interactive selection if not provided). Get UUIDs from `zibby workflow list`.").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",c,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").action(async(o,e)=>{const{triggerWorkflowCommand:i}=await import("../commands/workflows/trigger.js");return i(o,e)}),t.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,e)=>{const{logsCommand:i}=await import("../commands/workflows/logs.js");return i(o,e)}),t.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=t.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:e}=await import("../commands/memory.js");return e(o)}),a.command("reset").description("Wipe the memory database").option("-f, --force","Confirm reset").action(async o=>{const{memoryResetCommand:e}=await import("../commands/memory.js");return e(o)});const r=t.command("workflow").description("Manage workflow graphs \u2014 new, start, deploy, trigger, logs, list, download, delete");r.command("new [name]").description("Scaffold a new custom workflow (alias of `zibby g workflow`)").option("--skip-install","Skip running `npm install` in the new workflow folder").action(async(o,e)=>{const{generateWorkflowCommand:i}=await import("../commands/workflows/generate.js");return i(o,e)}),r.command("start <workflow-name>").description("Start a local dev server for a workflow (alias of `zibby start`)").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(o,e)=>{const{startWorkflowCommand:i}=await import("../commands/workflows/start.js");return i(o,e)}),r.command("deploy [workflow-name]").description("Deploy a workflow to Zibby Cloud (alias of `zibby deploy`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--verbose","Show raw CodeBuild logs during the bundle build").action(async(o,e)=>{const{deployWorkflowCommand:i}=await import("../commands/workflows/deploy.js");return i(o,e)}),r.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (alias of `zibby trigger`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",c,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").action(async(o,e)=>{const{triggerWorkflowCommand:i}=await import("../commands/workflows/trigger.js");return i(o,e)}),r.command("logs [jobId]").description("Tail logs from a workflow execution (alias of `zibby logs`)").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (fetches the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --follow","Stream logs in real-time (like Heroku logs -t)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(o,e)=>{const{logsCommand:i}=await import("../commands/workflows/logs.js");return i(o,e)}),r.command("download [uuid]").description("Download a workflow from Zibby Cloud to .zibby/workflows/<name>/. Pass a UUID (from `zibby workflow list`) for custom workflows, or use --type for built-ins.").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--type <type>","Built-in workflow type: analysis, implementation, run_test (alternative to positional <uuid>)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--output <dir>","Output directory base (default: .zibby/workflows)").option("--include-default","Download the built-in default graph if no custom one exists").action(async(o,e)=>{const{workflowDownloadCommand:i}=await import("../commands/workflow.js");return i({...e,uuid: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:i}=await import("../commands/workflow.js");return i(o)}if(o.localOnly){const{listLocalWorkflowsCommand:i}=await import("../commands/workflows/list.js");return i(o)}const{listAllWorkflowsCommand:e}=await import("../commands/workflows/list.js");return e(o)}),r.command("delete <uuid>").description("Delete a deployed workflow by UUID").action(async o=>{const{deleteWorkflowCommand:e}=await import("../commands/workflows/delete.js");return e(o,{})});const W=t.command("project").description("Manage Zibby projects");W.command("list").description("List all projects").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async o=>{const{projectListCommand:e}=await import("../commands/project.js");return e(o)});const J=t.command("run-queue").description("Parallel capacity \u2014 on-disk wait queue (see parallel.waitWhenAtCapacity in .zibby.config.mjs)");J.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:e}=await import("../commands/run-capacity-queue-cli.js");await e(o),process.exit(0)}),t.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:e}=await import("../commands/uninstall.js");await e(o),process.exit(0)}),t.parse();
@@ -1,48 +1,48 @@
1
- import{readFileSync as C,writeFileSync as U,existsSync as b,mkdirSync as P}from"fs";import{resolve as N,join as w}from"path";import o from"chalk";import v from"ora";import R from"dotenv";import z from"inquirer";var m={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.app",description:"Production environment"}};function I(){let n;if(process.env.ZIBBY_API_URL)n=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";m[e]?n=m[e].apiUrl:n=m.prod.apiUrl}try{let e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),m.prod.apiUrl):n}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${n}`),m.prod.apiUrl}}function j(){let n=process.env.ZIBBY_ENV||"prod";return m[n]||m.prod}import{validateGraphConfig as Y,generateWorkflowCode as S,generateNodeConfigsJson as L}from"@zibby/agent-workflow";import"@zibby/core/templates/register-nodes.js";R.config();async function Z(n){let e=I(),i=v("Fetching projects...").start();try{let c=await fetch(`${e}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});c.ok||(i.fail("Failed to fetch projects"),process.exit(1));let t=await c.json();Array.isArray(t)||(t.projects&&Array.isArray(t.projects)?t=t.projects:t.data&&Array.isArray(t.data)?t=t.data:(i.fail("Unexpected response format"),process.exit(1))),(!t||t.length===0)&&(i.fail("No projects found"),process.exit(1)),i.stop();let a=t.map(r=>({name:`${r.name||"Unnamed"} (${r.id||"no-id"})`,value:r.id})),{projectId:d}=await z.prompt([{type:"list",name:"projectId",message:"Select a project:",choices:a}]);return d}catch(c){i.fail(`Error: ${c.message}`),process.exit(1)}}function B(n){let e=n.apiKey||process.env.ZIBBY_API_KEY;e||(console.log(o.red(`
1
+ import{readFileSync as Y,writeFileSync as U,existsSync as k,mkdirSync as x}from"fs";import{resolve as S,join as w}from"path";import o from"chalk";import v from"ora";import F from"dotenv";import L from"inquirer";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 I(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";$[e]?t=$[e].apiUrl:t=$.prod.apiUrl}try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${e.protocol} (only http/https allowed)`),$.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),$.prod.apiUrl}}function b(){let t=process.env.ZIBBY_ENV||"prod";return $[t]||$.prod}import{existsSync as z}from"fs";import{join as R}from"path";import{pathToFileURL as N}from"url";async function P(t){let e=R(t,".zibby.config.mjs");if(!z(e))throw new Error(".zibby.config.mjs not found");try{let n=await import(N(e).href);return n.default||n}catch(n){throw new Error(`Failed to load .zibby.config.mjs: ${n.message}`,{cause:n})}}import{validateGraphConfig as Z,generateWorkflowCode as O,generateNodeConfigsJson as K}from"@zibby/agent-workflow";import"@zibby/core/templates/register-nodes.js";F.config();async function J(t){let e=I(),n=v("Fetching projects...").start();try{let l=await fetch(`${e}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});l.ok||(n.fail("Failed to fetch projects"),process.exit(1));let r=await l.json();Array.isArray(r)||(r.projects&&Array.isArray(r.projects)?r=r.projects:r.data&&Array.isArray(r.data)?r=r.data:(n.fail("Unexpected response format"),process.exit(1))),(!r||r.length===0)&&(n.fail("No projects found"),process.exit(1)),n.stop();let p=r.map(a=>({name:`${a.name||"Unnamed"} (${a.id||"no-id"})`,value:a.id})),{projectId:c}=await L.prompt([{type:"list",name:"projectId",message:"Select a project:",choices:p}]);return c}catch(l){n.fail(`Error: ${l.message}`),process.exit(1)}}function B(t){let e=t.apiKey||process.env.ZIBBY_API_KEY;e||(console.log(o.red(`
2
2
  ZIBBY_API_KEY not set`)),console.log(o.gray(` Add to .env: ZIBBY_API_KEY=zby_xxx
3
- `)),process.exit(1));let i=n.project||process.env.ZIBBY_PROJECT_ID;return i||(console.log(o.red(`
3
+ `)),process.exit(1));let n=t.project||process.env.ZIBBY_PROJECT_ID;return n||(console.log(o.red(`
4
4
  --project or ZIBBY_PROJECT_ID is required`)),console.log(o.gray(` Example: zibby workflow download --project <id> --type analysis
5
- `)),process.exit(1)),{apiKey:e,projectId:i}}async function F(n){let e=n.apiKey||process.env.ZIBBY_API_KEY;e||(console.log(o.red(`
5
+ `)),process.exit(1)),{apiKey:e,projectId:n}}async function W(t){let e=t.apiKey||process.env.ZIBBY_API_KEY;e||(console.log(o.red(`
6
6
  ZIBBY_API_KEY not set`)),console.log(o.gray(` Add to .env: ZIBBY_API_KEY=zby_xxx
7
- `)),process.exit(1));let i=n.project||process.env.ZIBBY_PROJECT_ID;return i||(i=await Z(e)),{apiKey:e,projectId:i}}var _=["analysis","implementation","run_test"],O=/^[a-z][a-z0-9_-]{0,62}[a-z0-9]$/;function x(n){let e=n.type;return e||(console.log(o.red(`
7
+ `)),process.exit(1));let n=t.project||process.env.ZIBBY_PROJECT_ID;return n||(n=await J(e)),{apiKey:e,projectId:n}}var _=["analysis","implementation","run_test"],G=/^[a-z][a-z0-9_-]{0,62}[a-z0-9]$/;function D(t){let e=t.type;return e||(console.log(o.red(`
8
8
  --type is required`)),console.log(o.gray(` Built-in types: ${_.join(", ")}`)),console.log(o.gray(` Custom workflows: any lowercase slug (e.g., ticket-triage)
9
- `)),process.exit(1)),!_.includes(e)&&!O.test(e)&&(console.log(o.red(`
9
+ `)),process.exit(1)),!_.includes(e)&&!G.test(e)&&(console.log(o.red(`
10
10
  Invalid workflow type: "${e}"`)),console.log(o.gray(` Built-in: ${_.join(", ")}`)),console.log(o.gray(` Custom: lowercase letters, digits, hyphens (2\u201364 chars)
11
- `)),process.exit(1)),e}var K=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function J(n,e){let i=I(),c={"Content-Type":"application/json",Authorization:`Bearer ${e}`},t=await fetch(`${i}/projects`,{method:"GET",headers:c});if(!t.ok)throw new Error(`Failed to list projects: HTTP ${t.status}`);let{projects:a=[]}=await t.json();for(let d of a){let r=await fetch(`${i}/projects/${d.projectId}/workflows`,{method:"GET",headers:c});if(!r.ok)continue;let s=await r.json(),l=(Array.isArray(s)?s:[]).find(p=>p.uuid===n);if(l){let p=l.workflowType||l.name;return{projectId:d.projectId,workflowType:p}}}return null}async function to(n){let e=j(),i,c,t;if(n.uuid){K.test(n.uuid)||(console.log(o.red(`
12
- '${n.uuid}' is not a UUID.`)),console.log(o.gray(" Cloud workflows are identified by UUID. Run `zibby workflow list` to find yours,")),console.log(o.gray(` or use --type <built-in> for built-in workflow types.
13
- `)),process.exit(1)),t=n.apiKey||process.env.ZIBBY_API_KEY,t||(t=B({...n,project:"pending"}).apiKey);let d=await J(n.uuid,t);d||(console.log(o.red(`
14
- Workflow with UUID '${n.uuid}' not found in any of your projects.`)),console.log(o.gray(` Check: zibby workflow list
15
- `)),process.exit(1)),i=d.projectId,c=d.workflowType}else{let d=B(n);t=d.apiKey,i=d.projectId,c=x(n)}console.log(o.bold.cyan(`
11
+ `)),process.exit(1)),e}var V=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function q(t,e){let n=I(),l={"Content-Type":"application/json",Authorization:`Bearer ${e}`},r=await fetch(`${n}/projects`,{method:"GET",headers:l});if(!r.ok)throw new Error(`Failed to list projects: HTTP ${r.status}`);let{projects:p=[]}=await r.json();for(let c of p){let a=await fetch(`${n}/projects/${c.projectId}/workflows`,{method:"GET",headers:l});if(!a.ok)continue;let s=await a.json(),d=(Array.isArray(s)?s:[]).find(i=>i.uuid===t);if(d){let i=d.workflowType||d.name;return{projectId:c.projectId,workflowType:i}}}return null}async function go(t){let e=b(),n,l,r;if(t.uuid){V.test(t.uuid)||(console.log(o.red(`
12
+ '${t.uuid}' is not a UUID.`)),console.log(o.gray(" Cloud workflows are identified by UUID. Run `zibby workflow list` to find yours,")),console.log(o.gray(` or use --type <built-in> for built-in workflow types.
13
+ `)),process.exit(1)),r=t.apiKey||process.env.ZIBBY_API_KEY,r||(r=B({...t,project:"pending"}).apiKey);let c=await q(t.uuid,r);c||(console.log(o.red(`
14
+ Workflow with UUID '${t.uuid}' not found in any of your projects.`)),console.log(o.gray(` Check: zibby workflow list
15
+ `)),process.exit(1)),n=c.projectId,l=c.workflowType}else{let c=B(t);r=c.apiKey,n=c.projectId,l=D(t)}console.log(o.bold.cyan(`
16
16
  Zibby Workflow Download
17
- `)),console.log(o.gray(" ".padEnd(52,"-"))),console.log(o.white(` Environment: ${o.cyan(e.name)}`)),console.log(o.white(` Project: ${o.cyan(i)}`)),console.log(o.white(` Type: ${o.cyan(c)}`)),console.log(o.gray(" ".padEnd(52,"-")));let a=v(" Fetching workflow from cloud...").start();try{let d=I(),r=await fetch(`${d}/projects/${i}/workflows/${c}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});if(!r.ok){let p=await r.text();a.fail(` API error: ${r.status}`),console.log(o.red(` ${p}
18
- `)),process.exit(1)}let s=await r.json();!s.graph&&s.isDefault?a.info(" No custom workflow saved -- downloading default graph"):a.succeed(` Fetched workflow (v${s.version||0})`);let l=s.graph||null;if(!l){console.log(o.yellow(`
17
+ `)),console.log(o.gray(" ".padEnd(52,"-"))),console.log(o.white(` Environment: ${o.cyan(e.name)}`)),console.log(o.white(` Project: ${o.cyan(n)}`)),console.log(o.white(` Type: ${o.cyan(l)}`)),console.log(o.gray(" ".padEnd(52,"-")));let p=v(" Fetching workflow from cloud...").start();try{let c=I(),a=await fetch(`${c}/projects/${n}/workflows/${l}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`}});if(!a.ok){let i=await a.text();p.fail(` API error: ${a.status}`),console.log(o.red(` ${i}
18
+ `)),process.exit(1)}let s=await a.json();!s.graph&&s.isDefault?p.info(" No custom workflow saved -- downloading default graph"):p.succeed(` Fetched workflow (v${s.version||0})`);let d=s.graph||null;if(!d){console.log(o.yellow(`
19
19
  No graph config available for this workflow.`)),console.log(o.gray(" The project is using the built-in default graph.")),console.log(o.gray(` Edit the graph in the UI first, or use --include-default to download the default.
20
- `)),n.includeDefault||process.exit(0),a.start(" Fetching default graph...");let{getDefaultGraph:p}=await import("@zibby/core/templates/graphs/index.js"),g=p(c);return g||(a.fail(` No default graph found for type "${c}"`),process.exit(1)),D(c,{graph:g,version:0,isDefault:!0,projectId:i,workflowType:c,sources:null,uuid:null},n)}return D(c,{graph:l,version:s.version||0,isDefault:s.isDefault||!1,projectId:i,workflowType:c,sources:s.sources||null,uuid:s.uuid||s.workflowUuid||null},n)}catch(d){a.fail(" Download failed"),console.log(o.red(`
21
- ${d.message}
22
- `)),process.exit(1)}}function D(n,e,i){let c=process.cwd(),t=i.output||w(c,".zibby","workflows"),a=w(t,n);b(a)||P(a,{recursive:!0});let d={projectId:e.projectId,workflowType:e.workflowType,version:e.version,isDefault:e.isDefault},r=[];if(e.sources&&typeof e.sources=="object"&&Object.keys(e.sources).length>0)for(let[l,p]of Object.entries(e.sources)){if(l.includes("..")||l.startsWith("/")){console.log(o.yellow(` \u26A0 Skipping unsafe source path: ${l}`));continue}let g=w(a,l),h=w(g,"..");b(h)||P(h,{recursive:!0}),U(g,p,"utf-8"),r.push(l)}else{let l=w(a,"graph.mjs");U(l,S(e.graph,d),"utf-8"),r.push("graph.mjs");let p=e.graph.nodeConfigs||{},g=L(p),h=w(a,"workflow.config.json");U(h,`${JSON.stringify(g,null,2)}
23
- `,"utf-8"),r.push("workflow.config.json")}if(e.uuid){let l={uuid:e.uuid,name:n,projectId:e.projectId,version:e.version,downloadedAt:new Date().toISOString()};U(w(a,".zibby-deploy.json"),`${JSON.stringify(l,null,2)}
24
- `,"utf-8"),r.push(".zibby-deploy.json")}let s=`.zibby/workflows/${n}/`;console.log(o.green(`
25
- Downloaded to ${o.bold(s)}`));for(let l of r)console.log(o.gray(` ${l}`));console.log(""),console.log(o.gray(` Version: ${e.version}`)),console.log(o.gray(` Nodes: ${e.graph.nodes?.length||0}`)),console.log(o.gray(` Edges: ${e.graph.edges?.length||0}`)),e.uuid&&console.log(o.gray(` UUID: ${e.uuid}`)),console.log(""),console.log(o.white(" Next steps:")),console.log(o.cyan(` cd ${s} && npm install `)+o.gray("Install workflow deps")),console.log(o.cyan(` zibby workflow start ${n} `)+o.gray("Run locally")),console.log(o.cyan(` zibby workflow deploy ${n} `)+o.gray("Re-deploy after changes (same UUID)")),console.log("")}async function ro(n){let e=j(),{apiKey:i,projectId:c}=await F(n),t=x(n);console.log(o.bold.cyan(`
20
+ `)),t.includeDefault||process.exit(0),p.start(" Fetching default graph...");let{getDefaultGraph:i}=await import("@zibby/core/templates/graphs/index.js"),g=i(l);return g||(p.fail(` No default graph found for type "${l}"`),process.exit(1)),C(l,{graph:g,version:0,isDefault:!0,projectId:n,workflowType:l,sources:null,uuid:null},t)}return C(l,{graph:d,version:s.version||0,isDefault:s.isDefault||!1,projectId:n,workflowType:l,sources:s.sources||null,uuid:s.uuid||s.workflowUuid||null},t)}catch(c){p.fail(" Download failed"),console.log(o.red(`
21
+ ${c.message}
22
+ `)),process.exit(1)}}async function C(t,e,n){let l=process.cwd(),r=".zibby/workflows";if(!n.output)try{r=(await P(l))?.paths?.workflows||".zibby/workflows"}catch{}let p=n.output||w(l,r),c=w(p,t);k(c)||x(c,{recursive:!0});let a={projectId:e.projectId,workflowType:e.workflowType,version:e.version,isDefault:e.isDefault},s=[];if(e.sources&&typeof e.sources=="object"&&Object.keys(e.sources).length>0)for(let[i,g]of Object.entries(e.sources)){if(i.includes("..")||i.startsWith("/")){console.log(o.yellow(` \u26A0 Skipping unsafe source path: ${i}`));continue}let y=w(c,i),h=w(y,"..");k(h)||x(h,{recursive:!0}),U(y,g,"utf-8"),s.push(i)}else{let i=w(c,"graph.mjs");U(i,O(e.graph,a),"utf-8"),s.push("graph.mjs");let g=e.graph.nodeConfigs||{},y=K(g),h=w(c,"workflow.config.json");U(h,`${JSON.stringify(y,null,2)}
23
+ `,"utf-8"),s.push("workflow.config.json")}if(e.uuid){let i={uuid:e.uuid,name:t,projectId:e.projectId,version:e.version,downloadedAt:new Date().toISOString()};U(w(c,".zibby-deploy.json"),`${JSON.stringify(i,null,2)}
24
+ `,"utf-8"),s.push(".zibby-deploy.json")}let d=`.zibby/workflows/${t}/`;console.log(o.green(`
25
+ Downloaded to ${o.bold(d)}`));for(let i of s)console.log(o.gray(` ${i}`));console.log(""),console.log(o.gray(` Version: ${e.version}`)),console.log(o.gray(` Nodes: ${e.graph.nodes?.length||0}`)),console.log(o.gray(` Edges: ${e.graph.edges?.length||0}`)),e.uuid&&console.log(o.gray(` UUID: ${e.uuid}`)),console.log(""),console.log(o.white(" Next steps:")),console.log(o.cyan(` cd ${d} && npm install `)+o.gray("Install workflow deps")),console.log(o.cyan(` zibby workflow start ${t} `)+o.gray("Run locally")),console.log(o.cyan(` zibby workflow deploy ${t} `)+o.gray("Re-deploy after changes (same UUID)")),console.log("")}async function uo(t){let e=b(),{apiKey:n,projectId:l}=await W(t),r=D(t);console.log(o.bold.cyan(`
26
26
  Zibby Workflow Upload
27
- `)),console.log(o.gray(" ".padEnd(52,"-"))),console.log(o.white(` Environment: ${o.cyan(e.name)}`)),console.log(o.white(` Project: ${o.cyan(c)}`)),console.log(o.white(` Type: ${o.cyan(t)}`)),console.log(o.gray(" ".padEnd(52,"-")));let a=process.cwd(),d=w(a,".zibby",`workflow-${t}.json`),r=w(a,".zibby",`workflow-${t}.js`),s=n.file||(b(r)?r:d);b(s)||(console.log(o.red(`
27
+ `)),console.log(o.gray(" ".padEnd(52,"-"))),console.log(o.white(` Environment: ${o.cyan(e.name)}`)),console.log(o.white(` Project: ${o.cyan(l)}`)),console.log(o.white(` Type: ${o.cyan(r)}`)),console.log(o.gray(" ".padEnd(52,"-")));let p=process.cwd(),c=w(p,".zibby",`workflow-${r}.json`),a=w(p,".zibby",`workflow-${r}.js`),s=t.file||(k(a)?a:c);k(s)||(console.log(o.red(`
28
28
  File not found: ${s}`)),console.log(o.gray(` Download a workflow first: zibby workflow download --project <id> --type <type>
29
- `)),process.exit(1));let l=s.endsWith(".js")||s.endsWith(".mjs"),p;if(l){let f=v(" Loading JS workflow module...").start();try{let{pathToFileURL:u}=await import("url"),y=await import(u(N(s)).href),$=y.buildGraph();p=$.serialize();let E=y.nodeConfigs||{};if(Object.keys(E).length>0)for(let[A,T]of Object.entries(E))p.nodeConfigs[A]={...T,...p.nodeConfigs[A]};f.succeed(` Loaded JS module (${$.nodes.size} nodes)`)}catch(u){f.fail(" Failed to load JS module"),console.log(o.red(`
29
+ `)),process.exit(1));let d=s.endsWith(".js")||s.endsWith(".mjs"),i;if(d){let f=v(" Loading JS workflow module...").start();try{let{pathToFileURL:u}=await import("url"),m=await import(u(S(s)).href),j=m.buildGraph();i=j.serialize();let E=m.nodeConfigs||{};if(Object.keys(E).length>0)for(let[A,T]of Object.entries(E))i.nodeConfigs[A]={...T,...i.nodeConfigs[A]};f.succeed(` Loaded JS module (${j.nodes.size} nodes)`)}catch(u){f.fail(" Failed to load JS module"),console.log(o.red(`
30
30
  ${u.message}
31
- `)),process.exit(1)}}else{let f;try{f=JSON.parse(C(s,"utf-8"))}catch($){console.log(o.red(`
32
- Failed to parse ${s}: ${$.message}
33
- `)),process.exit(1)}let{_meta:u,...y}=f;p=y}(!p.nodes||!p.edges)&&(console.log(o.red(`
31
+ `)),process.exit(1)}}else{let f;try{f=JSON.parse(Y(s,"utf-8"))}catch(j){console.log(o.red(`
32
+ Failed to parse ${s}: ${j.message}
33
+ `)),process.exit(1)}let{_meta:u,...m}=f;i=m}(!i.nodes||!i.edges)&&(console.log(o.red(`
34
34
  Invalid workflow file: missing nodes or edges`)),console.log(o.gray(` The file should contain { nodes: [...], edges: [...], nodeConfigs: {...} }
35
35
  `)),process.exit(1)),console.log(o.gray(`
36
- File: ${s}`)),console.log(o.gray(` Format: ${l?"JavaScript (serialized via graph.serialize())":"JSON"}`)),console.log(o.gray(` Nodes: ${p.nodes.length}`)),console.log(o.gray(` Edges: ${p.edges.length}`));let g=v(" Validating graph...").start(),h=Y(p);if(!h.valid){g.fail(" Graph validation failed"),console.log("");for(let f of h.errors)console.log(o.red(` ${f}`));console.log(o.gray(`
36
+ File: ${s}`)),console.log(o.gray(` Format: ${d?"JavaScript (serialized via graph.serialize())":"JSON"}`)),console.log(o.gray(` Nodes: ${i.nodes.length}`)),console.log(o.gray(` Edges: ${i.edges.length}`));let g=v(" Validating graph...").start(),y=Z(i);if(!y.valid){g.fail(" Graph validation failed"),console.log("");for(let f of y.errors)console.log(o.red(` ${f}`));console.log(o.gray(`
37
37
  Fix the errors above and try again.
38
- `)),process.exit(1)}g.succeed(" Graph is valid");let k=v(" Uploading to cloud...").start();try{let f=I(),u=await fetch(`${f}/projects/${c}/workflows/${t}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({graph:p})});if(!u.ok){let $=await u.text();k.fail(` API error: ${u.status}`),console.log(o.red(` ${$}
39
- `)),process.exit(1)}let y=await u.json();k.succeed(` Uploaded successfully (v${y.version})`),console.log(o.green(`
40
- Workflow "${t}" updated to version ${y.version}`)),console.log(o.gray(` Project: ${c}
41
- `))}catch(f){k.fail(" Upload failed"),console.log(o.red(`
38
+ `)),process.exit(1)}g.succeed(" Graph is valid");let h=v(" Uploading to cloud...").start();try{let f=I(),u=await fetch(`${f}/projects/${l}/workflows/${r}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({graph:i})});if(!u.ok){let j=await u.text();h.fail(` API error: ${u.status}`),console.log(o.red(` ${j}
39
+ `)),process.exit(1)}let m=await u.json();h.succeed(` Uploaded successfully (v${m.version})`),console.log(o.green(`
40
+ Workflow "${r}" updated to version ${m.version}`)),console.log(o.gray(` Project: ${l}
41
+ `))}catch(f){h.fail(" Upload failed"),console.log(o.red(`
42
42
  ${f.message}
43
- `)),process.exit(1)}}var W=["analysis","implementation","run_test"];async function so(n){let e=j(),{apiKey:i,projectId:c}=B(n);console.log(o.bold.cyan(`
43
+ `)),process.exit(1)}}var M=["analysis","implementation","run_test"];async function wo(t){let e=b(),{apiKey:n,projectId:l}=B(t);console.log(o.bold.cyan(`
44
44
  Zibby Workflows
45
- `));let t=v(" Fetching workflows...").start();try{let a=I(),d=[];for(let r of W){let s=await fetch(`${a}/projects/${c}/workflows/${r}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`}});if(s.ok){let l=await s.json();d.push({type:r,version:l.version||0,isDefault:l.isDefault!==!1&&!l.graph,nodes:l.graph?.nodes?.length||0,updatedAt:l.updatedAt||null})}}t.succeed(` Fetched workflows
46
- `),console.log(o.gray(" ".padEnd(70,"-"))),console.log(o.white(" Type".padEnd(20))+o.white("Version".padEnd(10))+o.white("Nodes".padEnd(10))+o.white("Status".padEnd(15))+o.white("Updated")),console.log(o.gray(" ".padEnd(70,"-")));for(let r of d){let s=r.isDefault?o.gray("default"):o.green("custom"),l=r.updatedAt?new Date(r.updatedAt).toLocaleDateString():o.gray("-");console.log(` ${o.cyan(r.type.padEnd(18))}${String(r.version).padEnd(10)}${String(r.nodes).padEnd(10)}${s.padEnd(15)}${l}`)}console.log(o.gray(" ".padEnd(70,"-"))),console.log("")}catch(a){t.fail(" Failed to fetch workflows"),console.log(o.red(`
47
- ${a.message}
48
- `)),process.exit(1)}}export{to as workflowDownloadCommand,so as workflowListCommand,ro as workflowUploadCommand};
45
+ `));let r=v(" Fetching workflows...").start();try{let p=I(),c=[];for(let a of M){let s=await fetch(`${p}/projects/${l}/workflows/${a}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});if(s.ok){let d=await s.json();c.push({type:a,version:d.version||0,isDefault:d.isDefault!==!1&&!d.graph,nodes:d.graph?.nodes?.length||0,updatedAt:d.updatedAt||null})}}r.succeed(` Fetched workflows
46
+ `),console.log(o.gray(" ".padEnd(70,"-"))),console.log(o.white(" Type".padEnd(20))+o.white("Version".padEnd(10))+o.white("Nodes".padEnd(10))+o.white("Status".padEnd(15))+o.white("Updated")),console.log(o.gray(" ".padEnd(70,"-")));for(let a of c){let s=a.isDefault?o.gray("default"):o.green("custom"),d=a.updatedAt?new Date(a.updatedAt).toLocaleDateString():o.gray("-");console.log(` ${o.cyan(a.type.padEnd(18))}${String(a.version).padEnd(10)}${String(a.nodes).padEnd(10)}${s.padEnd(15)}${d}`)}console.log(o.gray(" ".padEnd(70,"-"))),console.log("")}catch(p){r.fail(" Failed to fetch workflows"),console.log(o.red(`
47
+ ${p.message}
48
+ `)),process.exit(1)}}export{go as workflowDownloadCommand,wo as workflowListCommand,uo as workflowUploadCommand};
@@ -1 +1 @@
1
- function d(n,o){return n?.uuid||n?.workflowUuid||o?.uuid||null}function l({uuid:n,name:o,projectId:i,result:u,existingManifest:e=null,now:t=()=>new Date().toISOString()}){let r=u?.version??(e?.version??0)+1;return{uuid:n,name:o,projectId:i,version:r,deployedAt:t()}}export{l as buildDeployManifest,d as pickCloudUuid};
1
+ function f(e,r){return e?.uuid||e?.workflowUuid||r?.uuid||null}var o=4;function l({elapsedMs:e,phase:r,step:t}){let n=` \u2014 ${Math.max(0,Math.floor(e/1e3))}s`;return t?`Building bundle on Zibby Cloud... [${t.n}/${o}] ${t.label}${n}`:r?`Building bundle on Zibby Cloud... (${r.toLowerCase()})${n}`:`Building bundle on Zibby Cloud...${n}`}var d=/\[(\d+)\/\d+\]\s+(.+?)\s*\.{0,3}\s*$/;function a(e){if(!e)return null;let r=d.exec(e);if(!r)return null;let t=parseInt(r[1],10);return!Number.isInteger(t)||t<1?null:{n:t,label:r[2].trim()}}function c(e){if(!e)return!0;let t=e.trim().replace(/^\[Container\]\s+\d{4}\/\d{2}\/\d{2}\s+\d{2}:\d{2}:\d{2}\.\d+\s*/,"");return!!(/^Phase complete:/.test(t)||/^Phase context status code:/.test(t)||/^Entering phase /.test(t)||/^Running command /.test(t)||/^Phase is /.test(t)||/^Waiting for /.test(t)||/^Registering with agent$/.test(t)||/^Running on CodeBuild /.test(t)||/^Phases found in YAML:/.test(t)||/^CODEBUILD_SRC_DIR=/.test(t)||/^YAML location is /.test(t)||/^Processing environment variables$/.test(t)||/^Moving to directory /.test(t)||/^Cache is not defined /.test(t)||/^Skip cache due to:/.test(t)||/^\s*INSTALL: \d+ commands?$/.test(t)||/^\s*BUILD: \d+ commands?$/.test(t)||/^Set report auto-discover timeout/.test(t)||/^Expanding /.test(t)||/^Assembling file list$/.test(t)||/^No matching auto-discover/.test(t)||/^Report auto-discover/.test(t)||t==="")}function m({uuid:e,name:r,projectId:t,result:u,existingManifest:n=null,now:i=()=>new Date().toISOString()}){let s=u?.version??(n?.version??0)+1;return{uuid:e,name:r,projectId:t,version:s,deployedAt:i()}}export{o as BUNDLE_BUILD_TOTAL_STEPS,m as buildDeployManifest,l as formatBundleSpinnerText,c as isBundleNoiseLine,a as parseBundleStepLine,f as pickCloudUuid};
@@ -1,33 +1,34 @@
1
- import{existsSync as k,readFileSync as W,writeFileSync as Mo}from"fs";import{join as m}from"path";import j from"chalk";import G from"ora";import Ko from"dotenv";import{select as ko}from"@inquirer/prompts";import{existsSync as To}from"fs";import{join as Po}from"path";import{pathToFileURL as Bo}from"url";async function eo(o){let e=Po(o,".zibby.config.mjs");if(!To(e))throw new Error(".zibby.config.mjs not found");try{let n=await import(Bo(e).href);return n.default||n}catch(n){throw new Error(`Failed to load .zibby.config.mjs: ${n.message}`,{cause:n})}}var A={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.app",description:"Production environment"}};function B(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";A[e]?o=A[e].apiUrl:o=A.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)`),A.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),A.prod.apiUrl}}function no(o,e){return o?.uuid||o?.workflowUuid||e?.uuid||null}function to({uuid:o,name:e,projectId:n,result:t,existingManifest:h=null,now:a=()=>new Date().toISOString()}){let s=t?.version??(h?.version??0)+1;return{uuid:o,name:e,projectId:n,version:s,deployedAt:a()}}import{existsSync as Fo,readFileSync as Yo}from"fs";import{join as Zo}from"path";import K from"chalk";import{confirm as Jo}from"@inquirer/prompts";import l from"chalk";import J from"ora";import{spawn as Lo}from"child_process";import{existsSync as so,mkdirSync as Ao,readFileSync as Co,writeFileSync as zo}from"fs";import{homedir as ro}from"os";import{join as O}from"path";function io(){return process.env.ZIBBY_CONFIG_DIR||O(ro(),".zibby")}function lo(){return O(io(),"config.json")}var _o=O(ro(),".zibby"),re=O(_o,"config.json");function Eo(){let o=io();so(o)||Ao(o,{recursive:!0})}function S(){try{let o=lo();if(so(o)){let e=Co(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function C(o){Eo(),zo(lo(),JSON.stringify(o,null,2))}function co(){return S().sessionToken||null}function ao(o){let e=S();e.sessionToken=o,C(e)}function po(){return S().user||null}function uo(o){let e=S();e.user=o,C(e)}function fo(o){let e=S();e.proxyUrl=o,C(e)}function go(o){let e=S();e.mem0ProxyUrl=o,C(e)}function yo(o){let e=S();e.projects=o,C(e)}import{existsSync as ce,mkdirSync as ae,readFileSync as pe,writeFileSync as ue,unlinkSync as fe}from"fs";import{resolve as de}from"path";import{homedir as he}from"os";function Oo(o){let e=process.platform;try{let n,t;return e==="darwin"?(n="open",t=[o]):e==="win32"?(n="cmd",t=["/c","start","",o]):(n="xdg-open",t=[o]),Lo(n,t,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function Do(){let o=co(),e=po();return o&&e?{loggedIn:!0,user:e,token:o}:{loggedIn:!1}}async function wo(){try{console.log(l.cyan(`
1
+ import{existsSync as k,readFileSync as G,writeFileSync as qo}from"fs";import{join as w}from"path";import j from"chalk";import V from"ora";import Xo from"dotenv";import{select as vo}from"@inquirer/prompts";import{existsSync as Ao}from"fs";import{join as _o}from"path";import{pathToFileURL as Eo}from"url";async function to(o){let t=_o(o,".zibby.config.mjs");if(!Ao(t))throw new Error(".zibby.config.mjs not found");try{let e=await import(Eo(t).href);return e.default||e}catch(e){throw new Error(`Failed to load .zibby.config.mjs: ${e.message}`,{cause:e})}}var A={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.app",description:"Production environment"}};function C(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let t=process.env.ZIBBY_ENV||"prod";A[t]?o=A[t].apiUrl:o=A.prod.apiUrl}try{let t=new URL(o);return t.protocol!=="http:"&&t.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${t.protocol} (only http/https allowed)`),A.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),A.prod.apiUrl}}function no(o,t){return o?.uuid||o?.workflowUuid||t?.uuid||null}var Lo=4;function M({elapsedMs:o,phase:t,step:e}){let p=` \u2014 ${Math.max(0,Math.floor(o/1e3))}s`;return e?`Building bundle on Zibby Cloud... [${e.n}/${Lo}] ${e.label}${p}`:t?`Building bundle on Zibby Cloud... (${t.toLowerCase()})${p}`:`Building bundle on Zibby Cloud...${p}`}var zo=/\[(\d+)\/\d+\]\s+(.+?)\s*\.{0,3}\s*$/;function ro(o){if(!o)return null;let t=zo.exec(o);if(!t)return null;let e=parseInt(t[1],10);return!Number.isInteger(e)||e<1?null:{n:e,label:t[2].trim()}}function so(o){if(!o)return!0;let e=o.trim().replace(/^\[Container\]\s+\d{4}\/\d{2}\/\d{2}\s+\d{2}:\d{2}:\d{2}\.\d+\s*/,"");return!!(/^Phase complete:/.test(e)||/^Phase context status code:/.test(e)||/^Entering phase /.test(e)||/^Running command /.test(e)||/^Phase is /.test(e)||/^Waiting for /.test(e)||/^Registering with agent$/.test(e)||/^Running on CodeBuild /.test(e)||/^Phases found in YAML:/.test(e)||/^CODEBUILD_SRC_DIR=/.test(e)||/^YAML location is /.test(e)||/^Processing environment variables$/.test(e)||/^Moving to directory /.test(e)||/^Cache is not defined /.test(e)||/^Skip cache due to:/.test(e)||/^\s*INSTALL: \d+ commands?$/.test(e)||/^\s*BUILD: \d+ commands?$/.test(e)||/^Set report auto-discover timeout/.test(e)||/^Expanding /.test(e)||/^Assembling file list$/.test(e)||/^No matching auto-discover/.test(e)||/^Report auto-discover/.test(e)||e==="")}function io({uuid:o,name:t,projectId:e,result:n,existingManifest:p=null,now:f=()=>new Date().toISOString()}){let r=n?.version??(p?.version??0)+1;return{uuid:o,name:t,projectId:e,version:r,deployedAt:f()}}import{existsSync as Wo,readFileSync as Go}from"fs";import{join as Vo}from"path";import W from"chalk";import{confirm as Ho}from"@inquirer/prompts";import a from"chalk";import J from"ora";import{spawn as Fo}from"child_process";import{existsSync as lo,mkdirSync as Do,readFileSync as Ro,writeFileSync as Oo}from"fs";import{homedir as co}from"os";import{join as R}from"path";function ao(){return process.env.ZIBBY_CONFIG_DIR||R(co(),".zibby")}function uo(){return R(ao(),"config.json")}var No=R(co(),".zibby"),pe=R(No,"config.json");function Yo(){let o=ao();lo(o)||Do(o,{recursive:!0})}function I(){try{let o=uo();if(lo(o)){let t=Ro(o,"utf-8");return JSON.parse(t)}}catch{}return{}}function _(o){Yo(),Oo(uo(),JSON.stringify(o,null,2))}function po(){return I().sessionToken||null}function fo(o){let t=I();t.sessionToken=o,_(t)}function go(){return I().user||null}function yo(o){let t=I();t.user=o,_(t)}function ho(o){let t=I();t.proxyUrl=o,_(t)}function mo(o){let t=I();t.mem0ProxyUrl=o,_(t)}function wo(o){let t=I();t.projects=o,_(t)}import{existsSync as ge,mkdirSync as ye,readFileSync as he,writeFileSync as me,unlinkSync as we}from"fs";import{resolve as ke}from"path";import{homedir as xe}from"os";function Zo(o){let t=process.platform;try{let e,n;return t==="darwin"?(e="open",n=[o]):t==="win32"?(e="cmd",n=["/c","start","",o]):(e="xdg-open",n=[o]),Fo(e,n,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function Mo(){let o=po(),t=go();return o&&t?{loggedIn:!0,user:t,token:o}:{loggedIn:!1}}async function ko(){try{console.log(a.cyan(`
2
2
  \u{1F510} Initiating login...
3
- `));let o=Do();if(o.loggedIn){console.log(l.green("\u2705 Already logged in!")),console.log(l.gray(`User: ${o.user.email}`)),console.log(l.gray(`Name: ${o.user.name}
4
- `));let{createInterface:e}=await import("readline"),n=e({input:process.stdin,output:process.stdout});return new Promise((t,h)=>{let a=()=>{n.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},s=()=>{console.log(l.yellow(`
3
+ `));let o=Mo();if(o.loggedIn){console.log(a.green("\u2705 Already logged in!")),console.log(a.gray(`User: ${o.user.email}`)),console.log(a.gray(`Name: ${o.user.name}
4
+ `));let{createInterface:t}=await import("readline"),e=t({input:process.stdin,output:process.stdout});return new Promise((n,p)=>{let f=()=>{e.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},r=()=>{console.log(a.yellow(`
5
5
 
6
6
  \u26A0\uFE0F Login cancelled
7
- `)),a(),process.exit(0)};process.on("SIGINT",s),n.question(l.yellow("Continue with this session? (Y/n): "),async d=>{process.removeListener("SIGINT",s),a();try{if(d.toLowerCase()==="n"||d.toLowerCase()==="no"){console.log(l.gray(`Starting new login...
8
- `));let u=await ho();t(u)}else console.log(l.green(`Using existing session.
9
- `)),t({success:!0,...o})}catch(u){h(u)}})})}return await ho()}catch(o){return console.error(l.red(`
10
- \u274C Login failed:`,o.message)),{success:!1,error:o.message}}}async function Ro(o){let e=B();try{let n=await fetch(`${e}/projects`,{headers:{Authorization:`Bearer ${o}`}});if(n.ok){let h=((await n.json()).projects||[]).map(a=>({name:a.name,projectId:a.projectId,apiToken:a.apiToken}));return yo(h),h}}catch(n){console.log(l.gray(`\u26A0\uFE0F Could not fetch projects: ${n.message}`))}return[]}async function ho(){let o=B(),e=J("Requesting login code...").start(),n=await fetch(`${o}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!n.ok){e.fail("Failed to request login code");let g=await n.json();throw new Error(g.error||"Failed to initiate login")}let{deviceCode:t,userCode:h,verificationUrl:a,expiresIn:s,interval:d}=await n.json();e.succeed("Login code generated"),console.log(""),console.log(l.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")),console.log(l.cyan("\u2551")+l.white.bold(" Complete login in your browser ")+l.cyan("\u2551")),console.log(l.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")),console.log(""),console.log(l.white("Opening browser to login page...")),console.log(l.gray(`Code expires in ${Math.floor(s/60)} minutes`)),console.log(""),await Oo(a)||(console.log(l.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(l.white("Please open this URL manually: ")+l.blue(a)),console.log(""));let p=J("Waiting for authorization...").start(),f=(d||3)*1e3,i=Math.floor(s/(d||3)),b=0,D=!1,y=()=>{D=!0,p.stop(),console.log(l.yellow(`
7
+ `)),f(),process.exit(0)};process.on("SIGINT",r),e.question(a.yellow("Continue with this session? (Y/n): "),async y=>{process.removeListener("SIGINT",r),f();try{if(y.toLowerCase()==="n"||y.toLowerCase()==="no"){console.log(a.gray(`Starting new login...
8
+ `));let g=await bo();n(g)}else console.log(a.green(`Using existing session.
9
+ `)),n({success:!0,...o})}catch(g){p(g)}})})}return await bo()}catch(o){return console.error(a.red(`
10
+ \u274C Login failed:`,o.message)),{success:!1,error:o.message}}}async function Jo(o){let t=C();try{let e=await fetch(`${t}/projects`,{headers:{Authorization:`Bearer ${o}`}});if(e.ok){let p=((await e.json()).projects||[]).map(f=>({name:f.name,projectId:f.projectId,apiToken:f.apiToken}));return wo(p),p}}catch(e){console.log(a.gray(`\u26A0\uFE0F Could not fetch projects: ${e.message}`))}return[]}async function bo(){let o=C(),t=J("Requesting login code...").start(),e=await fetch(`${o}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){t.fail("Failed to request login code");let l=await e.json();throw new Error(l.error||"Failed to initiate login")}let{deviceCode:n,userCode:p,verificationUrl:f,expiresIn:r,interval:y}=await e.json();t.succeed("Login code generated"),console.log(""),console.log(a.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")),console.log(a.cyan("\u2551")+a.white.bold(" Complete login in your browser ")+a.cyan("\u2551")),console.log(a.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")),console.log(""),console.log(a.white("Opening browser to login page...")),console.log(a.gray(`Code expires in ${Math.floor(r/60)} minutes`)),console.log(""),await Zo(f)||(console.log(a.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(a.white("Please open this URL manually: ")+a.blue(f)),console.log(""));let u=J("Waiting for authorization...").start(),b=(y||3)*1e3,d=Math.floor(r/(y||3)),v=0,m=!1,i=()=>{m=!0,u.stop(),console.log(a.yellow(`
11
11
 
12
12
  \u26A0\uFE0F Login cancelled
13
- `)),process.exit(0)};process.on("SIGINT",y);try{for(;b<i&&!D;){await No(f),b++;let g=await fetch(`${o}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:t})});if(g.status===202)continue;if(!g.ok){p.fail("Authorization failed");let I=await g.json();throw new Error(I.error||"Authorization failed")}let c=await g.json();if(c.status==="authorized"){p.succeed(l.white("Authorization successful!")),ao(c.token),uo(c.user),c.proxyUrl&&fo(c.proxyUrl),c.mem0ProxyUrl&&go(c.mem0ProxyUrl),console.log(""),console.log(l.gray(`User: ${c.user.email}`));let I=J("Fetching projects...").start(),x=await Ro(c.token);return I.succeed(`Fetched ${x.length} project${x.length!==1?"s":""}`),console.log(l.gray(`Session saved to: ~/.zibby/config.json
14
- `)),{success:!0,loggedIn:!0,user:c.user,token:c.token}}if(c.status==="denied")throw p.fail("Authorization denied"),new Error("User denied authorization")}throw p.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",y)}}function No(o){return new Promise(e=>setTimeout(e,o))}function mo(){try{let o=process.env.HOME||process.env.USERPROFILE;if(!o)return null;let e=Zo(o,".zibby","config.json");return Fo(e)&&JSON.parse(Yo(e,"utf-8")).sessionToken||null}catch{return null}}function M(){console.log(`
15
- Not authenticated.`),console.log(` Run ${K.cyan("zibby login")} or set ${K.cyan("ZIBBY_API_KEY")} in your environment.
16
- `)}async function bo(o={}){let e=o.apiKey||process.env.ZIBBY_API_KEY||null,n=mo();if(n||e)return{sessionToken:n,apiKey:e};if(!process.stdin.isTTY){if(o.optional)return{sessionToken:null,apiKey:null};M(),process.exit(1)}console.log(K.yellow(`
17
- Not logged in.`));let t;try{t=await Jo({message:"Open browser to log in now?",default:!0})}catch{t=!1}if(!t){if(o.optional)return{sessionToken:null,apiKey:null};M(),process.exit(1)}if(await wo(),n=mo(),!n){if(o.optional)return{sessionToken:null,apiKey:null};M(),process.exit(1)}return{sessionToken:n,apiKey:null}}Ko.config();async function Wo({apiUrl:o,projectId:e,workflowName:n,buildId:t,authToken:h,spinner:a}){let s=Date.now(),d,u;for(;;){let p=new URL(`${o}/projects/${e}/workflows/${n}/build/${t}`);d&&p.searchParams.set("logsToken",d);let f;try{let i=await fetch(p,{headers:{Authorization:`Bearer ${h}`}});if(!i.ok)throw new Error(`HTTP ${i.status}`);f=await i.json()}catch{await new Promise(b=>setTimeout(b,2e3));continue}f.phase&&f.phase!==u&&(u=f.phase,a.text=`Building bundle on Zibby Cloud... (${u.toLowerCase()})`),f.nextLogsToken&&f.nextLogsToken!==d&&(d=f.nextLogsToken);for(let i of f.logEvents||[]){let b=String(i.m||"").trimEnd();b&&process.stdout.write(` ${b}
18
- `)}if(f.done){let i=(Date.now()-s)/1e3;return{status:f.status,elapsedSec:i,lastPhase:u}}await new Promise(i=>setTimeout(i,2e3))}}async function Go(o,e){let n=B(),t=G("Fetching projects...").start();try{let h=e||o,a=await fetch(`${n}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`}});a.ok||(t.fail("Failed to fetch projects"),process.exit(1));let s=await a.json();Array.isArray(s)||(s.projects&&Array.isArray(s.projects)?s=s.projects:s.data&&Array.isArray(s.data)?s=s.data:(t.fail("Unexpected response format"),process.exit(1))),(!s||s.length===0)&&(t.fail("No projects found"),process.exit(1)),t.succeed(`Found ${s.length} project${s.length===1?"":"s"}`),console.log("");let d=s.map(p=>{let f=p.projectId||p.id||p._id||"unknown";return{name:`${p.name||p.projectName||"Unnamed"} (${f})`,value:f}});return await ko({message:"Select a project to deploy to:",choices:d})}catch(h){t.fail(`Error: ${h.message}`),process.exit(1)}}async function Ze(o,e={}){let n=process.cwd(),t=".zibby/workflows";try{t=(await eo(n))?.paths?.workflows||".zibby/workflows"}catch{}if(o){let y=m(n,t,o);k(y)||(console.log(`
19
- Error: Workflow not found: ${t}/${o}/`),console.log(" Run `zibby workflow list` to see local workflows,"),console.log(` or scaffold a new one: zibby workflow new ${o}
20
- `),process.exit(1))}else{let y=m(n,t);k(y)||(console.log(`
21
- Error: No workflows found in ${t}/`),console.log(` Create one with: zibby workflow new <name>
22
- `),process.exit(1));let{readdir:g,stat:c}=await import("fs/promises"),I=await g(y),x=[];for(let $ of I){let v=m(y,$);if(!(await c(v)).isDirectory())continue;(k(m(v,"graph.mjs"))||k(m(v,"graph.js")))&&x.push($)}x.length===0&&(console.log(`
23
- Error: No workflows found in ${t}/`),console.log(` Create one with: zibby workflow new <name>
24
- `),process.exit(1)),console.log(""),o=await ko({message:"Select a workflow to deploy:",choices:x.map($=>({name:$,value:$}))})}let{sessionToken:h,apiKey:a}=await bo({apiKey:e.apiKey}),s=e.project||process.env.ZIBBY_PROJECT_ID;s||(console.log(""),s=await Go(a,h));let d=h||a,u=m(n,t,o),p=m(u,"graph.mjs"),f=m(u,"workflow.json");k(p)||(console.log(`
25
- Error: graph.mjs not found in ${t}/${o}/`),process.exit(1)),console.log(`
13
+ `)),process.exit(0)};process.on("SIGINT",i);try{for(;v<d&&!m;){await Ko(b),v++;let l=await fetch(`${o}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:n})});if(l.status===202)continue;if(!l.ok){u.fail("Authorization failed");let T=await l.json();throw new Error(T.error||"Authorization failed")}let c=await l.json();if(c.status==="authorized"){u.succeed(a.white("Authorization successful!")),fo(c.token),yo(c.user),c.proxyUrl&&ho(c.proxyUrl),c.mem0ProxyUrl&&mo(c.mem0ProxyUrl),console.log(""),console.log(a.gray(`User: ${c.user.email}`));let T=J("Fetching projects...").start(),x=await Jo(c.token);return T.succeed(`Fetched ${x.length} project${x.length!==1?"s":""}`),console.log(a.gray(`Session saved to: ~/.zibby/config.json
14
+ `)),{success:!0,loggedIn:!0,user:c.user,token:c.token}}if(c.status==="denied")throw u.fail("Authorization denied"),new Error("User denied authorization")}throw u.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",i)}}function Ko(o){return new Promise(t=>setTimeout(t,o))}function jo(){try{let o=process.env.HOME||process.env.USERPROFILE;if(!o)return null;let t=Vo(o,".zibby","config.json");return Wo(t)&&JSON.parse(Go(t,"utf-8")).sessionToken||null}catch{return null}}function K(){console.log(`
15
+ Not authenticated.`),console.log(` Run ${W.cyan("zibby login")} or set ${W.cyan("ZIBBY_API_KEY")} in your environment.
16
+ `)}async function xo(o={}){let t=o.apiKey||process.env.ZIBBY_API_KEY||null,e=jo();if(e||t)return{sessionToken:e,apiKey:t};if(!process.stdin.isTTY){if(o.optional)return{sessionToken:null,apiKey:null};K(),process.exit(1)}console.log(W.yellow(`
17
+ Not logged in.`));let n;try{n=await Ho({message:"Open browser to log in now?",default:!0})}catch{n=!1}if(!n){if(o.optional)return{sessionToken:null,apiKey:null};K(),process.exit(1)}if(await ko(),e=jo(),!e){if(o.optional)return{sessionToken:null,apiKey:null};K(),process.exit(1)}return{sessionToken:e,apiKey:null}}Xo.config();async function Qo({apiUrl:o,projectId:t,workflowName:e,buildId:n,authToken:p,spinner:f,verbose:r}){let y=Date.now(),g,u=null,b=null,d=setInterval(()=>{f.text=M({elapsedMs:Date.now()-y,phase:u,step:b})},1e3);try{for(;;){let v=new URL(`${o}/projects/${t}/workflows/${e}/build/${n}`);g&&v.searchParams.set("logsToken",g);let m;try{let i=await fetch(v,{headers:{Authorization:`Bearer ${p}`}});if(!i.ok)throw new Error(`HTTP ${i.status}`);m=await i.json()}catch{await new Promise(l=>setTimeout(l,2e3));continue}m.phase&&m.phase!==u&&(u=m.phase),m.nextLogsToken&&m.nextLogsToken!==g&&(g=m.nextLogsToken);for(let i of m.logEvents||[]){let l=String(i.m||"").trimEnd();if(!l)continue;let c=ro(l);if(c&&(b=c),r){process.stdout.write(` ${l}
18
+ `);continue}so(l)||c||process.stdout.write(` ${l}
19
+ `)}if(f.text=M({elapsedMs:Date.now()-y,phase:u,step:b}),m.done){let i=(Date.now()-y)/1e3;return{status:m.status,elapsedSec:i,lastPhase:u}}await new Promise(i=>setTimeout(i,2e3))}}finally{clearInterval(d)}}async function oe(o,t){let e=C(),n=V("Fetching projects...").start();try{let p=t||o,f=await fetch(`${e}/projects`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`}});f.ok||(n.fail("Failed to fetch projects"),process.exit(1));let r=await f.json();Array.isArray(r)||(r.projects&&Array.isArray(r.projects)?r=r.projects:r.data&&Array.isArray(r.data)?r=r.data:(n.fail("Unexpected response format"),process.exit(1))),(!r||r.length===0)&&(n.fail("No projects found"),process.exit(1)),n.succeed(`Found ${r.length} project${r.length===1?"":"s"}`),console.log("");let y=r.map(u=>{let b=u.projectId||u.id||u._id||"unknown";return{name:`${u.name||u.projectName||"Unnamed"} (${b})`,value:b}});return await vo({message:"Select a project to deploy to:",choices:y})}catch(p){n.fail(`Error: ${p.message}`),process.exit(1)}}async function Ve(o,t={}){let e=process.cwd(),n=".zibby/workflows";try{n=(await to(e))?.paths?.workflows||".zibby/workflows"}catch{}if(o){let i=w(e,n,o);k(i)||(console.log(`
20
+ Error: Workflow not found: ${n}/${o}/`),console.log(" Run `zibby workflow list` to see local workflows,"),console.log(` or scaffold a new one: zibby workflow new ${o}
21
+ `),process.exit(1))}else{let i=w(e,n);k(i)||(console.log(`
22
+ Error: No workflows found in ${n}/`),console.log(` Create one with: zibby workflow new <name>
23
+ `),process.exit(1));let{readdir:l,stat:c}=await import("fs/promises"),T=await l(i),x=[];for(let U of T){let $=w(i,U);if(!(await c($)).isDirectory())continue;(k(w($,"graph.mjs"))||k(w($,"graph.js")))&&x.push(U)}x.length===0&&(console.log(`
24
+ Error: No workflows found in ${n}/`),console.log(` Create one with: zibby workflow new <name>
25
+ `),process.exit(1)),console.log(""),o=await vo({message:"Select a workflow to deploy:",choices:x.map(U=>({name:U,value:U}))})}let{sessionToken:p,apiKey:f}=await xo({apiKey:t.apiKey}),r=t.project||process.env.ZIBBY_PROJECT_ID;r||(console.log(""),r=await oe(f,p));let y=p||f,g=w(e,n,o),u=w(g,"graph.mjs"),b=w(g,"workflow.json");k(u)||(console.log(`
26
+ Error: graph.mjs not found in ${n}/${o}/`),process.exit(1)),console.log(`
26
27
  Deploying Workflow
27
- `),console.log(" ".padEnd(60,"-")),console.log(` Workflow: ${o}`),console.log(` Project: ${s}`),console.log(" ".padEnd(60,"-")),console.log("");let i=G("Validating workflow...").start(),b=W(p,"utf-8");if(b.includes("@zibby/core")||b.includes("@zibby/skills")){let y=m(u,"package.json");k(y)||(i.fail("Missing package.json"),console.log(""),console.log(j.red(" \u2717 graph.mjs imports @zibby packages but no package.json found")),console.log(""),console.log(j.yellow(" Create package.json with:")),console.log(""),console.log(j.gray(" {")),console.log(j.gray(' "type": "module",')),console.log(j.gray(' "dependencies": {')),console.log(j.gray(' "@zibby/core": "workspace:*"')),console.log(j.gray(" }")),console.log(j.gray(" }")),console.log(""),process.exit(1));let g=JSON.parse(W(y,"utf-8"));!{...g.dependencies,...g.devDependencies}["@zibby/core"]&&b.includes("@zibby/core")&&(i.fail("Missing @zibby/core dependency"),console.log(""),console.log(j.red(" \u2717 graph.mjs imports @zibby/core but it's not in package.json")),console.log(""),console.log(j.yellow(" Add to package.json dependencies:")),console.log(j.gray(' "@zibby/core": "workspace:*"')),console.log(""),process.exit(1))}i.text="Loading workflow graph...";try{let{pathToFileURL:y}=await import("url"),g=await import(y(p).href),c;if(g.default)if(typeof g.default=="function"){let r=g.default.prototype;r&&r.buildGraph?c=new g.default:c=g.default()}else i.fail("graph.mjs must export a class or factory function"),process.exit(1);else{let r=Object.values(g).find(w=>w.prototype&&w.prototype.buildGraph);r?c=new r:(i.fail("graph.mjs must export a WorkflowAgent class or factory function"),process.exit(1))}let x=c.buildGraph().serialize(),{readdir:$,readFile:v}=await import("fs/promises"),U={};i.text="Packaging workflow sources...";let V=await v(p,"utf-8");if(U["graph.mjs"]=V,k(f)){let r=await v(f,"utf-8");U["workflow.json"]=r}let R=m(u,"nodes");if(k(R)){let r=await $(R);for(let w of r)if(w.endsWith(".mjs")||w.endsWith(".js")){let P=m(R,w),Z=await v(P,"utf-8");U[`nodes/${w}`]=Z}}let H=m(u,"package.json");if(k(H)){let r=await v(H,"utf-8");U["package.json"]=r,i.text="Including package.json for dependencies..."}let q=m(u,"package-lock.json");if(k(q)){let r=await v(q,"utf-8");U["package-lock.json"]=r}i.text=`Uploading to cloud (${x.nodes.size||Object.keys(x.nodes||{}).length} nodes, ${Object.keys(U).length} files)...`;let z=B(),X=JSON.stringify({format:1,sources:U}),Q=Buffer.byteLength(X,"utf8"),_=await fetch(`${z}/projects/${s}/workflows/${o}/sources/presign`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${d}`},body:JSON.stringify({contentLength:Q})});if(!_.ok){let r=await _.json().catch(()=>({}));i.fail("Deploy failed (presign)"),console.log(` Error: ${r.error||r.message||_.statusText}
28
- `),process.exit(1)}let jo=await _.json(),{uploadUrl:xo,key:vo,headers:Uo}=jo,N=await fetch(xo,{method:"PUT",headers:{...Uo||{},"Content-Length":String(Q)},body:X});if(!N.ok){let r=await N.text().catch(()=>"");i.fail("Deploy failed (S3 upload)"),console.log(` S3 PUT failed: ${N.status} ${r.slice(0,200)}
29
- `),process.exit(1)}i.text="Saving workflow definition...";let E=await fetch(`${z}/projects/${s}/workflows/${o}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${d}`},body:JSON.stringify({graph:x,sourcesStagingKey:vo,isDefault:!1})});if(!E.ok){let r=await E.json().catch(()=>({}));i.fail("Deploy failed"),console.log(` Error: ${r.message||r.error||E.statusText}
30
- `),process.exit(1)}let F=await E.json(),L=m(u,".zibby-deploy.json"),Y=k(L)?(()=>{try{return JSON.parse(W(L,"utf-8"))}catch{return null}})():null,T=no(F,Y);if(T){let r=to({uuid:T,name:o,projectId:s,result:F,existingManifest:Y});try{Mo(L,`${JSON.stringify(r,null,2)}
31
- `,"utf-8")}catch(w){console.log(` Warning: failed to write ${L}: ${w.message}`)}}let $o=Y?"Updated":"Deployed";if(i.succeed(`${$o} ${o} (v${F.version||1})`),!(e.noWait===!0||process.env.ZIBBY_DEPLOY_NO_BUNDLE==="1")){console.log("");let r=G("Building bundle on Zibby Cloud...").start();try{let w=await fetch(`${z}/projects/${s}/workflows/${o}/build`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${d}`}});if(w.ok){let P=await w.json(),{buildId:Z}=P,{status:oo,elapsedSec:So,lastPhase:Io}=await Wo({apiUrl:z,projectId:s,workflowName:o,buildId:Z,authToken:d,spinner:r});oo==="SUCCEEDED"?r.succeed(`Bundle ready (${So.toFixed(1)}s) \u2014 runtime npm install eliminated`):r.warn(`Bundle build ${oo} at phase ${Io||"unknown"} \u2014 workflow will fall back to runtime install`)}else{let P=await w.json().catch(()=>({}));r.warn(`Bundle build skipped: ${P.error||P.message||w.statusText}`),console.log(` Workflow will use slower runtime install path until next deploy.
32
- `)}}catch(w){r.warn(`Bundle build error: ${w.message}`)}}console.log(""),T&&console.log(` UUID: ${T}`),console.log(""),console.log(" Next steps:"),console.log(` zibby workflow start ${o} Run locally`),T&&console.log(` zibby workflow trigger ${T} Run in cloud`),console.log(" zibby workflow list View all workflows"),console.log("")}catch(y){i.fail("Deploy failed"),console.log(` Error: ${y.message}
33
- `),process.exit(1)}}export{Ze as deployWorkflowCommand};
28
+ `),console.log(" ".padEnd(60,"-")),console.log(` Workflow: ${o}`),console.log(` Project: ${r}`),console.log(" ".padEnd(60,"-")),console.log("");let d=V("Validating workflow...").start(),v=G(u,"utf-8");if(v.includes("@zibby/core")||v.includes("@zibby/skills")){let i=w(g,"package.json");k(i)||(d.fail("Missing package.json"),console.log(""),console.log(j.red(" \u2717 graph.mjs imports @zibby packages but no package.json found")),console.log(""),console.log(j.yellow(" Create package.json with:")),console.log(""),console.log(j.gray(" {")),console.log(j.gray(' "type": "module",')),console.log(j.gray(' "dependencies": {')),console.log(j.gray(' "@zibby/core": "workspace:*"')),console.log(j.gray(" }")),console.log(j.gray(" }")),console.log(""),process.exit(1));let l=JSON.parse(G(i,"utf-8"));!{...l.dependencies,...l.devDependencies}["@zibby/core"]&&v.includes("@zibby/core")&&(d.fail("Missing @zibby/core dependency"),console.log(""),console.log(j.red(" \u2717 graph.mjs imports @zibby/core but it's not in package.json")),console.log(""),console.log(j.yellow(" Add to package.json dependencies:")),console.log(j.gray(' "@zibby/core": "workspace:*"')),console.log(""),process.exit(1))}d.text="Loading workflow graph...";try{let{pathToFileURL:i}=await import("url"),l=await import(i(u).href),c;if(l.default)if(typeof l.default=="function"){let s=l.default.prototype;s&&s.buildGraph?c=new l.default:c=l.default()}else d.fail("graph.mjs must export a class or factory function"),process.exit(1);else{let s=Object.values(l).find(h=>h.prototype&&h.prototype.buildGraph);s?c=new s:(d.fail("graph.mjs must export a WorkflowAgent class or factory function"),process.exit(1))}let x=c.buildGraph().serialize(),{readdir:U,readFile:$}=await import("fs/promises"),S={};d.text="Packaging workflow sources...";let H=await $(u,"utf-8");if(S["graph.mjs"]=H,k(b)){let s=await $(b,"utf-8");S["workflow.json"]=s}let O=w(g,"nodes");if(k(O)){let s=await U(O);for(let h of s)if(h.endsWith(".mjs")||h.endsWith(".js")){let B=w(O,h),Z=await $(B,"utf-8");S[`nodes/${h}`]=Z}}let q=w(g,"package.json");if(k(q)){let s=await $(q,"utf-8");S["package.json"]=s,d.text="Including package.json for dependencies..."}let X=w(g,"package-lock.json");if(k(X)){let s=await $(X,"utf-8");S["package-lock.json"]=s}d.text=`Uploading to cloud (${x.nodes.size||Object.keys(x.nodes||{}).length} nodes, ${Object.keys(S).length} files)...`;let E=C(),Q=JSON.stringify({format:1,sources:S}),oo=Buffer.byteLength(Q,"utf8"),L=await fetch(`${E}/projects/${r}/workflows/${o}/sources/presign`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`},body:JSON.stringify({contentLength:oo})});if(!L.ok){let s=await L.json().catch(()=>({}));d.fail("Deploy failed (presign)"),console.log(` Error: ${s.error||s.message||L.statusText}
29
+ `),process.exit(1)}let $o=await L.json(),{uploadUrl:So,key:Uo,headers:Io}=$o,N=await fetch(So,{method:"PUT",headers:{...Io||{},"Content-Length":String(oo)},body:Q});if(!N.ok){let s=await N.text().catch(()=>"");d.fail("Deploy failed (S3 upload)"),console.log(` S3 PUT failed: ${N.status} ${s.slice(0,200)}
30
+ `),process.exit(1)}d.text="Saving workflow definition...";let z=await fetch(`${E}/projects/${r}/workflows/${o}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`},body:JSON.stringify({graph:x,sourcesStagingKey:Uo,isDefault:!1})});if(!z.ok){let s=await z.json().catch(()=>({}));d.fail("Deploy failed"),console.log(` Error: ${s.message||s.error||z.statusText}
31
+ `),process.exit(1)}let Y=await z.json(),D=w(g,".zibby-deploy.json"),F=k(D)?(()=>{try{return JSON.parse(G(D,"utf-8"))}catch{return null}})():null,P=no(Y,F);if(P){let s=io({uuid:P,name:o,projectId:r,result:Y,existingManifest:F});try{qo(D,`${JSON.stringify(s,null,2)}
32
+ `,"utf-8")}catch(h){console.log(` Warning: failed to write ${D}: ${h.message}`)}}let To=F?"Updated":"Deployed";if(d.succeed(`${To} ${o} (v${Y.version||1})`),!(t.noWait===!0||process.env.ZIBBY_DEPLOY_NO_BUNDLE==="1")){console.log("");let s=V("Building bundle on Zibby Cloud...").start();try{let h=await fetch(`${E}/projects/${r}/workflows/${o}/build`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`}});if(h.ok){let B=await h.json(),{buildId:Z}=B,Po=t.verbose===!0||process.env.ZIBBY_DEPLOY_VERBOSE==="1",{status:eo,elapsedSec:Bo,lastPhase:Co}=await Qo({apiUrl:E,projectId:r,workflowName:o,buildId:Z,authToken:y,spinner:s,verbose:Po});eo==="SUCCEEDED"?s.succeed(`Bundle ready (${Bo.toFixed(1)}s) \u2014 runtime npm install eliminated`):s.warn(`Bundle build ${eo} at phase ${Co||"unknown"} \u2014 workflow will fall back to runtime install`)}else{let B=await h.json().catch(()=>({}));s.warn(`Bundle build skipped: ${B.error||B.message||h.statusText}`),console.log(` Workflow will use slower runtime install path until next deploy.
33
+ `)}}catch(h){s.warn(`Bundle build error: ${h.message}`)}}console.log(""),P&&console.log(` UUID: ${P}`),console.log(""),console.log(" Next steps:"),console.log(` zibby workflow start ${o} Run locally`),P&&console.log(` zibby workflow trigger ${P} Run in cloud`),console.log(" zibby workflow list View all workflows"),console.log("")}catch(i){d.fail("Deploy failed"),console.log(` Error: ${i.message}
34
+ `),process.exit(1)}}export{Ve as deployWorkflowCommand};
@@ -128,7 +128,7 @@ Analyze the input and return a summary with a status.\`,
128
128
  outputSchema: ExampleOutputSchema,
129
129
  };
130
130
  `}function D(o,n){return`${JSON.stringify({name:o,description:`${n} workflow`,entryClass:n,triggers:{api:!0}},null,2)}
131
- `}function Z(){return`${JSON.stringify({type:"module",dependencies:{"@zibby/core":"^0.1.46"}},null,2)}
131
+ `}function Z(){return`${JSON.stringify({type:"module",dependencies:{"@zibby/core":"^0.1.47"}},null,2)}
132
132
  `}async function Ze(o,n={}){let e;o?e=o.toLowerCase():(e=Y(),console.log(t.gray(`
133
133
  No name provided \u2014 generated: ${t.white(e)}`))),T.test(e)||(console.log(t.red(`
134
134
  Invalid workflow name: "${o}"`)),console.log(t.gray(" Must be lowercase, start with a letter, use only a-z, 0-9, hyphens")),console.log(t.gray(" Length: 2\u201364 characters")),console.log(t.gray(` Example: ticket-triage, pr-review, deploy-checker
@@ -1,46 +1,42 @@
1
- import e from"chalk";import{readFileSync as R,existsSync as C}from"fs";import{homedir as _}from"os";import{join as j}from"path";var I="https://logs.workflows.zibby.app",A="https://logs-stream.zibby.app/",S=null;async function O(s){return S||(process.env.ZIBBY_SSE_ENDPOINT?(S=process.env.ZIBBY_SSE_ENDPOINT,S):(S=A,S))}function J(s){let n=j(_(),".zibby","config.json");C(n)||(console.log(e.red(`
1
+ import e from"chalk";import{readFileSync as v,existsSync as N}from"fs";import{homedir as R}from"os";import{join as j}from"path";var I="https://logs.workflows.zibby.app",C="https://logs-stream.zibby.app/",S=null;async function _(a){return S||(process.env.ZIBBY_SSE_ENDPOINT?(S=process.env.ZIBBY_SSE_ENDPOINT,S):(S=C,S))}function A(a){let r=j(R(),".zibby","config.json");N(r)||(console.log(e.red(`
2
2
  Not authenticated`)),console.log(e.gray(` Run: zibby login
3
- `)),process.exit(1));let t;try{t=JSON.parse(R(n,"utf-8"))}catch{console.log(e.red(`
3
+ `)),process.exit(1));let t;try{t=JSON.parse(v(r,"utf-8"))}catch{console.log(e.red(`
4
4
  Config file corrupt`)),console.log(e.gray(` Run: zibby login
5
- `)),process.exit(1)}let c=t.sessionToken;c||(console.log(e.red(`
5
+ `)),process.exit(1)}let n=t.sessionToken;n||(console.log(e.red(`
6
6
  Not authenticated`)),console.log(e.gray(` Run: zibby login
7
- `)),process.exit(1));let f=s.project;return{token:c,projectId:f}}function k(s){return new Date(s).toISOString().replace("T"," ").replace("Z","")}async function P(s,n){let t=await fetch(s,{headers:{Authorization:`Bearer ${n}`}});if(!t.ok){let c=await t.text();throw new Error(`API ${t.status}: ${c}`)}return t.json()}async function z(s,n,t,c){return s||(console.log(e.red(`
7
+ `)),process.exit(1));let f=a.project;return{token:n,projectId:f}}function E(a){return new Date(a).toISOString().replace("T"," ").replace("Z","")}async function k(a,r){let t=await fetch(a,{headers:{Authorization:`Bearer ${r}`}});if(!t.ok){let n=await t.text();throw new Error(`API ${t.status}: ${n}`)}return t.json()}async function O(a,r,t,n){return a||(console.log(e.red(`
8
8
  Workflow UUID is required`)),console.log(e.gray(" Usage: zibby workflow logs <workflow-uuid>")),console.log(e.gray(` zibby workflow logs <workflow-uuid> -t
9
- `)),process.exit(1)),s}async function T({token:s,executionId:n,sseEndpoint:t,stopped:c}){let f=null;try{let l=new URL(t);l.searchParams.set("jobId",n),f&&l.searchParams.set("lastEventId",f);let g=await fetch(l.toString(),{headers:{Authorization:`Bearer ${s}`,Accept:"text/event-stream"}});if(!g.ok)throw new Error(`SSE connection failed: ${g.status} ${g.statusText}`);let r=g.body.getReader(),p=new TextDecoder,y="",w=!1;for(;!c.value;){let{done:$,value:h}=await r.read();if($)break;y+=p.decode(h,{stream:!0});let d=y.split(`
10
- `);y=d.pop()||"";for(let o of d)if(o.trim()){if(o.startsWith("id:"))f=o.slice(3).trim();else if(o.startsWith("event:")){let a=o.slice(6).trim();if(a==="log")continue;if(a==="status"){let u=d[d.indexOf(o)+1];if(u&&u.startsWith("data:"))try{let m=JSON.parse(u.slice(5).trim());if(m.status==="new_execution"){let i=m.executionId,b=`${i.slice(0,8)}...${i.slice(-4)}`,x=m.taskId?m.taskId.slice(-8):"pending";console.log(e.cyan(`
9
+ `)),process.exit(1)),a}async function J({token:a,executionId:r,sseEndpoint:t,stopped:n}){let f=null;try{let l=new URL(t);l.searchParams.set("jobId",r),f&&l.searchParams.set("lastEventId",f);let c=await fetch(l.toString(),{headers:{Authorization:`Bearer ${a}`,Accept:"text/event-stream"}});if(!c.ok)throw new Error(`SSE connection failed: ${c.status} ${c.statusText}`);let s=c.body.getReader(),p=new TextDecoder,u="",y=!1;for(;!n.value;){let{done:h,value:$}=await s.read();if(h)break;u+=p.decode($,{stream:!0});let m=u.split(`
10
+ `);u=m.pop()||"";for(let o of m)if(o.trim()){if(o.startsWith("id:"))f=o.slice(3).trim();else if(o.startsWith("event:")){let g=o.slice(6).trim();if(g==="log")continue;if(g==="status"){let d=m[m.indexOf(o)+1];if(d&&d.startsWith("data:"))try{let w=JSON.parse(d.slice(5).trim());if(w.status==="new_execution"){let i=w.executionId,b=`${i.slice(0,8)}...${i.slice(-4)}`,x=w.taskId?w.taskId.slice(-8):"pending";console.log(e.cyan(`
11
11
  \u250C\u2500 Execution: ${b} (task: ${x})`)),console.log(e.cyan(` \u2514\u2500 Streaming logs...
12
- `))}else m.status==="waiting"&&console.log(e.gray(`
13
- Waiting for next execution...`))}catch{}continue}if(a==="complete"){w=!0;continue}if(a==="error"){let u=d[d.indexOf(o)+1];if(u&&u.startsWith("data:"))try{if(JSON.parse(u.slice(5).trim()).error==="No executions found for workflow")return{notFound:!0}}catch{}return{failed:!0}}}else if(o.startsWith("data:")){let a=o.slice(5).trim();if(!a)continue;try{let u=JSON.parse(a);if(u.timestamp&&u.message){let m=e.gray(k(u.timestamp)),i=u.taskId?e.gray(`(${u.taskId.slice(-8)}) `):"";console.log(`${m} ${i}${u.message.replace(/\n$/,"")}`)}}catch{}}}}return{completed:w}}catch(l){if(l.name==="AbortError")return{aborted:!0};throw l}}async function E({token:s,jobId:n,follow:t,projectId:c}){console.log(e.gray(` Streaming logs for workflow ${e.cyan(n)}...`)),console.log(t?e.gray(` Press Ctrl+C to stop.
14
- `):"");let f=await O(s);if(!f)return console.log(e.yellow(` SSE endpoint not configured, using CloudWatch polling...
15
- `)),v({token:s,projectId:null,jobId:n,follow:t,limit:1e5});let l={value:!1},g=()=>{l.value=!0,console.log(e.gray(`
16
- Stopped streaming.
17
- `)),process.exit(0)};process.on("SIGINT",g),process.on("SIGTERM",g);try{let r=await T({token:s,executionId:n,sseEndpoint:f,stopped:l});if(r.aborted||l.value)return;if(r.notFound)if(t)for(console.log(e.yellow(" No executions found yet. Waiting for workflow to be triggered...")),console.log(e.gray(` Press Ctrl+C to stop.
18
- `));!l.value;){if(await new Promise(p=>setTimeout(p,5e3)),l.value)return;try{if(!(await T({token:s,executionId:n,sseEndpoint:f,stopped:l})).notFound)return}catch{}}else console.log(e.yellow(`
12
+ `))}else w.status==="waiting"&&console.log(e.gray(`
13
+ Waiting for next execution...`))}catch{}continue}if(g==="complete"){y=!0;continue}if(g==="error"){let d=m[m.indexOf(o)+1];if(d&&d.startsWith("data:"))try{if(JSON.parse(d.slice(5).trim()).error==="No executions found for workflow")return{notFound:!0}}catch{}return{failed:!0}}}else if(o.startsWith("data:")){let g=o.slice(5).trim();if(!g)continue;try{let d=JSON.parse(g);if(d.timestamp&&d.message){let w=e.gray(E(d.timestamp)),i=d.taskId?e.gray(`(${d.taskId.slice(-8)}) `):"";console.log(`${w} ${i}${d.message.replace(/\n$/,"")}`)}}catch{}}}}return{completed:y}}catch(l){if(l.name==="AbortError")return{aborted:!0};throw l}}function M(a,{baseMs:r=500,capMs:t=3e4,rand:n=Math.random}={}){let f=Math.min(t,r*Math.pow(2,Math.max(0,a)));return Math.floor(n()*f)}async function z({attemptStream:a,stopped:r,follow:t,logger:n,sleep:f=p=>new Promise(u=>setTimeout(u,p)),exit:l=p=>{throw new Error(`exit:${p}`)},backoff:c=M,notFoundPollMs:s=5e3}){let p=0,u=!1;for(;!r.value;){let y;try{y=await a(),p=0}catch(h){if(h.name==="AbortError"||r.value)return{reason:"aborted"};if(u||(n.error(` SSE Error: ${h.message}`),t&&n.gray(" Reconnecting..."),u=!0),!t)return l("error")??{reason:"error"};let $=c(p);p++,await f($);continue}if(y.aborted||r.value)return{reason:"aborted"};if(y.notFound){if(t){u||(n.yellow(" No executions found yet. Waiting for workflow to be triggered..."),n.gray(" Press Ctrl+C to stop."),u=!0),await f(s);continue}return n.yellow(`
19
14
  No executions found for this workflow. Trigger the workflow first.
20
- `)),process.exit(1);if(r.failed){console.log(e.red(`
21
- Execution failed.`)),t||process.exit(1);return}if(r.completed&&process.exit(0),t&&!l.value)return console.log(e.gray(`
22
- Connection ended, reconnecting...
23
- `)),E({token:s,jobId:n,follow:t,projectId:null})}catch(r){if(r.name==="AbortError"||l.value)return;if(console.error(e.red(` SSE Error: ${r.message}`)),t&&!l.value)return console.log(e.gray(`
24
- Reconnecting...
25
- `)),E({token:s,jobId:n,follow:t,projectId:null})}}async function v({token:s,projectId:n,jobId:t,follow:c,limit:f}){let l=n?`${I}/logs/${n}/${t}`:`${I}/job/${t}`,g=null,r=0,p=new Set,y=!1,w=0,$=5,h=()=>{y=!0,console.log(e.gray(`
15
+ `),l("notFound")??{reason:"notFound"}}if(u&&(n.gray(` Reconnected.
16
+ `),u=!1),y.failed)return n.red(`
17
+ Execution failed.`),t?{reason:"failed"}:l("failed")??{reason:"failed"};if(y.completed)return l("completed")??{reason:"completed"};if(!t)return{reason:"disconnected"}}return{reason:"stopped"}}async function L({token:a,jobId:r,follow:t,projectId:n}){console.log(e.gray(` Streaming logs for workflow ${e.cyan(r)}...`)),console.log(t?e.gray(` Press Ctrl+C to stop.
18
+ `):"");let f=await _(a);if(!f)return console.log(e.yellow(` SSE endpoint not configured, using CloudWatch polling...
19
+ `)),T({token:a,projectId:null,jobId:r,follow:t,limit:1e5});let l={value:!1},c=()=>{l.value=!0,console.log(e.gray(`
20
+ Stopped streaming.
21
+ `)),process.exit(0)};process.on("SIGINT",c),process.on("SIGTERM",c),await z({attemptStream:()=>J({token:a,executionId:r,sseEndpoint:f,stopped:l}),stopped:l,follow:t,logger:{gray:s=>console.log(e.gray(s)),red:s=>console.log(e.red(s)),yellow:s=>console.log(e.yellow(s)),error:s=>console.error(e.red(s))},exit:s=>{s==="completed"&&process.exit(0),(s==="error"||s==="notFound"||s==="failed")&&process.exit(1)}})}async function T({token:a,projectId:r,jobId:t,follow:n,limit:f}){let l=r?`${I}/logs/${r}/${t}`:`${I}/job/${t}`,c=null,s=0,p=new Set,u=!1,y=0,h=5,$=()=>{u=!0,console.log(e.gray(`
26
22
  Stopped tailing.
27
- `)),process.exit(0)};for(process.on("SIGINT",h),process.on("SIGTERM",h),console.log(e.gray(` Fetching logs for workflow ${e.cyan(t)}...`)),console.log(c?e.gray(` Press Ctrl+C to stop.
28
- `):"");!y;)try{let d=new URLSearchParams({limit:String(f)});g&&d.set("nextToken",g);let o=await P(`${l}?${d}`,s);w=0,o.message&&o.lines?.length===0&&r===0&&console.log(e.gray(` ${o.message}`)),o.status==="starting"&&o.lines?.length===0&&r===0&&console.log(e.gray(" Container starting..."));for(let i of o.lines||[]){let b=`${i.timestamp}:${i.message}`;if(p.has(b))continue;p.add(b);let x=e.gray(k(i.timestamp)),N=o.taskId?e.gray(`(${o.taskId.slice(-8)}) `):"";console.log(`${x} ${N}${i.message.replace(/\n$/,"")}`)}if(r=o.lines?.length>0?0:r+1,g=o.nextForwardToken||null,o.status==="completed"||o.status==="failed"){let i=o.status==="completed"?e.green:e.red;console.log(i(`
29
- Job ${o.status}.`)),process.exit(o.status==="completed"?0:1)}if(!c){o.status&&console.log(e.gray(`
30
- Status: ${o.status}`));break}let m=o.lines?.length>0?500:r>5?5e3:2e3;await new Promise(i=>setTimeout(i,m))}catch(d){if(d.name==="AbortError")break;d.message.match(/API (400|401|403|404):/)&&(console.error(e.red(`
31
- ${d.message}
32
- `)),process.exit(1)),w++,console.error(e.red(` Error: ${d.message}`)),w>=$&&(console.error(e.red(`
33
- Too many consecutive errors (${$}). Stopping.
34
- `)),process.exit(1)),c||process.exit(1),await new Promise(a=>setTimeout(a,3e3))}}async function L({token:s,projectId:n,workflow:t,follow:c,limit:f}){let l=`${I}/all/${n}`,g=null,r=0,p=new Set,y=null,w=!1,$=0,h=5,d=()=>{w=!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(t)}...`)),console.log(n?e.gray(` Press Ctrl+C to stop.
24
+ `):"");!u;)try{let m=new URLSearchParams({limit:String(f)});c&&m.set("nextToken",c);let o=await k(`${l}?${m}`,a);y=0,o.message&&o.lines?.length===0&&s===0&&console.log(e.gray(` ${o.message}`)),o.status==="starting"&&o.lines?.length===0&&s===0&&console.log(e.gray(" Container starting..."));for(let i of o.lines||[]){let b=`${i.timestamp}:${i.message}`;if(p.has(b))continue;p.add(b);let x=e.gray(E(i.timestamp)),P=o.taskId?e.gray(`(${o.taskId.slice(-8)}) `):"";console.log(`${x} ${P}${i.message.replace(/\n$/,"")}`)}if(s=o.lines?.length>0?0:s+1,c=o.nextForwardToken||null,o.status==="completed"||o.status==="failed"){let i=o.status==="completed"?e.green:e.red;console.log(i(`
25
+ Job ${o.status}.`)),process.exit(o.status==="completed"?0:1)}if(!n){o.status&&console.log(e.gray(`
26
+ Status: ${o.status}`));break}let w=o.lines?.length>0?500:s>5?5e3:2e3;await new Promise(i=>setTimeout(i,w))}catch(m){if(m.name==="AbortError")break;m.message.match(/API (400|401|403|404):/)&&(console.error(e.red(`
27
+ ${m.message}
28
+ `)),process.exit(1)),y++,console.error(e.red(` Error: ${m.message}`)),y>=h&&(console.error(e.red(`
29
+ Too many consecutive errors (${h}). Stopping.
30
+ `)),process.exit(1)),n||process.exit(1),await new Promise(g=>setTimeout(g,3e3))}}async function F({token:a,projectId:r,workflow:t,follow:n,limit:f}){let l=`${I}/all/${r}`,c=null,s=0,p=new Set,u=null,y=!1,h=0,$=5,m=()=>{y=!0,console.log(e.gray(`
35
31
  Stopped tailing.
36
- `)),process.exit(0)};for(process.on("SIGINT",d),process.on("SIGTERM",d),console.log(e.gray(`
37
- Tailing all runs for ${e.cyan(t)}...`)),console.log(c?e.gray(` Press Ctrl+C to stop.
38
- `):"");!w;)try{let o=new URLSearchParams({workflow:t,limit:String(f)});g&&o.set("nextToken",g);let a=await P(`${l}?${o}`,s);$=0,a.message&&a.lines?.length===0&&r===0&&console.log(e.gray(` ${a.message}`));for(let i of a.lines||[]){let b=`${i.timestamp}:${i.jobId}:${i.message}`;if(p.has(b))continue;p.add(b),i.jobId!==y&&(y!==null&&console.log(""),console.log(e.dim(` \u2500\u2500 ${i.jobId} \u2500\u2500`)),y=i.jobId);let x=e.gray(k(i.timestamp));console.log(`${x} ${i.message.replace(/\n$/,"")}`)}if(r=a.lines?.length>0?0:r+1,g=a.nextToken||null,!c){g&&console.log(e.gray(`
39
- ... 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&&r>2){console.log(e.gray(`
40
- No running jobs. All caught up.`));break}let m=a.lines?.length>0?500:r>5?5e3:2e3;await new Promise(i=>setTimeout(i,m))}catch(o){if(o.name==="AbortError")break;o.message.match(/API (400|401|403|404):/)&&(console.error(e.red(`
32
+ `)),process.exit(0)};for(process.on("SIGINT",m),process.on("SIGTERM",m),console.log(e.gray(`
33
+ Tailing all runs for ${e.cyan(t)}...`)),console.log(n?e.gray(` Press Ctrl+C to stop.
34
+ `):"");!y;)try{let o=new URLSearchParams({workflow:t,limit:String(f)});c&&o.set("nextToken",c);let g=await k(`${l}?${o}`,a);h=0,g.message&&g.lines?.length===0&&s===0&&console.log(e.gray(` ${g.message}`));for(let i of g.lines||[]){let b=`${i.timestamp}:${i.jobId}:${i.message}`;if(p.has(b))continue;p.add(b),i.jobId!==u&&(u!==null&&console.log(""),console.log(e.dim(` \u2500\u2500 ${i.jobId} \u2500\u2500`)),u=i.jobId);let x=e.gray(E(i.timestamp));console.log(`${x} ${i.message.replace(/\n$/,"")}`)}if(s=g.lines?.length>0?0:s+1,c=g.nextToken||null,!n){c&&console.log(e.gray(`
35
+ ... more logs available. Run again or use --follow to stream.`)),g.jobCount&&console.log(e.gray(` ${g.jobCount} job(s) found.`));break}if(!g.hasRunning&&!c&&s>2){console.log(e.gray(`
36
+ No running jobs. All caught up.`));break}let w=g.lines?.length>0?500:s>5?5e3:2e3;await new Promise(i=>setTimeout(i,w))}catch(o){if(o.name==="AbortError")break;o.message.match(/API (400|401|403|404):/)&&(console.error(e.red(`
41
37
  ${o.message}
42
- `)),process.exit(1)),$++,console.error(e.red(` Error: ${o.message}`)),$>=h&&(console.error(e.red(`
43
- Too many consecutive errors (${h}). Stopping.
44
- `)),process.exit(1)),c||process.exit(1),await new Promise(u=>setTimeout(u,3e3))}}async function F(s,n){let{token:t,projectId:c}=J(n),f=n.follow===!0,l=n.lines?parseInt(n.lines,10):1e5;if(n.all){let r=n.workflow;return r||(console.log(e.red(`
38
+ `)),process.exit(1)),h++,console.error(e.red(` Error: ${o.message}`)),h>=$&&(console.error(e.red(`
39
+ Too many consecutive errors (${$}). Stopping.
40
+ `)),process.exit(1)),n||process.exit(1),await new Promise(d=>setTimeout(d,3e3))}}async function B(a,r){let{token:t,projectId:n}=A(r),f=r.follow===!0,l=r.lines?parseInt(r.lines,10):1e5;if(r.all){let s=r.workflow;return s||(console.log(e.red(`
45
41
  --workflow is required with --all`)),console.log(e.gray(` Example: zibby workflow logs --workflow ticket-triage --all --project <id>
46
- `)),process.exit(1)),L({token:t,projectId:c,workflow:r,follow:f,limit:l})}let g=await z(s,n,t,c);return f?E({token:t,jobId:g,follow:f,projectId:c}):v({token:t,projectId:c,jobId:g,follow:!1,limit:l})}export{F as logsCommand};
42
+ `)),process.exit(1)),F({token:t,projectId:n,workflow:s,follow:f,limit:l})}let c=await O(a,r,t,n);return f?L({token:t,jobId:c,follow:f,projectId:n}):T({token:t,projectId:n,jobId:c,follow:!1,limit:l})}export{B as logsCommand,z as runReconnectLoop,M as sseBackoffMs};
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import{mkdirSync as x,writeFileSync as Q,existsSync as O}from"fs";import{join as g,dirname as J,resolve as T}from"path";import{pathToFileURL as I}from"url";import{execSync as z,spawn as U}from"node:child_process";import{SQSClient as W,SendMessageCommand as K}from"@aws-sdk/client-sqs";var E=null;function D(){return E||(E=new W({region:process.env.AWS_REGION||"ap-southeast-2"})),E}async function P(r,{status:e,error:t}){let{EXECUTION_ID:n,SQS_AUTH_TOKEN:a,PROGRESS_API_URL:s,PROGRESS_QUEUE_URL:o,PROJECT_API_TOKEN:u}=r;if(!n)return;let l={executionId:n,...a&&{sqsAuthToken:a},status:e,...t&&{error:t},timestamp:new Date().toISOString()},d=s?"HTTP":o?"SQS":"NONE",f=JSON.stringify(l).length;console.log(`Sending final status: ${e} via ${d} (${(f/1024).toFixed(1)}KB)`);try{if(s)await B(s,n,l,u);else if(o){let c=["completed","failed","insufficient_context","blocked"].includes(e)?"execution_completed":"progress_update";await G(o,n,l,c)}else{console.warn("No transport configured for final status \u2014 neither PROGRESS_API_URL nor PROGRESS_QUEUE_URL set");return}console.log(`Final status ${e} sent via ${d}`)}catch(c){console.error(`Failed to send final status (${e}) via ${d}:`),console.error(` Payload: ${(f/1024).toFixed(1)}KB`),console.error(` Error: ${c.message}`),c.name&&console.error(` Error type: ${c.name}`),c.code&&console.error(` Error code: ${c.code}`)}}async function B(r,e,t,n){let a=`${r}/${e}/progress`,s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);let o=await fetch(a,{method:"POST",headers:s,body:JSON.stringify(t)});if(!o.ok){let u=await o.text();throw new Error(`HTTP ${o.status}: ${u}`)}}async function G(r,e,t,n="progress_update"){let a=JSON.stringify(t),s=(a.length/1024).toFixed(1);a.length>256*1024&&console.error(`\u274C SQS message too large: ${s}KB (limit 256KB) for ${e} [${n}]`),await D().send(new K({QueueUrl:r,MessageBody:a,MessageGroupId:e,MessageAttributes:{executionId:{DataType:"String",StringValue:e},messageType:{DataType:"String",StringValue:n}}}))}import"@zibby/core";var m=process.env.WORKSPACE||"/workspace";async function H(r,e){x(e,{recursive:!0});let t=Date.now();console.log("Fetching pre-built bundle (streaming curl \u2192 tar)...");let n=setInterval(()=>{let s=((Date.now()-t)/1e3).toFixed(1);console.log(` ...still extracting (${s}s elapsed)`)},3e3);try{await new Promise((s,o)=>{let u=U("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),l=U("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});u.stdout.pipe(l.stdin);let d,f,c=()=>{if(d!==void 0&&f!==void 0){if(d!==0)return o(new Error(`curl exited ${d}`));if(f!==0)return o(new Error(`tar exited ${f}`));s()}};u.on("close",p=>{d=p,c()}),l.on("close",p=>{f=p,c()}),u.on("error",o),l.on("error",o)})}finally{clearInterval(n)}let a=((Date.now()-t)/1e3).toFixed(1);return console.log(` Bundle extracted in ${a}s`),e}async function b(){let r=process.env.WORKFLOW_SOURCES_URL;if(!r)throw new Error("WORKFLOW_SOURCES_URL env var is required");console.log("Fetching workflow sources via pre-signed URL...");let e=await fetch(r);if(!e.ok)throw new Error(`Failed to fetch sources: ${e.status} ${e.statusText}`);let t=await e.json();if(!t.sources||typeof t.sources!="object")throw new Error('Invalid sources payload \u2014 missing "sources" map');return t}function M(r,e){let t=T(e),n=0;for(let[a,s]of Object.entries(r)){let o=T(e,a);if(!o.startsWith(`${t}/`)&&o!==t){console.error(` \u26D4 Skipping unsafe path: ${a}`);continue}x(J(o),{recursive:!0}),Q(o,s,"utf-8"),n++}return n}async function j(r,e){let t=g(r,"graph.mjs");if(!O(t))throw new Error(`graph.mjs not found at ${t}`);let n=await import(I(t).href),a=e?.entryClass,s=a&&n[a]||n.default||Object.values(n).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!s)throw new Error("No WorkflowAgent class found in graph.mjs");return s}async function se(){if(!process.env.NODE_PATH){process.env.NODE_PATH="/opt/zibby/packages";let i=await import("module");i.default._initPaths&&i.default._initPaths()}let{WORKFLOW_JOB_ID:r,WORKFLOW_TYPE:e,PROJECT_ID:t,AGENT_TYPE:n,MODEL:a}=process.env;e||(console.error("Missing WORKFLOW_TYPE env var"),process.exit(1)),console.log(`
3
- Zibby Custom Workflow Runner`),console.log(` Job: ${r||"local"}`),console.log(` Workflow: ${e}`),console.log(` Project: ${t||"none"}`),console.log(` Agent: ${n||"default"}`),console.log(` Model: ${a||"auto"}`),console.log("\u2500".repeat(60));let s=process.env.WORKFLOW_BUNDLE_URL,o,u={},l,d;if(s){l=e,o=g(m,".zibby","workflows",l);try{await H(s,o),console.log(" Extracted pre-built bundle (no npm install needed)");try{let i=await b();u=i.input||{},d=i.version}catch(i){console.warn(` Could not fetch input payload: ${i.message}`)}}catch(i){console.warn(` Bundle extract failed (${i.message}); falling back to source install`),o=null}}if(!o){let i=await b(),{sources:$,input:N,workflowType:C,version:k}=i;u=N||{},l=C||e,d=k,console.log(` Workflow v${d||"?"} \u2014 ${Object.keys($).length} source files`),o=g(m,".zibby","workflows",l);let F=M($,o);console.log(` Wrote ${F} files to ${o}`),console.log(" Installing dependencies...");try{z("npm install --silent --no-audit --no-fund",{cwd:o,stdio:"inherit"}),console.log(" Dependencies installed")}catch(L){console.warn(` npm install failed: ${L.message}`)}}let f={},c=g(o,"workflow.json");if(O(c)){let{readFileSync:i}=await import("fs");f=JSON.parse(i(c,"utf-8"))}let p=await j(o,f);console.log(` Loaded ${p.name}`);let R=g(o,"node_modules","@zibby","core","dist","index.js");if(O(R))try{await import(I(R).href),console.log(" Registered built-in agent strategies (cursor/claude/codex/gemini/assistant)")}catch(i){console.warn(` Failed to load bundle's @zibby/core: ${i.message}`)}else console.warn(" No @zibby/core in bundle \u2014 agent strategies may be unavailable");let v=Date.now(),w=new p({workflow:l||e}),y=w.buildGraph(),A={input:u||{},cwd:m,runId:r||`run-${Date.now()}`};console.log(`
4
- Running graph (${y.nodes?.size||"?"} nodes)...
5
- `);let S;try{S=await y.run(w,A)}catch(i){console.error(`
6
- Workflow execution failed: ${i.message}`),console.error(i.stack),await _("failed",i.message),process.exit(1)}let h=((Date.now()-v)/1e3).toFixed(1);S?.success!==!1?(console.log(`
7
- Workflow "${l||e}" completed in ${h}s`),await _("completed")):(console.error(`
8
- Workflow "${l||e}" failed after ${h}s`),await _("failed",S?.error||"Workflow execution failed"),process.exit(1)),w.onComplete&&await w.onComplete(S)}async function _(r,e=null){let t={EXECUTION_ID:process.env.WORKFLOW_JOB_ID,PROGRESS_API_URL:process.env.PROGRESS_API_URL,PROGRESS_QUEUE_URL:process.env.PROGRESS_QUEUE_URL,PROJECT_API_TOKEN:process.env.PROJECT_API_TOKEN,SQS_AUTH_TOKEN:process.env.SQS_AUTH_TOKEN};if(t.EXECUTION_ID)try{await P(t,{status:r,...e&&{error:e}})}catch(n){console.error(`\u26A0\uFE0F Failed to report status: ${n.message}`)}}export{se as runWorkflowCommand};
2
+ import{mkdirSync as D,writeFileSync as M,existsSync as w}from"fs";import{join as g,dirname as q,resolve as F}from"path";import{pathToFileURL as A}from"url";import{execSync as X,spawn as L}from"node:child_process";import{SQSClient as z,SendMessageCommand as Q}from"@aws-sdk/client-sqs";var P=null;function J(){return P||(P=new z({region:process.env.AWS_REGION||"ap-southeast-2"})),P}async function N(i,{status:e,error:n}){let{EXECUTION_ID:s,SQS_AUTH_TOKEN:a,PROGRESS_API_URL:r,PROGRESS_QUEUE_URL:o,PROJECT_API_TOKEN:f}=i;if(!s)return;let l={executionId:s,...a&&{sqsAuthToken:a},status:e,...n&&{error:n},timestamp:new Date().toISOString()},d=r?"HTTP":o?"SQS":"NONE",p=JSON.stringify(l).length;console.log(`Sending final status: ${e} via ${d} (${(p/1024).toFixed(1)}KB)`);try{if(r)await j(r,s,l,f);else if(o){let c=["completed","failed","insufficient_context","blocked"].includes(e)?"execution_completed":"progress_update";await H(o,s,l,c)}else{console.warn("No transport configured for final status \u2014 neither PROGRESS_API_URL nor PROGRESS_QUEUE_URL set");return}console.log(`Final status ${e} sent via ${d}`)}catch(c){console.error(`Failed to send final status (${e}) via ${d}:`),console.error(` Payload: ${(p/1024).toFixed(1)}KB`),console.error(` Error: ${c.message}`),c.name&&console.error(` Error type: ${c.name}`),c.code&&console.error(` Error code: ${c.code}`)}}async function j(i,e,n,s){let a=`${i}/${e}/progress`,r={"Content-Type":"application/json"};s&&(r.Authorization=`Bearer ${s}`);let o=await fetch(a,{method:"POST",headers:r,body:JSON.stringify(n)});if(!o.ok){let f=await o.text();throw new Error(`HTTP ${o.status}: ${f}`)}}async function H(i,e,n,s="progress_update"){let a=JSON.stringify(n),r=(a.length/1024).toFixed(1);a.length>256*1024&&console.error(`\u274C SQS message too large: ${r}KB (limit 256KB) for ${e} [${s}]`),await J().send(new Q({QueueUrl:i,MessageBody:a,MessageGroupId:e,MessageAttributes:{executionId:{DataType:"String",StringValue:e},messageType:{DataType:"String",StringValue:s}}}))}import"@zibby/core";var T=process.env.WORKSPACE||"/workspace";async function V(i,e){D(e,{recursive:!0});let n=Date.now();console.log("Fetching pre-built bundle (streaming curl \u2192 tar)...");let s=setInterval(()=>{let r=((Date.now()-n)/1e3).toFixed(1);console.log(` ...still extracting (${r}s elapsed)`)},3e3);try{await new Promise((r,o)=>{let f=L("curl",["-fsSL",i],{stdio:["ignore","pipe","inherit"]}),l=L("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(l.stdin);let d,p,c=()=>{if(d!==void 0&&p!==void 0){if(d!==0)return o(new Error(`curl exited ${d}`));if(p!==0)return o(new Error(`tar exited ${p}`));r()}};f.on("close",S=>{d=S,c()}),l.on("close",S=>{p=S,c()}),f.on("error",o),l.on("error",o)})}finally{clearInterval(s)}let a=((Date.now()-n)/1e3).toFixed(1);return console.log(` Bundle extracted in ${a}s`),e}async function W(){let i=process.env.WORKFLOW_SOURCES_URL;if(!i)throw new Error("WORKFLOW_SOURCES_URL env var is required");console.log("Fetching workflow sources via pre-signed URL...");let e=await fetch(i);if(!e.ok)throw new Error(`Failed to fetch sources: ${e.status} ${e.statusText}`);let n=await e.json();if(!n.sources||typeof n.sources!="object")throw new Error('Invalid sources payload \u2014 missing "sources" map');return n}function Y(i,e){let n=F(e),s=0;for(let[a,r]of Object.entries(i)){let o=F(e,a);if(!o.startsWith(`${n}/`)&&o!==n){console.error(` \u26D4 Skipping unsafe path: ${a}`);continue}D(q(o),{recursive:!0}),M(o,r,"utf-8"),s++}return s}async function Z(i,e){let n=g(i,"graph.mjs");if(!w(n))throw new Error(`graph.mjs not found at ${n}`);let s=await import(A(n).href),a=e?.entryClass,r=a&&s[a]||s.default||Object.values(s).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!r)throw new Error("No WorkflowAgent class found in graph.mjs");return r}async function ce(){if(!process.env.NODE_PATH){process.env.NODE_PATH="/opt/zibby/packages";let t=await import("module");t.default._initPaths&&t.default._initPaths()}let{WORKFLOW_JOB_ID:i,WORKFLOW_TYPE:e,PROJECT_ID:n,AGENT_TYPE:s,MODEL:a}=process.env;e||(console.error("Missing WORKFLOW_TYPE env var"),process.exit(1)),console.log(`
3
+ Zibby Custom Workflow Runner`),console.log(` Job: ${i||"local"}`),console.log(` Workflow: ${e}`),console.log(` Project: ${n||"none"}`),console.log(` Agent: ${s||"default"}`),console.log(` Model: ${a||"auto"}`),console.log("\u2500".repeat(60));let r=process.env.WORKFLOW_BUNDLE_URL,o,f={},l,d;if(r){l=e,o=g(T,".zibby","workflows",l);try{await V(r,o),console.log(" Extracted pre-built bundle (no npm install needed)");try{let t=await W();f=t.input||{},d=t.version}catch(t){console.warn(` Could not fetch input payload: ${t.message}`)}}catch(t){console.warn(` Bundle extract failed (${t.message}); falling back to source install`),o=null}}if(!o){let t=await W(),{sources:u,input:y,workflowType:O,version:E}=t;f=y||{},l=O||e,d=E,console.log(` Workflow v${d||"?"} \u2014 ${Object.keys(u).length} source files`),o=g(T,".zibby","workflows",l);let b=Y(u,o);console.log(` Wrote ${b} files to ${o}`),console.log(" Installing dependencies...");try{X("npm install --silent --no-audit --no-fund",{cwd:o,stdio:"inherit"}),console.log(" Dependencies installed")}catch($){console.warn(` npm install failed: ${$.message}`)}}let p={},c=g(o,"workflow.json");if(w(c)){let{readFileSync:t}=await import("fs");p=JSON.parse(t(c,"utf-8"))}let S=await Z(o,p);console.log(` Loaded ${S.name}`);let m=[],x=g(o,"node_modules","@zibby","agent-workflow"),k=g(o,"node_modules","@zibby","core","node_modules","@zibby","agent-workflow");w(x)&&m.push({kind:"hoisted",path:x}),w(k)&&m.push({kind:"nested",path:k});let R=process.env.ZIBBY_RUN_DIAG==="1";if(R){let{readdirSync:t}=await import("fs");console.log(` [diag] @zibby/agent-workflow copies in bundle: ${m.length}`);for(let u of m)console.log(` [diag] ${u.kind}: ${u.path}`);try{let u=g(o,"node_modules","@zibby");w(u)&&console.log(` [diag] node_modules/@zibby/ contents: [${t(u).join(", ")}]`)}catch{}}let I=g(o,"node_modules","@zibby","core","dist","index.js");if(w(I)&&m.length>0)try{let t=await import(A(I).href),u=[t.AssistantStrategy,t.CursorAgentStrategy,t.ClaudeAgentStrategy,t.CodexAgentStrategy,t.GeminiAgentStrategy].filter(Boolean);for(let y of m){let O=g(y.path,"dist","index.js");if(!w(O))continue;let E=await import(A(O).href),b=R?E.listStrategies():null;for(let $ of u)try{E.registerStrategy(new $)}catch(G){console.warn(` register ${$.name} into ${y.kind} failed: ${G.message}`)}R&&console.log(` [diag] ${y.kind} registry: before=[${b.join(",")||"empty"}] after=[${E.listStrategies().join(",")||"empty"}]`)}console.log(" Registered built-in agent strategies (cursor/claude/codex/gemini/assistant)")}catch(t){console.warn(` Failed to bridge strategies into bundle: ${t.message}`)}else console.warn(" No @zibby/core or @zibby/agent-workflow in bundle \u2014 agent strategies may be unavailable");let K=Date.now(),_=new S({workflow:l||e}),C=_.buildGraph(),B={input:f||{},cwd:T,runId:i||`run-${Date.now()}`};console.log(`
4
+ Running graph (${C.nodes?.size||"?"} nodes)...
5
+ `);let h;try{h=await C.run(_,B)}catch(t){console.error(`
6
+ Workflow execution failed: ${t.message}`),console.error(t.stack),await U("failed",t.message),process.exit(1)}let v=((Date.now()-K)/1e3).toFixed(1);h?.success!==!1?(console.log(`
7
+ Workflow "${l||e}" completed in ${v}s`),await U("completed")):(console.error(`
8
+ Workflow "${l||e}" failed after ${v}s`),await U("failed",h?.error||"Workflow execution failed"),process.exit(1)),_.onComplete&&await _.onComplete(h)}async function U(i,e=null){let n={EXECUTION_ID:process.env.WORKFLOW_JOB_ID,PROGRESS_API_URL:process.env.PROGRESS_API_URL,PROGRESS_QUEUE_URL:process.env.PROGRESS_QUEUE_URL,PROJECT_API_TOKEN:process.env.PROJECT_API_TOKEN,SQS_AUTH_TOKEN:process.env.SQS_AUTH_TOKEN};if(n.EXECUTION_ID)try{await N(n,{status:i,...e&&{error:e}})}catch(s){console.error(`\u26A0\uFE0F Failed to report status: ${s.message}`)}}export{ce as runWorkflowCommand};
@@ -1,16 +1,16 @@
1
- import{existsSync as y}from"fs";import{readFile as j}from"fs/promises";import{join as m}from"path";import{pathToFileURL as E}from"url";import o from"chalk";import T from"ora";var W=3848;function S(e){let n=process.cwd();return m(n,".zibby","workflows",e)}async function z(e,n){let t=m(e,"graph.mjs");if(!y(t))throw new Error(`graph.mjs not found in .zibby/workflows/${n}/`);let l=await O(e,n),a=await import(E(t).href),s=l.entryClass,i=s&&a[s]||a.default||Object.values(a).find(r=>typeof r=="function"&&r.prototype?.buildGraph);if(!i)throw new Error("No WorkflowAgent class found in graph.mjs. Export a class with buildGraph() method.");return{AgentClass:i,manifest:l}}async function O(e,n){let t=m(e,"workflow.json");if(!y(t))return{name:n,triggers:{api:!0}};let l=await j(t,"utf-8");return JSON.parse(l)}async function A(e,n){e||(console.log(o.red(`
1
+ import{existsSync as h}from"fs";import{readFile as W}from"fs/promises";import{join as k}from"path";import{pathToFileURL as F}from"url";import o from"chalk";import R from"ora";import{existsSync as T}from"fs";import{join as z}from"path";import{pathToFileURL as S}from"url";async function j(n){let e=z(n,".zibby.config.mjs");if(!T(e))throw new Error(".zibby.config.mjs not found");try{let t=await import(S(e).href);return t.default||t}catch(t){throw new Error(`Failed to load .zibby.config.mjs: ${t.message}`,{cause:t})}}var L=3848;async function O(n){try{return(await j(n))?.paths?.workflows||".zibby/workflows"}catch{return".zibby/workflows"}}async function U(n,e,t){let s=k(n,"graph.mjs");if(!h(s))throw new Error(`graph.mjs not found in ${t}/${e}/`);let a=await v(n,e),l=await import(F(s).href),i=a.entryClass,r=i&&l[i]||l.default||Object.values(l).find(f=>typeof f=="function"&&f.prototype?.buildGraph);if(!r)throw new Error("No WorkflowAgent class found in graph.mjs. Export a class with buildGraph() method.");return{AgentClass:r,manifest:a}}async function v(n,e){let t=k(n,"workflow.json");if(!h(t))return{name:e,triggers:{api:!0}};let s=await W(t,"utf-8");return JSON.parse(s)}async function X(n,e){n||(console.log(o.red(`
2
2
  Workflow name is required`)),console.log(o.gray(" Usage: zibby workflow start <workflow-name>")),console.log(o.gray(` Example: zibby workflow start ticket-triage
3
- `)),process.exit(1));let t=e.toLowerCase(),l=S(t);y(l)||(console.log(o.red(`
4
- Workflow not found: .zibby/workflows/${t}/`)),console.log(o.gray(" Create one first:")),console.log(o.cyan(` zibby workflow new ${t}
5
- `)),process.exit(1));let a=T(` Loading workflow "${t}"...`).start(),s,i;try{({AgentClass:s,manifest:i}=await z(l,t)),a.succeed(` Loaded ${o.bold(i.entryClass||s.name)} (${t})`)}catch(g){a.fail(" Failed to load workflow"),console.log(o.red(`
6
- ${g.message}
7
- `)),process.exit(1)}let r=parseInt(n.port,10)||W,f;try{f=(await import("express")).default}catch{console.log(o.red(`
3
+ `)),process.exit(1));let t=n.toLowerCase(),s=process.cwd(),a=await O(s),l=k(s,a,t);h(l)||(console.log(o.red(`
4
+ Workflow not found: ${a}/${t}/`)),console.log(o.gray(" Create one first:")),console.log(o.cyan(` zibby workflow new ${t}
5
+ `)),process.exit(1));let i=R(` Loading workflow "${t}"...`).start(),r,f;try{({AgentClass:r,manifest:f}=await U(l,t,a)),i.succeed(` Loaded ${o.bold(f.entryClass||r.name)} (${t})`)}catch(w){i.fail(" Failed to load workflow"),console.log(o.red(`
6
+ ${w.message}
7
+ `)),process.exit(1)}let g=parseInt(e.port,10)||L,u;try{u=(await import("express")).default}catch{console.log(o.red(`
8
8
  express is required for local workflow server`)),console.log(o.gray(` npm install express
9
- `)),process.exit(1)}let w=f();w.use(f.json({limit:"1mb"})),w.get("/health",(g,d)=>{d.json({status:"ok",workflow:t,class:s.name})}),w.post("/trigger",async(g,d)=>{let c=`local-${Date.now()}`,h=g.body.input||g.body||{};console.log(o.cyan(`
10
- \u25B6 Run ${c} triggered`)),console.log(o.gray(` input: ${JSON.stringify(h).slice(0,200)}`)),d.status(202).json({runId:c,status:"running",workflow:t});try{let u=Date.now(),p=new s({workflow:t}),$=p.buildGraph(),C={input:h,cwd:process.cwd(),runId:c},k=await $.run(p,C),b=((Date.now()-u)/1e3).toFixed(1),x=k?.success!==!1;console.log(x?o.green(` \u2714 Run ${c} succeeded (${b}s)`):o.red(` \u2716 Run ${c} failed (${b}s)`)),p.onComplete&&await p.onComplete(k)}catch(u){console.log(o.red(` \u2716 Run ${c} error: ${u.message}`))}}),w.listen(r,()=>{console.log(o.bold.cyan(`
9
+ `)),process.exit(1)}let p=u();p.use(u.json({limit:"1mb"})),p.get("/health",(w,y)=>{y.json({status:"ok",workflow:t,class:r.name})}),p.post("/trigger",async(w,y)=>{let c=`local-${Date.now()}`,b=w.body.input||w.body||{};console.log(o.cyan(`
10
+ \u25B6 Run ${c} triggered`)),console.log(o.gray(` input: ${JSON.stringify(b).slice(0,200)}`)),y.status(202).json({runId:c,status:"running",workflow:t});try{let m=Date.now(),d=new r({workflow:t}),x=d.buildGraph(),E={input:b,cwd:process.cwd(),runId:c},$=await x.run(d,E),C=((Date.now()-m)/1e3).toFixed(1),P=$?.success!==!1;console.log(P?o.green(` \u2714 Run ${c} succeeded (${C}s)`):o.red(` \u2716 Run ${c} failed (${C}s)`)),d.onComplete&&await d.onComplete($)}catch(m){console.log(o.red(` \u2716 Run ${c} error: ${m.message}`))}}),p.listen(g,()=>{console.log(o.bold.cyan(`
11
11
  Zibby Workflow Server \u2014 ${t}
12
- `)),console.log(o.gray(" ".padEnd(56,"-"))),console.log(o.white(` Workflow: ${o.cyan(t)}`)),console.log(o.white(` Class: ${o.cyan(s.name)}`)),console.log(o.white(` Port: ${o.cyan(r)}`)),console.log(o.gray(" ".padEnd(56,"-"))),console.log(o.white(`
13
- Endpoints:`)),console.log(o.gray(` GET http://localhost:${r}/health`)),console.log(o.cyan(` POST http://localhost:${r}/trigger`)),console.log(o.white(`
14
- Test with:`)),console.log(o.gray(` curl -X POST http://localhost:${r}/trigger \\`)),console.log(o.gray(' -H "Content-Type: application/json" \\')),console.log(o.gray(` -d '{"input": {"key": "value"}}'
12
+ `)),console.log(o.gray(" ".padEnd(56,"-"))),console.log(o.white(` Workflow: ${o.cyan(t)}`)),console.log(o.white(` Class: ${o.cyan(r.name)}`)),console.log(o.white(` Port: ${o.cyan(g)}`)),console.log(o.gray(" ".padEnd(56,"-"))),console.log(o.white(`
13
+ Endpoints:`)),console.log(o.gray(` GET http://localhost:${g}/health`)),console.log(o.cyan(` POST http://localhost:${g}/trigger`)),console.log(o.white(`
14
+ Test with:`)),console.log(o.gray(` curl -X POST http://localhost:${g}/trigger \\`)),console.log(o.gray(' -H "Content-Type: application/json" \\')),console.log(o.gray(` -d '{"input": {"key": "value"}}'
15
15
  `)),console.log(o.gray(` Ctrl+C to stop
16
- `))})}export{A as startWorkflowCommand};
16
+ `))})}export{X as startWorkflowCommand};
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/cli",
3
- "version": "0.1.83",
3
+ "version": "0.1.87",
4
4
  "description": "Zibby CLI - Test automation generator and runner",
5
5
  "type": "module",
6
6
  "bin": {
@@ -8,7 +8,7 @@
8
8
  },
9
9
  "scripts": {
10
10
  "build": "node ../scripts/build.mjs --extra-dirs bin",
11
- "test": "vitest run test/auth*.test.js test/two-layer-auth.test.js test/trigger-params.test.js test/trigger-helpers.test.js test/deploy-helpers.test.js test/cli-namespace-consistency.test.js test/cli-workflow-subcommands.test.js test/run-bundle-core-import.test.js",
11
+ "test": "vitest run test/auth*.test.js test/two-layer-auth.test.js test/trigger-params.test.js test/trigger-helpers.test.js test/deploy-helpers.test.js test/cli-namespace-consistency.test.js test/cli-workflow-subcommands.test.js test/run-bundle-core-import.test.js test/start-respects-config.test.js test/sse-backoff.test.js test/sse-reconnect-loop.test.js",
12
12
  "test:unit": "vitest run src/",
13
13
  "test:auth": "vitest run test/auth*.test.js test/two-layer-auth.test.js",
14
14
  "lint": "eslint .",
@@ -34,7 +34,7 @@
34
34
  "dependencies": {
35
35
  "@aws-sdk/client-sqs": "^3.1038.0",
36
36
  "@zibby/agent-workflow": "^0.1.2",
37
- "@zibby/core": "^0.1.46",
37
+ "@zibby/core": "^0.1.47",
38
38
  "@zibby/memory": "^0.1.5",
39
39
  "@zibby/skills": "^0.1.11",
40
40
  "adm-zip": "^0.5.17",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/cli",
3
- "version": "0.1.83",
3
+ "version": "0.1.87",
4
4
  "description": "Zibby CLI - Test automation generator and runner",
5
5
  "type": "module",
6
6
  "bin": {
@@ -8,7 +8,7 @@
8
8
  },
9
9
  "scripts": {
10
10
  "build": "node ../scripts/build.mjs --extra-dirs bin",
11
- "test": "vitest run test/auth*.test.js test/two-layer-auth.test.js test/trigger-params.test.js test/trigger-helpers.test.js test/deploy-helpers.test.js test/cli-namespace-consistency.test.js test/cli-workflow-subcommands.test.js test/run-bundle-core-import.test.js",
11
+ "test": "vitest run test/auth*.test.js test/two-layer-auth.test.js test/trigger-params.test.js test/trigger-helpers.test.js test/deploy-helpers.test.js test/cli-namespace-consistency.test.js test/cli-workflow-subcommands.test.js test/run-bundle-core-import.test.js test/start-respects-config.test.js test/sse-backoff.test.js test/sse-reconnect-loop.test.js",
12
12
  "test:unit": "vitest run src/",
13
13
  "test:auth": "vitest run test/auth*.test.js test/two-layer-auth.test.js",
14
14
  "lint": "eslint .",
@@ -34,7 +34,7 @@
34
34
  "dependencies": {
35
35
  "@aws-sdk/client-sqs": "^3.1038.0",
36
36
  "@zibby/agent-workflow": "^0.1.2",
37
- "@zibby/core": "^0.1.46",
37
+ "@zibby/core": "^0.1.47",
38
38
  "@zibby/memory": "^0.1.5",
39
39
  "@zibby/skills": "^0.1.11",
40
40
  "adm-zip": "^0.5.17",