Context Reference

Context Reference

The Context object is passed to every command and provides access to platform services, storage, integrations, and request metadata.

Overview

from huitzo_sdk import command, Context

@command("example", namespace="demo")
async def example(args: Args, ctx: Context) -> dict:
    # Access storage
    await ctx.storage.save("key", {"data": "value"})

    # Use integrations
    response = await ctx.llm.complete("Summarize this text...")

    # Access metadata
    print(f"User: {ctx.user_id}")
    print(f"Tenant: {ctx.tenant_id}")

    return {"response": response}

Context Properties

Identity & Metadata

Property Type Description
ctx.user_id UUID Current user's ID
ctx.tenant_id UUID Current tenant's ID
ctx.session_id UUID Current session ID
ctx.correlation_id str Request correlation ID for tracing
ctx.command_name str Name of the executing command
ctx.namespace str Namespace of the executing command
ctx.command_version str Version of the executing command

Deployment Mode

Property Type Description
ctx.deployment_mode DeploymentMode Current deployment mode
ctx.local_storage Optional[StorageBackend] Local storage for edge mode (future)
ctx.inference_backend Optional[InferenceBackend] Local inference for edge mode (future)

The deployment_mode property indicates the current execution environment:

from huitzo_sdk import DeploymentMode

@command("check-mode", namespace="utils")
async def check_mode(args: Args, ctx: Context) -> dict:
    return {
        "mode": ctx.deployment_mode.value,
        "is_cloud": ctx.deployment_mode == DeploymentMode.CLOUD,
        "is_self_hosted": ctx.deployment_mode == DeploymentMode.SELF_HOSTED,
        "is_edge": ctx.deployment_mode == DeploymentMode.EDGE,
    }

Deployment Modes:

Mode Description Status
CLOUD Huitzo-managed multi-tenant infrastructure Production
SELF_HOSTED Customer-managed single-tenant deployment Production (Year 1)
EDGE Offline-capable edge device Design phase (Year 3+)

Most commands should work identically across all deployment modes. Use ctx.deployment_mode only when behavior must differ (e.g., offline sync handling).

Example: Accessing Metadata

@command("whoami", namespace="utils")
async def whoami(args: Args, ctx: Context) -> dict:
    return {
        "user_id": str(ctx.user_id),
        "tenant_id": str(ctx.tenant_id),
        "session_id": str(ctx.session_id),
        "correlation_id": ctx.correlation_id,
        "command": f"{ctx.namespace}.{ctx.command_name}",
        "version": ctx.command_version,
    }

Services

ctx.storage

Tenant-isolated key-value storage backed by a pluggable storage backend (PostgreSQL JSONB for cloud/self-hosted, SQLite for edge in future).

# pseudocode — ctx.storage usage

await ctx.storage.save(key, value)              # save data
await ctx.storage.save(key, value, ttl=3600)    # save with expiration (seconds)
data = await ctx.storage.get(key)               # get data (returns None if missing)
data = await ctx.storage.get(key, default={})   # get with default
keys = await ctx.storage.list(prefix="...")      # list keys by prefix
await ctx.storage.delete(key)                    # delete
exists = await ctx.storage.exists(key)           # check existence

Batch Operations:

# pseudocode — batch storage operations

await ctx.storage.save_many({key1: val1, key2: val2, ...})
results = await ctx.storage.get_many([key1, key2, ...])
await ctx.storage.delete_many([key1, key2, ...])

Query by Metadata:

# pseudocode — query by metadata
results = await ctx.storage.query(prefix="...", metadata={...}, limit=100)

See: Storage Reference

ctx.llm

AI/LLM completion service.

# pseudocode — ctx.llm usage

# Simple completion
response = await ctx.llm.complete(prompt="...", model="<model-name>")

# With system message
response = await ctx.llm.complete(prompt=..., system="...", model="<model-name>")

# Structured output (returns validated Pydantic model instance)
response = await ctx.llm.complete(prompt=..., response_format="json", schema=YourModel)

# Streaming
async for chunk in ctx.llm.stream(prompt="...", model="<model-name>"):
    # process each chunk
    ...

See: Integrations Reference

ctx.email

Email sending service.

# pseudocode — ctx.email usage

# Simple email
await ctx.email.send(to="...", subject="...", body="...")

# HTML email
await ctx.email.send(to="...", subject="...", html="<h1>...</h1>")

# With attachments
await ctx.email.send(to="...", subject="...", body="...",
    attachments=[{"filename": "report.pdf", "content": bytes_data}])

# Multiple recipients
await ctx.email.send(to=["[email protected]", "[email protected]"], cc=["[email protected]"], ...)

ctx.tts

Platform speech synthesis (text-to-speech via the platform's ElevenLabs key — no BYOK). Requires services.tts + the tts:synthesize permission token; unwired access raises IntegrationError (fail-closed).

# pseudocode — ctx.tts usage

result = await ctx.tts.synthesize(text, voice_id="...", language="en")
# -> SynthesisResult(audio: bytes, characters: int, request_id: str)

voices = await ctx.tts.voices()   # platform-curated voice catalog

See: TTS Reference

ctx.files

File reading and writing service.

# Read Excel file
df = await ctx.files.read_excel("uploads/data.xlsx")
df = await ctx.files.read_excel("uploads/data.xlsx", sheet="Sales")

# Read CSV
df = await ctx.files.read_csv("uploads/data.csv")

# Read JSON
data = await ctx.files.read_json("uploads/config.json")

# Write file
await ctx.files.write("output/report.csv", df.to_csv())
await ctx.files.write("output/data.json", json.dumps(data))

# Get file info
info = await ctx.files.info("uploads/data.xlsx")
# Returns: {"size": 1024, "created": datetime, "modified": datetime}

# List files
files = await ctx.files.list("uploads/")

See: Files permissions

ctx.http

HTTP client for external API calls.

# GET request
response = await ctx.http.get("https://api.example.com/data")

# With headers
response = await ctx.http.get(
    "https://api.example.com/data",
    headers={"Authorization": "Bearer token"}
)

# POST request
response = await ctx.http.post(
    "https://api.example.com/submit",
    json={"name": "value"}
)

# With timeout
response = await ctx.http.get(
    "https://slow-api.example.com/data",
    timeout=60
)

# Form data
response = await ctx.http.post(
    "https://api.example.com/upload",
    data={"field": "value"},
    files={"file": file_bytes}
)

Domain Restrictions

HTTP requests are restricted to domains declared in your pack's huitzo.yaml:

services:
  http:
    allowed_domains:
      - "api.example.com"        # Exact match
      - "*.trusted-domain.org"   # Wildcard subdomain

Enforcement: - Requests to unlisted domains raise HTTPSecurityError - Wildcards match any subdomain (e.g., *.example.com matches api.example.com) - Protocol is always HTTPS in production - Each redirect hop gets the same checks (Redirects)

Error Handling:

from huitzo_sdk.errors import HTTPSecurityError

try:
    response = await ctx.http.get("https://blocked-domain.com/data")
except HTTPSecurityError as e:
    ctx.log.error(f"Domain not allowed: {e.domain}")

ctx.cron

Cron schedule metadata for commands triggered by the scheduler.

# pseudocode — ctx.cron usage

# Check if this is a scheduled run
if ctx.cron.is_scheduled:
    schedule = ctx.cron.schedule         # e.g., "0 8 * * 1-5"
    scheduled_at = ctx.cron.scheduled_at # datetime when this run was scheduled (UTC)

# Query next/last run times
next_run = await ctx.cron.get_next_run()
last_run = await ctx.cron.get_last_run()

# Query another command's schedule
next_digest = await ctx.cron.get_next_run("@scope/pack/digest")

Properties:

Property Type Description
ctx.cron.is_scheduled bool True if triggered by scheduler, False for on-demand
ctx.cron.schedule str \| None Cron expression (e.g., "0 8 * * 1-5")
ctx.cron.scheduled_at datetime \| None When this run was scheduled (UTC)

Methods:

Method Returns Description
await ctx.cron.get_next_run(command_namespace?) datetime \| None Next scheduled run time (UTC)
await ctx.cron.get_last_run(command_namespace?) datetime \| None Last scheduled run time (UTC)

Requirements: Declare cron in your pack's services section and set a schedule field on the command in huitzo.yaml. See Manifest Reference.

ctx.telegram

Telegram messaging service.

# Send message
await ctx.telegram.send(
    chat_id="123456789",
    message="Hello from Huitzo!"
)

# With formatting
await ctx.telegram.send(
    chat_id="123456789",
    message="*Bold* and _italic_",
    parse_mode="Markdown"
)

# Send document
await ctx.telegram.send_document(
    chat_id="123456789",
    document=pdf_bytes,
    filename="report.pdf",
    caption="Your weekly report"
)

ctx.ssh

Hosted execution: ctx.ssh is wired only when the pack declares services.ssh, a non-empty ssh_targets.allowed and ssh:execute in policy.allowed_actions, and the calling tenant has a matching ssh integration. See SSH Execution — Context Factory Integration for the routes that wire it.

Remote command execution on user-registered SSH targets (GPU clusters, custom servers, on-premise machines).

# Execute a command on a remote server
result = await ctx.ssh.run("gpu-cluster", "nvidia-smi --query-gpu=name,memory.used --format=csv")
print(result.stdout)     # Command output
print(result.exit_code)  # 0 = success

# With custom timeout
result = await ctx.ssh.run("gpu-cluster", "python train.py", timeout=3600)

# Check exit code (non-zero does NOT auto-raise)
if result.exit_code != 0:
    ctx.log.error(f"Command failed: {result.stderr}")

Key Points: - target is the human-readable name the user registered (e.g., "gpu-cluster") - Returns SSHResult with stdout, stderr, exit_code - Output truncated at 1 MB per stream - Pack must declare allowed targets in huitzo.yaml under ssh_targets

Error Handling:

from huitzo_sdk.errors import SSHError

try:
    result = await ctx.ssh.run("gpu-cluster", "nvidia-smi")
except SSHError as e:
    ctx.log.error(f"SSH failed on {e.target}: {e.message}")

See: SSH Integration Reference

ctx.mcp

Not available on hosted execution yet: ctx.mcp is not wired on any hosted execution path, so a command that calls it fails with IntegrationError. Tracked in #1943.

Access to MCP (Model Context Protocol) servers configured in the pack manifest. MCP servers expose external tools that become callable from your commands—no LLM required.

# Call an MCP tool
result = await ctx.mcp.call(
    server="github",
    tool="create_issue",
    arguments={
        "owner": "acme",
        "repo": "project",
        "title": "Bug report"
    }
)

# Attribute access syntax (alternative)
result = await ctx.mcp.github.create_issue(
    owner="acme",
    repo="project",
    title="Bug report"
)

# List available tools from a server
tools = await ctx.mcp.list_tools("github")
for tool in tools:
    print(f"{tool.name}: {tool.description}")

# Get tool schema
schema = await ctx.mcp.get_tool_schema("github", "create_issue")

# Check configured servers
servers = ctx.mcp.servers  # dict[str, MCPServerInfo]

Key Points: - MCP servers are configured in huitzo.yaml under mcp_servers - Tools are discovered automatically on first use - STDIO (subprocess) and HTTP (remote) transports supported - Arguments are validated against the tool's JSON Schema - Connections are lazily initialized and pooled

Error Handling:

from huitzo_sdk.errors import MCPConnectionError, MCPToolError

try:
    result = await ctx.mcp.call("github", "create_issue", {...})
except MCPConnectionError:
    ctx.log.error("GitHub MCP server unavailable")
except MCPToolError as e:
    ctx.log.error(f"Tool failed: {e.message}")

See: MCP Reference for complete API documentation.

ctx.integrations

Access to deployment-scoped extensions advertised by the active deployment. Where built-in integrations (ctx.llm, ctx.email, ctx.http) are kernel-managed and ship with the platform, extensions are independently-versioned Python wheels — fetched as part of the signed bundle on huitzo login, declared per-pack in huitzo.yaml, and surfaced under a single namespace.

# pseudocode — accessing a deployment-advertised extension
result = await ctx.integrations.crm.search("example")

Key Points:

  • Extensions are advertised by the deployment via /api/v1/capabilities and fetched as a signed bundle on huitzo login.
  • Resolution is lazy: the wheel is imported on first attribute access, not at pack startup.
  • A name not in the deployment's descriptor raises ExtensionNotAvailable(name, deployment, available).
  • Built-in surfaces (ctx.llm, ctx.email, …) are unchanged and do not migrate here.

Error Handling:

# pseudocode — graceful degradation when an extension isn't advertised
from huitzo_sdk.errors import ExtensionNotAvailable

try:
    crm = ctx.integrations.crm
except ExtensionNotAvailable as exc:
    ctx.log.warning(f"CRM extension not available on {exc.deployment}; falling back")
    return {"results": []}

See: Extensions Reference for the full pack-author guide; Deployment Capabilities for the descriptor + trust contract.

ctx.log

Structured logging service.

# Log levels
ctx.log.debug("Detailed debug info")
ctx.log.info("Operation completed")
ctx.log.warning("Something might be wrong")
ctx.log.error("An error occurred")

# With context
ctx.log.info("Processing file", extra={
    "filename": args.filename,
    "size": file_size,
    "rows": row_count
})

# Automatic correlation
# All logs automatically include correlation_id, user_id, tenant_id

ctx.pipeline

Programmatic builder for declarative pipelines — the runtime alternative to the pipelines: section of huitzo.yaml. Builder-produced pipelines execute through the same PipelineExecutor as manifest-declared ones (identical semantics: sequential / streaming / parallel paths, route filtering, cross-pack permission gate, checkpointing). See Piping Protocol and Building Pipelines for the manifest form.

# pseudocode — programmatic pipeline

@command("run-etl", namespace="data")
async def run_etl(args, ctx):
    pipeline = ctx.pipeline.create("etl-job")
    pipeline.add_stage("source:fetch-data", config={"source": args.source})
    pipeline.add_stage("filter:clean", config={"rules": args.rules})
    pipeline.add_stage("action:analyze", config={"model": "gpt-4o"})

    result = await pipeline.execute({"trigger": "manual"})
    return {"pipeline_id": result.id, "status": result.status.value}

Builder surface:

Method Returns Purpose
ctx.pipeline.create(name, *, timeout=300) PipelineBuilder Start a new builder bound to the outer command's identity (tenant / user / correlation).
builder.add_stage(command, *, config=None, accept_routes=None, buffer_size=100, checkpoint_after=False, name=None) Self Append a single stage. Auto-names as stage_<index> when name is omitted. Chainable.
builder.add_parallel(branches, joiner, *, name=None, checkpoint_after=False) Self Append a fan-out / fan-in block. branches is a list of stage dicts (2–16); joiner is the single dict that assembles branch outputs.
builder.build() PipelineSpec Materialize the same Pydantic model that huitzo.yaml parsing produces — useful for introspection or persistence.
await builder.execute(initial_args, *, timeout=None) PipelineResult Run via the runtime-bound executor. Inherits tenant / user / correlation from the outer command's ctx. The resulting run is persisted to pipeline_runs (RLS-scoped) so it surfaces in the Hub viewer and can be looked up via ctx.pipeline.get(). A run that raises PipelineError is persisted too, as FAILED with the stages that ran, before the error reaches the command.
await ctx.pipeline.get(pipeline_id) PipelineResult Look up a persisted run (RLS-scoped to the caller's tenant).
await ctx.pipeline.resume(pipeline_id) PipelineResult Resume from the highest live checkpoint. Currently restricted to the originating user of the run because create_context does not yet plumb the caller's role / API-key scopes through; elevated callers (admin/owner role, pipeline:resume API-key scope) should use POST /api/v1/pipelines/runs/{id}/resume in the meantime. Status / live-checkpoint gates match the REST endpoint.

Pipelines execute as a single correlation unit with streaming backpressure.

Nesting limit. Programmatic pipelines must not recurse deeper than 4 levels — each ctx.pipeline.create().execute() call inside another pipeline stage counts as one level. The runtime enforces the cap with a clear RuntimeError; split the work into separate commands invoked via the REST API if you need deeper composition.

Per-run limit. One command run can start at most 4,095 pipelines through ctx.pipeline, counting the ones its stages start. The next call raises a RuntimeError before the pipeline runs. A command that loops over a large batch should process it in several command runs.

Request scope. ctx.pipeline holds the request-scoped db_session in a closure, so the client must not escape the command body. Do not stash ctx.pipeline in module-level state or schedule it inside a BackgroundTask that outlives the request — the session will already be closed when the closure fires.

Cross-pack stages

Requires huitzo ≥ v0.11.4 — check your platform version before using this section. On v0.11.3 and earlier a cross-pack stage inherits the declaring pack's policy.allowed_actions and receives no service allowlists at all, so any ctx.http call from one fails with HTTPSecurityError: No allowed domains configured — no matter which pack declares the domain. On those versions no manifest change on either pack works around it, and republishing will not help; invoke the target command directly over REST instead.

Cross-pack stages run under the target pack's own manifest. When a stage names a command in another pack (@scope/pack:namespace:command), that stage's ctx is built from the target pack's manifest — its services, its http.allowed_domains, its db.integrations, its policy.allowed_actions — exactly as if the command had been invoked directly over REST. Your pack's declarations do not reach it.

Two practical consequences, in the order authors hit them:

  • Do not add a capability to your manifest to satisfy a stage in someone else's pack. If a cross-pack stage fails with HTTPSecurityError: No allowed domains configured, or an SDK "integration not wired" RuntimeError, the manifest to fix is the target's, and republishing the target with the capability it needs is what closes the gap. Declaring the capability in the calling pack changes nothing, on any version.
  • Your manifest still needs the grant. commands:execute:@scope/pack must appear in your permissions: and your policy.allowed_actions — that is what authorizes the call. It is authority to invoke, not a capability the target inherits. The calling tenant must also be independently entitled to execute that command.

Identity follows the same rule: a cross-pack stage's ctx.storage partitions to the target pack, and ctx.secrets resolves secrets the user configured for the target pack (with the usual pack-agnostic and BYOK fallbacks). Values you wrote via ctx.storage in the calling command are not visible to the stage, and vice versa — pass data through the stage's arguments and return value, which is the only supported channel between stages. On v0.11.3 and earlier this attribution ran the other way, under the declaring pack's identity — so anything a cross-pack stage persisted on an older version stays in that partition and is not visible to it after the upgrade.

Two gaps remain, tracked as later ADR-031 phases: a cross-pack stage does not receive the target's own grant list, so a nested ctx.pipeline inside a cross-pack stage cannot itself make cross-pack calls (Phase 4); and intra-pack stages do not yet receive a full projection of their own pack's manifest (Phase 2) — of the allowlists, only ssh_targets reaches them today, on manifest-declared pipelines and their resume, not on stages built with ctx.pipeline.create().

If you publish a pack others may invoke as a stage

Your manifest is the whole authorization for what your pack does as someone else's pipeline stage. An orchestrator that holds commands:execute:@you/your-pack — and whose tenant is entitled to your pack — can invoke your command repeatedly and unattended, choosing its arguments, and your pack will run at its full declared capability. The orchestrator's own policy card no longer restrains it.

So declare the minimum you actually need — but know that the lever differs by capability. The capabilities in the table below are policy-gated: your policy.allowed_actions is what decides whether each one is wired at all, on every route including a stage. Three others are not gated by your policy card at all, and are covered separately after the table.

You declare A stage invocation of your pack can then reach
llm:complete / llm:stream model calls metered against the calling user's credit account, using the calling tenant's BYOK key if they configured one. Alongside files:*, the row to think hardest about: it spends someone else's money
files:read / files:write / files:delete reading, writing or deleting (move needs write and delete) across the calling tenant's entire file namespace — ctx.files is tenant-scoped, not pack-scoped, unlike ctx.storage
tts:synthesize speech synthesis against the calling tenant's TTS quota and character meter
http:request + services.http.allowed_domains your declared domains, unioned with any allowed_domains on the tenant's own http Integration row — so the effective list can be wider than your manifest, but only by the tenant's own configuration
email:send outbound email as the calling user
telegram:send Telegram delivery as the calling user
ssh:execute + services.ssh + ssh_targets.allowed commands on the calling tenant's registered ssh targets whose names your ssh_targets.allowed lists (["*"] means every ssh target that tenant has). Never the calling pack's targets, and never a target your list does not name

Every entry is a literal permissions: token. The set is closed (see Manifest Reference), so there is no storage:*-style wildcard, and an unrecognised token fails manifest validation with the valid set.

Three capabilities are not policy-gated, so "declare the minimum allowed_actions" cannot bound them. Pruning policy.allowed_actions closes none of these — ctx.storage and ctx.secrets are wired for every stage whenever a database session exists, and ctx.db is decided entirely by your services: block plus whether the calling tenant has a database Integration configured at all:

Reached with no allowed_actions token at all What a stage invocation of your pack gets
ctx.db — gated only by services.db in your manifest the calling tenant's postgres and mysql Integration rows. services.db declared with no integrations: list means ["*"] — every DB integration that tenant has configured. Not partitioned by pack, and no permission token can restrain it: the closed token set has no db:* member. The widest capability on this page
ctx.storage your own pack's partition only — the narrowest of the three. A stage invocation reaches only your data
ctx.secrets the calling user's secrets scoped to your pack, with the usual pack-agnostic and BYOK fallbacks — so an orchestrator can cause your code to read secrets that user configured for you, and act on them, without your policy card mentioning secrets at all

The practical consequence for ctx.db: if you do not want a stage caller reaching the calling tenant's databases through your pack, the lever is omitting services.db from your manifest, or naming an explicit integrations: allowlist — never trimming policy.allowed_actions, which has no effect on it.

Validate your inputs as if the caller were untrusted, because a stage caller is exactly that: another author's code choosing your arguments.

Environment & Configuration

ctx.env (Not yet available)

Not yet available in this SDK version. Accessing ctx.env raises ConfigurationError at runtime.

Read-only access to pack-scoped environment values.

It will not expose platform secrets. Tier 1 credentials (LLM provider keys, HUITZO_SENDGRID_API_KEY, …) are platform-owned; the platform consumes them internally when it services a ctx.llm / ctx.email / ctx.tts / ctx.telegram call, and no planned ctx.env will hand one to a pack. Do not design a pack around reading them, now or later. (This is a contract about the SDK surface, not a sandbox — see API-surface contract, not a sandbox.)

# pseudocode — planned shape, NOT callable today
api_key = ctx.env.get("MY_PACK_SETTING")
debug = ctx.env.get("DEBUG", "false")
value = ctx.env.require("REQUIRED_SETTING")

ctx.config (Not yet available)

Not yet available in this SDK version. Accessing ctx.config raises ConfigurationError at runtime. Until it ships, express per-deployment knobs as command arguments or user secrets.

Access pack-specific configuration.

# pseudocode — planned shape, NOT callable today
setting = ctx.config.get("feature_enabled")
db_host = ctx.config.get("database.host")
timeout = ctx.config.get("timeout", type=int, default=60)

ctx.secrets

Access user-provided secrets (API keys, credentials) for external services. User secrets are scoped to user + pack. ctx.secrets is the only credential accessor a pack has — platform credentials are never exposed to pack code.

You must declare every name you read. A pack can only read secret names its own manifest lists under secrets.user_required or secrets.user_optional. An undeclared name is refused before the lookup and behaves exactly as if the secret did not exist — get() returns None, exists() returns False, require() raises SecretsError — even when the user has configured a value. Forgetting to declare a name is therefore silent, and looks identical to misconfiguration. Republish the pack after adding a name. See Tier 3 scoping and Declared-secret authorization.

A declared secret can also be unresolvable, and that is not silent. If the name resolves to two credentials of equal standing, or the stored value fails to decrypt, all three methods — including get() and exists() — raise IntegrationError(service="secrets") rather than returning None/False. It is a platform-side configuration fault the user or an admin must fix, and it deliberately never falls back to a different credential. See IntegrationError from ctx.secrets.

# pseudocode — every method is async
api_key = await ctx.secrets.get("FINANCIAL_API_KEY")       # None if unset
api_key = await ctx.secrets.require("FINANCIAL_API_KEY")   # raises SecretsError if unset

if await ctx.secrets.exists("PREMIUM_API_KEY"):
    premium_key = await ctx.secrets.get("PREMIUM_API_KEY")

Secrets vs Platform Credentials

Tier How a pack reaches it Scope Use Case
Platform (Tier 1) No accessor. Call ctx.llm / ctx.email / ctx.tts / ctx.telegram; the platform supplies the key. Platform services Platform API keys (LLM provider keys, HUITZO_SENDGRID_API_KEY)
User (Tier 3) await ctx.secrets.get() User + Pack User's external API keys

Example: Using User Secrets

from huitzo_sdk import command, Context
from huitzo_sdk.errors import SecretsError, ExternalAPIError

@command("sync-data", namespace="integrations")
async def sync_data(args: Args, ctx: Context) -> dict:
    """Sync data from user's external service."""

    # Require the user's API key
    try:
        api_key = await ctx.secrets.require("EXTERNAL_API_KEY")
    except SecretsError:
        return {
            "error": "Missing API key",
            "help": "Add this key on the Integrations page (+ Add integration → Secret value)"
        }

    # Use the key to call external service
    try:
        response = await ctx.http.get(
            "https://api.external.com/data",
            headers={"Authorization": f"Bearer {api_key}"}
        )
    except HTTPError as e:
        if e.status_code == 401:
            raise ExternalAPIError(
                service="external-api",
                message="Invalid API key. Verify it on the Integrations page."
            )
        raise

    return {"synced": len(response["data"])}

Secret Management

Users configure their own secrets in the Hub, via Settings → Connections → Manage integrations → + Add integration → Secret value, one key/value row per declared name. Nothing prompts them at install time and nothing deep-links them there from a failed command — see Installation Flow for the full walkthrough, including the role-dependent scope of the row that gets created. (huitzo secrets is a local developer store on your own machine; it does not reach a deployment.)

Pack developers declare required and optional secrets in huitzo.yaml:

secrets:
  user_required:
    - name: "EXTERNAL_API_KEY"
      description: "Your API key from external.com"
      help_url: "https://external.com/api-keys"

See Pack Manifest - Secrets and Secrets Management for complete documentation.

Advanced Usage

Intra-Pack Command Execution

Commands within the same pack can invoke each other using ctx.commands.execute(). This enables composable workflows where higher-level commands build on lower-level ones without duplicating logic.

# pseudocode — intra-pack command composition

@command("compare-visits", namespace="claims", timeout=120)
async def compare_visits(args, ctx):
    # Call get-visit within the same pack
    actual = await ctx.commands.execute(
        "get-visit",
        {"pdv_id": args.pdv_id, "visit_id": args.actual_id},
    )
    anterior = await ctx.commands.execute(
        "get-visit",
        {"pdv_id": args.pdv_id, "visit_id": args.anterior_id},
    )
    # Score using loaded data...
    return {"score": compare(actual, anterior)}

ctx.commands.execute() Reference

# pseudocode — API signature
result = await ctx.commands.execute(
    command_name,        # short name within this pack (e.g., "get-visit")
    args,                # arguments dict
    timeout=None,        # override timeout (optional)
)

Execution Behavior

Concern Behavior
Scope Same-pack only — cannot call commands in other packs
Routing Always inline — never dispatched to Celery
Context Inherits parent (same user_id, tenant_id, storage scope)
Timeout Deducted from parent's remaining budget
Circular calls Detected and rejected (max depth 10)
Run page Not recorded as a step — the work, and any model call it makes, shows on the calling command's step

A nested call is ordinary code as far as the run page is concerned. When each piece of work should be its own step, declare the commands as pipeline stages. See Authoring for the Run View.

Error Handling

# pseudocode — error handling for intra-pack calls
from huitzo_sdk.errors import (
    CircularCommandError,
    CommandNotFoundError,
    CommandTimeoutError,
    CommandError,
)

try:
    result = await ctx.commands.execute("inner-cmd", args={...})
except CommandNotFoundError:
    # command does not exist in this pack
    ...
except CircularCommandError:
    # A -> B -> A detected
    ...
except CommandTimeoutError:
    # parent's timeout budget exhausted
    ...
except CommandError:
    # inner command raised an error
    ...

Pack-to-Pack Command Execution

Packs can execute commands from other installed packs using ctx.execute(). This enables composable workflows where packs build on each other's capabilities.

@command("generate-report", namespace="reporting")
async def generate_report(args: ReportArgs, ctx: Context) -> dict:
    # Call command from analytics pack
    analysis = await ctx.execute(
        pack="analytics",
        command="analyze-data",
        args={"dataset": args.dataset_id, "metrics": ["revenue", "growth"]}
    )

    # Call command from email pack
    await ctx.execute(
        pack="notifications",
        command="send-email",
        args={
            "to": args.recipient,
            "subject": "Your Report",
            "body": format_report(analysis)
        }
    )

    return {"status": "sent", "analysis_id": analysis["id"]}

ctx.execute() Reference

result = await ctx.execute(
    pack: str,           # Target pack namespace
    command: str,        # Command name
    args: dict,          # Command arguments
    timeout: int = None, # Override timeout (optional)
)

Execution Behavior

  • User Identity: Executes as the original user (preserves user_id, tenant_id)
  • Correlation: Links to parent via parent_correlation_id for tracing
  • Permissions: Respects the called command's permission requirements
  • Billing: Counts toward the original user's usage metrics

Concurrent Job Tracking

Cross-pack calls count toward the user's concurrent job limit:

# User has limit of 5 concurrent jobs
# Pack A calls Pack B → counts as 2 jobs total

# In v2: Tracked for observability, not enforced
# Future: May enforce limits at subscription tier level

Error Handling

from huitzo_sdk.errors import PackExecutionError

@command("composite-task", namespace="workflows")
async def composite_task(args: Args, ctx: Context) -> dict:
    try:
        result = await ctx.execute("other-pack", "some-command", args={...})
    except PackExecutionError as e:
        ctx.log.error(f"Cross-pack call failed: {e.message}")
        # e.pack, e.command, e.original_error available
        raise

Best Practices

  1. Check pack availability - Target pack must be installed for the tenant
  2. Handle failures gracefully - Cross-pack calls can fail independently
  3. Avoid circular calls - Pack A calling Pack B calling Pack A will fail
  4. Consider timeouts - Parent command timeout should account for child execution

Transaction Support

@command("atomic-operation", namespace="data")
async def atomic_operation(args: Args, ctx: Context) -> dict:
    async with ctx.storage.transaction():
        # All operations in this block are atomic
        await ctx.storage.save("key1", value1)
        await ctx.storage.save("key2", value2)

        if some_condition:
            raise Exception("Rollback!")  # Both saves are rolled back

    return {"status": "committed"}

Scoped Storage

@command("user-data", namespace="profile")
async def user_data(args: Args, ctx: Context) -> dict:
    # Default: scoped to tenant + user + pack
    await ctx.storage.save("preference", value)

    # Tenant-level (shared across users)
    await ctx.storage.save("tenant:setting", value, scope="tenant")

    # Pack-level only (not user-specific)
    await ctx.storage.save("cache:data", value, scope="pack")

Request Context

@command("with-headers", namespace="api")
async def with_headers(args: Args, ctx: Context) -> dict:
    # Access original request info
    client_ip = ctx.request.client_ip
    user_agent = ctx.request.headers.get("user-agent")

    return {"ip": client_ip, "ua": user_agent}

Best Practices

1. Always Use ctx.log

# ✅ Good: Use context logger
ctx.log.info("Processing started", extra={"items": len(items)})

# ❌ Bad: Using print
print(f"Processing {len(items)} items")

2. Handle Missing Data

# ✅ Good: Use defaults
data = await ctx.storage.get("key", default={})

# ❌ Bad: Assuming data exists
data = await ctx.storage.get("key")
process(data)  # Might be None!

3. Scope Storage Appropriately

# ✅ Good: User-specific data uses default scope
await ctx.storage.save("user:settings", settings)

# ✅ Good: Shared cache uses tenant scope
await ctx.storage.save("cache:exchange-rates", rates, scope="tenant")

Proposed Extensions

The following ctx.* extensions are architecturally specified but not yet implemented. See the linked architecture docs for full specifications.

ctx.resolve — Type-Based Resolution (Proposed)

The component model also describes a type-based resolution helper for dynamic dependency injection. Use named access via ctx.integrations for the common case; reach for ctx.resolve(IntegrationType) only when the concrete integration is selected at runtime.

# pseudocode — type-based resolution (advanced — dependency injection)

@command("sync-crm", namespace="enterprise")
async def sync_crm(args, ctx):
    crm = ctx.resolve(SalesforceIntegration)
    await crm.sync(args.records)

See Component Model — Access Pattern (Q1).

ctx.config — Hierarchical (Proposed)

Configuration with cascading overrides. See Component Model — Hierarchical Configuration.

Note the starting point: no ctx.config exists yet at all — not even a flat one (see ctx.config). The cascade below is the design target, not an enhancement of shipped behaviour.

# pseudocode — hierarchical config access

@command("generate-report", namespace="analytics")
async def generate_report(args, ctx):
    # Resolves through cascade: command -> integration -> pack -> platform
    timeout = ctx.config.get("http.timeout", default=30)

    # Explicit scope access (bypass cascade)
    platform_limit = ctx.config.get("http.timeout", scope="platform")

Cascade order: Platform defaults -> Pack manifest -> Integration config -> Command config -> User/tenant overrides.

ctx.events (Proposed)

Async pack-to-pack communication via the system event bus. See Event Bus.

# pseudocode — event bus API

@command("process-email", namespace="scanner")
async def process_email(args, ctx):
    invoice_data = await extract_invoice(args.email)

    # Fire-and-forget — any subscribed pack handles it
    await ctx.events.emit("invoice.received", {
        "sender": args.email.sender,
        "amount": invoice_data["total"],
    })

Events are tenant-scoped with at-least-once delivery. Handlers must be idempotent.

ctx.files — VFS Evolution (Proposed)

Mountable file system drivers extending the current ctx.files API. See Virtual File System.

# pseudocode — VFS mount access

@command("merge-reports", namespace="analytics")
async def merge_reports(args, ctx):
    # Reads from S3 via mounted driver
    s3_data = await ctx.files.read_csv("/mnt/s3-reports/q1-sales.csv")

    # Default mount (backward compatible — works exactly as today)
    local_data = await ctx.files.read_csv("data/local.csv")

Mount points are declared in the pack manifest. The current ctx.files API is fully backward compatible.


See Also

  • Storage Reference – Deep dive into storage patterns
  • Storage Backends – Backend protocol and implementations
  • Integrations Reference – All available integrations
  • Extensions Reference – Deployment-scoped pack-developer extensions
  • SSH Integration – Remote command execution via SSH
  • Commands Reference – Command definition patterns
  • Error Handling – Exception hierarchy and best practices
  • Components Reference – HuitzoIntegration and component types
  • Secrets Management – Three-tier secrets model
  • Architecture Overview – Deployment modes and system design
  • Component Model – UVM-inspired component taxonomy
  • Virtual File System – Mountable file drivers
  • Piping Protocol – Command composition via pipes
  • Event Bus – Async pack-to-pack communication