Skip to content
chatAgent
Esc
↑↓navigate↵open⌘Jpreview
On this page

Direct Pi Runtime

Direct Pi Runtime

The TypeScript shopping bot runs Pi directly in its RivetKit actor. AgentOS, VM provisioning, child workers and request/response files are no longer part of the runtime. Older AgentOS/Python examples elsewhere in these docs are historical designs, not the current implementation.

flowchart TD
    WA["WhatsApp webhook"] --> Gateway["Node HTTP gateway"]
    Gateway --> Actor["Rivet shoppingAgent per user"]
    Actor --> Pi["Direct Pi turn"]
    Pi --> Store["Controlled Shopify tools"]
    Pi --> Files["Scoped temporary file tools"]
    Actor --> Durable["Conversation, cart and security state"]
    Files --> Scratch["Node-local disposable workspace"]

Sources of truth

  • runtime/src/shoppingAgent.ts: security, full-turn serialization, persistence, idle scheduling and actor lifecycle hooks.
  • runtime/src/agent-runtime.ts: captures provider/store/router configuration and calls the Pi module directly.
  • runtime/src/agent-worker/shopping-agent-worker.ts: callable runAgentTurn, Jev routing, Shopify/file tools, cancellation and structured replies.
  • runtime/src/workspace.ts: actor-ID-hashed directories, file restrictions, active-use leases, expiry and crash recovery.
  • runtime/src/turn-queue.ts: close admission, cancel, then await settlement.

Each turn constructs its own Pi agent from the durable conversation and cart. The model runtime and Shopify configuration are turn-scoped; API keys are passed explicitly, not written into shared process.env. A Pi instance can be collected after a turn, while its session files remain available for follow-ups.

File lifetime

Event Behavior
A reply finishes Pi resources are released; session files remain.
Another message arrives Reuse the actor’s unexpired local workspace.
Actor sleeps Keep scratch files and durable state; release in-memory resources.
Idle expiry Delete scratch files and destroy the actor.
Explicit /api/destroy Stop admission, cancel/await active work, delete scratch, request destruction.
Graceful server shutdown Drain Rivet actors; leave unexpired files for restart continuity.
Crash or forced termination Startup and minute-by-minute sweeping remove abandoned expired directories.
Actor wakes on another host Recreate missing scratch; local files do not migrate with durable state.

The idle window is max(AGENT_IDLE_SLEEP_SECONDS, AGENT_IDLE_TERMINATE_SECONDS): 5-minute sleep and 1-hour expiry by default. Idle is measured from turn settlement, including failures. Scheduled IDs are durable so sleep/wake does not deliberately accumulate new schedules. A stale check must recheck current activity; it cannot destroy an active turn.

Filesystem acquisition, lease release and sweeping are serialized together. An active workspace is never expired by the local sweeper, even if a turn outlives its deadline. Cancellation is cooperative: Pi, router and Shopify requests receive an abort signal, and in-flight work is awaited before the lease is released. There is a 60-second whole-turn deadline in addition to LLM_REQUEST_TIMEOUT_MS per model call.

Lifecycle grace is aligned with that deadline: 65-second action timeout, 70-second actor drain, 80-second registry shutdown, and an 85-second host fallback (Docker allows 90 seconds). If a tool cannot settle during shutdown, the host exits without deleting its active scratch; crash recovery removes it after expiry. These bounds are not permission to delete files beneath a writer.

Cleanup never deletes SQLite conversation/cart records or a remote Shopify cart. The next actor restores its conversation and cart from the persistent store. Identity-change handling remains the separate explicit data-reset path.

Controlled file access, not an OS sandbox

The full agent has three scratch tools:

  • read_workspace_file
  • write_workspace_file
  • list_workspace_files

Paths must be relative to the actor’s workspace. Traversal, absolute paths and symlinks are rejected. File operations are serialized and bounded: 64 KiB per file, 1 MiB per workspace, 100 file/directory entries, eight path components. Cleanup metadata is outside the directory exposed to the tools. No tool changes process.cwd() or exposes shell/arbitrary code execution.

Actors may share a Node process and its OS permissions. These restrictions protect the controlled file-tool surface, not the machine from arbitrary code. If shell/code execution is added, a real security sandbox is required again.

AGENT_WORKSPACE_DIR optionally selects the root. Use node-local storage owned by exactly one runtime process, not a network directory or a root shared by several runners: the active-use lease is process-local. The default is a dedicated OS temp directory scoped to the runtime checkout. Docker uses /tmp/chatagent-workspaces, separate from the durable /data volume. Scratch is disposable and must not hold important uploads or databases.

Rivet Engine storage is also separate from scratch. For multiple local checkouts/tests, set a distinct RIVETKIT_STORAGE_PATH before starting Node: changing cwd or the Engine port does not isolate its database. A managed local Engine can outlive registry shutdown; never sweep its storage as agent scratch. The shopping registry disables the unused first-party Services host.

Build and bridge compatibility

Use Bun for tooling:

cd runtime
bun install
bun test
bun run typecheck
bun run build
bun run start

build compiles the host with TypeScript, then bundles the directly imported Pi module as ESM with its Markdown skills inlined and dependencies external. Node can therefore execute dist/server.js without a Markdown loader. Source development runs directly under Bun.

/api/iso-message is retained only as a deprecated alias of /api/message. It now uses the same actor serialization/security/lifecycle; it does not bypass the actor or run an isolate. Timing output uses processUptimeMs instead of the former vmUptimeMs; host uptime is not turn-startup latency.

bun run benchmark:workers measures resident direct-Pi allocation without provider or Shopify calls. It is not evidence of live concurrent-turn capacity.

Multi-product images

Two or more photos in one reply are sent as one generated image instead of a photo per item, in one of two layouts:

  • Listing (several products): a card per product — photo, name, and price in small text.
  • Collage (several photos of the same product, e.g. “show me more pictures”): photos only, no text; the caption carries the words.

Both are generated per send: rendered images are never cached. This is deliberately a code path, not a cache read.

How it is put together:

  • runtime/src/app/product-image.ts builds the element tree; satori lays it out as SVG (Inter WOFF bundled through @fontsource/inter — satori reads WOFF/TTF/OTF, not WOFF2) and sharp rasterises it, downscaling each photo and embedding it as a data URI.
  • The templates are styled with Tailwind utility classes, including arbitrary values (p-[56px], gap-[32px], rounded-[28px], theme colours from a small @theme block). satori takes inline styles, so scripts/build-listing-styles.ts runs the real Tailwind engine at build time and writes src/app/listing-styles.generated.ts — a class → style map. A class that produces no CSS fails the build, and an unknown class fails tw() at runtime, so a styling typo cannot ship silently. Regenerate with bun run styles:generate (part of bun run build).
  • Satori defaults to box-sizing: content-box (there is no Tailwind preflight), so sized boxes that carry padding or borders declare box-border explicitly.
  • Product names clamp to two lines with an ellipsis and every card’s price sits on a fixed line, so a long name cannot push a price out of the image.

Behaviour:

  • The listing shows every product in the reply (up to four, what the layout handles well); the separate-photo path keeps the WHATSAPP_MAX_IMAGES cap because several separate photos read as spam while one image does not.
  • The agent attaches up to four photos when the customer asks to see a product (and one otherwise), which is what gives the collage its material.
  • WHATSAPP_COMPOSITE_IMAGES=0 restores one photo per product. A reply that does not really list two named products, or a failed render, falls back to separate photos — a composed image is a presentation choice, never a reason to drop a reply.
  • The image is uploaded to the WhatsApp Cloud API and referenced by media id; the reply-to context of that message maps to the first product in the image.

Product photo cache

runtime/src/app/image-cache.ts is a bounded, disk-backed LRU for the source photos downloaded from the store CDN: the same product photo would otherwise be re-downloaded for every customer who asks about it.

Setting Env Default
directory (node-local) AGENT_IMAGE_CACHE_DIR dedicated OS temp dir
budget IMAGE_CACHE_MAX_MB 64 MB
entry TTL IMAGE_CACHE_TTL_SECONDS 7 days
single entry cap IMAGE_CACHE_MAX_ENTRY_MB 5 MB

Entries are keyed by URL, refreshed on read, and evicted least-recently-used when the budget is exceeded; the index is rebuilt from disk after a restart. ImageCache is an interface — the disk LRU is the implementation that ships, and a shared store can replace it without touching callers.

Outbound messages

Every reply leaves through one Effect program (sendReply in runtime/src/app/outbound.ts) driven by the pure plan from planOutbound:

  1. media — one generated image (listing or collage), or the separate photos
  2. the checkout link, when there is one (a cta_url button, sent on its own because mixing it with reply buttons fails delivery with status 131026)
  3. the reply button group, always last

Nothing is sent after the buttons, so the tappable group is the newest message in the chat. The ordering is a property of the plan, and runtime/test/outbound.test.ts fails if a step is added after it. A composed image that cannot be rendered falls back to sending the photos themselves — the reply is never dropped for a presentation failure.

Effect 4 gives each step a typed failure (OutboundError carries the step name and the underlying WhatsApp error) and runs the steps in order; failures stop the remaining steps and are logged with the step that failed. See AGENTS.md → “Learning more about Effect” before changing this code.

The agent layer (switch who answers, live)

Two independent switches, applied to the next inbound message — no redeploy, and every customer texting the WhatsApp number keeps reaching whatever is selected:

Switch Values Effect
profile default + any AGENT_PROFILES entry which Pi agent answers: provider, model, extra instructions appended to the shopping prompt
mode agent | handoff who answers: the shopping agent, or a person

Switch it from the control plane (POST /control/agents {"mode":"handoff"}, {"profile":"claude"}, {"reset":true}) or over the operator bridge (set_mode, set_profile). GET /control/agents lists the current state and the available profiles. The layer is process state, not durable storage: a restart returns to the configured defaults.

Handoff: a person answers

With mode=handoff the agent stays out of the thread and instead:

  1. every customer message is published to the operator bridge (below);
  2. when AGENT_HANDOFF_FORWARD_TO is set, the message is also forwarded to that WhatsApp number, so the person can answer from their own phone;
  3. the customer gets AGENT_HANDOFF_ACK when configured (empty by default — a person usually replies within the same minute, and the bot says nothing it cannot back up);
  4. the customer’s message is recorded in the conversation, as is every reply the person sends, so switching back to agent continues the thread with context.

Operator bridge (WebSocket)

WS /ws/messages?token=<CONTROL_TOKEN> (an Authorization: Bearer header works too; with no token configured the endpoint stays closed).

Server → client

Frame Meaning
{kind:"hello", mode, profileId, profiles} sent on connect
{kind:"event", type:"inbound", userId, text, audio, at} a customer message, published the moment the webhook lands (before batching, before any agent decides)
{kind:"event", type:"reply", userId, text, images, buttons, checkout, suppress, at} what the agent answered, including a suppressed failure
{kind:"event", type:"layer", mode, profileId, changedBy, at} someone switched the agent layer
{kind:"ack", id, ok, ...} result of a command, echoing the client’s id

Client → server ({id?, type, ...})

Command Effect
layer current mode, profile, forward-to number, profiles
set_mode {mode} / set_profile {profile} switch the agent layer
send_text {to, text} send as the WhatsApp number; records the reply in the conversation
send_image {to, imageUrl|dataBase64, mimeType?, caption?} send media, by link or uploaded from base64 (uploads via the Cloud API media endpoint)

The bridge is the manual counterpart of the agent: a person can read the whole conversation and answer with text or photos, and those sends are recorded so the agent keeps context when it takes the thread back.

Telemetry (OpenTelemetry)

Traces and logs are exported over OTLP when a collector endpoint is configured; without one the runtime stays silent (a service should not ship spans at nothing). The configuration contract is the pi-otel extension’s, so a .pi/settings.json otel block works here unchanged, and the environment overrides use the same names.

pi-otel itself is an extension for the pi CLI host (ExtensionAPI from @earendil-works/pi-coding-agent) and cannot load inside the embedded pi-agent-core; runtime/src/observability.ts wires the same span tree, logs signal and precedence directly into the runtime.

{
  "otel": {
    "enabled": true,
    "endpoint": "http://collector:4317",   // or set the env var below
    "protocol": "grpc",                    // or "http/protobuf"
    "headers": {},
    "serviceName": "chatagent-shopping-agent",
    "captureContent": "metadata_only",
    "spanNaming": "legacy",
    "sampleRatio": 1.0,
    "signals": { "traces": true, "metrics": false, "logs": true }
  }
}
Setting Environment override Default
endpoint OTEL_EXPORTER_OTLP_ENDPOINT — required to enable off
protocol OTEL_EXPORTER_OTLP_PROTOCOL (grpc | http/protobuf) grpc
headers OTEL_EXPORTER_OTLP_HEADERS (k=v,k=v, percent-encoded) {}
serviceName OTEL_SERVICE_NAME chatagent-shopping-agent
spanNaming PI_OTEL_SPAN_NAMING (legacy | genai) legacy
captureContent PI_OTEL_CAPTURE_CONTENT (full | no_tool_content | metadata_only) metadata_only
signals.logs PI_OTEL_LOGS 1
signals.traces PI_OTEL_TRACES 1
signals.metrics PI_OTEL_METRICS 0 — accepted, not exported yet
disable everything PI_OTEL_DISABLED=1 —

Span tree per customer turn:

Operation legacy name genai name key attributes
turn pi.interaction invoke_agent <serviceName> route, prompt length, history length, tool count/time, gen_ai.usage.*
provider request pi.llm_request chat <model> request/response model, finish reason, gen_ai.usage.*
tool call pi.tool.<name> execute_tool <name> tool name, call id, error type

Lifecycle records (chatagent.turn.route, chatagent.turn.end, chatagent.turn.error) ride the logs signal. The actor id is hashed before it reaches a span (pi.session.id), and metadata_only — the default — never attaches prompts, replies, tool arguments or tool results. sampleRatio < 1 applies a parent-based trace-id-ratio sampler.

In Docker, set OTEL_EXPORTER_OTLP_ENDPOINT (and OTEL_SERVICE_NAME) in .env; the compose file forwards the whole block. Buffered spans and log records are flushed on graceful shutdown.

Rivet’s engine uses the same endpoint — through a collector

The engine’s OTLP exporter is plaintext gRPC only (its gRPC client is built without TLS), so it cannot reach a TLS endpoint such as Grafana Cloud directly: exports fail with transport error. The compose stack therefore runs an OpenTelemetry Collector (otel-collector.yaml) that receives plaintext gRPC from the engine and forwards it over HTTPS with the credentials:

Rivet engine ──plaintext gRPC──▶ otel-collector ──HTTPS + auth──▶ OTLP endpoint

Both hops are configured from the same variables — OTEL_EXPORTER_OTLP_ENDPOINT for the destination and OTEL_AUTH_HEADER for the credential, as a header value (e.g. Basic <base64(instanceID:token)>). The collector passes it verbatim into its authorization: header; the runtime percent-encodes it for the OTLP wire. Compose points the engine at the collector with RIVET_OTEL_GRPC_ENDPOINT=http://otel-collector:4317. Without a collector, the runtime derives a gRPC endpoint from OTEL_EXPORTER_OTLP_ENDPOINT (signal paths dropped, :4318 → :4317, TLS keeps :443) and sets RIVET_OTEL_ENABLED=1, RIVET_OTEL_SAMPLER_RATIO and RIVET_SERVICE_NAME=<serviceName>-rivet itself; an explicit RIVET_OTEL_GRPC_ENDPOINT always wins and RIVET_OTEL_ENABLED=0 leaves the engine untouched.

Grafana Cloud

Grafana Cloud’s OTLP gateway uses HTTP Basic auth — base64(instanceID:token) — and rejects a bare glc_… token with 401. Point the base endpoint at the gateway (the runtime appends /v1/traces and /v1/logs), select http/protobuf, and pass the header percent-encoded:

printf '%s' "1491357:glc_your_write_token" | base64 -w0   # -> the Basic value
OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp-gateway-prod-ap-southeast-1.grafana.net/otlp
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_EXPORTER_OTLP_HEADERS=Authorization=Basic%20<base64 value from above>
OTEL_SERVICE_NAME=chatagent-shopping-agent

Last updated on October 11, 2026