Commands Reference

Commands Reference

Commands are the core building blocks of Intelligence Packs. This reference covers everything you need to know about creating commands.

The @command Decorator

The @command decorator is the primary way to define commands:

from huitzo_sdk import command, Context
from pydantic import BaseModel

class MyArgs(BaseModel):
    param1: str
    param2: int = 10

@command("my-command", namespace="my-pack")
async def my_command(args: MyArgs, ctx: Context) -> dict:
    """Command description shown in help."""
    return {"result": args.param1 * args.param2}

Decorator Parameters

Parameter Type Default Description
name str Required Command name (lowercase, hyphens allowed)
namespace str Required Pack namespace (typically pack-name)
version str "1.0.0" Command version (semver)
timeout int 60 Max execution time in seconds. Must not exceed the resolved queue's ceiling (fast 570, medium 1170, long 32370); publish refuses a larger value, so set queue="long" for anything over 1170 s
retries int 3 Number of retry attempts
retry_backoff float 1.0 Exponential backoff base (seconds)
retry_max_wait int 60 Maximum wait between retries (seconds)
queue str "medium" Task queue: "fast", "medium", "long". Each queue caps timeout (see above)
output_format str "auto" Output format: "json", "text", "auto"
description str From docstring Override command description; see Command description
streaming bool False Async-generator stage of the piping protocol; runs in an isolated child like every pack call

Queue and money refusals: queue defaults to "medium". A medium or long command returns 202 and reserves credits in the worker, so an INSUFFICIENT_CREDITS (402) or ledger-unavailable (503) refusal shows only in task polling and the worker log. Only a fast command returns the refusal inline (Insufficient Credits Error).

How the platform learns a command's metadata

The platform never imports your pack in its own processes. When a build is first registered (its first call on a replica, the publish-time reload notification, or a start-up), the platform imports it once in an isolated child, records what each @command declares -- any value of the declared type works, computed or imported -- and registers your commands from that record from then on (how registration works). Your code runs only inside isolated children: there, in publish's extraction child, and when a command is called. A wheel whose entry point does not load as a command is refused at publish (a load violation, 400 command_contract_violation). An entry point the registration child cannot describe is not registered, is logged, and is shown to platform staff.

A pipeline joiner's input is shaped by its args model: a field annotated list[...] gets every chunk of that branch; any other field gets the last chunk.

A command with timeout=0 (no limit of its own) is bounded by its caller: the pipeline's timeout, or the calling command's remaining budget for a ctx.commands call.

Retry Behavior: On failure, the SDK waits retry_backoff * (2 ^ attempt) seconds before retrying, capped at retry_max_wait. See Error Handling for details.

Example: Full Configuration

@command(
    "analyze-data",
    namespace="analytics",
    version="2.1.0",
    timeout=3600,           # 1 hour max
    retries=5,              # 5 retry attempts
    queue="long",           # Long-running queue
    output_format="json",   # Always JSON output
    description="Analyze large datasets with ML models"
)
async def analyze_data(args: AnalyzeArgs, ctx: Context) -> AnalysisResult:
    ...

Timeout Hierarchy

Huitzo uses a three-tier timeout system to ensure commands complete within reasonable bounds while giving flexibility at different levels:

Command Timeout ≤ Pack Timeout ≤ Platform Global Timeout

Timeout Levels

Level Defined By Default Description
Command @command decorator 60s Max time for this specific command
Pack huitzo.yaml manifest 3600s Must be ≥ max command timeout in pack
Platform Admin configuration 28800s (8h) Hard limit set by Huitzo (SaaS) or self-hosted admin

How Timeouts Apply

  1. Command-level timeout is specified in the @command decorator
  2. Pack-level timeout in huitzo.yaml must be ≥ the maximum of all command timeouts
  3. Platform timeout is the hard ceiling - commands cannot exceed this regardless of other settings

Example Configuration

# Command timeout: 300 seconds
@command("analyze", namespace="analytics", timeout=300)
async def analyze(args: Args, ctx: Context):
    ...
# huitzo.yaml - Pack timeout must be >= 300 (the max command timeout)
pack:
  name: "analytics"
  timeout: 600  # Pack-level ceiling
# Platform timeout (environment variable for self-hosted)
HUITZO_GLOBAL_TIMEOUT=28800  # 8 hours max

Validation Rules

  • Pack build fails if any command timeout exceeds the pack timeout
  • Command rejected at runtime if pack timeout exceeds platform global timeout
  • Self-hosted admins can configure their platform global timeout via environment variables

Input Arguments (Pydantic Models)

The platform derives each command's published JSON Schema from this model — see Command Input Schema.

All command inputs must be Pydantic models:

from pydantic import BaseModel, Field, field_validator
from typing import Optional, List
from datetime import date

class ReportArgs(BaseModel):
    """Arguments for report generation."""

    # Required field
    report_type: str = Field(description="Type of report to generate")

    # Optional with default
    start_date: Optional[date] = Field(
        default=None, 
        description="Start date for report"
    )

    # List field
    departments: List[str] = Field(
        default_factory=list,
        description="Filter by departments"
    )

    # Field with constraints
    max_rows: int = Field(
        default=1000,
        ge=1,
        le=100000,
        description="Maximum rows to include"
    )

    # Custom validation
    @field_validator("report_type")
    @classmethod
    def validate_report_type(cls, v: str) -> str:
        valid_types = ["sales", "inventory", "financial"]
        if v not in valid_types:
            raise ValueError(f"Must be one of: {valid_types}")
        return v

Return Types

Security Constraint: Command return values are serialized to JSON and stored as plaintext in the platform database (result_summary column, truncated to 1024 bytes). Commands MUST NOT return sensitive data in their result dict. Prohibited return values include API keys, credentials, full document bodies, LLM response text, and PII. Return only metadata, identifiers, counts, and safe status values. Violating this constraint exposes user data on any database compromise (see Security Architecture).

Commands can return various types:

Dictionary (most common)

@command("get-stats", namespace="analytics")
async def get_stats(args: Args, ctx: Context) -> dict:
    return {
        "total": 1000,
        "average": 45.5,
        "trend": "up"
    }

Pydantic Model

class StatsResult(BaseModel):
    total: int
    average: float
    trend: str

@command("get-stats", namespace="analytics")
async def get_stats(args: Args, ctx: Context) -> StatsResult:
    return StatsResult(total=1000, average=45.5, trend="up")

String

@command("greet", namespace="example")
async def greet(args: Args, ctx: Context) -> str:
    return f"Hello, {args.name}!"

None (side effects only)

@command("send-notification", namespace="alerts")
async def send_notification(args: Args, ctx: Context) -> None:
    await ctx.email.send(args.recipient, args.message)
    # No return value

Sync vs Async Commands

Use for I/O-bound operations:

@command("fetch-data", namespace="api")
async def fetch_data(args: Args, ctx: Context) -> dict:
    # Async HTTP call
    response = await ctx.http.get(args.url)

    # Async storage
    await ctx.storage.save("cached-data", response)

    return response

Sync

Use for CPU-bound operations:

@command("compute-hash", namespace="crypto")
def compute_hash(args: Args, ctx: Context) -> str:
    # CPU-intensive operation
    return hashlib.sha256(args.data.encode()).hexdigest()

Long-Running Commands

The @command decorator is the only way to define a command. Long-running work is expressed with the decorator's own knobs — timeout, retries, and queue — plus ordinary async iteration inside the function body:

# pseudocode — long-running import as a single @command callable
@command("import", namespace="data", timeout=7200, retries=3, queue="long")
async def import_data(args: ImportArgs, ctx: Context) -> dict:
    total_rows = 0
    async for batch in fetch_batches(args.source):  # pseudocode helper
        await process_batch(batch)                  # pseudocode helper
        total_rows += len(batch)
    return {"rows_imported": total_rows}

Progress reporting is a planned future addition on ctx (e.g. ctx.progress(percent, message)) — an additive ctx feature, not a separate command type. There is no class-based command model and no lifecycle-hook surface (on_start / on_complete / on_error / on_retry / on_progress); see ADR-004.

Error Handling

Built-in Exceptions

from huitzo_sdk.errors import (
    CommandError,      # General command failure
    ValidationError,   # Input validation failed
    IntegrationError,  # External service failed
    RateLimitError,    # Rate limited
)

@command("example", namespace="demo")
async def example(args: Args, ctx: Context) -> dict:
    # Validation error
    if args.count < 0:
        raise ValidationError(
            field="count",
            value=args.count,
            message="Count must be non-negative"
        )

    # Integration error
    try:
        result = await external_api.call()
    except APIError as e:
        raise IntegrationError(
            service="external-api",
            status_code=e.status,
            message=str(e)
        )

    return result

Custom Exit Codes

@command("check-status", namespace="health")
async def check_status(args: Args, ctx: Context) -> dict:
    status = await check_system()

    if status == "critical":
        raise CommandError(
            message="System is in critical state",
            exit_code=2  # Custom exit code
        )

    return {"status": status}

Command Metadata

Access command metadata at runtime:

@command("self-aware", namespace="meta")
async def self_aware(args: Args, ctx: Context) -> dict:
    return {
        "command_name": ctx.command_name,
        "namespace": ctx.namespace,
        "version": ctx.command_version,
        "correlation_id": ctx.correlation_id,
        "user_id": str(ctx.user_id),
        "tenant_id": str(ctx.tenant_id),
    }

Entry Points

You never register a command by hand. huitzo pack build reads the @command decorators in your package and writes one huitzo.commands entry point per command into the wheel's metadata, keyed by the full @scope/pack/command namespace:

# conceptual — the generated wheel metadata, not something you author

[huitzo.commands]
@acme/pallet-planner/plan-pallet = pallet_planner.commands:plan_pallet
@acme/pallet-planner/list-skus   = pallet_planner.commands:list_skus

The entry-point name is the namespace the platform routes on. huitzo pack build derives it from your pack's scope and name, so in normal use it always matches — but the name lives in the wheel, and the platform treats it as a claim to be checked rather than a fact. packs.scope/packs.name (unique per pack) is the authority.

Every entry point in the group must load as a @command-decorated callable. Publish refuses a wheel with one that does not, whether its import fails or it names a plain function the decorator never wrapped, and a wheel that does not export every command its manifest declares (fields load and missing of the Command Runtime Contract). Publish imports the pack only in its isolated extraction child, never in the API process. A command the platform's isolated introspection cannot describe is not registered and is shown to staff, see How the platform learns a command's metadata.

Every registration path checks the prefix: the start-up bulk load, the publish-time huitzo.reload_pack_commands notification, activation and a replica's miss path all register only the entry points under the pack's own @scope/pack/ prefix and log the rest.

Command Input Schema

Every published command carries a JSON Schema describing its arguments. The platform derives it — you never declare it in huitzo.yaml, and CommandSpec rejects unknown keys, so there is no manifest field to set.

Where it comes from

The @command decorator resolves your command's first parameter. When that parameter is annotated with a Pydantic model, the decorator records the model on the function object alongside the rest of the command metadata. At publish time the extraction step — which already runs inside the pack's own isolated venv to read entry points — asks that model for its JSON Schema and emits it next to the command's name, timeout and queue.

# conceptual, not runnable
@command-decorated function
  └── recorded args model  ──(publish: derive)──▶  JSON Schema
                                                      │
                            stored on the command row │
                                                      ▼
                        REST  GET /api/v1/commands  ·  MCP  tools/list

A command whose first parameter is not a Pydantic model (an untyped args, a plain dict, or a ctx-first signature) has no model to derive from. Note that Input Arguments requires a Pydantic args model — the no-model rows below are a publish-time degradation for commands that do not follow it, not a supported alternative.

What gets stored

Situation Stored schema
Args model present and derivable the derived JSON Schema
No args model to derive from {"type": "object"}
Derivation failed, or the result is not an object schema {"type": "object"}
Result exceeds the per-command size or nesting limit {"type": "object"}
Result cannot be encoded as JSON — a non-serializable value or a non-finite float default {"type": "object"}
Result carries an embedded NUL, which PostgreSQL refuses to store {"type": "object"}

An empty schema ({}) is never stored. {} advertises no arguments at all, which leaves an MCP client unable to construct a call; {"type": "object"} is the honest minimum — "an object, shape unspecified".

Nested and recursive models

Nested models are emitted the way Pydantic emits them, with definitions gathered under $defs and referenced by $ref. These are kept rather than inlined: inlining cannot represent a self-referential model.

Pydantic returns a document whose root is a reference rather than an object whenever the root schema is a definition it has already hoisted into $defs — a self-referential model, or a RootModel wrapping another model. Because a tool's input schema must describe an object, publish normalizes that shape — lifting the referenced definition to the root while leaving $defs in place, so inner references still resolve. A document that still does not describe an object after normalization falls back to the table above.

What the platform refuses to publish

Beyond the limits below, a derived schema is rejected — and the command falls back to {"type": "object"} — when its shape would leave a client unable to call it, or would send a client somewhere:

  • properties that is not a mapping of subschemas, or required that is not a list of property names. A tool advertising arguments a client cannot read is the un-callable tool this derivation exists to eliminate.
  • A reference that leaves the document. $ref, $dynamicRef and $recursiveRef must be exactly # or #/$defs/<name> (or #/definitions/<name>), where <name> uses only letters, digits, _, . and - — the shapes Pydantic emits. A deeper pointer such as #/required/x or #/$defs/X/default is refused, and so is a name with % or ~, because a resolver unescapes those into the same deeper pointer (X%2Fdefault). $defs and definitions must be objects. $id, $schema and the anchor keywords are refused outright, because they re-base how every other reference resolves. Resolving a remote pointer would make the client fetch an author-chosen address while preparing a tool call.
  • A reference cycle that never consumes an argument, such as {"allOf": [{"$ref": "#"}]} or two definitions that $ref each other through allOf/anyOf/oneOf/not/if/then/else/dependentSchemas. No value can finish validating against it, and the resolver would recurse until the interpreter gives up (as a native-extension panic on some Python versions). Recursion that descends into the argument, such as a tree whose children items $ref the tree, is what Pydantic emits for a self-referential model and is accepted.

The first two rules apply at every schema position, not only at the document root — a malformed body or a remote pointer one $ref deeper is just as un-callable.

When hosted MCP receives a call, it checks the arguments against the stored schema before running anything. That check is advisory: the command's Pydantic args model, running in the pack's own process, is the layer that enforces the contract. A hand-written model_json_schema that does not match the model is enforced only as far as the model itself goes. The check runs on the API, so its work is bounded:

  • Pack regexes never run. pattern and patternProperties are not evaluated, because an expression such as ^(a+)+$ can backtrack catastrophically on a caller's string. So additionalProperties beside a patternProperties is not checked either.
  • unevaluatedProperties and unevaluatedItems are not checked. Pydantic emits neither.
  • Work is weighted and capped. Each keyword is charged for what it iterates or compares (an enum its size, required its names, uniqueItems the array), and each error for its message. One check may spend 30,000 steps. A typical call needs a few hundred, and a 1,000-element array of a five-field model needs about 25,000.
  • Some calls skip the check. That happens when the arguments encode to more than 256 KiB, the check would exceed its budget, the schema fails the publish rules above (a row stored before they tightened), or the validator errors. Each skip is logged with the command and correlation ID, and the call goes on to the args model.

Moving this check off the API event loop entirely is tracked in #1927.

Position matters: a key spelled $ref inside a default, const, enum or examples is ordinary data that nothing resolves, and is left alone. Only references in schema positions are treated as pointers. The keywords recognized as carrying subschemas cover draft-07, 2019-09 and 2020-12 (including dependencies, additionalItems and contentSchema); anything outside that vocabulary is treated as data, because a validator does not resolve inside it.

Limits

A derived schema is bounded in both serialized size (16 KiB of JSON) and nesting depth (32 levels). Over either limit, the command falls back to {"type": "object"} and the publish continues — one command's pathological model never fails its siblings or the pack.

The bounds are applied inside the pack's venv before the schema is emitted, and re-checked by the platform before it is stored: the first check runs in the same interpreter that has already executed pack code, so it is advisory from the platform's side.

A degraded command is recorded in the platform logs, but it is not reported in the publish response. To confirm a command published with the schema you expect, read it back and check that input_schema carries the properties you declared.

Already-published commands

Versions published before this derivation existed hold {} on the command row. Both read paths — the REST command endpoints and the hosted MCP tools/list — normalize what they serve, so those commands advertise {"type": "object"} rather than an empty schema. They do not gain real argument shapes until the pack is republished.

Normalization is applied on read, not by rewriting stored rows: the schema can only be re-derived from the pack's own wheel, so a republish is what restores a real argument shape.

Command description

A command carries two texts with two different jobs. Neither is a second authority for the other:

Field Source Meant for
summary the manifest's commands[].description in huitzo.yaml one-line human listings: the WebCLI commands output and the Hub command palette
description the @command(description=...) argument, else the function's docstring commands get and detail views; used unchanged as the hosted MCP tool description

The API serves both on every command endpoint (see Where each text is served). The Hub WebCLI and the Hub command palette both list a command by its summary, falling back to the description's first line when the summary is empty.

Where it comes from

A command's description comes from the @command(description=...) argument. When that argument is omitted, the platform falls back to the function's docstring. If neither is present, the description is an empty string — never null.

A command's summary comes from the manifest entry whose name matches the command, commands[].description in huitzo.yaml; publish records it on that command's entry in the pack version's stored manifest. Write it as one self-contained line: a reader who never sees the full description should still know what the command does. A summary that differs from a longer docstring is expected, not an error — publish does not compare the two.

Normalization

Whichever source supplies it, the platform normalizes the value with inspect.cleandoc semantics: leading and trailing blank lines are dropped, common leading whitespace shared by every line after the first is stripped (so an indented docstring reads as flush text instead of carrying its source indentation), and the result is trimmed of surrounding whitespace. Nothing is truncated — the full text is always preserved. A value longer than 16,384 characters skips the per-line dedent and is only trimmed of surrounding whitespace — bounding the per-request cost of a pathologically large description — but it is still never truncated.

How the summary is derived

The platform derives the summary when it serves a command, never by rewriting stored rows:

  1. Take the manifest summary recorded for the command in its pack version's stored manifest, normalize it as above, and use its first non-empty line.
  2. When there is no manifest summary (the version was published before the platform recorded it, or the entry is empty), use the first non-empty line of the normalized description instead.
  3. When both are empty, the summary is "", never null.

The summary is never truncated. Fitting it to a column is a client concern: the Hub WebCLI's commands listings show the summary fitted to the terminal's current width (cut with … only when it does not fit), and commands get shows both the summary and the full description — see WebCLI terminal rendering. The native huitzo CLI follows the same contract from its next release (Huitzo-Inc/cli#356): its listings show a one-line summary — the summary field when the data it lists carries one, otherwise the description's first non-empty line — with inline markup stripped, fitted to the terminal's width. The local sandbox has no manifest access, so its listings always use the docstring's first line.

Where each text is served

GET /api/v1/commands and GET /api/v1/commands/{namespace} both return summary alongside the complete normalized description, as do the per-command entries in GET /api/v1/packs and GET /api/v1/packs/{id}. An empty value serves as "" on every one of these. Summaries never cost a query per command: the command endpoints read only the stored commands list of each distinct pack version in one query, and the pack endpoints reuse the version they already loaded.

The hosted MCP server's tools/list (api/v1/mcp.py) uses the full description as the tool description, never the summary, because the text an agent selects tools by is a separate decision that needs an evaluation, not a listing change. It falls back to a synthesized "Huitzo pack command <namespace>" when the normalized description is empty, since an MCP tool with no description is worse than one with a generic placeholder.

Inline markup

Inline literal markup — RST like this or Markdown `like this` — is allowed in a summary or a description. A client rendering a one-line summary as plain text should strip the markup characters rather than pass them through unrendered, since a terminal or a one-line listing is not a markup renderer. The WebCLI listings and the Hub command palette strip both forms (WebCLI terminal rendering), and so does the native CLI from its next release (Huitzo-Inc/cli#356).

Existing rows

Normalization happens on every read, not by rewriting stored rows: a NULL or raw, indented description already in the database serves as a normalized empty string or dedented text respectively, without a migration or backfill. The summary follows the same no-backfill rule, and this is the current behavior: a version published before the platform recorded manifest summaries has no summary stored, so it serves the first line of its description as its summary. Republishing the pack records its manifest summaries.

Command Registry

The platform resolves an incoming @scope/pack/command against an in-memory registry that maps the namespace to the callable plus its decorator metadata (timeout, queue, version, and the pack venv's site-packages path).

Field Source Used for
namespace entry-point name routing
timeout @command(timeout=...) execution deadline
queue @command(queue=...) inline vs medium/long dispatch
version pack version reporting and pinning
site_packages the pack's venv re-establishing your imports at call time

Each OS process keeps its own registry. A process fills it at startup for the packs that are already active, and a Celery worker additionally loads any pack it has not seen the first time it is asked to run one of that pack's medium/long commands — so on that path your command is runnable as soon as your publish commits, with no restart and no propagation delay. The inline fast/REST path and pipeline stages do not do this yet: a pipeline stage relies on the publish-time notification, and an API replica that did not serve your publish picks the pack up only on its next restart. The mechanisms, and why the miss path rather than the startup load is the guarantee, are specified in Resource Lifecycle.

Best Practices

1. Keep Commands Focused

# ✅ Good: Single responsibility
@command("send-email", namespace="notifications")
async def send_email(args: EmailArgs, ctx: Context) -> dict:
    ...

# ❌ Bad: Doing too much
@command("send-everything", namespace="notifications")
async def send_everything(args: Args, ctx: Context) -> dict:
    # Sending email, SMS, Slack, push notifications...

2. Use Meaningful Names

# ✅ Good: Verb-noun pattern
@command("generate-report", namespace="analytics")
@command("validate-data", namespace="etl")
@command("sync-inventory", namespace="warehouse")

# ❌ Bad: Vague names
@command("do-stuff", namespace="misc")
@command("process", namespace="data")

3. Document with Docstrings

@command("calculate-roi", namespace="finance")
async def calculate_roi(args: ROIArgs, ctx: Context) -> dict:
    """Calculate Return on Investment for a given period.

    This command analyzes revenue and costs to compute ROI metrics.
    Results are cached for 24 hours.

    Examples:
        calculate-roi --start-date 2024-01-01 --end-date 2024-12-31
        calculate-roi --department sales --include-projections
    """
    ...

The first line — "Calculate Return on Investment for a given period." — stands alone as a complete sentence. A listing shows the command's manifest summary (commands[].description in huitzo.yaml) and falls back to this first line only when no manifest summary was recorded, so keep the two in the same voice. Everything after it (the body, the Examples: block) is still part of the full description served by the REST API and hosted MCP; see Command description for the full contract and the current state of client-side support.

4. Handle Errors Gracefully

@command("safe-operation", namespace="utils")
async def safe_operation(args: Args, ctx: Context) -> dict:
    try:
        result = await risky_call()
        return {"success": True, "data": result}
    except SpecificError as e:
        ctx.log.warning(f"Expected error: {e}")
        return {"success": False, "error": str(e)}
    except Exception as e:
        ctx.log.error(f"Unexpected error: {e}")
        raise CommandError(
            message="Operation failed unexpectedly",
            details={"error_type": type(e).__name__}
        )

See Also