Work on the native TypeScript Laser SDK, its wire fixture port, Apache Iggy adapter, Node runtime, package exports, tests, BDD, examples, CI, and npm release gates under foreign/typescript, bdd/typescript, and examples/typescript.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Typescript Sdk?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/laserdata-typescript-sdk)
---
name: typescript-sdk
description: Work on the native TypeScript Laser SDK, its wire fixture port, Apache Iggy adapter, Node runtime, package exports, tests, BDD, examples, CI, and npm release gates under foreign/typescript, bdd/typescript, and examples/typescript.
---
# TypeScript SDK
Read [AGENTS.md](../../../AGENTS.md) and [laser-sdk-overview](../laser-sdk-overview/SKILL.md) first. Rust `laser-wire` types and fixtures remain authoritative. Never invent a TypeScript-only wire shape.
## Layout
- `foreign/typescript/src/wire`: native codecs and validators
- `foreign/typescript/src/iggy/apache-iggy.ts`: the only Apache Iggy and Node `Buffer` adaptation boundary
- `foreign/typescript/src/stream`, `managed`, `agent`, `memory`, `bridges`: public behavior by layer
- `foreign/typescript/test`: unit, wire, robustness, and real-Iggy integration
- `bdd/typescript`: every shared Gherkin scenario, no copied features
- `examples/typescript`: nine primitive and nine deep-dive mirrors
Public bytes are `Uint8Array`. Wire-sized u64 and u128 values are `bigint`. Public JSON is `unknown` until validated. Source is strict ESM, semicolon-free, has no public `any`, and uses no default exports. Managed operations negotiate capabilities and return `UnsupportedError` on Apache Iggy.
Lease acquisition is the managed-transport retry exception. `Kv.lease` disables reconnect replay for the acquisition request, repeats the same prepared identity after an ambiguous result until the requested TTL since the first send has passed, then raises `AmbiguousMutationError`. An aborted `signal` ends the repeat with `CancelledError`. `Lease.validUntilMs` is the first send plus the granted TTL on the `performance.now()` clock. Exclusive workflows keep their lease through verification and completion journaling, race an in-flight renewal against contract completion, renew over the coordination connection (`Kv.renewLeaseUntil`, `LeaseCoordinator.renew`) repeating an ambiguous renewal under its prepared identity until the earlier of `validUntilMs` and the workflow deadline, and throw the typed lease-lost error when the lease runs out.
Capability negotiation must match Rust and Python. `BackendAnnounce.ready === false` cannot enable managed surfaces or expose stale backends. An omitted ready field uses the wire's compatibility default. `refreshCapabilities()` and the one-second retry while the held set has no managed backend or an enabled backend that is not ready (`capabilityReprobeDue`, Rust `reprobe_due`) re-probe without reconnecting, preserve the builder's configured capability seed, and adopt announced topology except where the builder explicitly overrode a topology field. `withCapabilities()` remains an authoritative handle-local override and refresh must not replace it.
`src/iggy/apache-iggy.ts` uses Iggy's native VSR transport. Injected clients use the same transport, and `fromClient` only probes the injected client for liveness. LaserData hosts use TLS with the bundled root CA and explicit SNI. The Apache Iggy Node SDK supports VSR over TLS through its normal `getRawClient` path, with no Laser-side transport workaround. Synchronous client configuration failures must fail immediately and never enter the unlimited connection retry loop. This module is also the allocation boundary: a `Uint8Array` becomes a Node `Buffer` view over the same backing store rather than a copied buffer.
Streaming sends return Apache Iggy `SendMessagesResponse`. Re-export the confirmation types and preserve all confirmations through transport. An empty list is valid when the server does not report offsets. Completion follows the topic durability policy.
Every agent record of a stream rides one `agent.sessions` topic, keyed by session (`AgentTopic.Sessions`, beside `Streams`, `Heartbeats`, `Control`, `Memory`, `Audit`, `Registry`, `WorkflowJournal`, and `Dlq`). `laser.bootstrap(partitions?, retention?)` defaults to one partition and a one-day `TopicRetention` (`TopicRetention.new(expiryMs?, maxSizeBytes?)` refuses never-expire with no size bound, `TopicRetention.expireAfter(ms)`), creates `agent.heartbeats` with a one-hour expiry and the satellites `agent.streams`, `agent.memory`, `agent.dlq`, `agent.audit`, and `agent.workflow_journal`, and never creates `agent.control` or `agent.registry`. AGDX records on `agent.sessions` carry `agdx.to = "*"` when untargeted. The reliable consumer classifies every record with `classify` or `classifyGeneric` and hands only work to the handler. `operations` (on `ReliableConsumerOptions` and `Agent.builder()`) narrows the served command operations. `ReliableConsumer.run` resolves a delivery engine once: `policyAware(capabilities)` false, or no dialed connection string (`INTERNAL_DIALED`, warning through `runtime/warn.ts` when a managed backend is ready), reads natively through `INTERNAL_NATIVE_CONSUMER`. Otherwise it reads through `ConsumerGroup.consumer` with commit policy `disabled`, and, when it listens on `agent.sessions` or `agent.control` and the server serves filters and the catalog, binds its role group to `addresseeFilter(me)` with `create({ filter, filterName: ADDRESSEE_FILTER_NAME })`. Lanes commit through the internal `Consumer[INTERNAL_COMMIT_HANDLED]`, which queues the acknowledgment for the next read on a group-aware consumer, and an assignment probe at `SessionConfig.heartbeatValue` retires lanes of partitions `Consumer[INTERNAL_ASSIGNED_PARTITIONS]()` no longer lists. When `agent.control` exists, `loadControl` (`src/agent/pause.ts`) loads a bounded read of every control partition into a `ControlBook` (`src/agent/control.ts`) and a `ControlFollower` polls every partition from there, so each instance of a role sees every request. `Session.pendingControl()` and the internal `Session.controlState()` read the book, folding the retained control records when no follower keeps it current. An agent with an id runs a `PauseRuntime`: the pause check sits in `ReliableWorker.deliver` before the fence and dedup gates under a per-session gate, parks work as `session_parked` events, acknowledges pause and resume with `SessionTransition.acknowledges`, drains held work through `Replay` after the resume with `session_unparked` completions, and rereads the lane (`scanLane` in `src/agent/lane-scan.ts`) after an assignment change or a reopened consumer. `Session.parked()` returns `ParkedRecords`. Budgets live in `src/agent/budget.ts`: `Session.overBudget()` reads `SessionInfo.overBudget` with the `sessions` capability and folds the lane otherwise (`laneBreach`: first start record's budget, usage of every enveloped record), the runtime's `BudgetGate.admit` runs in `ReliableWorker.gated` after the pause gate for an agent with an id, reads the index once per session per poll batch keyed by the partition head offset (`ReceivedAgentMessage.currentOffset`), fails an over-budget session once through a latched lens with reason `budget`, and lets a record through on a failed index read. `Workflow.run` checks the budget after the cancel check and ends the run failed with reason `budget` on any `BudgetExceededError`. The record decoders live in `src/agent/decode.ts`, re-exported from `reliable-consumer.ts`, so the pause modules form no import cycle. Dead letters keep the record's conversation (the header value, else `ConversationId.derive` of its log position), and `SessionConfig.failOnDeadLetter` fails the session after a published dead letter. `ReliableConsumerOptions.sessions` and `AgentBuilder.sessions(config)` carry the `SessionConfig`. A command whose metadata marks it `submitted` marks its session working and holds a lease while the handler runs. There is no run registry: `ContractBuilder.parent(parent, root)` writes a child session's submitted start before the command and ends the child by the outcome, `Workflow.run` begins a root session with the run id, sends each step and compensation as a child, ends, fails, or cancels the run, and checks `session.cancelRequested()` (a `session_cancel` or canceled record on `agent.control`) at every step boundary.
`AgentCtx.approvalGate(approver, replyTopic, prompt, timeoutMs)` returns an `ApprovalGrant` and accepts only the approver's reply (`AgdxReplyReader` `expectedSource`), and `AgdxSend.withGrant(grant)` carries it to the governor so a step-up in its conversation proceeds. `requestInput` publishes an `input-required` status and an `input_request` command and sleeps only on a caught-up pass. The reliable consumer retries a failed dead-letter publish in place on `consumerBackoff`, then stops with `deadLetterFailure` instead of reopening, answers a dead-lettered correlated command on `respondOn`, addresses the pickup status to the source, and refuses `ackOnPickup` without `respondOn`. A spawned agent publishes its card with the inbox and a ttl of three heartbeats through `advertiseAgent`, refreshes it every heartbeat, and withdraws it on stop. The registry validates and caps folded cards, `inboxFor` falls back to the card inbox, and `refreshPresence` reads nothing on Apache Iggy. `resolveTargets` refuses a quarantined named route, and contracts pick through `resolveRoutable`.
`laser.sessions(config?)` returns `Sessions`. `create(label)` and `start()` return a `SessionBuilder` (`agent` required, `namespace`, `parent`, `withId`, `idleTimeout`, `budget`, `tag`, `id()`), and `begin()` writes the start and returns `{ session, lease }` (the lease heartbeat names its stream generation, and `wire.sessionHeartbeatCountsFor` is the reader rule), refusing an ended labeled or explicit id with `SessionEndedError`, while `resume()` also reopens a completed or failed one. `SubmitBuilder.id()` names the submitted session before `send()`, and a failed command publish ends that session failed. `contextMessageBody(message)` is the envelope body or the payload, the bytes `AssembledContext.text()`, manifests, and the default `TokenBudget` count. `assemble(policy)` selects from conversation records only. `open(id)` is a lens with no IO. `deriveSessionId(stream, namespace, label)` derives labeled ids. `submit(agent, input).from(submitter).send()` writes a submitted session and its first command, and `control(stream, id).asOperator(op)` sends `pause`, `resume`, `cancel`, and `forceCancel` on `agent.control`, signed after `signedBy(key)`. AGDX records on `agent.control` also carry `agdx.to = "*"` when untargeted. A `SessionLease` keeps the session in the per-connection heartbeat (an unref'd timer publishing `SessionHeartbeat` bodies on `agent.heartbeats`) until `release()`. `Session` has `asAgent`, `signedBy(key)` (signs the terminal record), `pendingControl()`, `append(envelope)`, `end` (snapshots changed state first), `fail`, `cancel` with a shared terminal latch, `run(lease, work)`, `state()` (`set`, `patch`, `replace`, `snapshot`, `get`, automatic snapshot every 64 deltas, seeded before its first write from the lane fold, or from `Session.managedStateView()` when the fold is incomplete, the `sessions` capability is present, and the view is not behind the fold), `assemble(policy)`, `model`, `tool`, `recordModelCall`, `recordRetrieval`, `recordCompaction`, `redact`, `actingOn`, `reference`, `kv`, `linkedGraph`, and `linkedMemory`. `AgentCtx.session()` is the handled record's session acting on that record. The managed session index reads (`Sessions.get`, `list`, `events`, `state`, `links`, `sources`, `changes`, `watch`, `Session.status`) check the `sessions` capability first, send the session codes, and throw `SessionError` on a typed failure. `SessionControl.participants(agents)` fixes the pause participants, otherwise `pause()` derives them from the lane (`laneParticipants`). `SessionListRequest.root(id)` and `labelPrefix(prefix)` narrow a session list, and `page(n)` and `results(n)` pick the page of a list or a timeline, which replies with `totalPages`, `totalResults`, `page`, and the walk's bound `asOf` and `series`, passed back on later pages with `asOf(asOf, series)`. `changes(page, results)` pages the ascending change sequence and replies with `floor`, the oldest retained sequence. `SessionWatch` starts in one read, refuses a zero `pollEveryMs` with `InvalidError`, and is an `AsyncIterable` for `for await`. `SessionPage.rebuilding` is false when the reply omits it and is encoded only when true, matching the Rust bytes. AG-UI state is that document: `publishStateSnapshot(source, conversation, state)` is `state().replace` then `snapshot`, `publishStateDelta` is `state().patch`, `reconstructState(conversation)` folds the lane first, reads the managed view only when the fold is incomplete and the view is not behind it, and returns the document once `revision > 0` or `complete`, and `envelopeToAgUi` decodes the CBOR `StateSnapshot` and `StateDelta` bodies. `laser.readAt(ref)` reads one record by message reference and returns `undefined` when the topic generation or offset differs. The reply hub completes a request only on a correlated response or error in the request's session, addressed to the requester when the request named one. `ContextMessage` carries `timestampMicros`, `streamId`, and `topicId`. An explicit `SessionConfig.layout` is declared for the resolved stream on the connection, shared by clones. Under `perAgentPartition`, AGDX commands, responses, errors, and chunks on `agent.sessions` addressed to a mapped agent go to its zero-based partition, and everything else keys by conversation. Under `perAgentTopic` (`topics` maps agent id to topic), `resolveAgentTopic` in `src/agent/partitioning.ts` moves AGDX commands, responses, errors, and chunks, and plain records sent with a target, on `agent.sessions` addressed to a declared agent to its topic keyed by session, without the lane guard. `Sessions.bootstrap` creates the declared topics through `INTERNAL_ENSURE_RETAINED`, a declared agent spawned on `agent.sessions` reads its own topic, and `request`, `contract`, `requestInput`, and MCP tool calls wait on the requester's declared topic (`replyTopicFor`). `Sessions.bootstrap` uses one partition under `singlePartition`, and after registering the source it polls `changes(0, 1)` every 100 ms until `NotRegistered` stops, up to the publish timeout, reporting `registered: false` with a warning otherwise. `Sessions.watch` is async and resolves after its one start read of page 1. `AgentCtx.requestAt()` returns the handled record's position. `context()` and `contextWith(policy)` return `SessionTurn[]`, each a timeline `display` type and a `ContextMessage`. `memory()` returns `ScopedMemory` in the configured namespace and `memoryIn(namespace)` in another, which provides `remember`, `recall`, `search(query, { limit, folded })` (limit 50 by default), `block(tokenBudget)`, `consolidate(maxItems, { summarizer, pruneSummarized })`, `forget` and `improve` (scoped to the conversation), and `withLineage`.
`checkpoint()` returns a `Checkpoint` over the session lane, with `toJSON`, `Checkpoint.fromJSON`, and `topics()`. `turnsAt`, `turnsSince`, `stateAt`, and `replay` read around its saved offsets. `new SessionConfig()` chains `stream`, `layout`, `idleTimeout`, `heartbeat`, `registerSource`, `failOnDeadLetter`, `memoryNamespace`, `contextTurns`, `contextTokens`, and `sdk`. Context policies report `name()`, `version()`, and `selection(history)` like Rust, and `TokenBudget` estimates with the wire `estimateTokens`.
The context assembler reads each partition through the Rust window: at most the newest `CONTEXT_READ_WINDOW` (10,000) raw records, tail anchored, or the window ending at a `toCheckpoint`, then filters by conversation. A checkpoint resume ignores `fromOffsets`, as in Rust. `contextCheckpoint(laser, topics)` captures a checkpoint. `ContextAssembler.builder().conversationId(id)` starts an assembly, and `fromCheckpoint` and `toCheckpoint` read around a checkpoint, while state replay uses the whole range for `from-checkpoint` and `at` bounds. A topic without records assembles as empty.
Memory follows the Rust structure. `MemoryHandle.supersede(oldId, payload)` returns a `SupersedeBuilder` that remembers the correction and forgets `oldId` in every conversation, `MemoryHandle.context(conversation, tokenBudget?)` renders a conversation block, memory payloads and key-value keys take `string` or `Uint8Array`, and a default log recall waits for the connection's own writes on the view and folds the topic where no view is served. `laser.scratchStream(prefix)` returns a `ScratchStream` (`name`, `laser`, `delete()`, `[Symbol.asyncDispose]`). `workflow.stepLocal(label, run)` runs a step in process, and `WorkflowOutcome` carries `completedSteps`, `status` and `text(label)`. `laser.memory(namespace)` uses the default `agent.memory` topic. `RememberBuilder.origin` and `producer` stamp lineage on remembered items. `laser.memoryOnTopic(topic, stream?)` opens an isolated existing topic. `laser.memoryTopic(topic).stream(name).partitions(n).ttl(ttlMs).build()` configures a topic with message expiry. `noExpiry()` creates the topic with never-expire retention. `laser.context(conversation).memory(handle)` must retain the exact topic-backed handle instead of substituting another namespace. `MemoryHandle.set`, `fetch`, `fetchFolded`, `update`, and `remove` address named facts like Rust and throw `UnsupportedError` on a non-log backend. `LogMemory` spells them `setNamed`, `fetchNamed`, `fetchNamedFolded`, `updateNamed`, and `forgetNamed`. `memory.remember(payload).scope(conversation)` and `memory.recall(conversation)` scope a call, and `RecallBuilder.block(tokenBudget?)` renders a block. `laser.memoryWith(namespace, backend, embedder?)` and `ContextScope.memoryWith` refuse a vector backend without an embedder and any other backend with one, both with `InvalidError` at open. `ContextScope.fetch(topics, n, tokenBudget?)` and `block(topics, n, tokenBudget?)` apply `Chain([LastN(n), TokenBudget(t)])`. `Agent.builder().consolidateEvery(0)` is a `HandlerConfigError`.
## Streaming and error parity
Producer options `batchLength` (1000, splits a direct batch), `lingerMs`, `maxTopicBytes`, `unlimitedTopicSize`, and `background` (`ProducerBackgroundOptions` with Iggy's `BackgroundConfig` defaults, one ordered worker, a send returns once queued, `onError`, and `shutdown()` drains, closes, and reports a background failure). `ProducerOptions.sharding` (`(ShardRequest) => number`, needs `background`) replaces the named sharding. `Encryption` (`src/stream/encryption.ts`, `node:crypto` AES-256-GCM in the Iggy nonce, ciphertext, tag layout) goes in `ProducerOptions.encryption` and `ConsumerOptions.encryption`. An encrypted header block travels as `MessageWithHeaders.userHeaders`, which the adapter sends through its own `SendMessages` encoding because the Apache Iggy client's send only takes structured headers. `ProducerOptions.idempotent` gives the producer a `ProducerSequences` (in the adapter): a random 63-bit producer id, an epoch, and a sequence per partition. The adapter stamps that producer section into the batch header, checksums the batch again, sends one chunk per partition at a time, and resends an uncertain send with the same section. `Producer.flush` is internal. `QueryRequest.rowsTyped(codec)` (needs `maxRows`). `MemoryHandle.backend` reports `log`, `vector`, or `custom`. `AgentScope.contract(router)`. Capability helpers `isOpenOnly`, `servesConsistency`, `isReady`, `readinessReasons`, `enabledBackends`, `unreadyBackends`, `backend`, `OPEN_CAPABILITIES` are exported. `SwappableGovernor.current()`, and `swap()` returns the previous governor.
- `Consumer.nextWithin(ms, { signal })` returns a `ConsumerMessage` and throws `TimeoutError` on deadline and `InvalidError` after shutdown, like Rust `next_within`. `ConsumerOptions` carries `commitPolicy` (the ten Rust variants, such as `{ kind: "disabled" }`), `maxWaitMs` (the server-held wait, default 5000), `minCount`, `maxBytes`, `createGroup`, `pollingRetryIntervalMs`, `initRetries`, and `allowReplay`. A group consumer always joins its group. The default `batchLength` is 1000. The default `commitPolicy` is `{ kind: "all" }`, and an unnamed consumer's is `disabled`. `commit` stores under the delivery's partition context, and `storeOffset`, `deleteOffset`, `seek`, `lastStoredOffset`, and `storedOffset` mirror Rust.
- `Producer` creates its topic before the first send unless `createTopic` is false, and its stream only with `createStream`. A one-shot publish creates a missing stream and topic, as in every client. A session or AGDX record on a stream without `bootstrap` is refused by the lane guard, whose text names `bootstrap` and `memoryTopic`. Where a missing stream or topic does surface it fails as `isStreamOrTopicNotFound` (`missingResource` in `src/iggy/apache-iggy.ts` carries the Iggy code). A producer takes `partitions`, `expireAfterMs`, `neverExpire`, and `replicationFactor`. `Topic.ensure(partitions, replicationFactor?)`, `ensureTopic`, `ensureTopicWithExpiry`, and `createTopicIfAbsent` (`TopicCreateSettings.replicationFactor`) pass the factor to `client.topic.create`, checked against 1..=`MAX_REPLICATION_FACTOR` (32) by `validateReplicationFactor` in `src/iggy/apache-iggy.ts` with `InvalidError("replication factor must be 1..=32")`. Agent topics keep the server default. `PartitionInfo` carries no node lists, so partition `members` and `inSyncMembers` come from the raw client's `topic.get`. `laser.streams()`, `Stream.get`, `exists`, `topics`, and the `Topic` verbs `get`, `exists`, `delete`, `partitions`, `addPartitions`, `deletePartitions`, and `consumerGroups`, with `ConsumerGroup.delete`, run through optional `LaserTransport` methods (`listStreams`, `findStream`, `listTopics`, `findTopic`, `deleteTopic`, `addPartitions`, `deletePartitions`, `listConsumerGroups`, `deleteConsumerGroup`). `ApacheIggyTransport` reads the stream, topic, and partition creation times from the raw reply, so `createdAtMicros` keeps microseconds. A transport without one of these methods throws `UnsupportedError`. `Stream.rename`, `Topic.update`, `Topic.deleteSegments`, and the server calls in `src/client/server.ts` (`User`, `PersonalAccessToken`, `Laser.users`, `personalAccessTokens`, `ping`, `stats`, `me`, `clients`, `clientInfo`, `cluster`, `snapshot`, `describeOptions`, `metadataChanges`) run one raw command each through the optional `LaserTransport.administer`. The command encoding and reply decoding live in `src/iggy/server-admin.ts`, the only place outside `apache-iggy.ts` that imports Apache Iggy command modules. `get()` and `exists()` read a missing stream or topic as `undefined` or `false`, and `topics()`, `partitions()`, and `consumerGroups()` fail with an error that `isStreamOrTopicNotFound` recognizes. The transport reads Iggy codes 20, 1009, 1010, 2010, and 2011 as missing, the same set as the Rust `is_missing_resource`. `Topic.delete` drops the cached partition count, the reply hub of the topic, and the agent registry cache for `agent.registry`.
- A group consumer reads every partition `next`. `joinSeeds` in `src/stream/consumer-start.ts` takes at the join the seed of each partition the group never stored (`startSeed`: offset n stores n - 1, timestamp the record before the first match or the head, last head - 1), held partitions are stored at the start (native `storeHeldSeeds` in `consumer-group.ts` after a sync, policy-aware `FilteredReader.storeOwnedSeeds` over the member's `CoordinatorConnection.storeOffset`, since the fork fences a group store to the owner), later ones before their first read if still unstored, a seed refused as not owned (5009) or transient (58, the partition is not installed or routable on the node yet) stays pending with its partition unread, and any other failed seed fails the start with the Iggy error and leaves the group. The internal `FilteredReaderBuilder.seedStart` is the only way in, so the advanced reader keeps its `start`.
- The native consumer reports a lasting refusal (`LASTING_REFUSALS` in `src/stream/consumer.ts`) on the sixth refused poll in a row of a partition (`REFUSALS_PER_REPORT`), Rust's upstream stop count, holds each refused poll for `pollingRetryIntervalMs`, and resumes after the stored offset. `Topic.batching()` returns `BatchingProducerBuilder` (`maxRecords`, `maxBytes`, `linger`, `partitionKey`) in `src/stream/batching.ts`.
- A failed send throws `PublishFailedError` with `stream`, `topic`, `committed`, `unconfirmed`, and `publishCause()`. `src/client/error-classify.ts` holds the Rust classifier family (`isPermissionDenied`, `isUnsupported`, `isNotFound`, `isUnavailable`, `isNotLeader`, `isStale`, `isVersionSkew`, `isVersionConflict`, `isAmbiguousMutation`, `isStreamOrTopicNotFound`, `isNoCapableAgent`, `isLeaseLost`, `isFenceViolation`, `isBudgetExceeded`, `isQuarantined`, `filterReason`, `iggyErrorCode`, `code`). Each one answers through publish wrapping. `FenceViolationError`, `QuarantinedError`, and `NoRespondTopicError` mirror the Rust variants.
- `Kv.expire(key, ttlMs?, nowMicros?)` takes a TTL like Rust and Python, and `expireAt` takes an absolute time. `KvSetRequest.send()` throws `InvalidError` when a precondition was set. `msgpack` is available on the set and fenced CAS builders. Fork `embedding` takes `Iterable<number>`. Payload text goes through `TextEncoder` and `TextDecoder`, since the root exports no UTF-8 helpers.
- Names follow Rust: `Laser.client`, `Laser.fromClient`, `dlqTopic`, `withDlqTopic`, `aggAs`, `stddev`, `asStr`, and `ForkHandle.id`. Relative durations are millisecond numbers named for their unit where it is not obvious (`ttl(ttlMs)`, `lease(key, holder, ttlMs)`, `expireAfterMs`, `QueryRequest.window(field, everyMs)`, `TestClock.advance(byMs)`, `ModelResponse.durationMs`). Absolute times stay epoch microseconds as `bigint` and are named with `At` (`deadlineAtMicros`, `withDeadlineAtMicros`), and offsets are a `Map`.
- Every awaiting public call takes a trailing `CallOptions` (`{ signal?: AbortSignal }`, `src/client/call-options.ts`), merged into the call's own trailing options object when it has one, never a positional signal. An aborted signal rejects with `CancelledError` before I/O and during the wait: pass it to `executeManaged`, held polls, reply waits and the transport's publish attempt loop (the `signal` of the `send*` options, checked before each attempt and racing the retry wait), use `delay` in loops, and `throwIfAborted`, `abortable` or `cancellable` elsewhere. Teardown and the seams an application implements take none, except that the `Memory` writes (`remember`, `append`, `improve`, `forget`) and `recall` receive the caller's options, so `LogMemory` stops retrying a write and waiting out a refused read on abort, and `LogMemory.fetchNamed` takes them too. `test/unit/cancellation.test.ts` checks the API report for every promise-returning member. The `FilteredReader` runs one public call at a time through a `Mutex` and bounds `nextPage({ timeoutMs })` waits by the time left.
- Handles have no public constructor where Rust has none. `Topic`, `Stream`, `Producer`, `Consumer`, `QueryRequest`, `Sessions`, `MemoryHandle`, `AgentHandle`, `AgentRegistry`, `ContextScope`, and the builders come from `Laser` or `Agent.builder()...build().spawn(laser)`. `laser.advertisePresence` takes a wire `AgentPresence` from `newAgentPresence(agent.wireId(), inbox)`. Route policies and gather policies are tagged objects such as `{ kind: "any" }` and `{ kind: "requireAll" }`.
## Data stack parity
The native modules `wire/schema.ts`, `destination.ts`, `arrow.ts`, and Query in `wire/query.ts` mirror Rust field-for-field. Successful query replies must validate result fields, positional row width, tagged values against logical types, delivered consistency, and operational evidence before reaching application code.
`Laser.query()` builds an operational target. `QueryRequest` supports typed raw SQL parameters and offset paging. Filter, `whereEq` and raw SQL values take a `QueryValue`: a tagged `TypedValue` or a native value inferred like Python (`typedValue` in `src/managed/query.ts`). `rows()` returns `QueryRows` and `rowsTyped()` `TypedQueryRows`, both `AsyncIterable` with `next()` and `frontierMoved`, and `fetchAll()` returns an iterable `QueryRowSet`. Each walked row is a `QueryRow` (`QueryRow.fromPage`) read by name.
Every managed command descriptor carries its capability surface and correct `OpVersions` field. Query commands use `versions.query`.
`PublishRequest.arrowIpc` and the batch peer validate metadata and exact payload length before I/O. Use `Uint8Array` for bytes and `bigint` for wire u64 and u128 values.
Any public change updates root and full exports, both API reports, unit and wire tests, robustness tests, fixture manifest, README examples, and the shared BDD steps. Run `build:test` before test runners so they execute the current source. Then regenerate `docs/parity.md` with `python3 scripts/check-parity.py --write` and run `just parity-check`.
## Exports
- root: ordinary application API
- `./full`: root plus the complete wire namespace
- `./testing`: deterministic seams and factories
- `./opentelemetry`: optional observer adapter
Do not add deep package exports. Review generated API reports after every public change.
## Verification
From `foreign/typescript` run:
```sh
npm run verify
npm run test:integration
```
Then run `scripts/run-bdd-tests.sh typescript` and the example package tests against Apache Iggy. The cluster tests (`test/integration/cluster*.test.ts`, `reconnect.test.ts`) start their own `TestIggyCluster` (`start(nodes, environment)`, five nodes for the replication factor tests) and run one file at a time. The bound-policy cluster tests run only when `LASER_TEST_CATALOG` names the `laser-test-catalog` binary of the workspace's `test-support` crate (`TestCatalog`). `verify` includes format, lint, emitted dependency cycles, strict types, builds, API reports, fixture and robustness tests, coverage, licenses, and packed ESM/CommonJS-interoperating consumers.
Dependency policy. A lockfile change may only introduce versions that have been on the npm registry for at least seven days: `node scripts/release-age-check.mjs <base package-lock.json>` is the PR gate (`MINIMUM_RELEASE_AGE_DAYS`, default 7), the supply-chain cooldown that keeps a freshly published or compromised release out of the lockfile until the ecosystem has had time to catch it. `apache-iggy` is the one exemption: the SDK pins the exact client build of the server release it is developed against and consumes it the day it ships. The security workflow fails on any known vulnerability in the lockfile (osv-scanner, on every push and weekly) and on high advisories (`npm audit`). A vulnerable transitive dependency that no parent's range reaches is raised to its fixed version through `overrides` in `package.json`, pinned exactly, then `npm install` to rewrite the lock and `npm run verify` and `npm run test:integration` to prove the parents still work. A version that fixes a published advisory does not wait for the cooldown: add it, and any new dependency it pulls in, as one exact `name@version` entry of `ADVISORY_FIX_COOLDOWN_EXEMPT` in the script, named with the advisory, and drop the entry once the version is older than the cooldown.
Node 22.14 and Node 24 are supported. Bun, Deno, and browsers are unsupported until their transport and complete gates pass. Release tags use `ts-v*` and publish the exact CI-produced tarball through npm OIDC. A merged pull request with the `release` label publishes the tarball its own run produced, as AGENTS.md describes.
## Publish recovery
Defaults, failure reports, and outage handling are in [publish recovery](../../../docs/publish-recovery.md) and [connect timeout and cleanup](../../../docs/connect-timeout.md).
In `foreign/typescript/src/iggy/apache-iggy.ts`, a socket replacement during a leader change does not count as a lost connection. Allow the current send to finish. Run only one publish attempt per connection at a time. The Apache Iggy client resends all queued commands when it changes nodes. A second queued send can return the connection to the metadata leader. The three-node reconnect test depends on both rules. `laser.connectionEvents()` follows the same rule. The transport reports `disconnected` only from the raw client's `sessionReset` of a signed-in session or from its own lost-connection mark, never from a link event, and `connected` plus `signed_in` from the first heartbeat after that or from a reconnect (`src/client/connection-events.ts`).
The transport hands the connection string's reconnection policy to the Apache Iggy client, which redials each replica link and resumes the session. A send with an unproven outcome is never resent, the next send to its partition resolves it first. A poll its caller cancelled is reported as `CancelledError` and never retires the client, and apache-iggy sends the deferred cancel (108) for a held request whose signal aborts. `close()` during a redial settles and leaves no socket or timer (`test/integration/reconnect.test.ts`).
The reply hub (`src/agent/replies.ts`) holds its per-primary fetches through a `holding` signal that aborts when the last request or stream waiter leaves and on `stop`, so an idle hub holds nothing. `heldRead` (`src/stream/cursor.ts`) rejects as soon as one fetch fails and cancels the others, so the caller reads every partition again instead of waiting out the other holds. The `agent.control` follower aborts its held fetch on stop.
The managed group reader (`src/managed/filters.ts`) gives each filtered wait an id from a process-wide counter and cancels the waits still held on other nodes (`AGDX_FILTERED_WAIT_CANCEL_CODE`, `cancelHeldWaits`) when one node answers ready, when a membership refresh (during held waits or at a round) finds the assignment changed, when its idle wait is aborted, and on `close`. A failed cancel warns through `runtime/warn.ts`. A wait refused with a stale route or `unavailable` forgets the routes of its partitions and waits again at once, once in a row (`waitRefused`), a second refusal paced by the idle interval, a held wait that misses a partition now routed to its node is cancelled and replaced (`HeldWait.partitions`), and a read or acknowledgment the caller's node refuses as `NotPrimary` is resent once after a fresh route lookup. Every attempt of `exchange`, a resend included, goes through `sendUnlessMoved`, so a resend to a crashed primary the route still names moves when the cluster names the successor instead of waiting out the call deadline.
## Consumer-group filters
Group handles, filter setup, scan budgets, progress, and cross-language test parity follow the [consumer-filters](../consumer-filters/SKILL.md) skill.
## Coordination and lifecycle
`src/managed/coordination.ts` holds `FencedLeaseClient`, `PreparedMutation`, and `DedicatedKvTransport`: prepared operations with stable bytes, readiness checked before a request is sent, operation-specific recovery (a `pending`, `backend_unavailable` or `unavailable` reply resets the transport and is `AmbiguousMutationError` naming the prepared identity, like a lost reply), and a terminal `close`. `Laser.advertisePresence` pins the replica that answered and `clearPresence` goes there, failing as unavailable while that replica does not answer (`PRESENCE_ATTEMPT_MS`). `defineRoleAs`, `deleteRoleAs` and `bindRolesAs` take the caller's receipt identity (`validateMutationId`). Background `onError` callbacks can return promises. Low-level reliable consumers take `shutdownGraceMs`. `ConsolidationReport` uses `summarized`, `reweighted`, `pruned`, and `derived`.
Native partition and group polls preserve microsecond timestamps, message IDs, checksums, current offsets, and raw user headers. Malformed header blocks are marked on each record. Native polling defaults to no delay. Lease attempts use the dedicated coordination transport and its 10-second attempt bound. An injected client cannot create that dedicated connection.
Managed resource naming mirrors the Rust `ResourceNaming`: `Laser.resourceNaming()`, `withResourceNaming`, `resourceName`, and the builder's `resourceNaming("stream" | "bare")`. Handles get a `ResourceScope` (`src/client/resource-scope.ts`) from `Laser.resourceScopeOf()` and scope KV namespaces (`Kv.resourceNamespace`, `Kv.namespace` is the local name), fence and copy namespaces, the KV and graph lens `stream`, memory header and read view namespaces, graph names, fork ids, parents, tables, and projections (`ForkHandle.resourceId`), query indexes and forks, the watch index, projection ids, binding refs and indexes, and the schema registry stream (`ControlEnvelope.stream` and the browse requests). Listings drop other streams' names and strip the caller's prefix. `Filters` stamps `ConsumerFilter.schemaStream` on definitions with schema refs, and a group's filter lookup accepts its scoped name. Under `Capabilities.streamTenancy`, `watch` reads `streamOpsTopic(stream, CHANGES_TOPIC)`.
Materialization setup lives in `sdk/src/materialize.rs`, `foreign/python/src/materialize.rs`, and `foreign/typescript/src/managed/materialize.ts`. The shared scenarios are `bdd/scenarios/materialization.feature` and `bdd/scenarios/operational_sql.feature`. Keep append and keyed history, rejection policies, captured-target readiness, and explicit raw SQL dialects aligned in every client. Read `docs/client-behavior.md` from the repository root for the public contract.