spawn/packages/cli
Ahmed Abushagur f7652de45b
feat(cli): posthog feature flags + fast_provision experiment (#3366)
* feat(cli): posthog feature flags + fast_provision experiment

Wires PostHog `/decide` into the CLI so we can A/B-test provisioning
behaviors. First experiment: `fast_provision` — for users who didn't
pass --beta or --fast manually, the `test` variant turns on
`tarball + images` by default. Hypothesis: faster provisioning →
fewer drop-offs in the "VM ready → install completed" leg of the
funnel.

What's added:

- `shared/install-id.ts` — stable per-machine UUID, persisted at
  ~/.config/spawn/.telemetry-id. Reuses telemetry's existing path
  so existing users keep their PostHog identity. Falls back to an
  ephemeral UUID on disk-write failure.
- `shared/feature-flags.ts` — hand-rolled POST to PostHog /decide
  (no SDK dep). 1.5s timeout, fail-open. On-disk cache at
  $SPAWN_HOME/feature-flags-cache.json with 1h TTL so cold starts
  don't pay the network cost. SPAWN_FEATURE_FLAGS_DISABLED=1 kill
  switch. Captures `$feature_flag_called` exposure events for both
  arms so PostHog can compute conversion.
- `shared/telemetry.ts` — moves user-id loading into install-id.ts
  so flags and events share the same `distinct_id`.
- `index.ts` — `await initFeatureFlags()` at the top of `main()`,
  then applies `fast_provision`'s `test` variant by appending
  `tarball,images` to SPAWN_BETA — but only if the user didn't
  pass --beta or --fast (those always win, so opt-out is free).

Why tarball+images and not all four (`+parallel,docker`):
clean attribution. The hypothesis is about tarball/image; if we
ship the full --fast bundle we can't tell which feature moved the
metric. Keep --fast as the user-facing power-user knob.

Tests: 14 new (install-id roundtrip + format guard, feature-flags
fetch/timeout/HTTP500/malformed/disabled/idempotent/stale-cache,
exposure-event behavior). Full suite: 2183 pass, same 4 pre-existing
failures as upstream/main.

Bumps CLI to 1.0.23.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(cli): skip feature-flag fetch in pick/feedback fast path; implement real SWR

Two review-fix commits from PR feedback squashed into one:

1. Move `await initFeatureFlags()` below the `spawn pick` and
   `spawn feedback` bypass clauses in `main()`. Both commands are called
   from bash scripts and must stay fast; neither gates on a flag, so
   there's no reason to pay up to 1.5s of network latency on cold cache.

2. Implement real stale-while-revalidate in `shared/feature-flags.ts`.
   The prior implementation did a synchronous fetch on stale cache,
   which contradicted the docstring and PR description. Now:
     - fresh cache (<TTL)  → use cache, no network
     - stale cache (>=TTL) → use cache immediately, refresh in background
     - no cache            → await sync fetch (first run only)

   Adds `_awaitBackgroundRefreshForTest()` so tests can deterministically
   wait for the background refresh before asserting. Updated the existing
   "stale cache" test to verify SWR semantics (stale served first, fresh
   lands next invocation) and added a "fresh cache does not fetch" test.

All 2127 tests pass; biome clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Claude <claude@anthropic.com>
2026-04-27 17:50:56 -07:00
..
src feat(cli): posthog feature flags + fast_provision experiment (#3366) 2026-04-27 17:50:56 -07:00
.gitignore Remove Daytona cloud provider from codebase (#2261) 2026-03-06 18:53:08 -05:00
build-clouds.ts fix: navigate back to list after delete/remove errors (#2488) 2026-03-11 00:04:51 -07:00
bun.lock feat: Bun workspace monorepo — packages/cli + packages/shared (#1853) 2026-02-23 22:07:05 -08:00
bunfig.toml feat(digitalocean): guided readiness before deploy (#3336) 2026-04-21 21:55:01 -07:00
package-lock.json feat: Bun workspace monorepo — packages/cli + packages/shared (#1853) 2026-02-23 22:07:05 -08:00
package.json feat(cli): posthog feature flags + fast_provision experiment (#3366) 2026-04-27 17:50:56 -07:00
README.md refactor: Remove dead code and stale references (#2278) 2026-03-07 03:56:13 -05:00
tsconfig.json feat: Bun workspace monorepo — packages/cli + packages/shared (#1853) 2026-02-23 22:07:05 -08:00

Spawn CLI

The spawn CLI is a command-line tool for launching AI coding agents on cloud providers, pre-configured with OpenRouter.

Overview

The spawn CLI provides a unified interface to:

  • Launch any supported AI agent (Claude Code, Codex, etc.) on any supported cloud provider
  • Interactively browse available agents and clouds
  • View the agent × cloud compatibility matrix
  • Self-update to the latest version

Architecture

Installation Strategy

The installer uses bun to build the TypeScript CLI into a standalone JavaScript file. If bun is not already installed, the installer auto-installs it first (~5 seconds).

Why bun?

  • Fast: Native TypeScript runtime, instant builds
  • Universal: Auto-installed if missing, works on any system with bash and curl
  • Zero friction: No prerequisite installation required
  • Single implementation: One codebase, always feature-complete

Directory Structure

cli/
├── src/
│   ├── index.ts        # Entry point (routes commands to handlers)
│   ├── commands/       # Per-command modules (interactive, list, run, etc.)
│   │   └── index.ts    # Barrel re-export
│   ├── manifest.ts     # Manifest fetching and caching logic
│   ├── update-check.ts # Auto-update check (once per day)
│   └── __tests__/      # Test suite (Bun test runner)
├── ../sh/cli/install.sh # Installer (auto-installs bun if needed, lives in sh/cli/)
├── package.json        # Package metadata and dependencies
└── tsconfig.json       # TypeScript configuration

TypeScript Implementation

The TypeScript CLI (src/*.ts) provides:

  • Interactive mode: Terminal UI with prompts for selecting agents and clouds
  • Manifest caching: Local cache with TTL to minimize network requests
  • Auto-update check: Non-intrusive daily version check with notifications
  • Progress indicators: Spinners and colored output for better UX
  • Error handling: Structured error messages and exit codes

Key dependencies:

  • @clack/prompts — Interactive terminal prompts
  • picocolors — Terminal color support

Installation

Quick Install

curl -fsSL https://raw.githubusercontent.com/OpenRouterTeam/spawn/main/sh/cli/install.sh | bash

The installer will:

  1. Install bun if not already present
  2. Clone the CLI source
  3. Build and install the spawn binary to ~/.local/bin

Environment Variables

  • SPAWN_INSTALL_DIR — Override install directory (default: $HOME/.local/bin)

Manual Installation (Development)

cd cli
bun install
bun link

Or build a standalone binary:

bun run compile  # Creates ./spawn executable

Usage

Interactive Mode

spawn

Launches an interactive picker to select an agent and cloud provider.

Direct Launch

spawn <agent> <cloud>

Examples:

spawn claude sprite    # Launch Claude Code on Sprite
spawn codex hetzner    # Launch Codex CLI on Hetzner Cloud

Agent Information

spawn <agent>

Show which cloud providers support the specified agent.

Example:

spawn claude
# Output:
# Claude Code — AI coding agent from Anthropic
#
# Available clouds:
#   Sprite          spawn claude sprite
#   Hetzner Cloud   spawn claude hetzner

List All Combinations

spawn list

Display the full agent × cloud compatibility matrix.

List Agents

spawn agents

Show all available agents with descriptions.

List Cloud Providers

spawn clouds

Show all available cloud providers with descriptions.

Update CLI

spawn update

Displays update instructions (re-run installer).

Auto-update check: The CLI automatically checks for updates once per day and displays a notification if a newer version is available. To disable this, set SPAWN_NO_UPDATE_CHECK=1.

Version

spawn version

Display the current CLI version.

Development

Prerequisites

  • Bun 1.0+

Running Locally

bun run dev             # Run TypeScript CLI directly
bun run build           # Build to cli.js
bun run compile         # Compile to standalone binary

Testing

bun run dev list
bun run dev agents
bun run dev claude sprite

Code Organization

src/index.ts

  • Command-line argument parsing
  • Routes to appropriate command handler
  • Minimal logic (just dispatching)

src/commands/

  • Per-command modules: interactive.ts, list.ts, run.ts, delete.ts, update.ts, etc.
  • shared.ts — helpers, entity resolution, fuzzy matching, credential hints
  • index.ts — barrel re-export for backward compatibility with existing imports

src/manifest.ts

  • Manifest fetching from GitHub
  • Local caching with TTL
  • Offline fallback to stale cache
  • Typed manifest structure

src/version.ts

  • Single source of truth for version number

Adding a New Command

  1. Add a new file src/commands/mycommand.ts:

    export async function cmdMyCommand() {
      const manifest = await loadManifest();
      // ... implementation
    }
    
  2. Re-export from src/commands/index.ts:

    export { cmdMyCommand } from "./mycommand.js";
    
  3. Add routing in src/index.ts:

    case "mycommand":
      await cmdMyCommand();
      break;
    
  4. Update help text in src/commands/help.tscmdHelp()

Design Rationale

Why TypeScript?

  • Type safety: Manifest structure is type-checked at compile time
  • Modern async/await: Clean, readable asynchronous code
  • Rich ecosystem: Access to high-quality CLI libraries (@clack/prompts, etc.)
  • Single codebase: Same code runs on bun, node, or as a compiled binary

Why Auto-install Bun?

  • Single implementation: No need to maintain a separate bash CLI
  • Feature parity: Every user gets the full TypeScript CLI with all features
  • Fast install: Bun installs in ~5 seconds via curl -fsSL https://bun.sh/install | bash
  • Simple maintenance: One codebase, one source of truth

Manifest Caching

The CLI caches the manifest locally to reduce network requests:

  • Cache location: $XDG_CACHE_HOME/spawn/manifest.json (or ~/.cache/spawn/manifest.json)
  • TTL: 1 hour (3600 seconds)
  • Offline fallback: If fetch fails, uses stale cache if available
  • Invalidation: spawn update clears the cache

Script Execution Flow

When you run spawn <agent> <cloud>:

  1. Load manifest: Fetch from GitHub or use cached version
  2. Validate combination: Check that matrix["<cloud>/<agent>"] is "implemented"
  3. Download script: Fetch https://openrouter.ai/labs/spawn/<cloud>/<agent>.sh
    • Fallback to GitHub raw URL if OpenRouter CDN fails
  4. Execute: Pipe script to bash -c with inherited stdio
  5. Interactive handoff: User interacts directly with the spawned agent

Contributing

Before Submitting Changes

  1. Test the CLI:

    bun run dev --help
    
  2. Ensure version numbers are synchronized:

    • src/version.tsVERSION
    • package.jsonversion
  3. Update this README if you add new commands or change behavior

  4. Run the installer locally to verify it works:

    bash install.sh
    

Release Checklist

  1. Bump version in both locations (see above)
  2. Update CHANGELOG (if exists)
  3. Test installer on clean system
  4. Tag release: git tag -a cli-vX.Y.Z -m "Release vX.Y.Z"
  5. Push tag: git push --tags

License

See repository root for license information.