Skip to content
Back to skills

Agent Runtime

ASecurity

The Laser SDK runtime - `sdk/src/agent/`. Use when changing the `Laser` facade (bootstrap, send_agent, request/reply, producer cache, spawn_subconversation), the typed AGDX producer verbs (`Laser::agdx` -> `Agdx`/`AgdxStream`), the `ChunkAssembler` stream reassembly, the reliable consumer (dedup, retry, DLQ, deadline, undecodable handling), `Agent::builder`/`AgentHandle` shutdown, `Router`, sessions (`Laser::sessions`, `Session`, `SessionLease`, `SessionLayout`, submit, control), or `SessionP...

  • 14 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added October 7, 2026
businesstypescriptpythonrustgotestingapibackend

Works with

  • cursor
  • terminal
  • cli
  • api

Security analysis

A100/100

Scanned November 30, 2026

npx -y skills add laserdata/laser-sdk --skill agent-runtime --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Agent Runtime?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Agent Runtime
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/laserdata-agent-runtime/badge)](https://www.skillsdirectory.com/skills/laserdata-agent-runtime)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: agent-runtime
description: The Laser SDK runtime - `sdk/src/agent/`. Use when changing the `Laser` facade (bootstrap, send_agent, request/reply, producer cache, spawn_subconversation), the typed AGDX producer verbs (`Laser::agdx` -> `Agdx`/`AgdxStream`), the `ChunkAssembler` stream reassembly, the reliable consumer (dedup, retry, DLQ, deadline, undecodable handling), `Agent::builder`/`AgentHandle` shutdown, `Router`, sessions (`Laser::sessions`, `Session`, `SessionLease`, `SessionLayout`, submit, control), or `SessionPolicy`.
---

# Agent runtime

The native TypeScript peer is `foreign/typescript/src/agent`, with contracts, workflows, and real-Iggy runtime tests under `foreign/typescript/test`. The Go peer is the `agent*.go`, `agdx*.go`, `registry*.go`, `router.go`, `session*.go` and `sessions.go` files under `foreign/go/laser`, with handler test helpers in `foreign/go/laser/lasertest`.

`agent/` is the public runtime: how you send, consume reliably, route, and spawn agents. Load [laser-sdk-overview](../laser-sdk-overview/SKILL.md) first. Repo rules in [AGENTS.md](../../../AGENTS.md).

Iggy provides the VSR transport and AGDX command classifier. Agent publish, poll, consumer-group, replay, retry, and dead-letter paths use standard Iggy commands. Managed presence, registry enrichment, fenced workflows, and session reads use the non-replicated extension path and remain capability-gated by the connected Iggy server.

## STOP and ask the user before

- Changing public signatures: `Laser::{send_agent, request, bootstrap, spawn_subconversation}`, `AgentHandler::handle` (takes `&AgentMessage` + an `&AgentCtx<'_>`), `AgentCtx`, `Agent`/`AgentHandle`, `ReliableConsumer::run`. These are the API users code against.
- Both `Serial` and `SerialPerPartition` read through `ConsumerGroup::consumer()` with `CommitPolicy::Disabled` and commit only the handled prefix. Changing this policy requires explicit authorization. Do not weaken at-least-once handling.
- Changing dedup-before-handle ordering or the DLQ behavior.

## Key files and symbols

- `laser.rs` - `Laser` facade.
  - `send_agent`: encode provenance -> headers through the shared wire encoder, resolve the partition at the send boundary from the stream's declared `SessionLayout` (`partitioning.rs`: a command by its addressee, a reply by its requester, everything else by session), send via a per-topic cached producer, which never creates its stream or topic, so a missing one fails as stream-or-topic not found ([client behavior](../../../docs/client-behavior.md#publication-and-reads)). A cached producer is rebuilt once after a missing-resource publish error.
  - The producer cache stores `Arc<OnceCell<Arc<IggyProducer>>>` values in a `DashMap`, keyed by stream and topic. Hold the map lock only to obtain the cell. Run `producer.init().await` through the cell after releasing the map lock.
  - `request` uses `ReplyHub` in `agent/replies.rs`. It creates a fresh `correlation_id` and records it in `agdx.corr`. `AgentCtx::respond` and `reply_provenance` echo that correlation, not `idempotency_key`. A conversation ID alone cannot match a request. Call `subscribe(correlation)` before publication and `ticket.wait(timeout)` afterward. One reply reader serves all waiters. It follows the reply topic with one held fetch per primary (`poll::TopicFollower`) only while a waiter exists: `ReplyHubInner::forget` wakes the dispatcher when the last waiter leaves, which drops the follower at once so the upstream reader cancels its fetch and an idle client holds nothing on the server. Each waiter carries `ExpectedReply { session, requester }`: a record completes it only in the request's session, only as a `Response` or `Error` when enveloped, and only when addressed to the requester if the request named one. The request's own committed address never completes it.

AGDX contracts and workflows use a tail-seeded `AgentReplyReader`. `poll_contract` and `next_agdx_match` apply their pickup, terminal, and signature rules.
  - `spawn_subconversation(&Provenance) -> Provenance`: fresh `conversation_id`, `parent_conversation_id` = parent's, `root_conversation_id` carried through.
  - `bootstrap(partitions, TopicRetention)`/`ensure_topic`/`ensure_stream`: idempotent create-if-missing. `bootstrap` creates `agent.sessions` under the given retention (`TopicRetention::default()` keeps records one day, Python and TypeScript default to one partition and that retention), `agent.heartbeats` with a one-hour expiry, and `agent.streams`, `agent.memory`, `agent.dlq`, `agent.audit`, `agent.workflow_journal`. It never creates `agent.control` (operator-only, provisioned) or `agent.registry` (the first card or registry fact ensures it with one partition). A pre-existing stream is used as it is. It also warms a producer per created topic concurrently.
- `consumer.rs` provides public `ReliableConsumer::run` and private `ReliableWorker`. Decode each record first. `dead_letter_undecodable` preserves invalid payloads with `DeadLetterReason::DecodeFailed` and keeps the original conversation. Classify each record with the wire `classify` (enveloped) or `classify_generic` (no envelope). Only `Dispatch::Work` for the handler's `operations` reaches the handler. `Observational`, `Reply`, `Lifecycle`, and `Foreign` are skipped and committed, and `Control` goes to the control follower (`control.rs`, `ControlBook`, `Session::pending_control()`). The author is never a discriminator. Then apply stale-fence rejection, deadline handling, and duplicate suppression, in that order, so neither a stale-holder replay nor an expired copy claims the idempotency key a resend needs. Expired fence-map entries are removed after its soft limit. A command with metadata `submitted = true` marks its session working on pickup (`Session::pick_up`) and holds a `SessionLease` while the handler runs. The handler call runs under `catch_unwind`, and a panic becomes a non-retryable `HandlerConfig` error that dead-letters as `Rejected`.

Retry `is_retryable()` handler failures through `max_attempts`. `LaserError::Rejected` and `LaserError::HandlerConfig` do not retry. Exhaustion publishes an `AgentDeadLetter`. Its reason is `DecodeFailed`, `DeadlineExceeded`, `Rejected`, or `RetryExhausted`. It includes attempts, full `LogPosition`, and the original payload. Preserve provenance, clear the deadline, and set `agdx.ct = cbor`.

`dead_letter` and `dead_letter_undecodable` call `publish_dead_letter`. A failed required publication reports through the optional `DeadLetterSink`, fails the worker, and leaves the source offset uncommitted. Ordered `AgentMiddleware` runs `before_handle` once before retries and `after_handle` after each attempt. A middleware rejection bypasses the handler and uses the dead-letter path.

`run` reports readiness after joining. Reads are held by the server for up to `max_wait` (`DEFAULT_MAX_WAIT`, 5 s, configurable), and a landing record ends the wait at once. Delivery runs on `ConsumerGroup::consumer()` with `CommitPolicy::Disabled`, so a server that resolves group policies reads through the group-aware engine. `DeliveryEngine::resolve` decides once per run: a server without group-aware reads, or a `Laser` with no connection string (a caller-supplied client, warned about when a managed backend is ready), reads natively. The group defaults to `ConsumerGroupName::for_agent(id)`, one group per agent id. It is fallible (`TryFrom<&AgentId>` too), because an agent id can be 256 bytes and a group name at most 255, and `spawn` fails the agent instead of panicking. `DeliveryEngine::bind_addressee` binds it to `addressee_filter(me)` (`agdx.to In [<agent>, "*"]`), saved under `ADDRESSEE_FILTER_NAME` (`agent-addressee`), on `agent.sessions` and `agent.control` only, before the first read, when the server serves native filters and the catalog, and a group bound to another filter is refused. In every other case the group stays unbound and the client classifies. An uncertain capability probe is an error. Retryable poll failures (stale membership, unavailable catalog, transient transport) reopen the consumer with backoff. Others (conflict, source changed, filter faults) stop the runtime. `Serial` handles records in order on the task that owns the consumer and commits each handled record.

`SerialPerPartition { max_partitions }` sends work to bounded per-partition lanes. Lanes report completions and the owning task commits them. Global record and byte semaphores bound queued work. Lanes run concurrently across partitions and serially within each partition. A new partition at the lane cap closes the lanes holding no record (`retire_idle`), or waits for one to drain while committing the others' completions and honoring the stop signal, so no record runs on the polling task. A failed lane stops its successors and ends consumption before a later offset can pass it.

Shutdown stops new polls and drains accepted work. The serial path stops the Iggy loop, and the lane path closes its senders. `shutdown_grace` defaults to 30s. Exceeding it returns `LaserError::Timeout`, each lane finishes the record in its hands and takes no further one, and the records left in the queues are read again by the next owner. `AgentHandle::abort()` stops immediately.
- `Laser::redrive_dead_letter(&AgentDeadLetter)` in `agent/laser.rs` reads the original source record and republishes its body and headers. It uses numeric stream and topic IDs and conversation routing. Missing or expired source records return `LaserError::Invalid`.
- Use `message.header.offset` in `AgentMessage::from_received`. `received.current_offset` is the partition head and can be identical for several messages in a batch.
- `from_received` uses `is_agdx` and `agdx.av` to detect an `AgentEnvelope`. It exposes the result through `AgentMessage.envelope` and dead-letters decode failures as `DecodeFailed`. `provenance_from_envelope` supplies conversation, source, target, idempotency, and deadline values for runtime decisions. Non-AGDX records use `Provenance::try_from` with `envelope = None`.

Use `envelope.unmet_requirements(understood)` with the supported `agent::features` bits. Reject or dead-letter records that require unknown features. No bits are currently defined, so valid records use `must_understand == 0`.
- `Provenance::try_from(&IggyMessage)` matches keys first and fails-not-skips: a known provenance key with a non-string value is a decode error, while foreign/unknown keys are ignored. The AGDX typed headers (`agdx.ct` u8, `agdx.av` u32, the `Uint128` routing duplicates) coexist on one record because they are foreign to the provenance dictionary, not because non-string values are skipped.
- `Deduplicator` provides asynchronous `observe(key) -> bool`. `SlidingWindow` uses the bounded local `DedupWindow`. Applications can supply another implementation through `Agent::builder` or `ReliableConsumer`. `StateStore` and managed `Kv` can supply persistent storage. `warm_dedup` (`warm_dedup_window` in `consumer.rs`, TypeScript `ReliableConsumer.warmDedup`) preloads the configured implementation from the committed tail of each partition, keeping each keyed record as a `WarmSeed` (key, position, server timestamp, deadline), and `refills` decides per record under `WarmDedupPolicy` (`DeadLetters` default, `Unexpired`, `All`, strum snake_case, TypeScript `WarmDedupPolicy` const, Python `warm_dedup_policy=`). `DeadLetters` reads `agent.dlq` once through `expired_copies`, only when a seed has a deadline, from the oldest such seed less `DEAD_LETTER_CLOCK_MARGIN_MICROS`, at most `dedup_window` records per partition, and leaves out positions a `DeadlineExceeded` dead letter names. An incomplete read (cap, retention, error) warns and falls back to `Unexpired`, never fails the start. A seed without a deadline always refills.
- `Laser::capabilities()` returns grouped `Capabilities` from `capabilities.rs`. Original Apache Iggy defaults to `OPEN`. `AGDX_HELLO` and `refresh_capabilities()` discover current support. A `BackendAnnounce` with `ready=false` retains descriptive versions and topology but must not enable managed operations.

Builder capabilities remain the additive seed during refresh. `Laser::with_capabilities(..)` is an authoritative handle-local override. Inspect capabilities before using managed operations. Groups include `managed`, `query`, `kv`, `graph`, `forks`, and `a2a_gateway`. Nested values include `capabilities.kv.available`, `capabilities.kv.cas`, and `capabilities.query.consistency`. `examples::managed_feature_ready` demonstrates this pattern.
- `Agent::builder` requires identity, input topic, and handler. It also accepts `respond_on`, `max_wait`, `inbox_route`, and `capabilities`. Runtime controls include `dedup_window`, `retry(RetryPolicy)`, `verifier`, `signing_key`, `shutdown_grace`, `concurrency(ConcurrencyPolicy)`, `middleware`, `on_dead_letter`, and `governor`. `spawn(Laser)` returns `AgentHandle`.

`InboxRoute::Advertised` is the default, and the chosen route passes to the consumer and context. Non-empty capabilities trigger `advertise` before consumption. It publishes a card through `Laser::publish_card` and can call `advertise_presence` when supported. Presence is query-gated and best-effort except `PresenceConflict`. One connection can advertise one identity.

`ack_on_pickup` defaults off and requires `respond_on` (spawn fails with `LaserError::Config` without it). When enabled, a consumer publishes `Working` on `respond_on`, addressed to the command's source, before handling a command. A dead-lettered correlated command is answered on `respond_on` with an AGDX error carrying `dead_letter_reason`, and a failed dead-letter publish is retried in place on the consumer backoff before the consumer stops with the record uncommitted. A spawned agent with capabilities advertises through the hidden `Advertisement` (`start` before the consumer runs, `withdraw` after, never wrapping the run future): its card names its inbox, carries a ttl of three heartbeats, is republished every heartbeat, and is withdrawn on a graceful stop. `ready()` waits for group membership and polling readiness. A runtime that stopped first (a `PresenceConflict` from `Advertisement::start` for a second advertising agent on one connection) makes the first `ready()` return its error, a later one `HandlerConfig`. Python `PyAgentHandle` (`wait_ready`) awaits the task when the ready channel closes and keeps the typed `PyErr` for every later `ready`, `shutdown`, `join`, and `__aexit__`, as TypeScript's settled promise does. A run that ends cleanly before ready reports `HandlerConfig("agent stopped before it became ready")` in all three: Rust from the taken task, Python from `wait_ready`, TypeScript by rejecting `readyPromise` with `stoppedBeforeReady`, which `shutdown` and `join` throw again once a wait reported it (`stopReported`). `shutdown()` drains within `shutdown_grace`, `join()` returns the task result, and `abort()` stops immediately. Dropping the handle signals a graceful shutdown and stops periodic consolidation.
- `../govern.rs` - effect-boundary policy. `QuorumGovernor` runs voters concurrently. Every mandatory voter must affirm. Mandatory errors, empty sets, invalid thresholds, duplicate names, and conflicting body replacements block. Non-mandatory errors abstain. `SwappableGovernor::swap` returns the replaced policy and `current` reads the active one.
- `../swarm.rs` - replay-safe coordinator fold. `observe` drops unattributed evidence and deduplicates by `decision_id`. Latest evidence is selected by `(at_micros, decision_id)`.
- `../crash_context.rs` - combines already-read journal, dead letter, and policy evidence. `summarize` bounds and escapes untrusted text so payload control characters cannot forge lines.
- `../intent.rs` - SDK typed records, not AGDX wire. `Intent::builder().build`, `Vote::cast`, and `decide` are fallible. Construction and replay validate voter sets, thresholds, deadlines, and body digest. Ballots are time-bounded by the `ObservedVote` server timestamp the reader supplies, never the voter's claim, and canonicalized, every mandatory voter must allow, and `Decision::authorizes` verifies id, digest, and policy version before an effect. Names remain claims unless signing or topic ACLs authenticate authorship.
- `AgentCtx` supplies `respond`, `reply_on`, `send`, `request`, `respond_input`, `spawn_subconversation`, and `laser` and `message` accessors. It carries the selected agent identity, `respond_on`, and `inbox_route`. Replies preserve correlation and use the agent signing key when configured.

`fan_out(selector, payload, GatherPolicy, deadline) -> Gather` resolves capable agents and sends each branch to its inbox. Replies return through the orchestrator reply topic. An unresolved inbox produces a branch failure, not a shared-topic fallback. `approval_gate(approver, reply_topic, prompt, timeout) -> ApprovalGrant` asks `approver` through `Agdx::input_reply`, accepts only that approver's reply, and reports rejection as `Rejected`. `AgdxSend::with_grant(&grant)` carries the grant to the governor, so a step-up in its conversation proceeds. With a pause runtime and `reply_topic` equal to the consumer topic the gate parks: `ApprovalSlot` (hidden, shared with the Python context) carries the interrupt, `deliver` parks the record through `PauseRuntime::park_approval` under the prompt position, `hold` parks the session's later work behind it, and a reply with an approval correlation (`approval_correlation`, tag `0xa6a6`) resumes it through `resume_approval` and `Replay::resume`. `Replay::resume` re-enters `deliver` with the decision, which skips every gate the record already passed. Keep `deliver` one function and await the consumer run directly rather than inside a wrapper future: each nested poll frame adds its temporaries to the worker stack, and the debug Python extension, on 2 MiB tokio worker stacks, overflowed with a SIGSEGV when both had an extra layer. Expiry rides a timer and `reconcile`.

Python `PyAgentCtx` in `foreign/python/src/agent_runtime.rs` exposes these operations. Each call rebuilds the Rust `AgentCtx` (`laser_sdk::testing::agent_ctx` plus the hidden `with_runtime_state`) because Python classes cannot retain the borrowed one, so Python replies take the Rust reply paths.
- `Laser::agdx(topic, source, conversation)` creates `Agdx`. Its `command`, `respond`, `emit`, `status`, and `fail` methods return `AgdxSend` builders. They check the envelope at `send()`. `request_input(reply_topic, prompt, timeout)` creates a fresh interrupt correlation, publishes an `input-required` task status and the prompt as an `input_request` command (only an agent listing `input_request` among its operations receives it), and waits for its response. The prompt is addressed to every agent. `request_input_from(target, ..)` addresses it to one agent and accepts only its reply (Python `request_input(..., target=)`, TypeScript `requestInput(.., { target })`). An error reply returns `LaserError::Rejected`. Configured verifiers reject unsigned or invalid replies.

`stream(correlation, purpose)` creates `AgdxStream`. The opening chunk carries purpose and deadline, `DEFAULT_CHUNK_ABANDON_MS` after opening unless set. Each write assigns a sequence once its chunk is published or buffered, a failed flush keeps the buffered chunks, and `finish` or `fail` supplies the terminal. `reassemble_channel` ends a stream with no terminal past that deadline `abandoned`. `.buffered(max_chunks, linger)` groups records, including the terminal, without a background task. `Agdx::assemble` is shared by individual and buffered sends.

`sdk/src/batching.rs` supplies `topic.batching()` for general records. It bounds records, bytes, and delay, and requires one partition key per handle. Size-triggered flush runs inline to apply backpressure. A failed linger-timer flush never stops the timer. Its failure is kept and returned by the next `send()`, `flush()`, or `close()`. A `send()` that finds it refuses its own record and adds it to the unconfirmed records. `flush()` and `close()` drain the queue first. Several kept failures become one `LaserError::PublishFailed` that lists the records of every failed batch. Drop flushing is best-effort and logs failures.

Sends attach the header block from the shared wire encoder: `agdx.ct`, `agdx.av`, the conversation as a canonical Crockford string, `agdx.parent_conv` and `agdx.root_conv` for a child session, the author `gen_ai.agent.id`, and `agdx.to` with the target or `*` on a shared session topic. Partition routing uses the canonical conversation string unless the declared layout places addressed work on the addressee's partition. `AgdxStream::write` rejects bodies above `MAX_CHUNK_BODY_BYTES` before publication and advances the sequence only after success. The guidance constants are `DEFAULT_CHUNK_FLUSH_BYTES`, `DEFAULT_CHUNK_LINGER_MS`, and `MAX_CHUNK_BODY_BYTES`.
- `ChunkAssembler` in `assembler.rs` applies chunks in order and counts discarded duplicates. A gap creates a local `gap` terminal. Records after a terminal are dropped. `abandon()` creates a local `abandoned` terminal. `StreamEvent::{Body, Finished, Failed}` reports results without I/O or a clock.
- `router.rs` - `Router::{To, ToPrincipal, Broadcast, ToCapable, AllCapable}`. `ToPrincipal` and `CapabilitySelector::principal(PrincipalId)` require the selected live presence to carry that server-authenticated principal, a missing or foreign claim is `RoutePrincipalMismatch` (Forbidden, non-retryable). Capability policies rank only the principal-filtered candidates. `InboxRoute::{Advertised, Fixed(topic)}` turns a resolved target into the topic to address: `Advertised` resolves live presence, `Fixed` uses a caller-owned topic. A route resolves within the caller's stream, cross-stream addressing is deferred federation.
- The AG-UI helpers in `../agui.rs` ride session state: `publish_state_snapshot(source, conversation, state)` replaces then snapshots, `publish_state_delta(source, conversation, patch)` patches, and `reconstruct_state(conversation)` folds the lane first through `SessionState::current_view` and reads the managed state view only when the lane fold is incomplete and the view is not behind it. A fresh `SessionState` handle seeds its revision from the folded lane before its first write.
- `Laser::agent_registry` creates `AgentRegistry` from cards and optional live presence. `refresh` selects current `RegisteredCard` values and expires old cards by `ttl_micros`. `resolve(skill, now)` selects available agents. `RegistryCache` stores cards, quarantines, presence, and cursor offsets per data stream so reads resume incrementally.

Presence uses `refresh_presence`, with a cache lifetime of about 2s. `Laser::advertise_presence` and `clear_presence` use `AGDX_SET_CLIENT_METADATA`. `Laser::client_metadata()` reads paged discovery data. These methods require `query`. `PresenceEntry` retains the authenticated `user_id`. `inbox_for_principal(agent, user_id)` requires that identity, while `inbox_for(agent)` resolves the claim alone.

`Laser::quarantine(operator, agent)` appends a status fact, and `apply_quarantine` excludes it from `resolve`. `is_quarantined` reports the state. `Laser::unquarantine(operator, agent)` reverses it. Registry-topic permissions control these writes. With `sign` and `LaserBuilder::verifier(Arc<KeyRegistry>)`, `quarantine_signed` and `unquarantine_signed` also require valid operator signatures.
- `contract.rs` - `Laser::contract(Router) -> ContractBuilder` resolves one target and watches pickup plus terminal. With a verifier enrolled, plain, invalid, and wrong-identity replies are ignored. A principal-bound route binds verification to the same authenticated principal, a claim route binds to the target's enrolled identity. Accepted replies carry `AgentMessage::verified_principal`, and scatter preserves it per branch. Python `contract` returns a `Contract` (`Completed(reply)`, `Failed(reply)`, `NotConsumed()`, `TimedOut()`, the reply on `.reply`) whose reply carries the verified principal, and `scatter_report` returns a `ScatterReport`. `scatter` stays a body-only convenience. Scatter and fan-out take a required deadline and a `GatherPolicy` in all three SDKs (Python `gather=`), refuse `Quorum(0)`, and gather through `ctx.rs` `gather_branches`, so `ScatterReport` and `Gather` carry `cancelled` and `satisfied`. A contract waits on the shared `ReplyHub` (`replies.rs`, `ReplyTicket::next_within` and `consumed`) under the `ExpectedReply` session and addressee rule, mints its command record id first and carries it as `ExpectedReply::command`, so an expiry answer caused by another copy of the request settles neither the wait nor the resume scan, stamps `deadline_micros` as the earlier of the expiry and the completion deadline, and fails a child session whose command did not publish. Contracts default to a 30-second deadline in all three SDKs and take `expire_if_not_consumed`, `reply_on`, `conversation`, `fence`, `parent(parent, root)` (run as a child session: submitted start before the command, ended by the outcome), and named-agent routing (Python `agent=`, TypeScript `expireIfNotConsumed`). `Laser::agent(id)` returns `AgentScope` in all three.
- `Laser::workflow(name)` creates `Workflow`, with `budget(WorkflowBudget)`, `inbox_route`, `step(label, Router, StepFn)`, `step_local(label, StepFn)`, and `run`. A local step (`Step.target == None`) runs its body in process inside the step deadline, journals only `StepCompleted { agents: [] }`, opens no child session, compensates in process, and refuses `exclusive`. `run` bootstraps the stream with the defaults when `agent.sessions` or `agent.workflow_journal` is missing (`run_topics_missing`), then starts again once. `WorkflowOutcome` carries `outputs`, `run_id`, `completed_steps`, `status` (`SessionStatus::Completed`) and `text(label)`. `StepFailed` carries `target` (`route_text`) and `deadline_ms`, and its text names them for a timed-out step. The run is a root session started with `sessions().start().with_id(run_id)`, and every step and compensation is a child session whose id derives from the run (`{run}/{label}/{attempt}`, `{run}/{label}/compensate/{n}`, exclusive steps keep `{run}/{label}`). `StepHandle` supplies `after`, `verify_with`, `exclusive`, `exclusive_in(namespace)`, `on_timeout`, `deadline` (30 s default), and `compensate_with`. `run()` validates the whole configuration first, orders dependencies, passes outputs through `StepContext`, enforces the `WorkflowBudget`, verifies results inside the step deadline, and records completion. The journal holds `RunStarted`, `StepDispatched { label, attempt, reply_from }`, `StepCompleted { label, output, agents }`, and `StepCompensated`, replayed whole through `ContextAssembler::replay`. A dispatch reuses `Dispatch::new(run, label, attempt)` for its conversation, correlation, and idempotency key, and a resumed one scans the reply topic from `reply_from` (`Laser::agdx_reply_reader_from`) before sending. Every step failure is `LaserError::StepFailed { run, step, reason: StepFailure }`, a resume of a shortened journal `LaserError::JournalTruncated`. Failure compensates every step with an effect in reverse order, to the agents that ran it. An `all_capable` step succeeds when at least one dispatched agent completes.

Exclusive steps require `kv_fenced_leases` and a unique holder per assignment. The lease lasts 15 s, a `KvError::LeaseHeld` on acquisition (a crashed holder's live lease) is retried inside the step deadline, and a `LeaseGuard` releases the lease when the run future is dropped. The default coordination namespace is `WORKFLOW_FENCE_NAMESPACE`, or `agdx.workflow.fence`. `exclusive_in` selects the namespace shared with the handler `Kv::cas_fenced(target_key, fence_namespace, run_id, token)` call. Renew halfway through the granted lifetime over the coordination connection, repeating an ambiguous renewal under its prepared identity until the earlier of the lease's `valid_until` and the workflow deadline, then fail with `LeaseLost`. Retain the lease through verification and the completion journal write.

`OnTimeout::Reassign` reacquires only after release, so the next holder receives a greater fence. Failed renewal or release must stop the workflow. Keep the command conversation derived from `run_id` and step label. Reject reassignment on non-exclusive steps. The handler must use fenced CAS to protect external state.

Every step boundary checks `Session::cancel_requested()`, which reads this session's records on `agent.control`, then compensates and returns `LaserError::Cancelled`. After it, `Session::budget_breach()` (behind `Session::over_budget()` in `budget.rs`) compensates and returns `LaserError::BudgetExceeded`, and any `BudgetExceeded` ends the run session failed with `SessionEnd.reason = "budget"`. The run session ends by the outcome: completed, canceled, or failed. `AgentMessage::body()` supports AGDX and ordinary agent messages. The `WorkflowBudget` (tokens, wall-clock, invocations) is separate from the wire session `Budget` (tokens, cost) on a session start.
- `session.rs` defines `SessionPolicy::{PerCall, PerUser}`, `TopicRetention` (refuses never-expire with no size bound, `expire_after(age)`), `SessionLayout::{Shared, PerAgentTopic(map), PerAgentPartition(map), SinglePartition}` (the per-agent topic map moves addressed `agent.sessions` work onto each declared agent's topic, see `partitioning.rs`), `SessionConfig` (stream, layout, 5-minute idle timeout, 60-second heartbeat, `register_source` on, `fail_on_dead_letter` off, memory namespace, context bounds, SDK info), and `derive_session_id(stream, namespace, label)`. `Laser::sessions()` and `sessions_with(SessionConfig)` return `Sessions`. A declared layout holds for every later send on that stream through the connection.

`Sessions::create(label)` and `start()` return a `SessionBuilder` (`agent` required, `namespace`, `parent(parent, root)`, `with_id`, `idle_timeout`, `budget`, `tag`). `begin()` writes `status(session, Working)` with a `SessionStart` body on the lane and returns `(Session, SessionLease)`. `open(id)` is a lens with no I/O, no lease, and no author until `as_agent`. `Sessions::bootstrap(partitions, retention)` bootstraps and, when the server announces `sessions` and `register_source` is on, publishes `RegisterSessionSource { stream, topics: All }`. A refusal is a warning and `registered: false`.

`Session::{end, fail, cancel}` share one `TerminalIntent` latch across clones: the first verb fixes state, body, and record id, a retry resends that record, and a different verb is `Invalid`. `end` snapshots changed state first, through `SessionState::snapshot_if_changed`, and every snapshot (`snapshot`, the automatic one every 64 deltas, the one before `end`) first checks `holds_current`: a seeded handle refolds `current_view` and writes only when revision, document and, when both know it, head match its cursor, since `write_delta` counts a delta that may have been stale. Otherwise `snapshot` fails with `SessionError::Stale`, the other two skip, and the cursor reseeds (TypeScript `holdsCurrent` with `equalJson`). The document check is `laser_wire::agent::equal_json`, which compares numbers by value, so `1.0` equals `1`. `SessionState::get` uses the same comparison: on a complete fold a snapshot counts only at the reached revision with a document equal to the folded one, and is skipped otherwise. `run(lease, work)` catches an unwind, writes a failure with `detail.panic = true`, and resumes the panic. `append` takes a typed envelope for this session only. `context`, `checkpoint`, `turns_at`, `turns_since`, `state_at`, and `replay` read `agent.sessions` and return `SessionTurn { display, message }`.

`session_ops.rs` holds `assemble(policy) -> AssembledContext { fragments, manifest, text() }` (no write), `model(request, assembled) -> ModelCall` and `tool(name, args) -> ToolCall` (commands addressed to the writing agent with metadata `recorded = true`, so `classify` keeps them observational and the agent never handles its own recorded calls, one correlation per logical call, `complete`/`fail` write the result with `duration_micros`), `record_model_call`, `record_retrieval`, `record_compaction`, `state() -> SessionState { set, patch, snapshot, get }` (deltas with `base_revision`, `op_id` and `base_op_id`, the cursor's head, seeded from the view's `head_op_id` and set to the handle's own last delta, a snapshot every 64 deltas and before `end`, an Iggy-only fold `fold_state` in `get` that reports `complete` and `head_op_id` and marks a delta whose `base_op_id` is not the head stale, so a handle that lost a race writes stale deltas until it reseeds), `kv(ns)`, `linked_graph(name)`, `linked_memory()`, `reference()`, `redact(fn)` (`default_redact` drops `authorization`, `api_key`, `token`, `password`, `secret`, `cookie`), `acting_on(source)`, `cancel_requested()`, `Sessions::submit(agent, input) -> SubmitBuilder` (`id()` names the session before `send`, a failed command publish ends the session failed, a labeled canceled session is refused with `LaserError::SessionEnded`) `-> Submitted { session, correlation }`, `SessionBuilder::begin` (refuses an ended labeled or explicit id with `LaserError::SessionEnded`) and `resume` (reopens a completed or failed session, the index treats its start record as a resume), and `Sessions::control(stream, id).as_operator(op).{pause, resume, cancel, force_cancel}` on `agent.control`.

`session_reads.rs` holds the managed reads: `Sessions::{get, list -> SessionListRequest, events -> SessionEventsRequest, state, links, sources, changes, watch -> SessionWatch}` and `Session::status()`. List and events page by `page(n)` (1-based) and `results(n)` and reply with `total_pages`, `total_results`, `page`, and the walk's bound `as_of` and `series`, never a cursor. `as_of(as_of, series)` passes the first page's bound back on later pages, so the walk holds the sessions created and events folded up to it, newest created first for a list. `changes(page, results)` pages the dense change sequence ascending, page `p` of size `r` holding `(p - 1) * r + 1 ..= p * r`, with `floor` the oldest retained sequence. `watch` starts with one read of page 1 and follows from `total_results + 1`, rereading its page until it fills, resyncs on a new `series`, a `floor` past its next sequence, or a truncated row, refuses a zero interval, and `SessionWatch::stream()` is its `futures::Stream`. Every read is gated on `capabilities().sessions` and decodes `SessionReply` (an `Err` becomes `LaserError::Session`). The file also holds `Laser::read_at(&SourceRef)`, a standard single-record poll that checks the topic generation and the returned offset. `control.rs` holds the runtime's `ControlBook`: the consumer follows `agent.control`, folds a session's retained control records on first sight, and `Session::pending_control()` returns `PendingControl { pause_requested, cancel_requested }`. The runtime never interrupts a handler. `SessionControl::signed_by(key)` (feature `sign`) signs control records, and untargeted records on `agent.control` carry `agdx.to = *`. `Agent::builder().sessions(SessionConfig)` sets the configuration the runtime applies, including `fail_on_dead_letter`. `budget.rs` holds `Session::over_budget()`: the index's `SessionInfo.over_budget` with the `sessions` capability (a `NotFound` or `NotRegistered` session falls back), otherwise a fold of the retained lane, the first start record's budget against the summed `usage` of every enveloped record. The consumer's `BudgetGate` runs after the pause gate for an agent with an id, only with the `sessions` capability, reading the index once per session per poll batch (keyed by the partition's head offset). Work for a session over its budget fails the session once through a latched lens with reason `budget` and is committed without reaching the handler. The runtime never folds the lane per record on open Apache Iggy.

`pause.rs` holds the pause and resume runtime. The control follower reads every `agent.control` partition directly from a tail captured by a bounded startup scan, outside any consumer group. `SessionControl::pause()` writes `SessionPauseRequest { participants }`, from `participants(..)` or derived from the lane. A named participant acknowledges with `status(session, Paused)` and `SessionTransition.acknowledges` set to the request position, an unnamed agent acknowledges when it first holds work. Work for a paused session is parked before commit as `event(session_parked)` with `SessionParking { source, role, request }`, and after the resume each held record is handled before new work and closed with `session_unparked`. Cancel while paused leaves held records unhandled. `Session::parked()` returns `ParkedRecords { records, complete }`. Recovery runs a bounded lane scan at startup and after every rebalance or reopen and reports incomplete recovery. The runtime never interrupts a handler. `Session::signed_by(key)` signs the terminal record, `SessionControl::signed_by(key)` the control records.

`lease.rs` keeps a per-connection lease map keyed by stream name, stream creation time, and session. The heartbeat task publishes one `status(progress)` per stream per interval on `agent.heartbeats` with a `SessionHeartbeat` body that names the stream creation time in `stream_generation`, split at `MAX_HEARTBEAT_SESSIONS`. A reader ignores a heartbeat of another stream generation (`SessionHeartbeat::counts_for`), since a stream created again reuses the name and ids. `AgentCtx::session()` returns the handled record's session as the handling agent, acting on the handled record, with no lease.
- `laser_sdk::testing` in `../testing.rs` provides `agent_message(payload, provenance)` and `agent_ctx(&laser, &message, agent, respond_on, inbox_route)`. These construct handler inputs without a live consumer. A handler needs a server only for I/O methods it calls. Python exposes equivalent owned objects through `foreign/python/src/agent_runtime.rs`.
- `state.rs` - `ConversationState::load(laser, conversation, topics, bound, init, fold)` under an explicit `ReplayBound`, plus `load_with(store, ..)` seeding from a `SnapshotStore`. See [context-and-memory](../context-and-memory/SKILL.md).

## Rules specific to this area

- Both schedulers read one `ConsumerGroup::consumer()` with `CommitPolicy::Disabled` and commit only the handled prefix, from the task that owns the consumer. Never commit queued successors after a handler failure or a failed dead-letter publish. A bound group must never fall back to native polling after an error. Do not add a second Iggy transport or standard consumer implementation.
- Returning `Ok(())` from the wrapper permits the serial committer to store the source offset. Skip, dedup, deadline, and successfully published dead-letter paths return `Ok(())` on purpose. A required dead-letter publication failure returns `Err` and must leave the offset uncommitted.
- Anything that takes a topic and needs an `Identifier` on a poll/get path uses `AgentTopic::as_identifier()`. Produce/consumer-group calls take the `&str` name (`topic_string()`).

## Review smells

- A lock held across `.await` (especially the producer map or dedup).
- `request` rescanning from offset 0 each poll instead of advancing a cursor.
- A spawned task whose error is dropped (use `AgentHandle::join`/`shutdown`).
- Dropping `AgentHandle` while the agent should keep running. A dropped handle signals a graceful shutdown, so hold it until `shutdown()` or `join()`.
- Undecodable messages silently skipped instead of dead-lettered.
- A permanent / bad-input failure retried `max_attempts` times instead of returning `LaserError::rejected(..)` (immediate DLQ).
- Assuming a premium capability is present without checking `Laser::capabilities()`.
- A handler path that treats a reply, status, event, or record for another agent as work, or that keys dispatch on the author.
- A session record sent off `agent.sessions`, or a control operation sent anywhere but `agent.control`.

## Client defaults

Connect budgets, publish timeouts, retries, and failure reports have one owning page each: [connect timeout and cleanup](../../../docs/connect-timeout.md) and [publish recovery](../../../docs/publish-recovery.md). Shared client behavior is in [client behavior](../../../docs/client-behavior.md).

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in business →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.