@oxap/client (TypeScript)
The TypeScript Agent Service client drives OAP adapters over HTTP and SSE
with schema/v0.1 envelopes and exact uint64 values. Start the product with
oxap serve --config examples/agent-service.json and connect using dial.
Its client type is AgentServiceClient, also available as OapClient. It
is the counterpart of the Go client package — same wire surface, same
semantics — so non-Go hosts (HyperNeo and friends) can consume the exact
envelope stream the Go client sees.
- Zero-dependency runtime: platform
fetch and streams only; Node 18+
baseline. typescript and @types/node are dev dependencies, nothing
ships.
- The client never logs, carries no credentials, and adds no protocol
semantics of its own: the daemon is a single-user local service.
Install
The package is @oxap/client on npm, versioned with the OXAP release line. It
is not published yet; until it is, use it from a checkout as a file:
dependency:
{
"dependencies": {
"@oxap/client": "file:../oxap/clients/ts"
}
}
(A Git remote cannot select a package subdirectory — npm resolves it at the
repository root, which is the TypeScript SDK — so advertise and use the file:
form.)
Prepare the checkout once before consumers install it: run npm install in
clients/ts, which builds dist/. npm does not install a local-path
package's own dependencies, so a file: install of an unprepared checkout
cannot build and fails. The build records hashes of its sources, configuration
and emitted JavaScript/declarations. prepare skips compilation only when
those inputs and every output still match. A fresh, complete checkout installs
without the dev toolchain; stale or partial output is rebuilt when the compiler
is available, otherwise installation fails with instructions to prepare the
checkout. In a bare checkout, npm install prepares it, or run npm run build
directly. Builds clean dist/ first, so removed source modules leave no stale
output behind. A checkout missing source or configuration files cannot prove its
build is current; restore the complete checkout before preparing it.
Canonical lifecycle
import { dial, EnvelopeType, finalText, payload, type PermissionRequestedPayload } from '@oxap/client';
const client = dial('127.0.0.1:6270'); // or 'http://host:port'
// Discovery: the adapter listing and one capability snapshot.
const [adapter] = await client.adapters();
const caps = await client.capabilities(adapter.name);
// One session, subscribed before submitting so the run's first envelope
// cannot be missed.
const session = await client.open('memory', { sessionId: 'demo' });
const events = session.events(); // subscription starts now
await events.ready; // …and is live
await session.submit({
messages: [{ role: 'user', content: 'run the golden script' }],
delivery: 'auto',
});
// Consume the run, resolving interactive gates as they arrive.
for await (const envelope of events) {
switch (envelope.type) {
case EnvelopeType.ActionPermissionRequested: {
const gate = payload<PermissionRequestedPayload>(envelope);
await session.resolvePermission({
interaction_id: gate.interaction_id,
requested_by: gate.requested_by,
run_id: gate.run_id,
choice_id: 'approve',
granted: true,
});
break;
}
case EnvelopeType.UserInputRequested:
// …resolveInput({ interaction_id, requested_by, run_id, answers }) likewise
break;
case EnvelopeType.RunCompleted:
console.log('final:', finalText(envelope));
break;
}
}
// The loop ends on its own at the run's terminal event.
await session.close();
session.resolve(...) dispatches on payload shape (granted → permission,
answers → user input) if you prefer one method.
The event stream
session.events() returns an async iterable of typed envelopes. By default a
dropped connection is resumed invisibly: the client reconnects with the
last observed sequence as the Last-Event-ID / ?after= cursor, the daemon
replays the suffix, and iteration continues without duplicates. A repeated or
skipped sequence within a run, a frame id disagreeing with its envelope, or
an envelope naming another session surface as typed errors — never silent
skips. Iteration ends cleanly (the for await finishes) once a run's
terminal event has been delivered.
dial(addr, { strictResume: true }) turns resume off: a drop raises a
DisconnectError carrying the last (runId, lastSequence).
The daemon's terminal transport signals surface as typed errors carrying the
reconnect cursor:
OverflowError — this connection's bounded buffer fell behind; resume with
session.eventsAfter(err.runId, err.lastSequence).
ReplayGapError — the requested cursor is no longer retained;
oldestAvailable/latestAvailable bound what is, so a consumer that
accepts the loss resumes at or after oldestAvailable - 1.
DisconnectError — a drop that was not resumed (strict mode, or repeated
empty reconnects).
ResumeMismatchError — eventsAfter replayed a different run than the
cursor belongs to.
DuplicateSequenceError / SequenceGapError / MalformedFrameError —
wire defects in the stream's positions or framing.
session.eventsAfter(runId, after) is the manual resume path: the run's
envelopes after after first, then live events.
Daemon refusals arrive as ServerError with the correlated
error.response code — serverCode(err) reads it, e.g. unknown_session,
run_active, session_closed. Requests and responses stay correlated and
session/run-scoped: a response citing another request or another scope is
rejected client-side as a protocol violation.
Options
dial(addr, {
fetch: myFetch, // inject the transport (tests, proxies, undici)
participant: 'user', // responder identity for gate resolutions
strictResume: false, // true: report drops instead of resuming
});
client.open('memory', { sessionId, participant }); // per-session overrides
session.events({ signal: controller.signal }); // AbortSignal ends the stream
Dev-mode envelope validation (the Go client's WithEnvelopeValidation) is
deliberately absent here: it would need a JSON-Schema library at runtime, and
this client is zero-dependency by contract. The hand-written interfaces are
cross-checked against schema/v0.1/*.json by the test suite instead (shape
assertions on every envelope and payload type).
API reference
The exported surface, with the documentation that lives on it in src/. protocol is the
wire model the client mirrors from schema/v0.1; the rest is the client surface built on it.
Nine of the eleven documented errors exports are covered under
the event stream, where the resume rules that give them meaning are set out;
the two that are not appear under errors below.
Exact uint64 values
In OAP envelopes and their event-stream cursors, every uint64 field is always
bigint, including 0n and 1n. This covers
usage counts, envelope sequences, history-token counts and payload positions,
as well as replay cursors and sequence properties on stream errors. There is
no magnitude-dependent number | bigint type. eventsAfter(runId, 0n) starts
at zero; use bigint literals and arithmetic consistently.
Use parseEnvelope and serializeEnvelope together for wire envelopes:
import { parseEnvelope, payload, serializeEnvelope, type RunCompletedPayload } from '@oxap/client';
const envelope = parseEnvelope(rawEnvelopeJSON);
const usage = payload<RunCompletedPayload>(envelope).usage;
if (usage?.input_tokens !== undefined && usage.output_tokens !== undefined) {
const sum: bigint = usage.input_tokens + usage.output_tokens;
console.log(sum.toString());
}
const wireJSON = serializeEnvelope(envelope);
9007199254740993n and 18446744073709551615n are written as exact, unquoted
JSON number tokens. Native JSON.stringify does not serialize bigint; use the
client serializer for envelopes. The HTTP client uses it automatically. Missing
counts remain unknown, and 0n remains a measured zero. Usage counts follow
Decision 0065's canonical spelling/range rules; integral decimal/exponent
sequence spellings remain accepted under hub D31 and serialize canonically.
This representation is specific to uint64 fields. Signed timestamps, limits and
arbitrary application/tool-result JSON numbers remain number; their normal
JavaScript numeric behavior is unchanged. Bigints in those arbitrary JSON
positions are not accepted by the envelope serializer. The parser is not a
general runtime JSON-Schema validator, and no runtime dependency is added.
protocol