arcade-mcp/libs/arcade-cli/arcade_cli/new.py
Eric Gustin 113d0d3086
CLI Usage (#593)
TLDR; 

The philosophy of CLI usage is "fire and forget" and "best effort". You
can opt out by setting `ARCADE_USAGE_TRACKING=0`.

We are capturing two events: `CLI execution succeeded` and `CLI
execution failed`. Reporting to PostHog is a short lived (maximum 10
seconds) subprocess that does not block the main CLI execution process.

`~/.arcade/usage.json` persists two values `anon_id` and
`linked_principal_id`. The logged in status of the CLI user determines
which ID is used. Upon `arcade login`, the `anon_id` is aliased with
`linked_principal_id`. Upon `arcade logout` the `linked_principal_id` is
removed and the `anon_id` is rotated.

## CLI Usage Tracking - How It Works

The usage tracking system implements an identity management and event
tracking pipeline. Here's how the pieces work together:

### **Identity State Management (`usage.json`)**

The system maintains a persistent identity file at
`~/.arcade/usage.json` with this structure:
```json
{
  "anon_id": "uuid",
  "linked_principal_id": "uuid" | null
}
```

**Key mechanics:**
- **`anon_id`**: Generated once on first CLI use and persists across
sessions. This UUID tracks all anonymous activity.
- **`linked_principal_id`**: Initially `null`. Once the user logs in and
we successfully alias their identity, this field stores their
`principal_id` to indicate this `anon_id` has been linked.
- **Atomic writes**: All updates use a temp file + atomic rename pattern
to prevent corruption from concurrent CLI processes
- **File locking**: Uses `fcntl` (Unix) to coordinate reads/writes
across multiple simultaneous CLI invocations
- **In-memory cache**: The `UsageIdentity` class caches the loaded data
to avoid repeated file I/O within a single CLI invocation

### **Identity Resolution Flow**

When tracking an event, the system determines the `distinct_id` (who to
attribute the event to) via this waterfall:

1. **Check `linked_principal_id`** in `usage.json`
   - If present → use it (user was previously aliased)
   - This is the fastest path and avoids API calls

2. **Fetch `principal_id` from Arcade Cloud API**
- Makes HTTP request to `/api/v1/auth/validate` with the user's API key
from `~/.arcade/credentials.yaml`
   - If authenticated → returns `principal_id`
   - Has 2s timeout for responsiveness

3. **Fall back to `anon_id`**
   - If not authenticated or API call fails → use anonymous ID
   - Marks event with `is_anon=True` flag

### **The Aliasing Lifecycle**

PostHog aliasing links anonymous activity to authenticated users. Here's
the state machine:

#### **Stage 1: Anonymous User**
```
usage.json: { "anon_id": "abc-123", "linked_principal_id": null }
All events → sent with distinct_id="abc-123" and is_anon=True
```

#### **Stage 2: Login Event**
1. User runs `arcade login`
2. Command completes successfully (auth token saved)
3. `CommandTracker` detects successful login
4. Fetches `principal_id` from API
5. Checks `should_alias()` → returns `True` because
`linked_principal_id` is `null`
6. **Calls `alias()` synchronously** (blocking):
   ```python
   posthog.alias(previous_id="abc-123", distinct_id="zyx-321")
   ```
7. Updates `usage.json`:
   ```json
   { "anon_id": "abc-123", "linked_principal_id": "zyx-321" }
   ```
8. PostHog backend merges all events with `distinct_id="abc-123"` into
the user profile for `"zyx-321"`

#### **Stage 3: Authenticated User**
```
usage.json: { "anon_id": "abc-123", "linked_principal_id": "zyx-321" }
All events → sent with distinct_id="zyx-321" and is_anon=False
```
- Events are directly attributed to the authenticated user
- No more API calls needed (uses cached `linked_principal_id`)

#### **Stage 4: Logout Event**
1. User runs `arcade logout`
2. Logout event is sent with the authenticated `distinct_id`
3. `CommandTracker` detects successful logout
4. **Rotates identity** by calling `reset_to_anonymous()`:
   ```json
   { "anon_id": "xyz-789", "linked_principal_id": null }
   ```
5. New `anon_id` prevents cross-contamination if another user logs in

### **Critical Constraint: Alias Timing**

PostHog requires that `alias()` is called **BEFORE** any events are sent
with the new `distinct_id`. This is why:
- **`alias()` is synchronous (blocking)**: Guarantees it completes
before the login success event is sent
- **Subsequent events use `linked_principal_id`**: Once aliased, all
future events use the authenticated ID
- **Lazy aliasing**: If a user authenticates via another mechanism (not
through `arcade login`), the system detects this on the next command and
performs aliasing before sending that command's event

### **Event Capture Pipeline**

When `CommandTracker.track_command_execution()` is called:

1. **Resolve identity** → determines `distinct_id` and `is_anon` flag
2. **Build event properties**:
   ```python
   {
     "command_name": "toolkit.run",
     "cli_version": "1.2.3",
     "python_version": "3.11.0",
     "os_type": "Darwin",
     "os_release": "23.4.0",
     "duration": 1250.42,  # milliseconds
     "error_message": "..."  # if failed
   }
   ```
3. **Call `UsageService.capture()`**:
   - Serializes event data to JSON
   - Spawns detached subprocess: `python -m arcade_cli.usage`
   - Passes data via `ARCADE_USAGE_EVENT_DATA` env var
   - **Returns immediately** (non-blocking)

4. **Detached subprocess (`__main__.py`)**:
   - Runs independently, survives parent CLI exit
   - Deserializes event data
- If `is_anon=True`, sets `$process_person_profile=False` (tells PostHog
not to create a full profile)
   - Sends event to PostHog with 5s timeout
   - Exits (hard exit after 10s max via timeout thread)

### **Concurrency Handling**

Multiple CLI processes can run simultaneously. The system handles this
via:
- **File locking** on `usage.json` (shared lock for reads, exclusive for
writes)
- **Atomic writes** via temp files ensure incomplete writes never
corrupt the file
- **Idempotent aliasing**: `should_alias()` prevents redundant alias
calls

### **Edge Cases Handled**

1. **Side-channel authentication**: User authenticates outside of
`arcade login` (e.g., manually editing credentials)
   - Detected via "lazy aliasing" check on every command
- Performs alias if `linked_principal_id` doesn't match current
`principal_id`

2. **API failures during identity fetch**: Falls back to anonymous
tracking
   - 2s timeout prevents hanging
   - Silent failure doesn't disrupt CLI

3. **PostHog merge restrictions**: Can't alias returning users who
already have a profile
- System stores `linked_principal_id` to avoid retrying impossible
aliases
   - New users (never logged in before) get full history stitched

4. **Multiple accounts on same machine**: Logout rotates `anon_id`
   - User A's anonymous activity won't leak into User B's profile

### **Privacy & Performance**

- **Opt-out**: `ARCADE_USAGE_TRACKING=0` disables all tracking
- **Non-blocking**: Events never slow down CLI (detached subprocess)
- **Anonymous profiles**: `$process_person_profile=False` for `anon_id`
events minimizes data collection
- **Silent failures**: Network issues or PostHog errors never surface to
users
2025-10-03 10:15:08 -07:00

279 lines
9.6 KiB
Python

import re
import shutil
from datetime import datetime
from importlib.metadata import version as get_version
from pathlib import Path
from typing import Optional
import typer
from jinja2 import Environment, FileSystemLoader, select_autoescape
from rich.console import Console
from arcade_cli.templates import get_full_template_directory, get_minimal_template_directory
console = Console()
# Retrieve the installed version of arcade-mcp
try:
ARCADE_MCP_MIN_VERSION = get_version("arcade-mcp")
ARCADE_MCP_MAX_VERSION = str(int(ARCADE_MCP_MIN_VERSION.split(".")[0]) + 1) + ".0.0"
except Exception as e:
console.print(f"[red]Failed to get arcade-mcp version: {e}[/red]")
ARCADE_MCP_MIN_VERSION = "1.0.0rc2" # Default version if unable to fetch
ARCADE_MCP_MAX_VERSION = "4.0.0"
ARCADE_TDK_MIN_VERSION = "2.6.0rc2"
ARCADE_TDK_MAX_VERSION = "3.0.0"
ARCADE_SERVE_MIN_VERSION = "2.2.0rc2"
ARCADE_SERVE_MAX_VERSION = "3.0.0"
ARCADE_MCP_SERVER_MIN_VERSION = "1.0.0rc2"
ARCADE_MCP_SERVER_MAX_VERSION = "3.0.0"
def ask_question(question: str, default: Optional[str] = None) -> str:
"""
Ask a question via input() and return the answer.
"""
answer = typer.prompt(question, default=default, show_default=False)
if not answer and default:
return default
return str(answer)
def ask_yes_no_question(question: str, default: bool = True) -> bool:
"""
Ask a yes/no question via input() and return the bool answer.
"""
default_str = "Y/n" if default else "y/N"
answer = typer.prompt(
f"{question} ({default_str})", default="y" if default else "n", show_default=False
)
return answer.lower() in [
"y",
"y/",
"yes",
"true",
"1",
"ye",
"yes",
"yeah",
"yep",
"sure",
"ok",
"yup",
]
def render_template(env: Environment, template_string: str, context: dict) -> str:
"""Render a template string with the given variables."""
template = env.from_string(template_string)
return template.render(context)
def write_template(path: Path, content: str) -> None:
"""Write content to a file."""
path.write_text(content, encoding="utf-8")
def create_ignore_pattern(
include_evals: bool, is_community_or_official_toolkit: bool
) -> re.Pattern[str]:
"""Create an ignore pattern based on user preferences."""
patterns = [
"__pycache__",
r"\.DS_Store",
r"Thumbs\.db",
r"\.git",
r"\.svn",
r"\.hg",
r"\.vscode",
r"\.idea",
"build",
"dist",
r".*\.egg-info",
r".*\.pyc",
r".*\.pyo",
]
if not include_evals:
patterns.append("evals")
if not is_community_or_official_toolkit:
patterns.extend([".ruff.toml", ".pre-commit-config.yaml", "LICENSE"])
else:
patterns.extend(["README.md"])
return re.compile(f"({'|'.join(patterns)})$")
def create_package(
env: Environment,
template_path: Path,
output_path: Path,
context: dict,
ignore_pattern: re.Pattern[str],
) -> None:
"""Recursively create a new toolkit directory structure from jinja2 templates."""
if ignore_pattern.match(template_path.name):
return
try:
if template_path.is_dir():
folder_name = render_template(env, template_path.name, context)
new_dir_path = output_path / folder_name
new_dir_path.mkdir(parents=True, exist_ok=True)
for item in template_path.iterdir():
create_package(env, item, new_dir_path, context, ignore_pattern)
else:
# Render the file name
file_name = render_template(env, template_path.name, context)
with open(template_path, encoding="utf-8") as f:
content = f.read()
# Render the file content
content = render_template(env, content, context)
write_template(output_path / file_name, content)
except Exception as e:
console.print(f"[red]Failed to create package: {e}[/red]")
raise
def remove_toolkit(toolkit_directory: Path, toolkit_name: str) -> None:
"""Teardown logic for when creating a new toolkit fails."""
toolkit_path = toolkit_directory / toolkit_name
if toolkit_path.exists():
shutil.rmtree(toolkit_path)
def create_new_toolkit(output_directory: str, toolkit_name: str) -> None:
"""Create a new toolkit from a template with user input."""
toolkit_directory = Path(output_directory)
# Check for illegal characters in the toolkit name
if re.match(r"^[a-z0-9_]+$", toolkit_name):
if (toolkit_directory / toolkit_name).exists():
console.print(f"[red]Toolkit '{toolkit_name}' already exists.[/red]")
exit(1)
else:
console.print(
"[red]Toolkit name contains illegal characters. "
"Only lowercase alphanumeric characters and underscores are allowed. "
"Please try again.[/red]"
)
exit(1)
toolkit_description = ask_question("Describe what your toolkit will do (optional)", default="")
toolkit_author_name = ask_question("Your GitHub username (optional)", default="")
while True:
toolkit_author_email = ask_question("Your email (optional)", default="")
if toolkit_author_email == "" or re.match(r"[^@ ]+@[^@ ]+\.[^@ ]+", toolkit_author_email):
break
console.print(
"[red]Invalid email format. Please enter a valid email address or leave it empty.[/red]"
)
include_evals = ask_yes_no_question(
"Do you want an evals directory created for you?", default=True
)
cwd = Path.cwd()
# TODO: this detection mechanism works only for people that didn't change the
# name of the repo, a better detection method is required here
is_community_toolkit = False
if cwd.name == "toolkits" and cwd.parent.name == "arcade-mcp":
prompt = (
"Is your toolkit a community contribution (to be merged into "
"\x1b]8;;https://github.com/ArcadeAI/arcade-mcp\x1b\\ArcadeAI/arcade-mcp\x1b]8;;\x1b\\ repo)?"
)
is_community_toolkit = ask_yes_no_question(prompt, default=True)
is_official_toolkit = cwd.name == "toolkits" and cwd.parent.name == "tools"
context = {
"package_name": "arcade_" + toolkit_name if is_community_toolkit else toolkit_name,
"toolkit_name": toolkit_name,
"toolkit_description": toolkit_description,
"toolkit_author_name": toolkit_author_name,
"toolkit_author_email": toolkit_author_email,
"arcade_tdk_min_version": ARCADE_TDK_MIN_VERSION,
"arcade_tdk_max_version": ARCADE_TDK_MAX_VERSION,
"arcade_serve_min_version": ARCADE_SERVE_MIN_VERSION,
"arcade_serve_max_version": ARCADE_SERVE_MAX_VERSION,
"arcade_mcp_min_version": ARCADE_MCP_MIN_VERSION,
"arcade_mcp_max_version": ARCADE_MCP_MAX_VERSION,
"creation_year": datetime.now().year,
"is_community_toolkit": is_community_toolkit,
"is_official_toolkit": is_official_toolkit,
}
template_directory = get_full_template_directory() / "{{ toolkit_name }}"
env = Environment(
loader=FileSystemLoader(str(template_directory)),
autoescape=select_autoescape(["html", "xml"]),
)
# Create dynamic ignore pattern based on user preferences
ignore_pattern = create_ignore_pattern(
include_evals, is_community_toolkit or is_official_toolkit
)
try:
create_package(env, template_directory, toolkit_directory, context, ignore_pattern)
console.print(
f"[green]Toolkit '{toolkit_name}' created successfully at '{toolkit_directory}'.[/green]"
)
create_deployment(toolkit_directory, toolkit_name)
except Exception:
remove_toolkit(toolkit_directory, toolkit_name)
raise
def create_deployment(toolkit_directory: Path, toolkit_name: str) -> None:
# No longer create worker.toml for MCP servers
# The server.py file handles all configuration
pass
def create_new_toolkit_minimal(output_directory: str, toolkit_name: str) -> None:
"""Create a new toolkit from a template with user input."""
toolkit_directory = Path(output_directory)
# Check for illegal characters in the toolkit name
if re.match(r"^[a-z0-9_]+$", toolkit_name):
if (toolkit_directory / toolkit_name).exists():
raise FileExistsError(
f"Server with name '{toolkit_name}' already exists at '{toolkit_directory / toolkit_name}'"
)
else:
raise ValueError(
f"Server name '{toolkit_name}' contains illegal characters. "
"Only lowercase alphanumeric characters and underscores are allowed. "
"Please try again."
)
context = {
"toolkit_name": toolkit_name,
"arcade_mcp_min_version": ARCADE_MCP_MIN_VERSION,
"arcade_mcp_max_version": ARCADE_MCP_MAX_VERSION,
"arcade_mcp_server_min_version": ARCADE_MCP_SERVER_MIN_VERSION,
"arcade_mcp_server_max_version": ARCADE_MCP_SERVER_MAX_VERSION,
}
template_directory = get_minimal_template_directory() / "{{ toolkit_name }}"
env = Environment(
loader=FileSystemLoader(str(template_directory)),
autoescape=select_autoescape(["html", "xml"]),
)
ignore_pattern = create_ignore_pattern(False, False)
try:
create_package(env, template_directory, toolkit_directory, context, ignore_pattern)
console.print(
f"[green]Toolkit '{toolkit_name}' created successfully at '{toolkit_directory}'.[/green]"
)
except Exception:
remove_toolkit(toolkit_directory, toolkit_name)
raise