PUBLIC MODULE · lib/io.js

Agent.IO

lib/io.js — IO: provider IO/schema conversion, nothing else.

This module depends on lib/context.js and lib/env.js. It completes a registered provider class's wire side (lib/io/provider.js), maps the library thinking levels to the model's native modes, and publishes the provider failure taxonomy (ProviderError) and THINKING_LEVELS.

An IO instance keeps NO context between requests: each write() receives the caller's Context and converts it to one provider request. During the request, context is that Context: IO keeps its ROOT RECORD (type "io-root": the qualified model and a hash of the request's tool definitions) current, so a model or tool change shows as context.dirty, and providers read context.dirty to drop replay data bound to history that changed. It holds connection state for the active request (a provider connection is created and closed for each request) and exposes:

settings — provider-namespaced LIVE settings view (via the Env connection, env.connection(selector)) tools() — the request's tool catalog (Env.tools(safe, selector), snapshotted once per request), per-instance availability selection applied authSet(a) — persists endpoint data through the Env connection write(context, callbacks?, options?) — one request over a Context, resolves with the terminal done/error event close() — cancel active request, emit terminal partial, close, permanently disconnect

State machine per instance: idle → sending → reading → idle, repeating. Sending while not idle is a contract error (no concurrent in-flight requests). After close() the instance is "closed" forever; the caller constructs a replacement.

IO knows nothing about agents, and publishes no events of its own: each write() reports its request through the callbacks it was given. model retains a qualified <endpoint>/<model> selector; only wire translators extract the native model ID. Switching endpoints requires another IO instance.

IO sanitizes outgoing requests (headers/body from the connector) and validates converted responses (valid response events; message metadata rides along — tolerant reader). An auth-classified failure before any response data triggers the MULTI-PROCESS refresh (another process may have rotated the endpoint's credentials): Env re-reads the endpoint's persisted settings/auth record and the request retries ONCE with the updated token (lib/io/request.js). Metadata RECORDS (context entries with a string type — harness/tool-owned data, messageIsRecord) and empty messages are filtered OUT of every provider-bound context: they persist in the session and ride the agent's array, but the model never sees them. Errors surface in the auth/network/provider/malformed taxonomy (+ "cancelled" on close()).

Per-request timeouts (each: write options > live provider- namespaced settings > provider metadata > default; all accept a millisecond numeral or a unit string via lib/util.js): - timeout overall cap per request (default 1048575ms) — an agent may legitimately work for a long time; - connectTimeout no response from the provider at all (default 30000ms) — a hung connection. Its connection budget is computed from the serialized request body; callers should treat it as a guardrail, not a latency prediction; - stuckTimeout no DATA between message events while reading (default 120000ms) — a stuck model; every frame (text/thinking/tool-call block or delta) resets it, so long-but-active generations never trip it.

class IO class

One provider IO session: context in, normalized response events out.

Defined in lib/io.js

Provider field

Wire-completed provider constructor for trusted host/provider code.

Returns Function — Wire-completed provider constructor for trusted host/provider code.

authSet(auth, options) method

Route auth persistence to the endpoint's namespace and refresh the live settings view.

auth object
Authentication data to persist.

Returns object — The persisted endpoint section returned by the Env connection.

Throws — {Error} Propagates persistence or Env connection errors.

Effects — Persists endpoint authentication and updates the underlying live settings view.

cancel() method

Interrupt the active request, emitting a terminal partial; IO remains reusable.

Returns Promise<void> — Resolves after the in-flight request settles; no-op when idle/closed.

Effects — Aborts the owned connection signal, awaits teardown, and returns to idle. Repeated calls are safe.

close() method

Permanently disconnect after interrupting any active request.

Returns Promise<void> — Resolves when the request settles and its connection closes; concurrent/repeated calls await the same outcome.

Throws — {Error|AggregateError} Request finalization or connection teardown failures, after the instance enters closed. Repeated close reports the same failure; construct a new IO to reconnect.

Effects — Aborts the owned connection signal and transitions irreversibly to closed.

connectTimeout property

Read: get connectTimeout()

Current default connection watchdog in milliseconds.

Returns number — Current default connection watchdog in milliseconds.

connectionCreate({ signal, onBytes } = {…}) method

A fresh provider connection over this endpoint/model for a provider tool's one-off request (context2msg/send/read/close); the caller closes it.

[options={}] object
Connection options.
[options.signal] AbortSignal
Signal assigned to abort its transport.
[options.onBytes] (bytes: Uint8Array) => void
Raw response-byte progress callback.

Returns object — A newly constructed provider connection; caller owns and must close it.

Throws — {Error} If the provider constructor fails.

Effects — Creates a new provider connection and optionally attaches the signal and byte callback.

constructor(options = {…}) constructor

Configure one provider IO session. Resolves the registered endpoint and provider; URL, credentials and timeout defaults read Env's live provider configuration, including after this IO is cached.

[options={}] Object
Constructor options.
options.env object
Env registry; required.
options.model string
Registered `<endpoint>/<model>` selector.
[options.tools] string[]
Tool selection: omitted or ["*"] means all, [] none, otherwise the named subset.
[options.safe=false] boolean
Whether to publish read-only tools only.
[options.onData] (event:object)=>void
Optional default data callback.
[options.onLog] (line:string)=>void
Optional default log callback.
[options.remember=true] boolean
Whether Env.connection records this pair as last used.

Returns IO — The initialized provider IO session.

Throws — {TypeError} Invalid options container, unknown own top-level keys (including symbols), missing `env`, a separate endpoint option, or invalid qualified model. Key validation precedes provider lookup; settings payload keys remain open.

Throws — {ProviderError} If endpoint resolution reports a provider-classified failure; other resolution errors propagate.

Effects — Resolves and retains the provider link and initializes this instance in the idle state.

context field

The Context of the request in flight (null while idle); providers read its dirty and may edit replay data in it.

Returns ?Context — The Context of the request in flight (null while idle); providers read its `dirty` and may edit replay data in it.

env field

The shared live environment.

Returns Env — The shared live environment.

fetch(url, init = {…}, { deadline, connectTimeout } = {…}) method

fetch bounded by a wall-clock deadline and a fast connect fail-fast (provider tools' plain HTTP requests).

url string|URL
Request URL.
[init={}] object
Fetch initialization; any supplied signal is honored.

Returns Promise<Response> — Resolves to the fetch response.

Throws — {TypeError} May reject for invalid fetch arguments; transport and deadline failures reject the promise.

Effects — Starts a bounded HTTP request using the global `fetch` implementation.

model property

Read: get model()

Qualified endpoint/model selector; assignment changes the model only while idle and on this connection's endpoint.

Returns string — Qualified endpoint/model selector; assignment changes the model only while idle and on this connection's endpoint.

Write: set model(selector)

Select a model on the same endpoint. Validation precedes mutation; busy/closed IO refuses selection. @param {string} selector Qualified model. @throws {TypeError|ProviderError} Invalid, cross-endpoint, busy, or closed selection.

name field

Connection endpoint name.

Returns string — Connection endpoint name.

protocol field

Provider protocol registry name.

Returns string — Provider protocol registry name.

provider field

Live provider metadata; never serialize wholesale to a model.

Returns object — Live provider metadata; never serialize wholesale to a model.

settings property

Read: get settings()

Build the live provider-namespaced settings view with per-instance agent-local thinking applied. The returned think is the model's native mode, mapped from the library level and narrowed by model/provider capabilities.

Returns object — A fresh merged settings object; undefined native thinking means provider default.

Effects — None; does not mutate the Env settings.

settingsSet(key, value) method

Set/clear the Agent's thinking selection AFTER construction. Provider configuration changes must go through Env.

key string
value *
Thinking level; `undefined` restores the Env default.

Returns void

Effects — Changes this IO instance's non-persisted thinking selection.

state property

Read: get state()

Read the request state machine's current state.

Returns "idle"|"sending"|"reading"|"cancelling"|"closing"|"closed" — Current lifecycle state.

Effects — None; this is a read-only view.

stuckTimeout property

Read: get stuckTimeout()

Current default reading watchdog in milliseconds.

Returns number — Current default reading watchdog in milliseconds.

timeout property

Read: get timeout()

Current default overall request timeout in milliseconds.

Returns number — Current default overall request timeout in milliseconds.

tools() method

Return this request's publishable tool catalog, filtered by availability, safe mode, configured selection, and the endpoint's provider tools.

Returns Array<{name: string, ...Object}> — Fresh tool descriptors; secret tools are excluded.

Effects — None; reads the request's tool catalog snapshot.

url property

Read: get url()

Effective URL from the current Env provider configuration.

Returns string — Effective URL from the current Env provider configuration.

write(context, callbacks = {…}, options = {…}) method

Run one provider request over a complete context.

context Context
The conversation; metadata records and empty messages are filtered before validation/provider conversion, and IO updates its root record during the request.
[callbacks={}] Object
CamelCase response callbacks for this request.
[options={}] Object
Per-request overrides.
[options.timeout] number|string
Overall request cap override.
[options.connectTimeout] number|string
Connection timeout override.
[options.stuckTimeout] number|string
Reading watchdog override.

Returns Promise<object> — Resolves with the terminal done/error event. Rejects TypeError for a non-Context argument or any model/endpoint write override without reserving the instance; rejects ProviderError for a closed/busy instance or malformed context.

Effects — Reserves the instance synchronously, may refresh OAuth, starts one request, and returns the instance to idle after request finalization unless closed.

class ProviderError extends Error class

The stable provider failure class (auth/network/provider/malformed).

Defined in lib/io/provider-error.js

constructor(kind, message, detail = {…}) constructor

Build a classified error, assigning the supplied detail fields onto it.

kind "auth"|"network"|"provider"|"malformed"
failure class; not validated by this constructor
message string
error message passed to {@link Error}
[detail={}] object
enumerable metadata fields to copy onto the error; may override existing fields

Returns ProviderError — The constructed error instance.

Throws — Propagates errors raised while copying enumerable detail properties.

Context unknown

The Context namespace for validating every provider-bound request.

Defined in lib/context.js

Env unknown

The global environment constructor used by IO and provider authors.

Defined in lib/env.js

THINKING_LEVELS = ["none", "low", "medium", "high", "xhigh", "max"] constant

Selectable thinking levels, weakest -> strongest (IO maps them to native modes).

Defined in lib/io/thinking.js

timeoutsResolve(options = {…}) function

Resolve a request timeout using the Env's provider settings and an optional per-request override. @param {{env: Env, model: string, timeout?: number|string}} options Request inputs; no provider settings override. @returns {number} Milliseconds. @throws {TypeError|Error} Missing Env, unsupported settings override, or invalid model.

Defined in lib/io.js