@zibby/cli 0.4.24 → 0.4.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/zibby.js +3 -3
- package/dist/commands/analyze-graph.js +1 -1
- package/dist/commands/chat.js +2 -2
- package/dist/commands/init.js +1 -1
- package/dist/commands/run.js +2 -2
- package/dist/commands/template.js +1 -1
- package/dist/commands/workflow.js +2 -2
- package/dist/commands/workflows/download.js +42 -0
- package/dist/commands/workflows/generate.js +143 -143
- package/dist/commands/workflows/name-helpers.js +1 -0
- package/dist/package.json +5 -3
- package/package.json +5 -3
package/dist/bin/zibby.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
process.stdout.on("error",e=>{e.code}),process.stderr.on("error",e=>{e.code}),process.env.DOTENV_CONFIG_QUIET="true";import"@zibby/skills";import{Command as
|
|
3
|
-
`),
|
|
2
|
+
process.stdout.on("error",e=>{e.code}),process.stderr.on("error",e=>{e.code}),process.env.DOTENV_CONFIG_QUIET="true";import"@zibby/skills";import{Command as h}from"commander";import{initCommand as k}from"../commands/init.js";import{runCommand as b}from"../commands/run.js";import{videoCommand as v}from"../commands/video.js";import{uploadCommand as C}from"../commands/upload.js";import{ciSetupCommand as I}from"../commands/ci-setup.js";import{setupPlaywrightMcpCommand as P,setupCiCommand as S,testWithVideoCommand as A}from"../commands/setup-scripts.js";import{readFileSync as j}from"fs";import{fileURLToPath as B}from"url";import{dirname as x,join as _}from"path";import{bootstrapAgentEnv as z}from"../utils/agent-credentials.js";const E=B(import.meta.url),D=x(E),u=JSON.parse(j(_(D,"../package.json"),"utf-8"));function s(e,o){return o.push(e),o}function f(e){if(e===void 0||e===!0||e==="")return 1;const o=parseInt(e,10);if(!Number.isFinite(o)||o<1||o>5)throw new Error(`--warm must be an integer 1-5 (got "${e}"). Omit the flag to disable warm pool.`);return o}const w=`zibby v${u.version}`,i=process.argv.slice(2),R=i.includes("-h")||i.includes("--help"),Y=i.includes("-v")||i.includes("-V")||i.includes("--version");Y&&(console.log(w),process.exit(0));const y=i[0],Z=i[1],O=["logs","uninstall"],L=y==="workflow"&&Z==="list";!O.includes(y)&&!L&&console.log(`${w}
|
|
3
|
+
`),z(process.cwd());const M=i[0]==="chat",U=["--verbose","--agent","--stream","-s"],W=i.length>0&&i.every(e=>U.includes(e)||i[i.indexOf(e)-1]==="--agent"),J=i.length===0||M||W;if(J&&!R){const e={},o=i.indexOf("--agent");o!==-1&&i[o+1]&&(e.agent=i[o+1]),i.includes("--verbose")&&(e.verbose=!0),(i.includes("--stream")||i.includes("-s"))&&(e.stream=!0);const{chatCommand:t}=await import("../commands/chat.js");await t(e),process.exit(0)}const n=new h;n.name("zibby").description("Zibby \u2014 the cloud pipeline for Claude Code, Cursor, Codex, and Gemini. Compose them into structured workflows with schema-enforced handoff.").version(u.version,"-V, --version"),n.configureHelp({visibleCommands:()=>[]}),n.addHelpText("after",`
|
|
4
4
|
Workflow (the platform):
|
|
5
5
|
workflow new <name> Scaffold a new workflow at .zibby/workflows/<name>/
|
|
6
6
|
workflow run <name> Run a workflow locally (one-shot, mirrors trigger flags)
|
|
@@ -45,4 +45,4 @@ Examples:
|
|
|
45
45
|
|
|
46
46
|
Docs: https://docs.zibby.app
|
|
47
47
|
GitHub: https://github.com/ZibbyHQ/zibby-agent
|
|
48
|
-
`),n.command("init").description("Initialize a Zibby project (config + credentials only \u2014 pass -t <name> to also scaffold a workflow template)").argument("[project-name]","Project name (optional, uses current directory if not provided)").option("--agent <type>","Agent to use (claude, cursor, codex, gemini)").option("--memory-backend <backend>","Memory backend to configure (dolt, mem0)","dolt").option("-t, --template <name>","Workflow template to scaffold into .zibby/ (see `zibby template list`). Default: none \u2014 init only sets up config and credentials.").option("--skip-install","Skip npm install").option("--skip-memory","Skip test memory setup during initialization").option("-f, --force","Force reinitialize (overwrite existing config)").option("--headed","Run MCP browser in headed mode (visible browser)").option("--headless","Run MCP browser in headless mode (hidden browser)").option("--api-key <key>","Zibby API key for cloud sync").option("--cloud-sync","Enable cloud sync and install Zibby MCP").option("--agent-key <key>","Agent API key (non-interactive). For Claude this is the per-token API key").option("--agent-oauth-token <token>","Claude OAuth subscription token (non-interactive). Saves to ~/.zibby/config.json").action(h),n.command("test").description("Run a test specification").argument("[spec-path]","Path to test spec file or inline test description in quotes").option("--sources <ids>","Comma-separated test case IDs to fetch from cloud").option("--execution <id>","Execution ID containing the test cases (required with --sources)").option("--agent <type>","Agent to use (claude, cursor, codex, gemini) - overrides config").option("--workflow <name>","Workflow to use (e.g., QuickSmokeWorkflow, quick-smoke)").option("--headless","Run browser in headless mode").option("--node <name>","Run only a specific node (e.g., execute_live, generate_script)").option("--session <id>",'Use existing session (e.g., 1768974629717 or "last") - requires --node').option("--session-path <dir>","Use this session folder (absolute or relative to cwd); Studio pins artifacts here").option("--project <id>","Project ID (optional, auto-detected from ZIBBY_API_KEY)").option("--collection <id-or-name>","Collection ID or name (creates new if name doesn't exist)").option("--folder <path>","Folder path within collection (optional, requires --collection)").option("--sync","Force upload to cloud (overrides cloudSync: false)").option("--no-sync","Skip upload to cloud (overrides cloudSync: true)").option("--config <path>","Path to config file",".zibby.config.mjs").option("--auto-approve","Auto-approve MCP tools (for CI/CD)").option("-o, --open","Open test results in browser after completion").option("--verbose","Show info level logs").option("--debug","Show debug level logs (most verbose)").option("-m, --mem","Enable test memory (Dolt-backed knowledge from previous runs)").action((e,o)=>(o.debug?process.env.ZIBBY_DEBUG="true":o.verbose&&(process.env.ZIBBY_VERBOSE="true"),b(e,o))),n.command("implement").description("Implement a Jira ticket using AI agent (runs in ECS container)").action(async(...e)=>{const{implementCommand:o}=await import("../commands/implement.js");return o(...e)}),n.command("analyze").description("Analyze a Jira ticket against the codebase (runs in ECS container)").option("--workflow <path>","Path to a local workflow JSON file (e.g., .zibby/workflow-analysis.json)").action(async(...e)=>{const{analyzeCommand:o}=await import("../commands/analyze-graph.js");return o(...e)}),n.command("video").description("Organize test videos next to test files").action(v),n.command("upload <spec-path>").description("Upload existing test artifacts to Zibby Cloud").option("--project <id>","Project ID (REQUIRED - use flag or ZIBBY_PROJECT_ID env)").option("--collection <id-or-name>","Collection ID or name (creates new if name doesn't exist)").option("--folder <path>","Folder path within collection (optional)").option("--agent <type>","Agent used (for metadata)").action(C),n.command("login").description("Log in to Zibby (opens browser for authentication)").action(async()=>{const{loginCli:e}=await import("../auth/cli-login.js");await e(),process.exit(0)}),n.command("logout").description("Log out from Zibby (clears saved session)").action(async()=>{const{logoutCli:e}=await import("../auth/cli-login.js");e(),process.exit(0)}),n.command("status").description("Show current authentication status and token details").option("--json","Output in JSON format (for scripts)").action(async e=>{const{showLoginStatus:o}=await import("../auth/cli-login.js");await o(e),process.exit(0)}),n.command("list").description("List your projects and API tokens").action(async()=>{const{listProjectsCommand:e}=await import("../commands/list-projects.js");await e()}),n.command("ci-setup").description("Setup Cursor Agent for CI/CD (patch and configure)").option("--get-keys","Get MCP approval keys").option("--save","Save approval keys to project").action(I),n.command("setup-playwright").description("Setup official Playwright MCP (from cursor-agent-package)").option("--headed","Configure MCP in headed mode (visible browser)").option("--viewport-width <width>","Viewport width (default: 1280)","1280").option("--viewport-height <height>","Viewport height (default: 720)","720").action(e=>{const o={width:parseInt(e.viewportWidth,10)||1280,height:parseInt(e.viewportHeight,10)||720};return P({...e,viewport:o})}),n.command("setup-ci-full").description("Complete CI/CD setup from scratch").action(S),n.command("test-video").description("Run Playwright tests with video recording").argument("[test-file]","Test file to run (default: tests/)").option("--headed","Run in headed mode (visible browser)").action(A),n.command("generate").description("Generate test specs from a ticket + codebase (local analysis using real AI agent)").option("-t, --ticket <key>","Jira ticket key (fetches automatically)").option("-i, --input <file>","Input file with ticket description/requirements").option("-d, --description <text>","Inline ticket description").option("--repo <path>","Path to the codebase (default: current directory)").option("--agent <type>","Agent to use (codex, claude, cursor, gemini)").option("--model <model>","Model override").option("-o, --output <dir>","Output directory for spec files (default: test-specs)").action(async e=>{const{generateCommand:o}=await import("../commands/generate.js");return o(e)}),n.command("studio").description("Launch Zibby Studio desktop (installs from CDN if needed). Uses this folder as the Zibby project.").option("-p, --port <port>","Port for the Studio API bridge (default: 3847)").option("--no-open","Start the API only; do not launch desktop app").option("--update","Force re-download of the latest Studio binary").action(async e=>{const{studioCommand:o}=await import("../commands/studio.js");return o(e)});const m=n.command("creds").description("Manage credentials Zibby has stored for your workspace (KMS-encrypted)");m.command("list").description("List credentials stored for your workspace (masked)").action(async()=>{const{listCmd:e}=await import("../commands/creds.js");await e(),process.exit(0)}),m.command("sync").description("Re-read ~/.zibby/credentials.env and upload any new tokens").action(async()=>{const{syncCmd:e}=await import("../commands/creds.js");await e(),process.exit(0)}),m.command("remove <type> <index>").description("Remove a stored credential. e.g. zibby creds remove oauth 0").action(async(e,o)=>{const{removeCmd:t}=await import("../commands/creds.js");await t(e,o),process.exit(0)});const T=n.command("g").description("Generate scaffolds");T.command("workflow [name]").description("Scaffold a new custom workflow in .zibby/workflows/<name>/ (auto-generates name if omitted)").option("-t, --template <name>","Scaffold from a template (see `zibby template list`). Future: also accepts npm package / git URL identifiers.").option("--skip-install","Skip running `npm install` in the new workflow folder").option("--skip-init-check","Skip the first-run init prompt that fires when ~/.zibby/config.json is missing (CI/scripted setups)").option("--agent-helpers [list]",'Install agent helpers (Claude Code / Cursor slash commands). List = comma-separated, e.g. "claude" or "claude,cursor". Bare flag defaults to claude.').option("--no-agent-helpers","Skip agent helpers even if .zibby.config.mjs says install").option("--agent <agent>","(legacy) Set up agent helpers: claude | cursor | codex | all | none. Prefer --agent-helpers.").option("--force-agents","Overwrite user-edited agent helper files (use with --agent-helpers)").action(async(e,o)=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(e,o)}),n.command("start <workflow-name>").description("Start a local dev server for a custom workflow").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(e,o)=>{const{startWorkflowCommand:t}=await import("../commands/workflows/start.js");return t(e,o)}),n.command("run <workflow-name>").description("Run a workflow locally \u2014 one-shot (alias of `zibby workflow run`)").option("-p, --param <key=value>","Input param (repeatable)",s,[]).option("--input <json>","Input as JSON string").option("--input-file <path>","Input as JSON file").action(async(e,o)=>{const{runLocalWorkflowCommand:t}=await import("../commands/workflows/run-local.js");return t(e,o)}),n.command("deploy [workflow-name]").description("Deploy a custom workflow to Zibby Cloud (interactive selection if workflow-name not provided)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--dedicated-ip <action>","Manage dedicated egress IP addon: enable | status | disable | use | unuse").option("--env <path>","Path to a .env file to sync into per-workflow env vars after deploy (repeatable)",s,[]).option("--verbose","Show raw CodeBuild logs during the bundle build").option("--no-creds-check","Skip the project secrets sanity check (CI/CD when the secret is provisioned out-of-band)").option("--force","Deploy even if the source checksum matches the last deployed version (bypasses the unchanged check)").option("--warm [count]","Enable warm-pool execution for this workflow (default 1, max 5). Skips ~60s Fargate cold-start by routing triggers to a per-account pool of always-on tasks. Pricing applies (paid feature).",f).action(async(e,o)=>{if(o.dedicatedIp){const{dedicatedEgressCommand:r}=await import("../commands/workflows/dedicated-egress.js");return r(o.dedicatedIp,o.project)}const{deployWorkflowCommand:t}=await import("../commands/workflows/deploy.js");return t(e,o)}),n.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (interactive selection if not provided). Get UUIDs from `zibby workflow list`.").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").option("-t, --follow","Stream logs in real-time after triggering (no need to run `logs -t` separately)").action(async(e,o)=>{const{triggerWorkflowCommand:t}=await import("../commands/workflows/trigger.js");return t(e,o)}),n.command("logs [jobId]").description("Fetch and display logs from a workflow execution (use -t to stream in real-time)").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (fetches the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --follow","Stream logs in real-time (like Heroku logs -t)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(e,o)=>{const{logsCommand:t}=await import("../commands/workflows/logs.js");return t(e,o)}),n.command("run-workflow").description("Run a deployed workflow from S3 sources (used by ECS containers)").action(async()=>{const{runWorkflowCommand:e}=await import("../commands/workflows/run.js");return e()});const g=n.command("template").description("Manage workflow templates in this project");g.command("list").description("List available workflow templates").action(async()=>{const{templateListCommand:e}=await import("../commands/template.js");return e()}),g.command("add",{hidden:!0}).argument("<name>","Template name (see `zibby template list`)").description("(deprecated \u2014 `zibby test` auto-installs the template) Copy a template into .zibby/, overwriting existing files").option("--skip-memory","Strip SKILLS.MEMORY from copied execute-live.mjs (browser-test only)").action(async(e,o)=>{const{templateAddCommand:t}=await import("../commands/template.js");return t(e,{enableMemory:!o.skipMemory})});const c=n.command("memory").description("Test memory database \u2014 version-controlled knowledge from runs");c.command("stats").description("Show memory database statistics").action(async()=>{const{memoryStatsCommand:e}=await import("../commands/memory.js");return e()}),c.command("init").description("Initialize the memory database (Dolt)").action(async()=>{const{memoryInitCommand:e}=await import("../commands/memory.js");return e()}),c.command("compact").description("Prune old data and run Dolt GC to reclaim storage").option("--max-runs <n>","Keep last N runs per spec (default: 50)",parseInt).option("--max-age <days>","Remove data older than N days (default: 90)",parseInt).action(async e=>{const{memoryCompactCommand:o}=await import("../commands/memory.js");return o(e)}),c.command("reset").description("Wipe the memory database").option("-f, --force","Confirm reset").action(async e=>{const{memoryResetCommand:o}=await import("../commands/memory.js");return o(e)}),c.command("cost").description("Show real LLM token usage from past runs (input/output/cache)").action(async()=>{const{memoryCostCommand:e}=await import("../commands/memory.js");return e()});const p=c.command("remote").description("Configure a remote so the team shares cross-spec memory");p.command("add").argument("<url>","Remote URL: aws://, gs://, https://, file:///").option("--name <name>","Remote name (default: origin)","origin").description("Point the local memory DB at a shared remote (S3/GCS/DoltHub/filesystem)").action(async(e,o)=>{const{memoryRemoteAddCommand:t}=await import("../commands/memory.js");return t(e,o)}),p.command("use").description("Switch to a managed remote backend. Currently: --hosted (Zibby-managed S3, signed-in users only).").option("--hosted","Use Zibby-managed S3 (allocates a tenant-scoped prefix per-project)").option("--project-id <id>","Override the projectId from .zibby.config.mjs").action(async e=>{e.hosted||(console.log("Pass --hosted. (Other backends will be added later.)"),process.exit(1));const{memoryRemoteUseHostedCommand:o}=await import("../commands/memory.js");return o(e)}),p.command("info").description("Show the configured memory remote (if any)").action(async()=>{const{memoryRemoteInfoCommand:e}=await import("../commands/memory.js");return e()}),p.command("remove").argument("[name]","Remote name (default: origin)").description("Remove a configured memory remote (memory becomes local-only)").action(async e=>{const{memoryRemoteRemoveCommand:o}=await import("../commands/memory.js");return o(e)}),c.command("pull").description("Pull latest team memory from the configured remote").action(async()=>{const{memoryPullCommand:e}=await import("../commands/memory.js");return e()}),c.command("push").description("Push local memory to the configured remote (auto-runs after passing tests)").action(async()=>{const{memoryPushCommand:e}=await import("../commands/memory.js");return e()});const F=n.command("agents").description("Manage Claude/Cursor/Codex helper files for working with Zibby workflows");F.command("add [agent]").description("Add agent helpers (claude | cursor | codex | all). Prompts if no agent given.").option("--force","Overwrite user-edited helper files").action(async(e,o)=>{const{runAgentHelpers:t,addAgent:r}=await import("../commands/workflows/agent-helpers.js");if(e){const l=["claude","cursor","codex","all","none"];l.includes(e)||(console.error(`Unknown agent "${e}". Valid: ${l.join(", ")}`),process.exit(1)),e==="none"?await t({forcedAgents:["none"],force:o.force===!0}):e==="all"?await t({forcedAgents:["claude","cursor","codex"],force:o.force===!0}):await r(e,{force:o.force===!0})}else await t({forcedAgents:void 0,force:o.force===!0,forcePrompt:!0})});const a=n.command("workflow").description("Manage workflow graphs \u2014 new, start, deploy, trigger, logs, list, download, delete");a.command("new [name]").description("Scaffold a new custom workflow (alias of `zibby g workflow`)").option("-t, --template <name>","Scaffold from a template (see `zibby template list`). Future: also accepts npm package / git URL identifiers.").option("--skip-install","Skip running `npm install` in the new workflow folder").option("--skip-init-check","Skip the first-run init prompt that fires when ~/.zibby/config.json is missing (CI/scripted setups)").option("--agent-helpers [list]",'Install agent helpers (Claude Code / Cursor slash commands). List = comma-separated, e.g. "claude" or "claude,cursor". Bare flag defaults to claude.').option("--no-agent-helpers","Skip agent helpers even if .zibby.config.mjs says install").option("--agent <agent>","(legacy) Set up agent helpers: claude | cursor | codex | all | none. Prefer --agent-helpers.").option("--force-agents","Overwrite user-edited agent helper files (use with --agent-helpers)").action(async(e,o)=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(e,o)}),a.command("run <workflow-name>").description("Run a workflow locally \u2014 one-shot, same input flags as `workflow trigger`").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON file \u2014 lowest precedence").action(async(e,o)=>{const{runLocalWorkflowCommand:t}=await import("../commands/workflows/run-local.js");return t(e,o)}),a.command("start <workflow-name>").description("Start a long-lived local dev server (Studio integration). Prefer `workflow run` for one-shots.").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(e,o)=>{const{startWorkflowCommand:t}=await import("../commands/workflows/start.js");return t(e,o)}),a.command("deploy [workflow-name]").description("Deploy a workflow to Zibby Cloud (alias of `zibby deploy`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--env <path>","Path to a .env file to sync into per-workflow env vars after deploy (repeatable)",s,[]).option("--verbose","Show raw CodeBuild logs during the bundle build").option("--no-creds-check","Skip the project secrets sanity check (CI/CD when the secret is provisioned out-of-band)").option("--force","Deploy even if the source checksum matches the last deployed version (bypasses the unchanged check)").option("--warm [count]","Enable warm-pool execution for this workflow (default 1, max 5). Skips ~60s Fargate cold-start by routing triggers to a per-account pool of always-on tasks. Pricing applies (paid feature).",f).action(async(e,o)=>{const{deployWorkflowCommand:t}=await import("../commands/workflows/deploy.js");return t(e,o)}),a.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (alias of `zibby trigger`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").option("-t, --follow","Stream logs in real-time after triggering (no need to run `logs -t` separately)").action(async(e,o)=>{const{triggerWorkflowCommand:t}=await import("../commands/workflows/trigger.js");return t(e,o)}),a.command("logs [jobId]").description("Tail logs from a workflow execution (alias of `zibby logs`)").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (fetches the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --follow","Stream logs in real-time (like Heroku logs -t)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(e,o)=>{const{logsCommand:t}=await import("../commands/workflows/logs.js");return t(e,o)}),a.command("download [uuid]").description("Download a 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(e,o)=>{const{workflowDownloadCommand:t}=await import("../commands/workflow.js");return t({...o,uuid:e})}),a.command("list").description("List all workflows (local + remote if credentials available)").option("--local-only","Show only local workflows").option("--remote-only","Show only remote workflows (requires --project)").option("--project <id>","Project ID (optional, uses ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async e=>{if(e.remoteOnly){const{workflowListCommand:t}=await import("../commands/workflow.js");return t(e)}if(e.localOnly){const{listLocalWorkflowsCommand:t}=await import("../commands/workflows/list.js");return t(e)}const{listAllWorkflowsCommand:o}=await import("../commands/workflows/list.js");return o(e)}),a.command("validate <name>").description("Static-check a local workflow (.zibby/workflows/<name>/). Catches schema/topology/skill errors in ~30ms before you run anything.").option("--verbose","Print stack traces on graph.mjs import errors").action(async(e,o)=>{const{validateCommand:t}=await import("../commands/workflows/validate.js");return t(e,o)}),a.command("schedule <uuid> [action] [cron]").description(`Manage a workflow's cron schedule. Actions: get (default) | set <cron> | clear. Cron is Unix 5-field, e.g. "0 9 * * 1-5".`).option("--tz <iana>","IANA timezone for the schedule (default: UTC)").option("-p, --param <key=value>","Fixed input param for every scheduled run (repeatable)",s,[]).option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o,t,r)=>{const{scheduleCommand:l}=await import("../commands/workflows/schedule.js");return l(e,o,t,r)}),a.command("delete <uuid>").description("Delete a deployed workflow by UUID").action(async e=>{const{deleteWorkflowCommand:o}=await import("../commands/workflows/delete.js");return o(e,{})});const d=a.command("env").description("Manage per-workflow encrypted env vars (set ANTHROPIC_API_KEY, DATABASE_URL, etc. per workflow)");d.command("list <uuid>").description("List env var key names for a workflow (values never returned)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{listEnvCommand:t}=await import("../commands/workflows/env.js");return t(e,o)}),d.command("set <uuid> <kv>").description("Set or update one env var: zibby workflow env set <uuid> KEY=value").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o,t)=>{const{setEnvCommand:r}=await import("../commands/workflows/env.js");return r(e,o,t)}),d.command("unset <uuid> <key>").description("Remove one env var from a workflow").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o,t)=>{const{unsetEnvCommand:r}=await import("../commands/workflows/env.js");return r(e,o,t)}),d.command("push <uuid>").description("Bulk-replace env from one or more .env files (later files override). Removes any keys not in the new map.").option("--file <path>","Path to a .env file (repeatable, e.g. --file .env --file .env.prod)",s,[]).option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{pushEnvCommand:t}=await import("../commands/workflows/env.js");return t(e,o)});const K=n.command("project").description("Manage Zibby projects");K.command("list").description("List all projects").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async e=>{const{projectListCommand:o}=await import("../commands/project.js");return o(e)});const N=n.command("run-queue").description("Parallel capacity \u2014 on-disk wait queue (see parallel.waitWhenAtCapacity in .zibby.config.mjs)");N.command("list").description("List CLI processes waiting for a run slot").option("--config <path>","Path to config file",".zibby.config.mjs").action(async e=>{const{runCapacityQueueListCommand:o}=await import("../commands/run-capacity-queue-cli.js");await o(e),process.exit(0)}),n.command("uninstall").description("Remove all Zibby data: global CLI, ~/.zibby, Cursor MCP config, Studio, and current project").option("--dry-run","Show what would be deleted without deleting").option("--deep","Also remove npx cache dirs containing zibby").action(async e=>{const{uninstallCommand:o}=await import("../commands/uninstall.js");await o(e),process.exit(0)}),n.parse();
|
|
48
|
+
`),n.command("init").description("Initialize a Zibby project (config + credentials only \u2014 pass -t <name> to also scaffold a workflow template)").argument("[project-name]","Project name (optional, uses current directory if not provided)").option("--agent <type>","Agent to use (claude, cursor, codex, gemini)").option("--memory-backend <backend>","Memory backend to configure (dolt, mem0)","dolt").option("-t, --template <name>","Workflow template to scaffold into .zibby/ (see `zibby template list`). Default: none \u2014 init only sets up config and credentials.").option("--skip-install","Skip npm install").option("--skip-memory","Skip test memory setup during initialization").option("-f, --force","Force reinitialize (overwrite existing config)").option("--headed","Run MCP browser in headed mode (visible browser)").option("--headless","Run MCP browser in headless mode (hidden browser)").option("--api-key <key>","Zibby API key for cloud sync").option("--cloud-sync","Enable cloud sync and install Zibby MCP").option("--agent-key <key>","Agent API key (non-interactive). For Claude this is the per-token API key").option("--agent-oauth-token <token>","Claude OAuth subscription token (non-interactive). Saves to ~/.zibby/config.json").action(k),n.command("test").description("Run a test specification").argument("[spec-path]","Path to test spec file or inline test description in quotes").option("--sources <ids>","Comma-separated test case IDs to fetch from cloud").option("--execution <id>","Execution ID containing the test cases (required with --sources)").option("--agent <type>","Agent to use (claude, cursor, codex, gemini) - overrides config").option("--workflow <name>","Workflow to use (e.g., QuickSmokeWorkflow, quick-smoke)").option("--headless","Run browser in headless mode").option("--node <name>","Run only a specific node (e.g., execute_live, generate_script)").option("--session <id>",'Use existing session (e.g., 1768974629717 or "last") - requires --node').option("--session-path <dir>","Use this session folder (absolute or relative to cwd); Studio pins artifacts here").option("--project <id>","Project ID (optional, auto-detected from ZIBBY_API_KEY)").option("--collection <id-or-name>","Collection ID or name (creates new if name doesn't exist)").option("--folder <path>","Folder path within collection (optional, requires --collection)").option("--sync","Force upload to cloud (overrides cloudSync: false)").option("--no-sync","Skip upload to cloud (overrides cloudSync: true)").option("--config <path>","Path to config file",".zibby.config.mjs").option("--auto-approve","Auto-approve MCP tools (for CI/CD)").option("-o, --open","Open test results in browser after completion").option("--verbose","Show info level logs").option("--debug","Show debug level logs (most verbose)").option("-m, --mem","Enable test memory (Dolt-backed knowledge from previous runs)").action((e,o)=>(o.debug?process.env.ZIBBY_DEBUG="true":o.verbose&&(process.env.ZIBBY_VERBOSE="true"),b(e,o))),n.command("implement").description("Implement a Jira ticket using AI agent (runs in ECS container)").action(async(...e)=>{const{implementCommand:o}=await import("../commands/implement.js");return o(...e)}),n.command("analyze").description("Analyze a Jira ticket against the codebase (runs in ECS container)").option("--workflow <path>","Path to a local workflow JSON file (e.g., .zibby/workflow-analysis.json)").action(async(...e)=>{const{analyzeCommand:o}=await import("../commands/analyze-graph.js");return o(...e)}),n.command("video").description("Organize test videos next to test files").action(v),n.command("upload <spec-path>").description("Upload existing test artifacts to Zibby Cloud").option("--project <id>","Project ID (REQUIRED - use flag or ZIBBY_PROJECT_ID env)").option("--collection <id-or-name>","Collection ID or name (creates new if name doesn't exist)").option("--folder <path>","Folder path within collection (optional)").option("--agent <type>","Agent used (for metadata)").action(C),n.command("login").description("Log in to Zibby (opens browser for authentication)").action(async()=>{const{loginCli:e}=await import("../auth/cli-login.js");await e(),process.exit(0)}),n.command("logout").description("Log out from Zibby (clears saved session)").action(async()=>{const{logoutCli:e}=await import("../auth/cli-login.js");e(),process.exit(0)}),n.command("status").description("Show current authentication status and token details").option("--json","Output in JSON format (for scripts)").action(async e=>{const{showLoginStatus:o}=await import("../auth/cli-login.js");await o(e),process.exit(0)}),n.command("list").description("List your projects and API tokens").action(async()=>{const{listProjectsCommand:e}=await import("../commands/list-projects.js");await e()}),n.command("ci-setup").description("Setup Cursor Agent for CI/CD (patch and configure)").option("--get-keys","Get MCP approval keys").option("--save","Save approval keys to project").action(I),n.command("setup-playwright").description("Setup official Playwright MCP (from cursor-agent-package)").option("--headed","Configure MCP in headed mode (visible browser)").option("--viewport-width <width>","Viewport width (default: 1280)","1280").option("--viewport-height <height>","Viewport height (default: 720)","720").action(e=>{const o={width:parseInt(e.viewportWidth,10)||1280,height:parseInt(e.viewportHeight,10)||720};return P({...e,viewport:o})}),n.command("setup-ci-full").description("Complete CI/CD setup from scratch").action(S),n.command("test-video").description("Run Playwright tests with video recording").argument("[test-file]","Test file to run (default: tests/)").option("--headed","Run in headed mode (visible browser)").action(A),n.command("generate").description("Generate test specs from a ticket + codebase (local analysis using real AI agent)").option("-t, --ticket <key>","Jira ticket key (fetches automatically)").option("-i, --input <file>","Input file with ticket description/requirements").option("-d, --description <text>","Inline ticket description").option("--repo <path>","Path to the codebase (default: current directory)").option("--agent <type>","Agent to use (codex, claude, cursor, gemini)").option("--model <model>","Model override").option("-o, --output <dir>","Output directory for spec files (default: test-specs)").action(async e=>{const{generateCommand:o}=await import("../commands/generate.js");return o(e)}),n.command("studio").description("Launch Zibby Studio desktop (installs from CDN if needed). Uses this folder as the Zibby project.").option("-p, --port <port>","Port for the Studio API bridge (default: 3847)").option("--no-open","Start the API only; do not launch desktop app").option("--update","Force re-download of the latest Studio binary").action(async e=>{const{studioCommand:o}=await import("../commands/studio.js");return o(e)});const m=n.command("creds").description("Manage credentials Zibby has stored for your workspace (KMS-encrypted)");m.command("list").description("List credentials stored for your workspace (masked)").action(async()=>{const{listCmd:e}=await import("../commands/creds.js");await e(),process.exit(0)}),m.command("sync").description("Re-read ~/.zibby/credentials.env and upload any new tokens").action(async()=>{const{syncCmd:e}=await import("../commands/creds.js");await e(),process.exit(0)}),m.command("remove <type> <index>").description("Remove a stored credential. e.g. zibby creds remove oauth 0").action(async(e,o)=>{const{removeCmd:t}=await import("../commands/creds.js");await t(e,o),process.exit(0)});const F=n.command("g").description("Generate scaffolds");F.command("workflow [name]").description("Scaffold a new custom workflow in .zibby/workflows/<name>/ (auto-generates name if omitted)").option("-t, --template <name>","Scaffold from a template (see `zibby template list`). Future: also accepts npm package / git URL identifiers.").option("--skip-install","Skip running `npm install` in the new workflow folder").option("--skip-init-check","Skip the first-run init prompt that fires when ~/.zibby/config.json is missing (CI/scripted setups)").option("--agent-helpers [list]",'Install agent helpers (Claude Code / Cursor slash commands). List = comma-separated, e.g. "claude" or "claude,cursor". Bare flag defaults to claude.').option("--no-agent-helpers","Skip agent helpers even if .zibby.config.mjs says install").option("--agent <agent>","(legacy) Set up agent helpers: claude | cursor | codex | all | none. Prefer --agent-helpers.").option("--force-agents","Overwrite user-edited agent helper files (use with --agent-helpers)").action(async(e,o)=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(e,o)}),n.command("start <workflow-name>").description("Start a local dev server for a custom workflow").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(e,o)=>{const{startWorkflowCommand:t}=await import("../commands/workflows/start.js");return t(e,o)}),n.command("run <workflow-name>").description("Run a workflow locally \u2014 one-shot (alias of `zibby workflow run`)").option("-p, --param <key=value>","Input param (repeatable)",s,[]).option("--input <json>","Input as JSON string").option("--input-file <path>","Input as JSON file").action(async(e,o)=>{const{runLocalWorkflowCommand:t}=await import("../commands/workflows/run-local.js");return t(e,o)}),n.command("deploy [workflow-name]").description("Deploy a custom workflow to Zibby Cloud (interactive selection if workflow-name not provided)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--dedicated-ip <action>","Manage dedicated egress IP addon: enable | status | disable | use | unuse").option("--env <path>","Path to a .env file to sync into per-workflow env vars after deploy (repeatable)",s,[]).option("--verbose","Show raw CodeBuild logs during the bundle build").option("--no-creds-check","Skip the project secrets sanity check (CI/CD when the secret is provisioned out-of-band)").option("--force","Deploy even if the source checksum matches the last deployed version (bypasses the unchanged check)").option("--warm [count]","Enable warm-pool execution for this workflow (default 1, max 5). Skips ~60s Fargate cold-start by routing triggers to a per-account pool of always-on tasks. Pricing applies (paid feature).",f).action(async(e,o)=>{if(o.dedicatedIp){const{dedicatedEgressCommand:r}=await import("../commands/workflows/dedicated-egress.js");return r(o.dedicatedIp,o.project)}const{deployWorkflowCommand:t}=await import("../commands/workflows/deploy.js");return t(e,o)}),n.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (interactive selection if not provided). Get UUIDs from `zibby workflow list`.").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").option("-t, --follow","Stream logs in real-time after triggering (no need to run `logs -t` separately)").action(async(e,o)=>{const{triggerWorkflowCommand:t}=await import("../commands/workflows/trigger.js");return t(e,o)}),n.command("logs [jobId]").description("Fetch and display logs from a workflow execution (use -t to stream in real-time)").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (fetches the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --follow","Stream logs in real-time (like Heroku logs -t)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(e,o)=>{const{logsCommand:t}=await import("../commands/workflows/logs.js");return t(e,o)}),n.command("run-workflow").description("Run a deployed workflow from S3 sources (used by ECS containers)").action(async()=>{const{runWorkflowCommand:e}=await import("../commands/workflows/run.js");return e()});const g=n.command("template").description("Manage workflow templates in this project");g.command("list").description("List available workflow templates").action(async()=>{const{templateListCommand:e}=await import("../commands/template.js");return e()}),g.command("add",{hidden:!0}).argument("<name>","Template name (see `zibby template list`)").description("(deprecated \u2014 `zibby test` auto-installs the template) Copy a template into .zibby/, overwriting existing files").option("--skip-memory","Strip SKILLS.MEMORY from copied execute-live.mjs (browser-test only)").action(async(e,o)=>{const{templateAddCommand:t}=await import("../commands/template.js");return t(e,{enableMemory:!o.skipMemory})});const c=n.command("memory").description("Test memory database \u2014 version-controlled knowledge from runs");c.command("stats").description("Show memory database statistics").action(async()=>{const{memoryStatsCommand:e}=await import("../commands/memory.js");return e()}),c.command("init").description("Initialize the memory database (Dolt)").action(async()=>{const{memoryInitCommand:e}=await import("../commands/memory.js");return e()}),c.command("compact").description("Prune old data and run Dolt GC to reclaim storage").option("--max-runs <n>","Keep last N runs per spec (default: 50)",parseInt).option("--max-age <days>","Remove data older than N days (default: 90)",parseInt).action(async e=>{const{memoryCompactCommand:o}=await import("../commands/memory.js");return o(e)}),c.command("reset").description("Wipe the memory database").option("-f, --force","Confirm reset").action(async e=>{const{memoryResetCommand:o}=await import("../commands/memory.js");return o(e)}),c.command("cost").description("Show real LLM token usage from past runs (input/output/cache)").action(async()=>{const{memoryCostCommand:e}=await import("../commands/memory.js");return e()});const p=c.command("remote").description("Configure a remote so the team shares cross-spec memory");p.command("add").argument("<url>","Remote URL: aws://, gs://, https://, file:///").option("--name <name>","Remote name (default: origin)","origin").description("Point the local memory DB at a shared remote (S3/GCS/DoltHub/filesystem)").action(async(e,o)=>{const{memoryRemoteAddCommand:t}=await import("../commands/memory.js");return t(e,o)}),p.command("use").description("Switch to a managed remote backend. Currently: --hosted (Zibby-managed S3, signed-in users only).").option("--hosted","Use Zibby-managed S3 (allocates a tenant-scoped prefix per-project)").option("--project-id <id>","Override the projectId from .zibby.config.mjs").action(async e=>{e.hosted||(console.log("Pass --hosted. (Other backends will be added later.)"),process.exit(1));const{memoryRemoteUseHostedCommand:o}=await import("../commands/memory.js");return o(e)}),p.command("info").description("Show the configured memory remote (if any)").action(async()=>{const{memoryRemoteInfoCommand:e}=await import("../commands/memory.js");return e()}),p.command("remove").argument("[name]","Remote name (default: origin)").description("Remove a configured memory remote (memory becomes local-only)").action(async e=>{const{memoryRemoteRemoveCommand:o}=await import("../commands/memory.js");return o(e)}),c.command("pull").description("Pull latest team memory from the configured remote").action(async()=>{const{memoryPullCommand:e}=await import("../commands/memory.js");return e()}),c.command("push").description("Push local memory to the configured remote (auto-runs after passing tests)").action(async()=>{const{memoryPushCommand:e}=await import("../commands/memory.js");return e()});const T=n.command("agents").description("Manage Claude/Cursor/Codex helper files for working with Zibby workflows");T.command("add [agent]").description("Add agent helpers (claude | cursor | codex | all). Prompts if no agent given.").option("--force","Overwrite user-edited helper files").action(async(e,o)=>{const{runAgentHelpers:t,addAgent:r}=await import("../commands/workflows/agent-helpers.js");if(e){const l=["claude","cursor","codex","all","none"];l.includes(e)||(console.error(`Unknown agent "${e}". Valid: ${l.join(", ")}`),process.exit(1)),e==="none"?await t({forcedAgents:["none"],force:o.force===!0}):e==="all"?await t({forcedAgents:["claude","cursor","codex"],force:o.force===!0}):await r(e,{force:o.force===!0})}else await t({forcedAgents:void 0,force:o.force===!0,forcePrompt:!0})});const a=n.command("workflow").description("Manage workflow graphs \u2014 new, start, deploy, trigger, logs, list, download, delete");a.command("new [name]").description("Scaffold a new custom workflow (alias of `zibby g workflow`)").option("-t, --template <name>","Scaffold from a template (see `zibby template list`). Future: also accepts npm package / git URL identifiers.").option("--skip-install","Skip running `npm install` in the new workflow folder").option("--skip-init-check","Skip the first-run init prompt that fires when ~/.zibby/config.json is missing (CI/scripted setups)").option("--agent-helpers [list]",'Install agent helpers (Claude Code / Cursor slash commands). List = comma-separated, e.g. "claude" or "claude,cursor". Bare flag defaults to claude.').option("--no-agent-helpers","Skip agent helpers even if .zibby.config.mjs says install").option("--agent <agent>","(legacy) Set up agent helpers: claude | cursor | codex | all | none. Prefer --agent-helpers.").option("--force-agents","Overwrite user-edited agent helper files (use with --agent-helpers)").action(async(e,o)=>{const{generateWorkflowCommand:t}=await import("../commands/workflows/generate.js");return t(e,o)}),a.command("run <workflow-name>").description("Run a workflow locally \u2014 one-shot, same input flags as `workflow trigger`").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON file \u2014 lowest precedence").action(async(e,o)=>{const{runLocalWorkflowCommand:t}=await import("../commands/workflows/run-local.js");return t(e,o)}),a.command("start <workflow-name>").description("Start a long-lived local dev server (Studio integration). Prefer `workflow run` for one-shots.").option("-p, --port <port>","Port for the workflow server (default: 3848)").action(async(e,o)=>{const{startWorkflowCommand:t}=await import("../commands/workflows/start.js");return t(e,o)}),a.command("deploy [workflow-name]").description("Deploy a workflow to Zibby Cloud (alias of `zibby deploy`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--env <path>","Path to a .env file to sync into per-workflow env vars after deploy (repeatable)",s,[]).option("--verbose","Show raw CodeBuild logs during the bundle build").option("--no-creds-check","Skip the project secrets sanity check (CI/CD when the secret is provisioned out-of-band)").option("--force","Deploy even if the source checksum matches the last deployed version (bypasses the unchanged check)").option("--warm [count]","Enable warm-pool execution for this workflow (default 1, max 5). Skips ~60s Fargate cold-start by routing triggers to a per-account pool of always-on tasks. Pricing applies (paid feature).",f).action(async(e,o)=>{const{deployWorkflowCommand:t}=await import("../commands/workflows/deploy.js");return t(e,o)}),a.command("trigger [uuid]").description("Trigger a deployed workflow by UUID (alias of `zibby trigger`)").option("--project <id>","Project ID (interactive prompt if not provided, or ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("-p, --param <key=value>","Input param (repeatable, e.g. -p url=https://x.com -p count=5)",s,[]).option("--input <json>",`Input as JSON string \u2014 overridden by --param (e.g. '{"key":"value"}')`).option("--input-file <path>","Input as JSON/YAML file \u2014 lowest precedence").option("--idempotency-key <key>","Idempotency key to prevent duplicate executions").option("-t, --follow","Stream logs in real-time after triggering (no need to run `logs -t` separately)").action(async(e,o)=>{const{triggerWorkflowCommand:t}=await import("../commands/workflows/trigger.js");return t(e,o)}),a.command("logs [jobId]").description("Tail logs from a workflow execution (alias of `zibby logs`)").option("--project <id>","Project ID (or ZIBBY_PROJECT_ID env)").option("--workflow <name>","Workflow name (fetches the latest run)").option("--all","Show interleaved logs from all runs (requires --workflow)").option("-t, --follow","Stream logs in real-time (like Heroku logs -t)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").option("--lines <n>","Max log lines per fetch (default: 500)").action(async(e,o)=>{const{logsCommand:t}=await import("../commands/workflows/logs.js");return t(e,o)}),a.command("download <uuid>").description("Download a deployed workflow back to local (edit it, then re-deploy with `zibby workflow deploy`)").option("--dest <path>","Destination directory (default: ./workflows/<name> when run inside a .zibby project)").option("--force","Overwrite without prompting; bypass uuid-mismatch guard").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{downloadWorkflowCommand:t}=await import("../commands/workflows/download.js");return t(e,o)}),a.command("list").description("List all workflows (local + remote if credentials available)").option("--local-only","Show only local workflows").option("--remote-only","Show only remote workflows (requires --project)").option("--project <id>","Project ID (optional, uses ZIBBY_PROJECT_ID env)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async e=>{if(e.remoteOnly){const{workflowListCommand:t}=await import("../commands/workflow.js");return t(e)}if(e.localOnly){const{listLocalWorkflowsCommand:t}=await import("../commands/workflows/list.js");return t(e)}const{listAllWorkflowsCommand:o}=await import("../commands/workflows/list.js");return o(e)}),a.command("validate <name>").description("Static-check a local workflow (.zibby/workflows/<name>/). Catches schema/topology/skill errors in ~30ms before you run anything.").option("--verbose","Print stack traces on graph.mjs import errors").action(async(e,o)=>{const{validateCommand:t}=await import("../commands/workflows/validate.js");return t(e,o)}),a.command("schedule <uuid> [action] [cron]").description(`Manage a workflow's cron schedule. Actions: get (default) | set <cron> | clear. Cron is Unix 5-field, e.g. "0 9 * * 1-5".`).option("--tz <iana>","IANA timezone for the schedule (default: UTC)").option("-p, --param <key=value>","Fixed input param for every scheduled run (repeatable)",s,[]).option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o,t,r)=>{const{scheduleCommand:l}=await import("../commands/workflows/schedule.js");return l(e,o,t,r)}),a.command("delete <uuid>").description("Delete a deployed workflow by UUID").action(async e=>{const{deleteWorkflowCommand:o}=await import("../commands/workflows/delete.js");return o(e,{})});const d=a.command("env").description("Manage per-workflow encrypted env vars (set ANTHROPIC_API_KEY, DATABASE_URL, etc. per workflow)");d.command("list <uuid>").description("List env var key names for a workflow (values never returned)").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{listEnvCommand:t}=await import("../commands/workflows/env.js");return t(e,o)}),d.command("set <uuid> <kv>").description("Set or update one env var: zibby workflow env set <uuid> KEY=value").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o,t)=>{const{setEnvCommand:r}=await import("../commands/workflows/env.js");return r(e,o,t)}),d.command("unset <uuid> <key>").description("Remove one env var from a workflow").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o,t)=>{const{unsetEnvCommand:r}=await import("../commands/workflows/env.js");return r(e,o,t)}),d.command("push <uuid>").description("Bulk-replace env from one or more .env files (later files override). Removes any keys not in the new map.").option("--file <path>","Path to a .env file (repeatable, e.g. --file .env --file .env.prod)",s,[]).option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async(e,o)=>{const{pushEnvCommand:t}=await import("../commands/workflows/env.js");return t(e,o)});const K=n.command("project").description("Manage Zibby projects");K.command("list").description("List all projects").option("--api-key <key>","API key (or ZIBBY_API_KEY env)").action(async e=>{const{projectListCommand:o}=await import("../commands/project.js");return o(e)});const N=n.command("run-queue").description("Parallel capacity \u2014 on-disk wait queue (see parallel.waitWhenAtCapacity in .zibby.config.mjs)");N.command("list").description("List CLI processes waiting for a run slot").option("--config <path>","Path to config file",".zibby.config.mjs").action(async e=>{const{runCapacityQueueListCommand:o}=await import("../commands/run-capacity-queue-cli.js");await o(e),process.exit(0)}),n.command("uninstall").description("Remove all Zibby data: global CLI, ~/.zibby, Cursor MCP config, Studio, and current project").option("--dry-run","Show what would be deleted without deleting").option("--deep","Also remove npx cache dirs containing zibby").action(async e=>{const{uninstallCommand:o}=await import("../commands/uninstall.js");await o(e),process.exit(0)}),n.parse();
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{dirname as b,join as G,resolve as J}from"path";import{fileURLToPath as L}from"url";import{readFileSync as j,existsSync as B}from"fs";import{compileGraph as Q,validateGraphConfig as z,WorkflowGraph as W}from"@zibby/agent-workflow";import{invokeAgent as q}from"@zibby/core";import{buildAnalysisGraph as H}from"@zibby/
|
|
2
|
+
import{dirname as b,join as G,resolve as J}from"path";import{fileURLToPath as L}from"url";import{readFileSync as j,existsSync as B}from"fs";import{compileGraph as Q,validateGraphConfig as z,WorkflowGraph as W}from"@zibby/agent-workflow";import{invokeAgent as q}from"@zibby/core";import{buildAnalysisGraph as H}from"@zibby/workflow-templates/code-analysis/graph.js";import{analysisStateSchema as X}from"@zibby/workflow-templates/code-analysis/state.js";import"@zibby/workflow-templates/register-nodes.js";async function U(r,t){let a=process.env.CONTEXT_PRESIGNED_URL;if(!a)throw new Error("CONTEXT_PRESIGNED_URL env var is required");console.log("\u{1F4E6} Fetching execution context via pre-signed URL");let e=await fetch(a);if(!e.ok)throw new Error(`Failed to fetch execution context: ${e.status}`);let o=await e.json();return console.log(` \u2705 Got ticketContext (${JSON.stringify(o.ticketContext||{}).length} chars)`),o.nodeConfigs&&Object.keys(o.nodeConfigs).length>0&&console.log(` \u2705 Got nodeConfigs (${Object.keys(o.nodeConfigs).length} nodes configured)`),{ticketContext:o.ticketContext||{},nodeConfigs:o.nodeConfigs||{},graphConfig:o.graphConfig||null,repos:o.repos||[]}}import{SQSClient as M,SendMessageCommand as D}from"@aws-sdk/client-sqs";var I=null;function F(){return I||(I=new M({region:process.env.AWS_REGION||"ap-southeast-2"})),I}async function A(r,t,a,e){let{EXECUTION_ID:o,SQS_AUTH_TOKEN:s,PROGRESS_API_URL:d,PROGRESS_QUEUE_URL:i,PROJECT_API_TOKEN:_}=e;if(!o)return;let g={executionId:o,...s&&{sqsAuthToken:s},step:{name:r,status:t,logs:a,timestamp:new Date().toISOString(),...t==="success"&&{completedAt:new Date().toISOString()}},status:t==="failed"?"failed":"running"};try{d?await v(d,o,g,_):i&&await k(i,o,g)}catch(u){console.error(`\u26A0\uFE0F Failed to send progress: ${u.message}`)}}async function N(r,t,a){let{EXECUTION_ID:e,SQS_AUTH_TOKEN:o,PROGRESS_API_URL:s,PROGRESS_QUEUE_URL:d,PROJECT_API_TOKEN:i}=r;if(!e||!a)return;let _=JSON.stringify(a).length;console.log(`Sending artifact: ${t} (${(_/1024).toFixed(1)}KB)`);let g={executionId:e,...o&&{sqsAuthToken:o},artifacts:{[t]:a},timestamp:new Date().toISOString()},u=s?"HTTP":d?"SQS":"NONE",f=JSON.stringify(g).length;try{if(s)await v(s,e,g,i);else if(d)await k(d,e,g);else{console.warn(`\u26A0\uFE0F No transport configured for artifact ${t} \u2014 neither PROGRESS_API_URL nor PROGRESS_QUEUE_URL set`);return}console.log(`Artifact ${t} sent via ${u} (payload=${(f/1024).toFixed(1)}KB, value=${(_/1024).toFixed(1)}KB)`)}catch(c){console.error(`Failed to send artifact ${t} via ${u}:`),console.error(` Payload size: ${(f/1024).toFixed(1)}KB, Value size: ${(_/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}`),f>256*1024&&console.error(" \u26A0\uFE0F Message exceeds SQS 256KB limit! Consider splitting or compressing.")}}async function P(r,{status:t,error:a,finalState:e}){let{EXECUTION_ID:o,SQS_AUTH_TOKEN:s,PROGRESS_API_URL:d,PROGRESS_QUEUE_URL:i,PROJECT_API_TOKEN:_}=r;if(!o)return;let g={executionId:o,...s&&{sqsAuthToken:s},status:t,...a&&{error:a},...e&&typeof e=="object"&&Object.keys(e).length>0?{finalState:e}:{},timestamp:new Date().toISOString()},u=d?"HTTP":i?"SQS":"NONE",f=JSON.stringify(g).length;console.log(`Sending final status: ${t} via ${u} (${(f/1024).toFixed(1)}KB)`);try{if(d)await v(d,o,g,_);else if(i){let c=["completed","failed","insufficient_context","blocked"].includes(t)?"execution_completed":"progress_update";await k(i,o,g,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 ${t} sent via ${u}`)}catch(c){console.error(`Failed to send final status (${t}) via ${u}:`),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 v(r,t,a,e){let o=`${r}/${t}/progress`,s={"Content-Type":"application/json"};e&&(s.Authorization=`Bearer ${e}`);let d=await fetch(o,{method:"POST",headers:s,body:JSON.stringify(a)});if(!d.ok){let i=await d.text();throw new Error(`HTTP ${d.status}: ${i}`)}}async function k(r,t,a,e="progress_update"){let o=JSON.stringify(a),s=(o.length/1024).toFixed(1);o.length>256*1024&&console.error(`\u274C SQS message too large: ${s}KB (limit 256KB) for ${t} [${e}]`),await F().send(new D({QueueUrl:r,MessageBody:o,MessageGroupId:t,MessageAttributes:{executionId:{DataType:"String",StringValue:t},messageType:{DataType:"String",StringValue:e}}}))}import{writeMcpConfig as V}from"@zibby/core/utils/mcp-config-writer.js";var Y=L(import.meta.url),Z=b(Y),ee=JSON.parse(j(G(Z,"../../package.json"),"utf-8")),oe={analyze_ticket:r=>({key:"analysis",value:{raw:r.raw,structured:r.output}}),generate_code:r=>({key:"codeImplementation",value:r.output?.codeImplementation}),generate_test_cases:r=>({key:"tests",value:r.output?.tests}),finalize:r=>({key:"report",value:r.output?.report})};function te(r,t){return async function(e,o,s){let d=Date.now(),i=[],_="",g=console.log,u=process.stdout.write.bind(process.stdout),f=process.stderr.write.bind(process.stderr),c=!1;console.log=(...n)=>{let h=n.map(w=>typeof w=="string"?w:JSON.stringify(w)).join(" ");i.push(h),c=!0,g(...n),c=!1};let S="";process.stdout.write=(n,h,w)=>{if(!c){let p=typeof n=="string"?n:n.toString();S+=p;let $=S.split(`
|
|
3
3
|
`);S=$.pop()||"";for(let y of $){let O=y.trim();O&&i.push(O)}}return u(n,h,w)},g(`[Middleware] Started capturing logs for ${e}`);let R=!1,T=setInterval(()=>{if(R)return;let n=i.join(`
|
|
4
4
|
`);n!==_&&n.length>0&&(_=n,f(`\u{1F4E1} [Middleware] Sending live update for ${e}: ${n.length} chars, ${i.length} lines
|
|
5
5
|
`),r(e,"in_progress",n,s).catch(h=>{f(`\u26A0\uFE0F [Middleware] Failed to send live update: ${h.message}
|
package/dist/commands/chat.js
CHANGED
|
@@ -16,7 +16,7 @@ var Go=Object.defineProperty;var $e=(t,e)=>()=>(t&&(e=t(t=0)),e);var ve=(t,e)=>{
|
|
|
16
16
|
|
|
17
17
|
${cs(e)}`),n+=`
|
|
18
18
|
H: ${o}
|
|
19
|
-
AI:`,n}function ls(t){let e=t.filter(o=>!process.env[o]);return{ok:e.length===0,missing:e}}function us(t){let e=me(t,".zibby.config.mjs");if(!Ce(e))return{};try{return import(e).then(o=>o.default||{})}catch{return{}}}async function ds(t){let e=me(t,".zibby","chat.mjs");if(Ce(e)){let r=await import(e);if(r.CHAT_CONFIG||r.default)return r.CHAT_CONFIG||r.default}let o=me(es(),".zibby","chat.mjs");if(o!==e&&Ce(o)){let r=await import(o);if(r.CHAT_CONFIG||r.default)return r.CHAT_CONFIG||r.default}let n=await import("@zibby/
|
|
19
|
+
AI:`,n}function ls(t){let e=t.filter(o=>!process.env[o]);return{ok:e.length===0,missing:e}}function us(t){let e=me(t,".zibby.config.mjs");if(!Ce(e))return{};try{return import(e).then(o=>o.default||{})}catch{return{}}}async function ds(t){let e=me(t,".zibby","chat.mjs");if(Ce(e)){let r=await import(e);if(r.CHAT_CONFIG||r.default)return r.CHAT_CONFIG||r.default}let o=me(es(),".zibby","chat.mjs");if(o!==e&&Ce(o)){let r=await import(o);if(r.CHAT_CONFIG||r.default)return r.CHAT_CONFIG||r.default}let n=await import("@zibby/workflow-templates/browser-test-automation/chat.mjs");return n.CHAT_CONFIG||n.default||{}}function No(t){try{let e=me(t,".zibby","commands");return Ce(e)?Jn(e).filter(o=>o.toLowerCase().endsWith(".md")).sort((o,n)=>o.localeCompare(n)):[]}catch{return[]}}function ps(t,e){let o=String(e||"").trim();if(!o.startsWith("/"))return o;let[n,...r]=o.split(/\s+/),s=r.join(" ").trim(),a=n.slice(1);if(!a)return o;let c=a.toLowerCase().endsWith(".md")?[a]:[a,`${a}.md`],l=me(t,".zibby","commands"),p=c.find($=>Ce(St(l,$)));if(!p)return o;try{let $=Ro(St(l,p),"utf-8").trim();return s?`${$}
|
|
20
20
|
|
|
21
21
|
${s}`:$}catch{return o}}function fs(t){let e=t.slice(-Bo),o=[],n=0;for(let r=e.length-1;r>=0;r--){let s=e[r],a=String(s?.content||""),c=s?.role==="human"?"user":"assistant",l=a.length;if(o.length>=6&&n+l>is)break;o.push({role:c,content:a}),n+=l}return o.reverse()}function Be(t,e){let o=String(t||"");return o.length<=e?o:`${o.slice(0,Math.max(0,e-24))}
|
|
22
22
|
|
|
@@ -40,7 +40,7 @@ ${I}
|
|
|
40
40
|
`)),process.exit(1)}let z=jt(),W=Wt()?.[0]?.name,A=Vt(e),R="zibby",B=a.skills||[],he=Xt(e),L=he?[...new Set([...B,...he])]:[...B],H={data:null,timestamp:0},ue=300*1e3,ye={jira:"jira",github:"github",slack:"slack",sentry:"sentry"};try{let b=Ye();if(b){let ee=le(),te=await fetch(`${ee}/integrations/status`,{method:"GET",headers:{Authorization:`Bearer ${b}`}});if(te.ok){let C=await te.json();for(let[d,Z]of Object.entries(ye)){let re=C[d]?.connected,J=L.indexOf(Z),Ve=Re(Z);re&&J===-1&&Ve?L.push(Z):!re&&J!==-1&&L.splice(J,1)}Ue(e,L)}}}catch{}let be=L.filter(b=>b!=="skill-installer"&&b!=="core-tools"),_=be.length>0?`Skills: ${be.join(", ")}`:"Skills: (none)";_s({userName:z?.name?.split(" ")[0],cwd:e,projectName:W,restoredCount:A.length,skillsLine:_});let k=No(e),I=Lo(k);return new Promise(b=>{let ee=process.env.ZIBBY_CHAT_TAB_COMPLETION==="1",te={input:process.stdin,output:process.stdout,prompt:i.green(" > "),terminal:!0};ee&&(te.completer=S=>{let g=String(S||"");if(!g.startsWith("/"))return[[],g];let v=I.map(U=>U.cmd),P=v.filter(U=>U.startsWith(g));return[P.length>0?P:v,g]});let C=Vn(te),d=xs(C),Z=null,re=!1,J=[],Ve=0,Mo=1200,pe=!1,we=!1,_e=!1,ie=!1,de="",ae=0,q=typeof C._ttyWrite=="function"?C._ttyWrite.bind(C):null;q&&(C._ttyWrite=(...S)=>{if(!(ie||Date.now()<ae))return q(...S)});function jo(){_e||!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004h"),_e=!0)}function vt(){_e&&(!process.stdout?.isTTY||typeof process.stdout.write!="function"||(process.stdout.write("\x1B[?2004l"),_e=!1))}function zo(S){let g="\x1B[200~",v="\x1B[201~";if(!ie&&!S.includes(g))return!1;let P=S,U=!1;for(;P.length>0;){if(!ie){let N=P.indexOf(g);if(N===-1)break;U=!0,It(),ie=!0,de="",P=P.slice(N+g.length);continue}let V=P.indexOf(v);if(V===-1){U=!0,de+=P;break}U=!0,de+=P.slice(0,V);let ce=String(de||"").replace(/\r\n/g,`
|
|
41
41
|
`).replace(/\r/g,`
|
|
42
42
|
`);if(ce.length>0){let N=ce.split(`
|
|
43
|
-
`);for(let oe of N)nt(oe)}Me(),de="",ie=!1,P=P.slice(V+v.length)}return U}function At(){if(!pe){pe=!0;try{Ne(e,A),Ue(e,L)}catch{}try{vt()}catch{}try{C.close()}catch{}process.exit(0)}}async function Xe(){if(!pe){pe=!0,typeof $?.cleanup=="function"&&await $.cleanup().catch(()=>{});try{let{killAllChatOrchestratedRuns:S}=await Promise.resolve().then(()=>(ft(),pt)),{postCliInterruptedRunIndex:g}=await import("@zibby/
|
|
43
|
+
`);for(let oe of N)nt(oe)}Me(),de="",ie=!1,P=P.slice(V+v.length)}return U}function At(){if(!pe){pe=!0;try{Ne(e,A),Ue(e,L)}catch{}try{vt()}catch{}try{C.close()}catch{}process.exit(0)}}async function Xe(){if(!pe){pe=!0,typeof $?.cleanup=="function"&&await $.cleanup().catch(()=>{});try{let{killAllChatOrchestratedRuns:S}=await Promise.resolve().then(()=>(ft(),pt)),{postCliInterruptedRunIndex:g}=await import("@zibby/workflow-templates/run-index-post-cli.js");S(e,process.pid,s),g({cwd:e,config:s})}catch{}Ne(e,A),Ue(e,L),d.pushSystem(i.gray("Session saved. Goodbye!")),vt(),C.close(),process.exit(0)}}if(d.mount(),jo(),process.stdout?.isTTY){let S;process.stdout.on("resize",()=>{clearTimeout(S),S=setTimeout(()=>{d.handleResize()},80)})}let Qe=0,De=S=>{if(typeof S=="string"?S==="\x1B":S&&typeof S.length=="number"?S.length===1&&S[0]===27:!1){Z&&Z.abort(),At();return}let v=typeof S=="string"?S:S&&typeof S.length=="number"?Buffer.from(S).toString("utf8"):"";if(!v)return;if(zo(v)){Qe=Date.now()+1200,ae=Date.now()+1200,ot();return}let P=(v.includes(`
|
|
44
44
|
`)||v.includes("\r"))&&v!=="\r"&&v!==`
|
|
45
45
|
`&&v!==`\r
|
|
46
46
|
`,U=v.includes("\x1B[200~")||v.includes("\x1B[201~"),V=v.length>=16&&/\s/.test(v)&&!v.startsWith("\x1B");(P||U||V)&&(Qe=Date.now()+1200,ae=Date.now()+1200,It(),ot())},F={query:"",matches:[],selected:0},G={prefix:"",matches:[],nextIndex:0},O={active:!1,prefix:"",lines:[],timer:null},et=[],Ct=0,tt="",Fo=new Set($t.map(S=>S.cmd));function Se(S,{preserveFrame:g=!1}={}){let v=String(S||"");C.line=v,C.cursor=v.length,tt=v,typeof C._refreshLine=="function"?C._refreshLine():C.prompt(),g&&d.touchInputFrame()}function kt(){G.prefix="",G.matches=[],G.nextIndex=0}function Me(){if(O.timer&&(clearTimeout(O.timer),O.timer=null),O.active&&O.lines.length>0){Ct+=1;let S=O.lines.length,g=`[Pasted text #${Ct} +${S} lines]`,v=O.lines.join(`
|
package/dist/commands/init.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var ko=Object.defineProperty;var j=(e,o)=>()=>(e&&(o=e(e=0)),o);var L=(e,o)=>{for(var t in o)ko(e,t,{get:o[t],enumerable:!0})};var $e={};L($e,{resolveTemplate:()=>Ie,templateAddCommand:()=>Do,templateListCommand:()=>Lo,writeTemplateFiles:()=>Pe,writeTemplateFilesToDir:()=>Ce});import{mkdir as _e,writeFile as Co,readFile as Po}from"fs/promises";import{existsSync as Q,readdirSync as $o,statSync as So,readFileSync as Eo}from"fs";import{join as D,dirname as Ro}from"path";import{fileURLToPath as zo}from"url";import{spawn as To}from"child_process";import{createRequire as Oo}from"module";import x from"chalk";import Ko from"ora";function jo(e){return No.some(o=>o.test(e))}async function Ae(e,o,t=null){let i=[];Q(o)||await _e(o,{recursive:!0});for(let s of $o(e)){if(jo(s))continue;let n=D(e,s),p=D(o,s),d=So(n);if(d.isDirectory()){let l=await Ae(n,p,t);for(let m of l)i.push(`${s}/${m}`)}else if(d.isFile()){let l=await Po(n,"utf-8");t&&(l=t(s,l)),await Co(p,l),i.push(s)}}return i}async function Ie(e){if(!e||typeof e!="string")throw new Error("Template name is required");if(/^(git\+|https?:)/.test(e))throw new Error(`Git/URL templates are not yet supported (got "${e}"). For now use a built-in template \u2014 see \`zibby template list\`.`);if(e.startsWith("@")||e.includes("/")||e.startsWith("zibby-template-"))throw new Error(`npm-package templates are not yet supported (got "${e}"). For now use a built-in template \u2014 see \`zibby template list\`.`);let{TemplateFactory:o}=await import("@zibby/
|
|
1
|
+
var ko=Object.defineProperty;var j=(e,o)=>()=>(e&&(o=e(e=0)),o);var L=(e,o)=>{for(var t in o)ko(e,t,{get:o[t],enumerable:!0})};var $e={};L($e,{resolveTemplate:()=>Ie,templateAddCommand:()=>Do,templateListCommand:()=>Lo,writeTemplateFiles:()=>Pe,writeTemplateFilesToDir:()=>Ce});import{mkdir as _e,writeFile as Co,readFile as Po}from"fs/promises";import{existsSync as Q,readdirSync as $o,statSync as So,readFileSync as Eo}from"fs";import{join as D,dirname as Ro}from"path";import{fileURLToPath as zo}from"url";import{spawn as To}from"child_process";import{createRequire as Oo}from"module";import x from"chalk";import Ko from"ora";function jo(e){return No.some(o=>o.test(e))}async function Ae(e,o,t=null){let i=[];Q(o)||await _e(o,{recursive:!0});for(let s of $o(e)){if(jo(s))continue;let n=D(e,s),p=D(o,s),d=So(n);if(d.isDirectory()){let l=await Ae(n,p,t);for(let m of l)i.push(`${s}/${m}`)}else if(d.isFile()){let l=await Po(n,"utf-8");t&&(l=t(s,l)),await Co(p,l),i.push(s)}}return i}async function Ie(e){if(!e||typeof e!="string")throw new Error("Template name is required");if(/^(git\+|https?:)/.test(e))throw new Error(`Git/URL templates are not yet supported (got "${e}"). For now use a built-in template \u2014 see \`zibby template list\`.`);if(e.startsWith("@")||e.includes("/")||e.startsWith("zibby-template-"))throw new Error(`npm-package templates are not yet supported (got "${e}"). For now use a built-in template \u2014 see \`zibby template list\`.`);let{TemplateFactory:o}=await import("@zibby/workflow-templates");return o.getTemplateFiles(e)}async function Ce(e,o,t={}){let i=t.enableMemory!==!1,{template:s}=await Ie(o);Q(e)||await _e(e,{recursive:!0});let n=await Ae(s.path,e,(p,d)=>!i&&p==="execute-live.mjs"?d.replace("skills: [SKILLS.BROWSER, SKILLS.MEMORY],","skills: [SKILLS.BROWSER],"):d);return{template:s,copied:n}}async function Pe(e,o,t={}){return Ce(D(e,".zibby"),o,t)}async function Lo(){let{TemplateFactory:e}=await import("@zibby/workflow-templates"),o=e.listTemplates();console.log(""),console.log(x.bold.cyan(" Available templates")),console.log("");for(let t of o){if(console.log(` ${x.cyan(t.name)}`),console.log(` ${x.white(t.displayName)}`),t.description&&console.log(` ${x.gray(t.description)}`),t.features&&t.features.length)for(let s of t.features)console.log(x.gray(` \u2022 ${s}`));let i=t.defaultSlug||"your-workflow-name";console.log(""),console.log(` ${x.gray("Scaffold:")} ${x.cyan(`zibby workflow new ${i} -t ${t.name}`)}`),console.log("")}}async function Do(e,o={}){e||(console.log(x.red(`
|
|
2
2
|
Missing template name.
|
|
3
3
|
`)),console.log(x.gray(" Usage: zibby template add <name>")),console.log(x.gray(` See available templates: zibby template list
|
|
4
4
|
`)),process.exit(1));let t=o.cwd||process.cwd(),i=D(t,".zibby");Q(i)||(console.log(x.yellow(`
|
package/dist/commands/run.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var De=Object.defineProperty;var je=(t,o)=>()=>(t&&(o=t(t=0)),o);var Ye=(t,o)=>{for(var s in o)De(t,s,{get:o[s],enumerable:!0})};var xe={};Ye(xe,{_resetLoaderCacheForTests:()=>lo,loadCredentialsIntoEnv:()=>co});import Pe from"node:fs";import to from"node:path";import no from"node:os";async function Ee(){if(!(process.env.__ZIBBY_CLAUDE_PLAN||process.platform!=="darwin"||!(process.env.CLAUDE_CODE_OAUTH_TOKEN||process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL||process.env.ANTHROPIC_AUTH_TOKEN)))try{let{execSync:o}=await import("node:child_process"),s=o('security find-generic-password -s "Claude Code-credentials" -w',{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(s){let i=JSON.parse(s)?.claudeAiOauth?.subscriptionType;i&&(process.env.__ZIBBY_CLAUDE_PLAN=i)}}catch{}}function io(t){try{if(!Pe.existsSync(t))return{};let o=Pe.readFileSync(t,"utf-8"),s=JSON.parse(o);return s&&s.agentKeys&&typeof s.agentKeys=="object"?s.agentKeys:{}}catch{return{}}}async function co(t={}){let{verbose:o=!1,force:s=!1,configPath:l}=t;if(q&&!s)return G;if(!!(process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL||process.env.ANTHROPIC_API_KEY_POOL||process.env.CLAUDE_CODE_OAUTH_TOKEN||process.env.ANTHROPIC_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN))return await Ee(),q=!0,G={oauthCount:0,apiCount:0,source:"cloud-env"},o&&console.log("[credentials-loader] env vars already set \u2014 skipping local discovery"),G;let a=l||to.join(no.homedir(),".zibby","config.json"),n=io(a),y="none",d=0,m=0;for(let h of so)n[h]&&!process.env[h]&&(process.env[h]=String(n[h]).trim(),y="config.json",h.endsWith("_POOL")?d+=String(n[h]).split(",").filter(D=>D.trim()).length:d+=1);for(let h of ro)n[h]&&!process.env[h]&&(process.env[h]=String(n[h]).trim(),y="config.json",h.endsWith("_POOL")?m+=String(n[h]).split(",").filter(D=>D.trim()).length:m+=1);return await Ee(),q=!0,G={oauthCount:d,apiCount:m,source:y},o&&d+m>0&&console.log(`[credentials-loader] loaded ${d} OAuth + ${m} API from ${y} (~/.zibby/config.json)`),G}function lo(){q=!1,G=null}var q,G,so,ro,be=je(()=>{q=!1,G=null,so=["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN_POOL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_AUTH_TOKEN_POOL"],ro=["ANTHROPIC_API_KEY","ANTHROPIC_API_KEY_POOL"]});import{runTest as ao,logger as U,DEFAULT_OUTPUT_BASE as uo,SESSIONS_DIR as po}from"@zibby/core";import{zibbyScratchSpecsDir as ae}from"@zibby/core/constants/zibby-scratch.js";import{createCliRunIndexPipelineProgressAppender as fo,postCliInterruptedRunIndex as Oe}from"@zibby/
|
|
1
|
+
var De=Object.defineProperty;var je=(t,o)=>()=>(t&&(o=t(t=0)),o);var Ye=(t,o)=>{for(var s in o)De(t,s,{get:o[s],enumerable:!0})};var xe={};Ye(xe,{_resetLoaderCacheForTests:()=>lo,loadCredentialsIntoEnv:()=>co});import Pe from"node:fs";import to from"node:path";import no from"node:os";async function Ee(){if(!(process.env.__ZIBBY_CLAUDE_PLAN||process.platform!=="darwin"||!(process.env.CLAUDE_CODE_OAUTH_TOKEN||process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL||process.env.ANTHROPIC_AUTH_TOKEN)))try{let{execSync:o}=await import("node:child_process"),s=o('security find-generic-password -s "Claude Code-credentials" -w',{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(s){let i=JSON.parse(s)?.claudeAiOauth?.subscriptionType;i&&(process.env.__ZIBBY_CLAUDE_PLAN=i)}}catch{}}function io(t){try{if(!Pe.existsSync(t))return{};let o=Pe.readFileSync(t,"utf-8"),s=JSON.parse(o);return s&&s.agentKeys&&typeof s.agentKeys=="object"?s.agentKeys:{}}catch{return{}}}async function co(t={}){let{verbose:o=!1,force:s=!1,configPath:l}=t;if(q&&!s)return G;if(!!(process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL||process.env.ANTHROPIC_API_KEY_POOL||process.env.CLAUDE_CODE_OAUTH_TOKEN||process.env.ANTHROPIC_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN))return await Ee(),q=!0,G={oauthCount:0,apiCount:0,source:"cloud-env"},o&&console.log("[credentials-loader] env vars already set \u2014 skipping local discovery"),G;let a=l||to.join(no.homedir(),".zibby","config.json"),n=io(a),y="none",d=0,m=0;for(let h of so)n[h]&&!process.env[h]&&(process.env[h]=String(n[h]).trim(),y="config.json",h.endsWith("_POOL")?d+=String(n[h]).split(",").filter(D=>D.trim()).length:d+=1);for(let h of ro)n[h]&&!process.env[h]&&(process.env[h]=String(n[h]).trim(),y="config.json",h.endsWith("_POOL")?m+=String(n[h]).split(",").filter(D=>D.trim()).length:m+=1);return await Ee(),q=!0,G={oauthCount:d,apiCount:m,source:y},o&&d+m>0&&console.log(`[credentials-loader] loaded ${d} OAuth + ${m} API from ${y} (~/.zibby/config.json)`),G}function lo(){q=!1,G=null}var q,G,so,ro,be=je(()=>{q=!1,G=null,so=["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN_POOL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_AUTH_TOKEN_POOL"],ro=["ANTHROPIC_API_KEY","ANTHROPIC_API_KEY_POOL"]});import{runTest as ao,logger as U,DEFAULT_OUTPUT_BASE as uo,SESSIONS_DIR as po}from"@zibby/core";import{zibbyScratchSpecsDir as ae}from"@zibby/core/constants/zibby-scratch.js";import{createCliRunIndexPipelineProgressAppender as fo,postCliInterruptedRunIndex as Oe}from"@zibby/workflow-templates/run-index-post-cli.js";import{createWriteStream as Ke,mkdirSync as Fe}from"fs";import{join as pe,isAbsolute as ze}from"path";var Ge="studio-cli.log";function He(t,o){if(!t||typeof t!="string")return null;let s=t.trim();return s?ze(s)?s:pe(o,s):null}function Ze(t){if(!t)return()=>{};Fe(t,{recursive:!0});let o=pe(t,Ge),s=Ke(o,{flags:"a"}),l=process.stdout.write.bind(process.stdout),i=process.stderr.write.bind(process.stderr),a=n=>function(d,m,h){typeof m=="function"&&(h=m,m=void 0);try{Buffer.isBuffer(d)?s.write(d):s.write(String(d),m||"utf8")}catch{}return n(d,m,h)};return process.stdout.write=a(l),process.stderr.write=a(i),()=>{process.stdout.write=l,process.stderr.write=i;try{s.end()}catch{}}}function oe(t,o,s){let l=null;function i(a){if(!l&&a?.sessionPath){let n=He(a.sessionPath,o);n&&(l=Ze(n))}typeof t=="function"&&t(a)}return i.dispose=()=>{typeof l=="function"&&(l(),l=null)},i}import{existsSync as fe,mkdirSync as Me,readFileSync as Ve,readdirSync as Lo,unlinkSync as We,writeFileSync as ge}from"fs";import{join as he}from"path";import{execSync as Yo}from"child_process";import{DEFAULT_OUTPUT_BASE as Je}from"@zibby/core";function ye(t){return t?.paths?.output||Je}function te(t,o,s){return he(t,o,`.zibby-chat-run-pids-${s}.json`)}function me(t,o,s){let l=te(t,o,s);if(!fe(l))return[];try{let i=JSON.parse(Ve(l,"utf8"));return(Array.isArray(i?.pids)?i.pids:[]).map(n=>Number(n)).filter(n=>Number.isFinite(n)&&n>0)}catch{return[]}}function Ie(t,o,s,l={}){let i=Number(o),a=Number(s);if(!Number.isFinite(i)||i<=0||!Number.isFinite(a)||a<=0)return;let n=ye(l),y=he(t,n);Me(y,{recursive:!0});let d=me(t,n,i);d.includes(a)||d.push(a),ge(te(t,n,i),`${JSON.stringify({v:1,pids:d})}
|
|
2
2
|
`,"utf8")}function _e(t,o,s,l={}){let i=Number(o),a=Number(s);if(!Number.isFinite(i)||i<=0||!Number.isFinite(a)||a<=0)return;let n=ye(l),y=te(t,n,i);if(!fe(y))return;let d=me(t,n,i).filter(m=>m!==a);if(d.length===0)try{We(y)}catch{}else ge(y,`${JSON.stringify({v:1,pids:d})}
|
|
3
3
|
`,"utf8")}import{readFileSync as O,existsSync as w,statSync as Te,mkdirSync as Ue,writeFileSync as Se,appendFileSync as go,rmSync as $e}from"fs";import{resolve as B,join as $,dirname as ho,isAbsolute as Ne}from"path";import{fileURLToPath as yo}from"url";import{glob as X}from"glob";import e from"chalk";import Be from"ora";import mo from"dotenv";import Io from"open";var b={local:{name:"Local Development",apiUrl:"http://localhost:3001",accountApiUrl:"http://localhost:3001",frontendUrl:"http://localhost:3000",description:"Local backend running on port 3001"},prod:{name:"Production",apiUrl:process.env.ZIBBY_PROD_API_URL||"https://api-prod.zibby.app",accountApiUrl:process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app",frontendUrl:process.env.ZIBBY_PROD_FRONTEND_URL||"https://studio.zibby.dev",description:"Production environment"}};function W(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let o=process.env.ZIBBY_ENV||"prod";b[o]?t=b[o].apiUrl:t=b.prod.apiUrl}try{let o=new URL(t);return o.protocol!=="http:"&&o.protocol!=="https:"?(console.error(`\u26A0\uFE0F Invalid API URL protocol: ${o.protocol} (only http/https allowed)`),b.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),b.prod.apiUrl}}function we(){if(process.env.ZIBBY_ACCOUNT_API_URL)return process.env.ZIBBY_ACCOUNT_API_URL;let t=process.env.ZIBBY_ENV||"prod";return(b[t]||b.prod).accountApiUrl}function ne(){let t=process.env.ZIBBY_ENV||"prod";return b[t]||b.prod}function se(){let t;if(process.env.ZIBBY_FRONTEND_URL)t=process.env.ZIBBY_FRONTEND_URL;else{let o=process.env.ZIBBY_ENV||"prod";b[o]?t=b[o].frontendUrl:t=b.prod.frontendUrl}try{let o=new URL(t);if(o.protocol!=="http:"&&o.protocol!=="https:")return console.error(`\u26A0\uFE0F Invalid frontend URL protocol: ${o.protocol} (only http/https allowed)`),b.local.frontendUrl;if(process.env.NODE_ENV==="production"||process.env.ZIBBY_ENV==="prod"){let l=["zibby.dev","studio.zibby.dev","studio-staging.zibby.dev","zibby.app","studio.zibby.app","studio-staging.zibby.app"],i=o.hostname;if(!l.some(n=>i===n||i.endsWith(`.${n}`))&&!i.includes("localhost")&&i!=="127.0.0.1")return console.error(`\u26A0\uFE0F Untrusted frontend URL in production: ${i}`),"https://studio.zibby.dev"}return t}catch{return console.error(`\u26A0\uFE0F Invalid frontend URL: ${t}`),b.local.frontendUrl}}import{existsSync as qe,mkdirSync as Ho,readFileSync as Xe,writeFileSync as Zo}from"fs";import{homedir as ve}from"os";import{join as J}from"path";function Qe(){return process.env.ZIBBY_CONFIG_DIR||J(ve(),".zibby")}function eo(){return J(Qe(),"config.json")}var oo=J(ve(),".zibby"),Wo=J(oo,"config.json");function Ae(){try{let t=eo();if(qe(t)){let o=Xe(t,"utf-8");return JSON.parse(o)}}catch{}return{}}function re(){return Ae().sessionToken||null}function ie(){return Ae().user||null}var _o=yo(import.meta.url),wo=ho(_o),vo=JSON.parse(O($(wo,"../../package.json"),"utf-8"));function Ao(t){let o=s=>s?typeof s.message=="string"&&s.message.includes("Interrupted by user")?!0:Array.isArray(s.errors)?s.errors.some(o):s.cause?o(s.cause):!1:!1;return o(t)}function Ce(t,o){if(t==null)return null;let s=String(t).trim();return s?Ne(s)?s:B(o,s):null}function Po(t,o){try{if(!t||!w(t))return;let s=$(t,"studio-cli.log"),l=`
|
|
4
4
|
[CLI_FATAL] ${new Date().toISOString()}
|
|
@@ -93,7 +93,7 @@ Error: no Claude credentials found
|
|
|
93
93
|
`)),console.log(e.white(`Get your API key from: https://cursor.com/settings
|
|
94
94
|
`)),console.log(e.white(`Add it to your CI/CD environment variables.
|
|
95
95
|
`)),process.exit(1)):console.log(e.yellow(`\u26A0\uFE0F CURSOR_API_KEY not set (using locally stored Cursor credentials)
|
|
96
|
-
`)))}console.log(e.white(`Test Spec: ${e.cyan(t)}`));let D=typeof n.agent=="object"?n.agent.provider:n.agent;console.log(e.white(`Agent: ${e.cyan(D)}`)),console.log(e.white(`Browser: ${e.cyan(n.mcp||"playwright")} ${n.headless?e.gray("(headless)"):e.gray("(headed)")}`)),n.cloudSync&&console.log(e.white(`Cloud Sync: ${e.green("enabled")}`)),o.autoApprove&&console.log(e.white(`Auto-approve: ${e.yellow("enabled (CI/CD mode)")}`)),o.collection?console.log(e.white(`Collection: ${e.cyan(o.collection)}${o.folder?` / ${o.folder}`:""}`)):console.log(e.gray("Mode: Orphan execution (History tab)"));let k;if(o.sessionPath!=null&&String(o.sessionPath).trim()!==""){let r=String(o.sessionPath).trim();k=Ne(r)?B(r):B(process.cwd(),r),console.log(e.white(`Session path: ${e.cyan(k)}`))}console.log(e.gray("\u2501".repeat(50)));let v=Be({text:"Initializing...",stream:process.stdout}).start(),f=()=>{try{Oe({cwd:process.cwd(),config:n})}catch{}},T=process.env.ZIBBY_CHAT_OWNER_PID,S=T!=null&&String(T).trim()!==""?Number(T):null,L=S!=null&&Number.isFinite(S)&&S>0,K=()=>{if(L)try{_e(process.cwd(),S,process.pid,n)}catch{}},Y=null,M=Ce(k,process.cwd());try{v.stop();let{waitUntilRunCapacity:r}=await import("@zibby/core/utils/run-capacity-coordinator.js"),{basename:u}=await import("path");await r({cwd:process.cwd(),config:n,meta:{source:process.env.ZIBBY_RUN_SOURCE||"cli",specHint:t?u(t):"",studioTestCaseId:process.env.ZIBBY_STUDIO_TEST_CASE_ID||null},log:p=>console.log(e.gray(p))});let I=await import("@zibby/
|
|
96
|
+
`)))}console.log(e.white(`Test Spec: ${e.cyan(t)}`));let D=typeof n.agent=="object"?n.agent.provider:n.agent;console.log(e.white(`Agent: ${e.cyan(D)}`)),console.log(e.white(`Browser: ${e.cyan(n.mcp||"playwright")} ${n.headless?e.gray("(headless)"):e.gray("(headed)")}`)),n.cloudSync&&console.log(e.white(`Cloud Sync: ${e.green("enabled")}`)),o.autoApprove&&console.log(e.white(`Auto-approve: ${e.yellow("enabled (CI/CD mode)")}`)),o.collection?console.log(e.white(`Collection: ${e.cyan(o.collection)}${o.folder?` / ${o.folder}`:""}`)):console.log(e.gray("Mode: Orphan execution (History tab)"));let k;if(o.sessionPath!=null&&String(o.sessionPath).trim()!==""){let r=String(o.sessionPath).trim();k=Ne(r)?B(r):B(process.cwd(),r),console.log(e.white(`Session path: ${e.cyan(k)}`))}console.log(e.gray("\u2501".repeat(50)));let v=Be({text:"Initializing...",stream:process.stdout}).start(),f=()=>{try{Oe({cwd:process.cwd(),config:n})}catch{}},T=process.env.ZIBBY_CHAT_OWNER_PID,S=T!=null&&String(T).trim()!==""?Number(T):null,L=S!=null&&Number.isFinite(S)&&S>0,K=()=>{if(L)try{_e(process.cwd(),S,process.pid,n)}catch{}},Y=null,M=Ce(k,process.cwd());try{v.stop();let{waitUntilRunCapacity:r}=await import("@zibby/core/utils/run-capacity-coordinator.js"),{basename:u}=await import("path");await r({cwd:process.cwd(),config:n,meta:{source:process.env.ZIBBY_RUN_SOURCE||"cli",specHint:t?u(t):"",studioTestCaseId:process.env.ZIBBY_STUDIO_TEST_CASE_ID||null},log:p=>console.log(e.gray(p))});let I=await import("@zibby/workflow-templates/browser-test-automation/graph.mjs").catch(()=>null);if(L)try{Ie(process.cwd(),S,process.pid,n)}catch{}process.on("SIGINT",f),process.on("SIGTERM",f);let E=process.cwd(),A={},j=p=>{let P=Ce(p?.sessionPath,E);P&&(M=P)};if(typeof n.onPipelineProgress=="function"){let p=oe(n.onPipelineProgress,E,n);Y=()=>p.dispose(),A.onPipelineProgress=P=>{j(P),p({...P,specPath:t,taskDescription:a})}}else if(n.runIndex?.pipelineProgress!==!1){let p=fo({cwd:E,config:n}),P=oe(p,E,n);Y=()=>P.dispose(),A.onPipelineProgress=H=>{j(H),P({...H,specPath:t,taskDescription:a})}}let _=await ao(i,{...n,...A,specPath:t,apiKey:process.env.ANTHROPIC_API_KEY,autoApprove:o.autoApprove,force:o.autoApprove,singleNode:o.node,sessionId:o.session,...k?{sessionPath:k}:{},workflow:o.workflow,contextConfig:n.context,fallbackAgentModule:I}),x=_.outputPath||null;x&&(x=x.replace(/\/+/g,"/"),x.includes(process.cwd())&&(x=x.replace(`${process.cwd()}/`,"")));let V=_.state?.generate_script?.scriptPath||_.state?.verify_script?.success;if(console.log(e.gray(`
|
|
97
97
|
${"\u2501".repeat(50)}`)),V&&x)console.log(e.green("\u2713 Test execution completed")),console.log(e.white(`Generated test: ${e.cyan(x)}`)),_.toolCount!==void 0&&console.log(e.white(`Tools used: ${e.cyan(_.toolCount)}`)),console.log(e.gray(`${"\u2501".repeat(50)}
|
|
98
98
|
`)),console.log(e.cyan("Next steps:")),console.log(e.white(` 1. Review generated test: ${x}`)),console.log(e.white(` 2. Run with Playwright: npx playwright test ${x}`)),console.log(e.white(` 3. View report: npx playwright show-report
|
|
99
99
|
`));else{let p=_.state?.execute_live;p?p.steps?.length>0||p.actions?.length>0?(console.log(e.white(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{mkdir as y,writeFile as b,readFile as w}from"fs/promises";import{existsSync as m,readdirSync as $,statSync as h,readFileSync as S}from"fs";import{join as c,dirname as z}from"path";import{fileURLToPath as k}from"url";import{spawn as R}from"child_process";import{createRequire as v}from"module";import o from"chalk";import _ from"ora";var j=k(import.meta.url),T=z(j),x=[/^__tests__$/,/^__mocks__$/,/^node_modules$/,/\.test\.[mc]?js$/,/\.spec\.[mc]?js$/,/^\.DS_Store$/,/^chat\.mjs$/];function F(e){return x.some(s=>s.test(e))}async function g(e,s,t=null){let a=[];m(s)||await y(s,{recursive:!0});for(let l of $(e)){if(F(l))continue;let n=c(e,l),p=c(s,l),r=h(n);if(r.isDirectory()){let i=await g(n,p,t);for(let f of i)a.push(`${l}/${f}`)}else if(r.isFile()){let i=await w(n,"utf-8");t&&(i=t(l,i)),await b(p,i),a.push(l)}}return a}async function L(e){if(!e||typeof e!="string")throw new Error("Template name is required");if(/^(git\+|https?:)/.test(e))throw new Error(`Git/URL templates are not yet supported (got "${e}"). For now use a built-in template \u2014 see \`zibby template list\`.`);if(e.startsWith("@")||e.includes("/")||e.startsWith("zibby-template-"))throw new Error(`npm-package templates are not yet supported (got "${e}"). For now use a built-in template \u2014 see \`zibby template list\`.`);let{TemplateFactory:s}=await import("@zibby/
|
|
1
|
+
import{mkdir as y,writeFile as b,readFile as w}from"fs/promises";import{existsSync as m,readdirSync as $,statSync as h,readFileSync as S}from"fs";import{join as c,dirname as z}from"path";import{fileURLToPath as k}from"url";import{spawn as R}from"child_process";import{createRequire as v}from"module";import o from"chalk";import _ from"ora";var j=k(import.meta.url),T=z(j),x=[/^__tests__$/,/^__mocks__$/,/^node_modules$/,/\.test\.[mc]?js$/,/\.spec\.[mc]?js$/,/^\.DS_Store$/,/^chat\.mjs$/];function F(e){return x.some(s=>s.test(e))}async function g(e,s,t=null){let a=[];m(s)||await y(s,{recursive:!0});for(let l of $(e)){if(F(l))continue;let n=c(e,l),p=c(s,l),r=h(n);if(r.isDirectory()){let i=await g(n,p,t);for(let f of i)a.push(`${l}/${f}`)}else if(r.isFile()){let i=await w(n,"utf-8");t&&(i=t(l,i)),await b(p,i),a.push(l)}}return a}async function L(e){if(!e||typeof e!="string")throw new Error("Template name is required");if(/^(git\+|https?:)/.test(e))throw new Error(`Git/URL templates are not yet supported (got "${e}"). For now use a built-in template \u2014 see \`zibby template list\`.`);if(e.startsWith("@")||e.includes("/")||e.startsWith("zibby-template-"))throw new Error(`npm-package templates are not yet supported (got "${e}"). For now use a built-in template \u2014 see \`zibby template list\`.`);let{TemplateFactory:s}=await import("@zibby/workflow-templates");return s.getTemplateFiles(e)}async function E(e,s,t={}){let a=t.enableMemory!==!1,{template:l}=await L(s);m(e)||await y(e,{recursive:!0});let n=await g(l.path,e,(p,r)=>!a&&p==="execute-live.mjs"?r.replace("skills: [SKILLS.BROWSER, SKILLS.MEMORY],","skills: [SKILLS.BROWSER],"):r);return{template:l,copied:n}}async function P(e,s,t={}){return E(c(e,".zibby"),s,t)}async function U(){let{TemplateFactory:e}=await import("@zibby/workflow-templates"),s=e.listTemplates();console.log(""),console.log(o.bold.cyan(" Available templates")),console.log("");for(let t of s){if(console.log(` ${o.cyan(t.name)}`),console.log(` ${o.white(t.displayName)}`),t.description&&console.log(` ${o.gray(t.description)}`),t.features&&t.features.length)for(let l of t.features)console.log(o.gray(` \u2022 ${l}`));let a=t.defaultSlug||"your-workflow-name";console.log(""),console.log(` ${o.gray("Scaffold:")} ${o.cyan(`zibby workflow new ${a} -t ${t.name}`)}`),console.log("")}}async function B(e,s={}){e||(console.log(o.red(`
|
|
2
2
|
Missing template name.
|
|
3
3
|
`)),console.log(o.gray(" Usage: zibby template add <name>")),console.log(o.gray(` See available templates: zibby template list
|
|
4
4
|
`)),process.exit(1));let t=s.cwd||process.cwd(),a=c(t,".zibby");m(a)||(console.log(o.yellow(`
|
|
@@ -1,4 +1,4 @@
|
|
|
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 I from"ora";import F from"dotenv";import L from"inquirer";var v={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.dev",description:"Production environment"}};function j(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";v[e]?t=v[e].apiUrl:t=v.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)`),v.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),v.prod.apiUrl}}function b(){let t=process.env.ZIBBY_ENV||"prod";return v[t]||v.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/
|
|
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 I from"ora";import F from"dotenv";import L from"inquirer";var v={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.dev",description:"Production environment"}};function j(){let t;if(process.env.ZIBBY_API_URL)t=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";v[e]?t=v[e].apiUrl:t=v.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)`),v.prod.apiUrl):t}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${t}`),v.prod.apiUrl}}function b(){let t=process.env.ZIBBY_ENV||"prod";return v[t]||v.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/workflow-templates/register-nodes.js";F.config();async function J(t){let e=j(),n=I("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
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
|
|
@@ -17,7 +17,7 @@ import{readFileSync as Y,writeFileSync as U,existsSync as k,mkdirSync as x}from"
|
|
|
17
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=I(" Fetching workflow from cloud...").start();try{let c=j(),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
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
|
-
`)),t.includeDefault||process.exit(0),p.start(" Fetching default graph...");let{getDefaultGraph:i}=await import("@zibby/
|
|
20
|
+
`)),t.includeDefault||process.exit(0),p.start(" Fetching default graph...");let{getDefaultGraph:i}=await import("@zibby/workflow-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
21
|
${c.message}
|
|
22
22
|
`)),process.exit(1)}}async function C(t,e,n){let l=process.cwd(),r="workflows";if(!n.output)try{r=(await P(l))?.paths?.workflows||"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
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)}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
var uo=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});import{existsSync as ro,readFileSync as Po,writeFileSync as L,mkdirSync as B,mkdtempSync as Ao,renameSync as _o,rmSync as _}from"fs";import{join as w,dirname as co,resolve as T}from"path";import{tmpdir as Bo}from"os";import a from"chalk";import so from"ora";import io from"inquirer";import{existsSync as Uo,readFileSync as So}from"fs";import{join as Io}from"path";import E from"chalk";import{confirm as xo}from"@inquirer/prompts";import t from"chalk";import C from"ora";import{spawn as mo}from"child_process";var I={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.dev",description:"Production environment"}};function x(){let o;if(process.env.ZIBBY_API_URL)o=process.env.ZIBBY_API_URL;else{let e=process.env.ZIBBY_ENV||"prod";I[e]?o=I[e].apiUrl:o=I.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)`),I.prod.apiUrl):o}catch{return console.error(`\u26A0\uFE0F Invalid API URL: ${o}`),I.prod.apiUrl}}import{existsSync as Y,mkdirSync as fo,readFileSync as po,writeFileSync as go}from"fs";import{homedir as Z}from"os";import{join as A}from"path";function J(){return process.env.ZIBBY_CONFIG_DIR||A(Z(),".zibby")}function G(){return A(J(),"config.json")}var yo=A(Z(),".zibby"),Fo=A(yo,"config.json");function ho(){let o=J();Y(o)||fo(o,{recursive:!0})}function k(){try{let o=G();if(Y(o)){let e=po(o,"utf-8");return JSON.parse(e)}}catch{}return{}}function j(o){ho(),go(G(),JSON.stringify(o,null,2))}function K(){return k().sessionToken||null}function W(o){let e=k();e.sessionToken=o,j(e)}function M(){return k().user||null}function V(o){let e=k();e.user=o,j(e)}function H(o){let e=k();e.proxyUrl=o,j(e)}function q(o){let e=k();e.mem0ProxyUrl=o,j(e)}function X(o){let e=k();e.projects=o,j(e)}import{existsSync as Jo,mkdirSync as Go,readFileSync as Ko,writeFileSync as Wo,unlinkSync as Mo}from"fs";import{resolve as Ho}from"path";import{homedir as Xo}from"os";function wo(o){let e=process.platform;try{let n,r;return e==="darwin"?(n="open",r=[o]):e==="win32"?(n="cmd",r=["/c","start","",o]):(n="xdg-open",r=[o]),mo(n,r,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function vo(){let o=K(),e=M();return o&&e?{loggedIn:!0,user:e,token:o}:{loggedIn:!1}}async function oo(){try{console.log(t.cyan(`
|
|
2
|
+
\u{1F510} Initiating login...
|
|
3
|
+
`));let o=vo();if(o.loggedIn){console.log(t.green("\u2705 Already logged in!")),console.log(t.gray(`User: ${o.user.email}`)),console.log(t.gray(`Name: ${o.user.name}
|
|
4
|
+
`));let{createInterface:e}=await import("readline"),n=e({input:process.stdin,output:process.stdout});return new Promise((r,l)=>{let s=()=>{n.close(),process.stdin.isTTY&&process.stdin.setRawMode(!1)},u=()=>{console.log(t.yellow(`
|
|
5
|
+
|
|
6
|
+
\u26A0\uFE0F Login cancelled
|
|
7
|
+
`)),s(),process.exit(0)};process.on("SIGINT",u),n.question(t.yellow("Continue with this session? (Y/n): "),async f=>{process.removeListener("SIGINT",u),s();try{if(f.toLowerCase()==="n"||f.toLowerCase()==="no"){console.log(t.gray(`Starting new login...
|
|
8
|
+
`));let g=await Q();r(g)}else console.log(t.green(`Using existing session.
|
|
9
|
+
`)),r({success:!0,...o})}catch(g){l(g)}})})}return await Q()}catch(o){return console.error(t.red(`
|
|
10
|
+
\u274C Login failed:`,o.message)),{success:!1,error:o.message}}}async function bo(o){let e=x();try{let n=await fetch(`${e}/projects`,{headers:{Authorization:`Bearer ${o}`}});if(n.ok){let l=((await n.json()).projects||[]).map(s=>({name:s.name,projectId:s.projectId,apiToken:s.apiToken}));return X(l),l}}catch(n){console.log(t.gray(`\u26A0\uFE0F Could not fetch projects: ${n.message}`))}return[]}async function Q(){let o=x(),e=C("Requesting login code...").start(),n=await fetch(`${o}/cli/login/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!n.ok){e.fail("Failed to request login code");let y=await n.json();throw new Error(y.error||"Failed to initiate login")}let{deviceCode:r,userCode:l,verificationUrl:s,expiresIn:u,interval:f}=await n.json();e.succeed("Login code generated"),console.log(""),console.log(t.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")),console.log(t.cyan("\u2551")+t.white.bold(" Complete login in your browser ")+t.cyan("\u2551")),console.log(t.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")),console.log(""),console.log(t.white("Opening browser to login page...")),console.log(t.gray(`Code expires in ${Math.floor(u/60)} minutes`)),console.log(""),await wo(s)||(console.log(t.yellow("\u26A0\uFE0F Could not open browser automatically.")),console.log(t.white("Please open this URL manually: ")+t.blue(s)),console.log(""));let m=C("Waiting for authorization...").start(),v=(f||3)*1e3,d=Math.floor(u/(f||3)),U=0,$=!1,P=()=>{$=!0,m.stop(),console.log(t.yellow(`
|
|
11
|
+
|
|
12
|
+
\u26A0\uFE0F Login cancelled
|
|
13
|
+
`)),process.exit(0)};process.on("SIGINT",P);try{for(;U<d&&!$;){await ko(v),U++;let y=await fetch(`${o}/cli/login/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:r})});if(y.status===202)continue;if(!y.ok){m.fail("Authorization failed");let S=await y.json();throw new Error(S.error||"Authorization failed")}let c=await y.json();if(c.status==="authorized"){m.succeed(t.white("Authorization successful!")),W(c.token),V(c.user),c.proxyUrl&&H(c.proxyUrl),c.mem0ProxyUrl&&q(c.mem0ProxyUrl),console.log(""),console.log(t.gray(`User: ${c.user.email}`));let S=C("Fetching projects...").start(),i=await bo(c.token);return S.succeed(`Fetched ${i.length} project${i.length!==1?"s":""}`),console.log(t.gray(`Session saved to: ~/.zibby/config.json
|
|
14
|
+
`)),{success:!0,loggedIn:!0,user:c.user,token:c.token}}if(c.status==="denied")throw m.fail("Authorization denied"),new Error("User denied authorization")}throw m.fail("Login timeout"),new Error("Login timed out - please try again")}finally{process.removeListener("SIGINT",P)}}function ko(o){return new Promise(e=>setTimeout(e,o))}function eo(){try{let o=process.env.HOME||process.env.USERPROFILE;if(!o)return null;let e=Io(o,".zibby","config.json");return Uo(e)&&JSON.parse(So(e,"utf-8")).sessionToken||null}catch{return null}}function O(){console.log(`
|
|
15
|
+
Not authenticated.`),console.log(` Run ${E.cyan("zibby login")} or set ${E.cyan("ZIBBY_API_KEY")} in your environment.
|
|
16
|
+
`)}async function no(o={}){let e=o.apiKey||process.env.ZIBBY_API_KEY||null,n=eo();if(n||e)return{sessionToken:n,apiKey:e};if(!process.stdin.isTTY){if(o.optional)return{sessionToken:null,apiKey:null};O(),process.exit(1)}console.log(E.yellow(`
|
|
17
|
+
Not logged in.`));let r;try{r=await xo({message:"Open browser to log in now?",default:!0})}catch{r=!1}if(!r){if(o.optional)return{sessionToken:null,apiKey:null};O(),process.exit(1)}if(await oo(),n=eo(),!n){if(o.optional)return{sessionToken:null,apiKey:null};O(),process.exit(1)}return{sessionToken:n,apiKey:null}}import{existsSync as jo}from"fs";import{join as To}from"path";import{pathToFileURL as $o}from"url";async function to(o){let e=To(o,".zibby.config.mjs");if(!jo(e))throw new Error(".zibby.config.mjs not found");try{let n=await import($o(e).href);return n.default||n}catch(n){throw new Error(`Failed to load .zibby.config.mjs: ${n.message}`,{cause:n})}}var No=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function $e(o,e={}){(!o||!No.test(o))&&(console.log(a.red(`
|
|
18
|
+
Invalid workflow UUID.`)),console.log(a.gray(` Got: ${o||"(empty)"}`)),console.log(a.gray(` Get one with: zibby workflow list
|
|
19
|
+
`)),process.exit(1));let{sessionToken:n,apiKey:r}=await no({apiKey:e.apiKey}),l=n||r;l||(console.log(a.red("\n Not authenticated \u2014 run `zibby login` or pass --api-key.\n")),process.exit(1));let s=x(),u=so(`Fetching workflow ${o}...`).start(),f=await fetch(`${s}/workflows/${encodeURIComponent(o)}/sources`,{headers:{Authorization:`Bearer ${l}`}}),g={};try{g=await f.json()}catch{}let m,v;f.ok?(m=g,v="bundle"):f.status===404&&g?.reason==="inline_graph_only"?(m=g,v="inline"):(u.fail(g?.error||g?.message||`HTTP ${f.status}`),process.exit(1));let{workflowType:d,version:U,projectId:$,graph:P}=m;d||(u.fail("Server response missing workflowType \u2014 cannot place the download safely."),process.exit(1)),u.succeed(`${d} v${U} (mode: ${v})`);let y=process.cwd(),c="workflows",S=!1;try{let h=await to(y);h?.paths?.workflows&&(c=h.paths.workflows),S=!0}catch{}let i;if(e.dest)i=T(y,e.dest);else if(S)i=w(y,c,d);else{console.log(a.yellow(`
|
|
20
|
+
This directory has no .zibby.config.mjs \u2014 not a Zibby project.`));let{chosen:h}=await io.prompt([{type:"input",name:"chosen",message:"Where should the workflow be downloaded?",default:`./workflows/${d}`}]);i=T(y,h)}let D=w(i,"workflow.json");if(ro(D)){let h={};try{h=JSON.parse(Po(D,"utf-8"))}catch{}let p=h?.uuid;if(p&&p!==o&&!e.force&&(console.log(a.red(`
|
|
21
|
+
${i} already holds a different workflow.`)),console.log(a.gray(` existing uuid: ${p}`)),console.log(a.gray(` incoming uuid: ${o}`)),console.log(a.gray(` Re-run with --force to overwrite, or pass --dest to pick a different dir.
|
|
22
|
+
`)),process.exit(1)),p===o&&!e.force){let{proceed:z}=await io.prompt([{type:"confirm",name:"proceed",message:`Overwrite local copy of ${d}?`,default:!1}]);z||(console.log(a.gray(`
|
|
23
|
+
Cancelled \u2014 no files touched.
|
|
24
|
+
`)),process.exit(0))}}let N=Ao(w(Bo(),"zibby-download-")),b=w(N,d);B(b,{recursive:!0});let R=so(`Writing ${v==="bundle"?"bundle":"inline graph"} to ${i}...`).start();try{if(v==="bundle"){let p=await fetch(m.downloadUrl);if(!p.ok){let ao=await p.text().catch(()=>"");throw new Error(`Presigned download failed: HTTP ${p.status} ${ao.slice(0,200)}`)}let z=await p.json(),F=Ro(z,b);R.text=`Wrote ${F} file${F===1?"":"s"} to staging`}else L(w(b,"graph.mjs"),zo(P),"utf-8");let h={name:d,uuid:o,version:U,projectId:$,downloadedAt:new Date().toISOString(),...v==="inline"?{source:"inline-graph"}:{}};L(w(b,"workflow.json"),`${JSON.stringify(h,null,2)}
|
|
25
|
+
`,"utf-8"),ro(i)&&_(i,{recursive:!0,force:!0}),B(co(i),{recursive:!0});try{_o(b,i)}catch(p){if(p?.code==="EXDEV")lo(b,i),_(b,{recursive:!0,force:!0});else throw p}_(N,{recursive:!0,force:!0}),R.succeed(`Downloaded ${d} v${U} \u2192 ${i}`)}catch(h){R.fail(h.message);try{_(N,{recursive:!0,force:!0})}catch{}process.exit(1)}console.log(""),console.log(a.gray(` ${a.bold("Edit")}: ${w(i,"graph.mjs")}`)),console.log(a.gray(` ${a.bold("Redeploy")}: zibby workflow deploy ${d}`)),console.log("")}function Ro(o,e){if(!o||typeof o!="object")throw new Error("Source bundle is empty or malformed.");let n=0;for(let[r,l]of Object.entries(o)){let s=T(e,r);if(!s.startsWith(`${T(e)}/`)&&s!==T(e))throw new Error(`Refusing to write file outside destination: ${r}`);B(co(s),{recursive:!0}),L(s,typeof l=="string"?l:JSON.stringify(l,null,2),"utf-8"),n++}return n}function zo(o){return`/**
|
|
26
|
+
* Inline-graph download. The remote workflow was created from a graph
|
|
27
|
+
* blob (e.g. seed / marketplace) and has no S3 source bundle.
|
|
28
|
+
*
|
|
29
|
+
* Edit + redeploy with: zibby workflow deploy <type>
|
|
30
|
+
*/
|
|
31
|
+
import { WorkflowAgent, WorkflowGraph } from '@zibby/core';
|
|
32
|
+
|
|
33
|
+
const GRAPH_BLOB = ${JSON.stringify(o||{},null,2)};
|
|
34
|
+
|
|
35
|
+
export default class extends WorkflowAgent {
|
|
36
|
+
buildGraph() {
|
|
37
|
+
const g = new WorkflowGraph();
|
|
38
|
+
g.fromJSON(GRAPH_BLOB);
|
|
39
|
+
return g;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
`}function lo(o,e){let{readdirSync:n,statSync:r,copyFileSync:l}=uo("fs");B(e,{recursive:!0});for(let s of n(o)){let u=w(o,s),f=w(e,s);r(u).isDirectory()?lo(u,f):l(u,f)}}export{$e as downloadWorkflowCommand};
|